mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
Add IAM provisioning preflight support (#1250)
* fix(iam): seed provisioning managed policies * feat(iam): support policy simulation preflight * fix(iam): address provisioning preflight review feedback * fix(iam): normalize condition context in evaluator
This commit is contained in:
1 parent
2d958b380f
commit
3acab2bf27
10 files changed
+508
-15
No files matched your search
@@ -103,7 +103,8 @@ public class AwsQueryController {
|
||||
"TagPolicy", "UntagPolicy", "ListPolicyTags",
|
||||
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
|
||||
"GenerateCredentialReport", "GetCredentialReport",
|
||||
"GetAccountSummary", "GetAccountAuthorizationDetails"
|
||||
"GetAccountSummary", "GetAccountAuthorizationDetails",
|
||||
"SimulatePrincipalPolicy"
|
||||
);
|
||||
|
||||
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
|
||||
|
||||
@@ -39,6 +39,8 @@ final class AwsManagedPolicies {
|
||||
"Provides full access to Amazon DynamoDB via the AWS Management Console."),
|
||||
new ManagedPolicyDef("AmazonEC2FullAccess", "/",
|
||||
"Provides full access to Amazon EC2 via the AWS Management Console."),
|
||||
new ManagedPolicyDef("AmazonEC2ContainerRegistryReadOnly", "/",
|
||||
"Provides read-only access to Amazon EC2 Container Registry repositories."),
|
||||
new ManagedPolicyDef("AmazonSQSFullAccess", "/",
|
||||
"Provides full access to Amazon SQS via the AWS Management Console."),
|
||||
new ManagedPolicyDef("AmazonSNSFullAccess", "/",
|
||||
@@ -47,6 +49,8 @@ final class AwsManagedPolicies {
|
||||
"Provides full access to Amazon VPC via the AWS Management Console."),
|
||||
new ManagedPolicyDef("CloudWatchFullAccess", "/",
|
||||
"Provides full access to CloudWatch."),
|
||||
new ManagedPolicyDef("CloudWatchAgentServerPolicy", "/",
|
||||
"Provides permissions required to use the CloudWatch agent on servers."),
|
||||
new ManagedPolicyDef("AWSLambdaFullAccess", "/",
|
||||
"Provides full access to Lambda, S3, DynamoDB, CloudWatch Metrics and Logs."),
|
||||
|
||||
@@ -108,6 +112,8 @@ final class AwsManagedPolicies {
|
||||
"Provides permissions for AWS Systems Manager diagnosis automation execution."),
|
||||
new ManagedPolicyDef("AWS-SSM-RemediationAutomation-ExecutionRolePolicy", "/",
|
||||
"Provides permissions for AWS Systems Manager remediation automation execution."),
|
||||
new ManagedPolicyDef("AmazonSSMManagedInstanceCore", "/",
|
||||
"Provides permissions required for instances to use AWS Systems Manager core service functionality."),
|
||||
|
||||
// SageMaker execution role policies
|
||||
new ManagedPolicyDef("AmazonSageMakerGeospatialExecutionRole", "/service-role/",
|
||||
|
||||
@@ -40,6 +40,22 @@ public class IamPolicyEvaluator {
|
||||
|
||||
public enum Decision { ALLOW, DENY }
|
||||
|
||||
public enum SimulationDecision {
|
||||
ALLOWED("allowed"),
|
||||
EXPLICIT_DENY("explicitDeny"),
|
||||
IMPLICIT_DENY("implicitDeny");
|
||||
|
||||
private final String awsValue;
|
||||
|
||||
SimulationDecision(String awsValue) {
|
||||
this.awsValue = awsValue;
|
||||
}
|
||||
|
||||
public String awsValue() {
|
||||
return awsValue;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamPolicyEvaluator.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -56,7 +72,7 @@ public class IamPolicyEvaluator {
|
||||
* @param resourcePolicies resource-based policy documents (Phase 2); may be null or empty
|
||||
* @param action IAM action, e.g. "s3:GetObject"
|
||||
* @param resource resource ARN, e.g. "arn:aws:s3:::my-bucket/key"
|
||||
* @param conditionCtx condition context key-value pairs (lowercase keys); may be null or empty
|
||||
* @param conditionCtx condition context key-value pairs; may be null or empty
|
||||
* @return {@link Decision#ALLOW} or {@link Decision#DENY}
|
||||
*/
|
||||
public Decision evaluate(CallerContext caller,
|
||||
@@ -64,7 +80,7 @@ public class IamPolicyEvaluator {
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, String> conditionCtx) {
|
||||
Map<String, String> ctx = conditionCtx == null ? Map.of() : conditionCtx;
|
||||
Map<String, String> ctx = normalizeConditionContext(conditionCtx);
|
||||
|
||||
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
|
||||
List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);
|
||||
@@ -119,10 +135,50 @@ public class IamPolicyEvaluator {
|
||||
return evaluate(CallerContext.of(policyDocuments), null, action, resource, conditionCtx);
|
||||
}
|
||||
|
||||
public SimulationDecision simulatePrincipalPolicy(CallerContext caller,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, String> conditionCtx) {
|
||||
Map<String, String> ctx = normalizeConditionContext(conditionCtx);
|
||||
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
|
||||
List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.sessionPolicyDocument()));
|
||||
List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.boundaryPolicyDocument()));
|
||||
|
||||
if (anyExplicitDeny(identityStmts, action, resource, ctx)
|
||||
|| (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx))
|
||||
|| (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) {
|
||||
return SimulationDecision.EXPLICIT_DENY;
|
||||
}
|
||||
if (!anyExplicitAllow(identityStmts, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
if (sessionStmts != null && !anyExplicitAllow(sessionStmts, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
|
||||
return SimulationDecision.IMPLICIT_DENY;
|
||||
}
|
||||
return SimulationDecision.ALLOWED;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Statement matching
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private Map<String, String> normalizeConditionContext(Map<String, String> conditionCtx) {
|
||||
if (conditionCtx == null || conditionCtx.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return conditionCtx.entrySet().stream()
|
||||
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
|
||||
.collect(java.util.stream.Collectors.toMap(
|
||||
entry -> entry.getKey().toLowerCase(java.util.Locale.ROOT),
|
||||
Map.Entry::getValue,
|
||||
(first, ignored) -> first));
|
||||
}
|
||||
|
||||
private boolean anyExplicitDeny(List<PolicyStatement> stmts, String action, String resource,
|
||||
Map<String, String> ctx) {
|
||||
for (PolicyStatement stmt : stmts) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -33,10 +34,12 @@ public class IamQueryHandler {
|
||||
private static final Logger LOG = Logger.getLogger(IamQueryHandler.class);
|
||||
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
|
||||
@Inject
|
||||
public IamQueryHandler(IamService iamService) {
|
||||
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator) {
|
||||
this.iamService = iamService;
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params) {
|
||||
@@ -142,6 +145,9 @@ public class IamQueryHandler {
|
||||
case "PutRolePermissionsBoundary" -> handlePutRolePermissionsBoundary(params);
|
||||
case "DeleteRolePermissionsBoundary" -> handleDeleteRolePermissionsBoundary(params);
|
||||
|
||||
// Policy Simulation
|
||||
case "SimulatePrincipalPolicy" -> handleSimulatePrincipalPolicy(params);
|
||||
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
|
||||
};
|
||||
@@ -711,6 +717,39 @@ public class IamQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
private Response handleSimulatePrincipalPolicy(MultivaluedMap<String, String> params) {
|
||||
String policySourceArn = getParam(params, "PolicySourceArn");
|
||||
CallerContext caller = iamService.resolvePrincipalContext(policySourceArn);
|
||||
List<String> actionNames = extractIndexedValues(params, "ActionNames.member");
|
||||
if (actionNames.isEmpty()) {
|
||||
throw new AwsException("ValidationError", "At least one ActionNames member is required.", 400);
|
||||
}
|
||||
List<String> resourceArns = extractIndexedValues(params, "ResourceArns.member");
|
||||
if (resourceArns.isEmpty()) {
|
||||
resourceArns = List.of("*");
|
||||
}
|
||||
Map<String, String> context = extractContextEntries(params);
|
||||
|
||||
XmlBuilder results = new XmlBuilder().start("EvaluationResults");
|
||||
for (String actionName : actionNames) {
|
||||
for (String resourceArn : resourceArns) {
|
||||
IamPolicyEvaluator.SimulationDecision decision =
|
||||
policyEvaluator.simulatePrincipalPolicy(caller, actionName, resourceArn, context);
|
||||
results.start("member")
|
||||
.elem("EvalActionName", actionName)
|
||||
.elem("EvalResourceName", resourceArn)
|
||||
.elem("EvalDecision", decision.awsValue())
|
||||
.start("MatchedStatements").end("MatchedStatements")
|
||||
.start("MissingContextValues").end("MissingContextValues")
|
||||
.end("member");
|
||||
}
|
||||
}
|
||||
String result = results.end("EvaluationResults")
|
||||
.elem("IsTruncated", false)
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// XML serialization helpers
|
||||
// =========================================================================
|
||||
@@ -854,6 +893,29 @@ public class IamQueryHandler {
|
||||
return keys;
|
||||
}
|
||||
|
||||
private List<String> extractIndexedValues(MultivaluedMap<String, String> params, String prefix) {
|
||||
List<String> values = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String value = params.getFirst(prefix + "." + i);
|
||||
if (value == null) break;
|
||||
values.add(value);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private Map<String, String> extractContextEntries(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> context = new HashMap<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("ContextEntries.member." + i + ".ContextKeyName");
|
||||
if (name == null) break;
|
||||
String value = params.getFirst("ContextEntries.member." + i + ".ContextKeyValues.member.1");
|
||||
if (value != null) {
|
||||
context.put(name, value);
|
||||
}
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
private String getParam(MultivaluedMap<String, String> params, String name) {
|
||||
return params.getFirst(name);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ public class IamService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamService.class);
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final String DEFAULT_DEPLOYER_USER = "floci-deployer";
|
||||
private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci";
|
||||
private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci";
|
||||
|
||||
private final StorageBackend<String, IamUser> users;
|
||||
private final StorageBackend<String, IamGroup> groups;
|
||||
@@ -80,6 +83,11 @@ public class IamService {
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void seedDefaults() {
|
||||
seedAwsManagedPolicies();
|
||||
seedDefaultDeployerPrincipal();
|
||||
}
|
||||
|
||||
void seedAwsManagedPolicies() {
|
||||
int seeded = 0;
|
||||
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
|
||||
@@ -98,6 +106,30 @@ public class IamService {
|
||||
}
|
||||
}
|
||||
|
||||
private void seedDefaultDeployerPrincipal() {
|
||||
String adminPolicyArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
|
||||
IamUser user = users.get(DEFAULT_DEPLOYER_USER)
|
||||
.orElseGet(() -> {
|
||||
String userId = "AIDA" + randomId(16);
|
||||
String arn = iamArn("user", "/", DEFAULT_DEPLOYER_USER);
|
||||
IamUser seededUser = new IamUser(userId, DEFAULT_DEPLOYER_USER, "/", arn);
|
||||
users.put(DEFAULT_DEPLOYER_USER, seededUser);
|
||||
LOG.infov("Seeded default IAM deployer user: {0}", DEFAULT_DEPLOYER_USER);
|
||||
return seededUser;
|
||||
});
|
||||
if (!user.getAttachedPolicyArns().contains(adminPolicyArn)) {
|
||||
user.getAttachedPolicyArns().add(adminPolicyArn);
|
||||
users.put(DEFAULT_DEPLOYER_USER, user);
|
||||
}
|
||||
if (accessKeys.get(DEFAULT_DEPLOYER_ACCESS_KEY_ID).isEmpty()) {
|
||||
accessKeys.put(DEFAULT_DEPLOYER_ACCESS_KEY_ID, new AccessKey(
|
||||
DEFAULT_DEPLOYER_ACCESS_KEY_ID,
|
||||
DEFAULT_DEPLOYER_SECRET_ACCESS_KEY,
|
||||
DEFAULT_DEPLOYER_USER));
|
||||
LOG.infov("Seeded default IAM deployer access key: {0}", DEFAULT_DEPLOYER_ACCESS_KEY_ID);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Users
|
||||
// =========================================================================
|
||||
@@ -893,6 +925,56 @@ public class IamService {
|
||||
return ctx == null ? null : ctx.identityPolicies();
|
||||
}
|
||||
|
||||
public Optional<String> resolveCallerArn(String accessKeyId) {
|
||||
if (accessKeyId == null || accessKeyId.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
|
||||
if (akOpt.isPresent()) {
|
||||
String userName = akOpt.get().getUserName();
|
||||
return users.get(userName).map(IamUser::getArn);
|
||||
}
|
||||
|
||||
Optional<SessionCredential> sessionOpt = sessions.get(accessKeyId);
|
||||
if (sessionOpt.isPresent()) {
|
||||
SessionCredential session = sessionOpt.get();
|
||||
if (session.getExpiration() != null && session.getExpiration().isBefore(java.time.Instant.now())) {
|
||||
sessions.delete(accessKeyId);
|
||||
return Optional.empty();
|
||||
}
|
||||
String roleArn = session.getRoleArn();
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
|
||||
return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/floci-session").toString());
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public CallerContext resolvePrincipalContext(String principalArn) {
|
||||
if (principalArn == null || principalArn.isBlank()) {
|
||||
throw new AwsException("ValidationError", "PolicySourceArn is required.", 400);
|
||||
}
|
||||
if (principalArn.contains(":user/")) {
|
||||
String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = collectUserPolicies(userName);
|
||||
if (identityPolicies == null) {
|
||||
throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null, resolveUserBoundaryDocument(userName));
|
||||
}
|
||||
if (principalArn.contains(":role/")) {
|
||||
String roleName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
|
||||
List<String> identityPolicies = collectRolePolicies(principalArn);
|
||||
if (identityPolicies == null) {
|
||||
throw new AwsException("NoSuchEntity", "Role " + roleName + " cannot be found.", 404);
|
||||
}
|
||||
return new CallerContext(identityPolicies, null, resolveRoleBoundaryDocument(principalArn));
|
||||
}
|
||||
throw new AwsException("InvalidInput", "PolicySourceArn must identify an IAM user or role.", 400);
|
||||
}
|
||||
|
||||
private String resolveUserBoundaryDocument(String userName) {
|
||||
return users.get(userName)
|
||||
.map(IamUser::getPermissionsBoundaryArn)
|
||||
|
||||
@@ -4,10 +4,13 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryController;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.AccountResolver;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -28,11 +31,16 @@ public class StsQueryHandler {
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
private final IamService iamService;
|
||||
private final AccountResolver accountResolver;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Context
|
||||
HttpHeaders headers;
|
||||
|
||||
@Inject
|
||||
public StsQueryHandler(IamService iamService, RegionResolver regionResolver) {
|
||||
public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver) {
|
||||
this.iamService = iamService;
|
||||
this.accountResolver = accountResolver;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@@ -91,10 +99,14 @@ public class StsQueryHandler {
|
||||
|
||||
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
|
||||
String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
|
||||
String arn = iamService.resolveCallerArn(accessKeyId)
|
||||
.orElse(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
|
||||
String result = new XmlBuilder()
|
||||
.elem("UserId", accountId)
|
||||
.elem("Account", accountId)
|
||||
.elem("Arn", AwsArnUtils.Arn.of("iam", "", accountId, "root").toString())
|
||||
.elem("Arn", arn)
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetCallerIdentity", AwsNamespaces.STS, result)).build();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user