mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
ff20750d91
commit
0ab58edb3c
9 files changed
+342
-44
No files matched your search
@@ -34,7 +34,9 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -126,6 +128,10 @@ class IamEnforcementFilterTest {
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilter(ResourceInfo resourceInfo) {
|
||||
return newFilter(resourceInfo, Clock.systemUTC());
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilter(ResourceInfo resourceInfo, Clock clock) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(false);
|
||||
@@ -134,7 +140,7 @@ class IamEnforcementFilterTest {
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, mock(CloudTrailService.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, null, resourceInfo);
|
||||
catalog, scpProvider, sessionAccountLookup, null, clock, resourceInfo);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -615,6 +621,28 @@ class IamEnforcementFilterTest {
|
||||
assertSame(checked.getValue(), resolved.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMomentBothLookupsAreAskedAboutIsReadFromTheInjectedClock() {
|
||||
// IamService measures session expiry on the injected clock, as AWS Sign-In stamps it, so a
|
||||
// moment read from the system clock would find a live Sign-In session expired in tests.
|
||||
Instant moment = Instant.parse("2026-01-01T00:00:00Z");
|
||||
IamEnforcementFilter filter = newFilter(null, Clock.fixed(moment, ZoneOffset.UTC));
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260101/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
|
||||
filter.filter(containerRequest);
|
||||
// A presigned POST's credential reaches enforcement only through this call.
|
||||
filter.authorizeAdditionalResource(auth, "s3:PutObject", "arn:aws:s3:::bucket/key");
|
||||
|
||||
verify(iamService, times(2)).isExpiredSession("ASIASESSION", moment);
|
||||
verify(iamService, times(2)).resolveCallerContext("ASIASESSION", moment);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownAccessKeyIsRejectedOnAnRpcCallNoRuleMaps() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
+25
-3
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
@@ -15,6 +16,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
@@ -23,7 +25,7 @@ import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* With enforcement on, a session past its expiration is answered with AWS's
|
||||
* With enforcement on, a session past its expiration on the injected clock is answered with AWS's
|
||||
* {@code ExpiredTokenException}, not as a key that exists nowhere, on every call and every time.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@@ -36,6 +38,9 @@ class ExpiredSessionEnforcementIntegrationTest {
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
MutableClock clock;
|
||||
|
||||
/**
|
||||
* The teardown runs after Quarkus has reset the port RestAssured points at, so it has to say
|
||||
* where the application is. The test port is random, which leaves this as the only place to
|
||||
@@ -114,12 +119,29 @@ class ExpiredSessionEnforcementIntegrationTest {
|
||||
.then().statusCode(403).body(containsString("<Code>ExpiredTokenException</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionIsLiveUntilTheInjectedClockPassesItsExpiry() {
|
||||
// AWS Sign-In stamps its sessions' expiry from the injected clock, so enforcement measures
|
||||
// it on that clock too. On the system clock such a session read as expired once issued.
|
||||
String accessKeyId = sessionExpiringAt(clock.instant().plus(Duration.ofMinutes(15)));
|
||||
|
||||
getCallerIdentity(accessKeyId).then().statusCode(200);
|
||||
|
||||
clock.advance(Duration.ofMinutes(16));
|
||||
getCallerIdentity(accessKeyId)
|
||||
.then().statusCode(403).body(containsString("<Code>ExpiredTokenException</Code>"));
|
||||
}
|
||||
|
||||
private String expiredSession() {
|
||||
String accessKeyId = "ASIAEXPIRED"
|
||||
return sessionExpiringAt(LONG_AGO);
|
||||
}
|
||||
|
||||
private String sessionExpiringAt(Instant expiration) {
|
||||
String accessKeyId = "ASIASESSION"
|
||||
+ UUID.randomUUID().toString().replace("-", "").substring(0, 9).toUpperCase(Locale.ROOT);
|
||||
cleanup.register(() -> iamService.unregisterSession(ACCOUNT_ID, accessKeyId));
|
||||
iamService.registerSessionForAccount(ACCOUNT_ID, accessKeyId, "secret",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/expired-session-role", LONG_AGO, null);
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/expired-session-role", expiration, null);
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,16 +23,20 @@ import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
|
||||
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -41,6 +45,8 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static io.github.hectorvent.floci.services.iam.InlinePolicyTestHelper.policyWithNonWhitespaceLength;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -243,6 +249,80 @@ class IamServiceTest {
|
||||
assertTrue(service.resolveCallerArns("ASIAEXPIREDSESSION").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionExpiryFollowsTheInjectedClock() {
|
||||
MutableClock clock = new MutableClock();
|
||||
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"), false, clock);
|
||||
service.createRole("ClockRole", "/", "{}", null, 3600, null);
|
||||
Map<String, Predicate<String>> lookups = new LinkedHashMap<>();
|
||||
lookups.put("secret key", key -> service.findSecretKey(key, "token").isPresent());
|
||||
lookups.put("account", key -> service.resolveAccountId(key).isPresent());
|
||||
lookups.put("caller context", key -> service.resolveCallerContext(key) != null);
|
||||
lookups.put("caller ARNs", key -> service.resolveCallerArns(key).isPresent());
|
||||
lookups.put("user ID", key -> service.resolveCallerUserId(key, "token").isPresent());
|
||||
|
||||
int sessionNumber = 0;
|
||||
for (Map.Entry<String, Predicate<String>> lookup : lookups.entrySet()) {
|
||||
// A fresh session per lookup: some lookups delete a session they find expired.
|
||||
String accessKeyId = "ASIACLOCKSESSION" + sessionNumber++;
|
||||
service.registerSession(accessKeyId, "secret", "token", "arn:aws:iam::000000000000:role/ClockRole",
|
||||
clock.instant().plusSeconds(60), null, "000000000000", "s", "AROACLOCKROLE:s");
|
||||
assertTrue(lookup.getValue().test(accessKeyId), lookup.getKey() + " before expiry");
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
assertFalse(lookup.getValue().test(accessKeyId), lookup.getKey() + " after expiry");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionIsExpiredFromTheInstantItsExpirationNames() {
|
||||
// Every lookup, the enforcement check and the sweep draw the same boundary, so none of them
|
||||
// accepts a session another one already treats as expired.
|
||||
Instant expiration = Instant.parse("2026-01-01T00:01:00Z");
|
||||
Map<String, BiPredicate<IamService, String>> expired = new LinkedHashMap<>();
|
||||
expired.put("secret key", (service, key) -> service.findSecretKey(key, "token").isEmpty());
|
||||
expired.put("account", (service, key) -> service.resolveAccountId(key).isEmpty());
|
||||
expired.put("caller context", (service, key) -> service.resolveCallerContext(key) == null);
|
||||
expired.put("caller ARNs", (service, key) -> service.resolveCallerArns(key).isEmpty());
|
||||
expired.put("user ID", (service, key) -> service.resolveCallerUserId(key, "token").isEmpty());
|
||||
expired.put("enforcement", (service, key) -> service.isExpiredSession(key, expiration));
|
||||
expired.put("sweep", (service, key) -> service.sweepExpiredSessions() == 1);
|
||||
|
||||
for (Map.Entry<String, BiPredicate<IamService, String>> check : expired.entrySet()) {
|
||||
// A fresh service per check: some checks delete a session they find expired.
|
||||
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"), false, Clock.fixed(expiration, ZoneOffset.UTC));
|
||||
service.createRole("ClockRole", "/", "{}", null, 3600, null);
|
||||
service.registerSession("ASIABOUNDARYSESSION", "secret", "token",
|
||||
"arn:aws:iam::000000000000:role/ClockRole", expiration, null, "000000000000", "s",
|
||||
"AROACLOCKROLE:s");
|
||||
assertTrue(check.getValue().test(service, "ASIABOUNDARYSESSION"), check.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExpiredSessionSweepFollowsTheInjectedClock() {
|
||||
// The presigned URL generator sweeps every stored session on its first URL, so a session
|
||||
// live on the clock, as a Sign-In session is in tests, has to survive it.
|
||||
MutableClock clock = new MutableClock();
|
||||
IamService service = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"), false, clock);
|
||||
service.registerSession("ASIALIVESESSION", "secret", "token", "arn:aws:iam::000000000000:role/ClockRole",
|
||||
clock.instant().plusSeconds(60), null, "000000000000", "s", "AROACLOCKROLE:s");
|
||||
service.registerSession("ASIAPASTSESSION", "secret", "token", "arn:aws:iam::000000000000:role/ClockRole",
|
||||
clock.instant().minusSeconds(1), null, "000000000000", "s", "AROACLOCKROLE:s");
|
||||
|
||||
assertEquals(1, service.sweepExpiredSessions());
|
||||
assertTrue(service.findSecretKey("ASIALIVESESSION", "token").isPresent());
|
||||
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
assertEquals(1, service.sweepExpiredSessions());
|
||||
}
|
||||
|
||||
private static final String READ_S3 = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";
|
||||
private static final String ALL_S3 = """
|
||||
|
||||
+16
-14
@@ -9,12 +9,14 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServiceSpecificCredential;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
@@ -62,6 +64,11 @@ class ServiceSpecificCredentialStateTest {
|
||||
|
||||
private static IamService newService(
|
||||
StorageBackend<String, ServiceSpecificCredential> credentials, String defaultAccount) {
|
||||
return newService(credentials, defaultAccount, Clock.systemUTC());
|
||||
}
|
||||
|
||||
private static IamService newService(
|
||||
StorageBackend<String, ServiceSpecificCredential> credentials, String defaultAccount, Clock clock) {
|
||||
return new IamService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
@@ -71,7 +78,7 @@ class ServiceSpecificCredentialStateTest {
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
credentials,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", defaultAccount), false, null);
|
||||
new RegionResolver("us-east-1", defaultAccount), false, null, clock);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -581,22 +588,18 @@ class ServiceSpecificCredentialStateTest {
|
||||
* A key past its {@code ExpirationDate} reports {@code Expired}, and an update to
|
||||
* {@code Active} cannot undo that: the status is derived on read, so the stored value is left
|
||||
* as the caller set it while the reported one tells the truth.
|
||||
*
|
||||
* <p>The expiry has to be planted directly in the store, because the smallest
|
||||
* {@code CredentialAgeDays} AWS allows is one day, so no sequence of calls reaches a past
|
||||
* expiry.
|
||||
*/
|
||||
@Test
|
||||
void aKeyPastItsExpiryReportsExpiredAndCannotBeReactivated() {
|
||||
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
|
||||
IamService service = newService(store, ACCOUNT_A);
|
||||
MutableClock clock = new MutableClock();
|
||||
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A, clock);
|
||||
service.createUser("expiry-user", "/");
|
||||
// One day, the shortest CredentialAgeDays AWS allows.
|
||||
ServiceSpecificCredential credential =
|
||||
service.createServiceSpecificCredential("expiry-user", BEDROCK, 1);
|
||||
assertEquals("Active", service.reportedStatus(credential));
|
||||
|
||||
credential.setExpirationDate(Instant.now().minusSeconds(60));
|
||||
store.put(credential.getServiceSpecificCredentialId(), credential);
|
||||
clock.advance(Duration.ofDays(1));
|
||||
|
||||
assertEquals("Expired", service.reportedStatus(credential));
|
||||
assertEquals("Expired", service.reportedStatus(service
|
||||
@@ -615,16 +618,15 @@ class ServiceSpecificCredentialStateTest {
|
||||
/** Expiry is terminal, so it outranks a status the caller set to Inactive. */
|
||||
@Test
|
||||
void anExpiredKeyReportsExpiredRatherThanInactive() {
|
||||
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
|
||||
IamService service = newService(store, ACCOUNT_A);
|
||||
MutableClock clock = new MutableClock();
|
||||
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A, clock);
|
||||
service.createUser("inactive-user", "/");
|
||||
ServiceSpecificCredential credential =
|
||||
service.createServiceSpecificCredential("inactive-user", BEDROCK, 1);
|
||||
service.updateServiceSpecificCredential(
|
||||
"inactive-user", credential.getServiceSpecificCredentialId(), "Inactive");
|
||||
|
||||
credential.setExpirationDate(Instant.now().minusSeconds(60));
|
||||
store.put(credential.getServiceSpecificCredentialId(), credential);
|
||||
clock.advance(Duration.ofDays(1));
|
||||
|
||||
assertEquals("Expired", service.reportedStatus(credential));
|
||||
}
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ class PreSignedUrlGeneratorSessionTest {
|
||||
assertFalse(secrets.containsKey(firstKey), "Expired superseded sessions are removed");
|
||||
assertTrue(secrets.containsKey(secondKey));
|
||||
assertEquals(2, secrets.size(), "Unexpired object-scoped sessions remain available");
|
||||
verify(iamService, times(1)).sweepExpiredSessions(start);
|
||||
verify(iamService, times(1)).sweepExpiredSessions();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+96
-1
@@ -1,23 +1,33 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.testing.MutableClock;
|
||||
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@@ -27,7 +37,7 @@ import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* {@code floci.auth.validate-signatures} authenticates every signed S3 request, whichever
|
||||
* placement carries the signature, without authorizing it: a forged or unknown credential is
|
||||
* placement carries the signature, without authorizing it: a forged, unknown or expired credential is
|
||||
* refused, while bucket policies are not evaluated and unsigned requests pass, as they do with
|
||||
* {@code enforce-auth} off. Shares {@link ValidateSignaturesProfile} with
|
||||
* {@link PreSignedUrlIntegrationTest}, which covers the presigned query-string placement.
|
||||
@@ -47,9 +57,16 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
"Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}
|
||||
""".formatted(BUCKET);
|
||||
|
||||
private static final String SIGNIN_CLIENT_ID = "arn:aws:signin:::devtools/same-device";
|
||||
private static final String SIGNIN_REDIRECT_URI = "http://127.0.0.1:4567/oauth/callback";
|
||||
private static final String SIGNIN_VERIFIER = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
||||
|
||||
private static String userAccessKeyId;
|
||||
private static String userSecretKey;
|
||||
|
||||
@Inject
|
||||
MutableClock clock;
|
||||
|
||||
@Test
|
||||
void layerContentLocationCanBeFetchedWithSignatureValidationEnabled() throws Exception {
|
||||
ByteArrayOutputStream archive = new ByteArrayOutputStream();
|
||||
@@ -296,6 +313,84 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
.body(containsString("<Code>AuthorizationHeaderMalformed</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(34)
|
||||
void headerSignedRequestsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
|
||||
// Sign-In stamps its access token's expiry from the injected clock, so IAM measures it on the same one.
|
||||
Response token = signIn();
|
||||
S3RequestSigner signinSigner = S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
|
||||
token.path("accessToken.secretAccessKey"), token.path("accessToken.sessionToken"));
|
||||
given()
|
||||
.filter(signinSigner)
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + KEY)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
clock.advance(Duration.ofSeconds(token.<Integer>path("expiresIn") + 1L));
|
||||
// A known gap from AWS, not the intended answer: S3 lists 400 ExpiredToken for a session past
|
||||
// its expiry, which only IAM enforcement gives today. Signature validation still answers it
|
||||
// as a key it does not know.
|
||||
given()
|
||||
.filter(signinSigner)
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + KEY)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("Error.Code", equalTo("InvalidAccessKeyId"));
|
||||
}
|
||||
|
||||
/** Runs the AWS Sign-In authorization-code flow through its consent page and returns the token response. */
|
||||
private static Response signIn() throws Exception {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(SIGNIN_VERIFIER.getBytes(StandardCharsets.US_ASCII));
|
||||
String consent = given()
|
||||
.redirects().follow(false)
|
||||
.queryParam("client_id", SIGNIN_CLIENT_ID)
|
||||
.queryParam("code_challenge", Base64.getUrlEncoder().withoutPadding().encodeToString(digest))
|
||||
.queryParam("code_challenge_method", "SHA-256")
|
||||
.queryParam("redirect_uri", SIGNIN_REDIRECT_URI)
|
||||
.queryParam("response_type", "code")
|
||||
.queryParam("scope", "openid")
|
||||
.queryParam("state", "validate-signatures")
|
||||
.when()
|
||||
.get("/v1/authorize")
|
||||
.then()
|
||||
.statusCode(302)
|
||||
.extract().header("Location");
|
||||
String callback = given()
|
||||
.redirects().follow(false)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("request_id", queryParams(URI.create(consent)).get("request_id"))
|
||||
.formParam("action", "continue")
|
||||
.when()
|
||||
.post("/_floci/signin/consent")
|
||||
.then()
|
||||
.statusCode(302)
|
||||
.extract().header("Location");
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body(Map.of(
|
||||
"clientId", SIGNIN_CLIENT_ID,
|
||||
"grantType", "authorization_code",
|
||||
"code", queryParams(URI.create(callback)).get("code"),
|
||||
"redirectUri", SIGNIN_REDIRECT_URI,
|
||||
"codeVerifier", SIGNIN_VERIFIER))
|
||||
.when()
|
||||
.post("/v1/token")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().response();
|
||||
}
|
||||
|
||||
private static Map<String, String> queryParams(URI uri) {
|
||||
return Arrays.stream(uri.getRawQuery().split("&"))
|
||||
.map(pair -> pair.split("=", 2))
|
||||
.collect(Collectors.toMap(
|
||||
parts -> URLDecoder.decode(parts[0], StandardCharsets.UTF_8),
|
||||
parts -> URLDecoder.decode(parts[1], StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private static void createIamUser(String userName) {
|
||||
// validate-signatures verifies IAM's signatures too, so these calls carry real ones.
|
||||
AwsRequestSigner iam = AwsRequestSigner.signedAs("test", "test", "iam");
|
||||
|
||||
Reference in new issue
Block a user