fix(secretsmanager): check Secrets Manager requests from the generated request resources (#8365)

Secrets Manager was built by hand in ResourceArnBuilder. It now moves out of
HAND_BUILT into NAMESPACES, so every operation's resources come from
iam-request-resources.json, and the hand builder and the enforcement filter's
routing to it are gone.

The six characters Secrets Manager mints after a secret's name come from
botocore, which documents CreateSecret's Name: "Secrets Manager automatically
adds a hyphen and six random characters after the secret name at the end of
the ARN". A new rule records them as mintedSuffixes ("-??????") and has the
create name the secret it makes by Name. The reader appends them open to a
secret Secrets Manager does not hold. An ARN given for a secret, a partial
one included, is checked on the ARN of the secret the operations read it as,
alone: SecretsManagerService resolves it through resolveStoredArn to the
caller's secret in the ARN's Region, else to the one the ARN's account holds
under that full ARN, reading only.

ARNs the table renders, and the resource a create makes that its tags are
checked on, take the request's partition for every namespace, as the
Secrets Manager builder did, so a Region Floci does not know keeps the
partition of the request.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 19:50:46 -04:00
1 parent 4373e83af1
commit 1b14d10b1f
15 files changed
+457 -193

No files matched your search

@@ -29,6 +29,7 @@ import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -206,6 +207,10 @@ class RequestResourceMembersTest {
assertTrue(events.get("connection").minted());
assertTrue(events.get("api-destination").minted());
assertFalse(events.get("event-bus").minted());
// A secret is followed by the six characters botocore documents Secrets Manager adding after its name.
assertEquals("-??????",
RequestResourceMembers.table().formats().get("secretsmanager").get("Secret").mintedSuffix());
assertNull(events.get("event-bus").mintedSuffix());
}
@Test
@@ -475,7 +480,9 @@ class RequestResourceMembersTest {
String arn = example(format.format());
String account = resource.account() != null ? "111122223333" : "000000000000";
String expected = resource.arn() != null || resource.through() != null || resource.byDefault() ? arn
: expected(format.format(), resource, account) + (format.minted() ? "/*" : "");
: expected(format.format(), resource, account) + (format.minted() ? "/*"
: format.mintedSuffix() != null && resource.fill().size() == 1
? format.mintedSuffix() : "");
ObjectNode body = MAPPER.createObjectNode();
StringBuilder form = new StringBuilder("Action=" + name);
Map<Member, String> values = resource.arn() != null ? Map.of(resource.arn(), arn)
@@ -23,7 +23,6 @@ import io.floci.aws.services.iam.model.InstanceProfile;
import io.floci.aws.services.iam.model.ServerCertificate;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
@@ -153,14 +152,6 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<LambdaMicrovmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(microvms);
return new ResourceArnBuilder(new ObjectMapper(), null, null, 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);
}
@@ -169,7 +160,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<EksService> instance = mock(Instance.class);
when(instance.get()).thenReturn(eks);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, instance);
}
private static IamService storeHolding(String userName, String path, String arn) {
@@ -1305,91 +1296,104 @@ class ResourceArnBuilderTest {
// ── Secrets Manager ──────────────────────────────────────────────────────────
@Test
void secretsManagerBuildsArnFromSecretId() {
setJsonBody("{\"SecretId\":\"app/prod/database\"}");
assertEquals(List.of("arn:aws:secretsmanager:us-east-1:000000000000:secret:app/prod/database"),
builder.buildSecretsManagerResources("secretsmanager:GetSecretValue", ctx, "us-east-1",
"000000000000", "aws"));
private static final String SECRET = "arn:aws:secretsmanager:us-east-1:000000000000:secret:";
/**
* Secrets Manager as IAM asks it: the ARN of each secret it holds, by name, or by an ARN, a partial one included,
* in whatever Region or account it names.
*/
private static StoredResourceArns secretsHolding(Map<String, String> stored) {
return new StoredResourceArns() {
@Override
public String namespace() {
return "secretsmanager";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return "Secret".equals(type) && names.size() == 1
? Optional.ofNullable(stored.get(names.getFirst())) : Optional.empty();
}
@Override
public Optional<String> resolveStoredArn(String arn) {
return Optional.ofNullable(stored.get(arn));
}
};
}
private List<String> secretsResources(ResourceArnBuilder builder, String operation, String region,
String partition) {
return builder.buildResources("secretsmanager", operation, ctx, region, ACCOUNT, partition);
}
/**
* A secret named by its name or an ARN, a partial one included, is the ARN Secrets Manager holds it under, random
* suffix included; one it does not hold has the six characters botocore documents open ({@code -??????}), and an
* ARN it does not hold is as given.
*/
@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));
void aSecretIsTheArnSecretsManagerHoldsItUnderOrItsNameWithTheSuffixOpen() {
String stored = SECRET + "app/core-AbC123";
ResourceArnBuilder backed = reading(secretsHolding(Map.of("app/core", stored, SECRET + "app/core", stored)));
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());
assertEquals(List.of(stored), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
setJsonBody("{\"SecretId\":\"" + SECRET + "app/core\"}");
assertEquals(List.of(stored), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
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);
assertEquals(List.of(SECRET + "app/missing-??????"),
secretsResources(backed, "secretsmanager:DescribeSecret", "us-east-1", "aws"));
setJsonBody("{\"SecretId\":\"" + SECRET + "app/missing\"}");
assertEquals(List.of(SECRET + "app/missing"),
secretsResources(backed, "secretsmanager:DescribeSecret", "us-east-1", "aws"));
}
/**
* {@code CreateSecret} names the secret it makes by {@code Name}, its suffix not minted yet, and every other
* operation by {@code SecretId}, so a member the serving operation does not read names nothing; an operation
* acting on no resource type is checked on {@code *}.
*/
@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);
void aCreateNamesTheSecretItMakesAndEveryOtherOperationTheOneItsSecretIdNames() {
ResourceArnBuilder backed = reading(secretsHolding(Map.of("app/existing", SECRET + "app/existing-AbC123")));
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"));
assertEquals(List.of(SECRET + "app/new-??????"),
secretsResources(backed, "secretsmanager:CreateSecret", "us-east-1", "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"));
assertEquals(List.of("*"), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
setJsonBody("{}");
assertEquals(List.of("*"), secretsResources(backed, "secretsmanager:ListSecrets", "us-east-1", "aws"));
}
/**
* A secret Secrets Manager holds in another Region than the request's, named by its ARN, partial or full, is the
* one its operations act on there, and so is one another account holds under the full ARN named: that ARN alone,
* no secret of its name in the request's Region or the caller's account.
*/
@Test
void aSecretHeldInAnotherRegionOrAccountIsCheckedOnItsArnAlone() {
String west = "arn:aws:secretsmanager:us-west-2:000000000000:secret:";
String stored = west + "app/core-AbC123";
String shared = "arn:aws:secretsmanager:us-east-1:111122223333:secret:app/shared-XyZ789";
ResourceArnBuilder backed = reading(secretsHolding(Map.of(west + "app/core", stored, stored, stored,
shared, shared)));
setJsonBody("{\"SecretId\":\"" + west + "app/core\"}");
assertEquals(List.of(stored), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
setJsonBody("{\"SecretId\":\"" + stored + "\"}");
assertEquals(List.of(stored), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
setJsonBody("{\"SecretId\":\"" + shared + "\"}");
assertEquals(List.of(shared), secretsResources(backed, "secretsmanager:GetSecretValue", "us-east-1", "aws"));
}
@Test
void secretsManagerMintsArnsInTheRequestPartition() {
void aSecretsArnIsInTheRequestsPartition() {
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"));
secretsResources(reading(secretsHolding(Map.of())), "secretsmanager:CreateSecret",
"polygondwanaland-west-1", "aws-cn"));
}
// ── KMS ──────────────────────────────────────────────────────────────────────
@@ -1404,7 +1408,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<KmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(kms);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, instance);
}
/** A builder reading the stored ARNs of a namespace, for every request of that namespace. */
@@ -1412,7 +1416,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
}
/** The finder of the stored ARNs of a namespace, answering one name of one type with one ARN. */
@@ -101,6 +101,21 @@ class SecretsManagerSecretArnEnforcementIntegrationTest {
.body("__type", equalTo("AccessDeniedException"));
}
@Test
void aSecretOfAnotherRegionNamedByItsArnIsAuthorizedAgainstThatArnAlone() {
String name = "app-" + UUID.randomUUID().toString().substring(0, 8);
String arn = createSecretIn("us-west-2", name);
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s"}]}"""
.formatted(arn));
// Signed for us-east-1, the request reads the us-west-2 secret its ARN names, and is checked on that one.
secretsCall(session, "GetSecretValue", "{\"SecretId\": \"" + arn + "\"}")
.then().statusCode(200)
.body("SecretString", equalTo("x"));
}
@Test
void createSecretIgnoresASecretIdTheHandlerDoesNotRead() {
String existing = "app-" + UUID.randomUUID().toString().substring(0, 8);
@@ -129,6 +144,17 @@ class SecretsManagerSecretArnEnforcementIntegrationTest {
"{\"SecretId\": \"" + name + "\", \"ForceDeleteWithoutRecovery\": true}").then().statusCode(200));
}
/** A secret the account creates in {@code region}, deleted after the test by its ARN; its ARN. */
private String createSecretIn(String region, String name) {
Response response = accountCall(region, "CreateSecret",
"{\"Name\": \"" + name + "\", \"SecretString\": \"x\"}");
response.then().statusCode(200);
String arn = response.path("ARN");
cleanup.register(() -> accountCall(region, "DeleteSecret",
"{\"SecretId\": \"" + arn + "\", \"ForceDeleteWithoutRecovery\": true}").then().statusCode(200));
return arn;
}
/** 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();
@@ -139,7 +165,11 @@ class SecretsManagerSecretArnEnforcementIntegrationTest {
/** 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"))
return accountCall("us-east-1", action, body);
}
private Response accountCall(String region, String action, String body) {
return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, region, "secretsmanager"))
.header("X-Amz-Target", "secretsmanager." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
@@ -0,0 +1,68 @@
package io.floci.aws.services.iam;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.LogsAuthorizationFixtures;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.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.restassured.RestAssured.given;
/**
* In a deployment whose partition is not {@code aws}, a request in a Region Floci does not know is in the deployment's
* partition, and so is the resource it creates, which the tags the request carries are checked on: a grant scoped to
* that partition reaches the tagging of the user pool a {@code CreateUserPool} makes, an action acting on no resource
* type whose tags go on the resource it makes.
*/
@QuarkusTest
@TestProfile(LogsNoncommercialUnknownRegionAuthorizationIntegrationTest.ChinaProfile.class)
class TagOnCreateUnknownRegionPartitionIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final String REGION = "polygondwanaland-west-1";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@TestHTTPResource
URI endpoint;
@BeforeAll
static void configureContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void theTagsACreateCarriesAreCheckedOnWhatItMakesInTheDeploymentsPartition() {
String name = "pool-" + UUID.randomUUID().toString().substring(0, 8);
String caller = LogsAuthorizationFixtures.user(cleanup, endpoint.getPort(), ACCOUNT, "tag-partition-",
"pools", "{\"Effect\":\"Allow\",\"Action\":\"cognito-idp:CreateUserPool\",\"Resource\":\"*\"},"
+ "{\"Effect\":\"Allow\",\"Action\":\"cognito-idp:TagResource\",\"Resource\":\"arn:aws-cn:"
+ "cognito-idp:" + REGION + ":" + ACCOUNT + ":userpool/*\"}");
Response created = cognitoCall(caller, "CreateUserPool",
"{\"PoolName\": \"" + name + "\", \"UserPoolTags\": {\"team\": \"blue\"}}");
created.then().statusCode(200);
String poolId = created.path("UserPool.Id");
cleanup.register(() -> cognitoCall(ACCOUNT, "DeleteUserPool", "{\"UserPoolId\": \"" + poolId + "\"}")
.then().statusCode(200));
}
private Response cognitoCall(String caller, String action, String body) {
return given().port(endpoint.getPort())
.header("Authorization", EnforcementFixtures.auth(caller, REGION, "cognito-idp"))
.header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when().post("/");
}
}
@@ -25,6 +25,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;
@@ -588,6 +589,38 @@ class SecretsManagerServiceTest {
assertFindArnNamesTheSecretTheOperationActsOn(svc, otherAccount.getArn(), REGION);
}
@Test
void anArnResolvesToTheSecretTheOperationsReadItAsTheCallersBeforeTheOneItsAccountHolds() {
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);
String partialArn = "arn:aws:secretsmanager:" + REGION + ":111122223333:secret:app/core";
Secret west = svc.createSecret("app/west", "value", null, null, null, null, "eu-west-1");
assertEquals(Optional.of(otherAccount.getArn()), svc.resolveStoredArn(otherAccount.getArn()));
// The caller's own secret, a partial ARN of it in another Region included.
assertEquals(Optional.of(west.getArn()), svc.resolveStoredArn(west.getArn()));
assertEquals(Optional.of(west.getArn()),
svc.resolveStoredArn("arn:aws:secretsmanager:eu-west-1:000000000000:secret:app/west"));
assertEquals(west.getArn(), svc.describeSecret(
"arn:aws:secretsmanager:eu-west-1:000000000000:secret:app/west", REGION).getArn());
// The operations read a partial ARN, or a suffix that account holds nothing under, in the caller's account.
assertTrue(svc.resolveStoredArn(partialArn).isEmpty());
assertTrue(svc.resolveStoredArn(otherAccount.getArn().replace("AbCdEf", "XyZ789")).isEmpty());
// A name or an ARN of no secret resolves nothing.
assertTrue(svc.resolveStoredArn("app/west").isEmpty());
assertTrue(svc.resolveStoredArn("arn:aws:s3:::app/west").isEmpty());
// A secret of the caller's own named like the ARN's resource is the one the operations read the ARN as.
Secret callers = svc.createSecret("app/core-AbCdEf", "value", null, null, null, null, REGION);
assertEquals(Optional.of(callers.getArn()), svc.resolveStoredArn(otherAccount.getArn()));
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.