fix(s3): reject unverified credentials and malformed auth in account routing (#4825) (#5059)

* fix(s3): enforce SigV4/SigV4A algorithm prefix in AccountResolver

* fix(s3): require X-Amz-Algorithm in AccountContextFilter presigned query resolution

* fix(s3): reject malformed Authorization header in S3HeaderSignatureFilter

* fix(s3): reject query presigned requests missing X-Amz-Algorithm in PreSignedUrlFilter

* test(s3): add reproduction tests for unverified credential account routing (#4825)

* fix(s3): isolate presigned query auth and permit SigV4A headers (#4825)

* fix(s3): gate signature checks on validation setting and restore unsigned presigned steering (#4825)

* fix(s3): stop unverified credentials from selecting an account (#4825)

Account selection now requires a SigV4/SigV4A Authorization scheme or a
query string carrying X-Amz-Algorithm. A bare "Credential=" header or an
X-Amz-Credential without X-Amz-Algorithm keeps feeding region resolution
only, so it can no longer steer a request into another account.

Credentials rebuilt outside the header (IAM presigned query, presigned
POST form) now carry the AWS4-HMAC-SHA256 scheme so IAM enforcement still
recognises them. With signature validation on, a query holding only
X-Amz-Signature is rejected with AuthorizationQueryParametersError.

* fix(s3): ignore unsupported Authorization headers for region and keep credential-only download URLs working (#4825)

A header without a SigV4/SigV4A scheme now selects neither account nor
region, so it cannot misattribute S3 data events to another region.

Floci's own download URLs (Lambda layers, Kubernetes init containers)
carry only X-Amz-Credential, so that parameter steers the account and
region again without X-Amz-Algorithm.

* fix(s3): let a present Authorization header win over X-Amz-Credential in account routing (#4825)

IamEnforcementFilter reads the query credential only when no Authorization
header exists. AccountContextFilter fell back to the query whenever the
header was unrecognised, so a malformed header plus X-Amz-Credential picked
an account that IAM then skipped. Both filters now use the same precedence.

* fix(s3): treat a whitespace-only Authorization header as absent in account routing (#4825)

S3's authorization parser ignores a blank header and uses the presigned
query credential, so AccountContextFilter must do the same instead of
falling back to the default account.

* fix(iam): treat a whitespace-only Authorization header as absent in IAM enforcement (#4825)

AccountContextFilter and S3 already ignore a blank header and use the
presigned query credential. IamEnforcementFilter only checked for null, so
a blank header made it find no access key and skip authorization for the
account the query credential had selected. All three now agree.

* fix(s3): presign internal lambda download URLs

* test(macie2): include SigV4 algorithm in account routing check

* docs(s3): list the SigV4A and incomplete presigned URL 400s under signature verification (#4825)

* docs(s3): say Floci does not verify SigV4A signatures yet instead of cannot
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-08 10:58:38 -04:00
1 parent df4fa58ea1
commit d39c7e1381
22 files changed
+607 -74

No files matched your search

+2
View File
@@ -269,6 +269,8 @@ For a signed request, verification rebuilds the canonical request from the wire
- an access key that is neither `test` nor registered in Floci IAM (`CreateAccessKey` keys, and STS keys with their session token), with `403 InvalidAccessKeyId`. Under `FLOCI_AUTH_VALIDATE_SIGNATURES` alone, a presigned URL from such a key falls back to the older `FLOCI_AUTH_PRESIGN_SECRET` check instead, which an SDK-made URL fails with `403 SignatureDoesNotMatch`
- a header-signed request more than 15 minutes from server time, with `403 RequestTimeTooSkewed`
- a body that does not match a declared `x-amz-content-sha256` digest, with `400 XAmzContentSHA256Mismatch`
- an `Authorization` header whose algorithm is not `AWS4-HMAC-SHA256`, with `400 AuthorizationHeaderMalformed`. This includes SigV4A (`AWS4-ECDSA-P256-SHA256`), which AWS accepts, for example on multi-region access points: Floci does not verify ECDSA signatures yet, so it refuses the request instead of serving it unverified
- a presigned URL that carries any of `X-Amz-Algorithm`, `X-Amz-Credential` or `X-Amz-Signature` but lacks one of `X-Amz-Algorithm`, `X-Amz-Credential`, `X-Amz-Signature`, `X-Amz-Date`, `X-Amz-SignedHeaders` or `X-Amz-Expires`, with `400 AuthorizationQueryParametersError`
`FLOCI_AUTH_VALIDATE_SIGNATURES` is authentication alone: use it when forged or stale credentials must fail but buckets should stay reachable without policies. `FLOCI_SERVICES_S3_ENFORCE_AUTH` adds authorization, so it also decides anonymous access the way AWS does: a bucket that anonymous clients read needs a public-read bucket policy or ACL.
@@ -87,8 +87,13 @@ public class AccountContextFilter implements ContainerRequestFilter {
rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceName(auth));
rejectPartitionAbsentService(ctx, SigV4CredentialScope.serviceName(auth).orElse(null));
} else {
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()) {
// A present Authorization header wins, as in IamEnforcementFilter: an unrecognised one
// must not let the query string pick an account that IAM then never checks.
boolean hasAuthHeader = auth != null && !auth.isBlank();
String credential = hasAuthHeader
? null : ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()
&& ctx.getUriInfo().getQueryParameters().containsKey("X-Amz-Algorithm")) {
String presignedAkid = accountResolver.extractPresignedAccessKeyId(credential);
requestContext.setAccountId(
resolveAccount(presignedAkid, accountResolver.resolveFromPresignedCredential(credential)));
@@ -11,6 +11,9 @@ import java.util.regex.Pattern;
public class AccountResolver {
private static final Pattern AKID_PATTERN = Pattern.compile("Credential=([^/]+)/");
public static final String SIGV4_SCHEME = "AWS4-HMAC-SHA256";
private static final String SIGV4_PREFIX = SIGV4_SCHEME + " ";
private static final String SIGV4A_PREFIX = "AWS4-ECDSA-P256-SHA256 ";
private final String defaultAccountId;
@@ -42,10 +45,14 @@ public class AccountResolver {
* or returns null if the header is absent or does not contain a Credential field.
*/
public String extractAccessKeyId(String authorizationHeader) {
if (authorizationHeader == null) {
if (authorizationHeader == null || authorizationHeader.isBlank()) {
return null;
}
Matcher m = AKID_PATTERN.matcher(authorizationHeader);
String trimmed = authorizationHeader.trim();
if (!trimmed.startsWith(SIGV4_PREFIX) && !trimmed.startsWith(SIGV4A_PREFIX)) {
return null;
}
Matcher m = AKID_PATTERN.matcher(trimmed);
return m.find() ? m.group(1) : null;
}
@@ -257,7 +257,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
String auth = ctx.getHeaderString("Authorization");
if (auth == null) {
if (auth == null || auth.isBlank()) {
auth = requestAuthorization(null, ctx.getUriInfo().getQueryParameters());
}
if (auth == null) {
@@ -944,7 +944,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return authorizationHeader;
}
String credential = queryParameters == null ? null : queryParameters.getFirst("X-Amz-Credential");
return credential == null || credential.isBlank() ? null : "Credential=" + credential;
if (credential == null || credential.isBlank()) {
return null;
}
// The scheme makes AccountResolver recognise a credential that did not come from the header.
return AccountResolver.SIGV4_SCHEME + " Credential=" + credential;
}
/**
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -44,14 +45,17 @@ public class LambdaLayerController {
private final ObjectMapper objectMapper;
private final LambdaLayerService layerService;
private final RegionResolver regionResolver;
private final PreSignedUrlGenerator presignGenerator;
@Inject
public LambdaLayerController(ObjectMapper objectMapper,
LambdaLayerService layerService,
RegionResolver regionResolver) {
RegionResolver regionResolver,
PreSignedUrlGenerator presignGenerator) {
this.objectMapper = objectMapper;
this.layerService = layerService;
this.regionResolver = regionResolver;
this.presignGenerator = presignGenerator;
}
@POST
@@ -195,13 +199,7 @@ public class LambdaLayerController {
}
/**
* Path-style URL to the archive in Floci's own S3 (a presigned URL in real AWS),
* built from the request so it targets the same endpoint the client is talking to.
* Segments are percent-encoded directly rather than through {@code UriBuilder.path},
* whose template syntax would throw on a layer name containing braces.
* Clients fetch this URL unsigned, so an {@code X-Amz-Credential} query steers
* Floci's account filter to the layer's owning account; without it a layer owned
* by a non-default account resolves the default-account bucket and 404s.
* Signed URL to the archive in Floci's own S3, using the layer's owning account.
*/
private String tasksLocation(LambdaLayerVersion lv, String region, UriInfo uriInfo) {
String base = uriInfo.getBaseUri().toString();
@@ -211,9 +209,7 @@ public class LambdaLayerController {
String account = AwsArnUtils.accountOrDefault(lv.getLayerVersionArn(), "000000000000");
String bucket = LambdaService.tasksBucketName(region);
String key = LambdaService.layerObjectKey(account, lv.getLayerName(), lv.getVersion());
return base + "/" + LambdaService.encodeObjectPath(bucket)
+ "/" + LambdaService.encodeObjectPath(key)
+ "?X-Amz-Credential=" + account + "%2F00010101%2F" + region + "%2Fs3%2Faws4_request";
return presignGenerator.generatePresignedUrl(base, bucket, key, "GET", 0, region, account);
}
private ObjectNode buildLayerVersionSummary(LambdaLayerVersion lv) {
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
import io.github.hectorvent.floci.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Typed;
@@ -93,6 +94,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
private final LambdaPodSpecFactory podSpecFactory;
private final KubernetesPodLogStreamer logStreamer;
private final S3Service s3Service;
private final PreSignedUrlGenerator presignGenerator;
private final Object orphanSweepLock = new Object();
private volatile boolean orphansSwept = false;
@@ -111,7 +113,8 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
LambdaLayerService layerService,
LambdaPodSpecFactory podSpecFactory,
KubernetesPodLogStreamer logStreamer,
S3Service s3Service) {
S3Service s3Service,
PreSignedUrlGenerator presignGenerator) {
this.client = client;
this.config = config;
this.runtimeApiServerFactory = runtimeApiServerFactory;
@@ -122,6 +125,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
this.podSpecFactory = podSpecFactory;
this.logStreamer = logStreamer;
this.s3Service = s3Service;
this.presignGenerator = presignGenerator;
}
/**
@@ -423,16 +427,11 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
}
/**
* Download URL for a tasks-bucket object. The init container fetches it over plain
* HTTP with no SigV4 header, so an {@code X-Amz-Credential} query steers Floci's
* account filter to the object's owning account. Without it a function or layer
* owned by a non-default account resolves the default-account prefix and 404s. A
* 12-digit account id doubles as its own access key id (LocalStack convention).
* Signed download URL for a tasks-bucket object owned by the given account.
*/
private String downloadUrl(String bucket, String key, String account, String region) {
return addressResolver.downloadBaseUrl() + "/" + bucket + "/"
+ LambdaService.encodeObjectPath(key)
+ "?X-Amz-Credential=" + account + "%2F00010101%2F" + region + "%2Fs3%2Faws4_request";
return presignGenerator.generatePresignedUrl(addressResolver.downloadBaseUrl(),
bucket, key, "GET", 0, region, account);
}
private void awaitRunning(String namespace, String podName, String functionName) {
@@ -4,9 +4,13 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
@@ -27,11 +31,16 @@ import java.util.Set;
import java.util.stream.Collectors;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class PreSignedUrlFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(PreSignedUrlFilter.class);
private static final String LEGACY_ACCESS_KEY_ID = "test";
private static final String LEGACY_SECRET_KEY = "test";
private static final Set<String> PRESIGNED_AUTH_SIGNALS = Set.of(
"X-Amz-Algorithm",
"X-Amz-Credential",
"X-Amz-Signature");
private static final Set<String> CHECKSUM_HEADERS_REQUIRING_SIGNATURE =
Set.of(
"x-amz-checksum-algorithm",
@@ -46,20 +55,34 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
private final S3Service s3Service;
private final IamService iamService;
private final CurrentVertxRequest currentVertxRequest;
private final ResourceInfo resourceInfo;
@Inject
public PreSignedUrlFilter(PreSignedUrlGenerator presignGenerator,
S3Service s3Service,
IamService iamService,
CurrentVertxRequest currentVertxRequest) {
CurrentVertxRequest currentVertxRequest,
@Context ResourceInfo resourceInfo) {
this.presignGenerator = presignGenerator;
this.s3Service = s3Service;
this.iamService = iamService;
this.currentVertxRequest = currentVertxRequest;
this.resourceInfo = resourceInfo;
}
PreSignedUrlFilter(PreSignedUrlGenerator presignGenerator,
S3Service s3Service,
IamService iamService,
CurrentVertxRequest currentVertxRequest) {
this(presignGenerator, s3Service, iamService, currentVertxRequest, null);
}
@Override
public void filter(ContainerRequestContext requestContext) {
if (!S3SignatureFilterScope.routedToS3(resourceInfo)) {
return;
}
// A browser preflight reuses the target request's presigned URL, so its OPTIONS method
// must not be verified against a signature created for the follow-up PUT/GET request.
// The dedicated S3 OPTIONS resource performs the bucket CORS evaluation instead.
@@ -69,9 +92,29 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters();
boolean hasPresignedAuthSignal = false;
for (String param : PRESIGNED_AUTH_SIGNALS) {
if (queryParams.containsKey(param)) {
hasPresignedAuthSignal = true;
break;
}
}
if (!hasPresignedAuthSignal) {
return;
}
// Only process if this is a pre-signed URL request
String algorithm = queryParams.getFirst("X-Amz-Algorithm");
if (algorithm == null) {
if (S3SignatureFilterScope.verifiesSignatures(s3Service, presignGenerator)) {
requestContext.abortWith(
errorResponse(
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS,
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE,
S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE
)
);
}
return;
}
@@ -140,6 +140,12 @@ public class PreSignedUrlGenerator {
*/
public String generatePresignedUrl(String baseUrl, String bucket, String key,
String method, int expiresSeconds, String region) {
return generatePresignedUrl(baseUrl, bucket, key, method, expiresSeconds, region,
resolveSigningIdentity(region).accountId());
}
public String generatePresignedUrl(String baseUrl, String bucket, String key,
String method, int expiresSeconds, String region, String accountId) {
int expiry = expiresSeconds > 0 ? expiresSeconds : defaultExpiry;
if (expiry < 1 || expiry > MAX_PRESIGN_EXPIRY_SECONDS) {
throw new IllegalArgumentException("Presigned URL expiry must be between 1 and 604800 seconds");
@@ -148,10 +154,10 @@ public class PreSignedUrlGenerator {
String amzDate = AMZ_DATE_FORMAT.format(signedAt);
if (iamService == null) {
return generateLegacyPresignedUrl(baseUrl, bucket, key, method, expiry, amzDate, region);
return generateLegacyPresignedUrl(baseUrl, bucket, key, method, expiry, amzDate, region, accountId);
}
SigningIdentity identity = resolveSigningIdentity(region);
SigningIdentity identity = new SigningIdentity(accountId, region);
TemporaryCredential temporaryCredential = temporaryCredential(identity, bucket, key, method, signedAt, expiry);
String date = amzDate.substring(0, 8);
String credentialScope = date + "/" + identity.region() + "/s3/aws4_request";
@@ -193,8 +199,8 @@ public class PreSignedUrlGenerator {
}
private String generateLegacyPresignedUrl(String baseUrl, String bucket, String key,
String method, int expiry, String amzDate, String region) {
String accountId = resolveSigningIdentity(region).accountId();
String method, int expiry, String amzDate, String region,
String accountId) {
String credential = accountId + "/" + amzDate.substring(0, 8)
+ "/" + region + "/s3/aws4_request";
@@ -3544,7 +3544,7 @@ public class S3Controller {
rejectUnknownPostRegion(credential);
if (credential != null && !credential.isEmpty()) {
iamEnforcementFilter.authorizeAdditionalResource(
"Credential=" + credential, "s3:PutObject",
AccountResolver.SIGV4_SCHEME + " Credential=" + credential, "s3:PutObject",
S3PublicAccessEvaluator.objectArn(s3Service.bucketPartition(bucket), bucket, key));
}
@@ -85,26 +85,41 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
private final PreSignedUrlGenerator presignGenerator;
private final IamService iamService;
private final CurrentVertxRequest currentVertxRequest;
@Context
ResourceInfo resourceInfo;
private final ResourceInfo resourceInfo;
@Inject
public S3HeaderSignatureFilter(S3Service s3Service, PreSignedUrlGenerator presignGenerator,
IamService iamService, CurrentVertxRequest currentVertxRequest) {
public S3HeaderSignatureFilter(S3Service s3Service,
PreSignedUrlGenerator presignGenerator,
IamService iamService,
CurrentVertxRequest currentVertxRequest,
@Context ResourceInfo resourceInfo) {
this.s3Service = s3Service;
this.presignGenerator = presignGenerator;
this.iamService = iamService;
this.currentVertxRequest = currentVertxRequest;
this.resourceInfo = resourceInfo;
}
S3HeaderSignatureFilter(S3Service s3Service,
PreSignedUrlGenerator presignGenerator,
IamService iamService,
CurrentVertxRequest currentVertxRequest) {
this(s3Service, presignGenerator, iamService, currentVertxRequest, null);
}
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
if (!verifiesSignatures() || !routedToS3()) {
if (!S3SignatureFilterScope.routedToS3(resourceInfo)
|| !S3SignatureFilterScope.verifiesSignatures(s3Service, presignGenerator)) {
return;
}
String authorization = ctx.getHeaderString("Authorization");
if (authorization == null || !authorization.startsWith(ALGORITHM + " ")) {
if (authorization == null || authorization.isBlank()) {
return;
}
if (!authorization.startsWith(ALGORITHM + " ")) {
abort(ctx, 400, "AuthorizationHeaderMalformed",
"The authorization header you provided is invalid.");
return;
}
@@ -188,14 +203,6 @@ public class S3HeaderSignatureFilter implements ContainerRequestFilter {
}
}
private boolean verifiesSignatures() {
return s3Service.isAuthEnforced() || presignGenerator.shouldValidateSignatures();
}
private boolean routedToS3() {
return resourceInfo != null && S3Controller.class.equals(resourceInfo.getResourceClass());
}
private boolean signatureMatches(ContainerRequestContext ctx, String secretKey, String scopeDate,
String region, String amzDate, String signedHeaders,
String payloadHash, String signature) throws Exception {
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.s3;
import jakarta.ws.rs.container.ResourceInfo;
final class S3SignatureFilterScope {
private S3SignatureFilterScope() {
}
static boolean verifiesSignatures(S3Service s3Service, PreSignedUrlGenerator presignGenerator) {
return (s3Service != null && s3Service.isAuthEnforced())
|| (presignGenerator != null && presignGenerator.shouldValidateSignatures());
}
static boolean routedToS3(ResourceInfo resourceInfo) {
return resourceInfo != null && S3Controller.class.equals(resourceInfo.getResourceClass());
}
}
@@ -392,6 +392,51 @@ class AccountContextFilterTest {
assertTrue(body.contains("polygondwanaland-west-1"), body);
}
@Test
void nonSigV4AuthHeaderDoesNotSelectAccount() {
ContainerRequestContext ctx = mockContext(
"X Credential=111122223333/20260617/us-west-2/s3/aws4_request",
null);
filter.filter(ctx);
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
}
@Test
void bareCredentialHeaderSelectsNeitherAccountNorRegion() {
ContainerRequestContext ctx = mockContext(
"Credential=111122223333/20260617/us-west-2/s3/aws4_request",
null);
filter.filter(ctx);
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertEquals(DEFAULT_REGION, requestContext.getRegion());
}
@Test
void unrecognisedAuthHeaderStopsQueryCredentialFromSelectingAccount() {
ContainerRequestContext ctx = mockContext("Credential=111122223333/20260617/us-west-2/s3/aws4_request",
"444455556666/20260617/eu-west-1/s3/aws4_request");
filter.filter(ctx);
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertEquals(DEFAULT_REGION, requestContext.getRegion());
}
@Test
void blankAuthHeaderDoesNotHidePresignedQueryCredential() {
ContainerRequestContext ctx = mockContext(" ", "111122223333/20260617/eu-west-1/s3/aws4_request");
filter.filter(ctx);
assertEquals("111122223333", requestContext.getAccountId());
assertEquals("eu-west-1", requestContext.getRegion());
}
@Test
void presignedCredentialWithoutAlgorithmDoesNotSelectAccount() {
ContainerRequestContext ctx = mockContext(null,
"111122223333/20260617/eu-west-1/s3/aws4_request", null);
filter.filter(ctx);
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertEquals(DEFAULT_REGION, requestContext.getRegion());
}
@Test
void populatesAccessKeyIdInRequestContextFromAuthHeader() {
String auth = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request, "
@@ -416,16 +461,6 @@ class AccountContextFilterTest {
assertNull(requestContext.getAccessKeyId());
}
@Test
void resolvesFromPresignedCredentialWhenAlgorithmIsMissing() {
ContainerRequestContext ctx = mockContext(null,
"AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request", null);
filter.filter(ctx);
assertEquals("AKIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());
assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());
assertEquals("us-east-1", requestContext.getRegion());
}
@Test
void populatesSessionTokenInRequestContextFromHeader() {
String auth = "AWS4-HMAC-SHA256 Credential=ASIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request, "
@@ -34,6 +34,32 @@ class AccountResolverTest {
assertEquals(DEFAULT_ACCOUNT, resolver.resolve(""));
}
@Test
void extractAccessKeyIdReturnsNullForBareCredentialHeader() {
String auth = "Credential=111122223333/20260617/us-east-1/s3/aws4_request";
assertNull(resolver.extractAccessKeyId(auth));
assertEquals(DEFAULT_ACCOUNT, resolver.resolve(auth));
}
@Test
void extractAccessKeyIdReturnsNullForNonSigV4Header() {
String auth = "X Credential=111122223333/20260617/us-east-1/s3/aws4_request";
assertNull(resolver.extractAccessKeyId(auth));
}
@Test
void resolvesFallbackToDefaultForMalformedAuthHeader() {
String auth = "X Credential=111122223333/20260617/us-east-1/s3/aws4_request";
assertEquals(DEFAULT_ACCOUNT, resolver.resolve(auth));
}
@Test
void extractsAccessKeyIdFromSigV4AHeader() {
String auth = "AWS4-ECDSA-P256-SHA256 Credential=000000000001/20260617/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc";
assertEquals("000000000001", resolver.extractAccessKeyId(auth));
assertEquals("000000000001", resolver.resolve(auth));
}
// --- resolveFromPresignedCredential(String credentialValue) tests ---
@Test
@@ -1337,7 +1337,43 @@ class IamEnforcementFilterTest {
"AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request");
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
when(containerRequest.getMediaType()).thenReturn(null);
when(accountResolver.extractAccessKeyId("Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
.thenReturn("AKIADENIEDUSER");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext("AKIADENIEDUSER"))
.thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""")));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
eq(ResourcePolicyDecision.NEUTRAL),
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("s3:PutObject"),
eq("arn:aws:s3:::some-bucket/test.txt"),
any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
verify(containerRequest).abortWith(any(Response.class));
}
@Test
void filterFallsBackToPresignedCredentialWhenAuthorizationHeaderIsBlank() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
stubPresignedCredential(containerRequest,
"AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request");
when(containerRequest.getHeaderString("Authorization")).thenReturn(" ");
when(containerRequest.getMediaType()).thenReturn(null);
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
.thenReturn("AKIADENIEDUSER");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext("AKIADENIEDUSER"))
@@ -1372,7 +1408,7 @@ class IamEnforcementFilterTest {
stubPresignedCredential(containerRequest,
"AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request");
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
when(accountResolver.extractAccessKeyId("Credential=AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request"))
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request"))
.thenReturn("AKIAALLOWEDUSER");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext("AKIAALLOWEDUSER"))
@@ -81,8 +81,8 @@ class LambdaLayerIntegrationTest {
.body("Content.CodeSize", greaterThan(0))
.body("Content.CodeSha256", not(emptyString()))
.body("Content.Location", containsString("awslambda-us-east-1-tasks/layers/"))
.body("Content.Location", endsWith("/" + LAYER_NAME
+ "/1?X-Amz-Credential=000000000000%2F00010101%2Fus-east-1%2Fs3%2Faws4_request"))
.body("Content.Location", containsString("/" + LAYER_NAME + "/1?X-Amz-Algorithm=AWS4-HMAC-SHA256"))
.body("Content.Location", containsString("X-Amz-Signature="))
.body("CreatedDate", not(emptyString()));
}
@@ -327,9 +327,8 @@ class LambdaLayerIntegrationTest {
@Test
@Order(19)
void contentLocation_ofNonDefaultAccountLayer_isFetchable() throws Exception {
// The Location URL is fetched unsigned, so it must carry the owning account in
// X-Amz-Credential. Without it the download resolves the default account's
// bucket namespace and 404s for a layer published under another account.
// The Location URL is fetched without an Authorization header, so its presigned
// credential must target the layer's owning account.
String location = given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/lambda/aws4_request, SignedHeaders=host, Signature=abc")
.contentType("application/json")
@@ -341,7 +340,8 @@ class LambdaLayerIntegrationTest {
.then()
.statusCode(201)
.body("Content.Location", containsString("/layers/000000000001/"))
.body("Content.Location", containsString("X-Amz-Credential=000000000001%2F"))
.body("Content.Location", containsString("X-Amz-Algorithm=AWS4-HMAC-SHA256"))
.body("Content.Location", containsString("X-Amz-Signature="))
.extract().path("Content.Location");
given()
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambda.model.ContainerState;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
import io.github.hectorvent.floci.services.s3.PreSignedUrlGenerator;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.BeforeEach;
@@ -81,6 +82,7 @@ class KubernetesPodLauncherTest {
private LambdaLayerService layerService;
private KubernetesPodLogStreamer logStreamer;
private S3Service s3Service;
private PreSignedUrlGenerator presignGenerator;
private KubernetesPodLauncher launcher;
@BeforeEach
@@ -125,12 +127,17 @@ class KubernetesPodLauncherTest {
anyString(), anyString(), anyString())).thenReturn(() -> { });
lenient().when(logStreamer.logStreamName(anyString())).thenReturn("2026/07/25/[$LATEST]test");
s3Service = mock(S3Service.class);
presignGenerator = mock(PreSignedUrlGenerator.class);
lenient().when(presignGenerator.generatePresignedUrl(anyString(), anyString(), anyString(),
eq("GET"), eq(0), anyString(), anyString())).thenAnswer(invocation ->
invocation.getArgument(0) + "/" + invocation.getArgument(1) + "/"
+ invocation.getArgument(2) + "?X-Amz-Algorithm=AWS4-HMAC-SHA256");
apiClient = new KubernetesApiClient(
URI.create(client.getConfiguration().getMasterUrl()), trustAllHttpClient(), null);
launcher = new KubernetesPodLauncher(apiClient, config, runtimeApiServerFactory, imageResolver,
addressResolver, awsEnv, layerService, new LambdaPodSpecFactory(config),
logStreamer, s3Service);
logStreamer, s3Service, presignGenerator);
}
/** The mock server's cert is self-signed and generated per run; trust it, not the JVM default. */
@@ -254,11 +261,14 @@ class KubernetesPodLauncherTest {
ContainerHandle handle = launcher.launch(fn);
// The init container fetches unauthenticated, so the download URL must carry the
// owning account or the object resolves under the default account and 404s.
// The init container fetches without an Authorization header. The presigner
// must register its temporary credential in the owning account.
Pod pod = client.pods().inNamespace("default").withName(handle.getContainerId()).get();
assertThat(pod.getSpec().getInitContainers().getFirst().getCommand().get(2))
.contains("snapshots/111122223333/my-fn?X-Amz-Credential=111122223333%2F");
.contains("snapshots/111122223333/my-fn?X-Amz-Algorithm=AWS4-HMAC-SHA256");
verify(presignGenerator).generatePresignedUrl(eq("http://10.0.0.5:4566"),
eq("awslambda-us-east-1-tasks"), anyString(), eq("GET"), eq(0),
eq("us-east-1"), eq("111122223333"));
}
@Test
@@ -285,7 +295,7 @@ class KubernetesPodLauncherTest {
doThrow(new RuntimeException("kube api down")).when(failingApiClient).deletePod(anyString(), anyString());
KubernetesPodLauncher failingLauncher = new KubernetesPodLauncher(failingApiClient, config,
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
new LambdaPodSpecFactory(config), logStreamer, s3Service);
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator);
markPodPhaseInBackground("floci-lambda-my-fn-", "Failed");
assertThatThrownBy(() -> failingLauncher.launch(function()))
@@ -435,7 +445,7 @@ class KubernetesPodLauncherTest {
}).when(flakyApiClient).listPods(anyString(), anyMap());
KubernetesPodLauncher retryingLauncher = new KubernetesPodLauncher(flakyApiClient, config,
runtimeApiServerFactory, imageResolver, addressResolver, awsEnv, layerService,
new LambdaPodSpecFactory(config), logStreamer, s3Service);
new LambdaPodSpecFactory(config), logStreamer, s3Service, presignGenerator);
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
ContainerHandle handle = retryingLauncher.launch(function());
@@ -101,7 +101,8 @@ class MacieOrganizationIntegrationTest {
.body("{\"adminAccountId\":\"" + ADMIN_ACCOUNT + "\"}")
.post("/admin").then().statusCode(200);
given().queryParam("X-Amz-Credential",
given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential",
MANAGEMENT_ACCOUNT + "/20260101/us-east-1/macie2/aws4_request")
.get("/admin").then().statusCode(200)
.body("adminAccounts[0].accountId", equalTo(ADMIN_ACCOUNT));
@@ -2,9 +2,14 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.lang.reflect.Method;
import java.util.List;
@@ -12,6 +17,13 @@ import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class PreSignedUrlFilterTest {
@@ -198,4 +210,119 @@ class PreSignedUrlFilterTest {
"x-amz-user-agent", "x-amz-checksum-type"),
"host"));
}
@Test
void abortsWhenPresignedParamPresentWithoutAlgorithm() {
PreSignedUrlGenerator presignGenerator = mock(PreSignedUrlGenerator.class);
when(presignGenerator.shouldValidateSignatures()).thenReturn(true);
PreSignedUrlFilter filter = new PreSignedUrlFilter(presignGenerator, null, null, null, s3ResourceInfo());
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("X-Amz-Credential", "111122223333/20261001/us-east-1/s3/aws4_request");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(captor.capture());
Response response = captor.getValue();
assertEquals(400, response.getStatus());
String entity = (String) response.getEntity();
assertTrue(entity.contains("<Code>AuthorizationQueryParametersError</Code>"), entity);
assertTrue(
entity.contains(S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE),
entity);
}
@Test
void abortsWhenOnlySignatureParamPresentWithoutAlgorithm() {
PreSignedUrlGenerator presignGenerator = mock(PreSignedUrlGenerator.class);
when(presignGenerator.shouldValidateSignatures()).thenReturn(true);
PreSignedUrlFilter filter = new PreSignedUrlFilter(presignGenerator, null, null, null, s3ResourceInfo());
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("X-Amz-Signature", "abc");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(captor.capture());
assertEquals(400, captor.getValue().getStatus());
assertTrue(((String) captor.getValue().getEntity()).contains("<Code>AuthorizationQueryParametersError</Code>"));
}
@Test
void allowsPresignedParamWithoutAlgorithmWhenValidationDisabled() {
PreSignedUrlFilter filter = new PreSignedUrlFilter(null, null, null, null, s3ResourceInfo());
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("X-Amz-Credential", "111122223333/20261001/us-east-1/s3/aws4_request");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsRequestWithoutAnyPresignedParams() {
PreSignedUrlFilter filter = new PreSignedUrlFilter(null, null, null, null, s3ResourceInfo());
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("prefix", "photos/");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsHeaderSignedRequestWithDateOrExpiresQueryParam() {
PreSignedUrlFilter filter = new PreSignedUrlFilter(null, null, null, null, s3ResourceInfo());
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("X-Amz-Date", "20261001T000000Z");
queryParams.add("X-Amz-Expires", "3600");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsNonS3Routes() {
ResourceInfo nonS3Info = mock(ResourceInfo.class);
doReturn(Object.class).when(nonS3Info).getResourceClass();
PreSignedUrlFilter filter = new PreSignedUrlFilter(null, null, null, null, nonS3Info);
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.add("X-Amz-Credential", "111122223333/20261001/us-east-1/s3/aws4_request");
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(ctx.getUriInfo()).thenReturn(uriInfo);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
private static ResourceInfo s3ResourceInfo() {
ResourceInfo info = mock(ResourceInfo.class);
doReturn(S3Controller.class).when(info).getResourceClass();
return info;
}
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.s3;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class S3HeaderSignatureFilterTest {
private S3HeaderSignatureFilter filter;
private ContainerRequestContext ctx;
private ResourceInfo resourceInfo;
private PreSignedUrlGenerator presignGenerator;
@BeforeEach
void setUp() {
resourceInfo = mock(ResourceInfo.class);
doReturn(S3Controller.class).when(resourceInfo).getResourceClass();
presignGenerator = mock(PreSignedUrlGenerator.class);
when(presignGenerator.shouldValidateSignatures()).thenReturn(true);
filter = new S3HeaderSignatureFilter(null, presignGenerator, null, null, resourceInfo);
ctx = mock(ContainerRequestContext.class);
}
@Test
void abortsWhenAuthorizationHeaderDoesNotStartWithAlgorithm() throws IOException {
when(ctx.getHeaderString("Authorization"))
.thenReturn("X Credential=111122223333/20261001/us-east-1/s3/aws4_request");
filter.filter(ctx);
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(captor.capture());
Response response = captor.getValue();
assertEquals(400, response.getStatus());
String entity = (String) response.getEntity();
assertTrue(entity.contains("<Code>AuthorizationHeaderMalformed</Code>"), entity);
assertTrue(entity.contains("The authorization header you provided is invalid."), entity);
}
@Test
void allowsRequestWhenAuthorizationHeaderAbsent() throws IOException {
when(ctx.getHeaderString("Authorization")).thenReturn(null);
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsRequestWhenAuthorizationHeaderBlank() throws IOException {
when(ctx.getHeaderString("Authorization")).thenReturn(" ");
filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void ignoresRequestWhenNotRoutedToS3() throws IOException {
ResourceInfo nonS3Info = mock(ResourceInfo.class);
doReturn(Object.class).when(nonS3Info).getResourceClass();
S3HeaderSignatureFilter nonS3Filter =
new S3HeaderSignatureFilter(null, presignGenerator, null, null, nonS3Info);
when(ctx.getHeaderString("Authorization")).thenReturn("Malformed Header");
nonS3Filter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsMalformedAuthorizationHeaderWhenValidationDisabled() throws IOException {
S3HeaderSignatureFilter permissiveFilter =
new S3HeaderSignatureFilter(null, null, null, null, resourceInfo);
when(ctx.getHeaderString("Authorization"))
.thenReturn("X Credential=111122223333/20261001/us-east-1/s3/aws4_request");
permissiveFilter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void allowsSigV4AAuthorizationHeaderWhenValidationDisabled() throws IOException {
S3HeaderSignatureFilter permissiveFilter =
new S3HeaderSignatureFilter(null, null, null, null, resourceInfo);
when(ctx.getHeaderString("Authorization"))
.thenReturn("AWS4-ECDSA-P256-SHA256 Credential=111122223333/20261001/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc");
permissiveFilter.filter(ctx);
verify(ctx, never()).abortWith(any());
}
@Test
void abortsSigV4AAuthorizationHeaderWhenValidationEnabled() throws IOException {
when(ctx.getHeaderString("Authorization"))
.thenReturn("AWS4-ECDSA-P256-SHA256 Credential=111122223333/20261001/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc");
filter.filter(ctx);
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
verify(ctx).abortWith(captor.capture());
Response response = captor.getValue();
assertEquals(400, response.getStatus());
String entity = (String) response.getEntity();
assertTrue(entity.contains("<Code>AuthorizationHeaderMalformed</Code>"), entity);
assertTrue(entity.contains("The authorization header you provided is invalid."), entity);
}
}
@@ -2342,7 +2342,7 @@ class S3IntegrationTest {
@Test
@Order(95)
void notificationDeliveredToQueueInDifferentRegion() {
String sqsAuth = "Credential=AKID/20260507/ap-southeast-2/s3/aws4_request";
String sqsAuth = "AWS4-HMAC-SHA256 Credential=AKID/20260507/ap-southeast-2/s3/aws4_request";
String queueUrl = given()
.header("Authorization", sqsAuth)
@@ -10,11 +10,14 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -45,6 +48,29 @@ class S3ValidateSignaturesIntegrationTest {
private static String userAccessKeyId;
private static String userSecretKey;
@Test
void layerContentLocationCanBeFetchedWithSignatureValidationEnabled() throws Exception {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(archive)) {
zip.putNextEntry(new ZipEntry("nodejs/index.js"));
zip.write("module.exports = {};".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
String location = given()
.contentType("application/json")
.body("""
{"Content":{"ZipFile":"%s"}}
""".formatted(Base64.getEncoder().encodeToString(archive.toByteArray())))
.when()
.post("/2018-10-31/layers/signed-location/versions")
.then()
.statusCode(201)
.body("Content.Location", containsString("X-Amz-Algorithm=AWS4-HMAC-SHA256"))
.extract().path("Content.Location");
given().urlEncodingEnabled(false).when().get(location).then().statusCode(200);
}
@Test
@Order(1)
void headerSignedRequestsWithAKnownKeyAreAccepted() {
@@ -207,6 +233,67 @@ class S3ValidateSignaturesIntegrationTest {
.statusCode(204);
}
@Test
@Order(30)
void headerWithMalformedSigV4IsRejectedWithoutCreatingBucket() {
given()
.header("Authorization", "X Credential=111122223333/20261001/us-east-1/s3/aws4_request")
.when()
.put("/routing-check-malformed")
.then()
.statusCode(400)
.body("Error.Code", equalTo("AuthorizationHeaderMalformed"))
.body("Error.Message", equalTo("The authorization header you provided is invalid."));
given().filter(LOCAL_SIGNER).when().get("/routing-check-malformed").then().statusCode(404);
}
@Test
@Order(31)
void presignedQueryMissingAlgorithmIsRejectedWithoutCreatingBucket() {
given()
.when()
.put("/routing-check-missing-algo?X-Amz-Credential=111122223333%2F20261001%2Fus-east-1%2Fs3%2Faws4_request")
.then()
.statusCode(400)
.body("Error.Code", equalTo("AuthorizationQueryParametersError"))
.body("Error.Message", equalTo(S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE));
given().filter(LOCAL_SIGNER).when().get("/routing-check-missing-algo").then().statusCode(404);
}
@Test
@Order(32)
void headerSignedRequestWithDateOrExpiresQueryParamIsAccepted() {
given()
.filter(LOCAL_SIGNER)
.when()
.put("/" + BUCKET + "/query-date-test.txt?X-Amz-Date=" + AMZ_DATE + "&X-Amz-Expires=3600")
.then()
.statusCode(200);
given()
.filter(LOCAL_SIGNER)
.when()
.get("/" + BUCKET + "/query-date-test.txt")
.then()
.statusCode(200);
}
@Test
@Order(33)
void sigV4AHeaderIsRejectedWhenSignatureValidationEnabled() {
String authSigV4A = "AWS4-ECDSA-P256-SHA256 Credential=test/" + CREDENTIAL_DATE
+ "/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=30450220abc";
given()
.header("Authorization", authSigV4A)
.when()
.get("/" + BUCKET + "/" + KEY)
.then()
.statusCode(400)
.body(containsString("<Code>AuthorizationHeaderMalformed</Code>"));
}
private static void createIamUser(String userName) {
String authorization = "AWS4-HMAC-SHA256 Credential=test/" + CREDENTIAL_DATE
+ "/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=unused";
@@ -654,7 +654,7 @@ class S3VectorsIntegrationTest {
void listVectorsByIndexArnResolvesTheArnsOwnRegionNotTheRequestRegion() {
String bucketName = "cross-region-vector-bucket";
String indexName = "cross-region-idx";
String otherRegionAuth = "Credential=AKID/20260101/us-west-2/s3vectors/aws4_request";
String otherRegionAuth = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/s3vectors/aws4_request";
// Create the bucket/index in us-west-2 (via the SigV4 credential scope region).
given()