mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(s3): sign generated presigned URLs with SigV4 (#4373)
* fix(s3): align generated presigned URLs with SigV4 and request region * fix(s3): refresh presign credentials after storage reset * fix(s3): retire expired generated presign sessions * fix(iam): sweep expired sessions by stored key * fix(s3): scope generated presign credentials * fix(s3): authorize conditional generated URLs and slash keys * test(s3): preserve signed URL semantics in tagging and SES regressions * fix(s3): reject tag injection on scoped generated PUT URLs * style(s3): alphabetize presigner Java imports * fix(s3): deny scoped requests without a raw HTTP path * fix(s3): authorize proxied presigned URLs by signed path * fix(s3): use signed path for proxied object requests * style(s3): order presigned URL test imports
This commit is contained in:
1 parent
5ec18c507c
commit
864f79cf31
20 files changed
+1232
-104
No files matched your search
@@ -15,6 +15,8 @@ import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
@@ -99,6 +101,10 @@ class IamEnforcementFilterTest {
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilter() {
|
||||
return newFilter(mock(CurrentVertxRequest.class));
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilter(CurrentVertxRequest currentVertxRequest) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ScpProvider> scpProvider =
|
||||
mock(Instance.class);
|
||||
@@ -107,7 +113,7 @@ class IamEnforcementFilterTest {
|
||||
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
|
||||
requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
currentVertxRequest,
|
||||
catalog, scpProvider, sessionAccountLookup);
|
||||
}
|
||||
|
||||
@@ -475,6 +481,91 @@ class IamEnforcementFilterTest {
|
||||
verifyNoInteractions(evaluator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedCredentialCannotBypassAnUnmappedAction() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASCOPE/20260927/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getMethod()).thenReturn("POST");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn(null);
|
||||
when(iamService.presignedScope("ASIASCOPE"))
|
||||
.thenReturn(Optional.of(new IamService.PresignedScope(
|
||||
"s3:GetObject", "arn:aws:s3:::bucket/key")));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopedPresignedRequestWithoutRoutingContextIsDenied() {
|
||||
assertScopedPresignedRequestWithoutHttpRequestIsDenied(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopedPresignedRequestWithoutHttpRequestIsDenied() {
|
||||
assertScopedPresignedRequestWithoutHttpRequestIsDenied(mock(RoutingContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopedPresignedRequestUsesWirePathForAbsoluteFormProxyTarget() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);
|
||||
RoutingContext routingContext = mock(RoutingContext.class);
|
||||
HttpServerRequest httpRequest = mock(HttpServerRequest.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASCOPE/20260927/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("ASIASCOPE"))
|
||||
.thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));
|
||||
when(iamService.presignedScope("ASIASCOPE"))
|
||||
.thenReturn(Optional.of(new IamService.PresignedScope(
|
||||
"s3:GetObject", "arn:aws:s3:::bucket//key")));
|
||||
when(currentVertxRequest.getCurrent()).thenReturn(routingContext);
|
||||
when(routingContext.request()).thenReturn(httpRequest);
|
||||
when(httpRequest.uri()).thenReturn("https://proxy.example/bucket//key?X-Amz-Algorithm=AWS4-HMAC-SHA256");
|
||||
when(httpRequest.path()).thenReturn("/bucket//key");
|
||||
when(conditionContextResolver.resolveRemainingTargets("s3", "s3:GetObject", containerRequest))
|
||||
.thenReturn(List.of());
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
newFilter(currentVertxRequest).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
verify(evaluator).evaluateResolvedResourcePolicy(any(), any(), any(),
|
||||
eq("s3:GetObject"), eq("arn:aws:s3:::bucket//key"), any());
|
||||
}
|
||||
|
||||
private void assertScopedPresignedRequestWithoutHttpRequestIsDenied(RoutingContext routingContext) {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASCOPE/20260927/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("ASIASCOPE"))
|
||||
.thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));
|
||||
when(iamService.presignedScope("ASIASCOPE"))
|
||||
.thenReturn(Optional.of(new IamService.PresignedScope(
|
||||
"s3:GetObject", "arn:aws:s3:::bucket/key")));
|
||||
if (routingContext != null) {
|
||||
when(currentVertxRequest.getCurrent()).thenReturn(routingContext);
|
||||
}
|
||||
|
||||
newFilter(currentVertxRequest).filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.forClass(Response.class);
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareAccountIdKeyWithNoScpCeilingStillPassesThrough() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
+56
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
@@ -108,7 +109,61 @@ class IamServicePersistenceTest {
|
||||
assertTrue(restarted.findSecretKey(accessKeyId, "legacy-session-token").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTemporarySessionsAreRemovedAfterRestart(@TempDir Path dir) {
|
||||
Instant now = Instant.now();
|
||||
IamService first = newService(dir);
|
||||
first.registerSessionForAccount("000000000000", "ASIAEXPIREDPRESIGN", "expired-secret",
|
||||
"expired-token", null, now.minusSeconds(1), null);
|
||||
first.registerSessionForAccount("000000000000", "ASIAVALIDPRESIGN", "valid-secret",
|
||||
"valid-token", null, now.plusSeconds(3600), null);
|
||||
|
||||
IamService restarted = newService(dir);
|
||||
assertEquals(1, restarted.sweepExpiredSessions(now));
|
||||
assertEquals(0, restarted.sweepExpiredSessions(now));
|
||||
assertEquals("valid-secret", restarted.findSecretKey("ASIAVALIDPRESIGN", "valid-token").orElseThrow());
|
||||
|
||||
IamService subsequentRestart = newService(dir);
|
||||
assertEquals(0, subsequentRestart.sweepExpiredSessions(now));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredSessionsWithoutOriginAreRemovedFromTheirStoredAccounts(@TempDir Path dir) {
|
||||
Instant now = Instant.now();
|
||||
String foreignKey = "ASIAFOREIGNEXPIRED";
|
||||
String legacyKey = "ASIALEGACYEXPIRED";
|
||||
String validKey = "ASIAFOREIGNVALID";
|
||||
StorageBackend<String, SessionCredential> raw = load(dir, "iam-sessions.json",
|
||||
new TypeReference<Map<String, SessionCredential>>() {});
|
||||
raw.put("111122223333/" + foreignKey,
|
||||
new SessionCredential(foreignKey, "secret", "token", null, now.minusSeconds(1), null));
|
||||
raw.put(legacyKey,
|
||||
new SessionCredential(legacyKey, "secret", "token", null, now.minusSeconds(1), null));
|
||||
raw.put("111122223333/" + validKey,
|
||||
new SessionCredential(validKey, "secret", "token", null, now.plusSeconds(3600), null));
|
||||
|
||||
StorageBackend<String, SessionCredential> reloaded = load(dir, "iam-sessions.json",
|
||||
new TypeReference<Map<String, SessionCredential>>() {});
|
||||
IamService restarted = newService(dir,
|
||||
new AccountAwareStorageBackend<>(reloaded, null, "000000000000"));
|
||||
assertEquals(2, restarted.sweepExpiredSessions(now));
|
||||
assertTrue(reloaded.get("111122223333/" + foreignKey).isEmpty());
|
||||
assertTrue(reloaded.get(legacyKey).isEmpty());
|
||||
assertTrue(reloaded.get("111122223333/" + validKey).isPresent());
|
||||
|
||||
StorageBackend<String, SessionCredential> subsequentReload = load(dir, "iam-sessions.json",
|
||||
new TypeReference<Map<String, SessionCredential>>() {});
|
||||
IamService subsequentRestart = newService(dir,
|
||||
new AccountAwareStorageBackend<>(subsequentReload, null, "000000000000"));
|
||||
assertEquals(0, subsequentRestart.sweepExpiredSessions(now));
|
||||
}
|
||||
|
||||
private IamService newService(Path dir) {
|
||||
return newService(dir, load(dir, "iam-sessions.json",
|
||||
new TypeReference<Map<String, SessionCredential>>() {}));
|
||||
}
|
||||
|
||||
private IamService newService(Path dir, StorageBackend<String, SessionCredential> sessionStore) {
|
||||
return new IamService(
|
||||
load(dir, "iam-users.json", new TypeReference<Map<String, IamUser>>() {}),
|
||||
load(dir, "iam-groups.json", new TypeReference<Map<String, IamGroup>>() {}),
|
||||
@@ -116,7 +171,7 @@ class IamServicePersistenceTest {
|
||||
load(dir, "iam-policies.json", new TypeReference<Map<String, IamPolicy>>() {}),
|
||||
load(dir, "iam-access-keys.json", new TypeReference<Map<String, AccessKey>>() {}),
|
||||
load(dir, "iam-instance-profiles.json", new TypeReference<Map<String, InstanceProfile>>() {}),
|
||||
load(dir, "iam-sessions.json", new TypeReference<Map<String, SessionCredential>>() {}),
|
||||
sessionStore,
|
||||
load(dir, "iam-account-aliases.json", new TypeReference<Map<String, String>>() {}),
|
||||
load(dir, "iam-password-policy.json", new TypeReference<Map<String, AccountPasswordPolicy>>() {}),
|
||||
load(dir, "iam-oidc-providers.json", new TypeReference<Map<String, OpenIDConnectProvider>>() {}),
|
||||
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ProxySelector;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(S3IamEnforcementProfile.class)
|
||||
class GeneratedPreSignedUrlAuthEnforcementIntegrationTest {
|
||||
|
||||
private static final S3RequestSigner OWNER = S3RequestSigner.signedAs("test", "test");
|
||||
|
||||
@Inject
|
||||
PreSignedUrlGenerator presignGenerator;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
IamPolicyEvaluator policyEvaluator;
|
||||
|
||||
@Test
|
||||
void generatedUrlUsesRegisteredSigV4SessionUnderEnforcedAuth() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "generated-presign-auth-" + suffix;
|
||||
String key = "exports/report with spaces.csv";
|
||||
String content = "recipient,status\nalice@example.com,DELIVERY\n";
|
||||
|
||||
given()
|
||||
.filter(OWNER)
|
||||
.when()
|
||||
.put("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(OWNER)
|
||||
.body(content)
|
||||
.when()
|
||||
.put("/" + bucket + "/" + key)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String url = presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:" + RestAssured.port, bucket, key, "GET", 3600);
|
||||
URI uri = URI.create(url);
|
||||
String credential = queryParam(uri, "X-Amz-Credential");
|
||||
String sessionToken = queryParam(uri, "X-Amz-Security-Token");
|
||||
String accessKeyId = credential.substring(0, credential.indexOf('/'));
|
||||
|
||||
assertTrue(accessKeyId.matches("ASIA[A-Z0-9]{16}"));
|
||||
assertNotNull(sessionToken);
|
||||
assertEquals("000000000000", iamService.resolveAccountId(accessKeyId).orElseThrow());
|
||||
assertTrue(iamService.findSecretKey(accessKeyId, sessionToken).isPresent());
|
||||
|
||||
CallerContext scopedCaller = iamService.resolveCallerContext(accessKeyId);
|
||||
assertNotNull(scopedCaller);
|
||||
String objectArn = "arn:aws:s3:::" + bucket + "/" + key;
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED,
|
||||
policyEvaluator.simulatePrincipalPolicy(scopedCaller, "s3:GetObject", objectArn, Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY,
|
||||
policyEvaluator.simulatePrincipalPolicy(scopedCaller, "s3:PutObject", objectArn, Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY,
|
||||
policyEvaluator.simulatePrincipalPolicy(scopedCaller, "s3:GetObject",
|
||||
"arn:aws:s3:::" + bucket + "/other.csv", Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY,
|
||||
policyEvaluator.simulatePrincipalPolicy(scopedCaller, "sqs:SendMessage", "*", Map.of()));
|
||||
|
||||
S3RequestSigner scopedSigner = S3RequestSigner.signedAs(accessKeyId,
|
||||
iamService.findSecretKey(accessKeyId, sessionToken).orElseThrow(), sessionToken);
|
||||
given().filter(scopedSigner).when().get("/" + bucket + "/other.csv")
|
||||
.then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));
|
||||
given().filter(scopedSigner).body("changed").when().put("/" + bucket + "/" + key)
|
||||
.then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));
|
||||
|
||||
URI wildcardUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:" + RestAssured.port, bucket, "wild*.csv", "GET", 60));
|
||||
String wildcardKey = queryParam(wildcardUri, "X-Amz-Credential").split("/", 2)[0];
|
||||
String wildcardToken = queryParam(wildcardUri, "X-Amz-Security-Token");
|
||||
S3RequestSigner wildcardSigner = S3RequestSigner.signedAs(wildcardKey,
|
||||
iamService.findSecretKey(wildcardKey, wildcardToken).orElseThrow(), wildcardToken);
|
||||
given().filter(wildcardSigner).when().get("/" + bucket + "/wild-other.csv")
|
||||
.then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(uri.getRawPath() + "?" + uri.getRawQuery())
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo(content));
|
||||
|
||||
String tamperedQuery = uri.getRawQuery().replaceFirst(
|
||||
"X-Amz-Signature=[0-9a-f]+", "X-Amz-Signature=" + "0".repeat(64));
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(uri.getRawPath() + "?" + tamperedQuery)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
|
||||
given().filter(OWNER).when().delete("/" + bucket + "/" + key).then().statusCode(204);
|
||||
given().filter(OWNER).when().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedUrlRegistersFreshCredentialsAfterStoredSessionIsRemoved() {
|
||||
String bucket = "generated-presign-reset-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String baseUrl = "http://localhost:" + RestAssured.port;
|
||||
URI oldUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "report.csv", "GET", 3600));
|
||||
String oldAccessKeyId = queryParam(oldUri, "X-Amz-Credential").split("/", 2)[0];
|
||||
|
||||
// A state reset removes the persisted IAM session while this generator stays alive.
|
||||
iamService.unregisterSession("000000000000", oldAccessKeyId);
|
||||
|
||||
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
|
||||
given().filter(OWNER).body("after reset").when().put("/" + bucket + "/report.csv")
|
||||
.then().statusCode(200);
|
||||
|
||||
URI newUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "report.csv", "GET", 3600));
|
||||
String newAccessKeyId = queryParam(newUri, "X-Amz-Credential").split("/", 2)[0];
|
||||
assertNotEquals(oldAccessKeyId, newAccessKeyId);
|
||||
assertTrue(iamService.findSecretKey(newAccessKeyId,
|
||||
queryParam(newUri, "X-Amz-Security-Token")).isPresent());
|
||||
|
||||
given().urlEncodingEnabled(false).when().get(newUri.getRawPath() + "?" + newUri.getRawQuery())
|
||||
.then().statusCode(200).body(equalTo("after reset"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedPutUrlCanReplaceObjectConditionallyUnderEnforcedIam() {
|
||||
String bucket = "generated-presign-conditional-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String key = "object.txt";
|
||||
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
|
||||
String eTag = given().filter(OWNER).body("old").when().put("/" + bucket + "/" + key)
|
||||
.then().statusCode(200).extract().header("ETag");
|
||||
|
||||
URI uri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:" + RestAssured.port, bucket, key, "PUT", 60));
|
||||
String accessKeyId = queryParam(uri, "X-Amz-Credential").split("/", 2)[0];
|
||||
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
|
||||
String objectArn = "arn:aws:s3:::" + bucket + "/" + key;
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED,
|
||||
policyEvaluator.simulatePrincipalPolicy(caller, "s3:GetObject", objectArn, Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.IMPLICIT_DENY,
|
||||
policyEvaluator.simulatePrincipalPolicy(caller, "s3:GetObject",
|
||||
"arn:aws:s3:::" + bucket + "/other.txt", Map.of()));
|
||||
|
||||
given().urlEncodingEnabled(false).header("If-Match", eTag).body("new")
|
||||
.when().put(uri.getRawPath() + "?" + uri.getRawQuery()).then().statusCode(200);
|
||||
given().filter(OWNER).when().get("/" + bucket + "/" + key)
|
||||
.then().statusCode(200).body(equalTo("new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedPutUrlCannotAddTagsWithoutTaggingPermission() {
|
||||
String bucket = "generated-presign-tags-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
|
||||
|
||||
URI uri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:" + RestAssured.port, bucket, "object.txt", "PUT", 60));
|
||||
String pathAndQuery = uri.getRawPath() + "?" + uri.getRawQuery();
|
||||
|
||||
given().urlEncodingEnabled(false).header("x-amz-tagging", "team=eng").body("tagged")
|
||||
.when().put(pathAndQuery)
|
||||
.then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));
|
||||
given().urlEncodingEnabled(false).body("untagged")
|
||||
.when().put(pathAndQuery).then().statusCode(200);
|
||||
given().filter(OWNER).when().get("/" + bucket + "/object.txt")
|
||||
.then().statusCode(200).body(equalTo("untagged"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedUrlsKeepLeadingSlashKeysDistinctUnderEnforcedIam() throws Exception {
|
||||
String bucket = "generated-presign-slash-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String baseUrl = "http://localhost:" + RestAssured.port;
|
||||
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
|
||||
|
||||
URI putUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "/object.txt", "PUT", 60));
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpResponse<String> put = client.send(HttpRequest.newBuilder(putUri)
|
||||
.PUT(HttpRequest.BodyPublishers.ofString("leading slash")).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, put.statusCode(), put.body());
|
||||
|
||||
URI getUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "/object.txt", "GET", 60));
|
||||
HttpResponse<String> get = client.send(HttpRequest.newBuilder(getUri).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, get.statusCode(), get.body());
|
||||
assertEquals("leading slash", get.body());
|
||||
given().filter(OWNER).when().get("/" + bucket + "/object.txt").then().statusCode(404);
|
||||
|
||||
URI alteredUri = URI.create(getUri.toString().replace("/" + bucket + "//", "/" + bucket + "/"));
|
||||
HttpResponse<String> altered = client.send(HttpRequest.newBuilder(alteredUri).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(403, altered.statusCode(), altered.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxiedGeneratedUrlUsesTheSignedPathWhenHostMatchesBucket() throws Exception {
|
||||
String bucket = "generated-presign-proxy-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
|
||||
given().filter(OWNER).body("signed object").when().put("/" + bucket + "/object.txt")
|
||||
.then().statusCode(200);
|
||||
given().filter(OWNER).body("other object").when().put("/" + bucket + "/" + bucket + "/object.txt")
|
||||
.then().statusCode(200);
|
||||
|
||||
HttpClient proxyClient = HttpClient.newBuilder()
|
||||
.proxy(ProxySelector.of(new InetSocketAddress("localhost", RestAssured.port)))
|
||||
.build();
|
||||
String baseUrl = "http://" + bucket;
|
||||
URI getUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "object.txt", "GET", 60));
|
||||
HttpResponse<String> get = proxyClient.send(HttpRequest.newBuilder(getUri).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, get.statusCode(), get.body());
|
||||
assertEquals("signed object", get.body());
|
||||
|
||||
URI putUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
baseUrl, bucket, "object.txt", "PUT", 60));
|
||||
HttpResponse<String> put = proxyClient.send(HttpRequest.newBuilder(putUri)
|
||||
.PUT(HttpRequest.BodyPublishers.ofString("updated object")).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, put.statusCode(), put.body());
|
||||
given().filter(OWNER).when().get("/" + bucket + "/object.txt")
|
||||
.then().statusCode(200).body(equalTo("updated object"));
|
||||
given().filter(OWNER).when().get("/" + bucket + "/" + bucket + "/object.txt")
|
||||
.then().statusCode(200).body(equalTo("other object"));
|
||||
}
|
||||
|
||||
private static String queryParam(URI uri, String name) {
|
||||
for (String pair : uri.getRawQuery().split("&")) {
|
||||
int equals = pair.indexOf('=');
|
||||
if (equals > 0 && name.equals(pair.substring(0, equals))) {
|
||||
return URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class GeneratedPreSignedUrlDefaultAuthIntegrationTest {
|
||||
|
||||
@Inject
|
||||
PreSignedUrlGenerator generator;
|
||||
|
||||
@Test
|
||||
void generatedUrlStillVerifiesItsSignatureWhenGlobalSignatureChecksAreDisabled() {
|
||||
String bucket = "generated-default-auth-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given().when().put("/" + bucket).then().statusCode(200);
|
||||
given().body("original").when().put("/" + bucket + "/key").then().statusCode(200);
|
||||
|
||||
URI uri = URI.create(generator.generatePresignedUrl(
|
||||
"http://localhost:" + RestAssured.port, bucket, "key", "GET", 60));
|
||||
String pathAndQuery = uri.getRawPath() + "?" + uri.getRawQuery();
|
||||
given().urlEncodingEnabled(false).when().get(pathAndQuery)
|
||||
.then().statusCode(200).body(equalTo("original"));
|
||||
|
||||
String tampered = pathAndQuery.replaceFirst("X-Amz-Signature=[0-9a-f]+",
|
||||
"X-Amz-Signature=" + "0".repeat(64));
|
||||
given().urlEncodingEnabled(false).when().get(tampered)
|
||||
.then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
|
||||
given().when().delete("/" + bucket + "/key").then().statusCode(204);
|
||||
given().when().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PreSignedUrlGeneratorSessionTest {
|
||||
|
||||
@Test
|
||||
void renewingCredentialsKeepsOldUrlsUsableUntilSessionExpiry() {
|
||||
Instant start = Instant.parse("2026-09-27T00:00:00Z");
|
||||
Clock clock = mock(Clock.class);
|
||||
when(clock.instant()).thenReturn(start, start.plus(Duration.ofDays(1)),
|
||||
start.plus(Duration.ofDays(7)).plusSeconds(2));
|
||||
|
||||
Map<String, String> secrets = new ConcurrentHashMap<>();
|
||||
IamService iamService = mock(IamService.class);
|
||||
doAnswer(invocation -> {
|
||||
secrets.put(invocation.getArgument(1), invocation.getArgument(2));
|
||||
return null;
|
||||
}).when(iamService).registerPresignedUrlSession(anyString(), anyString(), anyString(),
|
||||
anyString(), any(Instant.class), anyString(), anyString(), anyString());
|
||||
when(iamService.findSecretKey(anyString(), anyString())).thenAnswer(invocation ->
|
||||
Optional.ofNullable(secrets.get(invocation.getArgument(0))));
|
||||
doAnswer(invocation -> {
|
||||
secrets.remove(invocation.getArgument(1));
|
||||
return null;
|
||||
}).when(iamService).unregisterSession(anyString(), anyString());
|
||||
|
||||
PreSignedUrlGenerator generator = new PreSignedUrlGenerator(
|
||||
"secret", 3600, true, "us-east-1", "000000000000",
|
||||
iamService, null, new SecureRandom(), clock);
|
||||
String first = generator.generatePresignedUrl(
|
||||
"http://localhost:4566", "bucket", "one", "GET", 604800);
|
||||
String firstKey = accessKey(first);
|
||||
String second = generator.generatePresignedUrl(
|
||||
"http://localhost:4566", "bucket", "two", "GET", 604800);
|
||||
String secondKey = accessKey(second);
|
||||
|
||||
assertNotEquals(firstKey, secondKey);
|
||||
assertTrue(secrets.containsKey(firstKey), "The original URL is still valid after renewal");
|
||||
assertTrue(secrets.containsKey(secondKey));
|
||||
assertEquals(2, secrets.size());
|
||||
|
||||
generator.generatePresignedUrl("http://localhost:4566", "bucket", "three", "GET", 3600);
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
void credentialsExpireWithTheirUrlsAndAreScopedToAnObjectAndMethod() {
|
||||
Instant start = Instant.parse("2026-09-27T00:00:00Z");
|
||||
Clock clock = Clock.fixed(start, ZoneOffset.UTC);
|
||||
IamService iamService = mock(IamService.class);
|
||||
PreSignedUrlGenerator generator = new PreSignedUrlGenerator(
|
||||
"secret", 3600, true, "us-east-1", "000000000000",
|
||||
iamService, null, new SecureRandom(), clock);
|
||||
|
||||
String first = generator.generatePresignedUrl("http://localhost:4566", "bucket", "a", "GET", 60);
|
||||
String second = generator.generatePresignedUrl("http://localhost:4566", "bucket", "b", "GET", 60);
|
||||
String third = generator.generatePresignedUrl("http://localhost:4566", "bucket", "a", "PUT", 60);
|
||||
assertNotEquals(accessKey(first), accessKey(second));
|
||||
assertNotEquals(accessKey(first), accessKey(third));
|
||||
|
||||
ArgumentCaptor<Instant> expirations = ArgumentCaptor.forClass(Instant.class);
|
||||
ArgumentCaptor<String> policies = ArgumentCaptor.forClass(String.class);
|
||||
verify(iamService, times(3)).registerPresignedUrlSession(anyString(), anyString(), anyString(),
|
||||
anyString(), expirations.capture(), policies.capture(), anyString(), anyString());
|
||||
assertEquals(start.plusSeconds(61), expirations.getAllValues().getFirst());
|
||||
assertTrue(policies.getAllValues().get(0).contains("\"Action\":\"s3:GetObject\""));
|
||||
assertTrue(policies.getAllValues().get(0).contains("arn:aws:s3:::bucket/a"));
|
||||
assertTrue(policies.getAllValues().get(1).contains("arn:aws:s3:::bucket/b"));
|
||||
assertTrue(policies.getAllValues().get(2).contains("\"Action\":[\"s3:PutObject\",\"s3:GetObject\"]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> generator.generatePresignedUrl(
|
||||
"http://localhost:4566", "bucket", "a", "GET", 604801));
|
||||
}
|
||||
|
||||
private static String accessKey(String url) {
|
||||
String credential = url.split("X-Amz-Credential=", 2)[1].split("&", 2)[0];
|
||||
return credential.split("%2F", 2)[0];
|
||||
}
|
||||
}
|
||||
+72
-11
@@ -1,6 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -10,15 +14,24 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(PreSignedUrlIntegrationTest.PresignValidationProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class PreSignedUrlIntegrationTest {
|
||||
|
||||
public static final class PresignValidationProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.auth.validate-signatures", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String BUCKET = "presign-test-bucket";
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
@@ -27,6 +40,9 @@ class PreSignedUrlIntegrationTest {
|
||||
@Inject
|
||||
PreSignedUrlGenerator presignGenerator;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createBucketAndUploadObject() {
|
||||
@@ -43,7 +59,7 @@ class PreSignedUrlIntegrationTest {
|
||||
@Test
|
||||
@Order(2)
|
||||
void accessWithPresignedGetUrl() {
|
||||
int port = io.restassured.RestAssured.port;
|
||||
int port = RestAssured.port;
|
||||
String fullBaseUrl = "http://localhost:" + port;
|
||||
|
||||
String presignedUrl = presignGenerator.generatePresignedUrl(
|
||||
@@ -53,6 +69,7 @@ class PreSignedUrlIntegrationTest {
|
||||
URI uri = URI.create(presignedUrl);
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(uri.getRawPath() + "?" + uri.getRawQuery())
|
||||
.then()
|
||||
@@ -70,6 +87,7 @@ class PreSignedUrlIntegrationTest {
|
||||
assertTrue(url.contains("X-Amz-Credential="));
|
||||
assertTrue(url.contains("X-Amz-Date="));
|
||||
assertTrue(url.contains("X-Amz-Expires=300"));
|
||||
assertTrue(url.contains("X-Amz-Security-Token="));
|
||||
assertTrue(url.contains("X-Amz-SignedHeaders=host"));
|
||||
assertTrue(url.contains("X-Amz-Signature="));
|
||||
|
||||
@@ -77,21 +95,34 @@ class PreSignedUrlIntegrationTest {
|
||||
assertFalse(url.contains("AKIAIOSFODNN7EXAMPLE"),
|
||||
"X-Amz-Credential must not contain hardcoded AKIAIOSFODNN7EXAMPLE");
|
||||
|
||||
int credStart = url.indexOf("X-Amz-Credential=");
|
||||
int credEnd = url.indexOf("&", credStart);
|
||||
String encodedCredential = credEnd > 0
|
||||
? url.substring(credStart + "X-Amz-Credential=".length(), credEnd)
|
||||
: url.substring(credStart + "X-Amz-Credential=".length());
|
||||
String credential = URLDecoder.decode(encodedCredential, StandardCharsets.UTF_8);
|
||||
assertTrue(credential.startsWith("000000000000/"),
|
||||
"X-Amz-Credential should start with 12-digit account ID, got: " + credential);
|
||||
URI uri = URI.create(url);
|
||||
String credential = queryParam(uri, "X-Amz-Credential");
|
||||
String sessionToken = queryParam(uri, "X-Amz-Security-Token");
|
||||
String accessKeyId = credential.substring(0, credential.indexOf('/'));
|
||||
|
||||
assertTrue(accessKeyId.matches("ASIA[A-Z0-9]{16}"),
|
||||
"X-Amz-Credential should use a temporary access key, got: " + credential);
|
||||
assertNotNull(sessionToken);
|
||||
assertTrue(iamService.findSecretKey(accessKeyId, sessionToken).isPresent(),
|
||||
"The temporary credential must be registered for SigV4 validation");
|
||||
|
||||
URI secondUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:8080", BUCKET, "file.txt", "GET", 300));
|
||||
String secondCredential = queryParam(secondUri, "X-Amz-Credential");
|
||||
assertEquals(accessKeyId, secondCredential.substring(0, secondCredential.indexOf('/')),
|
||||
"Only URLs for the same object and method should reuse the scoped credential");
|
||||
assertEquals(sessionToken, queryParam(secondUri, "X-Amz-Security-Token"));
|
||||
|
||||
URI otherUri = URI.create(presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:8080", BUCKET, "second-file.txt", "GET", 300));
|
||||
assertNotEquals(accessKeyId, queryParam(otherUri, "X-Amz-Credential").split("/", 2)[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void expiredPresignedUrlReturns403() {
|
||||
// Create a URL with expired date by constructing manually
|
||||
int port = io.restassured.RestAssured.port;
|
||||
int port = RestAssured.port;
|
||||
|
||||
// Use an obviously expired date (year 2020)
|
||||
String expiredPath = "/" + BUCKET + "/secret-file.txt"
|
||||
@@ -113,7 +144,7 @@ class PreSignedUrlIntegrationTest {
|
||||
@Test
|
||||
@Order(5)
|
||||
void presignedPutUrl() {
|
||||
int port = io.restassured.RestAssured.port;
|
||||
int port = RestAssured.port;
|
||||
String fullBaseUrl = "http://localhost:" + port;
|
||||
String url = presignGenerator.generatePresignedUrl(
|
||||
fullBaseUrl, BUCKET, "uploaded-via-presign.txt", "PUT", 3600);
|
||||
@@ -121,6 +152,7 @@ class PreSignedUrlIntegrationTest {
|
||||
URI uri = URI.create(url);
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.body("uploaded via presigned PUT")
|
||||
.when()
|
||||
.put(uri.getRawPath() + "?" + uri.getRawQuery())
|
||||
@@ -136,6 +168,35 @@ class PreSignedUrlIntegrationTest {
|
||||
.body(equalTo("uploaded via presigned PUT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void tamperedPresignedUrlReturnsSignatureMismatch() {
|
||||
int port = RestAssured.port;
|
||||
String url = presignGenerator.generatePresignedUrl(
|
||||
"http://localhost:" + port, BUCKET, "secret-file.txt", "GET", 3600);
|
||||
URI uri = URI.create(url);
|
||||
String tamperedQuery = uri.getRawQuery().replaceFirst(
|
||||
"X-Amz-Signature=[0-9a-f]+", "X-Amz-Signature=" + "0".repeat(64));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(uri.getRawPath() + "?" + tamperedQuery)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
}
|
||||
|
||||
private static String queryParam(URI uri, String name) {
|
||||
for (String pair : uri.getRawQuery().split("&")) {
|
||||
int equals = pair.indexOf('=');
|
||||
if (equals > 0 && name.equals(pair.substring(0, equals))) {
|
||||
return URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- response-* query parameter overrides on presigned GET/HEAD ---
|
||||
|
||||
@Test
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class S3PresignedCanonicalRequestTest {
|
||||
|
||||
@Test
|
||||
void preservesWirePathSignedHeadersAndExplicitPayloadHash() {
|
||||
MultivaluedHashMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("tag", "b b");
|
||||
query.add("tag", "a+a");
|
||||
query.add("X-Amz-Signature", "excluded");
|
||||
Map<String, String> headers = Map.of("host", "localhost:4566", "x-custom", " a b ");
|
||||
|
||||
String canonicalRequest = S3PresignedCanonicalRequest.build(
|
||||
"PUT", "/bucket//a%2Bb", PreSignedUrlFilter.buildCanonicalQueryString(query),
|
||||
"host;x-custom", headers::get, "explicit-payload-hash");
|
||||
|
||||
assertEquals("PUT\n/bucket//a%2Bb\ntag=a%2Ba&tag=b%20b\n"
|
||||
+ "host:localhost:4566\nx-custom:a b\n\nhost;x-custom\nexplicit-payload-hash",
|
||||
canonicalRequest);
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
@@ -21,8 +20,11 @@ class S3PresignedPutTaggingIntegrationTest {
|
||||
|
||||
private static final String BUCKET = "presigned-tagging-bucket";
|
||||
|
||||
@Inject
|
||||
PreSignedUrlGenerator presignGenerator;
|
||||
// These tests exercise S3 tagging dispatch with deliberately edited URL parameters.
|
||||
// The CDI presigner now uses registered SigV4 credentials, so editing its signature
|
||||
// would correctly fail. Authenticated SigV4 tagging is covered by the companion suite.
|
||||
private final PreSignedUrlGenerator presignGenerator =
|
||||
new PreSignedUrlGenerator("test", 3600, false);
|
||||
|
||||
/**
|
||||
* Regression test for #932: a presigned PUT URL whose {@code X-Amz-SignedHeaders}
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(S3EnforceAuthProfile.class)
|
||||
class SesExportJobS3AuthEnforcementIntegrationTest {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=111122223333/20260101/eu-west-2/ses/aws4_request";
|
||||
|
||||
@Test
|
||||
void completedExportUrlCanBeFetchedWhenS3AuthIsEnforced() {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", AUTH)
|
||||
.body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\"}}")
|
||||
.when()
|
||||
.put("/v2/email/account/vdm")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String jobId = given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", AUTH)
|
||||
.body("""
|
||||
{"ExportDataSource": {"MessageInsightsDataSource":
|
||||
{"StartDate": %d, "EndDate": %d}},
|
||||
"ExportDestination": {"DataFormat": "CSV"}}
|
||||
""".formatted(Instant.now().minus(Duration.ofDays(1)).getEpochSecond(),
|
||||
Instant.now().plus(Duration.ofDays(1)).getEpochSecond()))
|
||||
.when()
|
||||
.post("/v2/email/export-jobs")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("JobId");
|
||||
|
||||
assertEquals("COMPLETED", awaitTerminal(jobId));
|
||||
|
||||
String url = given()
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.get("/v2/email/export-jobs/" + jobId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("ExportDestination.S3Url");
|
||||
URI uri = URI.create(url);
|
||||
String encodedCredential = Arrays.stream(uri.getRawQuery().split("&"))
|
||||
.filter(parameter -> parameter.startsWith("X-Amz-Credential="))
|
||||
.findFirst().orElseThrow().substring("X-Amz-Credential=".length());
|
||||
String credential = URLDecoder.decode(encodedCredential, StandardCharsets.UTF_8);
|
||||
assertTrue(credential.endsWith("/eu-west-2/s3/aws4_request"));
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Host", uri.getRawAuthority())
|
||||
.when()
|
||||
.get(uri.getRawPath() + "?" + uri.getRawQuery())
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(startsWith("\"messageid\",\"sendtimestamp\""));
|
||||
}
|
||||
|
||||
private static String awaitTerminal(String jobId) {
|
||||
for (int attempt = 0; attempt < 100; attempt++) {
|
||||
Response response = given()
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.get("/v2/email/export-jobs/" + jobId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().response();
|
||||
String status = response.path("JobStatus");
|
||||
if (!"PROCESSING".equals(status) && !"CREATED".equals(status)) {
|
||||
return status;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("interrupted while waiting for the export job", e);
|
||||
}
|
||||
}
|
||||
throw new AssertionError("export job " + jobId + " never reached a terminal state");
|
||||
}
|
||||
}
|
||||
+14
-8
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -51,6 +52,15 @@ class SesExportJobV2IntegrationTest {
|
||||
.when().post("/v2/email/export-jobs");
|
||||
}
|
||||
|
||||
private static String fetchExportCsv(String url) {
|
||||
URI uri = URI.create(url);
|
||||
// SigV4 signs Host as well as path and query. Keep the authority from the issued URL
|
||||
// while routing the request to the random Quarkus test listener.
|
||||
return given().urlEncodingEnabled(false).header("Host", uri.getRawAuthority())
|
||||
.when().get(uri.getRawPath() + "?" + uri.getRawQuery())
|
||||
.then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static String insightsSource() {
|
||||
return """
|
||||
{"ExportDataSource": {"MessageInsightsDataSource":
|
||||
@@ -218,8 +228,7 @@ class SesExportJobV2IntegrationTest {
|
||||
|
||||
// The URL is Floci's own S3 emulation, so the object is fetched back through it.
|
||||
String url = job.path("ExportDestination.S3Url");
|
||||
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
|
||||
String body = given().when().get(path).then().statusCode(200).extract().asString();
|
||||
String body = fetchExportCsv(url);
|
||||
assertTrue(body.startsWith("\"messageid\",\"sendtimestamp\""), body.substring(0, 60));
|
||||
assertTrue(body.contains("reader@example.com"), "the send should be in the export");
|
||||
}
|
||||
@@ -241,8 +250,7 @@ class SesExportJobV2IntegrationTest {
|
||||
String url = given().header("Authorization", AUTH)
|
||||
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
|
||||
.extract().path("ExportDestination.S3Url");
|
||||
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
|
||||
String body = given().when().get(path).then().statusCode(200).extract().asString();
|
||||
String body = fetchExportCsv(url);
|
||||
|
||||
assertTrue(body.startsWith("ISP,SEND_VOLUME\n"), body);
|
||||
assertTrue(body.contains("UNKNOWN_ISP,1.0000"), body);
|
||||
@@ -339,8 +347,7 @@ class SesExportJobV2IntegrationTest {
|
||||
String url = given().header("Authorization", AUTH)
|
||||
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
|
||||
.extract().path("ExportDestination.S3Url");
|
||||
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
|
||||
return given().when().get(path).then().statusCode(200).extract().asString();
|
||||
return fetchExportCsv(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -384,8 +391,7 @@ class SesExportJobV2IntegrationTest {
|
||||
String url = given().header("Authorization", AUTH)
|
||||
.when().get("/v2/email/export-jobs/" + jobId).then().statusCode(200)
|
||||
.extract().path("ExportDestination.S3Url");
|
||||
String path = url.substring(url.indexOf('/', url.indexOf("//") + 2));
|
||||
String body = given().when().get(path).then().statusCode(200).extract().asString();
|
||||
String body = fetchExportCsv(url);
|
||||
|
||||
assertTrue(body.startsWith("EMAIL_IDENTITY,SEND_VOLUME\n"), body);
|
||||
assertTrue(body.contains(SENDER), "a domain filter has to match the addresses inside it");
|
||||
|
||||
Reference in new issue
Block a user