diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 65b21edffb..87a76f4307 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -791,14 +791,15 @@ type comes from the Service Authorization Reference: | `arn:aws:states:::aws-sdk:sfn:describeMapRun` | `states:DescribeMapRun` | The Map Run | `Sfn.AccessDeniedException` | | `arn:aws:states:::states:startExecution`, with `.sync`, `.sync:2` or `.waitForTaskToken` | `states:StartExecution` | The child state machine | `StepFunctions.AccessDeniedException` | -A CloudFormation action is evaluated on the stack or stack set the request reaches, under the id -CloudFormation holds for it, so a name and the id it stands for are one resource: -`stack//` and `stackset/:`. `createStack` and `createChangeSet` on a stack -not there yet evaluate `stack//*`. A change set named by its ARN, or a `describeStackResources` -naming a `PhysicalResourceId`, is evaluated on the stack that holds it. `describeStacks` and -`getTemplateSummary` without a `StackName` are on `*`, as are `validateTemplate`, `listStacks`, `listExports`, -`createStackSet`, `listStackSets`, `describeOrganizationsAccess` and `activateOrganizationsAccess`, which -have no resource type. +A CloudFormation action is evaluated as the same request made directly is, from the generated request resources: +on the stack or stack set the request names, under the id CloudFormation holds for it, so a name and the id it +stands for are one resource: `stack//` and `stackset/:`. A stack or stack set +CloudFormation does not hold has its id open, `stack//*` or `stackset/:*`, and a stack +id it does not hold is evaluated as given. A request naming its stack by no `StackName` (a change set by its ARN +alone, a `describeStackResources` by `PhysicalResourceId` alone, a `describeStacks` or `getTemplateSummary` with +none) is on `*`, as are `validateTemplate`, `listStacks`, `listExports`, `createStackSet`, `listStackSets`, +`describeOrganizationsAccess` and `activateOrganizationsAccess`, which have no resource type. An API the handler +does not serve is evaluated the same way, and CloudFormation then answers it with `UnknownAction`. `states:InvokeHTTPEndpoint` has no resource type in the Service Authorization Reference, and the CDK grants it on `*`, while the Developer Guide's example scopes it to the state machine, so the state machine is what is @@ -819,11 +820,11 @@ Every integration that evaluates a role is refused on its `.waitForTaskToken` fo task starts nothing and waits for nothing. With the permission, it calls its service and then waits on its token. -A request naming nothing it can reach has only the role checks, and its service answers it: no `Name`, a stack -or stack set name its service does not have, no `SecretId`, no `UUID`, no `ApiEndpoint`, a `StateMachineArn` or -`MapRunArn` that is not one, or a token naming no task. A stack named by an ARN of what does not exist here is left -to the service. A secret is evaluated as a direct `DescribeSecret` naming it is, from the generated request resources. An API Floci does not serve keeps its -answer, whatever the role: it is "Unsupported", or CloudFormation's `UnknownAction`, and the role is not checked. +A request naming nothing it can reach has only the role checks, and its service answers it: no `Name`, no +`SecretId`, no `UUID`, no `ApiEndpoint`, a `StateMachineArn` or `MapRunArn` that is not one, or a token naming no +task. A secret is evaluated as a direct `DescribeSecret` naming it is, from the generated request resources. An API +Floci does not serve keeps its answer, whatever the role: it is "Unsupported", and the role is not checked, except a +CloudFormation API, which is evaluated as above before CloudFormation answers it with `UnknownAction`. An activity task is not evaluated: the CDK's own task needs no permission for it, and the worker calling `GetActivityTask` is authorized by its own request. `Map`'s `ItemReader` and `ResultWriter` S3 calls are not diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java index 005f1586d0..1bf6f7cfd9 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java @@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsQueryResponse; +import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.services.cloudformation.model.ChangeSet; import io.floci.aws.services.cloudformation.model.Stack; @@ -23,7 +24,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.UUID; /** @@ -45,24 +45,12 @@ public class CloudFormationQueryHandler { this.stackSetService = stackSetService; } - /** The id of the stack a stack name or id names, as a request naming it finds it. */ - public Optional stackId(String stackNameOrId, String region) { - return cfnService.stackId(stackNameOrId, region); - } - - /** The id of the stack holding the change set {@code changeSetArn} names. */ - public Optional stackIdOfChangeSet(String changeSetArn, String region) { - return cfnService.stackIdOfChangeSet(changeSetArn, region); - } - - /** The id of the stack that owns the resource {@code physicalResourceId} names. */ - public Optional stackIdOfResource(String physicalResourceId, String region) { - return cfnService.stackIdOfResource(physicalResourceId, region); - } - - /** The id of the stack set of this name. */ - public Optional stackSetId(String stackSetName) { - return stackSetService.stackSetId(stackSetName); + /** + * What IAM asks CloudFormation of the resources a request names, the stack or the stack set a name names, reading + * only: for a state machine's task, which has no HTTP request of its own. + */ + public StoredResourceArns storedResourceArns() { + return new CloudFormationStoredResourceArns(cfnService, stackSetService); } public Response handle(String action, MultivaluedMap params, String region) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index f5907ba518..e0408c1c17 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -398,32 +398,6 @@ public class CloudFormationService implements ResourceProvider { // ── DescribeStacks ──────────────────────────────────────────────────────── - /** The id of the stack a stack name or id names, as a request describing it finds it, reading only. */ - public Optional stackId(String stackNameOrId, String region) { - return Optional.ofNullable(resolveStackForDescribe(stackNameOrId, region)).map(Stack::getStackId); - } - - /** The id of the stack holding the change set {@code changeSetArn} names, reading only. */ - public Optional stackIdOfChangeSet(String changeSetArn, String region) { - try { - return Optional.ofNullable(findStackForChangeSetArn(changeSetArn, region, currentAccount())) - .map(Stack::getStackId); - } catch (AwsException expected) { - LOG.debugv("The change set ARN {0} names no change set: {1}", changeSetArn, expected.getMessage()); - return Optional.empty(); - } - } - - /** The id of the stack that owns the resource {@code physicalResourceId} names, reading only. */ - public Optional stackIdOfResource(String physicalResourceId, String region) { - try { - return Optional.of(stackContaining(physicalResourceId, region).getStackId()); - } catch (AwsException expected) { - LOG.debugv("No stack owns the resource {0}: {1}", physicalResourceId, expected.getMessage()); - return Optional.empty(); - } - } - public List describeStacks(String stackName, String region) { return describeStacks(stackName, region, currentAccount()); } diff --git a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java index 9b2317fa9c..608af77dd1 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java @@ -204,11 +204,6 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen organizationsAccess.put(ORGANIZATIONS_ACCESS_KEY, "ENABLED"); } - /** The id of the stack set of this name, reading only. */ - public Optional stackSetId(String name) { - return stackSets.get(name).map(StackSet::getStackSetId); - } - public StackSet describeStackSet(String name) { return getStackSetOrThrow(name); } diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index bea48f27df..1d3dfac5e0 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -1266,7 +1266,8 @@ public class AslExecutor { } Optional required = TaskPermissions.of(integration, input, sm, redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns(), ecsService, - taskToken != null, new TaskPermissions.ControlServices(cloudFormationHandler, + taskToken != null, new TaskPermissions.ControlServices( + cloudFormationHandler == null ? null : cloudFormationHandler.storedResourceArns(), sdkManagementTaskInvoker == null ? null : sdkManagementTaskInvoker.secretsStoredResourceArns(), sfnService == null || !sfnService.isResolvable() ? null : sfnService.get())); if (required.isEmpty()) { diff --git a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java index 53737fad63..02a7d25a27 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -8,7 +8,6 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RequestChecks; import io.floci.aws.core.common.RequestResources; import io.floci.aws.core.common.StoredResourceArns; -import io.floci.aws.services.cloudformation.CloudFormationQueryHandler; import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser; import io.floci.aws.services.dynamodb.DynamoDbTableNames; import io.floci.aws.services.eventbridge.EventBridgeService; @@ -77,18 +76,6 @@ record TaskPermissions(String deniedError, List permissions, boolean private static final Set SCHEDULER = Set.of("createSchedule", "updateSchedule", "deleteSchedule"); private static final Set SFN_SDK = Set.of("startExecution", "startSyncExecution", "sendTaskSuccess", "sendTaskFailure", "describeMapRun"); - private static final Set CFN_ANY_RESOURCE = Set.of("ValidateTemplate", "ListStacks", "ListExports", - "DescribeOrganizationsAccess", "ActivateOrganizationsAccess", "CreateStackSet", "ListStackSets"); - private static final Set CFN_OPTIONAL_STACK = Set.of("DescribeStacks", "GetTemplateSummary"); - private static final Set CFN_CREATES_STACK = Set.of("CreateStack", "CreateChangeSet"); - private static final Set CFN_NAMES_CHANGE_SET = - Set.of("DescribeChangeSet", "ExecuteChangeSet", "DeleteChangeSet"); - private static final Set CFN_STACK = Set.of("UpdateStack", "DeleteStack", "ContinueUpdateRollback", - "UpdateTerminationProtection", "ListChangeSets", "DescribeStackEvents", "DescribeStackResources", - "ListStackResources", "DescribeStackResource", "GetTemplate", "SetStackPolicy", "GetStackPolicy"); - private static final Set CFN_STACK_SET = Set.of("DescribeStackSet", "UpdateStackSet", "DeleteStackSet", - "CreateStackInstances", "ListStackInstances", "DescribeStackInstance", "DeleteStackInstances", - "ListStackSetOperations", "DescribeStackSetOperation", "ListStackSetAutoDeploymentTargets"); TaskPermissions(String deniedError, List permissions) { this(deniedError, permissions, true); @@ -102,13 +89,14 @@ record TaskPermissions(String deniedError, List permissions, boolean /** * What finds the resources of a control task's request, reading only. * - * @param cloudFormation the stack or stack set of a CloudFormation request; without it such a request names nothing + * @param cloudFormation the stack or stack set a CloudFormation request names by its name, whose id CloudFormation + * minted; without it one is the ARN its format gives the name, its id open * @param secrets the secret a Secrets Manager request names, random suffix included; without it a secret is * the ARN its format gives the name * @param states the state machine or activity whose task a callback's token names; without it a token * names nothing */ - record ControlServices(CloudFormationQueryHandler cloudFormation, StoredResourceArns secrets, + record ControlServices(StoredResourceArns cloudFormation, StoredResourceArns secrets, StoredResourceArns states) { } @@ -529,69 +517,25 @@ record TaskPermissions(String deniedError, List permissions, boolean arn(machine, "scheduler", "schedule/" + (group == null ? "default" : group) + "/" + name)))); } - /** Every action the CloudFormation handler serves; any other is its own {@code UnknownAction}. */ + /** + * Every CloudFormation operation the vendored request resources read, which a direct request is checked as too; + * one the handler does not serve is then its own {@code UnknownAction}. + */ private static boolean servedByCloudFormation(String api) { - String operation = AslExecutor.capitalizeFirst(api); - return CFN_ANY_RESOURCE.contains(operation) || CFN_OPTIONAL_STACK.contains(operation) - || CFN_CREATES_STACK.contains(operation) || CFN_NAMES_CHANGE_SET.contains(operation) - || CFN_STACK.contains(operation) || CFN_STACK_SET.contains(operation); + return RequestResources.reads("cloudformation:" + AslExecutor.capitalizeFirst(api)); } /** - * The action of the API's own name, on the stack or stack set the request reaches under the id CloudFormation - * holds for it, in the service reference's resource types, so a name and the id it stands for are the same - * resource. A stack not there yet has its id open for the APIs that create it; for any other API a stack or - * stack set CloudFormation does not have names nothing, so CloudFormation answers it. + * The check the vendored request resources give the same call made directly ({@link #requestPermissions}), + * {@code stored} finding the stack or the stack set a name names; on any resource when the request names none, + * whatever its input is, as a direct request naming none is checked. */ private static TaskPermissions cloudFormation(String operation, JsonNode input, StateMachine machine, - CloudFormationQueryHandler stored) { - String action = "cloudformation:" + operation; - if (CFN_ANY_RESOURCE.contains(operation)) { - return accessDenied(CLOUDFORMATION_PREFIX, List.of(new Permission(action, ANY_RESOURCE))); - } - String resource; - if (CFN_STACK_SET.contains(operation)) { - resource = cloudFormationStackSet(input, machine, stored); - } else if (CFN_OPTIONAL_STACK.contains(operation) && text(input.path("StackName")) == null) { - resource = ANY_RESOURCE; - } else { - resource = cloudFormationStack(operation, input, machine, stored); - } - return accessDenied(CLOUDFORMATION_PREFIX, - resource == null ? List.of() : List.of(new Permission(action, resource))); - } - - private static String cloudFormationStackSet(JsonNode input, StateMachine machine, - CloudFormationQueryHandler stored) { - String name = text(input.path("StackSetName")); - if (name == null || stored == null) { - return null; - } - return stored.stackSetId(name).map(id -> arn(machine, "cloudformation", "stackset/" + id)).orElse(null); - } - - /** The stack as each API finds it: by name or id, or else by the change set or the resource the API can name it by. */ - private static String cloudFormationStack(String operation, JsonNode input, StateMachine machine, - CloudFormationQueryHandler stored) { - String stack = text(input.path("StackName")); - String region = regionOf(machine); - if (stored == null) { - return null; - } - if (stack != null) { - Optional id = stored.stackId(stack, region); - boolean opensId = CFN_CREATES_STACK.contains(operation) && !AwsArnUtils.looksLikeArn(stack); - return id.orElseGet(() -> opensId ? arn(machine, "cloudformation", "stack/" + stack + "/*") : null); - } - String changeSet = text(input.path("ChangeSetName")); - if (CFN_NAMES_CHANGE_SET.contains(operation) && AwsArnUtils.looksLikeArn(changeSet)) { - return stored.stackIdOfChangeSet(changeSet, region).orElse(null); - } - String resource = text(input.path("PhysicalResourceId")); - if ("DescribeStackResources".equals(operation) && resource != null) { - return stored.stackIdOfResource(resource, region).orElse(null); - } - return null; + StoredResourceArns stored) { + List permissions = requestPermissions("cloudformation", operation, input, machine, stored); + return accessDenied(CLOUDFORMATION_PREFIX, permissions.isEmpty() + ? List.of(new Permission(IamAuthorizedActions.actionFor("cloudformation", operation), ANY_RESOURCE)) + : permissions); } /** @@ -663,10 +607,6 @@ record TaskPermissions(String deniedError, List permissions, boolean return new AwsArnUtils.Arn(owner.partition(), service, owner.region(), owner.accountId(), resource).toString(); } - private static String regionOf(StateMachine machine) { - return AwsArnUtils.parse(machine.getStateMachineArn()).region(); - } - /** The value when it is the non-blank string an id has to be, as the integrations require of one. */ private static String text(JsonNode value) { return value.isTextual() && !value.asText().isBlank() ? value.asText() : null; diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java index 848cdb6b37..e8cf1c9ad8 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java @@ -511,22 +511,39 @@ class StepFunctionsControlTaskIamIntegrationTest { assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); } + /** + * A stack or stack set CloudFormation does not hold is evaluated with its id open, as the same request made + * directly is; allowed there, CloudFormation answers it. + */ @ParameterizedTest - @CsvSource({"deleteStack,StackName", "describeStackEvents,StackName", "describeStackSet,StackSetName"}) - void aStackCloudFormationDoesNotHaveIsLeftToCloudFormation(String api, String member) throws Exception { + @CsvSource({"deleteStack,StackName,cloudformation:DeleteStack,stack/%s/*", + "describeStackEvents,StackName,cloudformation:DescribeStackEvents,stack/%s/*", + "describeStackSet,StackSetName,cloudformation:DescribeStackSet,stackset/%s:*"}) + void aStackCloudFormationDoesNotHoldIsEvaluatedWithItsIdOpen(String api, String member, String action, + String resource) throws Exception { + String name = "no-such-" + UUID.randomUUID(); + String open = String.format(resource, name); Map task = new LinkedHashMap<>(Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:cloudformation:" + api, - "Parameters", Map.of(member, "no-such-" + UUID.randomUUID()), "End", true)); + "Parameters", Map.of(member, name), "End", true)); - Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")); + Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, + role(STATES_TRUST, READ_ONLY)), "{}")); + assertFailed(refused, "CloudFormation.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(open), refused.asString()); + Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, + role(STATES_TRUST, allow("arn:aws:cloudformation:*:*:" + open, action))), "{}")); assertFalse(String.valueOf(completed.jsonPath().getString("error")).endsWith("AccessDeniedException"), completed.asString()); } - /** A change set's ARN does not hold its stack's name, so the stack is found through it. */ + /** + * A change set named by its ARN alone gives no {@code StackName}, which the generated request resources fill the + * stack from, so it is evaluated on any resource, as the same request made directly is. + */ @Test - void aChangeSetNamedByItsArnIsEvaluatedOnItsStack() throws Exception { + void aChangeSetNamedByItsArnAloneIsEvaluatedOnAnyResource() throws Exception { String name = "sfn-control-" + UUID.randomUUID(); String stackId = stack(name); Response changeSet = cloudFormation("CreateChangeSet", Map.of("StackName", name, "ChangeSetName", "c", @@ -537,11 +554,12 @@ class StepFunctionsControlTaskIamIntegrationTest { "Parameters", Map.of("ChangeSetName", changeSet.xmlPath() .getString("CreateChangeSetResponse.CreateChangeSetResult.Id")), "End", true)); - assertStackActionIsEvaluatedOnTheStack(task, stackId, "cloudformation:DescribeChangeSet"); + assertEvaluatedOnAnyResource(task, stackId, "cloudformation:DescribeChangeSet"); } + /** A physical resource id alone gives no {@code StackName} either, so it is evaluated on any resource too. */ @Test - void describeStackResourcesNamingAPhysicalIdIsEvaluatedOnItsStack() throws Exception { + void describeStackResourcesNamingAPhysicalIdAloneIsEvaluatedOnAnyResource() throws Exception { String name = "sfn-control-" + UUID.randomUUID(); String stackId = stack(name); String physicalId = cloudFormation("ListStackResources", Map.of("StackName", name)).xmlPath() @@ -550,17 +568,18 @@ class StepFunctionsControlTaskIamIntegrationTest { "Resource", "arn:aws:states:::aws-sdk:cloudformation:describeStackResources", "Parameters", Map.of("PhysicalResourceId", physicalId), "End", true)); - assertStackActionIsEvaluatedOnTheStack(task, stackId, "cloudformation:DescribeStackResources"); + assertEvaluatedOnAnyResource(task, stackId, "cloudformation:DescribeStackResources"); } - private void assertStackActionIsEvaluatedOnTheStack(Map task, String stackId, String action) + /** Refused under a grant on the stack itself, which does not reach {@code *}, and allowed under one on it. */ + private void assertEvaluatedOnAnyResource(Map task, String stackId, String action) throws Exception { - Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")); + Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, + role(STATES_TRUST, allow(stackId, action))), "{}")); assertFailed(refused, "CloudFormation.AccessDeniedException"); - assertTrue(refused.jsonPath().getString("cause").contains(stackId), refused.asString()); Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, - role(STATES_TRUST, allow(stackId, action))), "{}")); + role(STATES_TRUST, allow(ANY_RESOURCE, action))), "{}")); assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java index f2f20ac351..22a0eb0b4b 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.StoredResourceArns; -import io.floci.aws.services.cloudformation.CloudFormationQueryHandler; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; import io.floci.aws.services.stepfunctions.model.StateMachine; import org.junit.jupiter.api.Test; @@ -616,8 +615,9 @@ class TaskPermissionsTest { } private static final String STACK = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/s/id"; + private static final String STACK_SET = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/ss:id"; - private static TaskPermissions control(String tail, String request, CloudFormationQueryHandler cloudFormation, + private static TaskPermissions control(String tail, String request, StoredResourceArns cloudFormation, StoredResourceArns secrets, StoredResourceArns states, boolean callback) throws Exception { return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, null, callback, @@ -628,16 +628,23 @@ class TaskPermissionsTest { return control(tail, request, null, null, null, false); } - private static CloudFormationQueryHandler stacks() { - CloudFormationQueryHandler handler = mock(CloudFormationQueryHandler.class); - when(handler.stackId(any(), any())).thenReturn(Optional.empty()); - when(handler.stackId("s", "eu-west-1")).thenReturn(Optional.of(STACK)); - when(handler.stackId(STACK, "eu-west-1")).thenReturn(Optional.of(STACK)); - when(handler.stackIdOfChangeSet(any(), any())).thenReturn(Optional.empty()); - when(handler.stackIdOfResource(any(), any())).thenReturn(Optional.empty()); - when(handler.stackSetId(any())).thenReturn(Optional.empty()); - when(handler.stackSetId("ss")).thenReturn(Optional.of("ss:id")); - return handler; + /** CloudFormation as IAM asks it: the stack {@code s} and the stack set {@code ss}, under the ids it minted. */ + private static StoredResourceArns stacks() { + return new StoredResourceArns() { + @Override + public String namespace() { + return "cloudformation"; + } + + @Override + public Optional find(String type, List names, String region) { + return switch (type) { + case "stack" -> names.equals(List.of("s")) ? Optional.of(STACK) : Optional.empty(); + case "stackset" -> names.equals(List.of("ss")) ? Optional.of(STACK_SET) : Optional.empty(); + default -> Optional.empty(); + }; + } + }; } @ParameterizedTest @@ -660,7 +667,7 @@ class TaskPermissionsTest { @ParameterizedTest @ValueSource(strings = {"aws-sdk:scheduler:getSchedule", "aws-sdk:scheduler:listSchedules", - "aws-sdk:cloudformation:describeTypeRegistration", "aws-sdk:sfn:describeExecution", "aws-sdk:sfn:stopExecution", + "aws-sdk:sfn:describeExecution", "aws-sdk:sfn:stopExecution", "aws-sdk:ec2:describeInstances", "aws-sdk:lambda:invoke", "aws-sdk:secretsmanager:getSecretValue", "aws-sdk:s3:getObject", "s3:getObject", "aws-sdk:s3:listObjectsV2", "dynamodb:query", "aws-sdk:rdsdata:batchExecuteStatement", "http:get", "elasticmapreduce:describeCluster"}) @@ -685,6 +692,13 @@ class TaskPermissionsTest { assertEquals(36, actions); } + /** An API the handler does not serve is checked as the direct request is, and the handler answers it. */ + @Test + void aCloudFormationApiTheHandlerDoesNotServeIsCheckedAsTheTableGivesIt() throws Exception { + assertEquals(List.of(new Permission("cloudformation:DescribeTypeRegistration", "*")), + control("aws-sdk:cloudformation:describeTypeRegistration", "{}").permissions()); + } + @ParameterizedTest @ValueSource(strings = {"validateTemplate", "listStacks", "listExports", "describeOrganizationsAccess", "activateOrganizationsAccess", "createStackSet", "listStackSets"}) @@ -693,6 +707,15 @@ class TaskPermissionsTest { control("aws-sdk:cloudformation:" + api, "{}").permissions()); } + /** A task whose input is no object still needs its action, on any resource, as a direct request naming none. */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = {"listStacks|null", "listStacks|[]", "describeStacks|\"s\"", + "executeChangeSet|7"}) + void aCloudFormationTaskWhoseInputIsNoObjectIsOnAnyResource(String api, String input) throws Exception { + assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*")), + control("aws-sdk:cloudformation:" + api, input).permissions()); + } + @ParameterizedTest @ValueSource(strings = {"updateStack", "deleteStack", "continueUpdateRollback", "updateTerminationProtection", "createChangeSet", "describeChangeSet", "executeChangeSet", "deleteChangeSet", "listChangeSets", @@ -708,60 +731,42 @@ class TaskPermissionsTest { } } + /** A stack CloudFormation does not hold, one a create makes among them, is its ARN with the id open. */ @ParameterizedTest - @ValueSource(strings = {"createStack", "createChangeSet"}) - void aStackNotThereYetHasItsIdOpenForWhatCreatesIt(String api) throws Exception { + @ValueSource(strings = {"createStack", "createChangeSet", "updateStack", "deleteStack", "describeStacks", + "describeChangeSet", "getTemplateSummary"}) + void aStackCloudFormationDoesNotHoldHasItsIdOpen(String api) throws Exception { assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/new/*")), - control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"new\"}", stacks(), null, null, false).permissions()); - } - - @ParameterizedTest - @ValueSource(strings = {"updateStack", "deleteStack", "describeStacks", "describeChangeSet", "getTemplateSummary"}) - void aStackCloudFormationDoesNotHaveNamesNothing(String api) throws Exception { - assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"none\"}", stacks(), null, null, false) - .permissions()); + control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"new\"}", stacks(), null, null, false) + .permissions()); } @Test - void anUnknownStackIdNeverOpensAnIdEvenToCreate() throws Exception { - assertEquals(List.of(), control("aws-sdk:cloudformation:createStack", - "{\"StackName\":\"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/none/id\"}", stacks(), null, null, false) - .permissions()); + void aStackIdIsCheckedAsGiven() throws Exception { + String unknown = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/none/id"; + assertEquals(List.of(new Permission("cloudformation:CreateStack", unknown)), + control("aws-sdk:cloudformation:createStack", "{\"StackName\":\"" + unknown + "\"}", stacks(), null, + null, false).permissions()); } + /** + * A request naming its stack by no {@code StackName}, a change set by its ARN alone or a physical resource id + * alone among them, is checked on any resource, as the direct request is: the vendored request resources fill + * the stack from {@code StackName} only. + */ @ParameterizedTest - @ValueSource(strings = {"describeStacks", "getTemplateSummary"}) - void aCloudFormationActionWithAnOptionalStackIsOnAnyResourceWithoutOne(String api) throws Exception { + @CsvSource(delimiter = '|', value = { + "describeStacks|{}", + "getTemplateSummary|{}", + "describeChangeSet|{\"ChangeSetName\":\"arn:aws:cloudformation:eu-west-1:000000000000:changeSet/c/1\"}", + "executeChangeSet|{\"ChangeSetName\":\"arn:aws:cloudformation:eu-west-1:000000000000:changeSet/c/1\"}", + "deleteChangeSet|{\"ChangeSetName\":\"c\"}", + "describeStackResources|{\"PhysicalResourceId\":\"r-1\"}", + "listStackResources|{\"PhysicalResourceId\":\"r-1\"}"}) + void aRequestNamingNoStackIsOnAnyResource(String api, String request) throws Exception { assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*")), - control("aws-sdk:cloudformation:" + api, "{}", stacks(), null, null, false).permissions()); - } - - @ParameterizedTest - @ValueSource(strings = {"describeChangeSet", "executeChangeSet", "deleteChangeSet"}) - void aChangeSetArnFindsItsStack(String api) throws Exception { - CloudFormationQueryHandler handler = stacks(); - when(handler.stackIdOfChangeSet("arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":changeSet/c/1", "eu-west-1")) - .thenReturn(Optional.of(STACK)); - - assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), STACK)), - control("aws-sdk:cloudformation:" + api, - "{\"ChangeSetName\":\"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":changeSet/c/1\"}", - handler, null, null, false).permissions()); - assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"ChangeSetName\":\"c\"}", - handler, null, null, false).permissions()); - } - - @Test - void describeStackResourcesFindsTheStackOfThePhysicalId() throws Exception { - CloudFormationQueryHandler handler = stacks(); - when(handler.stackIdOfResource("r-1", "eu-west-1")).thenReturn(Optional.of(STACK)); - - assertEquals(List.of(new Permission("cloudformation:DescribeStackResources", STACK)), - control("aws-sdk:cloudformation:describeStackResources", "{\"PhysicalResourceId\":\"r-1\"}", - handler, null, null, false).permissions()); - assertEquals(List.of(), control("aws-sdk:cloudformation:listStackResources", "{\"PhysicalResourceId\":\"r-1\"}", - handler, null, null, false).permissions()); + control("aws-sdk:cloudformation:" + api, request, stacks(), null, null, false).permissions()); } @ParameterizedTest @@ -769,11 +774,13 @@ class TaskPermissionsTest { "listStackInstances", "describeStackInstance", "deleteStackInstances", "listStackSetOperations", "describeStackSetOperation", "listStackSetAutoDeploymentTargets"}) void aStackSetActionIsOnTheStackSetAsCloudFormationHoldsIt(String api) throws Exception { + assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), STACK_SET)), + control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"ss\"}", stacks(), null, null, false) + .permissions()); assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), - "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/ss:id")), - control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"ss\"}", stacks(), null, null, false).permissions()); - assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"none\"}", - stacks(), null, null, false).permissions()); + "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/none:*")), + control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"none\"}", stacks(), null, null, false) + .permissions()); } @Test