use of io.gravitee.am.service.model.NewCertificate in project gravitee-access-management by gravitee-io.
the class CertificatesResourceTest method shouldCreate.
@Test
public void shouldCreate() {
final String domainId = "domain-1";
final Domain mockDomain = new Domain();
mockDomain.setId(domainId);
NewCertificate newCertificate = new NewCertificate();
newCertificate.setName("certificate-name");
newCertificate.setType("certificate-type");
newCertificate.setConfiguration("certificate-configuration");
Certificate certificate = new Certificate();
certificate.setId("certificate-id");
certificate.setName("certificate-name");
doReturn(Maybe.just(mockDomain)).when(domainService).findById(domainId);
doReturn(Maybe.just("certificate-schema")).when(certificatePluginService).getSchema(anyString());
doReturn(Single.just(certificate)).when(certificateService).create(eq(domainId), any(), any());
final Response response = target("domains").path(domainId).path("certificates").request().post(Entity.json(newCertificate));
assertEquals(HttpStatusCode.CREATED_201, response.getStatus());
}
use of io.gravitee.am.service.model.NewCertificate in project gravitee-access-management by gravitee-io.
the class CertificateServiceImpl method create.
@Override
public Single<Certificate> create(String domain, NewCertificate newCertificate, User principal) {
LOGGER.debug("Create a new certificate {} for domain {}", newCertificate, domain);
Single<Certificate> certificateSingle = certificatePluginService.getSchema(newCertificate.getType()).switchIfEmpty(Maybe.error(new CertificatePluginSchemaNotFoundException(newCertificate.getType()))).map(schema -> objectMapper.readValue(schema, CertificateSchema.class)).flatMapSingle(new Function<CertificateSchema, SingleSource<Certificate>>() {
@Override
public SingleSource<Certificate> apply(CertificateSchema certificateSchema) throws Exception {
return Single.create(emitter -> {
String certificateId = RandomString.generate();
Certificate certificate = new Certificate();
certificate.setId(certificateId);
certificate.setDomain(domain);
certificate.setName(newCertificate.getName());
certificate.setType(newCertificate.getType());
// handle file
try {
JsonNode certificateConfiguration = objectMapper.readTree(newCertificate.getConfiguration());
certificateSchema.getProperties().entrySet().stream().filter(map -> map.getValue().getWidget() != null && "file".equals(map.getValue().getWidget())).map(map -> map.getKey()).forEach(key -> {
try {
JsonNode file = objectMapper.readTree(certificateConfiguration.get(key).asText());
byte[] data = Base64.getDecoder().decode(file.get("content").asText());
certificate.setMetadata(Collections.singletonMap(CertificateMetadata.FILE, data));
// update configuration to set the file name
((ObjectNode) certificateConfiguration).put(key, file.get("name").asText());
newCertificate.setConfiguration(objectMapper.writeValueAsString(certificateConfiguration));
} catch (IOException ex) {
LOGGER.error("An error occurs while trying to create certificate binaries", ex);
emitter.onError(ex);
}
});
certificate.setConfiguration(newCertificate.getConfiguration());
certificate.setCreatedAt(new Date());
certificate.setUpdatedAt(certificate.getCreatedAt());
} catch (Exception ex) {
LOGGER.error("An error occurs while trying to create certificate configuration", ex);
emitter.onError(ex);
}
emitter.onSuccess(certificate);
});
}
});
return certificateSingle.flatMap(certificate -> certificateRepository.create(certificate)).flatMap(certificate -> {
Event event = new Event(Type.CERTIFICATE, new Payload(certificate.getId(), ReferenceType.DOMAIN, certificate.getDomain(), Action.CREATE));
return eventService.create(event).flatMap(__ -> Single.just(certificate));
}).doOnError(ex -> {
LOGGER.error("An error occurs while trying to create a certificate", ex);
throw new TechnicalManagementException("An error occurs while trying to create a certificate", ex);
});
}
use of io.gravitee.am.service.model.NewCertificate in project gravitee-access-management by gravitee-io.
the class CertificateServiceImpl method create.
@Override
public Single<Certificate> create(String domain) {
// Define the default certificate
// Create a default PKCS12 certificate: io.gravitee.am.certificate.pkcs12.PKCS12Configuration
NewCertificate certificate = new NewCertificate();
certificate.setName("Default");
// TODO: how-to handle default certificate type ?
certificate.setType(DEFAULT_CERTIFICATE_PLUGIN);
return certificatePluginService.getSchema(certificate.getType()).map(new Function<String, CertificateSchema>() {
@Override
public CertificateSchema apply(String schema) throws Exception {
return objectMapper.readValue(schema, CertificateSchema.class);
}
}).map(new Function<CertificateSchema, String>() {
@Override
public String apply(CertificateSchema certificateSchema) throws Exception {
final int keySize = environment.getProperty("domains.certificates.default.keysize", int.class, 2048);
final int validity = environment.getProperty("domains.certificates.default.validity", int.class, 365);
final String name = environment.getProperty("domains.certificates.default.name", String.class, "cn=Gravitee.io");
final String sigAlgName = environment.getProperty("domains.certificates.default.algorithm", String.class, "SHA256withRSA");
final String alias = environment.getProperty("domains.certificates.default.alias", String.class, "default");
final String keyPass = environment.getProperty("domains.certificates.default.keypass", String.class, "gravitee");
final String storePass = environment.getProperty("domains.certificates.default.storepass", String.class, "gravitee");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
java.security.cert.Certificate[] chain = { generateCertificate(name, keyPair, validity, sigAlgName) };
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(null, null);
ks.setKeyEntry(alias, keyPair.getPrivate(), keyPass.toCharArray(), chain);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ks.store(outputStream, storePass.toCharArray());
ObjectNode certificateNode = objectMapper.createObjectNode();
ObjectNode contentNode = objectMapper.createObjectNode();
contentNode.put("content", new String(Base64.getEncoder().encode(outputStream.toByteArray())));
contentNode.put("name", domain + ".p12");
certificateNode.put("content", objectMapper.writeValueAsString(contentNode));
certificateNode.put("alias", alias);
certificateNode.put("storepass", storePass);
certificateNode.put("keypass", keyPass);
return objectMapper.writeValueAsString(certificateNode);
}
}).flatMapSingle(new Function<String, SingleSource<Certificate>>() {
@Override
public SingleSource<Certificate> apply(String configuration) throws Exception {
certificate.setConfiguration(configuration);
return create(domain, certificate);
}
});
}
use of io.gravitee.am.service.model.NewCertificate in project gravitee-access-management by gravitee-io.
the class CertificatesResource method create.
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create a certificate", notes = "User must have the DOMAIN_CERTIFICATE[CREATE] permission on the specified domain " + "or DOMAIN_CERTIFICATE[CREATE] permission on the specified environment " + "or DOMAIN_CERTIFICATE[CREATE] permission on the specified organization")
@ApiResponses({ @ApiResponse(code = 201, message = "Certificate successfully created"), @ApiResponse(code = 500, message = "Internal server error") })
public void create(@PathParam("organizationId") String organizationId, @PathParam("environmentId") String environmentId, @PathParam("domain") String domain, @ApiParam(name = "certificate", required = true) @Valid @NotNull final NewCertificate newCertificate, @Suspended final AsyncResponse response) {
final User authenticatedUser = getAuthenticatedUser();
checkAnyPermission(organizationId, environmentId, domain, Permission.DOMAIN_CERTIFICATE, Acl.CREATE).andThen(domainService.findById(domain).switchIfEmpty(Maybe.error(new DomainNotFoundException(domain))).flatMapSingle(schema -> certificateService.create(domain, newCertificate, authenticatedUser)).map(certificate -> Response.created(URI.create("/organizations/" + organizationId + "/environments/" + environmentId + "/domains/" + domain + "/certificates/" + certificate.getId())).entity(certificate).build())).subscribe(response::resume, response::resume);
}
Aggregations