mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(s3): answer an expired session with ExpiredToken when verifying signatures (#5435)
When S3 verified a signature, it answered a request signed with temporary credentials past their expiry as if the key did not exist: 403 InvalidAccessKeyId for a header-signed request, and 403 SignatureDoesNotMatch for a presigned POST and, under validate-signatures alone, for a presigned URL. S3's error list has 400 ExpiredToken, "The provided token has expired.", for an expired token, and IAM enforcement already answers S3 with it. The secret-key lookup finds nothing for an expired session, so when it comes back empty the three placements (header, presigned URL, presigned POST) now ask IamService whether the key and token belong to a session that has expired on its clock and is still stored, and answer 400 ExpiredToken if so. The token has to match. Sent with another token or none, an expired session is still answered as a key that is not registered, so a caller that does not hold the credential learns nothing about it. Once Floci has removed an expired session it no longer knows the key, as with enforcement. IamServiceTest moves a session past its expiry and checks that the new lookup answers only to the session's own token, and the boundary test now holds it to the same instant as the other lookups. S3ValidateSignaturesIntegrationTest signs with Sign-In credentials through a header, a presigned URL and a presigned POST: each is accepted until the clock passes their expiry, then answered 400 ExpiredToken. An expired session sent with another token still gets InvalidAccessKeyId. Each placement's test fails without its part of the change, and the token tests fail when the token is not checked. S3RequestSigner can now write a presigned URL's query string, so the presigned URL test signs the way an SDK presigner does.
This commit is contained in:
1 parent
7fa1a506c7
commit
013a9214b5
9 files changed
+220
-19
No files matched your search
@@ -287,6 +287,7 @@ class IamServiceTest {
|
||||
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("expired token", (service, key) -> service.isExpiredSessionToken(key, "token"));
|
||||
expired.put("sweep", (service, key) -> service.sweepExpiredSessions() == 1);
|
||||
|
||||
for (Map.Entry<String, BiPredicate<IamService, String>> check : expired.entrySet()) {
|
||||
@@ -323,6 +324,27 @@ class IamServiceTest {
|
||||
assertEquals(1, service.sweepExpiredSessions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionIsToldApartOnlyWithItsOwnToken() {
|
||||
// Signature validation asks once the secret-key lookup has found nothing, to answer a session
|
||||
// past its expiry as expired rather than as a key that exists nowhere.
|
||||
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("ASIACLOCKSESSION", "secret", "token", "arn:aws:iam::000000000000:role/ClockRole",
|
||||
clock.instant().plusSeconds(60), null, "000000000000", "s", "AROACLOCKROLE:s");
|
||||
|
||||
assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", "token"), "a live session");
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
assertTrue(service.findSecretKey("ASIACLOCKSESSION", "token").isEmpty());
|
||||
assertTrue(service.isExpiredSessionToken("ASIACLOCKSESSION", "token"), "an expired session");
|
||||
// Without its token the session stays as unknown as a key that exists nowhere.
|
||||
assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", "another-token"), "another token");
|
||||
assertFalse(service.isExpiredSessionToken("ASIACLOCKSESSION", null), "no token");
|
||||
assertFalse(service.isExpiredSessionToken("ASIANOSUCHSESSION", "token"), "a key that exists nowhere");
|
||||
}
|
||||
|
||||
private static final String READ_S3 = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";
|
||||
private static final String ALL_S3 = """
|
||||
|
||||
+100
-8
@@ -7,6 +7,7 @@ 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.RestAssured;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -318,8 +319,7 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
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"));
|
||||
S3RequestSigner signinSigner = signinSigner(token);
|
||||
given()
|
||||
.filter(signinSigner)
|
||||
.when()
|
||||
@@ -327,19 +327,101 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
.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.
|
||||
advancePastExpiry(token);
|
||||
given()
|
||||
.filter(signinSigner)
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + KEY)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Error.Code", equalTo("ExpiredToken"))
|
||||
.body("Error.Message", equalTo("The provided token has expired."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(35)
|
||||
void presignedUrlsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
|
||||
Response token = signIn();
|
||||
S3RequestSigner signinSigner = signinSigner(token);
|
||||
String path = "/" + BUCKET + "/" + KEY;
|
||||
URI uri = URI.create("http://localhost:" + RestAssured.port + path);
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(path + "?" + signinSigner.presignedQuery("GET", uri, 3600))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("signed body"));
|
||||
|
||||
advancePastExpiry(token);
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(path + "?" + signinSigner.presignedQuery("GET", uri, 3600))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Error.Code", equalTo("ExpiredToken"))
|
||||
.body("Error.Message", equalTo("The provided token has expired."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(36)
|
||||
void presignedPostsWithSigninCredentialsAreAcceptedUntilTheyExpire() throws Exception {
|
||||
Response token = signIn();
|
||||
postWithSigninCredentials(token, "post-signin-live.txt").then().statusCode(204);
|
||||
|
||||
advancePastExpiry(token);
|
||||
postWithSigninCredentials(token, "post-signin-expired.txt")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Error.Code", equalTo("ExpiredToken"))
|
||||
.body("Error.Message", equalTo("The provided token has expired."));
|
||||
given().filter(LOCAL_SIGNER).when().get("/" + BUCKET + "/post-signin-expired.txt").then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(37)
|
||||
void anExpiredSessionSentWithAnotherTokenIsStillAnUnknownKey() throws Exception {
|
||||
// Only the session's own token tells an expired session apart from a key that exists nowhere.
|
||||
Response token = signIn();
|
||||
advancePastExpiry(token);
|
||||
given()
|
||||
.filter(S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
|
||||
token.path("accessToken.secretAccessKey"), "another-token"))
|
||||
.when()
|
||||
.get("/" + BUCKET + "/" + KEY)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("Error.Code", equalTo("InvalidAccessKeyId"));
|
||||
}
|
||||
|
||||
private static S3RequestSigner signinSigner(Response token) {
|
||||
return S3RequestSigner.signedAs(token.path("accessToken.accessKeyId"),
|
||||
token.path("accessToken.secretAccessKey"), token.path("accessToken.sessionToken"));
|
||||
}
|
||||
|
||||
private void advancePastExpiry(Response token) {
|
||||
clock.advance(Duration.ofSeconds(token.<Integer>path("expiresIn") + 1L));
|
||||
}
|
||||
|
||||
/** A presigned POST of {@code key} signed with the Sign-In session, its token listed in the policy as S3 requires. */
|
||||
private static Response postWithSigninCredentials(Response token, String key) {
|
||||
String sessionToken = token.path("accessToken.sessionToken");
|
||||
String policy = postPolicy(key, sessionToken);
|
||||
return given()
|
||||
.multiPart("key", key)
|
||||
.multiPart("policy", policy)
|
||||
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
|
||||
.multiPart("x-amz-credential", token.path("accessToken.accessKeyId") + "/" + CREDENTIAL_DATE
|
||||
+ "/us-east-1/s3/aws4_request")
|
||||
.multiPart("x-amz-date", AMZ_DATE)
|
||||
.multiPart("x-amz-security-token", sessionToken)
|
||||
.multiPart("x-amz-signature", signPolicy(policy, token.path("accessToken.secretAccessKey")))
|
||||
.multiPart("file", key, "posted".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + BUCKET);
|
||||
}
|
||||
|
||||
/** 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")
|
||||
@@ -418,11 +500,21 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
}
|
||||
|
||||
private static String postPolicy(String key) {
|
||||
return encodePolicy("""
|
||||
[{"bucket": "%s"}, {"key": "%s"}]""".formatted(BUCKET, key));
|
||||
}
|
||||
|
||||
private static String postPolicy(String key, String sessionToken) {
|
||||
return encodePolicy("""
|
||||
[{"bucket": "%s"}, {"key": "%s"}, {"x-amz-security-token": "%s"}]""".formatted(BUCKET, key, sessionToken));
|
||||
}
|
||||
|
||||
private static String encodePolicy(String conditions) {
|
||||
String expiration = DateTimeFormatter.ISO_INSTANT.format(
|
||||
Instant.now().plusSeconds(3600).atZone(ZoneOffset.UTC));
|
||||
String policy = """
|
||||
{"expiration": "%s", "conditions": [{"bucket": "%s"}, {"key": "%s"}]}
|
||||
""".formatted(expiration, BUCKET, key);
|
||||
{"expiration": "%s", "conditions": %s}
|
||||
""".formatted(expiration, conditions);
|
||||
return Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.util.stream.Collectors;
|
||||
* session token is given, {@code x-amz-security-token}; the content hash is the SHA-256 of the
|
||||
* body the request carries. The {@code with*} methods return a copy that deliberately deviates
|
||||
* (a stale timestamp, a forged signature, a wrong content hash) for the rejection cases.
|
||||
* {@link #presignedQuery} signs the same credential into a presigned URL's query string instead.
|
||||
*/
|
||||
public final class S3RequestSigner implements Filter {
|
||||
|
||||
@@ -132,13 +133,10 @@ public final class S3RequestSigner implements Filter {
|
||||
String contentSha256 = contentSha256Override != null
|
||||
? contentSha256Override
|
||||
: sha256Hex(body);
|
||||
String host = uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
|
||||
? uri.getHost() + ":" + uri.getPort()
|
||||
: uri.getHost();
|
||||
|
||||
List<String[]> headers = new ArrayList<>();
|
||||
if (signHost) {
|
||||
headers.add(new String[]{"host", host});
|
||||
headers.add(new String[]{"host", host(uri)});
|
||||
}
|
||||
headers.add(new String[]{"x-amz-content-sha256", contentSha256});
|
||||
headers.add(new String[]{"x-amz-date", amzDate});
|
||||
@@ -179,6 +177,55 @@ public final class S3RequestSigner implements Filter {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The query string of a presigned URL for {@code method} on {@code uri}, written the way an AWS
|
||||
* SDK presigner writes it: the {@code X-Amz-*} parameters, {@code X-Amz-Security-Token} when a
|
||||
* session token is given, {@code host} as the only signed header, an unsigned payload, and the
|
||||
* signature last. Send it with URL encoding off, since it is already encoded.
|
||||
*/
|
||||
public String presignedQuery(String method, URI uri, int expiresSeconds) throws Exception {
|
||||
Instant at = signedAt != null ? signedAt : Instant.now();
|
||||
String amzDate = AMZ_DATE.format(at);
|
||||
String scopeDate = amzDate.substring(0, 8);
|
||||
String credentialScope = scopeDate + "/" + region + "/" + SERVICE + "/aws4_request";
|
||||
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("X-Amz-Algorithm", ALGORITHM);
|
||||
params.put("X-Amz-Credential", accessKeyId + "/" + credentialScope);
|
||||
params.put("X-Amz-Date", amzDate);
|
||||
params.put("X-Amz-Expires", Integer.toString(expiresSeconds));
|
||||
if (sessionToken != null) {
|
||||
params.put("X-Amz-Security-Token", sessionToken);
|
||||
}
|
||||
params.put("X-Amz-SignedHeaders", "host");
|
||||
String query = params.entrySet().stream()
|
||||
.map(param -> uriEncode(param.getKey()) + "=" + uriEncode(param.getValue()))
|
||||
.collect(Collectors.joining("&"));
|
||||
|
||||
String rawPath = uri.getRawPath() == null || uri.getRawPath().isEmpty() ? "/" : uri.getRawPath();
|
||||
String canonicalRequest = method + "\n"
|
||||
+ rawPath + "\n"
|
||||
+ canonicalQueryString(query) + "\n"
|
||||
+ "host:" + host(uri) + "\n"
|
||||
+ "\n"
|
||||
+ "host" + "\n"
|
||||
+ "UNSIGNED-PAYLOAD";
|
||||
String stringToSign = ALGORITHM + "\n"
|
||||
+ amzDate + "\n"
|
||||
+ credentialScope + "\n"
|
||||
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
|
||||
String signature = signatureOverride != null
|
||||
? signatureOverride
|
||||
: hexEncode(hmacSha256(signingKey(scopeDate), stringToSign));
|
||||
return query + "&X-Amz-Signature=" + signature;
|
||||
}
|
||||
|
||||
private static String host(URI uri) {
|
||||
return uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
|
||||
? uri.getHost() + ":" + uri.getPort()
|
||||
: uri.getHost();
|
||||
}
|
||||
|
||||
private byte[] signingKey(String scopeDate) throws Exception {
|
||||
byte[] kDate = hmacSha256(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), scopeDate);
|
||||
byte[] kRegion = hmacSha256(kDate, region);
|
||||
|
||||
Reference in new issue
Block a user