Search in sources :

Example 1 with SanitizedSecret

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

the class SecretsResourceIntegrationTest method listSpecificNonVersionedSecretByName.

@Test
public void listSpecificNonVersionedSecretByName() throws IOException {
    keywhizClient.login(DbSeedCommand.defaultUser, DbSeedCommand.defaultPassword.toCharArray());
    SanitizedSecret sanitizedSecret = keywhizClient.getSanitizedSecretByName("Nobody_PgPass");
    assertThat(sanitizedSecret.id()).isEqualTo(737);
}
Also used : SanitizedSecret(keywhiz.api.model.SanitizedSecret) Test(org.junit.Test)

Example 2 with SanitizedSecret

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

the class AutomationGroupResource method getGroupByName.

/**
 * Retrieve Group by a specified name, or all Groups if no name given
 *
 * @param automationClient the client with automation access performing this operation
 * @param name the name of the Group to retrieve, if provided
 * @return details on the specified group, or an all groups if no name specified
 *
 * optionalParams name
 * description Returns a single Group or a set of all Groups
 * responseMessage 200 Found and retrieved Group(s)
 * responseMessage 404 Group with given name not found (if name provided)
 */
@Timed
@ExceptionMetered
@GET
public Response getGroupByName(@Auth AutomationClient automationClient, @QueryParam("name") Optional<String> name) {
    if (name.isPresent()) {
        Group group = groupDAO.getGroup(name.get()).orElseThrow(NotFoundException::new);
        ImmutableList<Client> clients = ImmutableList.copyOf(aclDAO.getClientsFor(group));
        ImmutableList<SanitizedSecret> sanitizedSecrets = ImmutableList.copyOf(aclDAO.getSanitizedSecretsFor(group));
        return Response.ok().entity(GroupDetailResponse.fromGroup(group, sanitizedSecrets, clients)).build();
    }
    ImmutableList<SanitizedSecret> emptySecrets = ImmutableList.of();
    ImmutableList<Client> emptyClients = ImmutableList.of();
    List<GroupDetailResponse> groups = groupDAO.getGroups().stream().map((g) -> GroupDetailResponse.fromGroup(g, emptySecrets, emptyClients)).collect(toList());
    return Response.ok().entity(groups).build();
}
Also used : PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Event(keywhiz.log.Event) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) GroupResource(keywhiz.service.resources.automation.v2.GroupResource) QueryParam(javax.ws.rs.QueryParam) ImmutableList(com.google.common.collect.ImmutableList) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) DELETE(javax.ws.rs.DELETE) AuditLog(keywhiz.log.AuditLog) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) LongParam(io.dropwizard.jersey.params.LongParam) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) CreateGroupRequest(keywhiz.api.CreateGroupRequest) EventTag(keywhiz.log.EventTag) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) VisibleForTesting(com.google.common.annotations.VisibleForTesting) GroupDetailResponse(keywhiz.api.GroupDetailResponse) Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) GroupDetailResponse(keywhiz.api.GroupDetailResponse) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 3 with SanitizedSecret

use of keywhiz.api.model.SanitizedSecret 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 4 with SanitizedSecret

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

the class GroupsResource method groupDetailResponseFromId.

private GroupDetailResponse groupDetailResponseFromId(long groupId) {
    Optional<Group> optionalGroup = groupDAO.getGroupById(groupId);
    if (!optionalGroup.isPresent()) {
        throw new NotFoundException("Group not found.");
    }
    Group group = optionalGroup.get();
    ImmutableList<SanitizedSecret> secrets = ImmutableList.copyOf(aclDAO.getSanitizedSecretsFor(group));
    ImmutableList<Client> clients = ImmutableList.copyOf(aclDAO.getClientsFor(group));
    return GroupDetailResponse.fromGroup(group, secrets, clients);
}
Also used : Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) NotFoundException(javax.ws.rs.NotFoundException) Client(keywhiz.api.model.Client)

Example 5 with SanitizedSecret

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

the class BatchSecretDeliveryResource method getBatchSecret.

/**
 * Retrieve Secret by name
 *
 * @param secrets the name of the Secrets to retrieve in batch
 * @param client  the client performing the retrieval
 * @return the secret with the specified name, if present and accessible to the client
 * <p>
 * responseMessage 200 Found and retrieved Secret with given name
 * responseMessage 403 Secret is not assigned to Client
 * responseMessage 404 Secret with given name not found
 * responseMessage 500 Secret response could not be generated for given Secret
 */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public List<SecretDeliveryResponse> getBatchSecret(@Auth Client client, @Valid BatchSecretRequest request) {
    List<SanitizedSecret> clientAccessibleSecrets = aclDAO.getBatchSanitizedSecretsFor(client, request.secrets());
    List<Secret> existingSecrets = secretController.getSecretsByName(request.secrets());
    boolean clientExists = clientDAO.getClientByName(client.getName()).isPresent();
    List<String> forbiddenSecrets = new ArrayList<>();
    // The client is responsible for only requesting secrets they have permission for
    for (String secretname : request.secrets()) {
        boolean secretExists = existingSecrets.stream().anyMatch(s -> s.getName().equals(secretname));
        boolean secretAccessible = clientAccessibleSecrets.stream().anyMatch(s -> s.name().equals(secretname));
        if (!(clientExists && secretExists)) {
            logger.warn("Client {} or secret {} does not exist (client exists={}, secret exists={})", client.getName(), secretname, clientExists, secretExists);
            throw new NotFoundException();
        }
        if (!secretAccessible) {
            // at this point we know the client and secret both exist
            forbiddenSecrets.add(secretname);
        }
    }
    // If *any* of the secrets is forbidden
    if (!forbiddenSecrets.isEmpty()) {
        throw new ForbiddenException(format("Access denied: %s to secret(s) '%s'", client.getName(), forbiddenSecrets));
    }
    logger.info("Client {} granted access to {}.", client.getName(), clientAccessibleSecrets.stream().map(s -> s.name()).collect(toList()));
    try {
        // This is only possible if all secrets are both existing AND accessible to the client
        List<SecretDeliveryResponse> secrets = existingSecrets.stream().map(SecretDeliveryResponse::fromSecret).collect(toList());
        setTag("nSecrets", secrets.size());
        return secrets;
    } catch (IllegalArgumentException e) {
        logger.error(format("Failed creating batch response for secrets %s", existingSecrets.stream().map(s -> s.getName()).collect(toList())), e);
        throw new InternalServerErrorException();
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) SecretDeliveryResponse(keywhiz.api.SecretDeliveryResponse) Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Aggregations

SanitizedSecret (keywhiz.api.model.SanitizedSecret)41 Test (org.junit.Test)20 Group (keywhiz.api.model.Group)13 Client (keywhiz.api.model.Client)12 NotFoundException (javax.ws.rs.NotFoundException)10 IOException (java.io.IOException)9 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)7 Timed (com.codahale.metrics.annotation.Timed)7 GET (javax.ws.rs.GET)6 Secret (keywhiz.api.model.Secret)5 KeywhizClient (keywhiz.client.KeywhizClient)5 ImmutableList (com.google.common.collect.ImmutableList)4 SecretDeliveryResponse (keywhiz.api.SecretDeliveryResponse)4 AutomationClient (keywhiz.api.model.AutomationClient)4 NotFoundException (keywhiz.client.KeywhizClient.NotFoundException)4 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 BatchSecretRequest (keywhiz.api.BatchSecretRequest)3 GroupDetailResponse (keywhiz.api.GroupDetailResponse)3