Search in sources :

Example 11 with SecretSeriesAndContent

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

the class SecretController method getSanitizedSecretsWithGroupsAndCursor.

/**
 * @param expireMinTime timestamp for closest expiry to include (may be overridden by cursor)
 * @param expireMaxTime timestamp for farthest expiry to include
 * @param limit         limit on number of results to return
 * @param cursor        cursor to be used to enforce pagination
 * @return all existing sanitized secrets and their groups matching criteria.
 */
public SanitizedSecretWithGroupsListAndCursor getSanitizedSecretsWithGroupsAndCursor(@Nullable Long expireMinTime, @Nullable Long expireMaxTime, @Nullable Integer limit, @Nullable SecretRetrievalCursor cursor) {
    // Retrieve secrets based on the cursor (if provided).
    ImmutableList<SecretSeriesAndContent> secrets;
    // Retrieve one additional record to detect when information is missing
    Integer updatedLimit = null;
    if (limit != null) {
        updatedLimit = limit + 1;
    }
    if (cursor == null) {
        secrets = secretDAO.getSecrets(expireMaxTime, null, expireMinTime, null, updatedLimit);
    } else {
        secrets = secretDAO.getSecrets(expireMaxTime, null, cursor.expiry(), cursor.name(), updatedLimit);
    }
    // Set the cursor and strip the final record from the secrets if necessary
    SecretRetrievalCursor newCursor = null;
    if (limit != null && secrets.size() > limit) {
        // The name and expiry in the new cursor will be the first entry in the next set of results
        newCursor = SecretRetrievalCursor.of(secrets.get(limit).series().name(), secrets.get(limit).content().expiry());
        // Trim the last record from the list
        secrets = secrets.subList(0, limit);
    }
    Set<Long> secretIds = secrets.stream().map(s -> s.series().id()).collect(toSet());
    Map<Long, List<Group>> groupsForSecrets = aclDAO.getGroupsForSecrets(secretIds);
    List<SanitizedSecretWithGroups> secretsWithGroups = secrets.stream().map(s -> {
        List<Group> groups = groupsForSecrets.get(s.series().id());
        if (groups == null) {
            groups = ImmutableList.of();
        }
        return fromSecretSeriesAndContentAndGroups(s, groups);
    }).collect(toList());
    try {
        return SanitizedSecretWithGroupsListAndCursor.of(secretsWithGroups, SecretRetrievalCursor.toUrlEncodedString(newCursor));
    } catch (Exception e) {
        logger.warn("Unable to encode cursor to string (cursor: {}): {}", newCursor, e.getMessage());
        // The cursor is malformed; return what information could be gathered
        return SanitizedSecretWithGroupsListAndCursor.of(secretsWithGroups, null);
    }
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecretWithGroups(keywhiz.api.model.SanitizedSecretWithGroups) LoggerFactory(org.slf4j.LoggerFactory) KeywhizConfig(keywhiz.KeywhizConfig) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toMap(java.util.stream.Collectors.toMap) SecretTransformer(keywhiz.service.crypto.SecretTransformer) Map(java.util.Map) ContentEncodingException(keywhiz.service.crypto.ContentEncodingException) ContentCryptographer(keywhiz.service.crypto.ContentCryptographer) Nullable(javax.annotation.Nullable) Collectors.toSet(java.util.stream.Collectors.toSet) Group(keywhiz.api.model.Group) SanitizedSecretWithGroupsListAndCursor(keywhiz.api.model.SanitizedSecretWithGroupsListAndCursor) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) UTF_8(java.nio.charset.StandardCharsets.UTF_8) SecretRetrievalCursor(keywhiz.api.model.SecretRetrievalCursor) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) Base64(java.util.Base64) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SanitizedSecretWithGroups.fromSecretSeriesAndContentAndGroups(keywhiz.api.model.SanitizedSecretWithGroups.fromSecretSeriesAndContentAndGroups) SanitizedSecretWithGroups(keywhiz.api.model.SanitizedSecretWithGroups) SecretRetrievalCursor(keywhiz.api.model.SecretRetrievalCursor) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ContentEncodingException(keywhiz.service.crypto.ContentEncodingException)

Example 12 with SecretSeriesAndContent

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

the class SecretDAOTest method createSecretSucceedsIfCurrentVersionIsNull.

@Test
public void createSecretSucceedsIfCurrentVersionIsNull() {
    String name = "newSecret";
    long firstId = secretDAO.createSecret(name, "content1", cryptographer.computeHmac("content1".getBytes(UTF_8)), "creator1", ImmutableMap.of("foo", "bar"), 1000, "description1", "type1", ImmutableMap.of());
    jooqContext.update(SECRETS).set(SECRETS.CURRENT, (Long) null).where(SECRETS.ID.eq(firstId)).execute();
    long secondId = secretDAO.createSecret(name, "content2", cryptographer.computeHmac("content2".getBytes(UTF_8)), "creator2", ImmutableMap.of("foo2", "bar2"), 2000, "description2", "type2", ImmutableMap.of());
    assertThat(secondId).isEqualTo(firstId);
    SecretSeriesAndContent newSecret = secretDAO.getSecretById(firstId).get();
    assertThat(newSecret.series().createdBy()).isEqualTo("creator1");
    assertThat(newSecret.series().updatedBy()).isEqualTo("creator2");
    assertThat(newSecret.series().description()).isEqualTo("description2");
    assertThat(newSecret.series().type().get()).isEqualTo("type2");
    assertThat(newSecret.content().createdBy()).isEqualTo("creator2");
    assertThat(newSecret.content().encryptedContent()).isEqualTo("content2");
    assertThat(newSecret.content().metadata()).isEqualTo(ImmutableMap.of("foo2", "bar2"));
}
Also used : SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) Test(org.junit.Test)

