Search in sources :

Example 6 with SecretSeries

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

the class SecretDetailResponseV2Test method formsCorrectlyFromSecretSeriesAndContent.

@Test
public void formsCorrectlyFromSecretSeriesAndContent() {
    SecretSeries series = SecretSeries.of(1, "secret-name", "secret-owner", "secret-description", ApiDate.parse("2013-03-28T21:23:04.159Z"), "creator-user", ApiDate.parse("2014-03-28T21:23:04.159Z"), "updater-user", "text/plain", null, 1L);
    SecretContent content = SecretContent.of(1, 1, "YXNkZGFz", "checksum", ApiDate.parse("2014-03-28T21:23:04.159Z"), "updater-user", ApiDate.parse("2014-03-28T21:23:04.159Z"), "updater-user", ImmutableMap.of("owner", "root"), 1136214245);
    SecretSeriesAndContent seriesAndContent = SecretSeriesAndContent.of(series, content);
    SecretDetailResponseV2 fromSeriesAndContent = SecretDetailResponseV2.builder().seriesAndContent(seriesAndContent).build();
    assertThat(fromSeriesAndContent).isEqualTo(secretDetailResponse);
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) SecretContent(keywhiz.api.model.SecretContent) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) Test(org.junit.Test)

Example 7 with SecretSeries

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

the class SecretDAO method getSecretsBatched.

/**
 * @param idx the first index to select in a list of secrets sorted by creation time
 * @param num the number of secrets after idx to select in the list of secrets
 * @param newestFirst if true, order the secrets from newest creation time to oldest
 * @return A list of secrets
 */
