Search in sources :

Example 1 with Secret

use of keywhiz.api.model.Secret in project keywhiz by square.

the class SecretsResource method createSecret.

/**
   * Create Secret
   *
   * @excludeParams user
   * @param request the JSON client request used to formulate the Secret
   *
   * @description Creates a Secret with the name from a valid secret request.
   * Used by Keywhiz CLI and the web ui.
   * @responseMessage 200 Successfully created Secret
   * @responseMessage 400 Secret with given name already exists
   */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createSecret(@Auth User user, @Valid CreateSecretRequest request) {
    logger.info("User '{}' creating secret '{}'.", user, request.name);
    Secret secret;
    try {
        SecretController.SecretBuilder builder = secretController.builder(request.name, request.content, user.getName(), request.expiry);
        if (request.description != null) {
            builder.withDescription(request.description);
        }
        if (request.metadata != null) {
            builder.withMetadata(request.metadata);
        }
        secret = builder.create();
    } catch (DataAccessException e) {
        logger.info(format("Cannot create secret %s", request.name), e);
        throw new ConflictException(format("Cannot create secret %s.", request.name));
    }
    URI uri = UriBuilder.fromResource(SecretsResource.class).path("{secretId}").build(secret.getId());
    Response response = Response.created(uri).entity(secretDetailResponseFromId(secret.getId())).build();
    if (response.getStatus() == HttpStatus.SC_CREATED) {
        Map<String, String> extraInfo = new HashMap<>();
        if (request.description != null) {
            extraInfo.put("description", request.description);
        }
        if (request.metadata != null) {
            extraInfo.put("metadata", request.metadata.toString());
        }
        extraInfo.put("expiry", Long.toString(request.expiry));
        auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATE, user.getName(), request.name, extraInfo));
    }
    return response;
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Response(javax.ws.rs.core.Response) SecretDetailResponse(keywhiz.api.SecretDetailResponse) ConflictException(keywhiz.service.exceptions.ConflictException) HashMap(java.util.HashMap) Event(keywhiz.log.Event) SecretController(keywhiz.service.daos.SecretController) URI(java.net.URI) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 2 with Secret

use of keywhiz.api.model.Secret in project keywhiz by square.

the class AutomationSecretResource method readSecrets.

/**
 * Retrieve secret by a specified name, or all secrets if no name given
 * Note that retrieving all secrets could be an expensive query
 *
 * @param automationClient the client with automation access performing this operation
 * @param name the name of the secret to retrieve, if provided
 * @return details on the specified secret, or all secrets if no name given
 *
 * description Returns a single secret or a set of all secrets
 * responseMessage 200 Found and retrieved secret(s)
 * responseMessage 404 Secret with given name not found (if name provided)
 */
@Timed
@ExceptionMetered
@GET
public ImmutableList<AutomationSecretResponse> readSecrets(@Auth AutomationClient automationClient, @QueryParam("name") String name) {
    ImmutableList.Builder<AutomationSecretResponse> responseBuilder = ImmutableList.builder();
    if (name != null) {
        Optional<Secret> optionalSecret = secretController.getSecretByName(name);
        if (!optionalSecret.isPresent()) {
            throw new NotFoundException("Secret not found.");
        }
        Secret secret = optionalSecret.get();
        ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret));
        responseBuilder.add(AutomationSecretResponse.fromSecret(secret, groups));
    } else {
        List<SanitizedSecret> secrets = secretController.getSanitizedSecrets(null, null);
        for (SanitizedSecret sanitizedSecret : secrets) {
            Secret secret = secretController.getSecretById(sanitizedSecret.id()).orElseThrow(() -> new IllegalStateException(format("Cannot find record related to %s", sanitizedSecret)));
            ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret));
            responseBuilder.add(AutomationSecretResponse.fromSecret(secret, groups));
        }
    }
    return responseBuilder.build();
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) ImmutableList(com.google.common.collect.ImmutableList) AutomationSecretResponse(keywhiz.api.AutomationSecretResponse) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 3 with Secret

use of keywhiz.api.model.Secret in project keywhiz by square.

the class SecretResource method createSecret.

