mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(iam): enforce iam when it turned on (#411)
* fix: iam enforment feature * fix: adding iam enforment test * fix: adding iam enforment and update documentation
This commit is contained in:
1 parent
0c4eb1380c
commit
cfe48dfabe
21 files changed
+1756
-1
No files matched your search
@@ -270,6 +270,9 @@ public interface EmulatorConfig {
|
||||
interface IamServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean enforcementEnabled();
|
||||
}
|
||||
|
||||
interface ElastiCacheServiceConfig {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
|
||||
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.ResourceArnBuilder;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* JAX-RS filter that enforces IAM policies on every incoming request when
|
||||
* {@code floci.iam.enforcement-enabled = true}.
|
||||
*
|
||||
* <p>Bypass rules (request is always allowed through):
|
||||
* <ul>
|
||||
* <li>Enforcement is disabled (default)</li>
|
||||
* <li>Access key is {@code "test"} (root/admin stand-in)</li>
|
||||
* <li>Access key is not found in the IAM store (backward-compatible with pre-existing credentials)</li>
|
||||
* <li>The action cannot be resolved (unknown mapping → permissive)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Phase 1 evaluates identity-based policies only.
|
||||
* Resource-based policies (S3 bucket policy, Lambda resource policy, etc.) are Phase 2.
|
||||
*/
|
||||
@Provider
|
||||
@ApplicationScoped
|
||||
public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamEnforcementFilter.class);
|
||||
|
||||
/** Extracts the access key ID from an AWS SigV4 Authorization header. */
|
||||
private static final Pattern AKID_PATTERN =
|
||||
Pattern.compile("Credential=([^/]+)/");
|
||||
|
||||
/** Extracts the credential-scope service name (e.g. "s3", "lambda"). */
|
||||
private static final Pattern SERVICE_PATTERN =
|
||||
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final IamActionRegistry actionRegistry;
|
||||
private final ResourceArnBuilder arnBuilder;
|
||||
|
||||
@Inject
|
||||
public IamEnforcementFilter(EmulatorConfig config,
|
||||
IamService iamService,
|
||||
IamPolicyEvaluator evaluator,
|
||||
IamActionRegistry actionRegistry,
|
||||
ResourceArnBuilder arnBuilder) {
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.actionRegistry = actionRegistry;
|
||||
this.arnBuilder = arnBuilder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String auth = ctx.getHeaderString("Authorization");
|
||||
if (auth == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String akid = extractAccessKeyId(auth);
|
||||
if (akid == null || "test".equals(akid)) {
|
||||
return; // root bypass
|
||||
}
|
||||
|
||||
String credentialScope = extractCredentialScope(auth);
|
||||
if (credentialScope == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String action = actionRegistry.resolve(credentialScope, ctx);
|
||||
if (action == null) {
|
||||
return; // unknown action → ALLOW (permissive)
|
||||
}
|
||||
|
||||
List<String> policies = iamService.resolveCallerPolicies(akid);
|
||||
if (policies == null) {
|
||||
return; // unknown access key → bypass (backward-compat)
|
||||
}
|
||||
|
||||
String region = config.defaultRegion();
|
||||
String accountId = config.defaultAccountId();
|
||||
String resource = arnBuilder.build(credentialScope, ctx, region, accountId);
|
||||
|
||||
Decision decision = evaluator.evaluate(policies, action, resource);
|
||||
if (decision == Decision.DENY) {
|
||||
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
|
||||
ctx.abortWith(accessDeniedResponse(action));
|
||||
}
|
||||
}
|
||||
|
||||
private String extractAccessKeyId(String auth) {
|
||||
Matcher m = AKID_PATTERN.matcher(auth);
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
|
||||
private String extractCredentialScope(String auth) {
|
||||
Matcher m = SERVICE_PATTERN.matcher(auth);
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
|
||||
private Response accessDeniedResponse(String action) {
|
||||
String message = "User is not authorized to perform: " + action;
|
||||
String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}";
|
||||
return Response.status(403)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(body)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Maps (credentialScope, httpMethod, requestPath) → IAM action string.
|
||||
*
|
||||
* For Query-protocol services (SQS, SNS, IAM, STS, ...) the Action form
|
||||
* parameter is mapped directly to {@code <service>:<Action>}.
|
||||
*
|
||||
* For REST-JSON services the first matching rule wins (specific before wildcard).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamActionRegistry {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamActionRegistry.class);
|
||||
|
||||
private record ActionRule(String service, String method, Pattern pathPattern, String action) {}
|
||||
|
||||
private static final List<ActionRule> RULES = List.of(
|
||||
// ── S3 ─────────────────────────────────────────────────────────────────
|
||||
rule("s3", "GET", "^/?$", "s3:ListAllMyBuckets"),
|
||||
rule("s3", "PUT", "^/[^/]+/?$", "s3:CreateBucket"),
|
||||
rule("s3", "DELETE", "^/[^/]+/?$", "s3:DeleteBucket"),
|
||||
rule("s3", "HEAD", "^/[^/]+/?$", "s3:ListBucket"),
|
||||
rule("s3", "GET", "^/[^/]+/?$", "s3:ListBucket"),
|
||||
rule("s3", "GET", "^/[^/]+/.+", "s3:GetObject"),
|
||||
rule("s3", "PUT", "^/[^/]+/.+", "s3:PutObject"),
|
||||
rule("s3", "DELETE", "^/[^/]+/.+", "s3:DeleteObject"),
|
||||
rule("s3", "HEAD", "^/[^/]+/.+", "s3:GetObject"),
|
||||
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────
|
||||
rule("lambda", "GET", ".*/functions$", "lambda:ListFunctions"),
|
||||
rule("lambda", "POST", ".*/functions$", "lambda:CreateFunction"),
|
||||
rule("lambda", "GET", ".*/functions/[^/]+$", "lambda:GetFunction"),
|
||||
rule("lambda", "PUT", ".*/functions/[^/]+/code$", "lambda:UpdateFunctionCode"),
|
||||
rule("lambda", "PUT", ".*/functions/[^/]+/configuration$", "lambda:UpdateFunctionConfiguration"),
|
||||
rule("lambda", "DELETE", ".*/functions/[^/]+$", "lambda:DeleteFunction"),
|
||||
rule("lambda", "POST", ".*/functions/[^/]+/invocations$", "lambda:InvokeFunction"),
|
||||
rule("lambda", "GET", ".*/functions/[^/]+/aliases$", "lambda:ListAliases"),
|
||||
rule("lambda", "POST", ".*/functions/[^/]+/aliases$", "lambda:CreateAlias"),
|
||||
rule("lambda", "GET", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:GetAlias"),
|
||||
rule("lambda", "PUT", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:UpdateAlias"),
|
||||
rule("lambda", "DELETE", ".*/functions/[^/]+/aliases/[^/]+$", "lambda:DeleteAlias"),
|
||||
rule("lambda", "GET", ".*/functions/[^/]+/policy$", "lambda:GetPolicy"),
|
||||
rule("lambda", "POST", ".*/functions/[^/]+/policy$", "lambda:AddPermission"),
|
||||
rule("lambda", "DELETE", ".*/functions/[^/]+/policy/.+", "lambda:RemovePermission"),
|
||||
rule("lambda", "GET", ".*/event-source-mappings$", "lambda:ListEventSourceMappings"),
|
||||
rule("lambda", "POST", ".*/event-source-mappings$", "lambda:CreateEventSourceMapping"),
|
||||
rule("lambda", "DELETE", ".*/event-source-mappings/[^/]+$", "lambda:DeleteEventSourceMapping"),
|
||||
rule("lambda", "GET", ".*/functions/[^/]+/url$", "lambda:GetFunctionUrlConfig"),
|
||||
rule("lambda", "POST", ".*/functions/[^/]+/url$", "lambda:CreateFunctionUrlConfig"),
|
||||
rule("lambda", "PUT", ".*/functions/[^/]+/url$", "lambda:UpdateFunctionUrlConfig"),
|
||||
rule("lambda", "DELETE", ".*/functions/[^/]+/url$", "lambda:DeleteFunctionUrlConfig"),
|
||||
|
||||
// ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──
|
||||
// Handled via Query-style action extraction in the filter
|
||||
|
||||
// ── API Gateway ────────────────────────────────────────────────────────
|
||||
rule("apigateway", "GET", ".*/restapis$", "apigateway:GET"),
|
||||
rule("apigateway", "POST", ".*/restapis$", "apigateway:POST"),
|
||||
rule("apigateway", "GET", ".*/restapis/.+", "apigateway:GET"),
|
||||
rule("apigateway", "PUT", ".*/restapis/.+", "apigateway:PUT"),
|
||||
rule("apigateway", "PATCH", ".*/restapis/.+", "apigateway:PATCH"),
|
||||
rule("apigateway", "DELETE", ".*/restapis/.+", "apigateway:DELETE"),
|
||||
rule("apigateway", "POST", ".*/restapis/.+", "apigateway:POST"),
|
||||
|
||||
// ── Kinesis ────────────────────────────────────────────────────────────
|
||||
rule("kinesis", "POST", ".*", "kinesis:*")
|
||||
);
|
||||
|
||||
private static ActionRule rule(String service, String method, String path, String action) {
|
||||
return new ActionRule(service, method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the IAM action for an incoming request.
|
||||
*
|
||||
* For Query-protocol services the action comes directly from the {@code Action}
|
||||
* form param (e.g. {@code sqs:SendMessage}).
|
||||
*
|
||||
* For JSON 1.1 protocol the action comes from {@code X-Amz-Target}
|
||||
* (e.g. {@code DynamoDB_20120810.PutItem} → {@code dynamodb:PutItem}).
|
||||
*
|
||||
* For REST-JSON services the action is derived from the path rule table.
|
||||
*
|
||||
* Returns {@code null} when the action is unknown (caller treats this as ALLOW).
|
||||
*/
|
||||
public String resolve(String credentialScope, ContainerRequestContext ctx) {
|
||||
// Query-protocol: Action form param → service:Action
|
||||
String queryAction = ctx.getUriInfo().getQueryParameters().getFirst("Action");
|
||||
if (queryAction != null && !queryAction.isBlank()) {
|
||||
return credentialScope + ":" + queryAction;
|
||||
}
|
||||
|
||||
// JSON 1.1: X-Amz-Target → service:OperationName
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
if (target != null && target.contains(".")) {
|
||||
String operationName = target.substring(target.lastIndexOf('.') + 1);
|
||||
return credentialScope + ":" + operationName;
|
||||
}
|
||||
|
||||
// REST-JSON: match against rule table
|
||||
String method = ctx.getMethod().toUpperCase();
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
if (!path.startsWith("/")) path = "/" + path;
|
||||
|
||||
for (ActionRule rule : RULES) {
|
||||
if (rule.service().equals(credentialScope)
|
||||
&& rule.method().equals(method)
|
||||
&& rule.pathPattern().matcher(path).find()) {
|
||||
return rule.action();
|
||||
}
|
||||
}
|
||||
|
||||
LOG.debugv("No action mapping for {0} {1} {2} — defaulting to ALLOW", credentialScope, method, path);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyStatement;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Evaluates IAM policy documents against a requested action and resource.
|
||||
*
|
||||
* <p>Implements the AWS policy evaluation logic across Phases 1-4:
|
||||
* <ul>
|
||||
* <li>Phase 1: identity-based policies (inline + attached + groups)</li>
|
||||
* <li>Phase 2: resource-based policies (same-account grant semantics)</li>
|
||||
* <li>Phase 3: session policies + permission boundaries</li>
|
||||
* <li>Phase 4: condition operators, NotAction, NotResource</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Evaluation algorithm (AWS order of precedence):
|
||||
* <ol>
|
||||
* <li>Explicit Deny in ANY policy → DENY</li>
|
||||
* <li>identityAllow OR resourceAllow</li>
|
||||
* <li>AND (no session policy OR sessionAllow)</li>
|
||||
* <li>AND (no boundary OR boundaryAllow)</li>
|
||||
* <li>→ ALLOW</li>
|
||||
* <li>Otherwise → DENY (implicit)</li>
|
||||
* </ol>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamPolicyEvaluator {
|
||||
|
||||
public enum Decision { ALLOW, DENY }
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamPolicyEvaluator.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public IamPolicyEvaluator(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full evaluation including resource policies, session policy, boundary, and conditions.
|
||||
*
|
||||
* @param caller identity context (identity policies, optional session policy, optional boundary)
|
||||
* @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
|
||||
* @return {@link Decision#ALLOW} or {@link Decision#DENY}
|
||||
*/
|
||||
public Decision evaluate(CallerContext caller,
|
||||
List<String> resourcePolicies,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, String> conditionCtx) {
|
||||
Map<String, String> ctx = conditionCtx == null ? Map.of() : conditionCtx;
|
||||
|
||||
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
|
||||
List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);
|
||||
List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.sessionPolicyDocument()));
|
||||
List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
|
||||
? null : parseAll(List.of(caller.boundaryPolicyDocument()));
|
||||
|
||||
// 1. Explicit deny in ANY policy → DENY immediately
|
||||
if (anyExplicitDeny(identityStmts, action, resource, ctx)
|
||||
|| anyExplicitDeny(resourceStmts, action, resource, ctx)
|
||||
|| (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx))
|
||||
|| (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
// 2. Base grant: identity OR resource-based policy must allow
|
||||
boolean identityAllow = anyExplicitAllow(identityStmts, action, resource, ctx);
|
||||
boolean resourceAllow = anyExplicitAllow(resourceStmts, action, resource, ctx);
|
||||
if (!identityAllow && !resourceAllow) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
// 3. Session policy (if present) must also allow (intersection)
|
||||
if (sessionStmts != null && !anyExplicitAllow(sessionStmts, action, resource, ctx)) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
// 4. Permission boundary (if present) must also allow (caps maximum permissions)
|
||||
if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
return Decision.ALLOW;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience overload: identity policies only, no conditions.
|
||||
* Backward-compatible with Phase 1 callers.
|
||||
*/
|
||||
public Decision evaluate(List<String> policyDocuments, String action, String resource) {
|
||||
return evaluate(CallerContext.of(policyDocuments), null, action, resource, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a standalone set of policy documents — used by SimulateCustomPolicy.
|
||||
*/
|
||||
public Decision simulateCustomPolicy(List<String> policyDocuments,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, String> conditionCtx) {
|
||||
return evaluate(CallerContext.of(policyDocuments), null, action, resource, conditionCtx);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Statement matching
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private boolean anyExplicitDeny(List<PolicyStatement> stmts, String action, String resource,
|
||||
Map<String, String> ctx) {
|
||||
for (PolicyStatement stmt : stmts) {
|
||||
if (stmt.isDeny() && matchesStatement(stmt, action, resource, ctx)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean anyExplicitAllow(List<PolicyStatement> stmts, String action, String resource,
|
||||
Map<String, String> ctx) {
|
||||
for (PolicyStatement stmt : stmts) {
|
||||
if (stmt.isAllow() && matchesStatement(stmt, action, resource, ctx)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
|
||||
Map<String, String> ctx) {
|
||||
return matchesAction(stmt, action)
|
||||
&& matchesResource(stmt, resource)
|
||||
&& matchesConditions(stmt.getConditions(), ctx);
|
||||
}
|
||||
|
||||
/** Action: matches if any Action pattern matches; NotAction: matches if NO pattern matches. */
|
||||
private boolean matchesAction(PolicyStatement stmt, String action) {
|
||||
if (stmt.getActions() != null) {
|
||||
return matchesAny(stmt.getActions(), action);
|
||||
}
|
||||
if (stmt.getNotActions() != null) {
|
||||
return !matchesAny(stmt.getNotActions(), action);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */
|
||||
private boolean matchesResource(PolicyStatement stmt, String resource) {
|
||||
if (stmt.getResources() != null) {
|
||||
return matchesAny(stmt.getResources(), resource);
|
||||
}
|
||||
if (stmt.getNotResources() != null) {
|
||||
return !matchesAny(stmt.getNotResources(), resource);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesAny(List<String> patterns, String value) {
|
||||
if (patterns == null) {
|
||||
return false;
|
||||
}
|
||||
for (String pattern : patterns) {
|
||||
if (globMatches(pattern, value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Condition evaluation (Phase 4)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Evaluates all condition blocks. AND between blocks, OR within each block's value list.
|
||||
* Returns true if ALL blocks pass (or there are no conditions).
|
||||
*/
|
||||
private boolean matchesConditions(Map<String, Map<String, List<String>>> conditions,
|
||||
Map<String, String> ctx) {
|
||||
if (conditions == null || conditions.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (Map.Entry<String, Map<String, List<String>>> entry : conditions.entrySet()) {
|
||||
if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean evaluateConditionBlock(String operator,
|
||||
Map<String, List<String>> keyValueMap,
|
||||
Map<String, String> ctx) {
|
||||
boolean ifExists = operator.endsWith("IfExists");
|
||||
String baseOp = ifExists ? operator.substring(0, operator.length() - "IfExists".length()) : operator;
|
||||
|
||||
for (Map.Entry<String, List<String>> entry : keyValueMap.entrySet()) {
|
||||
String condKey = entry.getKey().toLowerCase();
|
||||
List<String> condValues = entry.getValue();
|
||||
String ctxValue = ctx.get(condKey);
|
||||
|
||||
if (ctxValue == null) {
|
||||
if ("Null".equalsIgnoreCase(baseOp)) {
|
||||
// Null: {key: "true"} → key must be absent → pass when any condValue is "true"
|
||||
boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
|
||||
if (!expectAbsent) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ifExists) {
|
||||
continue; // key missing + IfExists → pass this key
|
||||
}
|
||||
return false; // key missing, no IfExists → fail entire block
|
||||
}
|
||||
|
||||
if ("Null".equalsIgnoreCase(baseOp)) {
|
||||
// Key is present — Null:{key:"true"} should fail, Null:{key:"false"} should pass
|
||||
boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
|
||||
if (expectAbsent) {
|
||||
return false; // expected absent but key has value
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// OR across condValues for this key
|
||||
boolean keyMatch = false;
|
||||
for (String condValue : condValues) {
|
||||
if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
|
||||
keyMatch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!keyMatch) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue) {
|
||||
return switch (operator) {
|
||||
case "StringEquals" -> ctxValue.equals(condValue);
|
||||
case "StringNotEquals" -> !ctxValue.equals(condValue);
|
||||
case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(condValue);
|
||||
case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(condValue);
|
||||
case "StringLike" -> globMatches(condValue, ctxValue);
|
||||
case "StringNotLike" -> !globMatches(condValue, ctxValue);
|
||||
case "ArnEquals", "ArnLike" -> globMatches(condValue, ctxValue);
|
||||
case "ArnNotEquals", "ArnNotLike"-> !globMatches(condValue, ctxValue);
|
||||
case "Bool" -> Boolean.parseBoolean(condValue) == Boolean.parseBoolean(ctxValue);
|
||||
case "NumericEquals" -> compareNumeric(ctxValue, condValue) == 0;
|
||||
case "NumericNotEquals" -> compareNumeric(ctxValue, condValue) != 0;
|
||||
case "NumericLessThan" -> compareNumeric(ctxValue, condValue) < 0;
|
||||
case "NumericLessThanEquals" -> compareNumeric(ctxValue, condValue) <= 0;
|
||||
case "NumericGreaterThan" -> compareNumeric(ctxValue, condValue) > 0;
|
||||
case "NumericGreaterThanEquals" -> compareNumeric(ctxValue, condValue) >= 0;
|
||||
case "DateEquals" -> compareDates(ctxValue, condValue) == 0;
|
||||
case "DateNotEquals" -> compareDates(ctxValue, condValue) != 0;
|
||||
case "DateLessThan" -> compareDates(ctxValue, condValue) < 0;
|
||||
case "DateLessThanEquals" -> compareDates(ctxValue, condValue) <= 0;
|
||||
case "DateGreaterThan" -> compareDates(ctxValue, condValue) > 0;
|
||||
case "DateGreaterThanEquals" -> compareDates(ctxValue, condValue) >= 0;
|
||||
case "IpAddress" -> matchesIpAddress(condValue, ctxValue);
|
||||
case "NotIpAddress" -> !matchesIpAddress(condValue, ctxValue);
|
||||
default -> {
|
||||
LOG.warnv("Unsupported condition operator: {0} — treating as no-match", operator);
|
||||
yield false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private int compareNumeric(String ctxValue, String condValue) {
|
||||
try {
|
||||
return Double.compare(Double.parseDouble(ctxValue), Double.parseDouble(condValue));
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private int compareDates(String ctxValue, String condValue) {
|
||||
try {
|
||||
return Instant.parse(ctxValue).compareTo(Instant.parse(condValue));
|
||||
} catch (Exception e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matchesIpAddress(String condValue, String ctxValue) {
|
||||
if (condValue.contains("/")) {
|
||||
return matchesCidr(condValue, ctxValue);
|
||||
}
|
||||
return condValue.equals(ctxValue);
|
||||
}
|
||||
|
||||
private boolean matchesCidr(String cidr, String ip) {
|
||||
try {
|
||||
String[] parts = cidr.split("/");
|
||||
int prefix = Integer.parseInt(parts[1]);
|
||||
long cidrAddr = ipToLong(parts[0]);
|
||||
long ipAddr = ipToLong(ip);
|
||||
long mask = prefix == 0 ? 0L : (0xFFFFFFFFL << (32 - prefix)) & 0xFFFFFFFFL;
|
||||
return (cidrAddr & mask) == (ipAddr & mask);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private long ipToLong(String ip) {
|
||||
String[] octets = ip.split("\\.");
|
||||
long result = 0;
|
||||
for (String octet : octets) {
|
||||
result = (result << 8) | Integer.parseInt(octet);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Glob matching (case-insensitive, supports * and ?)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Case-insensitive glob matching supporting {@code *} (any sequence) and {@code ?} (any char).
|
||||
*/
|
||||
public static boolean globMatches(String pattern, String value) {
|
||||
if (pattern == null || value == null) {
|
||||
return false;
|
||||
}
|
||||
return globMatchesHelper(pattern.toLowerCase(), value.toLowerCase(), 0, 0);
|
||||
}
|
||||
|
||||
private static boolean globMatchesHelper(String pat, String val, int pi, int vi) {
|
||||
while (pi < pat.length() && vi < val.length()) {
|
||||
char p = pat.charAt(pi);
|
||||
if (p == '*') {
|
||||
while (pi < pat.length() && pat.charAt(pi) == '*') {
|
||||
pi++;
|
||||
}
|
||||
if (pi == pat.length()) {
|
||||
return true;
|
||||
}
|
||||
for (int i = vi; i <= val.length(); i++) {
|
||||
if (globMatchesHelper(pat, val, pi, i)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} else if (p == '?' || p == val.charAt(vi)) {
|
||||
pi++;
|
||||
vi++;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while (pi < pat.length() && pat.charAt(pi) == '*') {
|
||||
pi++;
|
||||
}
|
||||
return pi == pat.length() && vi == val.length();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Policy document parsing
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private List<PolicyStatement> parseAll(List<String> documents) {
|
||||
List<PolicyStatement> result = new ArrayList<>();
|
||||
if (documents == null) {
|
||||
return result;
|
||||
}
|
||||
for (String doc : documents) {
|
||||
try {
|
||||
result.addAll(parseStatements(doc));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse policy document: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<PolicyStatement> parseStatements(String document) throws Exception {
|
||||
JsonNode root = objectMapper.readTree(document);
|
||||
JsonNode stmtNode = root.path("Statement");
|
||||
List<PolicyStatement> result = new ArrayList<>();
|
||||
if (stmtNode.isArray()) {
|
||||
for (JsonNode s : stmtNode) {
|
||||
result.add(parseStatement(s));
|
||||
}
|
||||
} else if (stmtNode.isObject()) {
|
||||
result.add(parseStatement(stmtNode));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private PolicyStatement parseStatement(JsonNode stmt) {
|
||||
String effect = stmt.path("Effect").asText("Allow");
|
||||
List<String> actions = nodeToList(stmt.get("Action"));
|
||||
List<String> notActions = nodeToList(stmt.get("NotAction"));
|
||||
List<String> resources = nodeToList(stmt.get("Resource"));
|
||||
List<String> notResources= nodeToList(stmt.get("NotResource"));
|
||||
Map<String, Map<String, List<String>>> conditions = parseConditions(stmt.get("Condition"));
|
||||
return new PolicyStatement(
|
||||
effect,
|
||||
actions.isEmpty() ? null : actions,
|
||||
notActions.isEmpty() ? null : notActions,
|
||||
resources.isEmpty() ? null : resources,
|
||||
notResources.isEmpty()? null : notResources,
|
||||
conditions);
|
||||
}
|
||||
|
||||
private Map<String, Map<String, List<String>>> parseConditions(JsonNode condNode) {
|
||||
if (condNode == null || condNode.isNull() || !condNode.isObject()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Map<String, List<String>>> result = new LinkedHashMap<>();
|
||||
condNode.fields().forEachRemaining(opEntry -> {
|
||||
Map<String, List<String>> kvMap = new LinkedHashMap<>();
|
||||
opEntry.getValue().fields().forEachRemaining(kvEntry ->
|
||||
kvMap.put(kvEntry.getKey(), nodeToList(kvEntry.getValue())));
|
||||
result.put(opEntry.getKey(), kvMap);
|
||||
});
|
||||
return result.isEmpty() ? null : result;
|
||||
}
|
||||
|
||||
private List<String> nodeToList(JsonNode node) {
|
||||
List<String> list = new ArrayList<>();
|
||||
if (node == null) {
|
||||
return list;
|
||||
}
|
||||
if (node.isTextual()) {
|
||||
list.add(node.asText());
|
||||
} else if (node.isArray()) {
|
||||
for (JsonNode item : node) {
|
||||
list.add(item.asText());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,12 @@ public class IamQueryHandler {
|
||||
case "RemoveRoleFromInstanceProfile" -> handleRemoveRoleFromInstanceProfile(params);
|
||||
case "ListInstanceProfilesForRole" -> handleListInstanceProfilesForRole(params);
|
||||
|
||||
// Permission Boundaries
|
||||
case "PutUserPermissionsBoundary" -> handlePutUserPermissionsBoundary(params);
|
||||
case "DeleteUserPermissionsBoundary" -> handleDeleteUserPermissionsBoundary(params);
|
||||
case "PutRolePermissionsBoundary" -> handlePutRolePermissionsBoundary(params);
|
||||
case "DeleteRolePermissionsBoundary" -> handleDeleteRolePermissionsBoundary(params);
|
||||
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
|
||||
};
|
||||
@@ -675,6 +681,36 @@ public class IamQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("ListInstanceProfilesForRole", AwsNamespaces.IAM, xml.build())).build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Permission Boundaries
|
||||
// =========================================================================
|
||||
|
||||
private Response handlePutUserPermissionsBoundary(MultivaluedMap<String, String> params) {
|
||||
String userName = getParam(params, "UserName");
|
||||
String boundaryArn = getParam(params, "PermissionsBoundary");
|
||||
iamService.putUserPermissionsBoundary(userName, boundaryArn);
|
||||
return Response.ok(AwsQueryResponse.envelope("PutUserPermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteUserPermissionsBoundary(MultivaluedMap<String, String> params) {
|
||||
String userName = getParam(params, "UserName");
|
||||
iamService.deleteUserPermissionsBoundary(userName);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteUserPermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
private Response handlePutRolePermissionsBoundary(MultivaluedMap<String, String> params) {
|
||||
String roleName = getParam(params, "RoleName");
|
||||
String boundaryArn = getParam(params, "PermissionsBoundary");
|
||||
iamService.putRolePermissionsBoundary(roleName, boundaryArn);
|
||||
return Response.ok(AwsQueryResponse.envelope("PutRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteRolePermissionsBoundary(MultivaluedMap<String, String> params) {
|
||||
String roleName = getParam(params, "RoleName");
|
||||
iamService.deleteRolePermissionsBoundary(roleName);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// XML serialization helpers
|
||||
// =========================================================================
|
||||
|
||||
@@ -11,6 +11,8 @@ 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 io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -18,6 +20,7 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -39,6 +42,7 @@ public class IamService {
|
||||
private final StorageBackend<String, IamPolicy> policies;
|
||||
private final StorageBackend<String, AccessKey> accessKeys;
|
||||
private final StorageBackend<String, InstanceProfile> instanceProfiles;
|
||||
private final StorageBackend<String, SessionCredential> sessions;
|
||||
private final String accountId;
|
||||
|
||||
@Inject
|
||||
@@ -50,6 +54,7 @@ public class IamService {
|
||||
storageFactory.create("iam", "iam-policies.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-access-keys.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-instance-profiles.json", new TypeReference<>() {}),
|
||||
storageFactory.create("iam", "iam-sessions.json", new TypeReference<>() {}),
|
||||
config.defaultAccountId()
|
||||
);
|
||||
}
|
||||
@@ -60,6 +65,7 @@ public class IamService {
|
||||
StorageBackend<String, IamPolicy> policies,
|
||||
StorageBackend<String, AccessKey> accessKeys,
|
||||
StorageBackend<String, InstanceProfile> instanceProfiles,
|
||||
StorageBackend<String, SessionCredential> sessions,
|
||||
String accountId) {
|
||||
this.users = users;
|
||||
this.groups = groups;
|
||||
@@ -67,6 +73,7 @@ public class IamService {
|
||||
this.policies = policies;
|
||||
this.accessKeys = accessKeys;
|
||||
this.instanceProfiles = instanceProfiles;
|
||||
this.sessions = sessions;
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
@@ -799,10 +806,194 @@ public class IamService {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public java.util.Optional<String> findSecretKey(String accessKeyId) {
|
||||
public Optional<String> findSecretKey(String accessKeyId) {
|
||||
return accessKeys.get(accessKeyId).map(AccessKey::getSecretAccessKey);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// IAM Enforcement — session tracking and policy collection
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Stores an assumed-role session so the enforcement filter can resolve its policies.
|
||||
*/
|
||||
public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration) {
|
||||
sessions.put(sessionAccessKeyId, new SessionCredential(sessionAccessKeyId, roleArn, expiration));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores an assumed-role session with an optional inline session policy document.
|
||||
*/
|
||||
public void registerSession(String sessionAccessKeyId, String roleArn, java.time.Instant expiration,
|
||||
String sessionPolicyDocument) {
|
||||
sessions.put(sessionAccessKeyId,
|
||||
new SessionCredential(sessionAccessKeyId, roleArn, expiration, sessionPolicyDocument));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the full caller context for the given access key, including identity policies,
|
||||
* optional session policy, and optional permission boundary.
|
||||
*
|
||||
* <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
|
||||
*/
|
||||
public CallerContext resolveCallerContext(String accessKeyId) {
|
||||
// Check user access keys
|
||||
Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
|
||||
if (akOpt.isPresent()) {
|
||||
String userName = akOpt.get().getUserName();
|
||||
List<String> identityPolicies = collectUserPolicies(userName);
|
||||
String boundaryDoc = resolveUserBoundaryDocument(userName);
|
||||
return new CallerContext(identityPolicies, null, boundaryDoc);
|
||||
}
|
||||
|
||||
// Check assumed-role sessions
|
||||
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 null; // expired — unknown key → bypass
|
||||
}
|
||||
List<String> identityPolicies = collectRolePolicies(session.getRoleArn());
|
||||
String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn());
|
||||
return new CallerContext(identityPolicies, session.getSessionPolicyDocument(), boundaryDoc);
|
||||
}
|
||||
|
||||
// Unknown key — bypass
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all identity-based policy documents applicable to the caller identified
|
||||
* by {@code accessKeyId}.
|
||||
*
|
||||
* <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
|
||||
* Returns an empty list if the key is known but has no policies attached (implicit deny).
|
||||
*
|
||||
* <p>Order: inline policies first, then attached managed policies.
|
||||
*/
|
||||
public List<String> resolveCallerPolicies(String accessKeyId) {
|
||||
CallerContext ctx = resolveCallerContext(accessKeyId);
|
||||
return ctx == null ? null : ctx.identityPolicies();
|
||||
}
|
||||
|
||||
private String resolveUserBoundaryDocument(String userName) {
|
||||
return users.get(userName)
|
||||
.map(IamUser::getPermissionsBoundaryArn)
|
||||
.flatMap(arn -> policies.get(arn))
|
||||
.map(IamPolicy::getDefaultDocument)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private String resolveRoleBoundaryDocument(String roleArn) {
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
|
||||
return roles.get(roleName)
|
||||
.map(IamRole::getPermissionsBoundaryArn)
|
||||
.flatMap(arn -> policies.get(arn))
|
||||
.map(IamPolicy::getDefaultDocument)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Permission Boundaries
|
||||
// =========================================================================
|
||||
|
||||
public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn) {
|
||||
getPolicy(permissionsBoundaryArn); // validate policy exists
|
||||
IamUser user = getUser(userName);
|
||||
user.setPermissionsBoundaryArn(permissionsBoundaryArn);
|
||||
users.put(userName, user);
|
||||
LOG.infov("Set permissions boundary for user {0}: {1}", userName, permissionsBoundaryArn);
|
||||
}
|
||||
|
||||
public void deleteUserPermissionsBoundary(String userName) {
|
||||
IamUser user = getUser(userName);
|
||||
if (user.getPermissionsBoundaryArn() == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"User " + userName + " does not have a permissions boundary.", 404);
|
||||
}
|
||||
user.setPermissionsBoundaryArn(null);
|
||||
users.put(userName, user);
|
||||
LOG.infov("Deleted permissions boundary for user: {0}", userName);
|
||||
}
|
||||
|
||||
public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn) {
|
||||
getPolicy(permissionsBoundaryArn); // validate policy exists
|
||||
IamRole role = getRole(roleName);
|
||||
role.setPermissionsBoundaryArn(permissionsBoundaryArn);
|
||||
roles.put(roleName, role);
|
||||
LOG.infov("Set permissions boundary for role {0}: {1}", roleName, permissionsBoundaryArn);
|
||||
}
|
||||
|
||||
public void deleteRolePermissionsBoundary(String roleName) {
|
||||
IamRole role = getRole(roleName);
|
||||
if (role.getPermissionsBoundaryArn() == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Role " + roleName + " does not have a permissions boundary.", 404);
|
||||
}
|
||||
role.setPermissionsBoundaryArn(null);
|
||||
roles.put(roleName, role);
|
||||
LOG.infov("Deleted permissions boundary for role: {0}", roleName);
|
||||
}
|
||||
|
||||
private List<String> collectUserPolicies(String userName) {
|
||||
Optional<IamUser> userOpt = users.get(userName);
|
||||
if (userOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
IamUser user = userOpt.get();
|
||||
|
||||
// User inline policies
|
||||
List<String> docs = new ArrayList<>(user.getInlinePolicies().values());
|
||||
|
||||
// User attached managed policies
|
||||
for (String arn : user.getAttachedPolicyArns()) {
|
||||
Optional<IamPolicy> p = policies.get(arn);
|
||||
if (p.isPresent() && p.get().getDefaultDocument() != null) {
|
||||
docs.add(p.get().getDefaultDocument());
|
||||
}
|
||||
}
|
||||
|
||||
// Group policies
|
||||
for (String groupName : user.getGroupNames()) {
|
||||
Optional<IamGroup> groupOpt = groups.get(groupName);
|
||||
if (groupOpt.isEmpty()) continue;
|
||||
IamGroup group = groupOpt.get();
|
||||
docs.addAll(group.getInlinePolicies().values());
|
||||
for (String arn : group.getAttachedPolicyArns()) {
|
||||
Optional<IamPolicy> p = policies.get(arn);
|
||||
if (p.isPresent() && p.get().getDefaultDocument() != null) {
|
||||
docs.add(p.get().getDefaultDocument());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return docs;
|
||||
}
|
||||
|
||||
private List<String> collectRolePolicies(String roleArn) {
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
|
||||
Optional<IamRole> roleOpt = roles.get(roleName);
|
||||
if (roleOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
IamRole role = roleOpt.get();
|
||||
List<String> docs = new ArrayList<>();
|
||||
|
||||
// Role inline policies
|
||||
docs.addAll(role.getInlinePolicies().values());
|
||||
|
||||
// Role attached managed policies
|
||||
for (String arn : role.getAttachedPolicyArns()) {
|
||||
Optional<IamPolicy> p = policies.get(arn);
|
||||
if (p.isPresent() && p.get().getDefaultDocument() != null) {
|
||||
docs.add(p.get().getDefaultDocument());
|
||||
}
|
||||
}
|
||||
|
||||
return docs;
|
||||
}
|
||||
|
||||
private String iamArn(String resourceType, String path, String name) {
|
||||
return "arn:aws:iam::" + accountId + ":" + resourceType + path + name;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
|
||||
/**
|
||||
* Constructs the target resource ARN for a request so the policy evaluator
|
||||
* can match it against Resource patterns in policy documents.
|
||||
*
|
||||
* Returns {@code *} when the resource cannot be determined, which matches
|
||||
* permissive wildcard policies.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ResourceArnBuilder {
|
||||
|
||||
public String build(String credentialScope, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
return switch (credentialScope) {
|
||||
case "s3" -> buildS3Arn(path);
|
||||
case "lambda" -> buildLambdaArn(path, region, accountId);
|
||||
case "sqs" -> buildSqsArn(ctx, region, accountId);
|
||||
case "sns" -> buildSnsArn(ctx, region, accountId);
|
||||
case "dynamodb" -> buildDynamoDbArn(ctx, region, accountId);
|
||||
case "kinesis" -> buildKinesisArn(ctx, region, accountId);
|
||||
case "secretsmanager" -> buildSecretsManagerArn(ctx, region, accountId);
|
||||
case "ssm" -> buildSsmArn(ctx, region, accountId);
|
||||
case "kms" -> buildKmsArn(path, region, accountId);
|
||||
default -> "*";
|
||||
};
|
||||
}
|
||||
|
||||
// ── S3 ──────────────────────────────────────────────────────────────────────
|
||||
private String buildS3Arn(String path) {
|
||||
// path: /bucket or /bucket/key
|
||||
String stripped = path.startsWith("/") ? path.substring(1) : path;
|
||||
if (stripped.isEmpty()) {
|
||||
return "arn:aws:s3:::*";
|
||||
}
|
||||
int slash = stripped.indexOf('/');
|
||||
if (slash < 0) {
|
||||
return "arn:aws:s3:::" + stripped;
|
||||
}
|
||||
return "arn:aws:s3:::" + stripped;
|
||||
}
|
||||
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────────
|
||||
private String buildLambdaArn(String path, String region, String accountId) {
|
||||
// path: /2015-03-31/functions/name or similar
|
||||
String name = extractSegmentAfter(path, "functions");
|
||||
if (name == null) return "*";
|
||||
// strip qualifier if present
|
||||
int colon = name.indexOf(':');
|
||||
if (colon > 0) name = name.substring(0, colon);
|
||||
return "arn:aws:lambda:" + region + ":" + accountId + ":function:" + name;
|
||||
}
|
||||
|
||||
// ── SQS ─────────────────────────────────────────────────────────────────────
|
||||
private String buildSqsArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
String queueUrl = ctx.getUriInfo().getQueryParameters().getFirst("QueueUrl");
|
||||
if (queueUrl == null) {
|
||||
// Try form param for Query-protocol
|
||||
queueUrl = firstFormParam(ctx, "QueueUrl");
|
||||
}
|
||||
if (queueUrl != null) {
|
||||
String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1);
|
||||
return "arn:aws:sqs:" + region + ":" + accountId + ":" + queueName;
|
||||
}
|
||||
return "arn:aws:sqs:" + region + ":" + accountId + ":*";
|
||||
}
|
||||
|
||||
// ── SNS ─────────────────────────────────────────────────────────────────────
|
||||
private String buildSnsArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
String topicArn = firstFormParam(ctx, "TopicArn");
|
||||
return topicArn != null ? topicArn : "arn:aws:sns:" + region + ":" + accountId + ":*";
|
||||
}
|
||||
|
||||
// ── DynamoDB ─────────────────────────────────────────────────────────────────
|
||||
private String buildDynamoDbArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
// TableName comes in the JSON body; use wildcard since we don't parse the body here
|
||||
return "arn:aws:dynamodb:" + region + ":" + accountId + ":table/*";
|
||||
}
|
||||
|
||||
// ── Kinesis ──────────────────────────────────────────────────────────────────
|
||||
private String buildKinesisArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
return "arn:aws:kinesis:" + region + ":" + accountId + ":stream/*";
|
||||
}
|
||||
|
||||
// ── Secrets Manager ──────────────────────────────────────────────────────────
|
||||
private String buildSecretsManagerArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
return "arn:aws:secretsmanager:" + region + ":" + accountId + ":secret:*";
|
||||
}
|
||||
|
||||
// ── SSM ──────────────────────────────────────────────────────────────────────
|
||||
private String buildSsmArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
return "arn:aws:ssm:" + region + ":" + accountId + ":parameter/*";
|
||||
}
|
||||
|
||||
// ── KMS ──────────────────────────────────────────────────────────────────────
|
||||
private String buildKmsArn(String path, String region, String accountId) {
|
||||
String keyId = extractSegmentAfter(path, "keys");
|
||||
if (keyId == null) return "arn:aws:kms:" + region + ":" + accountId + ":key/*";
|
||||
return "arn:aws:kms:" + region + ":" + accountId + ":key/" + keyId;
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private String extractSegmentAfter(String path, String segment) {
|
||||
String marker = "/" + segment + "/";
|
||||
int idx = path.indexOf(marker);
|
||||
if (idx < 0) return null;
|
||||
String after = path.substring(idx + marker.length());
|
||||
// take only the first segment (stop at next /)
|
||||
int slash = after.indexOf('/');
|
||||
return slash > 0 ? after.substring(0, slash) : after;
|
||||
}
|
||||
|
||||
private String firstFormParam(ContainerRequestContext ctx, String name) {
|
||||
// Form params are typically available as query params in REST-Assured / JAX-RS
|
||||
String v = ctx.getUriInfo().getQueryParameters().getFirst(name);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,10 @@ public class StsQueryHandler {
|
||||
String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
|
||||
// Register session so IAM enforcement can resolve the role's policies
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
iamService.registerSession(accessKeyId, roleArn, expiration, sessionPolicy);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
.start("AssumedRoleUser")
|
||||
@@ -122,6 +126,9 @@ public class StsQueryHandler {
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com";
|
||||
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
iamService.registerSession(accessKeyId, roleArn, expiration, sessionPolicy);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
.start("AssumedRoleUser")
|
||||
@@ -155,6 +162,8 @@ public class StsQueryHandler {
|
||||
String assumedRoleArn = "arn:aws:sts::" + accountId + ":assumed-role/" + roleName + "/" + sessionName;
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
|
||||
iamService.registerSession(accessKeyId, roleArn, expiration, null);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
.start("AssumedRoleUser")
|
||||
@@ -187,6 +196,10 @@ public class StsQueryHandler {
|
||||
String federatedUserId = accountId + ":" + name;
|
||||
String federatedUserArn = "arn:aws:sts::" + accountId + ":federated-user/" + name;
|
||||
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
// Register federation token so enforcement can scope its policies via session policy
|
||||
iamService.registerSession(accessKeyId, federatedUserArn, expiration, sessionPolicy);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
.start("FederatedUser")
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package io.github.hectorvent.floci.services.iam.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Full IAM context for the calling identity, used by the enforcement filter.
|
||||
*
|
||||
* <p>Carries all inputs required for the complete AWS policy evaluation algorithm:
|
||||
* <ul>
|
||||
* <li>{@code identityPolicies} — inline + attached policies of the user, role, and groups</li>
|
||||
* <li>{@code sessionPolicyDocument} — optional inline session policy from AssumeRole (Phase 3)</li>
|
||||
* <li>{@code boundaryPolicyDocument} — optional permissions boundary document (Phase 3)</li>
|
||||
* </ul>
|
||||
*/
|
||||
public record CallerContext(
|
||||
List<String> identityPolicies,
|
||||
String sessionPolicyDocument,
|
||||
String boundaryPolicyDocument
|
||||
) {
|
||||
/** Convenience factory: no session policy, no boundary. */
|
||||
public static CallerContext of(List<String> identityPolicies) {
|
||||
return new CallerContext(identityPolicies, null, null);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public class IamRole {
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private List<String> attachedPolicyArns = new ArrayList<>();
|
||||
private Map<String, String> inlinePolicies = new HashMap<>();
|
||||
private String permissionsBoundaryArn;
|
||||
|
||||
public IamRole() {}
|
||||
|
||||
@@ -69,4 +70,7 @@ public class IamRole {
|
||||
|
||||
public Map<String, String> getInlinePolicies() { return inlinePolicies; }
|
||||
public void setInlinePolicies(Map<String, String> inlinePolicies) { this.inlinePolicies = inlinePolicies; }
|
||||
|
||||
public String getPermissionsBoundaryArn() { return permissionsBoundaryArn; }
|
||||
public void setPermissionsBoundaryArn(String permissionsBoundaryArn) { this.permissionsBoundaryArn = permissionsBoundaryArn; }
|
||||
}
|
||||
@@ -23,6 +23,7 @@ public class IamUser {
|
||||
private List<String> groupNames = new ArrayList<>();
|
||||
private List<String> attachedPolicyArns = new ArrayList<>();
|
||||
private Map<String, String> inlinePolicies = new HashMap<>();
|
||||
private String permissionsBoundaryArn;
|
||||
|
||||
public IamUser() {}
|
||||
|
||||
@@ -63,4 +64,7 @@ public class IamUser {
|
||||
|
||||
public Map<String, String> getInlinePolicies() { return inlinePolicies; }
|
||||
public void setInlinePolicies(Map<String, String> inlinePolicies) { this.inlinePolicies = inlinePolicies; }
|
||||
|
||||
public String getPermissionsBoundaryArn() { return permissionsBoundaryArn; }
|
||||
public void setPermissionsBoundaryArn(String permissionsBoundaryArn) { this.permissionsBoundaryArn = permissionsBoundaryArn; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.iam.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A single parsed statement from an IAM policy document.
|
||||
*
|
||||
* <p>Supports Phase 1 (actions, resources), Phase 4 (NotAction, NotResource, Condition).
|
||||
*/
|
||||
public class PolicyStatement {
|
||||
|
||||
private final String effect; // "Allow" or "Deny"
|
||||
private final List<String> actions; // IAM action patterns; null when notActions is set
|
||||
private final List<String> notActions; // NotAction patterns; null when actions is set
|
||||
private final List<String> resources; // resource ARN patterns; null when notResources is set
|
||||
private final List<String> notResources;// NotResource patterns; null when resources is set
|
||||
// Condition: outer key = operator (e.g. "StringEquals"), inner key = context key, value = list of values
|
||||
private final Map<String, Map<String, List<String>>> conditions;
|
||||
|
||||
public PolicyStatement(String effect,
|
||||
List<String> actions,
|
||||
List<String> notActions,
|
||||
List<String> resources,
|
||||
List<String> notResources,
|
||||
Map<String, Map<String, List<String>>> conditions) {
|
||||
this.effect = effect;
|
||||
this.actions = actions;
|
||||
this.notActions = notActions;
|
||||
this.resources = resources;
|
||||
this.notResources = notResources;
|
||||
this.conditions = conditions;
|
||||
}
|
||||
|
||||
/** Convenience constructor for simple allow/deny without conditions or Not* fields. */
|
||||
public PolicyStatement(String effect, List<String> actions, List<String> resources) {
|
||||
this(effect, actions, null, resources, null, null);
|
||||
}
|
||||
|
||||
public String getEffect() { return effect; }
|
||||
public List<String> getActions() { return actions; }
|
||||
public List<String> getNotActions() { return notActions; }
|
||||
public List<String> getResources() { return resources; }
|
||||
public List<String> getNotResources() { return notResources; }
|
||||
public Map<String, Map<String, List<String>>> getConditions() { return conditions; }
|
||||
|
||||
public boolean isDeny() { return "Deny".equalsIgnoreCase(effect); }
|
||||
public boolean isAllow() { return "Allow".equalsIgnoreCase(effect); }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.github.hectorvent.floci.services.iam.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SessionCredential {
|
||||
|
||||
private String accessKeyId;
|
||||
private String roleArn;
|
||||
private Instant expiration;
|
||||
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
|
||||
private String sessionPolicyDocument;
|
||||
|
||||
public SessionCredential() {}
|
||||
|
||||
public SessionCredential(String accessKeyId, String roleArn, Instant expiration) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.roleArn = roleArn;
|
||||
this.expiration = expiration;
|
||||
}
|
||||
|
||||
public SessionCredential(String accessKeyId, String roleArn, Instant expiration, String sessionPolicyDocument) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.roleArn = roleArn;
|
||||
this.expiration = expiration;
|
||||
this.sessionPolicyDocument = sessionPolicyDocument;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() { return accessKeyId; }
|
||||
public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
|
||||
|
||||
public String getRoleArn() { return roleArn; }
|
||||
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
|
||||
|
||||
public Instant getExpiration() { return expiration; }
|
||||
public void setExpiration(Instant expiration) { this.expiration = expiration; }
|
||||
|
||||
public String getSessionPolicyDocument() { return sessionPolicyDocument; }
|
||||
public void setSessionPolicyDocument(String sessionPolicyDocument) { this.sessionPolicyDocument = sessionPolicyDocument; }
|
||||
}
|
||||
Reference in new issue
Block a user