Example 13 with SecretSeriesAndContent

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

the class SecretDAO method getDeletedSecretVersionsBySecretId.

/**
 * @param secretId, the secret's id
 * @param versionIdx the first index to select in a list of versions sorted by creation time
 * @param numVersions the number of versions after versionIdx to select in the list of versions
 * @return all versions of a deleted secret, including the secret's content for each version,
 * matching input parameters or Optional.absent().
 */
public Optional<ImmutableList<SecretSeriesAndContent>> getDeletedSecretVersionsBySecretId(long secretId, int versionIdx, int numVersions) {
    checkArgument(versionIdx >= 0);
    checkArgument(numVersions >= 0);
    SecretContentDAO secretContentDAO = secretContentDAOFactory.using(dslContext.configuration());
    SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration());
    Optional<SecretSeries> series = secretSeriesDAO.getDeletedSecretSeriesById(secretId);
    if (series.isPresent()) {
        SecretSeries s = series.get();
        Optional<ImmutableList<SecretContent>> contents = secretContentDAO.getSecretVersionsBySecretId(secretId, versionIdx, numVersions);
        if (contents.isPresent()) {
            ImmutableList.Builder<SecretSeriesAndContent> b = new ImmutableList.Builder<>();
            b.addAll(contents.get().stream().map(c -> SecretSeriesAndContent.of(s, c)).collect(toList()));
            return Optional.of(b.build());
        }
    }
    return Optional.empty();
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) ImmutableList(com.google.common.collect.ImmutableList) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent)

Example 14 with SecretSeriesAndContent

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

the class SecretDAO method getSecrets.

/**
 * @param expireMaxTime the maximum expiration date for secrets to return (exclusive)
 * @param group the group secrets returned must be assigned to
 * @param expireMinTime the minimum expiration date for secrets to return (inclusive)
 * @param minName the minimum name (alphabetically) that will be returned for secrets
 *                expiring on expireMinTime (inclusive)
 * @param limit the maximum number of secrets to return
 *               which to start the list of returned secrets
 * @return list of secrets. can limit/sort by expiry, and for group if given
 */
public ImmutableList<SecretSeriesAndContent> getSecrets(@Nullable Long expireMaxTime, @Nullable Group group, @Nullable Long expireMinTime, @Nullable String minName, @Nullable Integer limit) {
    return dslContext.transactionResult(configuration -> {
        SecretContentDAO secretContentDAO = secretContentDAOFactory.using(configuration);
        SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(configuration);
        ImmutableList.Builder<SecretSeriesAndContent> secretsBuilder = ImmutableList.builder();
        for (SecretSeries series : secretSeriesDAO.getSecretSeries(expireMaxTime, group, expireMinTime, minName, limit)) {
            SecretContent content = secretContentDAO.getSecretContentById(series.currentVersion().get()).get();
            SecretSeriesAndContent seriesAndContent = SecretSeriesAndContent.of(series, content);
            secretsBuilder.add(seriesAndContent);
        }
        return secretsBuilder.build();
    });
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) ImmutableList(com.google.common.collect.ImmutableList) SecretContent(keywhiz.api.model.SecretContent) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent)

Example 15 with SecretSeriesAndContent

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

the class SecretDAO method getSecretsByName.

/**
 * @param names of secrets series to look up secrets by.
 * @return Secrets matching input parameters.
 */
public List<SecretSeriesAndContent> getSecretsByName(List<String> names) {
    checkArgument(!names.isEmpty());
    SecretContentDAO secretContentDAO = secretContentDAOFactory.using(dslContext.configuration());
    SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration());
    List<SecretSeries> multipleSeries = secretSeriesDAO.getMultipleSecretSeriesByName(names);
    List<SecretSeriesAndContent> ret = new ArrayList<SecretSeriesAndContent>();
    for (SecretSeries series : multipleSeries) {
        if (series.currentVersion().isPresent()) {
            long secretContentId = series.currentVersion().get();
            Optional<SecretContent> secretContent = secretContentDAO.getSecretContentById(secretContentId);
            if (secretContent.isPresent()) {
                ret.add(SecretSeriesAndContent.of(series, secretContent.get()));
            } else {
                throw new NotFoundException("Secret not found.");
            }
        }
    }
    return ret;
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) SecretContent(keywhiz.api.model.SecretContent) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent)

Aggregations

SecretSeriesAndContent (keywhiz.api.model.SecretSeriesAndContent)26 Test (org.junit.Test)16 SecretContent (keywhiz.api.model.SecretContent)9 SecretSeries (keywhiz.api.model.SecretSeries)8 ImmutableList (com.google.common.collect.ImmutableList)5 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)3 Timed (com.codahale.metrics.annotation.Timed)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 NotFoundException (javax.ws.rs.NotFoundException)2 Produces (javax.ws.rs.Produces)2 SanitizedSecret (keywhiz.api.model.SanitizedSecret)2 Secret (keywhiz.api.model.Secret)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 ArrayList (java.util.ArrayList)1