diff --git a/docs/services/iam.md b/docs/services/iam.md index 5685177c2e..da14291939 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1246,16 +1246,28 @@ a Query `Action` field on it does not change the action it is checked as, and it still percent-encoded, as the router matches it, so an encoded `/` inside a parameter cannot make the route's rule miss. -The REST routes mapped to an action are those of S3, Lambda, API Gateway, SES v2, RDS Data and -Kinesis. In Lambda they are the function, alias, event source mapping, function URL, durable -execution and Web Function routes, `InvokeWithResponseStream` (checked as `lambda:InvokeFunction`) -and `GetLayerVersionByArn` (`lambda:GetLayerVersion`); the other Lambda routes, such as layers, -versions, concurrency and MicroVMs, are not mapped yet. API Gateway's management API, v1 and v2, is -checked as `apigateway:` and the HTTP method, `apigateway:GET`, `apigateway:POST` and so on, except +The REST routes mapped to an action are those of S3, Lambda, API Gateway, SES v2, RDS Data, +Kinesis, EventBridge Scheduler and EventBridge Pipes. In Lambda they are the function, alias, +event source mapping, function URL, durable execution and Web Function routes, +`InvokeWithResponseStream` (checked as `lambda:InvokeFunction`) and `GetLayerVersionByArn` +(`lambda:GetLayerVersion`); the other Lambda routes, such as layers, versions, concurrency and +MicroVMs, are not mapped yet. API Gateway's management API, v1 and v2, is checked as `apigateway:` +and the HTTP method, `apigateway:GET`, `apigateway:POST` and so on, except `RejectDomainNameAccessAssociation` (`apigateway:RejectAccessAssociation`) and `PutRoutingRule` (`apigateway:UpdateRoutingRule`); the v2 routing rule, portal and portal product operations, which -AWS checks as actions of their own names, are not served. A route no rule maps is not checked, as -an unsigned REST request is not; the other REST services' routes are not mapped yet. +AWS checks as actions of their own names, are not served. + +A Scheduler request is checked against `schedule//`, the group from the body's +`GroupName` on a create or an update, from `groupName` otherwise, and `default` when neither names +one, or `schedule-group/`. A Pipes request is checked against `pipe/`. + +The shared tagging routes, `/tags` and `/v1/tags`, hand a request to the service its ARN names, +and it is checked as that service, against that ARN, whatever scope it is signed with. The ARN is +the one after `/tags/` or `/v1/tags/`, the body's `resourceArn` on `POST /tags`, and the +`resourceArn` query parameter on the other bare routes. + +A route no rule maps is not checked, as an unsigned REST request is not; the other REST services' +routes are not mapped yet. An S3 `CreateBucket` is checked as `s3:CreateBucket`, and also needs one action for each header that configures the new bucket, as the CreateBucket API reference lists them: @@ -1355,7 +1367,9 @@ role each passes: - **Step Functions:** `CreateStateMachine` and `UpdateStateMachine` pass `roleArn` to `states.amazonaws.com`, in a JSON or a CBOR body. - **EventBridge:** `PutRule` passes `RoleArn`, and `PutTargets` each target's `RoleArn`, to - `events.amazonaws.com`. + `events.amazonaws.com`. **EventBridge Scheduler:** `CreateSchedule` and `UpdateSchedule` pass the + target's `RoleArn` to `scheduler.amazonaws.com`. **EventBridge Pipes:** `CreatePipe` and + `UpdatePipe` pass `RoleArn` to `pipes.amazonaws.com`. - **CloudFormation:** `CreateStack`, `UpdateStack`, `DeleteStack`, `CreateChangeSet` and `ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request names one. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managed diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 476d4b6044..1531304c65 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -786,11 +786,37 @@ public class IamEnforcementFilter implements ContainerRequestFilter { || resourceInfo == null || resourceInfo.getResourceClass() == null) { return null; } - return catalog.byResourceClass(resourceInfo.getResourceClass()) + Class resourceClass = resourceInfo.getResourceClass(); + if (SharedTagsController.class.equals(resourceClass) || V1TagsController.class.equals(resourceClass)) { + return taggedServiceAuthorization(ctx); + } + return catalog.byResourceClass(resourceClass) .map(descriptor -> resolveRestAuthorization(descriptor, ctx)) .orElse(null); } + /** + * A shared tagging route hands the request to the service its ARN names, so it is checked as that + * service whatever scope it is signed with. A service with no rule for the route leaves it unchecked, as + * any route no rule maps; an ARN naming no service Floci serves, which the controller refuses, is left + * to the signing scope. + */ + private ResolvedAuthorization taggedServiceAuthorization(ContainerRequestContext ctx) { + String arn = arnBuilder.taggedArn(ctx); + if (!AwsArnUtils.isArn(arn)) { + return null; + } + String service = AwsArnUtils.parse(arn).service(); + return catalog.byCredentialScope(service) + .map(descriptor -> { + ResolvedAuthorization authorization = resolveRestAuthorization(descriptor, ctx); + return authorization != null + ? authorization + : new ResolvedAuthorization(catalog.canonicalCredentialScope(service), null); + }) + .orElse(null); + } + /** * Refuses a request whose {@code Authorization} header this filter cannot read a credential * from: an empty one, one naming no access key (a Bearer token, SigV2, a credential without the @@ -1452,7 +1478,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter { }; } - /** Logs and Secrets Manager targets depend on the serving operation and the request's partition. */ + /** + * Logs and Secrets Manager targets depend on the serving operation and the request's partition; + * Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in. + */ private List targetResources(String credentialScope, String action, ContainerRequestContext ctx, String region, String accountId) { if ("logs".equals(credentialScope)) { @@ -1461,6 +1490,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if ("secretsmanager".equals(credentialScope)) { return arnBuilder.buildSecretsManagerResources(action, ctx, region, accountId, requestPartition()); } + if ("scheduler".equals(credentialScope) || "pipes".equals(credentialScope)) { + return arnBuilder.buildResources(credentialScope, ctx, region, accountId, requestPartition()); + } return arnBuilder.buildResources(credentialScope, ctx, region, accountId); } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java index ef0dc5ddd3..53c8e1b79c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java @@ -60,6 +60,8 @@ final class PassedRoles { private static final String ECS_TASKS = ServicePrincipals.of("ecs-tasks"); private static final String STATES = ServicePrincipals.of("states"); private static final String EVENTS = ServicePrincipals.of("events"); + private static final String SCHEDULER = ServicePrincipals.of("scheduler"); + private static final String PIPES = ServicePrincipals.of("pipes"); private static final String CLOUDFORMATION = ServicePrincipals.of("cloudformation"); private static final String STACK_SET_ADMINISTRATION_ROLE = "AWSCloudFormationStackSetAdministrationRole"; @@ -111,6 +113,8 @@ final class PassedRoles { case "states:CreateStateMachine", "states:UpdateStateMachine" -> fromJson(ctx, STATES, "roleArn"); case "events:PutRule" -> fromJson(ctx, EVENTS, "RoleArn"); case "events:PutTargets" -> fromJson(ctx, EVENTS, "Targets", "[]", "RoleArn"); + case "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> fromJson(ctx, SCHEDULER, "Target", "RoleArn"); + case "pipes:CreatePipe", "pipes:UpdatePipe" -> fromJson(ctx, PIPES, "RoleArn"); case "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack", "cloudformation:CreateChangeSet", "cloudformation:ContinueUpdateRollback" -> fromForm(ctx, CLOUDFORMATION, "RoleARN"); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 8d537ccb58..2179172feb 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -66,6 +66,7 @@ import io.github.hectorvent.floci.services.s3.S3Controller; import io.github.hectorvent.floci.services.s3tables.S3TablesController; import io.github.hectorvent.floci.services.s3vectors.S3VectorsController; import io.github.hectorvent.floci.services.sagemaker.SageMakerRuntimeController; +import io.github.hectorvent.floci.services.scheduler.SchedulerController; import io.github.hectorvent.floci.services.securityhub.SecurityHubController; import io.github.hectorvent.floci.services.ses.SesAccountController; import io.github.hectorvent.floci.services.ses.SesConfigurationSetController; @@ -256,7 +257,7 @@ public class ResolvedServiceCatalog { descriptor("scheduler", "scheduler", config.services().scheduler().enabled(), true, "scheduler", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), - Set.of(), Set.of("scheduler"), Set.of(), Set.of()), + Set.of(), Set.of("scheduler"), Set.of(), Set.of(SchedulerController.class)), descriptor("logs", "cloudwatchlogs", config.services().cloudwatchlogs().enabled(), true, "cloudwatchlogs", storageMode(config.storage().services().cloudwatchlogs().mode(), config.storage().mode()), config.storage().services().cloudwatchlogs().flushIntervalMs(), null, ServiceProtocol.JSON, diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java index c539e95d7c..2ad7f0c24a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java @@ -141,6 +141,33 @@ public class IamActionRegistry { rule("apigateway", "PATCH", ".*", "apigateway:PATCH"), rule("apigateway", "DELETE", ".*", "apigateway:DELETE"), + // ── EventBridge Scheduler ────────────────────────────────────────────── + rule("scheduler", "GET", "^/schedules/[^/]+$", "scheduler:GetSchedule"), + rule("scheduler", "POST", "^/schedules/[^/]+$", "scheduler:CreateSchedule"), + rule("scheduler", "PUT", "^/schedules/[^/]+$", "scheduler:UpdateSchedule"), + rule("scheduler", "DELETE", "^/schedules/[^/]+$", "scheduler:DeleteSchedule"), + rule("scheduler", "GET", "^/schedules$", "scheduler:ListSchedules"), + rule("scheduler", "GET", "^/schedule-groups/[^/]+$", "scheduler:GetScheduleGroup"), + rule("scheduler", "POST", "^/schedule-groups/[^/]+$", "scheduler:CreateScheduleGroup"), + rule("scheduler", "DELETE", "^/schedule-groups/[^/]+$", "scheduler:DeleteScheduleGroup"), + rule("scheduler", "GET", "^/schedule-groups$", "scheduler:ListScheduleGroups"), + // Tagging is served at /tags/ and at /tags, naming the ARN in the query or the body. + rule("scheduler", "GET", "^/tags(/.+)?$", "scheduler:ListTagsForResource"), + rule("scheduler", "POST", "^/tags(/.+)?$", "scheduler:TagResource"), + rule("scheduler", "DELETE", "^/tags(/.+)?$", "scheduler:UntagResource"), + + // ── EventBridge Pipes ────────────────────────────────────────────────── + rule("pipes", "POST", "^/v1/pipes/[^/]+/start$", "pipes:StartPipe"), + rule("pipes", "POST", "^/v1/pipes/[^/]+/stop$", "pipes:StopPipe"), + rule("pipes", "GET", "^/v1/pipes/[^/]+$", "pipes:DescribePipe"), + rule("pipes", "POST", "^/v1/pipes/[^/]+$", "pipes:CreatePipe"), + rule("pipes", "PUT", "^/v1/pipes/[^/]+$", "pipes:UpdatePipe"), + rule("pipes", "DELETE", "^/v1/pipes/[^/]+$", "pipes:DeletePipe"), + rule("pipes", "GET", "^/v1/pipes$", "pipes:ListPipes"), + rule("pipes", "GET", "^/tags(/.+)?$", "pipes:ListTagsForResource"), + rule("pipes", "POST", "^/tags(/.+)?$", "pipes:TagResource"), + rule("pipes", "DELETE", "^/tags(/.+)?$", "pipes:UntagResource"), + // ── SES v2 ───────────────────────────────────────────────────────────── // SES v1 is a Query API and resolves from its Action like any other; v2 is REST-JSON under // /v2/email, so every operation needs its own rule. One rule per operation in the SES v2 diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index d9764c386e..b8aeb09a84 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -94,6 +94,16 @@ public class ResourceArnBuilder { public List buildResources(String credentialScope, ContainerRequestContext ctx, String region, String accountId) { + return buildResources(credentialScope, ctx, region, accountId, AwsRegions.partitionFor(region)); + } + + /** + * The resources a request is checked against. Scheduler and Pipes ARNs are minted in {@code partition}, + * the request's, as those services mint theirs, so a Region no partition publishes gets the deployment's + * partition rather than {@code aws}. + */ + public List buildResources(String credentialScope, ContainerRequestContext ctx, + String region, String accountId, String partition) { if (credentialScope == null) { return List.of("*"); } @@ -109,6 +119,8 @@ public class ResourceArnBuilder { case "kms" -> List.of(buildKmsArn(path, region, accountId)); case "iam" -> buildIamArns(ctx, region, accountId); case "resource-groups" -> List.of(buildResourceGroupArn(ctx, region, accountId)); + case "scheduler" -> List.of(buildSchedulerArn(path, ctx, region, accountId, partition)); + case "pipes" -> List.of(buildPipesArn(path, ctx, region, accountId, partition)); default -> List.of("*"); }; } @@ -703,6 +715,87 @@ public class ResourceArnBuilder { } } + /** + * The resource of an EventBridge Scheduler route: {@code schedule//}, the group read where + * Scheduler reads it, the body's {@code GroupName} on a create or an update and {@code groupName} + * otherwise, and {@code default} when the request names none; {@code schedule-group/}; or the + * ARN a tagging route names. The list routes name no resource. + */ + private String buildSchedulerArn(String path, ContainerRequestContext ctx, String region, String accountId, + String partition) { + String schedule = segmentAfterPrefix(path, "/schedules/"); + if (schedule != null) { + String group; + if ("POST".equalsIgnoreCase(ctx.getMethod()) || "PUT".equalsIgnoreCase(ctx.getMethod())) { + JsonNode body = readJsonBody(ctx); + group = body == null ? null : body.path("GroupName").asText(null); + } else { + group = ctx.getUriInfo().getQueryParameters().getFirst("groupName"); + } + if (group == null || group.isBlank()) { + group = "default"; + } + return new AwsArnUtils.Arn(partition, "scheduler", region, accountId, + "schedule/" + group + "/" + schedule).toString(); + } + String scheduleGroup = segmentAfterPrefix(path, "/schedule-groups/"); + if (scheduleGroup != null) { + return new AwsArnUtils.Arn(partition, "scheduler", region, accountId, + "schedule-group/" + scheduleGroup).toString(); + } + return taggedResource(ctx); + } + + /** The resource of an EventBridge Pipes route: {@code pipe/}, or the ARN a tagging route names. */ + private String buildPipesArn(String path, ContainerRequestContext ctx, String region, String accountId, + String partition) { + String pipe = segmentAfterPrefix(path, "/v1/pipes/"); + if (pipe != null) { + return new AwsArnUtils.Arn(partition, "pipes", region, accountId, "pipe/" + pipe).toString(); + } + return taggedResource(ctx); + } + + /** The ARN a shared tagging route names, or {@code *} for any other route. */ + private String taggedResource(ContainerRequestContext ctx) { + String arn = taggedArn(ctx); + return arn != null && arn.startsWith("arn:") ? arn : "*"; + } + + /** + * The ARN a shared tagging route acts on, read where its controller reads it: after {@code /tags/} or + * {@code /v1/tags/} in the path; on {@code POST /tags}, the body's {@code resourceArn}; and on the other + * bare routes, the {@code resourceArn} query parameter. Null for any other route, or when the request + * names none. + */ + public String taggedArn(ContainerRequestContext ctx) { + String path = ctx.getUriInfo().getPath(); + for (String route : List.of("/tags", "/v1/tags")) { + if (path.startsWith(route + "/")) { + return path.substring(route.length() + 1); + } + } + if ("/tags".equals(path) && "POST".equalsIgnoreCase(ctx.getMethod())) { + JsonNode body = readJsonBody(ctx); + return body == null ? null : body.path("resourceArn").asText(null); + } + if ("/tags".equals(path) || "/v1/tags".equals(path)) { + return ctx.getUriInfo().getQueryParameters().getFirst("resourceArn"); + } + return null; + } + + /** The path segment right after {@code prefix}, or null when the path doesn't start with it or names none. */ + private static String segmentAfterPrefix(String path, String prefix) { + if (!path.startsWith(prefix)) { + return null; + } + String rest = path.substring(prefix.length()); + int slash = rest.indexOf('/'); + String segment = slash < 0 ? rest : rest.substring(0, slash); + return segment.isEmpty() ? null : segment; + } + /** * The resource of a Lambda Web Functions route. An action on a revision or an endpoint is evaluated * against that child's ARN; an action on the function, a create of a revision or endpoint, the list of diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index 46420cbcd5..44ca35d68c 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.s3.S3Controller; +import io.github.hectorvent.floci.services.scheduler.SchedulerController; import io.quarkus.vertx.http.runtime.CurrentVertxRequest; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.web.RoutingContext; @@ -338,6 +339,31 @@ class IamEnforcementFilterTest { verify(conditionContextResolver).resolve("apigateway", "apigateway:POST", containerRequest); } + @Test + void schedulerResourcesAreBuiltInTheRequestsPartition() { + // A Region no partition publishes takes the deployment's partition, which Scheduler mints its ARNs in. + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260924/xx-local-1/scheduler/aws4_request, " + + "SignedHeaders=host, Signature=abc"; + requestContext.setAccountId("000000000000"); + requestContext.setRegion("xx-local-1"); + requestContext.setPartition("aws-cn"); + when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER"); + when(containerRequest.getHeaderString("Authorization")).thenReturn(auth); + when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)) + .thenReturn(ProtocolClaim.rest()); + when(catalog.byResourceClass(SchedulerController.class)) + .thenReturn(Optional.of(descriptor("scheduler", ServiceProtocol.JSON, + Set.of("scheduler"), SchedulerController.class))); + when(actionRegistry.resolveRoute("scheduler", containerRequest)).thenReturn("scheduler:GetSchedule"); + when(arnBuilder.buildResources(any(), any(), any(), any(), any())).thenReturn(List.of("*")); + when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of())); + + newFilter(resourceInfo(SchedulerController.class)).filter(containerRequest); + + verify(arnBuilder).buildResources("scheduler", containerRequest, "xx-local-1", "000000000000", "aws-cn"); + } + @Test void s3RouteDoesNotUseApiGatewayRules() { ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java index 1f3ffce0e1..418964a03f 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java @@ -136,6 +136,18 @@ class PassedRolesTest { + "{\"RoleArn\":\"" + ROLES + "two\"}]}"), LOOKUPS)); } + @Test + void schedulerAndPipesPassTheRoleTheyName() { + String target = "{\"Target\":{\"RoleArn\":\"" + ROLES + "schedule\"}}"; + assertEquals(List.of(passed("schedule", "scheduler.amazonaws.com")), + PassedRoles.of("scheduler:CreateSchedule", json(target), LOOKUPS)); + assertEquals(List.of(passed("schedule", "scheduler.amazonaws.com")), + PassedRoles.of("scheduler:UpdateSchedule", json(target), LOOKUPS)); + String pipe = "{\"RoleArn\":\"" + ROLES + "pipe\"}"; + assertEquals(List.of(passed("pipe", "pipes.amazonaws.com")), PassedRoles.of("pipes:CreatePipe", json(pipe), LOOKUPS)); + assertEquals(List.of(passed("pipe", "pipes.amazonaws.com")), PassedRoles.of("pipes:UpdatePipe", json(pipe), LOOKUPS)); + } + @Test void outsideEcsOnlyARoleArnIsPassed() { assertEquals(List.of(), PassedRoles.of("states:CreateStateMachine", json("{\"roleArn\":\"sm\"}"), LOOKUPS)); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java index 30d8699619..91fff7f57a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionRegistryTest.java @@ -268,6 +268,21 @@ class IamActionRegistryTest { assertNull(lambdaAction("GET", "/2018-10-31/layers")); } + @Test + void schedulerAndPipesTaggingIsCheckedOnBothTagRoutes() { + for (String scope : List.of("scheduler", "pipes")) { + for (String path : List.of("/tags/arn:aws:" + scope + ":us-east-1:000000000000:x", "/tags")) { + String prefix = scope + ":"; + assertEquals(prefix + "ListTagsForResource", registry.resolveRoute(scope, + mockCtx("GET", path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")), path); + assertEquals(prefix + "TagResource", registry.resolveRoute(scope, + mockCtx("POST", path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")), path); + assertEquals(prefix + "UntagResource", registry.resolveRoute(scope, + mockCtx("DELETE", path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")), path); + } + } + } + @Test void durableExecutionRoutesResolveToTheirActions() { String arn = "arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Afunction%3Af%3A%24LATEST" diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java index 8061114846..3e62e2251f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -47,6 +47,8 @@ class IamPassRoleEnforcementIntegrationTest { private static final String ECS_TASKS = "ecs-tasks.amazonaws.com"; private static final String ECS = "ecs.amazonaws.com"; private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":passrole-queue"; + private static final String SCHEDULER = "scheduler.amazonaws.com"; + private static final String PIPES = "pipes.amazonaws.com"; private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); @TestHTTPResource("/") @@ -392,6 +394,56 @@ class IamPassRoleEnforcementIntegrationTest { user.json("events", "AWSEvents.PutTargets").body(putTargets).post("/").then().statusCode(200); } + @Test + void aScheduleNeedsTheSchedulerActionOnItsArnAndPassRoleOnItsTargetsRole() { + String role = role("scheduler"); + String other = role("scheduler-other"); + User user = user("passrole-scheduler"); + String name = "passrole-schedule-" + suffix(); + String path = "/schedules/" + name; + String arn = "arn:aws:scheduler:us-east-1:" + ACCOUNT + ":schedule/default/" + name; + + // The route is checked as scheduler:CreateSchedule, on the schedule's ARN. + user.policy(allow("scheduler:CreateSchedule", arn + "-other") + "," + passRole(role, SCHEDULER)); + refused(user.rest("scheduler").body(schedule(role)).post(path).then(), "scheduler:CreateSchedule"); + user.policy(allow("scheduler:CreateSchedule", arn)); + denied(user.rest("scheduler").body(schedule(role)).post(path).then()); + user.policy(allow("scheduler:CreateSchedule", arn) + "," + passRole(role, SCHEDULER)); + user.rest("scheduler").body(schedule(role)).post(path).then().statusCode(200); + cleanup.register(() -> admin("scheduler").delete(path)); + + user.policy(allow("scheduler:UpdateSchedule", arn) + "," + passRole(role, SCHEDULER)); + denied(user.rest("scheduler").body(schedule(other)).put(path).then()); + user.policy(allow("scheduler:UpdateSchedule", arn) + "," + passRole(other, SCHEDULER)); + user.rest("scheduler").body(schedule(other)).put(path).then().statusCode(200); + } + + @Test + void aPipeNeedsThePipesActionOnItsArnAndPassRoleOnItsRole() { + String role = role("pipes"); + String other = role("pipes-other"); + User user = user("passrole-pipes"); + String name = "passrole-pipe-" + suffix(); + String path = "/v1/pipes/" + name; + String arn = "arn:aws:pipes:us-east-1:" + ACCOUNT + ":pipe/" + name; + String create = "{\"Source\":\"" + QUEUE_ARN + "\",\"Target\":\"" + QUEUE_ARN + "\",\"RoleArn\":\"" + role + + "\",\"DesiredState\":\"STOPPED\"}"; + + user.policy(allow("pipes:CreatePipe", arn + "-other") + "," + passRole(role, PIPES)); + refused(user.rest("pipes").body(create).post(path).then(), "pipes:CreatePipe"); + user.policy(allow("pipes:CreatePipe", arn)); + denied(user.rest("pipes").body(create).post(path).then()); + user.policy(allow("pipes:CreatePipe", arn) + "," + passRole(role, PIPES)); + user.rest("pipes").body(create).post(path).then().statusCode(200); + cleanup.register(() -> admin("pipes").delete(path)); + + String update = "{\"RoleArn\":\"" + other + "\",\"DesiredState\":\"STOPPED\"}"; + user.policy(allow("pipes:UpdatePipe", arn) + "," + passRole(role, PIPES)); + denied(user.rest("pipes").body(update).put(path).then()); + user.policy(allow("pipes:UpdatePipe", arn) + "," + passRole(other, PIPES)); + user.rest("pipes").body(update).put(path).then().statusCode(200); + } + @Test void aStackNeedsPassRoleOnAServiceRoleTheRequestNames() { String role = role("cloudformation"); @@ -553,6 +605,17 @@ class IamPassRoleEnforcementIntegrationTest { return compressed.toByteArray(); } + /** A REST request refused for the operation's own action, which the message names. */ + private static void refused(ValidatableResponse response, String action) { + response.statusCode(403).body(containsString(action)).body(not(containsString("iam:PassRole"))); + } + + private static String schedule(String role) { + return """ + {"ScheduleExpression":"rate(1 hour)","FlexibleTimeWindow":{"Mode":"OFF"}, + "Target":{"Arn":"%s","RoleArn":"%s"}}""".formatted(QUEUE_ARN, role); + } + private static void denied(ValidatableResponse response) { response.statusCode(403).body(containsString("iam:PassRole")); } @@ -628,6 +691,10 @@ class IamPassRoleEnforcementIntegrationTest { return json("ecs", "AmazonEC2ContainerServiceV20141113." + action); } + RequestSpecification rest(String service) { + return given().header("Authorization", auth(accessKeyId, service)).contentType("application/json"); + } + RequestSpecification json(String service, String target) { return given().header("Authorization", auth(accessKeyId, service)).header("X-Amz-Target", target) .contentType("application/x-amz-json-1.1"); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java index 516b2ec6c0..3ae64da35c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteCoverageTest.java @@ -51,6 +51,9 @@ class IamRestRouteCoverageTest { "GetBucketMetadataConfiguration", "s3:ListBucket", "DeleteBucketMetadataConfiguration", "s3:DeleteBucket"); + /** Models every operation of which is checked: the services whose routes the registry maps in full. */ + private static final Set FULLY_ROUTED_MODELS = Set.of("scheduler", "pipes"); + private final IamActionRegistry registry = new IamActionRegistry(); @TestFactory @@ -75,6 +78,26 @@ class IamRestRouteCoverageTest { return tests.stream(); } + @TestFactory + Stream everyOperationOfAFullyRoutedServiceResolvesToItsAction() throws IOException { + JsonNode models = load("/aws/rest-routes.json").path("models"); + JsonNode authorized = load("/aws/iam-authorized-actions.json").path("authorizedActions"); + List tests = new ArrayList<>(); + for (String model : FULLY_ROUTED_MODELS) { + String scope = models.path(model).path("credentialScope").asText(); + Iterator> operations = models.path(model).path("operations").fields(); + while (operations.hasNext()) { + Map.Entry operation = operations.next(); + Route route = new Route(scope, model, operation.getKey(), operation.getValue().path("method").asText(), + operation.getValue().path("requestUri").asText()); + String expected = authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey()); + tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(), + () -> assertEquals(expected, resolve(route), route.toString()))); + } + } + return tests.stream(); + } + /** Every model route of {@code operation} among the models Floci authorizes under {@code scope}. */ private static List routesOf(JsonNode models, String scope, String operation) { List routes = new ArrayList<>(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java index 70d840e01a..94a8186ec2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -68,6 +68,64 @@ class IamRestRouteEnforcementIntegrationTest { .get("/2018-10-31/layers").then().statusCode(404); } + @Test + void aScheduleRequestSignedForAnotherServiceIsStillCheckedAsScheduler() { + // Checked by the route it reached, not by the credential scope it was signed with: an S3 + // grant does not let the request through as an S3 request. + String user = user("route-scheduler-scope"); + policy(user, allow("s3:*", "*")); + refused(as(user, "s3").get("/schedules/route-schedule-" + suffix()).then(), "scheduler:GetSchedule"); + } + + @Test + void schedulerTaggingIsCheckedOnTheBareTagsRouteToo() { + // The shared tagging routes also take the ARN in the body of POST /tags. + String user = user("route-scheduler-tags"); + String group = scheduleGroup("route-group-" + suffix()); + + policy(user, allow("scheduler:ListTagsForResource", "*")); + refused(as(user, "scheduler").body(tagBody(group)).post("/tags").then(), "scheduler:TagResource"); + policy(user, allow("scheduler:TagResource", group)); + // Allowed on that group, the request reaches Scheduler, which has no such group. + as(user, "scheduler").body(tagBody(group)).post("/tags").then().statusCode(not(403)); + } + + @Test + void postTagsIsCheckedAgainstTheArnItsBodyNames() { + // POST /tags tags the ARN its body names: one named in the query does not move the check. + String user = user("route-tags-body"); + String allowed = scheduleGroup("route-allowed-" + suffix()); + String other = scheduleGroup("route-other-" + suffix()); + + policy(user, allow("scheduler:TagResource", allowed)); + refused(as(user, "scheduler").queryParam("resourceArn", allowed).body(tagBody(other)).post("/tags").then(), + "scheduler:TagResource"); + } + + @Test + void sharedTaggingIsCheckedAsTheServiceItsArnNames() { + // The shared tagging routes hand the request to the service its ARN names, whatever scope it is + // signed with: a Pipes grant does not let the caller tag a schedule group, and a scope with no + // tagging rule does not let the request through unchecked. + String user = user("route-tags-scope"); + String group = scheduleGroup("route-group-" + suffix()); + String cluster = "arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/route-cluster-" + suffix(); + + // Nor is an ARN of a service with no tagging rule checked as the signing scope's action. + as(user, "pipes").body(tagBody(cluster)).post("/tags").then().body(not(containsString("pipes:TagResource"))); + policy(user, allow("pipes:TagResource", "*")); + refused(as(user, "pipes").body(tagBody(group)).post("/tags").then(), "scheduler:TagResource"); + refused(as(user, "sqs").body(tagBody(group)).post("/tags").then(), "scheduler:TagResource"); + } + + private static String scheduleGroup(String name) { + return "arn:aws:scheduler:us-east-1:" + ACCOUNT + ":schedule-group/" + name; + } + + private static String tagBody(String arn) { + return "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"team\",\"value\":\"a\"}]}"; + } + private static void refused(ValidatableResponse response, String action) { response.statusCode(403).body(containsString(action)).body(not(containsString("iam:PassRole"))); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index ab39b543f2..81464a8aa2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -34,6 +34,7 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; @@ -1196,6 +1197,93 @@ class ResourceArnBuilderTest { assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000")); } + @Test + void schedulerRoutesResolveTheScheduleInItsGroupTheGroupOrTheTaggedArn() { + when(uriInfo.getPath()).thenReturn("/schedules/nightly"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule/default/nightly", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + queryParams.putSingle("groupName", "reports"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule/reports/nightly", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + // A create or update names its group in the body, which Scheduler reads, not in the query, which + // it ignores for them: a groupName there does not move the check to another group. + when(ctx.getMethod()).thenReturn("POST"); + setJsonBody("{\"GroupName\":\"billing\",\"ScheduleExpression\":\"rate(1 hour)\"}"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule/billing/nightly", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + queryParams.putSingle("groupName", "reports"); + setJsonBody("{\"GroupName\":\"billing\",\"ScheduleExpression\":\"rate(1 hour)\"}"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule/billing/nightly", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + queryParams.clear(); + when(ctx.getMethod()).thenReturn("PUT"); + setJsonBody("{\"ScheduleExpression\":\"rate(1 hour)\"}"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule/default/nightly", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + when(ctx.getMethod()).thenReturn("GET"); + queryParams.clear(); + when(uriInfo.getPath()).thenReturn("/schedule-groups/reports"); + assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule-group/reports", + builder.build("scheduler", ctx, "us-east-1", "000000000000")); + String group = "arn:aws:scheduler:us-east-1:000000000000:schedule-group/reports"; + when(uriInfo.getPath()).thenReturn("/tags/" + group); + assertEquals(group, builder.build("scheduler", ctx, "us-east-1", "000000000000")); + // The same tagging is served at /tags, the ARN in the resourceArn query parameter or body field. + when(uriInfo.getPath()).thenReturn("/tags"); + queryParams.putSingle("resourceArn", group); + assertEquals(group, builder.build("scheduler", ctx, "us-east-1", "000000000000")); + queryParams.clear(); + when(ctx.getMethod()).thenReturn("POST"); + setJsonBody("{\"resourceArn\":\"" + group + "\",\"tags\":[]}"); + assertEquals(group, builder.build("scheduler", ctx, "us-east-1", "000000000000")); + // POST /tags tags the body's ARN, so a resourceArn in the query does not move the check. + queryParams.putSingle("resourceArn", "arn:aws:scheduler:us-east-1:000000000000:schedule-group/other"); + setJsonBody("{\"resourceArn\":\"" + group + "\",\"tags\":[]}"); + assertEquals(group, builder.build("scheduler", ctx, "us-east-1", "000000000000")); + queryParams.clear(); + when(uriInfo.getPath()).thenReturn("/schedules"); + assertEquals("*", builder.build("scheduler", ctx, "us-east-1", "000000000000")); + } + + @Test + void schedulerAndPipesArnsAreMintedInTheRequestsPartition() { + // A Region no partition publishes takes the deployment's partition, as Scheduler and Pipes mint + // their ARNs, rather than aws. + when(uriInfo.getPath()).thenReturn("/schedules/nightly"); + assertEquals(List.of("arn:aws-cn:scheduler:xx-local-1:000000000000:schedule/default/nightly"), + builder.buildResources("scheduler", ctx, "xx-local-1", "000000000000", "aws-cn")); + when(uriInfo.getPath()).thenReturn("/schedule-groups/reports"); + assertEquals(List.of("arn:aws-cn:scheduler:xx-local-1:000000000000:schedule-group/reports"), + builder.buildResources("scheduler", ctx, "xx-local-1", "000000000000", "aws-cn")); + when(uriInfo.getPath()).thenReturn("/v1/pipes/orders"); + assertEquals(List.of("arn:aws-cn:pipes:xx-local-1:000000000000:pipe/orders"), + builder.buildResources("pipes", ctx, "xx-local-1", "000000000000", "aws-cn")); + } + + @Test + void theTaggedArnIsReadWhereTheSharedTaggingControllersReadIt() { + String arn = "arn:aws:pipes:us-east-1:000000000000:pipe/orders"; + when(ctx.getMethod()).thenReturn("GET"); + when(uriInfo.getPath()).thenReturn("/tags/" + arn); + assertEquals(arn, builder.taggedArn(ctx)); + when(uriInfo.getPath()).thenReturn("/v1/tags/" + arn); + assertEquals(arn, builder.taggedArn(ctx)); + when(uriInfo.getPath()).thenReturn("/tags"); + queryParams.putSingle("resourceArn", arn); + assertEquals(arn, builder.taggedArn(ctx)); + when(ctx.getMethod()).thenReturn("DELETE"); + assertEquals(arn, builder.taggedArn(ctx)); + // POST /v1/tags lists the tags of the ARN its query names, and POST /tags tags the one its body names. + when(ctx.getMethod()).thenReturn("POST"); + when(uriInfo.getPath()).thenReturn("/v1/tags"); + assertEquals(arn, builder.taggedArn(ctx)); + when(uriInfo.getPath()).thenReturn("/tags"); + setJsonBody("{\"tags\":[]}"); + assertNull(builder.taggedArn(ctx)); + when(uriInfo.getPath()).thenReturn("/v1/pipes/orders"); + assertNull(builder.taggedArn(ctx)); + } + @Test void aStreamingInvokeResolvesItsQualifiedFunctionAsAnInvokeDoes() { // A streaming invoke is an invoke: its qualifier and the account its function ARN names count. @@ -1205,6 +1293,19 @@ class ResourceArnBuilderTest { builder.build("lambda", ctx, "us-east-1", "000000000000")); } + @Test + void pipesRoutesResolveThePipeOrTheTaggedArn() { + String pipe = "arn:aws:pipes:us-east-1:000000000000:pipe/orders"; + when(uriInfo.getPath()).thenReturn("/v1/pipes/orders"); + assertEquals(pipe, builder.build("pipes", ctx, "us-east-1", "000000000000")); + when(uriInfo.getPath()).thenReturn("/v1/pipes/orders/start"); + assertEquals(pipe, builder.build("pipes", ctx, "us-east-1", "000000000000")); + when(uriInfo.getPath()).thenReturn("/tags/" + pipe); + assertEquals(pipe, builder.build("pipes", ctx, "us-east-1", "000000000000")); + when(uriInfo.getPath()).thenReturn("/v1/pipes"); + assertEquals("*", builder.build("pipes", ctx, "us-east-1", "000000000000")); + } + @Test void lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() { when(uriInfo.getPath()).thenReturn( diff --git a/src/test/resources/aws/rest-routes.json b/src/test/resources/aws/rest-routes.json index 992f391680..1f120f0548 100644 --- a/src/test/resources/aws/rest-routes.json +++ b/src/test/resources/aws/rest-routes.json @@ -334,6 +334,22 @@ "UpdateFunctionUrlConfig": {"method": "PUT", "requestUri": "/2021-10-31/functions/{FunctionName}/url"} } }, + "pipes": { + "credentialScope": "pipes", + "apiVersion": "2015-10-07", + "operations": { + "CreatePipe": {"method": "POST", "requestUri": "/v1/pipes/{Name}"}, + "DeletePipe": {"method": "DELETE", "requestUri": "/v1/pipes/{Name}"}, + "DescribePipe": {"method": "GET", "requestUri": "/v1/pipes/{Name}"}, + "ListPipes": {"method": "GET", "requestUri": "/v1/pipes"}, + "ListTagsForResource": {"method": "GET", "requestUri": "/tags/{resourceArn}"}, + "StartPipe": {"method": "POST", "requestUri": "/v1/pipes/{Name}/start"}, + "StopPipe": {"method": "POST", "requestUri": "/v1/pipes/{Name}/stop"}, + "TagResource": {"method": "POST", "requestUri": "/tags/{resourceArn}"}, + "UntagResource": {"method": "DELETE", "requestUri": "/tags/{resourceArn}"}, + "UpdatePipe": {"method": "PUT", "requestUri": "/v1/pipes/{Name}"} + } + }, "s3": { "credentialScope": "s3", "apiVersion": "2006-03-01", @@ -455,6 +471,24 @@ "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, "WriteGetObjectResponse": {"method": "POST", "requestUri": "/WriteGetObjectResponse"} } + }, + "scheduler": { + "credentialScope": "scheduler", + "apiVersion": "2021-06-30", + "operations": { + "CreateSchedule": {"method": "POST", "requestUri": "/schedules/{Name}"}, + "CreateScheduleGroup": {"method": "POST", "requestUri": "/schedule-groups/{Name}"}, + "DeleteSchedule": {"method": "DELETE", "requestUri": "/schedules/{Name}"}, + "DeleteScheduleGroup": {"method": "DELETE", "requestUri": "/schedule-groups/{Name}"}, + "GetSchedule": {"method": "GET", "requestUri": "/schedules/{Name}"}, + "GetScheduleGroup": {"method": "GET", "requestUri": "/schedule-groups/{Name}"}, + "ListScheduleGroups": {"method": "GET", "requestUri": "/schedule-groups"}, + "ListSchedules": {"method": "GET", "requestUri": "/schedules"}, + "ListTagsForResource": {"method": "GET", "requestUri": "/tags/{ResourceArn}"}, + "TagResource": {"method": "POST", "requestUri": "/tags/{ResourceArn}"}, + "UntagResource": {"method": "DELETE", "requestUri": "/tags/{ResourceArn}"}, + "UpdateSchedule": {"method": "PUT", "requestUri": "/schedules/{Name}"} + } } } } diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 2bb5460712..1c6aa3f5f7 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -35,7 +35,9 @@ MODELS: dict[str, str] = { "apigateway": "apigateway", "apigatewayv2": "apigateway", "lambda": "lambda", + "pipes": "pipes", "s3": "s3", + "scheduler": "scheduler", }