mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eventbridge): authorize the role of Redshift Data API targets (#7095)
This commit is contained in:
1 parent
e3cdb72171
commit
4d99aa9639
14 files changed
+1115
-85
No files matched your search
@@ -179,7 +179,28 @@ aws events put-targets \
|
||||
`Sqls` selects `BatchExecuteStatement`; otherwise the target submits `Sql` with
|
||||
`ExecuteStatement`. `SecretManagerArn` maps to the Data API's `SecretArn`. The target's ARN provides
|
||||
the region used for execution; statements run in the rule's account. The stored `RoleArn` is passed
|
||||
as the Data API principal; Floci does not assume the role or evaluate its IAM policies.
|
||||
as the Data API principal.
|
||||
|
||||
With IAM enforcement on (`FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED`), a delivery runs only when the role
|
||||
of the target can do what EventBridge does with it:
|
||||
|
||||
- the role belongs to the rule's account and trusts `events.amazonaws.com`. A trust condition on
|
||||
`aws:SourceArn` is matched against the rule's ARN, and `aws:SourceAccount` against the rule's account;
|
||||
- it is allowed `redshift-data:ExecuteStatement`, or `redshift-data:BatchExecuteStatement` with `Sqls`,
|
||||
on the cluster or workgroup ARN of the target;
|
||||
- it is allowed the action that authenticates the statement: `secretsmanager:GetSecretValue` on the
|
||||
secret for `SecretManagerArn`, `redshift-serverless:GetCredentials` on the workgroup for a Serverless
|
||||
target, or `redshift:GetClusterCredentials` on the database user and the database for `DbUser`.
|
||||
|
||||
The role's identity policies, permissions boundary and the account's service control policies all apply.
|
||||
A refused delivery fails with `AccessDeniedException`, which the dispatcher records as `NO_PERMISSIONS`
|
||||
and sends to the dead-letter queue without retrying. A target with no role is refused as well. The role is
|
||||
checked before a bad JSONPath in `Sql`, `Sqls` or `StatementName` is reported, but after the paths in
|
||||
`Database`, `DbUser` and `SecretManagerArn` are resolved, since the permissions depend on them. A
|
||||
`SecretManagerArn` that is not an ARN adds no permission to check: the Data API rejects it as an invalid
|
||||
`SecretArn`. The check
|
||||
does not cover `redshift:GetClusterCredentialsWithIAM`, and it does not assume the role: the statement
|
||||
runs as the stored `RoleArn`. With enforcement off the role is not checked.
|
||||
|
||||
String parameters, including entries in `Sqls`, can be complete JSONPath references such as
|
||||
`$.detail.database`, `$.detail.query` or `$.detail.queries[0]`. Paths resolve against the original event, before
|
||||
@@ -195,8 +216,10 @@ cross-account event-bus target with the same ID and ARN retains its previous
|
||||
role, as documented by AWS.
|
||||
|
||||
The value must be between 1 and 1600 characters when supplied. Floci stores
|
||||
the role as configuration; target delivery does not assume it or enforce its
|
||||
IAM policies.
|
||||
the role as configuration; target delivery does not assume it. Only Redshift
|
||||
Data API targets check the role's trust and permissions (see
|
||||
[Redshift Data API Targets](#redshift-data-api-targets)); no other target
|
||||
enforces its role's IAM policies.
|
||||
|
||||
## API Destination Targets
|
||||
|
||||
|
||||
+75
-9
@@ -27,6 +27,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParamet
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
import io.github.hectorvent.floci.services.firehose.model.Record;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
|
||||
@@ -49,11 +50,13 @@ import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -83,6 +86,7 @@ public class EventBridgeInvoker {
|
||||
private final EcsJsonHandler ecsJsonHandler;
|
||||
private final StepFunctionsService stepFunctionsService;
|
||||
private final RedshiftDataService redshiftDataService;
|
||||
private final EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer;
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -101,13 +105,14 @@ public class EventBridgeInvoker {
|
||||
EcsJsonHandler ecsJsonHandler,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
RedshiftDataService redshiftDataService,
|
||||
EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer,
|
||||
ServiceRegistry serviceRegistry,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
|
||||
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, serviceRegistry,
|
||||
regionResolver, objectMapper, config,
|
||||
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer,
|
||||
serviceRegistry, regionResolver, objectMapper, config,
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
|
||||
}
|
||||
|
||||
@@ -121,6 +126,7 @@ public class EventBridgeInvoker {
|
||||
EcsJsonHandler ecsJsonHandler,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
RedshiftDataService redshiftDataService,
|
||||
EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer,
|
||||
ServiceRegistry serviceRegistry,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
@@ -136,6 +142,7 @@ public class EventBridgeInvoker {
|
||||
this.ecsJsonHandler = ecsJsonHandler;
|
||||
this.stepFunctionsService = stepFunctionsService;
|
||||
this.redshiftDataService = redshiftDataService;
|
||||
this.redshiftTargetAuthorizer = redshiftTargetAuthorizer;
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -150,7 +157,8 @@ public class EventBridgeInvoker {
|
||||
EmulatorConfig config) {
|
||||
this(lambdaService, sqsService, snsService,
|
||||
null /* batch */, null /* firehose */, null /* eventBridge */, null /* ecs */,
|
||||
null /* ecsJsonHandler */, null /* stepFunctions */, null /* redshiftData */, null /* registry */,
|
||||
null /* ecsJsonHandler */, null /* stepFunctions */, null /* redshiftData */,
|
||||
null /* redshiftTargetAuthorizer */, null /* registry */,
|
||||
null /* regionResolver */,
|
||||
objectMapper, config);
|
||||
}
|
||||
@@ -164,12 +172,18 @@ public class EventBridgeInvoker {
|
||||
EmulatorConfig config) {
|
||||
this(lambdaService, sqsService, snsService,
|
||||
null /* batch */, null /* firehose */, null /* eventBridge */, null /* ecs */,
|
||||
null /* ecsJsonHandler */, null /* stepFunctions */, redshiftDataService, serviceRegistry,
|
||||
null /* ecsJsonHandler */, null /* stepFunctions */, redshiftDataService,
|
||||
null /* redshiftTargetAuthorizer */, serviceRegistry,
|
||||
null /* regionResolver */,
|
||||
objectMapper, config);
|
||||
}
|
||||
|
||||
public void invokeTarget(Target target, String eventJson, String region) {
|
||||
invokeTarget(target, eventJson, region, null);
|
||||
}
|
||||
|
||||
/** {@code ruleArn} is the rule that matched, which a role's trust policy may name in {@code aws:SourceArn}. */
|
||||
public void invokeTarget(Target target, String eventJson, String region, String ruleArn) {
|
||||
String arn = target.getArn();
|
||||
String payload;
|
||||
if (target.getInput() != null) {
|
||||
@@ -241,7 +255,7 @@ public class EventBridgeInvoker {
|
||||
LOG.debugv("EventBridge delivered to Firehose: {0}", arn);
|
||||
} else if (AwsArnUtils.isArnFor(arn, "redshift")
|
||||
|| AwsArnUtils.isArnFor(arn, "redshift-serverless")) {
|
||||
deliverToRedshiftData(target, arn, eventJson);
|
||||
deliverToRedshiftData(target, arn, eventJson, ruleArn);
|
||||
} else if (isStateMachineArn(arn)) {
|
||||
String targetRegion = extractRegionFromArn(arn, region);
|
||||
String targetAccount = AwsArnUtils.parse(arn).accountId();
|
||||
@@ -335,7 +349,7 @@ public class EventBridgeInvoker {
|
||||
}
|
||||
}
|
||||
|
||||
private void deliverToRedshiftData(Target target, String targetArn, String eventJson) {
|
||||
private void deliverToRedshiftData(Target target, String targetArn, String eventJson, String ruleArn) {
|
||||
if (serviceRegistry != null && !serviceRegistry.isServiceEnabled("redshift-data")) {
|
||||
throw new AwsException("ServiceNotAvailableException", "Service redshift-data is not enabled.", 400);
|
||||
}
|
||||
@@ -361,6 +375,13 @@ public class EventBridgeInvoker {
|
||||
putIfPresent(request, "Database", resolveRedshiftParameter(parameters.getDatabase(), eventJson));
|
||||
putIfPresent(request, "DbUser", resolveRedshiftParameter(parameters.getDbUser(), eventJson));
|
||||
putIfPresent(request, "SecretArn", resolveRedshiftParameter(parameters.getSecretManagerArn(), eventJson));
|
||||
|
||||
String ruleAccount = regionResolver != null && regionResolver.getAccountId() != null
|
||||
? regionResolver.getAccountId()
|
||||
: arn.accountId();
|
||||
// The SQL does not change what the role needs, so the role is checked before a bad path in it is reported.
|
||||
authorizeRedshiftTarget(target, targetArn, request, parameters.getSqls() != null, ruleAccount, targetRegion,
|
||||
ruleArn);
|
||||
putIfPresent(request, "Sql", resolveRedshiftParameter(parameters.getSql(), eventJson));
|
||||
putIfPresent(request, "StatementName", resolveRedshiftParameter(parameters.getStatementName(), eventJson));
|
||||
if (parameters.getSqls() != null) {
|
||||
@@ -373,9 +394,6 @@ public class EventBridgeInvoker {
|
||||
request.put("WithEvent", parameters.getWithEvent());
|
||||
}
|
||||
|
||||
String ruleAccount = regionResolver != null && regionResolver.getAccountId() != null
|
||||
? regionResolver.getAccountId()
|
||||
: arn.accountId();
|
||||
if (parameters.getSqls() != null) {
|
||||
RequestScopes.callAs(ruleAccount, targetRegion,
|
||||
() -> redshiftDataService.batchExecuteStatement(request, targetRegion, target.getRoleArn()));
|
||||
@@ -386,6 +404,54 @@ public class EventBridgeInvoker {
|
||||
LOG.debugv("EventBridge submitted SQL to Redshift Data API: {0}", targetArn);
|
||||
}
|
||||
|
||||
/**
|
||||
* EventBridge assumes the target's role to call the Data API, so the role has to be allowed the Data
|
||||
* API action and whatever authenticates it: a secret, temporary credentials for the database user,
|
||||
* or the Serverless workgroup's credentials. A refusal is an {@code AccessDeniedException}, which the
|
||||
* dispatcher classifies as NO_PERMISSIONS and sends to the dead-letter queue without retrying.
|
||||
*/
|
||||
private void authorizeRedshiftTarget(Target target, String targetArn, ObjectNode request, boolean batch,
|
||||
String ruleAccount, String targetRegion, String ruleArn) {
|
||||
if (redshiftTargetAuthorizer == null) {
|
||||
return;
|
||||
}
|
||||
// A cluster runs by name in the rule's account, whatever account the target ARN names, so that is the
|
||||
// cluster the role has to be allowed on.
|
||||
String statementTarget = request.has("ClusterIdentifier")
|
||||
? AwsArnUtils.Arn.of("redshift", targetRegion, ruleAccount,
|
||||
"cluster:" + request.path("ClusterIdentifier").asText()).toString()
|
||||
: targetArn;
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
permissions.add(new Permission(
|
||||
batch ? "redshift-data:BatchExecuteStatement" : "redshift-data:ExecuteStatement", statementTarget));
|
||||
// The Data API ignores a blank value, so it picks the credentials the same way.
|
||||
String secret = request.path("SecretArn").asText("");
|
||||
if (!secret.isBlank()) {
|
||||
// A secret named without its ARN has no resource to authorize against, and the Data API
|
||||
// rejects it as an invalid SecretArn before reading it, so no permission is checked for it.
|
||||
if (AwsArnUtils.isArn(secret)) {
|
||||
permissions.add(new Permission(
|
||||
"secretsmanager:GetSecretValue", secret));
|
||||
}
|
||||
} else if (request.has("WorkgroupName")) {
|
||||
permissions.add(new Permission(
|
||||
"redshift-serverless:GetCredentials", targetArn));
|
||||
} else if (!request.path("DbUser").asText("").isBlank()) {
|
||||
String cluster = request.path("ClusterIdentifier").asText();
|
||||
permissions.add(new Permission("redshift:GetClusterCredentials",
|
||||
AwsArnUtils.Arn.of("redshift", targetRegion, ruleAccount,
|
||||
"dbuser:" + cluster + "/" + request.path("DbUser").asText()).toString()));
|
||||
permissions.add(new Permission("redshift:GetClusterCredentials",
|
||||
AwsArnUtils.Arn.of("redshift", targetRegion, ruleAccount,
|
||||
"dbname:" + cluster + "/" + request.path("Database").asText()).toString()));
|
||||
}
|
||||
Optional<String> refusal = redshiftTargetAuthorizer.refusal(target.getRoleArn(), ruleAccount, ruleArn,
|
||||
permissions);
|
||||
if (refusal.isPresent()) {
|
||||
throw new AwsException("AccessDeniedException", refusal.get(), 403);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveRedshiftParameter(String value, String eventJson) {
|
||||
if (value == null || !DYNAMIC_PARAMETER_PATH.matcher(value).matches()) {
|
||||
return value;
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Decides whether the role of an EventBridge Redshift Data API target may submit its SQL. EventBridge
|
||||
* assumes the target's role, so the role has to trust {@code events.amazonaws.com}, and its identity
|
||||
* policies, permissions boundary and SCPs have to allow every {@link Permission} the submission needs:
|
||||
* the Data API action itself and the action that authenticates it. Only active with IAM enforcement on,
|
||||
* as for every other API call. A role of another account is refused, because the rule's account does
|
||||
* not own it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EventBridgeRedshiftTargetAuthorizer {
|
||||
|
||||
private static final String EVENTS_PRINCIPAL = ServicePrincipals.of("events");
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final ServiceRoleAuthorizer authorizer;
|
||||
|
||||
@Inject
|
||||
public EventBridgeRedshiftTargetAuthorizer(EmulatorConfig config, ServiceRoleAuthorizer authorizer) {
|
||||
this.config = config;
|
||||
this.authorizer = authorizer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not run the target, or nothing when it may.
|
||||
*
|
||||
* @param accountId the account that owns the rule
|
||||
* @param ruleArn the rule that matched, which a trust policy may require in {@code aws:SourceArn}; without
|
||||
* it such a condition does not match
|
||||
* @param permissions what the submission needs, each of which has to be allowed
|
||||
*/
|
||||
public Optional<String> refusal(String roleArn, String accountId, String ruleArn,
|
||||
List<Permission> permissions) {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (roleArn == null || roleArn.isBlank()) {
|
||||
return Optional.of("A Redshift target requires an IAM role, and this one names none.");
|
||||
}
|
||||
return authorizer.refusal(roleArn, accountId, EVENTS_PRINCIPAL, ruleArn, permissions);
|
||||
}
|
||||
}
|
||||
@@ -157,7 +157,7 @@ public class TargetDispatcher implements Resettable {
|
||||
|
||||
private void attempt(Delivery delivery, Target target, Instant now) {
|
||||
try {
|
||||
invoker.invokeTarget(target, delivery.eventJson(), delivery.region());
|
||||
invoker.invokeTarget(target, delivery.eventJson(), delivery.region(), delivery.ruleArn());
|
||||
} catch (Exception e) {
|
||||
if (delivery.generation() != generation.get()) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Decides whether a customer's service role may be assumed by an AWS service to perform actions on
|
||||
* their behalf, such as EventBridge submitting statements to Redshift Data API or Redshift Serverless
|
||||
* taking scheduled snapshots. The role has to belong to the caller's account, trust the service
|
||||
* principal (with optional conditions such as {@code aws:SourceArn} and {@code aws:SourceAccount}),
|
||||
* and its identity policies, permissions boundary and SCPs must allow every required action.
|
||||
*
|
||||
* <p>Only active with IAM enforcement on. With it off, every role is allowed.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ServiceRoleAuthorizer {
|
||||
|
||||
/** One IAM action the role needs, on the resource it acts on. */
|
||||
public record Permission(String action, String resourceArn) {
|
||||
}
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final AssumeRolePolicyEvaluator trustEvaluator;
|
||||
private final Instance<ScpProvider> scpProvider;
|
||||
|
||||
@Inject
|
||||
public ServiceRoleAuthorizer(EmulatorConfig config, IamService iamService,
|
||||
IamPolicyEvaluator evaluator,
|
||||
AssumeRolePolicyEvaluator trustEvaluator,
|
||||
Instance<ScpProvider> scpProvider) {
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.trustEvaluator = trustEvaluator;
|
||||
this.scpProvider = scpProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not be used by {@code servicePrincipal}, or empty when it may.
|
||||
*
|
||||
* @param roleArn the IAM role the service assumes
|
||||
* @param accountId the account that owns the resource and the role
|
||||
* @param servicePrincipal the AWS service principal that assumes the role (e.g. {@code events.amazonaws.com})
|
||||
* @param sourceArn optional ARN of the trigger or resource, checked against {@code aws:SourceArn} trust conditions
|
||||
* @param permissions the actions and resource ARNs the service needs to execute
|
||||
*/
|
||||
public Optional<String> refusal(String roleArn, String accountId, String servicePrincipal,
|
||||
String sourceArn, List<Permission> permissions) {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn parsed;
|
||||
try {
|
||||
parsed = AwsArnUtils.parse(roleArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Optional.of("The role " + roleArn + " is not a valid ARN.");
|
||||
}
|
||||
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
|
||||
return Optional.of("The role " + roleArn + " is not an IAM role.");
|
||||
}
|
||||
if (!accountId.equals(parsed.accountId())) {
|
||||
return Optional.of("The role " + roleArn + " belongs to another account.");
|
||||
}
|
||||
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
|
||||
Optional<IamRole> role = iamService.findRole(accountId, roleName)
|
||||
.filter(found -> IamService.roleArnMatches(roleArn, found));
|
||||
if (role.isEmpty()) {
|
||||
return Optional.of("The role " + roleArn + " does not exist.");
|
||||
}
|
||||
if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(), servicePrincipal,
|
||||
sourceArn, accountId)) {
|
||||
return Optional.of("The role " + roleArn + " does not trust " + servicePrincipal + ".");
|
||||
}
|
||||
CallerContext caller = iamService.resolvePrincipalContext(role.get().getArn());
|
||||
List<List<String>> scpLevels = scpProvider.isResolvable()
|
||||
? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
if (scpLevels != null) {
|
||||
caller = caller.withScpLevels(scpLevels);
|
||||
}
|
||||
for (Permission permission : permissions) {
|
||||
if (evaluate(caller, role.get().getArn(), accountId, permission) != Decision.ALLOW) {
|
||||
return Optional.of("The role " + roleArn + " is not authorized to perform "
|
||||
+ permission.action() + " on " + permission.resourceArn() + ".");
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Decision evaluate(CallerContext caller, String roleArn, String accountId, Permission permission) {
|
||||
AwsArnUtils.Arn resource = AwsArnUtils.isArn(permission.resourceArn())
|
||||
? AwsArnUtils.parse(permission.resourceArn()) : null;
|
||||
String region = resource != null ? resource.region() : null;
|
||||
String resourceAccount = resource != null ? resource.accountId() : accountId;
|
||||
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("aws:PrincipalArn", List.of(roleArn)),
|
||||
permission.resourceArn(), region, accountId, resourceAccount);
|
||||
return evaluator.evaluate(caller, List.of(), permission.action(), permission.resourceArn(), context);
|
||||
}
|
||||
}
|
||||
+7
-69
@@ -1,22 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -32,22 +22,11 @@ public class RedshiftServerlessScheduledActionAuthorizer {
|
||||
static final String CREATE_SNAPSHOT = "redshift-serverless:CreateSnapshot";
|
||||
private static final String SCHEDULER_PRINCIPAL = ServicePrincipals.of("scheduler.redshift");
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final AssumeRolePolicyEvaluator trustEvaluator;
|
||||
private final Instance<ScpProvider> scpProvider;
|
||||
private final ServiceRoleAuthorizer authorizer;
|
||||
|
||||
@Inject
|
||||
public RedshiftServerlessScheduledActionAuthorizer(EmulatorConfig config, IamService iamService,
|
||||
IamPolicyEvaluator evaluator,
|
||||
AssumeRolePolicyEvaluator trustEvaluator,
|
||||
Instance<ScpProvider> scpProvider) {
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.trustEvaluator = trustEvaluator;
|
||||
this.scpProvider = scpProvider;
|
||||
public RedshiftServerlessScheduledActionAuthorizer(ServiceRoleAuthorizer authorizer) {
|
||||
this.authorizer = authorizer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,48 +35,7 @@ public class RedshiftServerlessScheduledActionAuthorizer {
|
||||
* @param accountId the account that owns the action
|
||||
*/
|
||||
public Optional<String> refusal(String roleArn, String accountId, String targetArn) {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn parsed;
|
||||
try {
|
||||
parsed = AwsArnUtils.parse(roleArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Optional.of("The execution role " + roleArn + " is not a valid ARN.");
|
||||
}
|
||||
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
|
||||
return Optional.of("The execution role " + roleArn + " is not an IAM role.");
|
||||
}
|
||||
if (!accountId.equals(parsed.accountId())) {
|
||||
return Optional.of("The execution role " + roleArn + " belongs to another account.");
|
||||
}
|
||||
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
|
||||
Optional<IamRole> role = iamService.findRole(accountId, roleName)
|
||||
.filter(found -> IamService.roleArnMatches(roleArn, found));
|
||||
if (role.isEmpty()) {
|
||||
return Optional.of("The execution role " + roleArn + " does not exist.");
|
||||
}
|
||||
if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(), SCHEDULER_PRINCIPAL,
|
||||
null, accountId)) {
|
||||
return Optional.of("The execution role " + roleArn + " does not trust " + SCHEDULER_PRINCIPAL + ".");
|
||||
}
|
||||
CallerContext caller = iamService.resolvePrincipalContext(role.get().getArn());
|
||||
List<List<String>> scpLevels = scpProvider.isResolvable()
|
||||
? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
if (scpLevels != null) {
|
||||
caller = caller.withScpLevels(scpLevels);
|
||||
}
|
||||
AwsArnUtils.Arn target = AwsArnUtils.isArn(targetArn) ? AwsArnUtils.parse(targetArn) : null;
|
||||
String targetRegion = target != null ? target.region() : null;
|
||||
String targetAccount = target != null ? target.accountId() : accountId;
|
||||
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("aws:PrincipalArn", List.of(role.get().getArn())),
|
||||
targetArn, targetRegion, accountId, targetAccount);
|
||||
Decision decision = evaluator.evaluate(caller, List.of(), CREATE_SNAPSHOT, targetArn, context);
|
||||
if (decision != Decision.ALLOW) {
|
||||
return Optional.of("The execution role " + roleArn + " is not authorized to perform "
|
||||
+ CREATE_SNAPSHOT + " on " + targetArn + ".");
|
||||
}
|
||||
return Optional.empty();
|
||||
return authorizer.refusal(roleArn, accountId, SCHEDULER_PRINCIPAL, null,
|
||||
List.of(new Permission(CREATE_SNAPSHOT, targetArn)));
|
||||
}
|
||||
}
|
||||
+1
@@ -83,6 +83,7 @@ class EventBridgeInvokerTest {
|
||||
new HostVolumePolicy(emulatorConfig)),
|
||||
stepFunctionsService,
|
||||
redshiftDataService,
|
||||
null,
|
||||
serviceRegistry,
|
||||
regionResolver,
|
||||
new ObjectMapper(),
|
||||
|
||||
+1
-1
@@ -222,7 +222,7 @@ class EventBridgeRedshiftDataTargetTest {
|
||||
EventBridgeInvoker scopedInvoker = new EventBridgeInvoker(
|
||||
mock(LambdaService.class), mock(SqsService.class), mock(SnsService.class),
|
||||
null, null, null, null, null, null,
|
||||
redshiftDataService, serviceRegistry, resolver, new ObjectMapper(), config);
|
||||
redshiftDataService, null, serviceRegistry, resolver, new ObjectMapper(), config);
|
||||
|
||||
Target target = target(CLUSTER_ARN);
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EventBridgeRedshiftTargetAuthorizationTest {
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String CLUSTER_ARN = "arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:warehouse";
|
||||
private static final String WORKGROUP_ARN =
|
||||
"arn:aws:redshift-serverless:us-west-2:" + ACCOUNT + ":workgroup/warehouse";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT + ":role/EventBridgeRedshiftRole";
|
||||
private static final String SECRET_ARN = "arn:aws:secretsmanager:us-east-1:" + ACCOUNT + ":secret:db-AbCdEf";
|
||||
private static final String EVENT = "{\"id\":\"event-1\"}";
|
||||
|
||||
private RedshiftDataService redshiftDataService;
|
||||
private EventBridgeRedshiftTargetAuthorizer authorizer;
|
||||
private EventBridgeInvoker invoker;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
redshiftDataService = mock(RedshiftDataService.class);
|
||||
authorizer = mock(EventBridgeRedshiftTargetAuthorizer.class);
|
||||
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.empty());
|
||||
ServiceRegistry serviceRegistry = mock(ServiceRegistry.class);
|
||||
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.baseUrl()).thenReturn("http://localhost:4566");
|
||||
invoker = new EventBridgeInvoker(mock(LambdaService.class), mock(SqsService.class), mock(SnsService.class),
|
||||
null, null, null, null, null, null, redshiftDataService, authorizer, serviceRegistry, resolver,
|
||||
new ObjectMapper(), config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterTargetWithADbUserNeedsTheDataApiActionAndTemporaryCredentials() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setDbUser("admin");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(
|
||||
new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN),
|
||||
new Permission("redshift:GetClusterCredentials",
|
||||
"arn:aws:redshift:us-east-1:" + ACCOUNT + ":dbuser:warehouse/admin"),
|
||||
new Permission("redshift:GetClusterCredentials",
|
||||
"arn:aws:redshift:us-east-1:" + ACCOUNT + ":dbname:warehouse/dev")), permissions());
|
||||
verify(redshiftDataService).executeStatement(any(JsonNode.class), eq("us-east-1"), eq(ROLE_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretReplacesTheCredentialsPermission() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setDbUser("admin");
|
||||
parameters.setSecretManagerArn(SECRET_ARN);
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(
|
||||
new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN),
|
||||
new Permission("secretsmanager:GetSecretValue", SECRET_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterTargetNamingAnotherAccountIsCheckedAgainstTheClusterThatRuns() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target("arn:aws:redshift:us-east-1:999999999999:cluster:warehouse", parameters),
|
||||
EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankSecretIsIgnoredAndTheDbUserCredentialsAreChecked() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setDbUser("admin");
|
||||
parameters.setSecretManagerArn("");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(3, permissions().size());
|
||||
assertEquals("redshift:GetClusterCredentials", permissions().get(1).action());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankSecretOnAServerlessTargetStillNeedsTheWorkgroupCredentials() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSecretManagerArn(" ");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(WORKGROUP_ARN, parameters), EVENT, "us-west-2");
|
||||
|
||||
assertEquals(new Permission("redshift-serverless:GetCredentials", WORKGROUP_ARN), permissions().get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankDbUserAddsNoCredentialsPermission() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setDbUser("");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretNamedWithoutAnArnAddsNoPermissionBecauseTheDataApiRejectsIt() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSecretManagerArn("db");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverlessTargetWithASecretNeedsTheSecretAndNotTheWorkgroupCredentials() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSecretManagerArn(SECRET_ARN);
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(WORKGROUP_ARN, parameters), EVENT, "us-west-2");
|
||||
|
||||
assertEquals(List.of(
|
||||
new Permission("redshift-data:ExecuteStatement", WORKGROUP_ARN),
|
||||
new Permission("secretsmanager:GetSecretValue", SECRET_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchNeedsTheBatchAction() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSqls(List.of("select 1", "select 2"));
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(new Permission("redshift-data:BatchExecuteStatement", CLUSTER_ARN), permissions().getFirst());
|
||||
verify(redshiftDataService).batchExecuteStatement(any(JsonNode.class), eq("us-east-1"), eq(ROLE_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverlessTargetNeedsTheWorkgroupCredentials() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(WORKGROUP_ARN, parameters), EVENT, "us-west-2");
|
||||
|
||||
assertEquals(List.of(
|
||||
new Permission("redshift-data:ExecuteStatement", WORKGROUP_ARN),
|
||||
new Permission("redshift-serverless:GetCredentials", WORKGROUP_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterTargetWithoutADbUserOrSecretNeedsOnlyTheDataApiAction() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", CLUSTER_ARN)), permissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusedRoleIsAccessDeniedAndNothingIsSubmitted() {
|
||||
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1"));
|
||||
|
||||
assertEquals("AccessDeniedException", failure.getErrorCode());
|
||||
assertEquals(403, failure.getHttpStatus());
|
||||
assertEquals("not authorized", failure.getMessage());
|
||||
verifyNoInteractions(redshiftDataService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusedRoleIsReportedBeforeABadPathInTheSql() {
|
||||
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("$.detail.missing");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1"));
|
||||
|
||||
assertEquals("AccessDeniedException", failure.getErrorCode());
|
||||
verifyNoInteractions(redshiftDataService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowedRoleStillGetsTheValidationErrorForABadPathInTheSql() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("$.detail.missing");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", failure.getErrorCode());
|
||||
verifyNoInteractions(redshiftDataService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleRuleAccountAndMatchedRuleAreHandedToTheAuthorizer() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
String ruleArn = "arn:aws:events:us-east-1:" + ACCOUNT + ":rule/refresh";
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1", ruleArn);
|
||||
|
||||
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), eq(ruleArn), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deliveryWithoutAMatchedRuleHandsOverNone() {
|
||||
RedshiftDataParameters parameters = parameters("dev");
|
||||
parameters.setSql("select 1");
|
||||
|
||||
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
|
||||
|
||||
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), isNull(), anyList());
|
||||
}
|
||||
|
||||
private List<Permission> permissions() {
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Permission>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), any(), captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
private static RedshiftDataParameters parameters(String database) {
|
||||
RedshiftDataParameters parameters = new RedshiftDataParameters();
|
||||
parameters.setDatabase(database);
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private static Target target(String arn, RedshiftDataParameters parameters) {
|
||||
Target target = new Target();
|
||||
target.setId("redshift");
|
||||
target.setArn(arn);
|
||||
target.setRoleArn(ROLE_ARN);
|
||||
target.setRedshiftDataParameters(parameters);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EventBridgeRedshiftTargetAuthorizerTest {
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/events-redshift";
|
||||
private static final String CLUSTER = "arn:aws:redshift:us-east-1:" + ACCOUNT_ID + ":cluster:warehouse";
|
||||
private static final String SECRET = "arn:aws:secretsmanager:us-east-1:" + ACCOUNT_ID + ":secret:db-AbCdEf";
|
||||
private static final String TRUST = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
private static final String ALLOW_EXECUTE = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""";
|
||||
private static final String RULE_ARN = "arn:aws:events:us-east-1:" + ACCOUNT_ID + ":rule/refresh";
|
||||
private static final Permission EXECUTE = new Permission("redshift-data:ExecuteStatement", CLUSTER);
|
||||
|
||||
private EmulatorConfig config;
|
||||
private IamService iamService;
|
||||
private ScpProvider scps;
|
||||
private EventBridgeRedshiftTargetAuthorizer authorizer;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
iamService = mock(IamService.class);
|
||||
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
scps = mock(ScpProvider.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(true);
|
||||
when(scpProvider.get()).thenReturn(scps);
|
||||
ServiceRoleAuthorizer serviceRoleAuthorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
|
||||
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
|
||||
authorizer = new EventBridgeRedshiftTargetAuthorizer(config, serviceRoleAuthorizer);
|
||||
}
|
||||
|
||||
private void role(String trust, String... policies) {
|
||||
IamRole role = new IamRole("id", "events-redshift", "/", ROLE_ARN, trust);
|
||||
when(iamService.findRole(ACCOUNT_ID, "events-redshift")).thenReturn(Optional.of(role));
|
||||
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(policies)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustedRoleWithThePermissionIsAllowed() {
|
||||
role(TRUST, ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nothingIsCheckedWhileIamEnforcementIsOff() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
|
||||
assertTrue(authorizer.refusal("not-an-arn", ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
|
||||
verifyNoInteractions(iamService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRoleIsRefused() {
|
||||
when(iamService.findRole(ACCOUNT_ID, "events-redshift")).thenReturn(Optional.empty());
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
|
||||
.contains("does not exist"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleWithoutAnArnIsRefused() {
|
||||
assertTrue(authorizer.refusal(null, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
|
||||
.contains("requires an IAM role"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleOfAnotherAccountIsRefused() {
|
||||
assertTrue(authorizer.refusal("arn:aws:iam::999999999999:role/events-redshift", ACCOUNT_ID, RULE_ARN,
|
||||
List.of(EXECUTE)).orElseThrow().contains("belongs to another account"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleThatDoesNotTrustEventBridgeIsRefused() {
|
||||
role("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""", ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
|
||||
.contains("does not trust events.amazonaws.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleWithoutTheActionIsRefusedAndTheMessageNamesIt() {
|
||||
role(TRUST, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"redshift-data:DescribeStatement","Resource":"*"}]}""");
|
||||
|
||||
assertEquals("The role " + ROLE_ARN + " is not authorized to perform redshift-data:ExecuteStatement on "
|
||||
+ CLUSTER + ".",
|
||||
authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPermissionHasToBeAllowed() {
|
||||
role(TRUST, ALLOW_EXECUTE);
|
||||
Permission secret = new Permission("secretsmanager:GetSecretValue", SECRET);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE, secret)).orElseThrow()
|
||||
.contains("secretsmanager:GetSecretValue on " + SECRET));
|
||||
}
|
||||
|
||||
@Test
|
||||
void permissionsGrantedAcrossSeveralPoliciesAreAllowed() {
|
||||
role(TRUST, ALLOW_EXECUTE, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"secretsmanager:GetSecretValue","Resource":"%s"}]}""".formatted(SECRET));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN,
|
||||
List.of(EXECUTE, new Permission("secretsmanager:GetSecretValue", SECRET))).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyScopedToAnotherClusterIsRefused() {
|
||||
role(TRUST, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"redshift-data:ExecuteStatement",
|
||||
"Resource":"arn:aws:redshift:us-east-1:%s:cluster:other"}]}""".formatted(ACCOUNT_ID));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitDenyBeatsAnAllow() {
|
||||
role(TRUST, ALLOW_EXECUTE, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""");
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceControlPolicyDenyIsRefused() {
|
||||
role(TRUST, ALLOW_EXECUTE);
|
||||
when(scps.effectiveScpLevels(ACCOUNT_ID)).thenReturn(List.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""")));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void permissionsBoundaryThatDoesNotAllowTheActionIsRefused() {
|
||||
role(TRUST, ALLOW_EXECUTE);
|
||||
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(new CallerContext(
|
||||
List.of(ALLOW_EXECUTE), null, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"s3:*","Resource":"*"}]}"""));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustPolicyNamingTheMatchedRuleInSourceArnIsAllowed() {
|
||||
role(sourceArnTrust(RULE_ARN), ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustPolicyNamingAnotherRuleInSourceArnIsRefused() {
|
||||
role(sourceArnTrust("arn:aws:events:us-east-1:" + ACCOUNT_ID + ":rule/other"), ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
|
||||
.contains("does not trust events.amazonaws.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceArnConditionDoesNotMatchWhenTheRuleIsUnknown() {
|
||||
role(sourceArnTrust(RULE_ARN), ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, null, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
|
||||
private static String sourceArnTrust(String ruleArn) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"ArnEquals":{"aws:SourceArn":"%s"}}}]}""".formatted(ruleArn);
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustPolicyWithMismatchedSourceAccountConditionIsRefused() {
|
||||
role("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"StringEquals":{"aws:SourceAccount":"999999999999"}}}]}""", ALLOW_EXECUTE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RedshiftDataParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* With IAM enforcement on, an EventBridge Redshift target runs only when its role trusts
|
||||
* events.amazonaws.com and may call the Data API and authenticate to the cluster.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class EventBridgeRedshiftTargetRoleEnforcementIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String CLUSTER_ARN = "arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:warehouse";
|
||||
private static final String EVENTS_TRUST = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
private static final String LAMBDA_TRUST = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
private static final String DATA_API_AND_CREDENTIALS = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"redshift-data:ExecuteStatement","Resource":"%s"},
|
||||
{"Effect":"Allow","Action":"redshift:GetClusterCredentials","Resource":"*"}]}""".formatted(CLUSTER_ARN);
|
||||
|
||||
@Inject
|
||||
EventBridgeInvoker invoker;
|
||||
|
||||
@Inject
|
||||
TargetDispatcher dispatcher;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@InjectMock
|
||||
RedshiftDataService redshiftDataService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clearInvocations(redshiftDataService);
|
||||
when(redshiftDataService.executeStatement(any(), any(), any()))
|
||||
.thenReturn(JsonNodeFactory.instance.objectNode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleThatTrustsEventBridgeAndHoldsThePermissionsRunsTheStatement() {
|
||||
String roleArn = role("events-redshift-allowed", EVENTS_TRUST, DATA_API_AND_CREDENTIALS);
|
||||
|
||||
invoker.invokeTarget(target(roleArn), "{\"id\":\"event-1\"}", "us-east-1");
|
||||
|
||||
verify(redshiftDataService).executeStatement(any(JsonNode.class), eq("us-east-1"), eq(roleArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleThatDoesNotTrustEventBridgeIsRefused() {
|
||||
String roleArn = role("events-redshift-untrusted", LAMBDA_TRUST, DATA_API_AND_CREDENTIALS);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target(roleArn), "{\"id\":\"event-1\"}", "us-east-1"));
|
||||
|
||||
assertEquals("AccessDeniedException", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("does not trust events.amazonaws.com"), failure.getMessage());
|
||||
verify(redshiftDataService, never()).executeStatement(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleWithoutTheCredentialsPermissionIsRefused() {
|
||||
String roleArn = role("events-redshift-no-credentials", EVENTS_TRUST, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> invoker.invokeTarget(target(roleArn), "{\"id\":\"event-1\"}", "us-east-1"));
|
||||
|
||||
assertEquals(403, failure.getHttpStatus());
|
||||
assertTrue(failure.getMessage().contains("redshift:GetClusterCredentials"), failure.getMessage());
|
||||
verify(redshiftDataService, never()).executeStatement(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustConditionOnTheRuleArnIsMatchedForADeliveryThroughTheDispatcher() {
|
||||
String ruleArn = "arn:aws:events:us-east-1:" + ACCOUNT + ":rule/refresh";
|
||||
String roleArn = role("events-redshift-source-arn", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"ArnEquals":{"aws:SourceArn":"%s"}}}]}""".formatted(ruleArn),
|
||||
DATA_API_AND_CREDENTIALS);
|
||||
Target target = target(roleArn);
|
||||
|
||||
dispatcher.dispatch(ruleArn, target, "{\"id\":\"event-1\"}", "us-east-1", () -> List.of(target));
|
||||
verify(redshiftDataService).executeStatement(any(JsonNode.class), eq("us-east-1"), eq(roleArn));
|
||||
|
||||
clearInvocations(redshiftDataService);
|
||||
dispatcher.dispatch("arn:aws:events:us-east-1:" + ACCOUNT + ":rule/other", target,
|
||||
"{\"id\":\"event-2\"}", "us-east-1", () -> List.of(target));
|
||||
verify(redshiftDataService, never()).executeStatement(any(), any(), any());
|
||||
}
|
||||
|
||||
private String role(String name, String trust, String policy) {
|
||||
String arn = iamService.createRole(name, "/", trust, null, 3600, Map.of()).getArn();
|
||||
iamService.putRolePolicy(name, "redshift", policy);
|
||||
return arn;
|
||||
}
|
||||
|
||||
private static Target target(String roleArn) {
|
||||
RedshiftDataParameters parameters = new RedshiftDataParameters();
|
||||
parameters.setDatabase("dev");
|
||||
parameters.setDbUser("admin");
|
||||
parameters.setSql("select 1");
|
||||
Target target = new Target();
|
||||
target.setId("redshift");
|
||||
target.setArn(CLUSTER_ARN);
|
||||
target.setRoleArn(roleArn);
|
||||
target.setRedshiftDataParameters(parameters);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -218,7 +218,7 @@ class RuleSchedulerTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invokeTarget(Target target, String eventJson, String region) {
|
||||
public void invokeTarget(Target target, String eventJson, String region, String ruleArn) {
|
||||
invocationCount.incrementAndGet();
|
||||
onDelivery.run();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ServiceRoleAuthorizerTest {
|
||||
private static final String ACCOUNT_ID = "123456789012";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/service-role";
|
||||
private static final String RESOURCE = "arn:aws:s3:::my-bucket";
|
||||
private static final String SERVICE_PRINCIPAL = "events.amazonaws.com";
|
||||
private static final String SOURCE_ARN = "arn:aws:events:us-east-1:" + ACCOUNT_ID + ":rule/trigger";
|
||||
private static final String TRUST = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
private static final String ALLOW = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"s3:PutObject","Resource":"*"}]}""";
|
||||
private static final Permission PERMISSION = new Permission("s3:PutObject", RESOURCE);
|
||||
|
||||
private EmulatorConfig config;
|
||||
private IamService iamService;
|
||||
private ScpProvider scps;
|
||||
private ServiceRoleAuthorizer authorizer;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
iamService = mock(IamService.class);
|
||||
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
scps = mock(ScpProvider.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(true);
|
||||
when(scpProvider.get()).thenReturn(scps);
|
||||
authorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
|
||||
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
|
||||
}
|
||||
|
||||
private void role(String trust, String... policies) {
|
||||
IamRole role = new IamRole("id", "service-role", "/", ROLE_ARN, trust);
|
||||
when(iamService.findRole(ACCOUNT_ID, "service-role")).thenReturn(Optional.of(role));
|
||||
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(policies)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trustedRoleWithPermissionsIsAllowed() {
|
||||
role(TRUST, ALLOW);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcementOffAllowsEverything() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
|
||||
assertTrue(authorizer.refusal("not-an-arn", ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isEmpty());
|
||||
verifyNoInteractions(iamService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRoleIsRefused() {
|
||||
when(iamService.findRole(ACCOUNT_ID, "service-role")).thenReturn(Optional.empty());
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).orElseThrow().contains("does not exist"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleOfAnotherAccountIsRefusedWithoutLookup() {
|
||||
Optional<String> refusal = authorizer.refusal("arn:aws:iam::999999999999:role/service-role",
|
||||
ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN, List.of(PERMISSION));
|
||||
|
||||
assertTrue(refusal.orElseThrow().contains("belongs to another account"));
|
||||
verify(iamService, never()).findRole(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonRoleArnIsRefused() {
|
||||
assertTrue(authorizer.refusal("arn:aws:iam::" + ACCOUNT_ID + ":user/someone",
|
||||
ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN, List.of(PERMISSION)).orElseThrow()
|
||||
.contains("is not an IAM role"));
|
||||
assertTrue(authorizer.refusal("invalid-arn",
|
||||
ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN, List.of(PERMISSION)).orElseThrow()
|
||||
.contains("is not a valid ARN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void untrustedServicePrincipalIsRefused() {
|
||||
role(TRUST.replace("events.amazonaws.com", "lambda.amazonaws.com"), ALLOW);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).orElseThrow().contains("does not trust events.amazonaws.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingPermissionIsRefusedAndNamesActionAndResource() {
|
||||
role(TRUST, ALLOW);
|
||||
Permission other = new Permission("s3:GetObject", RESOURCE);
|
||||
|
||||
assertEquals("The role " + ROLE_ARN + " is not authorized to perform s3:GetObject on " + RESOURCE + ".",
|
||||
authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(other)).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPermissionMustBeAllowed() {
|
||||
role(TRUST, ALLOW);
|
||||
Permission denied = new Permission("s3:DeleteObject", RESOURCE);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION, denied)).orElseThrow().contains("s3:DeleteObject"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scpDenyIsRefused() {
|
||||
role(TRUST, ALLOW);
|
||||
when(scps.effectiveScpLevels(ACCOUNT_ID)).thenReturn(List.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Action":"s3:PutObject","Resource":"*"}]}""")));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void permissionsBoundaryDenyIsRefused() {
|
||||
role(TRUST, ALLOW);
|
||||
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(new CallerContext(
|
||||
List.of(ALLOW), null, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"sqs:*","Resource":"*"}]}"""));
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceArnTrustConditionIsEvaluated() {
|
||||
String conditionalTrust = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"ArnEquals":{"aws:SourceArn":"%s"}}}]}""".formatted(SOURCE_ARN);
|
||||
role(conditionalTrust, ALLOW);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isEmpty());
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, "arn:aws:events:us-east-1:123456789012:rule/other",
|
||||
List.of(PERMISSION)).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceAccountTrustConditionIsEvaluated() {
|
||||
String conditionalTrust = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"StringEquals":{"aws:SourceAccount":"%s"}}}]}""".formatted(ACCOUNT_ID);
|
||||
role(conditionalTrust, ALLOW);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isEmpty());
|
||||
|
||||
String mismatchTrust = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
|
||||
"Condition":{"StringEquals":{"aws:SourceAccount":"999999999999"}}}]}""";
|
||||
role(mismatchTrust, ALLOW);
|
||||
|
||||
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, SERVICE_PRINCIPAL, SOURCE_ARN,
|
||||
List.of(PERMISSION)).isPresent());
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -51,8 +52,9 @@ class RedshiftServerlessScheduledActionAuthorizerTest {
|
||||
scps = mock(ScpProvider.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(true);
|
||||
when(scpProvider.get()).thenReturn(scps);
|
||||
authorizer = new RedshiftServerlessScheduledActionAuthorizer(config, iamService, evaluator,
|
||||
ServiceRoleAuthorizer serviceRoleAuthorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
|
||||
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
|
||||
authorizer = new RedshiftServerlessScheduledActionAuthorizer(serviceRoleAuthorizer);
|
||||
}
|
||||
|
||||
private void role(String arn, String trust, String policy) {
|
||||
|
||||
Reference in new issue
Block a user