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:
XuJian authored and GitHub committed 2026-09-28 12:21:52 -04:00
1 parent 5ec18c507c
commit 864f79cf31
20 files changed
+1232 -104

No files matched your search

@@ -8,11 +8,14 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.IamService.PresignedScope;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -25,6 +28,8 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -274,7 +279,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String credentialScope = resolvedAuthorization.credentialScope();
String action = resolvedAuthorization.action();
if (action == null) {
return; // unknown action → ALLOW (permissive)
if (!"OPTIONS".equalsIgnoreCase(ctx.getMethod())
&& iamService.presignedScope(akid).isPresent()) {
ctx.abortWith(accessDeniedResponse("Unknown", credentialScope, ctx.getMediaType()));
}
return; // unknown action → ALLOW for ordinary credentials (permissive)
}
if ("sts:GetCallerIdentity".equals(action)) {
return; // AWS returns caller identity even when an identity policy explicitly denies it
@@ -328,6 +337,49 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
List<String> resources = resolveResourceArns(credentialScope,
arnBuilder.buildResources(credentialScope, ctx, region, accountId));
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
if (presignedScope.isPresent()) {
PresignedScope scope = presignedScope.get();
if ("s3".equals(credentialScope)) {
// UriInfo has normalized consecutive slashes. S3 and the SigV4 verifier use
// the wire path, where /bucket//key names the distinct object /key.
RoutingContext routingContext = currentVertxRequest.getCurrent();
HttpServerRequest request = routingContext == null ? null : routingContext.request();
// Use the wire path that S3's SigV4 verifier signs. uri() may instead be an
// absolute-form request target forwarded by a proxy.
String rawPath = request == null ? null : request.path();
if (rawPath == null || !rawPath.startsWith("/")) {
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
return;
}
String decodedPath;
try {
decodedPath = URLDecoder.decode(rawPath.replace("+", "%2B"), StandardCharsets.UTF_8);
} catch (IllegalArgumentException invalidEncoding) {
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
return;
}
resources = List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region),
"s3", "", decodedPath.substring(1)).toString());
}
// IAM's resource glob treats * and ? in object keys as patterns. An internal URL
// credential is narrower: it may authorize only its literal object and action.
if (!scope.action().equals(action) || resources.isEmpty()
|| resources.stream().anyMatch(resource -> !scope.resourceArn().equals(resource))) {
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
return;
}
// A tagged PutObject additionally requires s3:PutObjectTagging. Generated URLs
// grant only their object operation (and GetObject for conditional writes), so
// an unsigned tagging header must not add permissions to the scoped session.
if ("s3:PutObject".equals(action)
&& (ctx.getHeaderString("x-amz-tagging") != null
|| ctx.getUriInfo().getQueryParameters().containsKey("x-amz-tagging"))) {
ctx.abortWith(accessDeniedResponse("s3:PutObjectTagging", credentialScope, ctx.getMediaType()));
return;
}
}
Map<String, List<String>> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
// A request naming several resources is authorized once per resource, as on AWS, so a
// permitted first target cannot carry later targets that the policy does not allow.
@@ -154,6 +154,19 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.scan(k -> true);
}
/** Removes matching values using their actual stored keys, including unprefixed legacy keys. */
public int deleteAllAccountsMatching(Predicate<V> valueFilter) {
int removed = 0;
for (String rawKey : new ArrayList<>(delegate.keys())) {
if (delegate.get(rawKey).filter(valueFilter).isEmpty()) {
continue;
}
delegate.delete(rawKey);
removed++;
}
return removed;
}
/**
* Returns every stored entry with its raw delegate key intact.
*
@@ -70,6 +70,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final String TEMPORARY_ACCESS_KEY_PREFIX = "ASIA";
private static final String SCOPED_IDENTITY_SESSION_BASE_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
private static final String DEFAULT_DEPLOYER_USER = "floci-deployer";
private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci";
private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci";
@@ -2279,6 +2281,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
SessionCredential session = new SessionCredential(
sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration, sessionPolicyDocument,
accountId);
putSessionForAccount(accountId, sessionAccessKeyId, session);
}
/** An internal URL credential with both a session policy and an exact action/resource guard. */
public void registerPresignedUrlSession(String accountId, String accessKeyId, String secretAccessKey,
String sessionToken, Instant expiration, String policyDocument,
String action, String resourceArn) {
if (accountId == null || accountId.isBlank()) {
throw new IllegalArgumentException("Session account ID must not be blank");
}
SessionCredential session = new SessionCredential(
accessKeyId, secretAccessKey, sessionToken, null, expiration, policyDocument, accountId);
session.setPresignedAction(action);
session.setPresignedResourceArn(resourceArn);
putSessionForAccount(accountId, accessKeyId, session);
}
private void putSessionForAccount(String accountId, String sessionAccessKeyId, SessionCredential session) {
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(accountId, sessionAccessKeyId, session);
} else {
@@ -2286,6 +2306,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
public record PresignedScope(String action, String resourceArn) {
}
public Optional<PresignedScope> presignedScope(String accessKeyId) {
return currentSession(accessKeyId)
.filter(session -> session.getPresignedAction() != null
&& session.getPresignedResourceArn() != null)
.map(session -> new PresignedScope(
session.getPresignedAction(), session.getPresignedResourceArn()));
}
/**
* Stores a non-expiring session for a Lambda execution role under the function's account.
* Lambda launches can happen outside request scope, so the account namespace must be explicit.
@@ -2400,6 +2431,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return removed;
}
/** Removes expired temporary sessions, including those left in persistent storage after a restart. */
public int sweepExpiredSessions(Instant now) {
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
return aware.deleteAllAccountsMatching(session ->
session.getExpiration() != null && !session.getExpiration().isAfter(now));
}
List<SessionCredential> storedSessions = sessions.scan(key -> true);
int removed = 0;
for (SessionCredential session : storedSessions) {
if (session.getExpiration() == null || session.getExpiration().isAfter(now)) {
continue;
}
deleteSession(session.getAccessKeyId(), session);
removed++;
}
return removed;
}
/**
* Resolves the account an IAM or temporary access key belongs to. Long-term IAM access keys
* resolve from their owning account namespace. Temporary credentials resolve from the account
@@ -2474,7 +2523,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
if (session.getRoleArn() == null) {
return null; // identity session without mapped caller context — preserve historical bypass
// A locally minted identity session can carry a restrictive session policy.
// Unscoped GetSessionToken credentials retain the historical bypass.
return session.getPresignedAction() == null || session.getSessionPolicyDocument() == null ? null
: new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY),
session.getSessionPolicyDocument(), null);
}
List<String> identityPolicies = collectRolePolicies(session.getRoleArn());
String boundaryDoc = resolveRoleBoundaryDocument(session.getRoleArn());
@@ -29,6 +29,9 @@ public class SessionCredential {
private String ec2RoleId;
/** Exact ECS task ARN this session was minted for, when this is a task-role session. */
private String ecsTaskArn;
/** Exact object action and ARN for an internally generated S3 presigned URL. */
private String presignedAction;
private String presignedResourceArn;
public SessionCredential() {}
@@ -112,6 +115,12 @@ public class SessionCredential {
public String getEcsTaskArn() { return ecsTaskArn; }
public void setEcsTaskArn(String ecsTaskArn) { this.ecsTaskArn = ecsTaskArn; }
public String getPresignedAction() { return presignedAction; }
public void setPresignedAction(String presignedAction) { this.presignedAction = presignedAction; }
public String getPresignedResourceArn() { return presignedResourceArn; }
public void setPresignedResourceArn(String presignedResourceArn) { this.presignedResourceArn = presignedResourceArn; }
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }
}
@@ -124,37 +124,49 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
return;
}
// Verify signature: SigV4 when enforce-auth is enabled, custom when validateSignatures is enabled
if (s3Service.isAuthEnforced()) {
// Registered IAM credentials always carry standard SigV4. Account-shaped credentials
// from older Floci-generated URLs retain the custom validation path when enforcement is off.
boolean authEnforced = s3Service.isAuthEnforced();
String rawCredential = queryParams.getFirst("X-Amz-Credential");
String scopedAccessKey = URLDecoder.decode(rawCredential, StandardCharsets.UTF_8).split("/", 2)[0];
boolean generatedCredential = iamService != null && iamService.presignedScope(scopedAccessKey).isPresent();
if (authEnforced || presignGenerator.shouldValidateSignatures() || generatedCredential) {
String credential = queryParams.getFirst("X-Amz-Credential");
String decodedCredential = URLDecoder.decode(credential, StandardCharsets.UTF_8);
String[] credParts = decodedCredential.split("/");
if (credParts.length < 5) {
if (authEnforced || generatedCredential) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
}
} else {
String accessKeyId = credParts[0];
String secretKey = resolveSecretKey(accessKeyId, queryParams.getFirst("X-Amz-Security-Token"));
if (secretKey != null) {
if (!verifySigV4Signature(requestContext, signature, secretKey)) {
requestContext.abortWith(errorResponse(403, "SignatureDoesNotMatch",
"The request signature we calculated does not match the signature you provided."));
return;
}
List<String> unsignedChecksumHeaders = unsignedChecksumHeaders(
requestContext.getHeaders().keySet(), queryParams.getFirst("X-Amz-SignedHeaders"));
if (!unsignedChecksumHeaders.isEmpty()) {
requestContext.abortWith(headersNotSignedResponse(unsignedChecksumHeaders));
}
return;
}
}
if (authEnforced || generatedCredential) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
}
}
String accessKeyId = credParts[0];
String secretKey = resolveSecretKey(accessKeyId, queryParams.getFirst("X-Amz-Security-Token"));
if (secretKey == null) {
requestContext.abortWith(errorResponse(403, "InvalidAccessKeyId",
"The AWS Access Key Id you provided does not exist in our records."));
return;
}
if (!verifySigV4Signature(requestContext, signature, secretKey)) {
requestContext.abortWith(errorResponse(403, "SignatureDoesNotMatch",
"The request signature we calculated does not match the signature you provided."));
return;
}
List<String> unsignedChecksumHeaders = unsignedChecksumHeaders(
requestContext.getHeaders().keySet(), queryParams.getFirst("X-Amz-SignedHeaders"));
if (!unsignedChecksumHeaders.isEmpty()) {
requestContext.abortWith(headersNotSignedResponse(unsignedChecksumHeaders));
}
} else if (presignGenerator.shouldValidateSignatures()) {
if (presignGenerator.shouldValidateSignatures()) {
String path = requestContext.getUriInfo().getPath();
String[] parts = path.split("/", 3);
if (parts.length < 3) {
@@ -208,16 +220,6 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
String authority = S3VirtualHostFilter.resolveHost(requestContext.getHeaderString("Host"),
requestContext.getHeaderString("X-Forwarded-Host"), requestUri);
StringBuilder canonicalHeaders = new StringBuilder();
for (String header : signedHeaders.split(";")) {
if ("host".equals(header)) {
canonicalHeaders.append("host:").append(authority).append("\n");
} else {
String canonicalValue = canonicalizeHeaderValue(requestContext.getHeaderString(header));
canonicalHeaders.append(header).append(":").append(canonicalValue).append("\n");
}
}
// Canonical request: the wire path, since a leading-slash key travels (and is
// signed) as a double slash that JAX-RS would otherwise collapse.
String path = S3HeaderSignatureFilter.signedPath(currentVertxRequest, requestUri);
@@ -229,18 +231,12 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {
if (payloadHash == null) {
payloadHash = "UNSIGNED-PAYLOAD";
}
String canonicalRequest = requestContext.getMethod() + "\n"
+ path + "\n"
+ canonicalQueryString + "\n"
+ canonicalHeaders + "\n"
+ signedHeaders + "\n"
+ payloadHash;
// String to sign
String stringToSign = "AWS4-HMAC-SHA256\n"
+ amzDate + "\n"
+ credentialScope + "\n"
+ SigV4RequestValidator.sha256Hex(canonicalRequest);
String canonicalRequest = S3PresignedCanonicalRequest.build(
requestContext.getMethod(), path, canonicalQueryString, signedHeaders,
header -> "host".equals(header) ? authority : requestContext.getHeaderString(header),
payloadHash);
String stringToSign = S3PresignedCanonicalRequest.stringToSign(
amzDate, credentialScope, canonicalRequest);
// Derive signing key and compute expected signature
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, date, region, service);
@@ -1,23 +1,43 @@
package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedHashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@ApplicationScoped
public class PreSignedUrlGenerator {
private static final int MAX_PRESIGN_EXPIRY_SECONDS = 604800;
private static final ObjectMapper POLICY_MAPPER = new ObjectMapper();
private static final char[] ACCESS_KEY_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
private static final DateTimeFormatter AMZ_DATE_FORMAT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@@ -26,53 +46,83 @@ public class PreSignedUrlGenerator {
private final boolean validateSignatures;
private final String defaultRegion;
private final String defaultAccountId;
// Field-injected so the package-private test constructors remain valid
@Inject
Instance<RequestContext> requestContextInstance;
private final IamService iamService;
private final Instance<RequestContext> requestContextInstance;
private final SecureRandom random;
private final Clock clock;
private final ConcurrentMap<CredentialKey, TemporaryCredential> temporaryCredentials =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, RetiredCredential> retiredCredentials = new ConcurrentHashMap<>();
private final AtomicBoolean expiredSessionsSwept = new AtomicBoolean();
@Inject
public PreSignedUrlGenerator(EmulatorConfig config) {
public PreSignedUrlGenerator(EmulatorConfig config, IamService iamService,
Instance<RequestContext> requestContextInstance) {
this(config.auth().presignSecret(),
config.services().s3().defaultPresignExpirySeconds(),
config.auth().validateSignatures(),
config.defaultRegion(),
config.defaultAccountId());
config.defaultAccountId(),
iamService,
requestContextInstance,
new SecureRandom());
}
/** Package-private constructor for testing. */
PreSignedUrlGenerator(String secret, int defaultExpiry) {
this(secret, defaultExpiry, false, "us-east-1", "000000000000"); // partition-literal: test-shaped constructor default
this(secret, defaultExpiry, false, "us-east-1", "000000000000", null, null, new SecureRandom()); // partition-literal: test-shaped constructor default
}
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures) {
this(secret, defaultExpiry, validateSignatures, "us-east-1", "000000000000"); // partition-literal: test-shaped constructor default
this(secret, defaultExpiry, validateSignatures, "us-east-1", "000000000000", // partition-literal: test-shaped constructor default
null, null, new SecureRandom());
}
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion) {
this(secret, defaultExpiry, validateSignatures, defaultRegion, "000000000000");
this(secret, defaultExpiry, validateSignatures, defaultRegion, "000000000000",
null, null, new SecureRandom());
}
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion, String defaultAccountId) {
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion,
String defaultAccountId) {
this(secret, defaultExpiry, validateSignatures, defaultRegion, defaultAccountId,
null, null, new SecureRandom());
}
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion,
String defaultAccountId, IamService iamService,
Instance<RequestContext> requestContextInstance, SecureRandom random) {
this(secret, defaultExpiry, validateSignatures, defaultRegion, defaultAccountId,
iamService, requestContextInstance, random, Clock.systemUTC());
}
PreSignedUrlGenerator(String secret, int defaultExpiry, boolean validateSignatures, String defaultRegion,
String defaultAccountId, IamService iamService,
Instance<RequestContext> requestContextInstance, SecureRandom random, Clock clock) {
this.secret = secret;
this.defaultExpiry = defaultExpiry;
this.validateSignatures = validateSignatures;
this.defaultRegion = defaultRegion;
this.defaultAccountId = defaultAccountId;
this.iamService = iamService;
this.requestContextInstance = requestContextInstance;
this.random = random;
this.clock = clock;
}
private String resolveAccessKeyId() {
private SigningIdentity resolveSigningIdentity(String region) {
String accountId = defaultAccountId;
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
if (accountId != null) {
return accountId;
RequestContext requestContext = requestContextInstance.get();
if (requestContext.getAccountId() != null && !requestContext.getAccountId().isBlank()) {
accountId = requestContext.getAccountId();
}
} catch (ContextNotActiveException ignored) {
// outside request scope — fall through to default
// Direct callers outside HTTP request scope use the configured defaults.
}
}
return defaultAccountId;
return new SigningIdentity(accountId, region);
}
public boolean shouldValidateSignatures() {
@@ -91,20 +141,176 @@ public class PreSignedUrlGenerator {
public String generatePresignedUrl(String baseUrl, String bucket, String key,
String method, int expiresSeconds, String region) {
int expiry = expiresSeconds > 0 ? expiresSeconds : defaultExpiry;
String amzDate = AMZ_DATE_FORMAT.format(Instant.now());
String credential = resolveAccessKeyId() + "/" + amzDate.substring(0, 8) + "/" + region + "/s3/aws4_request";
if (expiry < 1 || expiry > MAX_PRESIGN_EXPIRY_SECONDS) {
throw new IllegalArgumentException("Presigned URL expiry must be between 1 and 604800 seconds");
}
Instant signedAt = clock.instant();
String amzDate = AMZ_DATE_FORMAT.format(signedAt);
String signature = computeSignature(method, bucket, key, amzDate, expiry);
if (iamService == null) {
return generateLegacyPresignedUrl(baseUrl, bucket, key, method, expiry, amzDate, region);
}
SigningIdentity identity = resolveSigningIdentity(region);
TemporaryCredential temporaryCredential = temporaryCredential(identity, bucket, key, method, signedAt, expiry);
String date = amzDate.substring(0, 8);
String credentialScope = date + "/" + identity.region() + "/s3/aws4_request";
String credential = temporaryCredential.accessKeyId() + "/" + credentialScope;
URI baseUri = URI.create(baseUrl);
String authority = baseUri.getRawAuthority();
if (authority == null || authority.isBlank()) {
throw new IllegalArgumentException("Pre-signed URL base must include an authority: " + baseUrl);
}
String path = "/" + PreSignedUrlFilter.awsUriEncode(bucket) + "/" + awsUriEncodePath(key);
MultivaluedHashMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.putSingle("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
queryParams.putSingle("X-Amz-Credential", credential);
queryParams.putSingle("X-Amz-Date", amzDate);
queryParams.putSingle("X-Amz-Expires", Integer.toString(expiry));
queryParams.putSingle("X-Amz-Security-Token", temporaryCredential.sessionToken());
queryParams.putSingle("X-Amz-SignedHeaders", "host");
String canonicalQuery = PreSignedUrlFilter.buildCanonicalQueryString(queryParams);
String canonicalRequest = S3PresignedCanonicalRequest.build(
method, path, canonicalQuery, "host", header -> authority, "UNSIGNED-PAYLOAD");
String signature;
try {
String stringToSign = S3PresignedCanonicalRequest.stringToSign(
amzDate, credentialScope, canonicalRequest);
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(
temporaryCredential.secretAccessKey(), date, identity.region(), "s3");
signature = SigV4RequestValidator.hexEncode(
SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
} catch (Exception e) {
throw new IllegalStateException("Failed to compute S3 SigV4 pre-signed URL", e);
}
String normalizedBaseUrl = baseUrl.endsWith("/")
? baseUrl.substring(0, baseUrl.length() - 1)
: baseUrl;
return normalizedBaseUrl + path + "?" + canonicalQuery + "&X-Amz-Signature=" + signature;
}
private String generateLegacyPresignedUrl(String baseUrl, String bucket, String key,
String method, int expiry, String amzDate, String region) {
String accountId = resolveSigningIdentity(region).accountId();
String credential = accountId + "/" + amzDate.substring(0, 8)
+ "/" + region + "/s3/aws4_request";
String signature = computeLegacySignature(method, bucket, key, amzDate, expiry);
return baseUrl + "/" + bucket + "/" + key
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=" + URLEncoder.encode(credential, StandardCharsets.UTF_8)
+ "&X-Amz-Credential=" + PreSignedUrlFilter.awsUriEncode(credential)
+ "&X-Amz-Date=" + amzDate
+ "&X-Amz-Expires=" + expiry
+ "&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=" + signature;
}
private TemporaryCredential temporaryCredential(SigningIdentity identity, String bucket, String key,
String method, Instant signedAt, int expiry) {
// The in-memory retirement list cannot survive a restart. Sweep persisted expired
// sessions once on first use, then retire this process's replacements as they expire.
if (expiredSessionsSwept.compareAndSet(false, true)) {
try {
iamService.sweepExpiredSessions(signedAt);
} catch (RuntimeException failure) {
expiredSessionsSwept.set(false);
throw failure;
}
}
// Previously issued URLs can still use a replaced credential. Sweep it only after expiry.
retiredCredentials.forEach((accessKeyId, retired) -> {
if (retired.credential().expiration().isBefore(signedAt)
&& retiredCredentials.remove(accessKeyId, retired)) {
iamService.unregisterSession(retired.accountId(), accessKeyId);
}
});
temporaryCredentials.forEach((keyToRemove, credential) -> {
if (credential.expiration().isBefore(signedAt)
&& temporaryCredentials.remove(keyToRemove, credential)) {
iamService.unregisterSession(keyToRemove.accountId(), credential.accessKeyId());
}
});
// The signed timestamp is second-granular. Keep the credential until the URL's
// final second, but never for the old seven-day floor.
Instant requiredExpiration = signedAt.truncatedTo(ChronoUnit.SECONDS).plusSeconds(expiry + 1L);
CredentialKey cacheKey = new CredentialKey(identity.accountId(), identity.region(), method, bucket, key);
return temporaryCredentials.compute(cacheKey, (ignored, existing) -> {
if (existing != null && !existing.expiration().isBefore(requiredExpiration)
&& iamService.findSecretKey(existing.accessKeyId(), existing.sessionToken())
.filter(existing.secretAccessKey()::equals).isPresent()) {
return existing;
}
TemporaryCredential created = new TemporaryCredential(
randomAccessKeyId(), randomUrlSafeValue(30), randomUrlSafeValue(48), requiredExpiration);
String action = presignedAction(method);
String resource = S3PublicAccessEvaluator.objectArn(
AwsRegions.partitionFor(identity.region()), bucket, key);
iamService.registerPresignedUrlSession(
identity.accountId(),
created.accessKeyId(),
created.secretAccessKey(),
created.sessionToken(),
created.expiration(),
scopedPolicy(method, action, resource), action, resource);
if (existing != null) {
if (existing.expiration().isBefore(signedAt)) {
iamService.unregisterSession(identity.accountId(), existing.accessKeyId());
} else {
retiredCredentials.put(existing.accessKeyId(),
new RetiredCredential(identity.accountId(), existing));
}
}
return created;
});
}
private static String presignedAction(String method) {
return switch (method) {
case "GET", "HEAD" -> "s3:GetObject";
case "PUT" -> "s3:PutObject";
case "DELETE" -> "s3:DeleteObject";
default -> throw new IllegalArgumentException("Unsupported S3 presigned URL method: " + method);
};
}
private static String scopedPolicy(String method, String action, String resource) {
try {
// S3 also checks GetObject for a conditional PutObject with If-Match. The
// presigned scope still restricts the credential to the URL's PUT operation.
Object actions = "PUT".equals(method)
? List.of(action, "s3:GetObject") : action;
return POLICY_MAPPER.writeValueAsString(Map.of(
"Version", "2012-10-17",
"Statement", List.of(Map.of("Effect", "Allow", "Action", actions, "Resource", resource))));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to encode S3 presigned session policy", e);
}
}
private String randomAccessKeyId() {
StringBuilder value = new StringBuilder("ASIA");
for (int index = 0; index < 16; index++) {
value.append(ACCESS_KEY_ALPHABET[random.nextInt(ACCESS_KEY_ALPHABET.length)]);
}
return value.toString();
}
private String randomUrlSafeValue(int byteCount) {
byte[] bytes = new byte[byteCount];
random.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private static String awsUriEncodePath(String value) {
return Arrays.stream(value.split("/", -1))
.map(PreSignedUrlFilter::awsUriEncode)
.collect(Collectors.joining("/"));
}
public boolean isExpired(String amzDate, int expiresSeconds) {
try {
Instant signedAt = Instant.from(AMZ_DATE_FORMAT.parse(amzDate));
@@ -116,12 +322,12 @@ public class PreSignedUrlGenerator {
public boolean verifySignature(String method, String bucket, String key,
String amzDate, int expiresSeconds, String signature) {
String expected = computeSignature(method, bucket, key, amzDate, expiresSeconds);
String expected = computeLegacySignature(method, bucket, key, amzDate, expiresSeconds);
return expected.equals(signature);
}
private String computeSignature(String method, String bucket, String key,
String amzDate, int expiresSeconds) {
private String computeLegacySignature(String method, String bucket, String key,
String amzDate, int expiresSeconds) {
String stringToSign = method + "\n" + bucket + "/" + key + "\n" + amzDate + "\n" + expiresSeconds;
return hmacSha256(secret, stringToSign);
}
@@ -131,7 +337,7 @@ public class PreSignedUrlGenerator {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
var sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
@@ -140,4 +346,17 @@ public class PreSignedUrlGenerator {
throw new RuntimeException("Failed to compute HMAC-SHA256", e);
}
}
private record SigningIdentity(String accountId, String region) {
}
private record CredentialKey(String accountId, String region, String method, String bucket, String key) {
}
private record TemporaryCredential(String accessKeyId, String secretAccessKey,
String sessionToken, Instant expiration) {
}
private record RetiredCredential(String accountId, TemporaryCredential credential) {
}
}
@@ -3807,7 +3807,7 @@ public class S3Controller {
}
/**
* Extracts the object key from the raw Vert.x request URI, preserving leading slashes
* Extracts the object key from the raw Vert.x request path, preserving leading slashes
* that JAX-RS path normalization would otherwise strip.
*/
private String extractObjectKey(UriInfo uriInfo, String bucket) {
@@ -3816,9 +3816,7 @@ public class S3Controller {
private String extractObjectKey(UriInfo uriInfo, String bucket, String fallbackKey) {
validateRawUri();
String rawUri = currentVertxRequest.getCurrent().request().uri();
int qIdx = rawUri.indexOf('?');
String rawPath = qIdx >= 0 ? rawUri.substring(0, qIdx) : rawUri;
String rawPath = currentVertxRequest.getCurrent().request().path();
String bucketPrefix = "/" + bucket + "/";
String rawKey;
if (isVirtualHostedRawPath(uriInfo, bucket, rawPath)) {
@@ -3883,9 +3881,7 @@ public class S3Controller {
}
private void validateRawUri() {
String rawUri = currentVertxRequest.getCurrent().request().uri();
int queryIndex = rawUri.indexOf('?');
String rawPath = queryIndex >= 0 ? rawUri.substring(0, queryIndex) : rawUri;
String rawPath = currentVertxRequest.getCurrent().request().path();
String decodedPath;
try {
decodedPath = URLDecoder.decode(rawPath.replace("+", "%2B"), StandardCharsets.UTF_8);
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import java.util.function.Function;
/** The canonical request and string-to-sign used by both S3 URL issuance and verification. */
final class S3PresignedCanonicalRequest {
private S3PresignedCanonicalRequest() {
}
static String build(String method, String signedPath, String canonicalQuery,
String signedHeaders, Function<String, String> headerValue, String payloadHash) {
StringBuilder canonicalHeaders = new StringBuilder();
for (String header : signedHeaders.split(";")) {
canonicalHeaders.append(header).append(':')
.append(PreSignedUrlFilter.canonicalizeHeaderValue(headerValue.apply(header)))
.append('\n');
}
return method + "\n" + signedPath + "\n" + canonicalQuery + "\n"
+ canonicalHeaders + "\n" + signedHeaders + "\n" + payloadHash;
}
static String stringToSign(String amzDate, String credentialScope, String canonicalRequest) throws Exception {
return "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
+ SigV4RequestValidator.sha256Hex(canonicalRequest);
}
}
@@ -373,7 +373,7 @@ public class SesExportJobService implements Resettable {
}
return Optional.of(preSignedUrlGenerator.generatePresignedUrl(baseUrl,
exportBucket(job.getAccountId(), job.getRegion()), job.getObjectKey(), "GET",
PRESIGNED_URL_EXPIRY_SECONDS));
PRESIGNED_URL_EXPIRY_SECONDS, job.getRegion()));
}
public List<ExportJob> listExportJobs(String region, String sourceType, String jobStatus) {