mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(iam): authorize Secrets Manager requests against the secret's ARN (#5781)
* fix(iam): authorize Secrets Manager requests against the secret's ARN IAM enforcement evaluated CreateSecret against secret:* because the builder read only SecretId, and a secret named by its name was evaluated as secret:<name>, without the random suffix every secret ARN carries. A secret:<name>-?????? policy, the pattern AWS documents for granting access to a secret that may not exist yet, matched neither. CreateSecret is now evaluated against secret:<Name>-??????, standing in for the suffix that is assigned at creation, and a name-based SecretId resolves to the stored secret's full ARN in the target account. Closes #5364 * fix(iam): pick the Secrets Manager target by the serving operation CreateSecret now reads only Name and other actions only SecretId, so a field the handler ignores cannot choose the resource. Minted ARNs take the request's partition, and a name lookup also reads a legacy unprefixed secret for the default account. Adds an SDK compatibility test. * fix(iam): resolve a partial-ARN SecretId to the stored secret's ARN A SecretId given as an ARN without the random suffix is now authorized against the stored secret's full ARN, resolved in the caller's account in the order the operations use: an exact ARN first, then the ARN read as a partial one. The enforcement tests share EnforcementFixtures' auth, a new assumeRole helper, and a new createRole helper that removes the role after the test. The Secrets Manager enforcement test also deletes the secrets it creates.
This commit is contained in:
1 parent
1cb8b0f747
commit
a611e9ea6f
13 files changed
+787
-107
No files matched your search
+157
@@ -0,0 +1,157 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.AccessKey;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
|
||||
@DisplayName("Secrets Manager secret resource permissions")
|
||||
class SecretsManagerSecretArnAuthorizationTest {
|
||||
|
||||
private IamClient iam;
|
||||
private SecretsManagerClient root;
|
||||
private SecretsManagerClient caller;
|
||||
private String user;
|
||||
private AccessKey key;
|
||||
private String prefix;
|
||||
private boolean policyCreated;
|
||||
private final List<String> secrets = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses emulator account-root credentials");
|
||||
iam = TestFixtures.iamClient("000000000000");
|
||||
root = client("000000000000", "test");
|
||||
String name = TestFixtures.uniqueName("secret-arn-permissions");
|
||||
iam.createUser(r -> r.userName(name));
|
||||
user = name;
|
||||
key = iam.createAccessKey(r -> r.userName(user)).accessKey();
|
||||
caller = client(key.accessKeyId(), key.secretAccessKey());
|
||||
boolean enforced = false;
|
||||
try {
|
||||
caller.listSecrets();
|
||||
} catch (SecretsManagerException error) {
|
||||
assertDenied(error);
|
||||
enforced = true;
|
||||
}
|
||||
Assumptions.assumeTrue(enforced, "Requires floci.services.iam.enforcement-enabled=true");
|
||||
prefix = name;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
assertAll("remove Secrets Manager and IAM fixtures and close every client",
|
||||
() -> {
|
||||
for (String secret : secrets) {
|
||||
root.deleteSecret(r -> r.secretId(secret).forceDeleteWithoutRecovery(true));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (policyCreated) {
|
||||
iam.deleteUserPolicy(r -> r.userName(user).policyName("secrets"));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (key != null) {
|
||||
iam.deleteAccessKey(r -> r.userName(user).accessKeyId(key.accessKeyId()));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (user != null) {
|
||||
iam.deleteUser(r -> r.userName(user));
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (caller != null) {
|
||||
caller.close();
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (root != null) {
|
||||
root.close();
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (iam != null) {
|
||||
iam.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a name-prefix grant allows CreateSecret only under that prefix")
|
||||
void createSecretUnderNamePrefix() {
|
||||
policy("{\"Effect\":\"Allow\",\"Action\":\"secretsmanager:CreateSecret\",\"Resource\":\""
|
||||
+ TestFixtures.arn("secretsmanager", "000000000000", "secret:" + prefix + "/*") + "\"}");
|
||||
|
||||
String created = caller.createSecret(r -> r.name(prefix + "/core").secretString("x")).arn();
|
||||
secrets.add(created);
|
||||
|
||||
assertThat(created).startsWith(TestFixtures.arn("secretsmanager", "000000000000",
|
||||
"secret:" + prefix + "/core-"));
|
||||
assertThatThrownBy(() -> caller.createSecret(r -> r.name("other-" + prefix).secretString("x")))
|
||||
.isInstanceOfSatisfying(SecretsManagerException.class, this::assertDenied);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a secret named by its name is authorized against its full ARN")
|
||||
void secretNamedByItsName() {
|
||||
String arn = root.createSecret(r -> r.name(prefix).secretString("x")).arn();
|
||||
secrets.add(arn);
|
||||
policy("{\"Effect\":\"Allow\",\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\""
|
||||
+ TestFixtures.arn("secretsmanager", "000000000000", "secret:" + prefix + "-??????") + "\"},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"secretsmanager:DescribeSecret\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"secretsmanager:DescribeSecret\",\"Resource\":\"" + arn + "\"}");
|
||||
|
||||
assertThat(caller.getSecretValue(r -> r.secretId(prefix)).secretString()).isEqualTo("x");
|
||||
assertThatThrownBy(() -> caller.describeSecret(r -> r.secretId(prefix)))
|
||||
.isInstanceOfSatisfying(SecretsManagerException.class, this::assertDenied);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a secret named by a partial ARN is authorized against its full ARN")
|
||||
void secretNamedByAPartialArn() {
|
||||
String arn = root.createSecret(r -> r.name(prefix).secretString("x")).arn();
|
||||
secrets.add(arn);
|
||||
String partialArn = arn.substring(0, arn.length() - "-AbCdEf".length());
|
||||
policy("{\"Effect\":\"Allow\",\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\""
|
||||
+ TestFixtures.arn("secretsmanager", "000000000000", "secret:" + prefix + "-??????") + "\"},"
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"secretsmanager:DescribeSecret\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"secretsmanager:DescribeSecret\",\"Resource\":\"" + arn + "\"}");
|
||||
|
||||
assertThat(caller.getSecretValue(r -> r.secretId(partialArn)).secretString()).isEqualTo("x");
|
||||
assertThatThrownBy(() -> caller.describeSecret(r -> r.secretId(partialArn)))
|
||||
.isInstanceOfSatisfying(SecretsManagerException.class, this::assertDenied);
|
||||
}
|
||||
|
||||
private void policy(String statements) {
|
||||
iam.putUserPolicy(r -> r.userName(user).policyName("secrets")
|
||||
.policyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"));
|
||||
policyCreated = true;
|
||||
}
|
||||
|
||||
private void assertDenied(SecretsManagerException error) {
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).contains("AccessDenied");
|
||||
}
|
||||
|
||||
private static SecretsManagerClient client(String accessKey, String secret) {
|
||||
return SecretsManagerClient.builder().endpointOverride(TestFixtures.endpoint()).region(TestFixtures.region())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret)))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1300,6 +1300,14 @@ ARNs take precedence over plain-name interpretation and must identify a local gr
|
||||
is accepted on a canonical local group ARN. These compatibility forms are not a claim that AWS accepts
|
||||
them for these APIs. Other Logs actions retain their existing wildcard resource evaluation.
|
||||
|
||||
**Secrets Manager secrets.** A request that names a secret by its name, or by a partial ARN without
|
||||
the random suffix, is evaluated against the stored secret's full ARN, suffix included, so a
|
||||
`secret:<name>-??????` resource, the pattern the Secrets Manager User Guide documents, matches it as
|
||||
it does on AWS, and a `Deny` on the full ARN applies. `CreateSecret` is evaluated against
|
||||
`secret:<Name>-??????`, standing in for the suffix the secret is assigned when it is created, so a
|
||||
policy scoped to a name prefix such as `secret:app/*` allows it. A name that matches no secret in the
|
||||
request's account and region is evaluated as `secret:<name>`, and an ARN that matches none as given.
|
||||
|
||||
**IAM's own resources are named.** When enforcement evaluates a request, the target resource comes
|
||||
from `ResourceArnBuilder`, which builds an ARN for S3, Lambda, SQS, SNS, DynamoDB, Kinesis, Secrets
|
||||
Manager, SSM, KMS and IAM. Within IAM the resource type each action is evaluated against is the one
|
||||
|
||||
@@ -416,9 +416,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
List<String> resources = resolveResourceArns(credentialScope,
|
||||
"logs".equals(credentialScope)
|
||||
? arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition())
|
||||
: arnBuilder.buildResources(credentialScope, ctx, region, accountId));
|
||||
targetResources(credentialScope, action, ctx, region, accountId));
|
||||
|
||||
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
|
||||
if (presignedScope.isPresent()) {
|
||||
@@ -1183,6 +1181,18 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
};
|
||||
}
|
||||
|
||||
/** Logs and Secrets Manager targets depend on the serving operation and the request's partition. */
|
||||
private List<String> targetResources(String credentialScope, String action, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
if ("logs".equals(credentialScope)) {
|
||||
return arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
if ("secretsmanager".equals(credentialScope)) {
|
||||
return arnBuilder.buildSecretsManagerResources(action, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
return arnBuilder.buildResources(credentialScope, ctx, region, accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The partition the request belongs to, for the principals this filter synthesizes. Set by
|
||||
* {@link AccountContextFilter}; the deployment partition covers a call that reaches here first.
|
||||
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -50,25 +51,39 @@ public class ResourceArnBuilder {
|
||||
/** Reads the CBOR bodies the RPC v2 and {@code x-amz-cbor-1.1} paths carry. */
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
/**
|
||||
* Stands in for the random suffix of a secret that {@code CreateSecret} has not made yet. Each
|
||||
* {@code ?} matches the one character a {@code secret:<name>-??????} policy expects there.
|
||||
*/
|
||||
private static final String UNASSIGNED_SECRET_SUFFIX = "-??????";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Looked up lazily through a provider: this builder is constructed by the enforcement filter,
|
||||
* which IamService itself does not depend on, and a direct injection would close that loop.
|
||||
*/
|
||||
private final Instance<IamService> iamService;
|
||||
/** Looked up lazily for the same reason, to resolve a secret named by its name or a partial ARN. */
|
||||
private final Instance<SecretsManagerService> secretsManagerService;
|
||||
|
||||
@Inject
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<SecretsManagerService> secretsManagerService) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamService = iamService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
}
|
||||
|
||||
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
this(objectMapper, iamService, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder() {
|
||||
this(new ObjectMapper(), null);
|
||||
this(new ObjectMapper(), null, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper) {
|
||||
this(objectMapper, null);
|
||||
this(objectMapper, null, null);
|
||||
}
|
||||
|
||||
public String build(String credentialScope, ContainerRequestContext ctx,
|
||||
@@ -90,7 +105,6 @@ public class ResourceArnBuilder {
|
||||
case "sns" -> List.of(buildSnsArn(ctx, region, accountId));
|
||||
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
|
||||
case "kinesis" -> List.of(buildKinesisArn(ctx, region, accountId));
|
||||
case "secretsmanager" -> List.of(buildSecretsManagerArn(ctx, region, accountId));
|
||||
case "ssm" -> List.of(buildSsmArn(ctx, region, accountId));
|
||||
case "kms" -> List.of(buildKmsArn(path, region, accountId));
|
||||
case "iam" -> buildIamArns(ctx, region, accountId);
|
||||
@@ -945,20 +959,57 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
// ── Secrets Manager ──────────────────────────────────────────────────────────
|
||||
private String buildSecretsManagerArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
|
||||
/**
|
||||
* Uses the serving operation, as {@link #buildLogResources} does: {@code CreateSecret}
|
||||
* names the secret in {@code Name} and every other operation in {@code SecretId}, so a field the
|
||||
* handler does not read cannot choose the resource. A minted ARN takes the request's partition,
|
||||
* the one the secret is created in, which a region Floci does not know cannot be mapped to.
|
||||
*/
|
||||
public List<String> buildSecretsManagerResources(String action, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
return List.of(buildSecretsManagerArn(action, ctx, region, accountId, partition));
|
||||
}
|
||||
|
||||
/**
|
||||
* A secret named by its name or a partial ARN is authorized against its full ARN, random suffix
|
||||
* included, so a {@code secret:<name>-??????} policy matches it as it does on AWS. The suffix of
|
||||
* the secret {@code CreateSecret} is making is not assigned until it is created.
|
||||
*/
|
||||
private String buildSecretsManagerArn(String action, ContainerRequestContext ctx, String region,
|
||||
String accountId, String partition) {
|
||||
JsonNode json = readJsonBody(ctx);
|
||||
if (json != null && json.isObject()) {
|
||||
if (json.hasNonNull("SecretId")) {
|
||||
if ("secretsmanager:CreateSecret".equals(action)) {
|
||||
if (json.hasNonNull("Name")) {
|
||||
String name = json.get("Name").asText().trim();
|
||||
if (!name.isEmpty()) {
|
||||
return secretArn(name + UNASSIGNED_SECRET_SUFFIX, region, accountId, partition);
|
||||
}
|
||||
}
|
||||
} else if (json.hasNonNull("SecretId")) {
|
||||
String secretId = json.get("SecretId").asText().trim();
|
||||
if (!secretId.isEmpty()) {
|
||||
Optional<String> stored = storedSecretArn(secretId, region, accountId);
|
||||
if (AwsArnUtils.isArnFor(secretId, "secretsmanager")) {
|
||||
return secretId;
|
||||
return stored.orElse(secretId);
|
||||
}
|
||||
return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:" + secretId).toString();
|
||||
return stored.orElseGet(() -> secretArn(secretId, region, accountId, partition));
|
||||
}
|
||||
}
|
||||
}
|
||||
return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:*").toString();
|
||||
return secretArn("*", region, accountId, partition);
|
||||
}
|
||||
|
||||
private Optional<String> storedSecretArn(String secretId, String region, String accountId) {
|
||||
if (secretsManagerService == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return secretsManagerService.get().findArn(accountId, secretId, region);
|
||||
}
|
||||
|
||||
private static String secretArn(String name, String region, String accountId, String partition) {
|
||||
return new AwsArnUtils.Arn(partition, "secretsmanager", region, accountId, "secret:" + name).toString();
|
||||
}
|
||||
|
||||
// ── SSM ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
+57
-10
@@ -37,6 +37,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -416,6 +417,39 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
return secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* The full ARN of the secret {@code secretId} names in the given account, or empty when there is
|
||||
* none, resolved in the order the operations resolve it: a name in {@code region}, or an ARN,
|
||||
* matched exactly before it is read as a partial ARN without the random suffix. An ARN that
|
||||
* matches neither way in this account is empty, and the caller authorizes the ARN as given, which
|
||||
* is the secret the operations then look for in the account the ARN names. IAM enforcement reads
|
||||
* it before the request runs: AWS authorizes a request against the secret's ARN, random suffix
|
||||
* included, however the request names the secret.
|
||||
*/
|
||||
public Optional<String> findArn(String accountId, String secretId, String region) {
|
||||
if (!secretId.startsWith("arn:")) {
|
||||
return findArnByName(accountId, secretId, region);
|
||||
}
|
||||
AwsArnUtils.Arn arn = parseOrNull(secretId);
|
||||
String nameFromArn = secretNameOrNull(arn);
|
||||
if (nameFromArn == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (findByArnInAccount(accountId, secretId, arn) != null) {
|
||||
return Optional.of(secretId);
|
||||
}
|
||||
return findArnByName(accountId, nameFromArn, arn.region());
|
||||
}
|
||||
|
||||
/** The full ARN of the secret with this name in the given account and region, or empty when there is none. */
|
||||
Optional<String> findArnByName(String accountId, String name, String region) {
|
||||
String key = regionKey(region, name);
|
||||
Optional<Secret> secret = store instanceof AccountAwareStorageBackend<Secret> aware
|
||||
? aware.getForAccount(accountId, key).or(() -> aware.getLegacyForAccount(accountId, key))
|
||||
: store.get(key);
|
||||
return secret.map(Secret::getArn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the secret with this ARN as owned by an AWS service, so that it rotates the way a
|
||||
* service-managed secret does. Ownership is normally set when the owning service creates the
|
||||
@@ -457,9 +491,14 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
|
||||
/** Finds a secret by full ARN within the account and region that ARN names. */
|
||||
private Secret findByArnInAccount(String secretArn, AwsArnUtils.Arn arn) {
|
||||
return findByArnInAccount(arn.accountId(), secretArn, arn);
|
||||
}
|
||||
|
||||
/** Finds a secret by full ARN within the given account and the region that ARN names. */
|
||||
private Secret findByArnInAccount(String accountId, String secretArn, AwsArnUtils.Arn arn) {
|
||||
Predicate<String> inRegion = key -> key.startsWith(arn.region() + "::");
|
||||
List<Secret> candidates = store instanceof AccountAwareStorageBackend<Secret> aware
|
||||
? aware.scanForAccount(arn.accountId(), inRegion)
|
||||
? aware.scanForAccount(accountId, inRegion)
|
||||
: store.scan(inRegion);
|
||||
return candidates.stream()
|
||||
.filter(s -> secretArn.equals(s.getArn()))
|
||||
@@ -1773,16 +1812,11 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
// ARN format: arn:<partition>:secretsmanager:<region>:<account>:secret:<name>
|
||||
// Parsed rather than matched against a literal prefix, because the ARN carries the
|
||||
// region's own partition and a pinned "arn:aws:" refused a GovCloud or China
|
||||
// secret its own ARN. The name comes off the parsed resource without a second
|
||||
// split: a secret name may itself contain colons.
|
||||
// secret its own ARN.
|
||||
AwsArnUtils.Arn parsedArn = parseOrNull(secretId);
|
||||
String secretResourcePrefix = "secret:";
|
||||
if (parsedArn != null
|
||||
&& "secretsmanager".equals(parsedArn.service())
|
||||
&& parsedArn.resource().startsWith(secretResourcePrefix)) {
|
||||
String arnRegion = parsedArn.region();
|
||||
String nameFromArn = parsedArn.resource().substring(secretResourcePrefix.length());
|
||||
Secret byName = store.get(regionKey(arnRegion, nameFromArn)).orElse(null);
|
||||
String nameFromArn = secretNameOrNull(parsedArn);
|
||||
if (nameFromArn != null) {
|
||||
Secret byName = store.get(regionKey(parsedArn.region(), nameFromArn)).orElse(null);
|
||||
if (byName != null) {
|
||||
return byName;
|
||||
}
|
||||
@@ -1834,6 +1868,19 @@ public class SecretsManagerService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The secret name a Secrets Manager secret ARN carries, taken off the parsed resource without a
|
||||
* second split because a name may itself contain colons, or {@code null} for any other ARN.
|
||||
*/
|
||||
private static String secretNameOrNull(AwsArnUtils.Arn arn) {
|
||||
String secretResourcePrefix = "secret:";
|
||||
if (arn == null || !"secretsmanager".equals(arn.service())
|
||||
|| !arn.resource().startsWith(secretResourcePrefix)) {
|
||||
return null;
|
||||
}
|
||||
return arn.resource().substring(secretResourcePrefix.length());
|
||||
}
|
||||
|
||||
private static String regionKey(String region, String name) {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
+5
-19
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
@@ -219,9 +220,6 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
return spec.when().post("/");
|
||||
}
|
||||
|
||||
private record Session(String accessKeyId, String sessionToken) {
|
||||
}
|
||||
|
||||
/** A user in {@link #OTHER_ACCOUNT} carrying the sts:AssumeRole its own policies have to allow. */
|
||||
private String createCallerUser(String user) {
|
||||
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
|
||||
@@ -234,24 +232,12 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
|
||||
/** A role in the trusted account that its own account may assume, allowed to call AssumeRole. */
|
||||
private void createCallerRole(String name, String path) {
|
||||
cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(),
|
||||
auth(TRUSTED_ACCOUNT, "iam"), name));
|
||||
given().formParam("Action", "CreateRole").formParam("RoleName", name).formParam("Path", path)
|
||||
.formParam("AssumeRolePolicyDocument", trustAccountRoot(TRUSTED_ACCOUNT))
|
||||
.header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
given().formParam("Action", "PutRolePolicy").formParam("RoleName", name).formParam("PolicyName", "p")
|
||||
.formParam("PolicyDocument", ALLOW_ASSUME_ROLE)
|
||||
.header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
EnforcementFixtures.createRole(cleanup, baseUri.getPort(), TRUSTED_ACCOUNT, path, name, ALLOW_ASSUME_ROLE);
|
||||
}
|
||||
|
||||
private static Session assumeCallerRole(String name, String path) {
|
||||
Response response = given().formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", "arn:aws:iam::" + TRUSTED_ACCOUNT + ":role" + path + name)
|
||||
.formParam("RoleSessionName", "s")
|
||||
.header("Authorization", auth(TRUSTED_ACCOUNT, "sts")).when().post("/");
|
||||
response.then().statusCode(200);
|
||||
return new Session(response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
|
||||
response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
|
||||
private Session assumeCallerRole(String name, String path) {
|
||||
return EnforcementFixtures.assumeRole(baseUri.getPort(), TRUSTED_ACCOUNT,
|
||||
"arn:aws:iam::" + TRUSTED_ACCOUNT + ":role" + path + name);
|
||||
}
|
||||
|
||||
private static Response assumeRoleWithSession(Session session, String role) {
|
||||
|
||||
+14
-32
@@ -1,16 +1,23 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
|
||||
@@ -32,8 +39,11 @@ class PrincipalContextKeysEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
|
||||
private record Session(String accessKeyId, String sessionToken) {
|
||||
}
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -68,8 +78,7 @@ class PrincipalContextKeysEnforcementIntegrationTest {
|
||||
@Test
|
||||
void aRoleSessionCarriesNoUserNameAndIsTypedAsAnAssumedRole() {
|
||||
String role = "principal-keys-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String roleArn = "arn:aws:iam::" + ACCOUNT + ":role/" + role;
|
||||
createRole(role, """
|
||||
String roleArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", role, """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalType":"AssumedRole"}}},
|
||||
@@ -77,7 +86,7 @@ class PrincipalContextKeysEnforcementIntegrationTest {
|
||||
"Condition":{"StringEquals":{"aws:username":"%s"}}},
|
||||
{"Effect":"Allow","Action":"iam:ListGroups","Resource":"*",
|
||||
"Condition":{"StringLike":{"aws:userid":"AROA*:s"}}}]}""".formatted(role));
|
||||
Session session = assumeRole(roleArn);
|
||||
Session session = EnforcementFixtures.assumeRole(baseUri.getPort(), ACCOUNT, roleArn);
|
||||
|
||||
iamCall(session.accessKeyId(), session.sessionToken(), "ListUsers").then().statusCode(200);
|
||||
// The guide lists aws:username as not present for a role, so a statement that matches on
|
||||
@@ -110,28 +119,6 @@ class PrincipalContextKeysEnforcementIntegrationTest {
|
||||
"CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static void createRole(String role, String policy) {
|
||||
given().formParam("Action", "CreateRole").formParam("RoleName", role)
|
||||
.formParam("AssumeRolePolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
|
||||
.formatted(ACCOUNT))
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
given().formParam("Action", "PutRolePolicy").formParam("RoleName", role)
|
||||
.formParam("PolicyName", "p").formParam("PolicyDocument", policy)
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Session assumeRole(String roleArn) {
|
||||
Response response = given().formParam("Action", "AssumeRole").formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", "s")
|
||||
.header("Authorization", auth(ACCOUNT, "sts")).when().post("/");
|
||||
response.then().statusCode(200);
|
||||
return new Session(
|
||||
response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
|
||||
response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
|
||||
}
|
||||
|
||||
private static Response iamCall(String accessKeyId, String sessionToken, String action) {
|
||||
RequestSpecification request = given().formParam("Action", action)
|
||||
.header("Authorization", auth(accessKeyId, "iam"));
|
||||
@@ -140,9 +127,4 @@ class PrincipalContextKeysEnforcementIntegrationTest {
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
@@ -108,6 +109,14 @@ class ResourceArnBuilderTest {
|
||||
return new ResourceArnBuilder(new ObjectMapper(), instance);
|
||||
}
|
||||
|
||||
/** A builder reading {@code secrets}, for a secret named by its name. */
|
||||
private static ResourceArnBuilder backedBy(SecretsManagerService secrets) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<SecretsManagerService> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(secrets);
|
||||
return new ResourceArnBuilder(new ObjectMapper(), null, instance);
|
||||
}
|
||||
|
||||
private static IamService storeHolding(String userName, String path, String arn) {
|
||||
IamUser user = new IamUser();
|
||||
user.setUserName(userName);
|
||||
@@ -902,8 +911,88 @@ class ResourceArnBuilderTest {
|
||||
@Test
|
||||
void secretsManagerBuildsArnFromSecretId() {
|
||||
setJsonBody("{\"SecretId\":\"app/prod/database\"}");
|
||||
String arn = builder.build("secretsmanager", ctx, "us-east-1", "000000000000");
|
||||
assertEquals("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/prod/database", arn);
|
||||
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/prod/database"),
|
||||
builder.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx, "us-east-1",
|
||||
"000000000000", "aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerResolvesASecretNamedByItsNameToItsStoredArn() {
|
||||
String storedArn = "arn:aws:secretsmanager:us-east-1:111122223333:secret:app/core-AbC123";
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
when(secrets.findArn("111122223333", "app/core", "us-east-1")).thenReturn(Optional.of(storedArn));
|
||||
setJsonBody("{\"SecretId\":\"app/core\"}");
|
||||
|
||||
List<String> arns = backedBy(secrets).buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx,
|
||||
"us-east-1", "111122223333", "aws");
|
||||
|
||||
assertEquals(List.of(storedArn), arns);
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerKeepsTheNameOfASecretThatIsNotStored() {
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
when(secrets.findArn(ACCOUNT, "app/missing", "us-east-1")).thenReturn(Optional.empty());
|
||||
setJsonBody("{\"SecretId\":\"app/missing\"}");
|
||||
|
||||
List<String> arns = backedBy(secrets).buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx,
|
||||
"us-east-1", ACCOUNT, "aws");
|
||||
|
||||
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/missing"), arns);
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerResolvesAPartialArnToTheStoredArnAndKeepsAnArnThatIsNotStored() {
|
||||
String partialArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app/core";
|
||||
String storedArn = partialArn + "-AbC123";
|
||||
String missingArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:app/missing";
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
when(secrets.findArn(ACCOUNT, partialArn, "us-east-1")).thenReturn(Optional.of(storedArn));
|
||||
when(secrets.findArn(ACCOUNT, missingArn, "us-east-1")).thenReturn(Optional.empty());
|
||||
ResourceArnBuilder backed = backedBy(secrets);
|
||||
|
||||
setJsonBody("{\"SecretId\":\"" + partialArn + "\"}");
|
||||
assertEquals(List.of(storedArn), backed.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx,
|
||||
"us-east-1", ACCOUNT, "aws"));
|
||||
setJsonBody("{\"SecretId\":\"" + missingArn + "\"}");
|
||||
assertEquals(List.of(missingArn), backed.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx,
|
||||
"us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerCreateSecretBuildsArnFromNameWithAnUnassignedSuffix() {
|
||||
setJsonBody("{\"Name\":\"app/core\",\"SecretString\":\"x\"}");
|
||||
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/core-??????"),
|
||||
builder.buildSecretsManagerResources("secretsmanager:CreateSecret", ctx, "us-east-1", ACCOUNT,
|
||||
"aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerTargetsTheFieldTheServingOperationReads() {
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
when(secrets.findArn(ACCOUNT, "app/existing", "us-east-1"))
|
||||
.thenReturn(Optional.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/existing-AbC123"));
|
||||
ResourceArnBuilder backed = backedBy(secrets);
|
||||
|
||||
setJsonBody("{\"Name\":\"app/new\",\"SecretId\":\"app/existing\",\"SecretString\":\"x\"}");
|
||||
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/new-??????"),
|
||||
backed.buildSecretsManagerResources("secretsmanager:CreateSecret", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
setJsonBody("{\"Name\":\"app/new\"}");
|
||||
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:*"),
|
||||
backed.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx, "us-east-1", ACCOUNT,
|
||||
"aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretsManagerMintsArnsInTheRequestPartition() {
|
||||
setJsonBody("{\"Name\":\"app/core\"}");
|
||||
assertEquals(List.of("arn:aws-cn:secretsmanager:polygondwanaland-west-1:000000000000:secret:app/core-??????"),
|
||||
builder.buildSecretsManagerResources("secretsmanager:CreateSecret", ctx, "polygondwanaland-west-1",
|
||||
ACCOUNT, "aws-cn"));
|
||||
setJsonBody("{\"SecretId\":\"app/core\"}");
|
||||
assertEquals(List.of("arn:aws-us-gov:secretsmanager:polygondwanaland-west-1:000000000000:secret:app/core"),
|
||||
builder.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx, "polygondwanaland-west-1",
|
||||
ACCOUNT, "aws-us-gov"));
|
||||
}
|
||||
|
||||
// ── SSM ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
+16
-27
@@ -1,15 +1,22 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@@ -24,8 +31,11 @@ class RoleSessionPrincipalArnEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
|
||||
private record Session(String accessKeyId, String sessionToken) {
|
||||
}
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -46,7 +56,7 @@ class RoleSessionPrincipalArnEnforcementIntegrationTest {
|
||||
{"Effect":"Allow","Action":"iam:ListGroups","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"iam:ListGroups","Resource":"*",
|
||||
"Condition":{"ArnEquals":{"aws:PrincipalArn":"%1$s"}}}]}""".formatted(roleArn, sessionArn));
|
||||
Session session = assumeRole(roleArn);
|
||||
Session session = EnforcementFixtures.assumeRole(baseUri.getPort(), ACCOUNT, roleArn);
|
||||
|
||||
// A condition on the role's own ARN matches the session.
|
||||
iamCall(session, "ListUsers").then().statusCode(200);
|
||||
@@ -73,7 +83,7 @@ class RoleSessionPrincipalArnEnforcementIntegrationTest {
|
||||
{"Effect":"Allow","Action":"ssm:GetParameter","Resource":"*"},
|
||||
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"*",
|
||||
"Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}}]}""".formatted(roleArn));
|
||||
Session session = assumeRole(roleArn);
|
||||
Session session = EnforcementFixtures.assumeRole(baseUri.getPort(), ACCOUNT, roleArn);
|
||||
|
||||
given().header("Authorization", auth(session.accessKeyId(), "ssm"))
|
||||
.header("X-Amz-Security-Token", session.sessionToken())
|
||||
@@ -86,24 +96,8 @@ class RoleSessionPrincipalArnEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/** A role under /team/ that its own account may assume, with {@code policy} inline. */
|
||||
private static void createRole(String role, String policy) {
|
||||
given().formParam("Action", "CreateRole").formParam("RoleName", role).formParam("Path", "/team/")
|
||||
.formParam("AssumeRolePolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""".formatted(ACCOUNT))
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
given().formParam("Action", "PutRolePolicy").formParam("RoleName", role).formParam("PolicyName", "p")
|
||||
.formParam("PolicyDocument", policy)
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Session assumeRole(String roleArn) {
|
||||
Response response = given().formParam("Action", "AssumeRole").formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", "s")
|
||||
.header("Authorization", auth(ACCOUNT, "sts")).when().post("/");
|
||||
response.then().statusCode(200);
|
||||
return new Session(response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
|
||||
response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
|
||||
private void createRole(String role, String policy) {
|
||||
EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/team/", role, policy);
|
||||
}
|
||||
|
||||
private static Response iamCall(Session session, String action) {
|
||||
@@ -112,9 +106,4 @@ class RoleSessionPrincipalArnEnforcementIntegrationTest {
|
||||
.header("X-Amz-Security-Token", session.sessionToken())
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* With {@code iam.enforcement-enabled=true}, a request that names a secret by its name or a partial
|
||||
* ARN is authorized against the secret's ARN, random suffix included, as AWS does. The Secrets Manager
|
||||
* user guide relies on it: a {@code secret:<name>-??????} resource "enables you to securely grant
|
||||
* permissions to a secret that doesn't yet exist".
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class SecretsManagerSecretArnEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String SECRET_ARN_PREFIX = "arn:aws:secretsmanager:us-east-1:" + ACCOUNT + ":secret:";
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSecretIsAuthorizedAgainstTheNewSecretsName() {
|
||||
String prefix = "app-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Session session = assumeRoleWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"secretsmanager:CreateSecret","Resource":"%s%s/*"}]}"""
|
||||
.formatted(SECRET_ARN_PREFIX, prefix));
|
||||
|
||||
deleteSecretAfterTheTest(prefix + "/core");
|
||||
secretsCall(session, "CreateSecret", "{\"Name\": \"" + prefix + "/core\", \"SecretString\": \"x\"}")
|
||||
.then().statusCode(200);
|
||||
secretsCall(session, "CreateSecret", "{\"Name\": \"other-" + prefix + "\", \"SecretString\": \"x\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecretNamedByItsNameIsAuthorizedAgainstItsFullArn() {
|
||||
String name = "app-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String arn = createSecret(name);
|
||||
Session session = assumeRoleWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s%s-??????"},
|
||||
{"Effect":"Allow","Action":"secretsmanager:DescribeSecret","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"secretsmanager:DescribeSecret","Resource":"%s"}]}"""
|
||||
.formatted(SECRET_ARN_PREFIX, name, arn));
|
||||
|
||||
// The documented name-plus-suffix pattern matches a secret read by its name.
|
||||
secretsCall(session, "GetSecretValue", "{\"SecretId\": \"" + name + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("SecretString", equalTo("x"));
|
||||
// A Deny on the stored ARN, suffix included, applies when the request names the secret.
|
||||
secretsCall(session, "DescribeSecret", "{\"SecretId\": \"" + name + "\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecretNamedByAPartialArnIsAuthorizedAgainstItsFullArn() {
|
||||
String name = "app-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String arn = createSecret(name);
|
||||
String partialArn = SECRET_ARN_PREFIX + name;
|
||||
Session session = assumeRoleWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s%s-??????"},
|
||||
{"Effect":"Allow","Action":"secretsmanager:DescribeSecret","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"secretsmanager:DescribeSecret","Resource":"%s"}]}"""
|
||||
.formatted(SECRET_ARN_PREFIX, name, arn));
|
||||
|
||||
secretsCall(session, "GetSecretValue", "{\"SecretId\": \"" + partialArn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("SecretString", equalTo("x"));
|
||||
secretsCall(session, "DescribeSecret", "{\"SecretId\": \"" + partialArn + "\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSecretIgnoresASecretIdTheHandlerDoesNotRead() {
|
||||
String existing = "app-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
createSecret(existing);
|
||||
Session session = assumeRoleWith("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"secretsmanager:CreateSecret","Resource":"%s%s-??????"}]}"""
|
||||
.formatted(SECRET_ARN_PREFIX, existing));
|
||||
|
||||
// A grant on the existing secret does not authorize creating another one beside it.
|
||||
secretsCall(session, "CreateSecret", "{\"Name\": \"other-" + existing + "\", \"SecretId\": \""
|
||||
+ existing + "\", \"SecretString\": \"x\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
private String createSecret(String name) {
|
||||
deleteSecretAfterTheTest(name);
|
||||
Response response = accountCall("CreateSecret", "{\"Name\": \"" + name + "\", \"SecretString\": \"x\"}");
|
||||
response.then().statusCode(200);
|
||||
return response.path("ARN");
|
||||
}
|
||||
|
||||
private void deleteSecretAfterTheTest(String name) {
|
||||
cleanup.register(() -> accountCall("DeleteSecret",
|
||||
"{\"SecretId\": \"" + name + "\", \"ForceDeleteWithoutRecovery\": true}").then().statusCode(200));
|
||||
}
|
||||
|
||||
/** A session of a new role that its own account may assume, with {@code policy} inline. */
|
||||
private Session assumeRoleWith(String policy) {
|
||||
int port = baseUri.getPort();
|
||||
String roleArn = EnforcementFixtures.createRole(cleanup, port, ACCOUNT, "/",
|
||||
"secret-arn-" + UUID.randomUUID().toString().substring(0, 8), policy);
|
||||
return EnforcementFixtures.assumeRole(port, ACCOUNT, roleArn);
|
||||
}
|
||||
|
||||
/** A call as the account itself, which the cleanup also makes after RestAssured's port is reset. */
|
||||
private Response accountCall(String action, String body) {
|
||||
return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "secretsmanager"))
|
||||
.header("X-Amz-Target", "secretsmanager." + action)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private static Response secretsCall(Session session, String action, String body) {
|
||||
return given().header("Authorization", auth(session.accessKeyId(), "secretsmanager"))
|
||||
.header("X-Amz-Security-Token", session.sessionToken())
|
||||
.header("X-Amz-Target", "secretsmanager." + action)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
* In a China deployment that also serves regions Floci does not know, {@code CreateSecret} is
|
||||
* authorized against the ARN in the partition the secret is created in: the deployment's for an
|
||||
* unknown region, rather than the commercial one a region lookup falls back to, and the region's
|
||||
* own for a known one.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.ChinaProfile.class)
|
||||
class SecretsManagerUnknownRegionAuthorizationIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@BeforeAll
|
||||
static void configureContentTypes() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"polygondwanaland-west-1,aws-cn", "cn-north-1,aws-cn", "us-gov-west-1,aws-us-gov", "us-east-1,aws"})
|
||||
void createSecretIsAuthorizedInThePartitionItIsCreatedIn(String region, String partition) {
|
||||
int port = endpoint.getPort();
|
||||
String name = "secret-partition-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String secretArnPrefix = "arn:" + partition + ":secretsmanager:" + region + ":" + ACCOUNT + ":secret:";
|
||||
String root = EnforcementFixtures.auth(ACCOUNT, "iam");
|
||||
String user = "secret-partition-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String caller = EnforcementFixtures.createUser(cleanup, port, root, user).accessKeyId();
|
||||
given().port(port).header("Authorization", root).formParam("Action", "PutUserPolicy")
|
||||
.formParam("UserName", user).formParam("PolicyName", "secrets")
|
||||
.formParam("PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"secretsmanager:CreateSecret","Resource":"%s%s-??????"}]}"""
|
||||
.formatted(secretArnPrefix, name))
|
||||
.when().post("/").then().statusCode(200);
|
||||
cleanup.register(() -> call(ACCOUNT, region, "DeleteSecret",
|
||||
"{\"SecretId\": \"" + name + "\", \"ForceDeleteWithoutRecovery\": true}").then().statusCode(200));
|
||||
|
||||
call(caller, region, "CreateSecret", "{\"Name\": \"" + name + "\", \"SecretString\": \"x\"}")
|
||||
.then().statusCode(200)
|
||||
.body("ARN", startsWith(secretArnPrefix + name + "-"));
|
||||
}
|
||||
|
||||
private Response call(String caller, String region, String action, String body) {
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=" + caller + "/20261015/" + region
|
||||
+ "/secretsmanager/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
return given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", auth).header("X-Amz-Target", "secretsmanager." + action)
|
||||
.body(body).when().post("/");
|
||||
}
|
||||
}
|
||||
+93
@@ -528,6 +528,99 @@ class SecretsManagerServiceTest {
|
||||
assertNull(sameNameHere.getOwningService());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnByNameReturnsTheStoredArnWithItsSuffix() {
|
||||
Secret created = service.createSecret("app/core", "value", null, null, null, null, REGION);
|
||||
|
||||
assertEquals(created.getArn(), service.findArnByName("000000000000", "app/core", REGION).orElseThrow());
|
||||
assertTrue(service.findArnByName("000000000000", "app/missing", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnByNameReadsOnlyTheNamedAccount() {
|
||||
AccountAwareStorageBackend<Secret> accountAware =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
SecretsManagerService svc = new SecretsManagerService(accountAware, 30);
|
||||
Secret otherAccount = new Secret();
|
||||
otherAccount.setName("app/core");
|
||||
otherAccount.setArn("arn:aws:secretsmanager:" + REGION + ":111122223333:secret:app/core-AbCdEf");
|
||||
accountAware.putForAccount("111122223333", REGION + "::app/core", otherAccount);
|
||||
|
||||
assertEquals(otherAccount.getArn(), svc.findArnByName("111122223333", "app/core", REGION).orElseThrow());
|
||||
assertTrue(svc.findArnByName("000000000000", "app/core", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnResolvesANameOrAnArnTheWayTheOperationsDo() {
|
||||
Secret core = service.createSecret("app/core", "value", null, null, null, null, REGION);
|
||||
String partialArn = core.getArn().substring(0, core.getArn().length() - "-AbCdEf".length());
|
||||
|
||||
assertEquals(core.getArn(), service.findArn("000000000000", "app/core", REGION).orElseThrow());
|
||||
assertEquals(core.getArn(), service.findArn("000000000000", core.getArn(), REGION).orElseThrow());
|
||||
assertEquals(core.getArn(), service.findArn("000000000000", partialArn, "eu-west-1").orElseThrow());
|
||||
assertFindArnNamesTheSecretTheOperationActsOn(service, "app/core", REGION);
|
||||
assertFindArnNamesTheSecretTheOperationActsOn(service, core.getArn(), REGION);
|
||||
assertFindArnNamesTheSecretTheOperationActsOn(service, partialArn, "eu-west-1");
|
||||
assertTrue(service.findArn("000000000000", partialArn.replace("app/core", "app/missing"), REGION).isEmpty());
|
||||
assertTrue(service.findArn("000000000000", "arn:aws:s3:::app/core", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnPrefersTheCallersAccountToTheOneTheArnNamesAsTheOperationsDo() {
|
||||
AccountAwareStorageBackend<Secret> accountAware =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
SecretsManagerService svc = new SecretsManagerService(accountAware, 30);
|
||||
Secret otherAccount = new Secret();
|
||||
otherAccount.setName("app/core");
|
||||
otherAccount.setArn("arn:aws:secretsmanager:" + REGION + ":111122223333:secret:app/core-AbCdEf");
|
||||
accountAware.putForAccount("111122223333", REGION + "::app/core", otherAccount);
|
||||
|
||||
// Only the account the ARN names holds it: the caller authorizes the ARN as given, and the
|
||||
// operation finds that secret there.
|
||||
assertTrue(svc.findArn("000000000000", otherAccount.getArn(), REGION).isEmpty());
|
||||
assertFindArnNamesTheSecretTheOperationActsOn(svc, otherAccount.getArn(), REGION);
|
||||
|
||||
// A secret of the caller's own named like the ARN's resource is the one the operation reads
|
||||
// the ARN as, before it looks in the account the ARN names.
|
||||
Secret callers = svc.createSecret("app/core-AbCdEf", "value", null, null, null, null, REGION);
|
||||
assertEquals(callers.getArn(), svc.findArn("000000000000", otherAccount.getArn(), REGION).orElseThrow());
|
||||
assertFindArnNamesTheSecretTheOperationActsOn(svc, otherAccount.getArn(), REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* IAM authorizes {@code findArn}'s answer, or an ARN as given when it has none, so it has to name
|
||||
* the secret the operation then acts on.
|
||||
*/
|
||||
private static void assertFindArnNamesTheSecretTheOperationActsOn(SecretsManagerService svc,
|
||||
String secretId, String region) {
|
||||
assertEquals(svc.describeSecret(secretId, region).getArn(),
|
||||
svc.findArn("000000000000", secretId, region).orElse(secretId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnMatchesAFullArnExactlyBeforeReadingItAsAPartialOne() {
|
||||
Secret core = service.createSecret("app/core", "value", null, null, null, null, REGION);
|
||||
String suffixed = core.getArn().substring(core.getArn().indexOf("app/core"));
|
||||
Secret namedLikeTheArn = service.createSecret(suffixed, "other", null, null, null, null, REGION);
|
||||
|
||||
assertEquals(core.getArn(), service.findArn("000000000000", core.getArn(), REGION).orElseThrow());
|
||||
assertEquals(namedLikeTheArn.getArn(), service.findArn("000000000000", suffixed, REGION).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findArnByNameReadsALegacyEntryOnlyForTheDefaultAccount() {
|
||||
InMemoryStorage<String, Secret> raw = new InMemoryStorage<>();
|
||||
SecretsManagerService svc = new SecretsManagerService(
|
||||
new AccountAwareStorageBackend<>(raw, null, "000000000000"), 30);
|
||||
Secret legacy = new Secret();
|
||||
legacy.setName("app/legacy");
|
||||
legacy.setArn("arn:aws:secretsmanager:" + REGION + ":000000000000:secret:app/legacy-AbCdEf");
|
||||
raw.put(REGION + "::app/legacy", legacy);
|
||||
|
||||
assertEquals(legacy.getArn(), svc.findArnByName("000000000000", "app/legacy", REGION).orElseThrow());
|
||||
assertTrue(svc.findArnByName("111122223333", "app/legacy", REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinarySecretNamedLikeAnRdsSecretStillNeedsALambdaArn() {
|
||||
// Ownership is a property of the secret, not of its name: anyone may create a secret
|
||||
|
||||
@@ -15,11 +15,12 @@ import static io.restassured.RestAssured.given;
|
||||
|
||||
/**
|
||||
* Takes an IAM user or an S3 bucket that a test created back out of the shared application, and
|
||||
* makes the users an enforcement test signs as ({@link #createUser}, {@link #auth}) and the SNS
|
||||
* topics it publishes to ({@link #createTopic}), registering each one's removal as it goes. A {@code @QuarkusTest} shares one application with every other
|
||||
* test class, so a fixture left behind outlives the class that made it and is visible to the next
|
||||
* class that lists users or buckets unscoped. Registered with {@link PartitionCleanup} as each
|
||||
* fixture is made.
|
||||
* makes the users, roles and role sessions an enforcement test signs as ({@link #createUser},
|
||||
* {@link #createRole}, {@link #assumeRole}, {@link #auth}) and the SNS topics it publishes to
|
||||
* ({@link #createTopic}), registering each one's removal as it goes. A {@code @QuarkusTest} shares
|
||||
* one application with every other test class, so a fixture left behind outlives the class that
|
||||
* made it and is visible to the next class that lists users or buckets unscoped. Registered with
|
||||
* {@link PartitionCleanup} as each fixture is made.
|
||||
*
|
||||
* <p>Both read back what is attached rather than taking it as an argument, and both return
|
||||
* quietly when the thing is not there. That is what makes them safe to register before the create
|
||||
@@ -105,6 +106,42 @@ public final class EnforcementFixtures {
|
||||
key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a role under {@code path} that the root of its own {@code account} may assume, with
|
||||
* {@code policy} inline, registering its {@link #removeRole} with {@code cleanup} before the
|
||||
* create runs, and returns the role's ARN.
|
||||
*/
|
||||
public static String createRole(PartitionCleanup cleanup, int port, String account, String path,
|
||||
String roleName, String policy) {
|
||||
String authorization = auth(account, "iam");
|
||||
cleanup.register(() -> removeRole(port, authorization, roleName));
|
||||
iam(port, authorization, "CreateRole", "RoleName", roleName, "Path", path,
|
||||
"AssumeRolePolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
|
||||
.formatted(account)).statusCode(200);
|
||||
iam(port, authorization, "PutRolePolicy", "RoleName", roleName, "PolicyName", "p",
|
||||
"PolicyDocument", policy).statusCode(200);
|
||||
return "arn:aws:iam::" + account + ":role" + path + roleName;
|
||||
}
|
||||
|
||||
/** The temporary credentials of a role session, which a request signs with and sends as its token. */
|
||||
public record Session(String accessKeyId, String sessionToken) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Assumes {@code roleArn} as {@code callerAccessKeyId}, in a session named {@code s}, and returns
|
||||
* the session's credentials. The role's trust policy has to admit the caller.
|
||||
*/
|
||||
public static Session assumeRole(int port, String callerAccessKeyId, String roleArn) {
|
||||
XmlPath credentials = query(port, auth(callerAccessKeyId, "sts"), "AssumeRole",
|
||||
"RoleArn", roleArn, "RoleSessionName", "s")
|
||||
.statusCode(200).extract().xmlPath();
|
||||
return new Session(
|
||||
credentials.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
|
||||
credentials.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A SigV4 {@code Authorization} header naming {@code accessKeyId}, scoped to {@code service} in
|
||||
* {@code us-east-1}. The signature is a placeholder, so under a profile that verifies signatures
|
||||
|
||||
Reference in new issue
Block a user