/**
 * Creates a secret and assigns to given groups
 *
 * @param request JSON request to create a secret
 *
 * responseMessage 201 Created secret and assigned to given groups
 * responseMessage 409 Secret already exists
 */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createSecret(@Auth AutomationClient automationClient, @Valid CreateSecretRequestV2 request) {
    // allows new version, return version in resulting path
    String name = request.name();
    String user = automationClient.getName();
    SecretBuilder builder = secretController.builder(name, request.content(), automationClient.getName(), request.expiry()).withDescription(request.description()).withMetadata(request.metadata()).withOwnerName(request.owner()).withType(request.type());
    Secret secret;
    try {
        secret = builder.create();
    } catch (DataAccessException e) {
        logger.info(format("Cannot create secret %s", name), e);
        throw new ConflictException(format("Cannot create secret %s.", name));
    }
    Map<String, String> extraInfo = new HashMap<>();
    if (request.description() != null) {
        extraInfo.put("description", request.description());
    }
    if (request.metadata() != null) {
        extraInfo.put("metadata", request.metadata().toString());
    }
    extraInfo.put("expiry", Long.toString(request.expiry()));
    auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATE, user, name, extraInfo));
    long secretId = secret.getId();
    groupsToGroupIds(request.groups()).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAO.findAndAllowAccess(secretId, groupId, auditLog, user, new HashMap<>())));
    UriBuilder uriBuilder = UriBuilder.fromResource(SecretResource.class).path(name);
    return Response.created(uriBuilder.build()).build();
}
Also used : Secret(keywhiz.api.model.Secret) Produces(javax.ws.rs.Produces) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) ContentCryptographer(keywhiz.service.crypto.ContentCryptographer) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) Group(keywhiz.api.model.Group) CreateSecretRequestV2(keywhiz.api.automation.v2.CreateSecretRequestV2) HOURS(java.time.temporal.ChronoUnit.HOURS) Set(java.util.Set) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SecretDAOFactory(keywhiz.service.daos.SecretDAO.SecretDAOFactory) SecretContent(keywhiz.api.model.SecretContent) PathParam(javax.ws.rs.PathParam) SecretDetailResponseV2(keywhiz.api.automation.v2.SecretDetailResponseV2) AclDAO(keywhiz.service.daos.AclDAO) SanitizedSecretWithGroups(keywhiz.api.model.SanitizedSecretWithGroups) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) PartialUpdateSecretRequestV2(keywhiz.api.automation.v2.PartialUpdateSecretRequestV2) HashMap(java.util.HashMap) SecretSeriesDAO(keywhiz.service.daos.SecretSeriesDAO) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) AutomationClient(keywhiz.api.model.AutomationClient) ImmutableList(com.google.common.collect.ImmutableList) SecretDAO(keywhiz.service.daos.SecretDAO) SecretBuilder(keywhiz.service.daos.SecretController.SecretBuilder) AuditLog(keywhiz.log.AuditLog) SanitizedSecretWithGroupsListAndCursor(keywhiz.api.model.SanitizedSecretWithGroupsListAndCursor) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) SecretSeriesDAOFactory(keywhiz.service.daos.SecretSeriesDAO.SecretSeriesDAOFactory) Readonly(keywhiz.service.config.Readonly) UTF_8(java.nio.charset.StandardCharsets.UTF_8) SecretRetrievalCursor(keywhiz.api.model.SecretRetrievalCursor) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) SetSecretVersionRequestV2(keywhiz.api.automation.v2.SetSecretVersionRequestV2) SecretController(keywhiz.service.daos.SecretController) SecretContentsResponseV2(keywhiz.api.automation.v2.SecretContentsResponseV2) SecretContentsRequestV2(keywhiz.api.automation.v2.SecretContentsRequestV2) EventTag(keywhiz.log.EventTag) Collectors.toList(java.util.stream.Collectors.toList) CreateOrUpdateSecretRequestV2(keywhiz.api.automation.v2.CreateOrUpdateSecretRequestV2) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) PUT(javax.ws.rs.PUT) ConflictException(keywhiz.service.exceptions.ConflictException) HashMap(java.util.HashMap) SecretBuilder(keywhiz.service.daos.SecretController.SecretBuilder) Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Event(keywhiz.log.Event) UriBuilder(javax.ws.rs.core.UriBuilder) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 4 with Secret

use of keywhiz.api.model.Secret in project keywhiz by square.

the class SecretsResource method createSecret.

