mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ses): authorize SES v2 calls against their IAM actions under enforcement (#4775)
SES v1 is a Query API, so IAM enforcement resolves its action from the request's Action like any other. SES v2 is REST-JSON under /v2/email and IamActionRegistry had no rules for it, so every v2 call resolved to no action, which the enforcement filter lets through: with enforcement on, the whole v2 API was unguarded, CreateConfigurationSetEventDestination included. IamActionRegistry now has one rule per operation in the SES v2 model (botocore sesv2/2019-09-27, 112 operations), each mapped to the IAM action AWS's service reference lists for it (servicereference.us-east-1.amazonaws.com/v1/ses/ses.json). That is always ses:<Operation>, in the ses namespace v1 and v2 share. SendEmail has no entry there; the Service Authorization Reference's SES v2 page defines ses:SendEmail as v2's only send action whatever the content (ses:SendRawEmail is a v1 action), so it takes its name too. No two rules can match the same path, so their order does not matter. The 20 operations Floci does not serve yet are mapped too, so a route added later is guarded from the start. Two ways round a rule are closed for every REST service, not only SES v2. IamActionRegistry.resolve read X-Amz-Target before the path rules, so a REST request carrying one was checked as whatever operation the header named: a POST /v2/email/outbound-emails with X-Amz-Target: SES.GetAccount went through for a caller denied ses:SendEmail. REST-claimed requests now resolve through a new resolveRoute, from method and path alone. And the rules matched the decoded path while the router matches the encoded one, so a%2Fb@example.com reached the suppressed-destination endpoint while its decoded path matched no rule and passed as an unknown action. resolveRoute matches the path still percent-encoded, read from the request URI since RESTEasy Reactive does not serve UriInfo.getPath(false). A denied call answers AccessDeniedException with HTTP 403, as the SES v2 API Reference lists among its common errors. Like v1, v2 is evaluated with resource "*"; resource ARNs for SES, and the extra actions the service reference lists for some operations (ses:TagResource on the create operations, iam:PassRole for event destinations), are left for later and documented in docs/services/ses.md. IamActionRegistryTest checks every operation against a table generated from the model and the service reference, not from the rule table. SesV2IamEnforcementIntegrationTest shows a caller without SES permissions refused, a single allowed action granting only that operation, a target header not changing the checked action, and an encoded slash still authorized.
This commit is contained in:
1 parent
be87f99220
commit
275d874fed
9 files changed
+498
-15
No files matched your search
@@ -8,6 +8,7 @@ import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -103,6 +104,8 @@ class CredentialScopeAliasTest {
|
||||
private static ContainerRequestContext getObjectRequest() {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getPath()).thenReturn("/my-bucket/my-key");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566/my-bucket/my-key"));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
|
||||
@@ -218,7 +218,9 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getMediaType()).thenReturn(MediaType.valueOf(contentType));
|
||||
stubClaim(containerRequest, protocol, dynamoDbDescriptor());
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
// A REST-claimed request resolves from its route, the others from the registry's full rules.
|
||||
lenient().when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
lenient().when(actionRegistry.resolveRoute("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("dynamodb:PutItem"), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
@@ -288,7 +290,9 @@ class IamEnforcementFilterTest {
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve(eq("s3"), eq(containerRequest));
|
||||
verify(actionRegistry).resolveRoute(eq("s3"), eq(containerRequest));
|
||||
// Nor does the header name the action: a REST request never reaches the header-reading rules.
|
||||
verify(actionRegistry, never()).resolve(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -305,14 +309,14 @@ class IamEnforcementFilterTest {
|
||||
when(catalog.byResourceClass(ApiGatewayController.class))
|
||||
.thenReturn(Optional.of(descriptor("apigateway", ServiceProtocol.REST_JSON,
|
||||
Set.of("apigateway", "execute-api"), ApiGatewayController.class)));
|
||||
when(actionRegistry.resolve("apigateway", containerRequest)).thenReturn("apigateway:POST");
|
||||
when(actionRegistry.resolveRoute("apigateway", containerRequest)).thenReturn("apigateway:POST");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(ApiGatewayController.class));
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve("apigateway", containerRequest);
|
||||
verify(actionRegistry, never()).resolve("iam", containerRequest);
|
||||
verify(actionRegistry).resolveRoute("apigateway", containerRequest);
|
||||
verify(actionRegistry, never()).resolveRoute("iam", containerRequest);
|
||||
verify(arnBuilder).buildResources("apigateway", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(conditionContextResolver).resolve("apigateway", "apigateway:POST", containerRequest);
|
||||
@@ -332,14 +336,14 @@ class IamEnforcementFilterTest {
|
||||
.thenReturn(Optional.of(descriptor("s3", ServiceProtocol.REST_XML,
|
||||
Set.of("s3", "s3express"), S3Controller.class)));
|
||||
when(catalog.canonicalCredentialScope("s3express")).thenReturn("s3");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:CreateBucket");
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:CreateBucket");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(S3Controller.class));
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve("s3", containerRequest);
|
||||
verify(actionRegistry, never()).resolve("apigateway", containerRequest);
|
||||
verify(actionRegistry).resolveRoute("s3", containerRequest);
|
||||
verify(actionRegistry, never()).resolveRoute("apigateway", containerRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -6,10 +6,13 @@ import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvFileSource;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@@ -167,6 +170,56 @@ class IamActionRegistryTest {
|
||||
mockCtx("POST", "/RollbackTransaction", new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The table is generated from the SES v2 model and AWS's service reference, not from the rule
|
||||
* table, so it checks the rules rather than restating them: each operation's path has to
|
||||
* resolve to the action AWS lists for it, and to no other operation's.
|
||||
*/
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@CsvFileSource(resources = "/iam/sesv2-operation-actions.csv")
|
||||
void resolvesEverySesV2OperationToItsAction(String operation, String method, String path, String action) {
|
||||
assertEquals(action, registry.resolve("ses",
|
||||
mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sesV2RulesMatchTheWholePath() {
|
||||
// A rule for /v2/email/configuration-sets must not also claim a path below it.
|
||||
assertEquals("ses:ListConfigurationSets", registry.resolve("ses",
|
||||
mockCtx("GET", "/v2/email/configuration-sets", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
assertEquals("ses:GetConfigurationSetEventDestinations", registry.resolve("ses",
|
||||
mockCtx("GET", "/v2/email/configuration-sets/my-set/event-destinations/", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
assertNull(registry.resolve("ses",
|
||||
mockCtx("GET", "/v2/email/configuration-sets/my-set/unknown", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestRouteIsNotRenamedByATargetHeader() {
|
||||
// The route decides a REST request's action; a caller-supplied target must not name another.
|
||||
ContainerRequestContext send = mockCtx("POST", "/v2/email/outbound-emails", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}");
|
||||
when(send.getHeaderString("X-Amz-Target")).thenReturn("SES.GetAccount");
|
||||
assertEquals("ses:SendEmail", registry.resolveRoute("ses", send));
|
||||
|
||||
ContainerRequestContext invoke = mockCtx("POST", "/2015-03-31/functions/f/invocations",
|
||||
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
|
||||
when(invoke.getHeaderString("X-Amz-Target")).thenReturn("AWSLambda.GetFunction");
|
||||
assertEquals("lambda:InvokeFunction", registry.resolveRoute("lambda", invoke));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEncodedSlashStaysInsideItsPathParameter() {
|
||||
assertEquals("ses:GetSuppressedDestination", registry.resolveRoute("ses",
|
||||
mockCtx("GET", "/v2/email/suppression/addresses/a%2Fb@example.com", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
assertEquals("ses:DeleteSuppressedDestination", registry.resolveRoute("ses",
|
||||
mockCtx("DELETE", "/v2/email/suppression/addresses/a%2Fb@example.com", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullForUnknownRestJsonRoute() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
@@ -440,6 +493,8 @@ class IamActionRegistryTest {
|
||||
UriInfo uriInfo = Mockito.mock(UriInfo.class);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(ctx.getUriInfo()).thenReturn(uriInfo);
|
||||
when(ctx.getMediaType()).thenReturn(mediaType);
|
||||
when(ctx.getMethod()).thenReturn(method);
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* With {@code iam.enforcement-enabled=true}, SES v2 calls are authorized against their {@code ses:}
|
||||
* action like any other request, instead of resolving to no action and passing unchecked.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class SesV2IamEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
|
||||
@Test
|
||||
void callerWithoutSesPermissionsIsRefusedEveryV2Operation() {
|
||||
String configurationSet = createConfigurationSet();
|
||||
String accessKeyId = userWithPolicy(null);
|
||||
|
||||
assertAccessDenied(getAccount(accessKeyId));
|
||||
assertAccessDenied(createEventDestination(accessKeyId, configurationSet));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowedActionGrantsThatOperationOnly() {
|
||||
String configurationSet = createConfigurationSet();
|
||||
String accessKeyId = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ses:GetAccount","Resource":"*"}]}""");
|
||||
|
||||
getAccount(accessKeyId).then().statusCode(200);
|
||||
assertAccessDenied(createEventDestination(accessKeyId, configurationSet));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEventDestinationActionAllowsCreatingOne() {
|
||||
String configurationSet = createConfigurationSet();
|
||||
String accessKeyId = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"ses:CreateConfigurationSetEventDestination","Resource":"*"}]}""");
|
||||
|
||||
createEventDestination(accessKeyId, configurationSet).then().statusCode(200);
|
||||
assertAccessDenied(getAccount(accessKeyId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetHeaderDoesNotChangeTheActionARestCallIsCheckedAs() {
|
||||
String accessKeyId = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"ses:SendEmail","Resource":"*"}]}""");
|
||||
|
||||
assertAccessDenied(given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth(accessKeyId, "ses"))
|
||||
.header("X-Amz-Target", "SES.GetAccount")
|
||||
.body("""
|
||||
{"FromEmailAddress":"sender@example.com","Destination":{"ToAddresses":["to@example.com"]},
|
||||
"Content":{"Simple":{"Subject":{"Data":"s"},"Body":{"Text":{"Data":"b"}}}}}""")
|
||||
.when().post("/v2/email/outbound-emails"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEncodedSlashInAPathParameterIsStillAuthorized() {
|
||||
String accessKeyId = userWithPolicy(null);
|
||||
|
||||
assertAccessDenied(given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Authorization", auth(accessKeyId, "ses"))
|
||||
.when().get("/v2/email/suppression/addresses/a%2Fb@example.com"));
|
||||
assertAccessDenied(given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Authorization", auth(accessKeyId, "ses"))
|
||||
.when().delete("/v2/email/suppression/addresses/a%2Fb@example.com"));
|
||||
}
|
||||
|
||||
/** SES v2 API Reference, common errors: {@code AccessDeniedException}, HTTP 403. */
|
||||
private static void assertAccessDenied(Response response) {
|
||||
response.then().statusCode(403).body("__type", equalTo("AccessDeniedException"));
|
||||
}
|
||||
|
||||
private static Response getAccount(String accessKeyId) {
|
||||
return given()
|
||||
.header("Authorization", auth(accessKeyId, "ses"))
|
||||
.when().get("/v2/email/account");
|
||||
}
|
||||
|
||||
private static Response createEventDestination(String accessKeyId, String configurationSet) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth(accessKeyId, "ses"))
|
||||
.body("""
|
||||
{"EventDestinationName":"dest","EventDestination":{"Enabled":true,
|
||||
"MatchingEventTypes":["SEND"],
|
||||
"CloudWatchDestination":{"DimensionConfigurations":[{"DimensionName":"d",
|
||||
"DimensionValueSource":"MESSAGE_TAG","DefaultDimensionValue":"v"}]}}}""")
|
||||
.when().post("/v2/email/configuration-sets/" + configurationSet + "/event-destinations");
|
||||
}
|
||||
|
||||
private static String createConfigurationSet() {
|
||||
String name = "sesv2-iam-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth(ACCOUNT, "ses"))
|
||||
.body("{\"ConfigurationSetName\":\"" + name + "\"}")
|
||||
.when().post("/v2/email/configuration-sets")
|
||||
.then().statusCode(200);
|
||||
return name;
|
||||
}
|
||||
|
||||
/** An IAM user in {@link #ACCOUNT} with {@code policy} inline, or no policy when it is null. */
|
||||
private static String userWithPolicy(String policy) {
|
||||
String user = "sesv2-iam-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given().formParam("Action", "CreateUser").formParam("UserName", user)
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
if (policy != null) {
|
||||
given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
|
||||
.formParam("PolicyDocument", policy)
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200);
|
||||
}
|
||||
return given().formParam("Action", "CreateAccessKey").formParam("UserName", user)
|
||||
.header("Authorization", auth(ACCOUNT, "iam")).when().post("/").then().statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260930/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user