mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(iam): route assumed-role credentials to the target account (#1549)
* feat(iam): route assumed-role credentials to the target account Assumed-role temporary credentials (ASIA… keys) collapsed to the default account: account resolution only recognised 12-digit access key IDs and had no link to the STS session store. Cross-account "assume a role in account B, then provision" flows therefore landed resources in account 000000000000 instead of B. Add a SessionAccountLookup port in core.common, implemented by IamService, mapping a temporary access key to its account — the account in the session's role (or federated-user) ARN, or the caller account captured at mint time for role-less GetSessionToken credentials. AccountContextFilter now resolves with the precedence 12-digit AKID → session lookup → default, for both the Authorization header and the presigned X-Amz-Credential parameter. STS handlers record the caller account on every minted session, and SessionCredential gains an originAccountId field. The session lookup is account-independent, since sessions are keyed by a globally unique access key. IamService is now @Startup so AWS-managed policies seed under the default account at boot. Seeding is account-namespaced and AccountContextFilter now instantiates IamService to resolve the request account, so lazy seeding would otherwise bind managed policies to whichever account made the first request. Tests: unit coverage for resolver/filter precedence and session lookup, plus an integration test proving a table created with role-B credentials materialises in account B and is invisible to account A. * perf(iam): skip session-store scan for non-ASIA access keys Account resolution runs on every request. Gating the session lookup on the ASIA temporary-credential prefix keeps the common case (e.g. the 'test' default credential) off the session-store scan, which would otherwise grow with every issued session. * chore: re-trigger CI Unrelated flaky CodeBuildTest.batchGetBuilds_eventuallySucceeds; root-cause fix in floci-io/floci#1577.
This commit is contained in:
1 parent
94468ba56f
commit
f52b9209cf
12 files changed
+410
-19
No files matched your search
@@ -8,11 +8,18 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Populates {@link RequestContext} with the account ID and region derived from
|
||||
* the incoming AWS Authorization header or, for presigned URL requests, the
|
||||
* X-Amz-Credential query parameter. Runs at AUTHENTICATION priority so that
|
||||
* downstream filters (e.g. IAM enforcement) can rely on the context being set.
|
||||
*
|
||||
* <p>Account resolution precedence: a 12-digit access key ID is used directly as
|
||||
* the account; otherwise temporary credentials (e.g. assumed-role {@code ASIA...}
|
||||
* keys) are looked up in the session store via {@link SessionAccountLookup}; if
|
||||
* neither matches, the configured default account applies.
|
||||
*/
|
||||
@Provider
|
||||
@ApplicationScoped
|
||||
@@ -22,26 +29,32 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
private final AccountResolver accountResolver;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RequestContext requestContext;
|
||||
private final SessionAccountLookup sessionAccountLookup;
|
||||
|
||||
@Inject
|
||||
public AccountContextFilter(AccountResolver accountResolver,
|
||||
RegionResolver regionResolver,
|
||||
RequestContext requestContext) {
|
||||
RequestContext requestContext,
|
||||
SessionAccountLookup sessionAccountLookup) {
|
||||
this.accountResolver = accountResolver;
|
||||
this.regionResolver = regionResolver;
|
||||
this.requestContext = requestContext;
|
||||
this.sessionAccountLookup = sessionAccountLookup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
String auth = ctx.getHeaderString("Authorization");
|
||||
if (auth != null && !auth.isEmpty()) {
|
||||
requestContext.setAccountId(accountResolver.resolve(auth));
|
||||
String akid = accountResolver.extractAccessKeyId(auth);
|
||||
requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
|
||||
requestContext.setRegion(regionResolver.resolveRegionFromAuth(auth));
|
||||
} else {
|
||||
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
|
||||
if (credential != null && !credential.isEmpty()) {
|
||||
requestContext.setAccountId(accountResolver.resolveFromPresignedCredential(credential));
|
||||
String akid = accountResolver.extractPresignedAccessKeyId(credential);
|
||||
requestContext.setAccountId(
|
||||
resolveAccount(akid, accountResolver.resolveFromPresignedCredential(credential)));
|
||||
requestContext.setRegion(regionResolver.resolveRegionFromPresignedCredential(credential));
|
||||
} else {
|
||||
requestContext.setAccountId(accountResolver.resolve(null));
|
||||
@@ -49,4 +62,19 @@ public class AccountContextFilter implements ContainerRequestFilter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the account-resolution precedence. A 12-digit AKID is already reflected in
|
||||
* {@code resolvedDefault} (the account or default returned by {@link AccountResolver});
|
||||
* for any other key shape, a live session lookup takes precedence before falling back.
|
||||
*/
|
||||
private String resolveAccount(String akid, String resolvedDefault) {
|
||||
if (akid != null && !akid.matches("\\d{12}")) {
|
||||
Optional<String> sessionAccount = sessionAccountLookup.resolveAccountId(akid);
|
||||
if (sessionAccount.isPresent()) {
|
||||
return sessionAccount.get();
|
||||
}
|
||||
}
|
||||
return resolvedDefault;
|
||||
}
|
||||
}
|
||||
@@ -62,11 +62,22 @@ public class AccountResolver {
|
||||
if (credentialValue == null || credentialValue.isEmpty()) {
|
||||
return defaultAccountId;
|
||||
}
|
||||
String[] parts = credentialValue.split("/");
|
||||
String akid = parts[0];
|
||||
if (akid.matches("\\d{12}")) {
|
||||
String akid = extractPresignedAccessKeyId(credentialValue);
|
||||
if (akid != null && akid.matches("\\d{12}")) {
|
||||
return akid;
|
||||
}
|
||||
return defaultAccountId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the access key ID from an X-Amz-Credential value
|
||||
* ({@code accessKeyID/date/region/service/aws4_request}), or returns null when
|
||||
* the value is absent or empty.
|
||||
*/
|
||||
public String extractPresignedAccessKeyId(String credentialValue) {
|
||||
if (credentialValue == null || credentialValue.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return credentialValue.split("/", 2)[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port that maps an STS temporary access key ID (e.g. {@code ASIA...}) to the AWS
|
||||
* account the request should resolve to.
|
||||
*
|
||||
* <p>Declared in {@code core.common} so {@link AccountContextFilter} can route
|
||||
* assumed-role and other temporary credentials to the correct account without
|
||||
* {@code core} depending on the {@code services.iam} package (which owns the
|
||||
* session store) — keeping the dependency direction services → core.
|
||||
*/
|
||||
public interface SessionAccountLookup {
|
||||
|
||||
/**
|
||||
* Returns the account ID associated with the given temporary access key ID,
|
||||
* or {@link Optional#empty()} if it is not a known, live session.
|
||||
*/
|
||||
Optional<String> resolveAccountId(String accessKeyId);
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
@@ -16,6 +18,7 @@ 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 io.quarkus.runtime.Startup;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -32,9 +35,16 @@ import java.util.Map;
|
||||
/**
|
||||
* Core IAM business logic — users, groups, roles, policies, access keys, instance profiles.
|
||||
* IAM is a global service: resources are not region-scoped and storage keys have no region prefix.
|
||||
*
|
||||
* <p>Eagerly initialized at startup so AWS-managed policies (and the optional deployer principal)
|
||||
* are seeded under the default account before any request runs. Seeding is account-namespaced via
|
||||
* the request context, so deferring it to the first request would otherwise bind the seed data to
|
||||
* whichever account happened to make that call — a real hazard now that {@code AccountContextFilter}
|
||||
* resolves the request account through this service.
|
||||
*/
|
||||
@Startup
|
||||
@ApplicationScoped
|
||||
public class IamService {
|
||||
public class IamService implements SessionAccountLookup {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamService.class);
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
@@ -945,6 +955,59 @@ public class IamService {
|
||||
new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores an assumed-role session and records {@code originAccountId} — the account of the
|
||||
* caller that minted it. The origin lets {@link #resolveAccountId(String)} route temporary
|
||||
* credentials that carry no role ARN (e.g. GetSessionToken) back to the caller's account.
|
||||
*/
|
||||
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
|
||||
java.time.Instant expiration, String sessionPolicyDocument,
|
||||
String originAccountId) {
|
||||
sessions.put(sessionAccessKeyId,
|
||||
new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration,
|
||||
sessionPolicyDocument, originAccountId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the account a temporary access key belongs to: the account encoded in the
|
||||
* session's role (or federated-user) ARN when present, otherwise the caller account captured
|
||||
* at mint time. Returns empty for unknown or expired sessions so callers fall back to the
|
||||
* default account.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> resolveAccountId(String accessKeyId) {
|
||||
// STS issues only ASIA-prefixed temporary keys, so anything else cannot be a session.
|
||||
// Short-circuit here to keep the per-request hot path off the session-store scan below.
|
||||
if (accessKeyId == null || !accessKeyId.startsWith("ASIA")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<SessionCredential> sessionOpt = findSessionAnyAccount(accessKeyId);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
SessionCredential session = sessionOpt.get();
|
||||
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String account = AwsArnUtils.accountOrDefault(session.getRoleArn(), session.getOriginAccountId());
|
||||
return account == null || account.isBlank() ? Optional.empty() : Optional.of(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up a session by its temporary access key ID independent of the request's account.
|
||||
*
|
||||
* <p>Sessions are keyed by a globally-unique access key (e.g. {@code ASIA...}) but stored in
|
||||
* the minting account's namespace. Account routing must resolve the session <em>before</em> the
|
||||
* request's account is known, so a normal account-scoped {@code get} would miss it. This scans
|
||||
* across all accounts; the access key's global uniqueness keeps the result unambiguous.
|
||||
*/
|
||||
private Optional<SessionCredential> findSessionAnyAccount(String accessKeyId) {
|
||||
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
|
||||
return Optional.ofNullable(aware.scanAllAccountsAsMap().get(accessKeyId));
|
||||
}
|
||||
return sessions.get(accessKeyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the full caller context for the given access key, including identity policies,
|
||||
* optional session policy, and optional permission boundary.
|
||||
|
||||
@@ -77,14 +77,16 @@ public class StsQueryHandler {
|
||||
String roleName = roleArn != null && roleArn.contains("/")
|
||||
? roleArn.substring(roleArn.lastIndexOf('/') + 1)
|
||||
: "UnknownRole";
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
|
||||
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
|
||||
// Register session so IAM enforcement can resolve the role's policies and so that
|
||||
// RDS/ElastiCache IAM token validation can find the temporary secret key.
|
||||
// Register session so IAM enforcement can resolve the role's policies, RDS/ElastiCache
|
||||
// IAM token validation can find the temporary secret key, and account routing can map
|
||||
// these temporary credentials to the assumed role's account.
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy);
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -119,7 +121,8 @@ public class StsQueryHandler {
|
||||
Instant expiration = Instant.now().plusSeconds(durationSeconds);
|
||||
|
||||
String result = credentialsXml(accessKeyId, secretKey, sessionToken, expiration);
|
||||
iamService.registerSession(accessKeyId, secretKey, null, expiration, null);
|
||||
// No role ARN — route these credentials back to the caller's account.
|
||||
iamService.registerSession(accessKeyId, secretKey, null, expiration, null, regionResolver.getAccountId());
|
||||
return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build();
|
||||
}
|
||||
|
||||
@@ -139,13 +142,14 @@ public class StsQueryHandler {
|
||||
Instant expiration = Instant.now().plusSeconds(durationSeconds);
|
||||
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
|
||||
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
String provider = providerId != null && !providerId.isBlank() ? providerId : "accounts.google.com";
|
||||
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy);
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -176,11 +180,12 @@ public class StsQueryHandler {
|
||||
Instant expiration = Instant.now().plusSeconds(durationSeconds);
|
||||
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
|
||||
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
|
||||
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
|
||||
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null);
|
||||
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null, callerAccountId);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -215,8 +220,9 @@ public class StsQueryHandler {
|
||||
String federatedUserArn = AwsArnUtils.Arn.of("sts", "", accountId, "federated-user/" + name).toString();
|
||||
|
||||
String sessionPolicy = getParam(params, "Policy");
|
||||
// Register federation token so enforcement can scope its policies via session policy
|
||||
iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy);
|
||||
// Register federation token so enforcement can scope its policies via session policy.
|
||||
// The federated-user ARN already carries the caller's account, so reuse it as the origin.
|
||||
iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy, accountId);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
|
||||
@@ -15,6 +15,11 @@ public class SessionCredential {
|
||||
private Instant expiration;
|
||||
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
|
||||
private String sessionPolicyDocument;
|
||||
/**
|
||||
* Account of the caller that minted this session, captured at mint time. Used to route
|
||||
* temporary credentials that carry no role ARN (e.g. GetSessionToken) back to the caller.
|
||||
*/
|
||||
private String originAccountId;
|
||||
|
||||
public SessionCredential() {}
|
||||
|
||||
@@ -40,6 +45,16 @@ public class SessionCredential {
|
||||
this.sessionPolicyDocument = sessionPolicyDocument;
|
||||
}
|
||||
|
||||
public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,
|
||||
String sessionPolicyDocument, String originAccountId) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.secretAccessKey = secretAccessKey;
|
||||
this.roleArn = roleArn;
|
||||
this.expiration = expiration;
|
||||
this.sessionPolicyDocument = sessionPolicyDocument;
|
||||
this.originAccountId = originAccountId;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() { return accessKeyId; }
|
||||
public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
|
||||
|
||||
@@ -54,4 +69,7 @@ public class SessionCredential {
|
||||
|
||||
public String getSessionPolicyDocument() { return sessionPolicyDocument; }
|
||||
public void setSessionPolicyDocument(String sessionPolicyDocument) { this.sessionPolicyDocument = sessionPolicyDocument; }
|
||||
|
||||
public String getOriginAccountId() { return originAccountId; }
|
||||
public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }
|
||||
}
|
||||
Reference in new issue
Block a user