mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+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