Search in sources :

Example 1 with NewCertificate

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());
}
Also used : Response(javax.ws.rs.core.Response) NewCertificate(io.gravitee.am.service.model.NewCertificate) Domain(io.gravitee.am.model.Domain) Certificate(io.gravitee.am.model.Certificate) NewCertificate(io.gravitee.am.service.model.NewCertificate) Test(org.junit.Test) JerseySpringTest(io.gravitee.am.management.handlers.management.api.JerseySpringTest)

Example 2 with NewCertificate

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);
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) Primary(org.springframework.context.annotation.Primary) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Type(io.gravitee.am.common.event.Type) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) X500Name(org.bouncycastle.asn1.x500.X500Name) GeneralSecurityException(java.security.GeneralSecurityException) CertificateMetadata(io.gravitee.am.certificate.api.CertificateMetadata) User(io.gravitee.am.identityprovider.api.User) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) JsonNode(com.fasterxml.jackson.databind.JsonNode) ReferenceType(io.gravitee.am.model.ReferenceType) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) io.reactivex(io.reactivex) KeyPairGenerator(java.security.KeyPairGenerator) Action(io.gravitee.am.common.event.Action) CertificateNotFoundException(io.gravitee.am.service.exception.CertificateNotFoundException) CertificateWithApplicationsException(io.gravitee.am.service.exception.CertificateWithApplicationsException) KeyStore(java.security.KeyStore) EventType(io.gravitee.am.common.audit.EventType) RandomString(io.gravitee.am.common.utils.RandomString) NewCertificate(io.gravitee.am.service.model.NewCertificate) Base64(java.util.Base64) Payload(io.gravitee.am.model.common.event.Payload) Environment(org.springframework.core.env.Environment) Lazy(org.springframework.context.annotation.Lazy) Certificate(io.gravitee.am.model.Certificate) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) BouncyCastleProviderSingleton(com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Event(io.gravitee.am.model.common.event.Event) UpdateCertificate(io.gravitee.am.service.model.UpdateCertificate) CertificateSchema(io.gravitee.am.plugins.certificate.core.CertificateSchema) io.gravitee.am.service(io.gravitee.am.service) Logger(org.slf4j.Logger) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Component(org.springframework.stereotype.Component) Function(io.reactivex.functions.Function) CertificateRepository(io.gravitee.am.repository.management.api.CertificateRepository) CertificateAuditBuilder(io.gravitee.am.service.reporter.builder.management.CertificateAuditBuilder) Collections(java.util.Collections) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) RandomString(io.gravitee.am.common.utils.RandomString) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) GeneralSecurityException(java.security.GeneralSecurityException) CertificateNotFoundException(io.gravitee.am.service.exception.CertificateNotFoundException) CertificateWithApplicationsException(io.gravitee.am.service.exception.CertificateWithApplicationsException) IOException(java.io.IOException) Date(java.util.Date) CertificateSchema(io.gravitee.am.plugins.certificate.core.CertificateSchema) Event(io.gravitee.am.model.common.event.Event) Payload(io.gravitee.am.model.common.event.Payload) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) X509Certificate(java.security.cert.X509Certificate) NewCertificate(io.gravitee.am.service.model.NewCertificate) Certificate(io.gravitee.am.model.Certificate) UpdateCertificate(io.gravitee.am.service.model.UpdateCertificate)

Example 3 with NewCertificate

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);
        }
    });
}
Also used : KeyPair(java.security.KeyPair) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) RandomString(io.gravitee.am.common.utils.RandomString) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) GeneralSecurityException(java.security.GeneralSecurityException) CertificateNotFoundException(io.gravitee.am.service.exception.CertificateNotFoundException) CertificateWithApplicationsException(io.gravitee.am.service.exception.CertificateWithApplicationsException) IOException(java.io.IOException) Function(io.reactivex.functions.Function) NewCertificate(io.gravitee.am.service.model.NewCertificate) CertificateSchema(io.gravitee.am.plugins.certificate.core.CertificateSchema) X509Certificate(java.security.cert.X509Certificate) NewCertificate(io.gravitee.am.service.model.NewCertificate) Certificate(io.gravitee.am.model.Certificate) UpdateCertificate(io.gravitee.am.service.model.UpdateCertificate)

Example 4 with NewCertificate

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);
}
Also used : Certificate(io.gravitee.am.model.Certificate) Json(io.vertx.core.json.Json) CertificateServiceProxy(io.gravitee.am.management.service.CertificateServiceProxy) Permission(io.gravitee.am.model.permissions.Permission) Maybe(io.reactivex.Maybe) DomainService(io.gravitee.am.service.DomainService) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) AbstractResource(io.gravitee.am.management.handlers.management.api.resources.AbstractResource) InitializingBean(org.springframework.beans.factory.InitializingBean) Value(org.springframework.beans.factory.annotation.Value) Valid(javax.validation.Valid) Acl(io.gravitee.am.model.Acl) User(io.gravitee.am.identityprovider.api.User) CertificateStatus(io.gravitee.am.management.handlers.management.api.model.CertificateStatus) io.swagger.annotations(io.swagger.annotations) JsonObject(io.vertx.core.json.JsonObject) CertificateEntity(io.gravitee.am.management.handlers.management.api.model.CertificateEntity) URI(java.net.URI) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) DomainNotFoundException(io.gravitee.am.service.exception.DomainNotFoundException) NotNull(javax.validation.constraints.NotNull) Instant(java.time.Instant) Suspended(javax.ws.rs.container.Suspended) NewCertificate(io.gravitee.am.service.model.NewCertificate) MediaType(io.gravitee.common.http.MediaType) ChronoUnit(java.time.temporal.ChronoUnit) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Environment(org.springframework.core.env.Environment) ResourceContext(javax.ws.rs.container.ResourceContext) StringUtils(org.springframework.util.StringUtils) User(io.gravitee.am.identityprovider.api.User) DomainNotFoundException(io.gravitee.am.service.exception.DomainNotFoundException)

Aggregations

Certificate (io.gravitee.am.model.Certificate)4 NewCertificate (io.gravitee.am.service.model.NewCertificate)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 RandomString (io.gravitee.am.common.utils.RandomString)2 User (io.gravitee.am.identityprovider.api.User)2 CertificateSchema (io.gravitee.am.plugins.certificate.core.CertificateSchema)2 CertificateNotFoundException (io.gravitee.am.service.exception.CertificateNotFoundException)2 CertificatePluginSchemaNotFoundException (io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException)2 CertificateWithApplicationsException (io.gravitee.am.service.exception.CertificateWithApplicationsException)2 TechnicalManagementException (io.gravitee.am.service.exception.TechnicalManagementException)2 UpdateCertificate (io.gravitee.am.service.model.UpdateCertificate)2 Function (io.reactivex.functions.Function)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 KeyStore (java.security.KeyStore)2 X509Certificate (java.security.cert.X509Certificate)2 Response (javax.ws.rs.core.Response)2