refactor(iam): measure session expiry on the injected clock (#5382)

IamService decided whether a temporary session had expired against
Instant.now(), while AWS Sign-In stamps the expiry of the sessions it
issues from the injected Clock. In production both read the system
clock, so nothing changes there. In tests the injected clock is a
MutableClock fixed at 2026-01-01, so a Sign-In session was already
expired when it was issued: no test could use its credentials, and no
test could move a session past its expiry without waiting.

IamService now takes the injected Clock and reads it everywhere it
decides whether a session has expired: the secret-key lookup (and with
it S3 signature validation and the EKS token webhook), account routing,
the caller context, the caller ARNs, the caller user ID, and the sweep
of expired sessions. The presigned URL generator ran that sweep on its
first URL with its own system-clock time, which in tests deleted every
Sign-In session issued before it; it now asks IamService to sweep on
its own clock. IamService's package-private constructors keep the
system clock.

Those checks now also agree on the boundary: a session is expired from
the instant its expiration names. The secret-key lookup and the sweep
already drew it there, while account routing, the caller lookups and
the enforcement check still accepted a session at that instant. The
injected clock can land on it exactly, so they now share one predicate.
In production that changes the answer at that one instant only.

IAM enforcement reads the same clock. The filter asks the
expired-session check and the caller lookup about one moment, on every
request and on a presigned POST, and now takes that moment from the
injected Clock. On the system clock a live Sign-In session was refused
with ExpiredTokenException in tests with enforcement on. The filter's
package-private constructors keep the system clock.

Issuers that stamp from the system clock keep doing so. Most of them
(STS, the EC2 metadata and ECS credential endpoints, EKS Pod Identity,
the SSO portal) report the expiry to an SDK client that compares it with
its own wall clock, the SDKs inside the Docker-backed tests included.
Their sessions stay valid in tests, as before. In tests IamService now
measures them on the MutableClock, months behind the system clock, so
there they never expire and no test can move one past its expiry. No
test relied on that.

Service-specific credentials read the same clock. One with a
CredentialAgeDays reports Expired once its ExpirationDate has passed,
and that date is counted from its CreateDate, so both the stamp and the
comparison now use the injected Clock. In production that is the system
clock, as before; in tests a one-day key, the shortest AWS allows, can
now be moved past its expiry instead of having a past date planted in
the store.

A unit test moves a session past its expiry on a MutableClock through
each of the five lookups, another checks that the sweep keeps a session
live on that clock, a third holds a fixed clock at a session's
expiration and checks that every lookup, the enforcement check and the
sweep treat it as expired, and S3ValidateSignaturesIntegrationTest signs
requests with Sign-In credentials until the clock passes their lifetime.
With enforcement on, ExpiredSessionEnforcementIntegrationTest accepts a
session stamped from the injected clock until the clock passes its
expiry, then gets ExpiredTokenException, and IamEnforcementFilterTest
checks that both enforcement paths ask about the clock's moment. All of
these fail without this change. ServiceSpecificCredentialStateTest's
two expiry tests now advance a MutableClock past a one-day key's
expiry.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-10 21:29:13 -05:00
1 parent ff20750d91
commit 0ab58edb3c
9 files changed
+342 -44

No files matched your search

@@ -33,6 +33,7 @@ import org.jboss.logging.Logger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
@@ -195,6 +196,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final Instance<ScpProvider> scpProvider;
private final SessionAccountLookup sessionAccountLookup;
private final Instance<ResourcePolicyProvider> resourcePolicyProviders;
/** The clock {@link IamService} measures session expiry on, so both read the same time. */
private final Clock clock;
private final ResourceInfo resourceInfo;
@Inject
@@ -213,6 +216,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
Instance<ScpProvider> scpProvider,
SessionAccountLookup sessionAccountLookup,
Instance<ResourcePolicyProvider> resourcePolicyProviders,
Clock clock,
@Context ResourceInfo resourceInfo) {
this.config = config;
this.accountResolver = accountResolver;
@@ -229,6 +233,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this.scpProvider = scpProvider;
this.sessionAccountLookup = sessionAccountLookup;
this.resourcePolicyProviders = resourcePolicyProviders;
this.clock = clock;
this.resourceInfo = resourceInfo;
}
@@ -250,7 +255,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this(config, accountResolver, iamService, evaluator, actionRegistry,
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
scpProvider, sessionAccountLookup, resourcePolicyProviders, null);
scpProvider, sessionAccountLookup, resourcePolicyProviders, Clock.systemUTC(), null);
}
/** Package-private constructor for callers predating resourcePolicyProviders. */
@@ -270,7 +275,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this(config, accountResolver, iamService, evaluator, actionRegistry,
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
scpProvider, sessionAccountLookup, null, null);
scpProvider, sessionAccountLookup, null, Clock.systemUTC(), null);
}
@Override
@@ -339,7 +344,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
// Both lookups are asked about one moment, so a session that expires between them is not
// deleted and then answered as a key that exists nowhere.
Instant now = Instant.now();
Instant now = clock.instant();
if (iamService.isExpiredSession(akid, now)) {
LOG.debugv("Rejecting request signed with an expired session {0}", akid);
ctx.abortWith(expiredTokenResponse(credentialScope, ctx));
@@ -861,7 +866,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
// One moment for both lookups, as in filter(): a session expiring between them would
// otherwise be deleted and then allowed below as a credential with no context.
Instant now = Instant.now();
Instant now = clock.instant();
if (iamService.isExpiredSession(akid, now)) {
throw expiredTokenException(credentialScope);
}
@@ -60,6 +60,7 @@ import java.security.SecureRandom;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -382,6 +383,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
private final Object mfaDeviceLock = new Object();
private final RegionResolver regionResolver;
private final Clock clock;
private final boolean seedDeployerPrincipal;
private final String seededAccountAlias;
/** Guards case-insensitive IAM name uniqueness checks and their corresponding writes. */
@@ -397,7 +399,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final Map<String, Map<String, IamPolicy>> awsManagedPoliciesByPartition = new ConcurrentHashMap<>();
@Inject
public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
Clock clock) {
this(
storageFactory.create("iam", "iam-users.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-groups.json", new TypeReference<>() {}),
@@ -423,7 +426,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
storageFactory.create("iam", "iam-outbound-federation.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal(),
config.services().iam().accountAlias().orElse(null)
config.services().iam().accountAlias().orElse(null),
clock
);
}
@@ -447,6 +451,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
StorageBackend<String, SessionCredential> sessions,
RegionResolver regionResolver,
boolean seedDeployerPrincipal) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, regionResolver,
seedDeployerPrincipal, Clock.systemUTC());
}
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
StorageBackend<String, SessionCredential> sessions,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
Clock clock) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -455,7 +473,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, null);
regionResolver, seedDeployerPrincipal, null, clock);
}
// 8-backend constructor (no org-root-features): kept for existing callers/tests;
@@ -533,6 +551,39 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, accountAliases,
passwordPolicies, loginProfiles, oidcProviders, serviceLinkedRoleDeletions, orgRootFeatures,
credentialReports, virtualMfaDevices, serverCertificates, signingCertificates, sshPublicKeys,
serviceCredentials, accountProperties, stsPreferences, outboundFederation,
regionResolver, seedDeployerPrincipal, seededAccountAlias, Clock.systemUTC());
}
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
StorageBackend<String, SessionCredential> sessions,
StorageBackend<String, String> accountAliases,
StorageBackend<String, AccountPasswordPolicy> passwordPolicies,
StorageBackend<String, LoginProfile> loginProfiles,
StorageBackend<String, OpenIDConnectProvider> oidcProviders,
StorageBackend<String, String> serviceLinkedRoleDeletions,
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
StorageBackend<String, CredentialReport> credentialReports,
StorageBackend<String, VirtualMfaDevice> virtualMfaDevices,
StorageBackend<String, ServerCertificate> serverCertificates,
StorageBackend<String, SigningCertificate> signingCertificates,
StorageBackend<String, SshPublicKey> sshPublicKeys,
StorageBackend<String, ServiceSpecificCredential> serviceCredentials,
StorageBackend<String, String> accountProperties,
StorageBackend<String, String> stsPreferences,
StorageBackend<String, OutboundWebIdentityFederation> outboundFederation,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias,
Clock clock) {
this.users = users;
this.groups = groups;
this.roles = roles;
@@ -558,6 +609,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
this.seededAccountAlias = seededAccountAlias;
this.clock = clock;
}
@PostConstruct
@@ -3224,7 +3276,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
credential.setServiceSpecificCredentialId(
"ACCA" + randomId(SERVICE_CREDENTIAL_ID_SUFFIX_LENGTH));
credential.setStatus(CREDENTIAL_STATUS_ACTIVE);
credential.setCreateDate(Instant.now());
credential.setCreateDate(clock.instant());
int version = freeCredentialVersion(
all, userName, longTermKey, credential.getCreateDate());
if (longTermKey) {
@@ -3339,7 +3391,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public String reportedStatus(ServiceSpecificCredential credential) {
Instant expiry = credential.getExpirationDate();
if (expiry != null && !expiry.isAfter(Instant.now())) {
if (expiry != null && !expiry.isAfter(clock.instant())) {
return CREDENTIAL_STATUS_EXPIRED;
}
return credential.getStatus();
@@ -4009,8 +4061,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
private Optional<SessionCredential> currentSession(String accessKeyId) {
return findSessionAnyAccount(accessKeyId)
.filter(session -> session.getExpiration() == null || Instant.now().isBefore(session.getExpiration()));
return findSessionAnyAccount(accessKeyId).filter(session -> !isExpired(session, clock.instant()));
}
/**
* Whether {@code session} has expired as of {@code now}: from the instant its expiration names.
* Every lookup, the enforcement check and the sweep share this boundary.
*/
private static boolean isExpired(SessionCredential session, Instant now) {
return session.getExpiration() != null && !session.getExpiration().isAfter(now);
}
private static boolean hasMatchingSessionToken(SessionCredential session, String sessionToken) {
@@ -4318,16 +4377,23 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return removed;
}
/** Removes expired temporary sessions, including those left in persistent storage after a restart. */
public int sweepExpiredSessions(Instant now) {
/**
* Removes temporary sessions expired on the injected clock, including those left in persistent
* storage after a restart.
*/
public int sweepExpiredSessions() {
return sweepExpiredSessions(clock.instant());
}
/** {@link #sweepExpiredSessions()} as of {@code now}. */
int sweepExpiredSessions(Instant now) {
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
return aware.deleteAllAccountsMatching(session ->
session.getExpiration() != null && !session.getExpiration().isAfter(now));
return aware.deleteAllAccountsMatching(session -> isExpired(session, now));
}
List<SessionCredential> storedSessions = sessions.scan(key -> true);
int removed = 0;
for (SessionCredential session : storedSessions) {
if (session.getExpiration() == null || session.getExpiration().isAfter(now)) {
if (!isExpired(session, now)) {
continue;
}
deleteSession(session.getAccessKeyId(), session);
@@ -4352,7 +4418,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return Optional.empty();
}
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
if (isExpired(session, clock.instant())) {
return Optional.empty();
}
String account = AwsArnUtils.accountOrDefault(session.getRoleArn(), session.getOriginAccountId());
@@ -4513,7 +4579,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
*/
public CallerContext resolveCallerContext(String accessKeyId) {
return resolveCallerContext(accessKeyId, Instant.now());
return resolveCallerContext(accessKeyId, clock.instant());
}
/**
@@ -4536,7 +4602,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(now)) {
if (isExpired(session, now)) {
deleteSession(accessKeyId, session);
return null; // expired — unknown key → bypass
}
@@ -4622,8 +4688,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return false;
}
return findSessionForCallerContext(accessKeyId)
.map(SessionCredential::getExpiration)
.filter(expiration -> expiration.isBefore(now))
.filter(session -> isExpired(session, now))
.isPresent();
}
@@ -4687,7 +4752,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
if (isExpired(session, clock.instant())) {
deleteSession(accessKeyId, session);
return Optional.empty();
}
@@ -4750,7 +4815,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
if (isExpired(session, clock.instant())) {
deleteSession(accessKeyId, session);
return Optional.empty();
}
@@ -219,9 +219,10 @@ public class PreSignedUrlGenerator {
String method, Instant signedAt, int expiry) {
// The in-memory retirement list cannot survive a restart. Sweep persisted expired
// sessions once on first use, then retire this process's replacements as they expire.
// IamService judges which sessions have expired on its own clock, as it does everywhere.
if (expiredSessionsSwept.compareAndSet(false, true)) {
try {
iamService.sweepExpiredSessions(signedAt);
iamService.sweepExpiredSessions();
} catch (RuntimeException failure) {
expiredSessionsSwept.set(false);
throw failure;