fix(iam): populate aws:CurrentTime, aws:EpochTime and aws:TokenIssueTime (#8131)

Every request context now carries aws:CurrentTime and aws:EpochTime, the time of the request, including S3's own bucket-policy check and the context of a call a service makes. Every session Floci issues records when it was issued, the STS sessions and the EC2, ECS and Lambda role sessions among them, and a request signed with it carries that as aws:TokenIssueTime, which long-term access keys leave out, as the IAM User Guide describes. A role policy that denies sessions issued before a time, the guide's way of revoking them, now takes effect.

Closes #8130
This commit is contained in:
Jeremy Chapeau authored and GitHub committed 2026-11-17 16:14:54 -04:00
1 parent 1e66899a95
commit 8eda666f82
10 files changed
+346 -41

No files matched your search

+20 -1
View File
@@ -3155,7 +3155,8 @@ variable can only resolve to a key floci populates, which is the list under
A role trust policy is the narrower case, because `sts:AssumeRole` is authorized before there is a
session to describe: its context carries `aws:PrincipalArn`, `aws:PrincipalAccount`,
`aws:ResourceAccount`, `aws:RequestedRegion`, `aws:PrincipalIsAWSService`, `sts:RoleSessionName`,
`aws:ResourceAccount`, `aws:RequestedRegion`, `aws:PrincipalIsAWSService`, `aws:CurrentTime`,
`aws:EpochTime`, `sts:RoleSessionName`, `aws:TokenIssueTime` when the caller is itself a session,
and `sts:ExternalId` when the request passes one. `aws:username`, `aws:userid` and
`aws:PrincipalType` are not among them, so a variable naming one of those resolves to nothing in a
trust policy and the value it sits in matches nothing.
@@ -3433,6 +3434,24 @@ floci populates:
`GetSessionToken`, and decides an `AssumeRole` without outliving it; a call that presents one also
publishes the keys for that call itself, so the permission to make it can be conditioned on MFA.
See [STS MFA](sts.md#mfa).
- `aws:TokenIssueTime`: when the temporary credentials the request is signed with were issued, as
an ISO 8601 date, for every STS session (`AssumeRole` and its SAML and web identity forms,
`GetSessionToken`, `GetFederationToken`, `AssumeRoot`) and every role session floci issues
itself (Lambda execution roles, EC2 instance profiles, ECS task roles). The guide says it "is
included in the request context only when the principal uses temporary credentials to make the
request" and "is not present in AWS CLI, AWS API, or AWS SDK requests that are made using access
keys", so it is absent for an IAM user access key and for the account root. It is the key the
`AWSRevokeOlderSessions` policy of
[revoking role sessions](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_revoke-sessions.html)
matches: a `Deny` on `DateLessThan` `aws:TokenIssueTime` refuses the sessions issued before that
time and leaves later sessions and long-term keys alone. A session stored by an earlier floci
version, which did not record its issue time, carries no value for it.
- `aws:CurrentTime` and `aws:EpochTime`: the time of the request, which the guide says "is always
included in the request context": `aws:CurrentTime` as an ISO 8601 date, `aws:EpochTime` as
whole seconds since January 1, 1970, so it matches the `Date` and the `Numeric` operators.
They are on every request the enforcement filter checks, its `iam:PassRole` checks included,
in the context S3 builds when it evaluates a bucket policy itself under `s3.enforce-auth`, in a
role trust policy's context, and in that of a call an AWS service makes on its own behalf.
- `aws:TagKeys`: the case-sensitive requested tag keys for all 16 IAM tagging actions
in the generated table (tag structures or a list of keys), EC2 `RunInstances` and
`CreateTags`, S3 `PutBucketTagging`, S3 Control `TagResource` (its `Tags` body) and
@@ -590,9 +590,23 @@ public class IamConditionContextResolver {
conditions.putIfAbsent("aws:ViaAWSService", List.of("false"));
// Enforcement evaluates signed IAM credentials, not direct AWS service principals.
conditions.put("aws:PrincipalIsAWSService", List.of("false"));
putRequestTime(conditions);
return conditions;
}
/**
* The time of the request, which the IAM User Guide says "is always included in the request
* context" under two keys: {@code aws:CurrentTime}, a Date, and {@code aws:EpochTime}, "the
* date and time of the request in epoch or Unix time", a Date and a Numeric, so whole seconds.
* Every context a request is evaluated against carries them, including those built outside
* {@link #withGlobalContext}, such as S3's own bucket-policy check.
*/
public static void putRequestTime(Map<String, List<String>> conditions) {
Instant now = Instant.now();
conditions.put("aws:CurrentTime", List.of(now.toString()));
conditions.put("aws:EpochTime", List.of(Long.toString(now.getEpochSecond())));
}
private static void putResourceAccount(Map<String, List<String>> conditions, String resourceArn,
String resourceOwnerAccountId, String action) {
// S3 ARNs omit the owner account. Both condition keys must use the stored bucket owner,
@@ -613,7 +627,8 @@ public class IamConditionContextResolver {
* {@code true}; {@code aws:PrincipalServiceName} and {@code aws:PrincipalServiceNamesList} name the
* service; {@code aws:SourceArn} and {@code aws:SourceAccount} name the resource whose
* configuration triggered the call, when it has them; and {@code aws:ResourceAccount} and
* {@code aws:RequestedRegion} describe the target. The keys that describe an IAM principal,
* {@code aws:RequestedRegion} describe the target; {@code aws:CurrentTime} and
* {@code aws:EpochTime} carry the time of the request, as on every request. The keys that describe an IAM principal,
* {@code aws:PrincipalArn} and {@code aws:PrincipalAccount} among them, are left out: no IAM
* principal makes the call. A call to an SNS topic from a service SNS lists as setting it also
* carries {@code aws:SourceOwner}, the source account, which is what the default topic policy
@@ -641,6 +656,7 @@ public class IamConditionContextResolver {
}
putResourceAccount(conditions, resourceArn, resourceOwnerAccountId, action);
putIfPresent(conditions, "aws:RequestedRegion", AwsArnUtils.regionOrDefault(resourceArn, null));
putRequestTime(conditions);
return conditions;
}
@@ -5115,7 +5115,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* Stores an assumed-role session so the enforcement filter can resolve its policies.
*/
public void registerSession(String sessionAccessKeyId, String roleArn, Instant expiration) {
sessions.put(sessionAccessKeyId, new SessionCredential(sessionAccessKeyId, roleArn, expiration));
sessions.put(sessionAccessKeyId, issuedNow(new SessionCredential(sessionAccessKeyId, roleArn, expiration)));
}
/**
@@ -5124,7 +5124,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void registerSession(String sessionAccessKeyId, String roleArn, Instant expiration,
String sessionPolicyDocument) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, roleArn, expiration, sessionPolicyDocument));
issuedNow(new SessionCredential(sessionAccessKeyId, roleArn, expiration, sessionPolicyDocument)));
}
/**
@@ -5140,8 +5140,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, Instant expiration, String sessionPolicyDocument) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,
expiration, sessionPolicyDocument));
issuedNow(new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,
expiration, sessionPolicyDocument)));
}
/**
@@ -5172,7 +5172,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
roleArn, expiration, sessionPolicyDocument, originAccountId);
session.setRoleSessionName(roleSessionName);
session.setAssumedRoleId(assumedRoleId);
sessions.put(sessionAccessKeyId, session);
sessions.put(sessionAccessKeyId, issuedNow(session));
}
/**
@@ -5202,7 +5202,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
} else if (issuingAccessKeyId == null || !holdsKey(issuingAccessKeyId)) {
session.setIssuerArn(regionResolver.buildGlobalArn("iam", originAccountId, "root"));
}
sessions.put(sessionAccessKeyId, session);
sessions.put(sessionAccessKeyId, issuedNow(session));
}
/**
@@ -5243,7 +5243,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
null, expiration, sessionPolicyDocument, ownerAccountId);
session.setDelegatedApproverArn(delegatedApproverArn);
session.setDelegatedRoleBoundaryArns(roleBoundaryArns);
sessions.put(sessionAccessKeyId, session);
sessions.put(sessionAccessKeyId, issuedNow(session));
}
/**
@@ -5296,7 +5296,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration, sessionPolicyDocument,
accountId);
session.setRoleSessionName(roleSessionName);
putSessionForAccount(accountId, sessionAccessKeyId, session);
putSessionForAccount(accountId, sessionAccessKeyId, issuedNow(session));
}
/** An internal URL credential with both a session policy and an exact action/resource guard. */
@@ -5310,7 +5310,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
accessKeyId, secretAccessKey, sessionToken, null, expiration, policyDocument, accountId);
session.setPresignedAction(action);
session.setPresignedResourceArn(resourceArn);
putSessionForAccount(accountId, accessKeyId, session);
putSessionForAccount(accountId, accessKeyId, issuedNow(session));
}
/**
* Records that {@code session} is issued now, which is its {@code aws:TokenIssueTime}: "the
* exact time at which the temporary security credentials were created" (IAM User Guide,
* revoking role sessions).
*/
private SessionCredential issuedNow(SessionCredential session) {
session.setIssuedAt(clock.instant());
return session;
}
private void putSessionForAccount(String accountId, String sessionAccessKeyId, SessionCredential session) {
@@ -5378,6 +5388,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
session.setLambdaExecutionRole(true);
session.setRoleSessionName(roleSessionName);
session.setAssumedRoleId(assumedRoleId);
issuedNow(session);
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(accountId, sessionAccessKeyId, session);
} else {
@@ -5393,6 +5404,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|| session.getEc2InstanceId() == null || session.getEc2InstanceId().isBlank()) {
throw new IllegalArgumentException("EC2 session account and instance ID must not be blank");
}
issuedNow(session);
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(session.getOriginAccountId(), session.getAccessKeyId(), session);
} else {
@@ -5420,6 +5432,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|| session.getEcsTaskArn() == null || session.getEcsTaskArn().isBlank()) {
throw new IllegalArgumentException("ECS task session account and task ARN must not be blank");
}
issuedNow(session);
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(session.getOriginAccountId(), session.getAccessKeyId(), session);
} else {
@@ -5965,11 +5978,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* @param organization the organization the principal's account belongs to, whose three keys go
* onto the context beside the ones above, or null when the account is in
* none and when Organizations is not deployed
* @param tokenIssueTime the request's {@code aws:TokenIssueTime}: when the temporary credentials
* the caller signed with were issued, or null for long-term credentials
*/
public record CallerArns(String callerArn, String principalArn, String principalType,
String userId, String userName, boolean permissionsBoundary,
Map<String, String> principalTags, SessionMfa sessionMfa,
PrincipalOrganization.OrganizationContext organization) {
PrincipalOrganization.OrganizationContext organization,
Instant tokenIssueTime) {
public CallerArns {
principalTags = Map.copyOf(principalTags);
@@ -5980,7 +5996,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String userId, String userName, boolean permissionsBoundary,
Map<String, String> principalTags, SessionMfa sessionMfa) {
this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary,
principalTags, sessionMfa, null);
principalTags, sessionMfa, null, null);
}
/**
@@ -5995,18 +6011,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public record SessionMfa(boolean present, long authAgeSeconds) {
}
/** A caller whose credentials say nothing about MFA, which is every long-term key. */
/**
* A caller signing with long-term credentials, whose credentials say nothing about MFA and
* carry no {@code aws:TokenIssueTime}.
*/
public CallerArns(String callerArn, String principalArn, String principalType,
String userId, String userName, boolean permissionsBoundary,
Map<String, String> principalTags) {
this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary,
principalTags, null);
principalTags, null, null, null);
}
/** Copy of this caller with what the session it signed with says about MFA. */
public CallerArns withSessionMfa(SessionMfa mfa) {
return new CallerArns(callerArn, principalArn, principalType, userId, userName,
permissionsBoundary, principalTags, mfa, organization);
permissionsBoundary, principalTags, mfa, organization, tokenIssueTime);
}
/**
@@ -6016,7 +6035,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public CallerArns withOrganization(PrincipalOrganization.OrganizationContext context) {
return context == null ? this : new CallerArns(callerArn, principalArn, principalType,
userId, userName, permissionsBoundary, principalTags, sessionMfa, context);
userId, userName, permissionsBoundary, principalTags, sessionMfa, context,
tokenIssueTime);
}
/** The same caller, signing with temporary credentials issued at {@code issuedAt}. */
public CallerArns withTokenIssueTime(Instant issuedAt) {
return new CallerArns(callerArn, principalArn, principalType, userId, userName,
permissionsBoundary, principalTags, sessionMfa, organization, issuedAt);
}
/** A caller without stored principal tags, including account-root and federated identities. */
@@ -6079,6 +6105,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* key left absent is what makes a policy that matches on it fail to match, which is the
* behaviour AWS documents for a key with no value, so omitting it is the enforcement, not
* a gap in it.
*
* <p>{@code aws:TokenIssueTime} follows the same rule: it is "included in the request
* context only when the principal uses temporary credentials to make the request" and "is
* not present in AWS CLI, AWS API, or AWS SDK requests that are made using access keys".
*/
public void putPrincipalKeys(Map<String, List<String>> context) {
context.put("aws:PrincipalArn", List.of(principalArn));
@@ -6096,6 +6126,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (organization != null) {
organization.putOrganizationKeys(context);
}
if (tokenIssueTime != null) {
context.put("aws:TokenIssueTime", List.of(tokenIssueTime.toString()));
}
}
/**
@@ -6212,11 +6245,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
deleteSession(accessKeyId, session);
return Optional.empty();
}
// Whatever identity the session resolves to, the MFA state belongs to the credentials
// rather than to the identity, so it is attached once here instead of at each of the
// identities below.
// Whatever identity the session resolves to, the MFA state and the issue time belong
// to the credentials rather than to the identity, so they are attached once here
// instead of at each of the identities below.
CallerArns.SessionMfa mfa = sessionMfa(session);
return callerForSession(session).map(caller -> caller.withSessionMfa(mfa));
return callerForSession(session)
.map(caller -> caller.withSessionMfa(mfa).withTokenIssueTime(session.getIssuedAt()));
}
return Optional.empty();
@@ -18,6 +18,11 @@ public class SessionCredential {
private String roleSessionName;
private String assumedRoleId;
private Instant expiration;
/**
* When the credentials were issued, the request's {@code aws:TokenIssueTime}. Null for a
* session stored before Floci recorded it.
*/
private Instant issuedAt;
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
private String sessionPolicyDocument;
/**
@@ -137,6 +142,9 @@ public class SessionCredential {
public Instant getExpiration() { return expiration; }
public void setExpiration(Instant expiration) { this.expiration = expiration; }
public Instant getIssuedAt() { return issuedAt; }
public void setIssuedAt(Instant issuedAt) { this.issuedAt = issuedAt; }
public String getSessionPolicyDocument() { return sessionPolicyDocument; }
public void setSessionPolicyDocument(String sessionPolicyDocument) { this.sessionPolicyDocument = sessionPolicyDocument; }
@@ -15,6 +15,7 @@ import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.FileTrees;
import io.floci.aws.core.common.IamConditionContextResolver;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
@@ -1745,6 +1746,7 @@ public class S3Service implements Resettable, ResourceProvider {
* whether S3 evaluates it or the enforcement filter does. For a role session
* {@code aws:PrincipalArn} is the role's ARN. {@code requestConditions}, when present, are the keys
* the request itself offers, such as an object creation's tags and Object Lock settings.
* {@code aws:CurrentTime} and {@code aws:EpochTime} are there as on every request.
*/
private static Map<String, List<String>> bucketPolicyContext(CallerArns caller,
Map<String, List<String>> requestConditions) {
@@ -1753,6 +1755,7 @@ public class S3Service implements Resettable, ResourceProvider {
context.putAll(requestConditions);
}
context.put("aws:PrincipalIsAWSService", List.of("false"));
IamConditionContextResolver.putRequestTime(context);
if (caller != null) {
caller.putPrincipalKeys(context);
}
@@ -1537,6 +1537,12 @@ class IamConditionContextResolverTest {
"ses.amazonaws.com", "arn:aws:sns:eu-west-2:111122223333:events", "111122223333",
"arn:aws:ses:eu-west-2:444455556666:configuration-set/my-set", "444455556666");
// The time of the request is on a service call as on every request; the rest is exact.
assertTrue(conditions.containsKey("aws:CurrentTime"));
assertTrue(conditions.containsKey("aws:EpochTime"));
Map<String, List<String>> rest = new HashMap<>(conditions);
rest.remove("aws:CurrentTime");
rest.remove("aws:EpochTime");
assertEquals(Map.of(
"aws:PrincipalIsAWSService", List.of("true"),
"aws:ViaAWSService", List.of("false"),
@@ -1546,7 +1552,7 @@ class IamConditionContextResolverTest {
"aws:SourceAccount", List.of("444455556666"),
"aws:SourceOwner", List.of("444455556666"),
"aws:ResourceAccount", List.of("111122223333"),
"aws:RequestedRegion", List.of("eu-west-2")), conditions);
"aws:RequestedRegion", List.of("eu-west-2")), rest);
}
@Test
@@ -41,6 +41,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -52,6 +53,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.atLeastOnce;
@@ -1279,7 +1281,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -1287,7 +1289,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
.thenReturn(null);
@@ -1301,14 +1303,14 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000")));
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000")));
verify(evaluator).evaluateResolvedResourcePolicy(
any(),
eq(ResourcePolicyDecision.NEUTRAL),
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000")));
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000")));
verify(containerRequest, never()).abortWith(any());
}
@@ -1337,7 +1339,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -1345,7 +1347,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
sameContext(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
.thenReturn(null);
@@ -1428,7 +1430,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(globalContext(conditions, "*", "222233334444"))))
sameContext(globalContext(conditions, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
@@ -1439,7 +1441,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(globalContext(conditions, "*", "222233334444")));
sameContext(globalContext(conditions, "*", "222233334444")));
verify(containerRequest).abortWith(any(Response.class));
}
@@ -1455,7 +1457,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(globalContext(first, "*", "222233334444"))))
sameContext(globalContext(first, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -1463,7 +1465,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(globalContext(second, "*", "222233334444"))))
sameContext(globalContext(second, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
@@ -1474,7 +1476,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(globalContext(second, "*", "222233334444")));
sameContext(globalContext(second, "*", "222233334444")));
verify(containerRequest).abortWith(any(Response.class));
}
@@ -1515,6 +1517,22 @@ class IamEnforcementFilterTest {
serviceContext, resourceArn, "us-east-1", accountId, null);
}
// aws:CurrentTime and aws:EpochTime are the time of the request, so an expected context built
// apart from it cannot carry the same values: both keys must be there, and the rest must match.
private static Map<String, List<String>> sameContext(Map<String, List<String>> expected) {
return argThat(actual -> actual != null
&& actual.containsKey("aws:CurrentTime")
&& actual.containsKey("aws:EpochTime")
&& withoutRequestTime(actual).equals(withoutRequestTime(expected)));
}
private static Map<String, List<String>> withoutRequestTime(Map<String, List<String>> context) {
Map<String, List<String>> rest = new LinkedHashMap<>(context);
rest.remove("aws:CurrentTime");
rest.remove("aws:EpochTime");
return rest;
}
private void stubTaggedTerminate(ContainerRequestContext containerRequest,
Map<String, List<String>> first,
List<Map<String, List<String>>> remaining) {
@@ -1565,7 +1583,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::bucket"),
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444"))))
sameContext(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
IamEnforcementFilter filter = newFilter();
@@ -1578,7 +1596,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::bucket"),
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444")));
sameContext(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444")));
}
@Test
@@ -2616,7 +2634,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::partner-bucket"),
eq(expected)))
sameContext(expected)))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
filterWithBucketOwner("111111111111").filter(containerRequest);
@@ -2627,7 +2645,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::partner-bucket"),
eq(expected));
sameContext(expected));
}
/** Builds a filter whose only resource-policy provider reports the given bucket owner. */
@@ -70,6 +70,13 @@ class IamServiceTest {
iamService = iamService(false);
}
// A session's caller is the long-term principal it acts as plus aws:TokenIssueTime, which the
// IAM User Guide includes "only when the principal uses temporary credentials".
private static void assertSessionCaller(IamService.CallerArns expected, IamService.CallerArns actual) {
assertNotNull(actual.tokenIssueTime());
assertEquals(expected.withTokenIssueTime(actual.tokenIssueTime()), actual);
}
private static IamService iamService(boolean seedDeployerPrincipal) {
return iamService(seedDeployerPrincipal, new InMemoryStorage<>());
}
@@ -501,7 +508,7 @@ class IamServiceTest {
// aws:username, which the guide lists as not present for a role.
// It carries what its credentials say about MFA as well, which for a session minted
// without a device is the key present and false.
assertEquals(new IamService.CallerArns("arn:aws:sts::123456789012:assumed-role/TestRole/s",
assertSessionCaller(new IamService.CallerArns("arn:aws:sts::123456789012:assumed-role/TestRole/s",
"arn:aws:iam::123456789012:role/team/TestRole",
IamService.CallerArns.TYPE_ASSUMED_ROLE, "AROATESTROLEID:s", null)
.withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)),
@@ -745,7 +752,7 @@ class IamServiceTest {
assertNull(context.sessionPolicyDocument());
// Acting as the user means carrying the user's principal keys, aws:username included:
// the guide gives one to an IAM user and to no other principal.
assertEquals(new IamService.CallerArns(alice.getArn(), alice.getArn(),
assertSessionCaller(new IamService.CallerArns(alice.getArn(), alice.getArn(),
IamService.CallerArns.TYPE_USER, alice.getUserId(), "alice")
.withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)),
service.resolveCallerArns("ASIASESSIONTOKEN").orElseThrow());
@@ -764,7 +771,7 @@ class IamServiceTest {
assertEquals(1, context.identityPolicies().size());
// "aws:userid: AWS account ID" and no aws:username, which the guide lists as not
// present for the account root.
assertEquals(new IamService.CallerArns("arn:aws:iam::000000000000:root",
assertSessionCaller(new IamService.CallerArns("arn:aws:iam::000000000000:root",
"arn:aws:iam::000000000000:root", IamService.CallerArns.TYPE_ACCOUNT,
"000000000000", null)
.withSessionMfa(new IamService.CallerArns.SessionMfa(false, 0)),
@@ -878,7 +885,7 @@ class IamServiceTest {
// aws:username: the guide lists it as not present for a federated user. No MFA state
// either, the same guide putting federated identities with the long-term keys, so this
// session publishes neither MFA key where every other session publishes the first.
assertEquals(new IamService.CallerArns(federatedArn, federatedArn,
assertSessionCaller(new IamService.CallerArns(federatedArn, federatedArn,
IamService.CallerArns.TYPE_FEDERATED_USER, "000000000000:Bob", null),
service.resolveCallerArns("ASIAWITHPOLICY").orElseThrow());
assertEquals("000000000000:Bob", service.resolveCallerUserId("ASIAWITHPOLICY", "token").orElseThrow());
@@ -0,0 +1,153 @@
package io.floci.aws.services.iam;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.MutableClock;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The request-time keys of the IAM User Guide's global condition keys: {@code aws:CurrentTime} and
* {@code aws:EpochTime}, "always included in the request context", and {@code aws:TokenIssueTime},
* present "only when the principal uses temporary credentials", which the guide's revoking role
* sessions page matches with its {@code AWSRevokeOlderSessions} policy.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class RequestTimeConditionKeysIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final String ALLOW_LIST_USERS = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}""";
private static final String ALLOW_ASSUME = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
@TestHTTPResource("/")
URI baseUri;
/** The clock STS issues sessions by, so the revocation time can sit between two of them. */
@Inject
MutableClock clock;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void revokingOlderSessionsDeniesSessionsIssuedBeforeAndAllowsSessionsIssuedAfter() {
String roleName = "revoked-role-" + suffix();
UserCredentials source = user("revoker-source-" + suffix(), ALLOW_ASSUME);
try (IamClient admin = admin(); StsClient sts = stsClient(source)) {
String roleArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", roleName,
ALLOW_LIST_USERS);
Credentials older = sts.assumeRole(r -> r.roleArn(roleArn).roleSessionName("older")).credentials();
try (IamClient olderSession = sessionClient(older)) {
olderSession.listUsers();
// The guide's policy names a time to the second, as the console writes it.
Instant revokedAt = clock.instant().truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
admin.putRolePolicy(r -> r.roleName(roleName).policyName("AWSRevokeOlderSessions")
.policyDocument(revokeOlderSessions(revokedAt)));
denied(olderSession::listUsers);
clock.advance(Duration.ofSeconds(2));
Credentials newer = sts.assumeRole(r -> r.roleArn(roleArn).roleSessionName("newer")).credentials();
try (IamClient newerSession = sessionClient(newer)) {
newerSession.listUsers();
}
denied(olderSession::listUsers);
}
}
}
@Test
void tokenIssueTimeIsAbsentForLongTermKeysAndPresentForTheirSessionTokens() {
String name = "token-time-user-" + suffix();
UserCredentials keys = user(name, ALLOW_LIST_USERS);
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), name, "revoke",
revokeOlderSessions(Instant.parse("2100-01-01T00:00:00Z")));
try (IamClient longTerm = userClient(keys); StsClient sts = stsClient(keys)) {
longTerm.listUsers();
Credentials session = sts.getSessionToken().credentials();
try (IamClient temporary = sessionClient(session)) {
denied(temporary::listUsers);
}
}
}
@Test
void currentTimeAndEpochTimeAreInEveryRequestContext() {
String name = "current-time-user-" + suffix();
UserCredentials keys = user(name, """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*",
"Condition":{"DateGreaterThan":{"aws:CurrentTime":"2020-01-01T00:00:00Z"},
"NumericGreaterThan":{"aws:EpochTime":"1577836800"},
"DateLessThan":{"aws:EpochTime":"4102444800"}}}]}""");
try (IamClient caller = userClient(keys)) {
caller.listUsers();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), name, "deny", """
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*",
"Condition":{"DateLessThan":{"aws:CurrentTime":"2100-01-01T00:00:00Z"}}}]}""");
denied(caller::listUsers);
}
}
private static String revokeOlderSessions(Instant revokedAt) {
return """
{"Version":"2012-10-17","Statement":{"Effect":"Deny","Action":"*","Resource":"*",
"Condition":{"DateLessThan":{"aws:TokenIssueTime":"%s"}}}}""".formatted(revokedAt);
}
private UserCredentials user(String name, String policy) {
UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), name);
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), name, "base", policy);
return keys;
}
private static IamClient admin() {
return AwsTestClients.create(IamClient.builder(), ACCOUNT, Region.US_EAST_1);
}
private static IamClient userClient(UserCredentials keys) {
return AwsTestClients.create(IamClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), Region.US_EAST_1);
}
private static StsClient stsClient(UserCredentials keys) {
return AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), Region.US_EAST_1);
}
private IamClient sessionClient(Credentials session) {
return AwsTestClients.create(IamClient.builder(),
AwsSessionCredentials.create(session.accessKeyId(), session.secretAccessKey(), session.sessionToken()),
Region.US_EAST_1, baseUri);
}
private static void denied(Runnable operation) {
AwsServiceException error = assertThrows(AwsServiceException.class, operation::run);
assertEquals(403, error.statusCode());
assertEquals("AccessDenied", error.awsErrorDetails().errorCode());
}
private static String suffix() {
return UUID.randomUUID().toString().substring(0, 8);
}
}
@@ -385,6 +385,47 @@ class S3BucketPolicyEnforcementIntegrationTest {
assertReadAndCopy(reader, source, destination, 403);
}
@Test
void aBucketPolicyReadsTheRequestTime() {
// aws:CurrentTime and aws:EpochTime are "always included in the request context", so the
// context S3 builds for its own bucket-policy check carries them too. A cross-account read
// needs that check's Allow, so a grant conditioned on the request time is refused when
// they are missing there.
String suffix = UUID.randomUUID().toString().substring(0, 8);
String source = "bp-time-" + suffix;
S3RequestSigner owner = sourceBucketInAccountA(source);
putObjectAs(source, "current/o.txt", "current", owner);
putObjectAs(source, "epoch/o.txt", "epoch", owner);
S3RequestSigner reader = createAccountAdmin("reader-" + suffix, ACCOUNT_B).signer();
putBucketPolicyAs(source, requestTimeGrant(source, "DateLessThan", "NumericLessThan"), owner);
given().filter(reader).when().get("/" + source + "/current/o.txt").then().statusCode(403);
given().filter(reader).when().get("/" + source + "/epoch/o.txt").then().statusCode(403);
putBucketPolicyAs(source, requestTimeGrant(source, "DateGreaterThan", "NumericGreaterThan"), owner);
given().filter(reader).when().get("/" + source + "/current/o.txt")
.then().statusCode(200).body(equalTo("current"));
given().filter(reader).when().get("/" + source + "/epoch/o.txt")
.then().statusCode(200).body(equalTo("epoch"));
}
/**
* Grants account B {@code current/*} on a {@code dateOperator} condition on
* {@code aws:CurrentTime}, and {@code epoch/*} on a {@code numericOperator} one on
* {@code aws:EpochTime}, both against January 1, 2020.
*/
private static String requestTimeGrant(String bucket, String dateOperator, String numericOperator) {
return """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::%2$s/current/*",
"Condition":{"%3$s":{"aws:CurrentTime":"2020-01-01T00:00:00Z"}}},
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::%2$s/epoch/*",
"Condition":{"%4$s":{"aws:EpochTime":"1577836800"}}}]}"""
.formatted(ACCOUNT_B, bucket, dateOperator, numericOperator);
}
/** Creates a bucket in account A holding {@code o.txt}, and returns its owner, an account-A administrator. */
private static S3RequestSigner sourceBucketInAccountA(String bucket) {
S3RequestSigner owner = createAccountAdmin("owner-" + bucket, ACCOUNT_A).signer();