public ImmutableList<SecretSeriesAndContent> getSecretsBatched(int idx, int num, boolean newestFirst) {
    return dslContext.transactionResult(configuration -> {
        SecretContentDAO secretContentDAO = secretContentDAOFactory.using(configuration);
        SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(configuration);
        ImmutableList.Builder<SecretSeriesAndContent> secretsBuilder = ImmutableList.builder();
        for (SecretSeries series : secretSeriesDAO.getSecretSeriesBatched(idx, num, newestFirst)) {
            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 8 with SecretSeries

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

the class SecretDAO method partialUpdateSecret.

@VisibleForTesting
public long partialUpdateSecret(String name, String creator, PartialUpdateSecretRequestV2 request) {
    return dslContext.transactionResult(configuration -> {
        long now = OffsetDateTime.now().toEpochSecond();
        SecretContentDAO secretContentDAO = secretContentDAOFactory.using(configuration);
        SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(configuration);
        // Get the current version of the secret, throwing exceptions if it is not found
        SecretSeries secretSeries = secretSeriesDAO.getSecretSeriesByName(name).orElseThrow(NotFoundException::new);
        Long currentVersion = secretSeries.currentVersion().orElseThrow(NotFoundException::new);
        SecretContent secretContent = secretContentDAO.getSecretContentById(currentVersion).orElseThrow(NotFoundException::new);
        long secretId = secretSeries.id();
        // Set the fields to the original series and current version's values or the request values if provided
        String description = request.descriptionPresent() ? request.description() : secretSeries.description();
        String type = request.typePresent() ? request.type() : secretSeries.type().orElse("");
        ImmutableMap<String, String> metadata = request.metadataPresent() ? request.metadata() : secretContent.metadata();
        Long expiry = request.expiryPresent() ? request.expiry() : secretContent.expiry();
        String owner = request.ownerPresent() ? request.owner() : secretSeries.owner();
        Long ownerId = getOwnerId(configuration, owner);
        String encryptedContent = secretContent.encryptedContent();
        String hmac = secretContent.hmac();
        // Mirrors hmac-creation in SecretController
        if (request.contentPresent()) {
            checkArgument(!request.content().isEmpty());
            hmac = cryptographer.computeHmac(request.content().getBytes(UTF_8), // Compute HMAC on base64 encoded data
            "hmackey");
            if (hmac == null) {
                throw new ContentEncodingException("Error encoding content for SecretBuilder!");
            }
            encryptedContent = cryptographer.encryptionKeyDerivedFrom(name).encrypt(request.content());
        }
        secretSeriesDAO.updateSecretSeries(secretId, name, ownerId, creator, description, type, secretSeries.generationOptions(), now);
        long secretContentId = secretContentDAO.createSecretContent(secretId, encryptedContent, hmac, creator, metadata, expiry, now);
        secretSeriesDAO.setCurrentVersion(secretId, secretContentId, creator, now);
        return secretId;
    });
}
Also used : ContentEncodingException(keywhiz.service.crypto.ContentEncodingException) SecretSeries(keywhiz.api.model.SecretSeries) SecretContent(keywhiz.api.model.SecretContent) NotFoundException(javax.ws.rs.NotFoundException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 9 with SecretSeries

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

the class SecretDAO method createSecret.

@VisibleForTesting
public long createSecret(String name, String ownerName, String encryptedSecret, String hmac, String creator, Map<String, String> metadata, long expiry, String description, @Nullable String type, @Nullable Map<String, String> generationOptions) {
    return dslContext.transactionResult(configuration -> {
        // check is here because this is where all APIs converge on secret creation
        if (name.startsWith(".")) {
            throw new BadRequestException(format("secret cannot be created with name `%s` - secret " + "names cannot begin with a period", name));
        }
        // enforce a shorter max length than the db to ensure secrets renamed on deletion still fit
        if (name.length() > SECRET_NAME_MAX_LENGTH) {
            throw new BadRequestException(format("secret cannot be created with name `%s` - secret " + "names must be %d characters or less", name, SECRET_NAME_MAX_LENGTH));
        }
        long now = OffsetDateTime.now().toEpochSecond();
        SecretContentDAO secretContentDAO = secretContentDAOFactory.using(configuration);
        SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(configuration);
        Long ownerId = getOwnerId(configuration, ownerName);
        Optional<SecretSeries> secretSeries = secretSeriesDAO.getSecretSeriesByName(name);
        long secretId;
        if (secretSeries.isPresent()) {
            SecretSeries secretSeries1 = secretSeries.get();
            if (secretSeries1.currentVersion().isPresent()) {
                throw new DataAccessException(format("secret already present: %s", name));
            } else {
                // Unreachable unless the implementation of getSecretSeriesByName is changed
                throw new IllegalStateException(format("secret %s retrieved without current version set", name));
            }
        } else {
            secretId = secretSeriesDAO.createSecretSeries(name, ownerId, creator, description, type, generationOptions, now);
        }
        long secretContentId = secretContentDAO.createSecretContent(secretId, encryptedSecret, hmac, creator, metadata, expiry, now);
        secretSeriesDAO.setCurrentVersion(secretId, secretContentId, creator, now);
        return secretId;
    });
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) BadRequestException(javax.ws.rs.BadRequestException) DataAccessException(org.jooq.exception.DataAccessException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 10 with SecretSeries

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

the class AclDAO method processSanitizedSecretRow.

private SanitizedSecret processSanitizedSecretRow(Record row, Client client) {
    boolean rowHmacLog = config.getRowHmacCheck() == RowHmacCheck.DISABLED_BUT_LOG;
    boolean rowHmacFail = config.getRowHmacCheck() == RowHmacCheck.ENFORCED;
    SecretSeries series = secretSeriesMapper.map(row.into(SECRETS));
    String secretHmac = rowHmacGenerator.computeRowHmac(SECRETS.getName(), List.of(row.getValue(SECRETS.NAME), row.getValue(SECRETS.ID)));
    if (!secretHmac.equals(row.getValue(SECRETS.ROW_HMAC))) {
        String errorMessage = String.format("Secret HMAC verification failed for secret: %s", row.getValue(SECRETS.NAME));
        if (rowHmacLog) {
            logger.warn(errorMessage);
        }
        if (rowHmacFail) {
            throw new AssertionError(errorMessage);
        }
    }
    String clientHmac = rowHmacGenerator.computeRowHmac(CLIENTS.getName(), List.of(client.getName(), client.getId()));
    if (!clientHmac.equals(row.getValue(CLIENTS.ROW_HMAC))) {
        String errorMessage = String.format("Client HMAC verification failed for client: %s", client.getName());
        if (rowHmacLog) {
            logger.warn(errorMessage);
        }
        if (rowHmacFail) {
            throw new AssertionError(errorMessage);
        }
    }
    String membershipsHmac = rowHmacGenerator.computeRowHmac(MEMBERSHIPS.getName(), List.of(client.getId(), row.getValue(MEMBERSHIPS.GROUPID)));
    if (!membershipsHmac.equals(row.getValue(MEMBERSHIPS.ROW_HMAC))) {
        String errorMessage = String.format("Memberships HMAC verification failed for clientId: %d in groupId: %d", client.getId(), row.getValue(MEMBERSHIPS.GROUPID));
        if (rowHmacLog) {
            logger.warn(errorMessage);
        }
        if (rowHmacFail) {
            throw new AssertionError(errorMessage);
        }
    }
    String accessgrantsHmac = rowHmacGenerator.computeRowHmac(ACCESSGRANTS.getName(), List.of(row.getValue(MEMBERSHIPS.GROUPID), row.getValue(SECRETS.ID)));
    if (!accessgrantsHmac.equals(row.getValue(ACCESSGRANTS.ROW_HMAC))) {
        String errorMessage = String.format("Access Grants HMAC verification failed for groupId: %d in secretId: %d", row.getValue(MEMBERSHIPS.GROUPID), row.getValue(SECRETS.ID));
        if (rowHmacLog) {
            logger.warn(errorMessage);
        }
        if (rowHmacFail) {
            throw new AssertionError(errorMessage);
        }
    }
    return SanitizedSecret.of(series.id(), series.name(), series.owner(), series.description(), row.getValue(SECRETS_CONTENT.CONTENT_HMAC), series.createdAt(), series.createdBy(), series.updatedAt(), series.updatedBy(), secretContentMapper.tryToReadMapFromMetadata(row.getValue(SECRETS_CONTENT.METADATA)), series.type().orElse(null), series.generationOptions(), row.getValue(SECRETS_CONTENT.EXPIRY), series.currentVersion().orElse(null), new ApiDate(row.getValue(SECRETS_CONTENT.CREATEDAT)), row.getValue(SECRETS_CONTENT.CREATEDBY));
}
Also used : ApiDate(keywhiz.api.ApiDate) SecretSeries(keywhiz.api.model.SecretSeries)

Aggregations

SecretSeries (keywhiz.api.model.SecretSeries)30 Test (org.junit.Test)12 SecretContent (keywhiz.api.model.SecretContent)9 SecretSeriesAndContent (keywhiz.api.model.SecretSeriesAndContent)8 ApiDate (keywhiz.api.ApiDate)6 ImmutableList (com.google.common.collect.ImmutableList)5 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 NotFoundException (javax.ws.rs.NotFoundException)3 SecretsRecord (keywhiz.jooq.tables.records.SecretsRecord)3 HashSet (java.util.HashSet)2 Group (keywhiz.api.model.Group)2 SanitizedSecret (keywhiz.api.model.SanitizedSecret)2 Secret (keywhiz.api.model.Secret)2 Event (keywhiz.log.Event)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 ArrayList (java.util.ArrayList)1 BadRequestException (javax.ws.rs.BadRequestException)1 ContentEncodingException (keywhiz.service.crypto.ContentEncodingException)1 Record (org.jooq.Record)1 DataAccessException (org.jooq.exception.DataAccessException)1