mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(stepfunctions): check the connection and secret permissions of an http task (#9645)
An HTTP task reads its EventBridge connection to authorize the request, but TaskPermissions.httpInvoke checked only states:InvokeHTTPEndpoint, so under IAM enforcement a role lacking the connection's permissions succeeded where AWS refuses it. The task now also needs events:RetrieveConnectionCredentials on the connection and secretsmanager:GetSecretValue and secretsmanager:DescribeSecret on the secret EventBridge keeps its credentials in, the grants the CDK's HttpInvoke task writes (aws-stepfunctions-tasks/lib/http/invoke.ts, buildTaskPolicyStatements). EventBridge answers the secret ARN through StoredResourceArns.recorded. The secret lookup and the call that uses the connection share one lookup by ARN, connectionNamedBy, so they cannot drift apart. The secret lookup reads the connection in the account its ARN names, in place, also finding one the default account saved under a bare key before stores kept accounts apart. A connection belongs to the account its ARN names: a lookup by ARN from another account finds none, and the call moves a legacy connection only into the account its ARN names, so a connection whose secret is not checked cannot be used. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
ab5759529f
commit
e951df03ad
7 files changed
+330
-54
No files matched your search
@@ -14,6 +14,7 @@ import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.ServiceRegistry;
|
||||
import io.floci.aws.core.common.SsrfProtection;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.batch.BatchService;
|
||||
import io.floci.aws.services.ecs.EcsJsonHandler;
|
||||
import io.floci.aws.services.ecs.EcsService;
|
||||
@@ -940,6 +941,11 @@ public class EventBridgeInvoker {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/** What finds the connections a request names and the secret each one stores its credentials in, reading only. */
|
||||
public StoredResourceArns storedResourceArns() {
|
||||
return eventBridgeService;
|
||||
}
|
||||
|
||||
private static ConnectionHttpParameters invocationHttpParameters(JsonNode authNode) {
|
||||
JsonNode invocationHttp = authNode.path("InvocationHttpParameters");
|
||||
return new ConnectionHttpParameters(readKeyValues(invocationHttp.path("HeaderParameters")),
|
||||
|
||||
@@ -2117,6 +2117,23 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
|
||||
.map(TagResource::tags).map(LinkedHashMap::new).orElseGet(LinkedHashMap::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* The secret a connection stored under {@code arn}, in the account and Region the ARN names, keeps its
|
||||
* credentials in, for {@code SecretArn} as botocore names that member of {@code DescribeConnection}'s output;
|
||||
* empty for any other member or an ARN naming no connection held under that whole ARN. A connection the default
|
||||
* account saved before stores kept accounts apart is found where it is, as the HTTP call that uses it finds it.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
if (!"SecretArn".equals(member) || !AwsArnUtils.isArnFor(arn, "events")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
return connectionNamedBy(arn, parsed.region(), parsed.accountId())
|
||||
.map(Connection::getSecretArn)
|
||||
.filter(secret -> !secret.isBlank());
|
||||
}
|
||||
|
||||
/** The Region's default event bus, which a request naming no bus acts on. */
|
||||
@Override
|
||||
public Optional<String> findDefault(String type, String region) {
|
||||
@@ -2439,25 +2456,57 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
|
||||
return connectionByArn(connectionArn, region, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection {@code connectionArn} names, looked up by its name in the ARN's Region ({@code region} when the ARN
|
||||
* names none) and held under that whole ARN: the ARN carries a generated id, so one for a connection deleted and
|
||||
* recreated under the same name does not match. {@code accountId} reads it in that account, in place, also finding
|
||||
* one the default account saved before stores kept accounts apart; null reads it in the request's account, moving
|
||||
* such a legacy connection into that account only when it is the account the ARN names. A connection belongs to
|
||||
* the account its ARN names, so a request of another account finds none, which keeps this lookup and the one in
|
||||
* the ARN's account, which an HTTP task's secret permissions read, in agreement.
|
||||
*/
|
||||
private Optional<Connection> connectionNamedBy(String connectionArn, String region, String accountId) {
|
||||
if (!AwsArnUtils.isArn(connectionArn)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(connectionArn);
|
||||
if (!parsed.resource().startsWith("connection/")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String reader = accountId == null ? regionResolver.getAccountId() : accountId;
|
||||
if (!reader.equals(parsed.accountId())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String remainder = parsed.resource().substring("connection/".length());
|
||||
int slash = remainder.indexOf('/');
|
||||
String name = slash > 0 ? remainder.substring(0, slash) : remainder;
|
||||
String key = connectionKey(parsed.region().isEmpty() ? region : parsed.region(), name);
|
||||
Optional<Connection> stored;
|
||||
if (accountId != null) {
|
||||
stored = readInAccount(connectionStore, accountId, key);
|
||||
} else if (connectionStore instanceof AccountAwareStorageBackend<Connection> accounts) {
|
||||
stored = accounts.getForAccountMigratingLegacy(reader, key,
|
||||
legacy -> connectionArn.equals(legacy.getConnectionArn()));
|
||||
} else {
|
||||
stored = connectionStore.get(key);
|
||||
}
|
||||
return stored.filter(connection -> connectionArn.equals(connection.getConnectionArn()));
|
||||
}
|
||||
|
||||
/** {@code verb} names the failing api-destination call in the not-found message, as AWS words it; null keeps the plain wording for internal callers. */
|
||||
private Connection connectionByArn(String connectionArn, String region, String verb) {
|
||||
if (connectionArn == null || connectionArn.isBlank()) {
|
||||
throw new AwsException("ResourceNotFoundException", "Connection ARN is required.", 400);
|
||||
}
|
||||
if (AwsArnUtils.isArn(connectionArn)) {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(connectionArn);
|
||||
String resource = parsed.resource();
|
||||
if (resource.startsWith("connection/")) {
|
||||
String remainder = resource.substring("connection/".length());
|
||||
int slash = remainder.indexOf('/');
|
||||
String name = slash > 0 ? remainder.substring(0, slash) : remainder;
|
||||
String connRegion = parsed.region().isEmpty() ? region : parsed.region();
|
||||
Optional<Connection> opt = connectionStore.get(connectionKey(connRegion, name));
|
||||
// The ARN carries a generated id: one for a connection deleted and recreated under the same name must not match
|
||||
if (opt.isPresent() && connectionArn.equals(opt.get().getConnectionArn())) {
|
||||
return opt.get();
|
||||
}
|
||||
}
|
||||
Optional<Connection> named = connectionNamedBy(connectionArn, region, null);
|
||||
if (named.isPresent()) {
|
||||
return named.get();
|
||||
}
|
||||
if (AwsArnUtils.isArn(connectionArn)
|
||||
&& !regionResolver.getAccountId().equals(AwsArnUtils.parse(connectionArn).accountId())) {
|
||||
throw verb == null
|
||||
? EventBridgeErrors.plainConnectionNotFound(connectionArn)
|
||||
: EventBridgeErrors.apiDestinationConnectionNotFound(verb, connectionArn);
|
||||
}
|
||||
return connectionStore.scan(k -> {
|
||||
Connection c = connectionStore.get(k).orElse(null);
|
||||
|
||||
@@ -1287,7 +1287,9 @@ public class AslExecutor {
|
||||
cloudFormationHandler == null ? null : cloudFormationHandler.storedResourceArns(),
|
||||
sdkManagementTaskInvoker == null ? null : sdkManagementTaskInvoker.secretsStoredResourceArns(),
|
||||
sfnService == null || !sfnService.isResolvable() ? null : sfnService.get(),
|
||||
schedulerService), new TaskPermissions.RequestLookups(passedRoleLookups, dynamoDbTables(sm)),
|
||||
schedulerService,
|
||||
eventBridgeInvoker == null ? null : eventBridgeInvoker.storedResourceArns()),
|
||||
new TaskPermissions.RequestLookups(passedRoleLookups, dynamoDbTables(sm)),
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId());
|
||||
if (required.isEmpty()) {
|
||||
return;
|
||||
|
||||
@@ -108,9 +108,11 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
* names nothing
|
||||
* @param scheduler the schedule group a Scheduler request naming none acts on, Scheduler's default; without
|
||||
* it such a request's group is open
|
||||
* @param events the secret an HTTP task's connection stores its credentials in; without it the secret's
|
||||
* permissions are not asked for
|
||||
*/
|
||||
record ControlServices(StoredResourceArns cloudFormation, StoredResourceArns secrets,
|
||||
StoredResourceArns states, StoredResourceArns scheduler) {
|
||||
StoredResourceArns states, StoredResourceArns scheduler, StoredResourceArns events) {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,7 +162,7 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
|
||||
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback) {
|
||||
return of(integration, input, machine, redshiftData, ecs, callback,
|
||||
new ControlServices(null, null, null, null));
|
||||
new ControlServices(null, null, null, null, null));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,7 +216,7 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
control.cloudFormation(), lookups));
|
||||
}
|
||||
if (integration.is("http", "invoke")) {
|
||||
return Optional.of(httpInvoke(input, machine));
|
||||
return Optional.of(httpInvoke(input, machine, control.events()));
|
||||
}
|
||||
if (integration.isSdk("ec2", "describeRegions")) {
|
||||
return Optional.of(ec2DescribeRegions(input, machine));
|
||||
@@ -721,11 +723,13 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
/**
|
||||
* {@code states:InvokeHTTPEndpoint} on the state machine, the resource the Developer Guide's policy scopes it to:
|
||||
* a role allowed it on {@code *}, as the CDK grants it, is allowed it there too. The two condition keys the guide
|
||||
* and the CDK write are given. The connection's own permissions, {@code events:RetrieveConnectionCredentials}
|
||||
* and its secret's, are not evaluated, although the task reads the connection to authorize its request: a role
|
||||
* lacking them succeeds here and fails on AWS. A request naming no endpoint is refused by the integration.
|
||||
* and the CDK write are given. The task reads its connection to authorize the request, so it also needs
|
||||
* {@code events:RetrieveConnectionCredentials} on the connection and {@code secretsmanager:GetSecretValue} and
|
||||
* {@code secretsmanager:DescribeSecret} on the secret {@code events} finds the connection keeps its credentials
|
||||
* in, as the CDK's {@code HttpInvoke} task grants them; a connection EventBridge does not hold has no secret to
|
||||
* ask for, and the integration answers it. A request naming no endpoint is refused by the integration.
|
||||
*/
|
||||
private static TaskPermissions httpInvoke(JsonNode input, StateMachine machine) {
|
||||
private static TaskPermissions httpInvoke(JsonNode input, StateMachine machine, StoredResourceArns events) {
|
||||
String endpoint = text(input.path("ApiEndpoint"));
|
||||
if (endpoint == null) {
|
||||
return accessDenied(HTTP_PREFIX, List.of());
|
||||
@@ -736,8 +740,21 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
if (method != null) {
|
||||
keys.put("states:HTTPMethod", List.of(method));
|
||||
}
|
||||
return accessDenied(HTTP_PREFIX, List.of(new Permission("states:InvokeHTTPEndpoint",
|
||||
machine.getStateMachineArn(), keys)));
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
permissions.add(new Permission("states:InvokeHTTPEndpoint", machine.getStateMachineArn(), keys));
|
||||
String connection = text(input.path("InvocationConfig").path("ConnectionArn"));
|
||||
if (connection == null) {
|
||||
connection = text(input.path("Authentication").path("ConnectionArn"));
|
||||
}
|
||||
if (connection != null) {
|
||||
permissions.add(new Permission("events:RetrieveConnectionCredentials", connection));
|
||||
Optional<String> secret = events == null ? Optional.empty() : events.recorded(connection, "SecretArn");
|
||||
secret.ifPresent(arn -> {
|
||||
permissions.add(new Permission("secretsmanager:GetSecretValue", arn));
|
||||
permissions.add(new Permission("secretsmanager:DescribeSecret", arn));
|
||||
});
|
||||
}
|
||||
return accessDenied(HTTP_PREFIX, permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package io.floci.aws.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.eventbridge.model.Connection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The secret a connection keeps its credentials in, which a Step Functions HTTP task's permissions ask for. A
|
||||
* connection saved before stores kept accounts apart sits under a bare key of the default account; the HTTP call
|
||||
* itself still finds it, so the permission lookup must too, without moving it.
|
||||
*/
|
||||
class EventBridgeConnectionSecretLookupTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String CONNECTION_ARN = "arn:aws:events:" + REGION + ":" + ACCOUNT + ":connection/saved/abc";
|
||||
private static final String SECRET_ARN = "arn:aws:secretsmanager:" + REGION + ":" + ACCOUNT
|
||||
+ ":secret:events!connection/saved/abc-XyZ";
|
||||
|
||||
@Test
|
||||
void aConnectionSavedUnderABareKeyStillNamesItsSecretAndStaysWhereItIs() {
|
||||
InMemoryStorage<String, Connection> raw = new InMemoryStorage<>();
|
||||
String bareKey = "connection:" + REGION + ":saved";
|
||||
raw.put(bareKey, connection());
|
||||
EventBridgeService service = service(new AccountAwareStorageBackend<>(raw, null, ACCOUNT));
|
||||
|
||||
assertEquals(Optional.of(SECRET_ARN), service.recorded(CONNECTION_ARN, "SecretArn"));
|
||||
assertEquals(Set.of(bareKey), raw.keys());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectionOfAnotherAccountUnderABareKeyNamesNoSecret() {
|
||||
InMemoryStorage<String, Connection> raw = new InMemoryStorage<>();
|
||||
raw.put("connection:" + REGION + ":saved", connection());
|
||||
EventBridgeService service = service(new AccountAwareStorageBackend<>(raw, null, ACCOUNT));
|
||||
|
||||
assertEquals(Optional.empty(), service.recorded(CONNECTION_ARN.replace(ACCOUNT, "222222222222"), "SecretArn"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A connection is its own account's: a request of another account naming it finds nothing, and does not move
|
||||
* the default account's legacy connection into its own partition, where the secret lookup, which reads the
|
||||
* account the ARN names, would no longer find it while the call still used it.
|
||||
*/
|
||||
@Test
|
||||
void anotherAccountNeitherUsesNorMovesTheDefaultAccountsLegacyConnection() {
|
||||
InMemoryStorage<String, Connection> raw = new InMemoryStorage<>();
|
||||
String bareKey = "connection:" + REGION + ":saved";
|
||||
raw.put(bareKey, connection());
|
||||
RegionResolver otherAccount = spy(new RegionResolver(REGION, ACCOUNT));
|
||||
when(otherAccount.getAccountId()).thenReturn("222222222222");
|
||||
EventBridgeService service = service(new AccountAwareStorageBackend<>(raw, null, ACCOUNT), otherAccount);
|
||||
|
||||
assertThrows(AwsException.class, () -> service.findConnectionByArn(CONNECTION_ARN, REGION));
|
||||
|
||||
assertEquals(Set.of(bareKey), raw.keys());
|
||||
assertEquals(Optional.of(SECRET_ARN), service.recorded(CONNECTION_ARN, "SecretArn"));
|
||||
}
|
||||
|
||||
/** The default account's own call still finds its legacy connection, and the secret lookup agrees. */
|
||||
@Test
|
||||
void theDefaultAccountsCallFindsItsLegacyConnectionAndTheSecretLookupStillAgrees() {
|
||||
InMemoryStorage<String, Connection> raw = new InMemoryStorage<>();
|
||||
raw.put("connection:" + REGION + ":saved", connection());
|
||||
EventBridgeService service = service(new AccountAwareStorageBackend<>(raw, null, ACCOUNT));
|
||||
|
||||
assertEquals(CONNECTION_ARN, service.findConnectionByArn(CONNECTION_ARN, REGION).getConnectionArn());
|
||||
|
||||
assertEquals(Optional.of(SECRET_ARN), service.recorded(CONNECTION_ARN, "SecretArn"));
|
||||
}
|
||||
|
||||
private static Connection connection() {
|
||||
Connection connection = new Connection();
|
||||
connection.setName("saved");
|
||||
connection.setConnectionArn(CONNECTION_ARN);
|
||||
connection.setSecretArn(SECRET_ARN);
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static EventBridgeService service(AccountAwareStorageBackend<Connection> connections) {
|
||||
return service(connections, new RegionResolver(REGION, ACCOUNT));
|
||||
}
|
||||
|
||||
private static EventBridgeService service(AccountAwareStorageBackend<Connection> connections,
|
||||
RegionResolver regions) {
|
||||
return new EventBridgeService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), connections,
|
||||
new InMemoryStorage<>(), regions, new ObjectMapper(), null, null, null, null, null, null);
|
||||
}
|
||||
}
|
||||
+74
-23
@@ -3,6 +3,7 @@ package io.floci.aws.services.stepfunctions;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
@@ -29,6 +30,7 @@ import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -309,7 +311,7 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
arguments.put("RoleARN", serviceRole);
|
||||
return new Target(target.integration(), target.machineName(), arguments, target.action(),
|
||||
target.resourceArn(), target.error(), target.serviceError(), target.reached(), target.notReached(),
|
||||
serviceRole);
|
||||
serviceRole, target.companions());
|
||||
}
|
||||
|
||||
/** Every integration mapped to a permission serves its callback form, and refuses it the same way. */
|
||||
@@ -481,9 +483,9 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
void anHttpGrantOnAnyResourceIsConditionedOnTheEndpoint(boolean matches, String status) throws Exception {
|
||||
Target target = target("http:invoke");
|
||||
String pattern = matches ? httpEndpoint() + "*" : "https://elsewhere.example/*";
|
||||
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action",
|
||||
String role = role(STATES_TRUST, target.grantWith(Map.of("Effect", "Allow", "Action",
|
||||
List.of("states:InvokeHTTPEndpoint"), "Resource", List.of("*"),
|
||||
"Condition", Map.of("StringLike", Map.of("states:HTTPEndpoint", pattern))))));
|
||||
"Condition", Map.of("StringLike", Map.of("states:HTTPEndpoint", pattern)))));
|
||||
|
||||
Response completed = terminal(start(machine(target, null, role), "{}"));
|
||||
|
||||
@@ -496,10 +498,10 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
@CsvSource({"GET,SUCCEEDED", "POST,FAILED"})
|
||||
void anHttpGrantOnTheStateMachineIsConditionedOnTheMethod(String method, String status) throws Exception {
|
||||
Target target = target("http:invoke");
|
||||
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action",
|
||||
String role = role(STATES_TRUST, target.grantWith(Map.of("Effect", "Allow", "Action",
|
||||
List.of("states:InvokeHTTPEndpoint"), "Resource", List.of(target.resourceArn()),
|
||||
"Condition", Map.of("StringEquals", Map.of("states:HTTPMethod", method),
|
||||
"StringLike", Map.of("states:HTTPEndpoint", httpEndpoint() + "*"))))));
|
||||
"StringLike", Map.of("states:HTTPEndpoint", httpEndpoint() + "*")))));
|
||||
|
||||
assertEquals(status, terminal(start(machine(target, null, role), "{}")).jsonPath().getString("status"));
|
||||
}
|
||||
@@ -514,15 +516,31 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* The task reads its Connection to authorize the request, but the connection's own permissions,
|
||||
* {@code events:RetrieveConnectionCredentials} and its secret's, are not evaluated: a role lacking them succeeds
|
||||
* here and fails on AWS, whose service reference example grants them.
|
||||
* The task reads its connection to authorize the request, so it needs the connection's credentials and the
|
||||
* secret that holds them, as the CDK's {@code HttpInvoke} grants them: a role lacking either is refused before
|
||||
* the endpoint is called.
|
||||
*/
|
||||
@Test
|
||||
void anHttpTaskDoesNotNeedTheConnectionsPermissions() throws Exception {
|
||||
@ParameterizedTest
|
||||
@CsvSource({"states:InvokeHTTPEndpoint,events:RetrieveConnectionCredentials",
|
||||
"states:InvokeHTTPEndpoint events:RetrieveConnectionCredentials,secretsmanager:GetSecretValue",
|
||||
"states:InvokeHTTPEndpoint events:RetrieveConnectionCredentials secretsmanager:GetSecretValue,"
|
||||
+ "secretsmanager:DescribeSecret"})
|
||||
void anHttpTaskNeedsTheConnectionsPermissions(String granted, String missing) throws Exception {
|
||||
Target target = target("http:invoke");
|
||||
Response completed = terminal(start(machine(target, null,
|
||||
role(STATES_TRUST, allow("*", "states:InvokeHTTPEndpoint"))), "{}"));
|
||||
role(STATES_TRUST, allow("*", granted.split(" ")))), "{}"));
|
||||
|
||||
assertFailed(completed, "States.Http.AccessDeniedException");
|
||||
assertTrue(completed.jsonPath().getString("cause").contains(missing), completed.asString());
|
||||
assertEquals(0, HTTP_CALLS.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anHttpTaskAllowedTheConnectionsPermissionsReachesTheEndpoint() throws Exception {
|
||||
Target target = target("http:invoke");
|
||||
Response completed = terminal(start(machine(target, null, role(STATES_TRUST, allow("*",
|
||||
"states:InvokeHTTPEndpoint", "events:RetrieveConnectionCredentials", "secretsmanager:GetSecretValue",
|
||||
"secretsmanager:DescribeSecret"))), "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
|
||||
assertEquals(1, HTTP_CALLS.get());
|
||||
@@ -742,10 +760,14 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
() -> assertEquals(404, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode()),
|
||||
"arn:aws:iam::" + ACCOUNT + ":role/AWSCloudFormationStackSetAdministrationRole");
|
||||
}
|
||||
case "http:invoke" -> target(integration, machine, Map.of("ApiEndpoint", httpEndpoint(), "Method", "GET",
|
||||
"InvocationConfig", Map.of("ConnectionArn", connection())),
|
||||
"states:InvokeHTTPEndpoint", machineArn(machine), "States.Http.AccessDeniedException", null,
|
||||
() -> assertEquals(1, HTTP_CALLS.get()), () -> assertEquals(0, HTTP_CALLS.get()));
|
||||
case "http:invoke" -> {
|
||||
String connection = connection();
|
||||
yield new Target(integration, machine, Map.of("ApiEndpoint", httpEndpoint(), "Method", "GET",
|
||||
"InvocationConfig", Map.of("ConnectionArn", connection)),
|
||||
"states:InvokeHTTPEndpoint", machineArn(machine), "States.Http.AccessDeniedException", null,
|
||||
() -> assertEquals(1, HTTP_CALLS.get()), () -> assertEquals(0, HTTP_CALLS.get()),
|
||||
null, connectionGrants(connection));
|
||||
}
|
||||
case "aws-sdk:ec2:describeRegions" -> target(integration, machine, Map.of(), "ec2:DescribeRegions", ANY_RESOURCE,
|
||||
"Ec2.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
|
||||
case "aws-sdk:lambda:listEventSourceMappings" -> target(integration, machine, Map.of(),
|
||||
@@ -821,20 +843,36 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
String resourceArn, String error, String serviceError, Check reached, Check notReached,
|
||||
String passedRole) {
|
||||
return new Target(integration, machine, arguments, action, resourceArn, error, serviceError, reached, notReached,
|
||||
passedRole);
|
||||
passedRole, List.of());
|
||||
}
|
||||
|
||||
/** @param passedRole the role the request passes, which needs {@code iam:PassRole}; null when it passes none */
|
||||
/**
|
||||
* @param passedRole the role the request passes, which needs {@code iam:PassRole}; null when it passes none
|
||||
* @param companions the statements the call also needs, on what its resource uses rather than on the resource
|
||||
* (an HTTP task's connection and the secret holding its credentials)
|
||||
*/
|
||||
private record Target(String integration, String machineName, Map<String, ?> arguments, String action,
|
||||
String resourceArn, String error, String serviceError, Check reached, Check notReached,
|
||||
String passedRole) {
|
||||
String passedRole, List<Map<String, Object>> companions) {
|
||||
|
||||
/** The action on the resource, and {@code iam:PassRole} on the role the request passes, if any. */
|
||||
/** The action on the resource, with {@link #grantWith}'s additions. */
|
||||
String grant() {
|
||||
Map<String, Object> onResource = Map.of("Effect", "Allow", "Action", List.of(action),
|
||||
"Resource", List.of(resourceArn));
|
||||
return policy(passedRole == null ? List.of(onResource) : List.of(onResource, Map.of("Effect", "Allow",
|
||||
"Action", List.of("iam:PassRole"), "Resource", List.of(passedRole))));
|
||||
return grantWith(Map.of("Effect", "Allow", "Action", List.of(action), "Resource", List.of(resourceArn)));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code statement}, {@code iam:PassRole} on the role the request passes, if any, and the {@link #companions}
|
||||
* the call also needs.
|
||||
*/
|
||||
String grantWith(Map<String, Object> statement) {
|
||||
List<Map<String, Object>> statements = new ArrayList<>();
|
||||
statements.add(statement);
|
||||
if (passedRole != null) {
|
||||
statements.add(Map.of("Effect", "Allow", "Action", List.of("iam:PassRole"),
|
||||
"Resource", List.of(passedRole)));
|
||||
}
|
||||
statements.addAll(companions);
|
||||
return policy(statements);
|
||||
}
|
||||
|
||||
/** {@link #reached}, for a task whose execution has not finished: the call happens after the task starts. */
|
||||
@@ -948,6 +986,19 @@ class StepFunctionsControlTaskIamIntegrationTest {
|
||||
return created.jsonPath().getString("ConnectionArn");
|
||||
}
|
||||
|
||||
/** The CDK's {@code HttpInvoke} grants: the connection's credentials and the secret EventBridge keeps them in. */
|
||||
private List<Map<String, Object>> connectionGrants(String connectionArn) {
|
||||
String secret = given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "events"))
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeConnection").contentType("application/x-amz-json-1.1")
|
||||
.body(MAPPER.valueToTree(Map.of("Name", AwsArnUtils.parse(connectionArn).resource().split("/")[1]))
|
||||
.toString())
|
||||
.post("/").jsonPath().getString("SecretArn");
|
||||
return List.of(Map.of("Effect", "Allow", "Action", List.of("events:RetrieveConnectionCredentials"),
|
||||
"Resource", connectionArn),
|
||||
Map.of("Effect", "Allow", "Action",
|
||||
List.of("secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret"), "Resource", secret));
|
||||
}
|
||||
|
||||
private int executions(String stateMachine) {
|
||||
return request("ListExecutions", Map.of("stateMachineArn", stateMachine)).jsonPath().getList("executions").size();
|
||||
}
|
||||
|
||||
@@ -305,7 +305,7 @@ class TaskPermissionsTest {
|
||||
orders.setTableName("orders");
|
||||
orders.setKeySchema(List.of(new KeySchemaElement("pk", "HASH")));
|
||||
return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, null, false,
|
||||
new TaskPermissions.ControlServices(null, null, null, null),
|
||||
new TaskPermissions.ControlServices(null, null, null, null, null),
|
||||
new TaskPermissions.RequestLookups(null, name -> "orders".equals(name) ? orders : null))
|
||||
.orElseThrow().permissions();
|
||||
}
|
||||
@@ -759,7 +759,7 @@ class TaskPermissionsTest {
|
||||
new Permission("iam:PassRole", "arn:aws:iam::111122223333:role/override", TO_ECS_TASKS)),
|
||||
TaskPermissions.of(integration(tail),
|
||||
json("{\"TaskDefinition\":\"orders\",\"Overrides\":{\"TaskRoleArn\":\"override\"}}"),
|
||||
machine("aws"), null, ecs(), false, new TaskPermissions.ControlServices(null, null, null, null),
|
||||
machine("aws"), null, ecs(), false, new TaskPermissions.ControlServices(null, null, null, null, null),
|
||||
roles()).orElseThrow().permissions());
|
||||
}
|
||||
|
||||
@@ -768,7 +768,7 @@ class TaskPermissionsTest {
|
||||
void aRunTaskNamingNoDefinitionNeedsNoPassRole() throws Exception {
|
||||
assertEquals(List.of(), TaskPermissions.of(integration("ecs:runTask"),
|
||||
json("{\"Overrides\":{\"TaskRoleArn\":\"override\"}}"), machine("aws"), null, ecs(), false,
|
||||
new TaskPermissions.ControlServices(null, null, null, null), roles()).orElseThrow().permissions());
|
||||
new TaskPermissions.ControlServices(null, null, null, null, null), roles()).orElseThrow().permissions());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -824,7 +824,7 @@ class TaskPermissionsTest {
|
||||
TaskPermissions.of(integration(tail), json("""
|
||||
{"Name":"c","ServiceRole":"service","JobFlowRole":"cluster-profile",
|
||||
"AutoScalingRole":"arn:aws:iam::111122223333:role/scaling"}"""), machine("aws"), null,
|
||||
null, false, new TaskPermissions.ControlServices(null, null, null, null), roles())
|
||||
null, false, new TaskPermissions.ControlServices(null, null, null, null, null), roles())
|
||||
.orElseThrow().permissions());
|
||||
}
|
||||
|
||||
@@ -862,7 +862,7 @@ class TaskPermissionsTest {
|
||||
StoredResourceArns secrets, StoredResourceArns states,
|
||||
boolean callback) throws Exception {
|
||||
return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, null, callback,
|
||||
new TaskPermissions.ControlServices(cloudFormation, secrets, states, schedules())).orElseThrow();
|
||||
new TaskPermissions.ControlServices(cloudFormation, secrets, states, schedules(), connections())).orElseThrow();
|
||||
}
|
||||
|
||||
private static TaskPermissions control(String tail, String request) throws Exception {
|
||||
@@ -891,6 +891,31 @@ class TaskPermissionsTest {
|
||||
};
|
||||
}
|
||||
|
||||
private static final String CONNECTION = "arn:aws:events:eu-west-1:" + ACCOUNT + ":connection/c/id";
|
||||
private static final String CONNECTION_SECRET =
|
||||
"arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:events!connection/c/id-AbCdEf";
|
||||
|
||||
/** EventBridge as IAM asks it: the connection {@code c}, whose credentials are in {@link #CONNECTION_SECRET}. */
|
||||
private static StoredResourceArns connections() {
|
||||
return new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "events";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
return CONNECTION.equals(arn) && "SecretArn".equals(member) ? Optional.of(CONNECTION_SECRET)
|
||||
: Optional.empty();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** 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() {
|
||||
@@ -936,7 +961,7 @@ class TaskPermissionsTest {
|
||||
"aws-sdk:rdsdata:batchExecuteStatement", "http:get", "elasticmapreduce:describeCluster"})
|
||||
void anApiNoIntegrationServesIsNotChecked(String tail) throws Exception {
|
||||
assertEquals(Optional.empty(), TaskPermissions.of(integration(tail), json("{}"), machine("aws"), null, null, false,
|
||||
new TaskPermissions.ControlServices(null, null, null, null)));
|
||||
new TaskPermissions.ControlServices(null, null, null, null, null)));
|
||||
}
|
||||
|
||||
/** A new case in the handler has to name its resource type here, or it would run unchecked under enforcement. */
|
||||
@@ -950,7 +975,7 @@ class TaskPermissionsTest {
|
||||
actions++;
|
||||
String api = Character.toLowerCase(action.group(1).charAt(0)) + action.group(1).substring(1);
|
||||
assertTrue(TaskPermissions.of(integration("aws-sdk:cloudformation:" + api), json("{}"), machine("aws"), null,
|
||||
null, false, new TaskPermissions.ControlServices(null, null, null, null)).isPresent(),
|
||||
null, false, new TaskPermissions.ControlServices(null, null, null, null, null)).isPresent(),
|
||||
action.group(1));
|
||||
}
|
||||
assertEquals(36, actions);
|
||||
@@ -1065,6 +1090,31 @@ class TaskPermissionsTest {
|
||||
control("http:invoke", "{\"ApiEndpoint\":\"https://a.example/x\"}").permissions().getFirst().conditionKeys());
|
||||
}
|
||||
|
||||
/** The CDK's {@code HttpInvoke} grants: the connection's credentials and the secret that holds them. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"InvocationConfig", "Authentication"})
|
||||
void anHttpTaskAlsoNeedsItsConnectionsCredentialsAndSecret(String member) throws Exception {
|
||||
TaskPermissions permissions = control("http:invoke", "{\"ApiEndpoint\":\"https://a.example/x\",\""
|
||||
+ member + "\":{\"ConnectionArn\":\"" + CONNECTION + "\"}}");
|
||||
|
||||
assertEquals(List.of(new Permission("states:InvokeHTTPEndpoint", machine("aws").getStateMachineArn(),
|
||||
Map.of("states:HTTPEndpoint", List.of("https://a.example/x"))),
|
||||
new Permission("events:RetrieveConnectionCredentials", CONNECTION),
|
||||
new Permission("secretsmanager:GetSecretValue", CONNECTION_SECRET),
|
||||
new Permission("secretsmanager:DescribeSecret", CONNECTION_SECRET)), permissions.permissions());
|
||||
}
|
||||
|
||||
/** A connection EventBridge does not hold has no secret to ask for: the integration answers it. */
|
||||
@Test
|
||||
void anHttpTaskWhoseConnectionIsNotHeldNeedsOnlyItsCredentials() throws Exception {
|
||||
String other = "arn:aws:events:eu-west-1:" + ACCOUNT + ":connection/gone/id";
|
||||
|
||||
assertEquals(List.of("states:InvokeHTTPEndpoint", "events:RetrieveConnectionCredentials"),
|
||||
control("http:invoke", "{\"ApiEndpoint\":\"https://a.example/x\",\"InvocationConfig\":"
|
||||
+ "{\"ConnectionArn\":\"" + other + "\"}}").permissions().stream()
|
||||
.map(Permission::action).toList());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{}", "{\"ApiEndpoint\":\" \"}", "{\"ApiEndpoint\":7}", "{\"Method\":\"GET\"}"})
|
||||
void anHttpTaskNamingNoEndpointNeedsNoPermission(String request) throws Exception {
|
||||
|
||||
Reference in new issue
Block a user