/**
 * Create Secret
 *
 * @param user    the admin user performing this operation
 * @param request the JSON client request used to formulate the Secret
 * @return 201 on success, 400 if a secret with the given name already exists
 * <p>
 * description Creates a Secret with the name from a valid secret request. Used by Keywhiz CLI and
 * the web ui.
 * <p>
 * responseMessage 201 Successfully created Secret
 * <p>
 * responseMessage 400 Secret with given name already exists
 */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createSecret(@Auth User user, @Valid CreateSecretRequestV2 request) {
    {
        String ownerPart = request.owner() == null ? "with no owner" : String.format("with owner '%s'", request.owner());
        logger.info("User '{}' creating secret '{}' {}.", user, request.name(), ownerPart);
    }
    Secret secret;
    try {
        SecretController.SecretBuilder builder = secretController.builder(request.name(), request.content(), user.getName(), request.expiry()).withOwnerName(request.owner());
        if (request.description() != null) {
            builder.withDescription(request.description());
        }
        if (request.metadata() != null) {
            builder.withMetadata(request.metadata());
        }
        secret = builder.create();
    } catch (DataAccessException e) {
        logger.info(format("Cannot create secret %s", request.name()), e);
        throw new ConflictException(format("Cannot create secret %s.", request.name()));
    }
    URI uri = UriBuilder.fromResource(SecretsResource.class).path("{secretId}").build(secret.getId());
    Response response = Response.created(uri).entity(secretDetailResponseFromId(secret.getId())).build();
    if (response.getStatus() == HttpStatus.SC_CREATED) {
        Map<String, String> extraInfo = new HashMap<>();
        if (request.description() != null) {
            extraInfo.put("description", request.description());
        }
        if (request.metadata() != null) {
            extraInfo.put("metadata", request.metadata().toString());
        }
        if (request.owner() != null) {
            extraInfo.put("owner", request.owner());
        }
        extraInfo.put("expiry", Long.toString(request.expiry()));
        auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATE, user.getName(), request.name(), extraInfo));
    }
    return response;
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Response(javax.ws.rs.core.Response) SecretDetailResponse(keywhiz.api.SecretDetailResponse) ConflictException(keywhiz.service.exceptions.ConflictException) HashMap(java.util.HashMap) Event(keywhiz.log.Event) SecretController(keywhiz.service.daos.SecretController) URI(java.net.URI) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 5 with Secret

use of keywhiz.api.model.Secret in project keywhiz by square.

the class SecretsResource method createOrUpdateSecret.

/**
 * Create or update secret
 *
 * @param user    the admin user performing this operation
 * @param request the JSON client request used to formulate the Secret
 * @return 201 when secret created or updated
 * <p>
 * responseMessage 201 Successfully created or updated Secret
 */
@Path("{name}")
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createOrUpdateSecret(@Auth User user, @PathParam("name") String secretName, @Valid CreateOrUpdateSecretRequestV2 request) {
    logger.info("User '{}' createOrUpdate secret '{}'.", user, secretName);
    Secret secret = secretController.builder(secretName, request.content(), user.getName(), request.expiry()).withDescription(request.description()).withMetadata(request.metadata()).withType(request.type()).createOrUpdate();
    URI uri = UriBuilder.fromResource(SecretsResource.class).path(secretName).build();
    Response response = Response.created(uri).entity(secretDetailResponseFromId(secret.getId())).build();
    if (response.getStatus() == HttpStatus.SC_CREATED) {
        Map<String, String> extraInfo = new HashMap<>();
        if (request.description() != null && !request.description().isEmpty()) {
            extraInfo.put("description", request.description());
        }
        if (request.metadata() != null && !request.metadata().isEmpty()) {
            extraInfo.put("metadata", request.metadata().toString());
        }
        extraInfo.put("expiry", Long.toString(request.expiry()));
        auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATEORUPDATE, user.getName(), secretName, extraInfo));
    }
    return response;
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Response(javax.ws.rs.core.Response) SecretDetailResponse(keywhiz.api.SecretDetailResponse) HashMap(java.util.HashMap) Event(keywhiz.log.Event) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Aggregations

Secret (keywhiz.api.model.Secret)34 SanitizedSecret (keywhiz.api.model.SanitizedSecret)21 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)15 Timed (com.codahale.metrics.annotation.Timed)15 Test (org.junit.Test)14 HashMap (java.util.HashMap)12 Event (keywhiz.log.Event)12 NotFoundException (javax.ws.rs.NotFoundException)10 POST (javax.ws.rs.POST)10 Path (javax.ws.rs.Path)9 Consumes (javax.ws.rs.Consumes)8 Group (keywhiz.api.model.Group)6 ConflictException (keywhiz.service.exceptions.ConflictException)6 Response (javax.ws.rs.core.Response)5 SecretController (keywhiz.service.daos.SecretController)5 DataAccessException (org.jooq.exception.DataAccessException)5 ArrayList (java.util.ArrayList)4 DELETE (javax.ws.rs.DELETE)4 GET (javax.ws.rs.GET)4 SecretDetailResponse (keywhiz.api.SecretDetailResponse)4