feat(iam): read S3 and S3 Control from the generated tables (#9155)

S3 leaves the registry's hand rules and ResourceArnBuilder's S3 branch: its requests are matched
on their botocore routes, checked as the actions the authorized-actions file gives them, on the
resources the request-resources table reads. regen_rest_routes.py no longer lists s3 as hand-routed,
and regen_iam_request_resources.py reads s3 instead of leaving it to the builder; the tables gain
S3's and S3 Control's 195 operations and nothing else changes. Operations sharing a route are told
apart by the query parameters and headers botocore requires, an S3 Control request by its route's
model, which also picks S3 Control's error envelope (isS3ControlRequest), and a member the two
clients locate apart is read for the client whose route the request matched.

An object key is read as S3 reads it, keeping the slashes it was sent with, through
RequestPathLabels, a per-namespace hook S3 implements with S3ObjectKeys. DeleteObjects names its
keys in its XML body, so it takes s3:DeleteObject's types from the S3 user guide's Either row and is
unread: the filter leaves it to S3, which checks each key.

The registry's S3 rules, S3 Control rules and sub-resource overrides are deleted, with the tests of
Floci's own handler order, the regional S3 Control ARN form, and a version for HEAD, HEAD
?annotation and Select, none of which an AWS source gives.

S3 also runs only what botocore routes, so what runs is what is checked: a request naming annotationName
is GetObjectAnnotation and a HEAD naming one HeadObject, SelectObjectContent runs on
?select&select-type=2 and reads the current version, the S3 Control tagging handler decodes its ARN
once, and a request two operations' routes take alike is refused under enforcement.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 17:44:36 -04:00
1 parent 546770ab69
commit 4735606fb9
29 files changed
+912 -1143

No files matched your search

@@ -457,6 +457,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (action == null) {
return; // unknown action → ALLOW for ordinary credentials (permissive)
}
// A request two operations' routes take alike, as one naming two of S3's sub-resources, runs as whichever its
// handler picks, so it is refused rather than checked as one of them.
if (!isRpcCall(ctx) && IamActionRegistry.ambiguousRoute(credentialScope, ctx)) {
LOG.infov("IAM enforcement DENY: akid={0} action={1}, a request two operations' routes take alike",
akid, action);
ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx));
return;
}
if ("sts:GetCallerIdentity".equals(action)) {
return; // AWS returns caller identity even when an identity policy explicitly denies it
}
@@ -0,0 +1,27 @@
package io.floci.aws.core.common;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.util.Map;
/**
* The values a service reads the labels of its REST requests' paths as, where they differ from what the router's
* normalized path gives the labels of the request's vendored route: S3 reads an object's key from the path as the
* client sent it, which keeps the key's own slashes ({@code PUT /bucket//email.txt} writes {@code /email.txt}, where
* the normalized path gives {@code email.txt}). The request-resources reader lays them over the route's labels, so a
* request is checked on the resource its handler acts on.
*
* <p>Implemented by the service whose handlers read their path so (S3); looked up lazily by namespace, as
* {@link StoredResourceArns} is.
*/
public interface RequestPathLabels {
/** The namespace whose requests it reads, as the request-resources table names it. */
String namespace();
/**
* The labels the request's path gives, by the label's name, that the service reads otherwise than {@code routed},
* the values the router's path gives the labels of the request's route; empty when it reads them alike.
*/
Map<String, String> labels(ContainerRequestContext ctx, Map<String, String> routed);
}
@@ -59,12 +59,10 @@ public class IamActionRegistry {
/**
* A route and the action it is checked as. A rule naming a query parameter matches only a request
* carrying it with that value, as {@code GET /layers?find=LayerVersion} is GetLayerVersionByArn
* where {@code GET /layers} is ListLayers. A rule flagged to match before the S3 query
* overrides is one of the S3 Control routes, which the control plane answers whatever its
* query string carries.
* where {@code GET /layers} is ListLayers.
*/
private record ActionRule(String service, String method, Pattern pathPattern, String queryParameter,
String queryValue, String action, boolean beforeS3QueryOverrides) {
String queryValue, String action) {
boolean matches(String scope, String requestMethod, String path, ContainerRequestContext ctx) {
return service.equals(scope) && method.equals(requestMethod) && pathPattern.matcher(path).find()
@@ -73,47 +71,8 @@ public class IamActionRegistry {
}
}
/**
* The routes of the S3 Control model, checked as the actions the Service Reference gives
* them by {@code IamRestRouteCoverageTest}. S3 Control clients sign with the s3 scope
* (botocore's s3control model declares signingName "s3"), so its operations are
* {@code s3:} actions, and its routes must be matched before the S3 data-plane query
* overrides: the control plane answers a tagging route whatever its query string carries,
* so a parameter such as {@code ?tagging} must not re-point the authorization at the
* data-plane object tagging it suggests, and the data-plane rules below would otherwise
* read {@code /v20180820/...} as a bucket named v20180820.
*
* <p>The account-level Block Public Access is the one route the Service Reference cannot
* settle, because it files S3's and S3 Control's GetPublicAccessBlock, PutPublicAccessBlock
* and DeletePublicAccessBlock under the bucket actions; the S3 User Guide's Block Public
* Access page gives the account level its own actions, and the exception is written down
* where the data is checked. ListAccessPoints and the account actions have no resource
* type, so IAM checks them against the wildcard rather than a bucket.
*/
/** The routes the registry checks as an action of its own, each a rule of the scope it serves. */
private static final List<ActionRule> RULES = List.of(
// ── S3 Control ───────────────────────────────────────────────────────────
s3ControlRule("GET", "^/v20180820/tags/.+", "s3:ListTagsForResource"),
s3ControlRule("POST", "^/v20180820/tags/.+", "s3:TagResource"),
s3ControlRule("DELETE", "^/v20180820/tags/.+", "s3:UntagResource"),
s3ControlRule("GET", "^/v20180820/accesspoint/?$", "s3:ListAccessPoints"),
s3ControlRule("PUT", "^/v20180820/configuration/publicAccessBlock/?$",
"s3:PutAccountPublicAccessBlock"),
s3ControlRule("GET", "^/v20180820/configuration/publicAccessBlock/?$",
"s3:GetAccountPublicAccessBlock"),
s3ControlRule("DELETE", "^/v20180820/configuration/publicAccessBlock/?$",
"s3:PutAccountPublicAccessBlock"),
// ── S3 ─────────────────────────────────────────────────────────────────
rule("s3", "GET", "^/?$", "s3:ListAllMyBuckets"),
rule("s3", "PUT", "^/[^/]+/?$", "s3:CreateBucket"),
rule("s3", "DELETE", "^/[^/]+/?$", "s3:DeleteBucket"),
rule("s3", "HEAD", "^/[^/]+/?$", "s3:ListBucket"),
rule("s3", "GET", "^/[^/]+/?$", "s3:ListBucket"),
rule("s3", "GET", "^/[^/]+/.+", "s3:GetObject"),
rule("s3", "PUT", "^/[^/]+/.+", "s3:PutObject"),
rule("s3", "DELETE", "^/[^/]+/.+", "s3:DeleteObject"),
rule("s3", "HEAD", "^/[^/]+/.+", "s3:GetObject"),
// ── Lambda ──────────────────────────────────────────────────────────────
// Code signing configs first: a config's function list ends in /functions, as ListFunctions does.
rule("lambda", "GET", "^/2020-04-22/code-signing-configs/[^/]+/functions$",
@@ -565,35 +524,22 @@ public class IamActionRegistry {
private static ActionRule rule(String service, String method, String path, String queryParameter,
String queryValue, String action) {
return new ActionRule(service, method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), queryParameter,
queryValue, action, false);
}
private static ActionRule s3ControlRule(String method, String path, String action) {
return new ActionRule("s3", method, Pattern.compile(path, Pattern.CASE_INSENSITIVE), null, null,
action, true);
queryValue, action);
}
/**
* Whether the request is one of the S3 Control routes, as the rules flag them. A denial then
* answers in S3 Control's own REST-XML envelope, the only one the s3control SDK
* deserializers read (issue #557), so the route decides the shape and not the action: the
* data plane resolves actions a control route never shares, and an action-name list would
* have to track every route to stay right. A request whose route cannot be read, which only
* a synthetic context is, is not a control one.
* Whether the request is an S3 Control one: the route it matches is the {@code s3control} model's. A denial then
* answers in S3 Control's own REST-XML envelope, the only one the s3control SDK deserializers read (issue #557),
* so the route decides the shape and not the action. A request whose route cannot be read, which only a synthetic
* context is, is not a control one.
*/
public static boolean isS3ControlRequest(String credentialScope, ContainerRequestContext ctx) {
if (!"s3".equals(credentialScope) || ctx.getMethod() == null || ctx.getUriInfo() == null
|| ctx.getUriInfo().getRequestUri() == null) {
return false;
}
String method = ctx.getMethod().toUpperCase();
String path = sentPath(ctx.getUriInfo());
for (ActionRule rule : RULES) {
if (rule.beforeS3QueryOverrides() && rule.matches(credentialScope, method, path, ctx)) {
return true;
}
}
return false;
return matchedRoute(IamRestRoutes.vendored(), credentialScope, ctx)
.map(match -> "s3control".equals(match.model())).orElse(false);
}
/**
@@ -675,36 +621,15 @@ public class IamActionRegistry {
* {@code apigateway:PUT} for a PUT. That is when Floci can check it as AWS does ({@code checkedAsAws}). One
* it cannot is left unmapped rather than checked on {@code *}, which would refuse a grant scoped to the
* resource AWS checks it on. A request a route filter moved under an internal prefix is matched on its
* path without the prefix ({@link #withoutInternalPrefix}), the path the model gives it. S3, the scope the
* vendored routes list as hand-routed, has its rules alone. Returns {@code null} when nothing maps the
* request (caller treats this as ALLOW).
* path without the prefix ({@link #withoutInternalPrefix}), the path the model gives it. Returns {@code null}
* when nothing maps the request (caller treats this as ALLOW).
*/
public String resolveRoute(String credentialScope, ContainerRequestContext ctx) {
String method = ctx.getMethod().toUpperCase();
// An S3 key may end in a slash, PUT /bucket// writes the key "/", and S3's rules already take a
// bucket's one trailing slash, so an S3 path is matched as sent.
// An S3 key may end in a slash, and one of slashes alone arrives escaped as S3SlashOnlyKeyFilter rewrites
// it (PUT /bucket// writes the key "/"), so an S3 path is matched as sent, not decoded.
String path = "s3".equals(credentialScope) ? sentPath(ctx.getUriInfo()) : routedPath(ctx);
if ("s3".equals(credentialScope)) {
// An S3 Control route is matched before the query overrides below, which would read the
// query string of a route the control plane answers whatever it carries: ?tagging on a
// tagging route is caller-supplied noise, not the object sub-resource it names.
for (ActionRule rule : RULES) {
if (rule.beforeS3QueryOverrides() && rule.matches(credentialScope, method, path, ctx)) {
return rule.action();
}
}
// S3 sub-resource override: the URL path alone doesn't distinguish
// s3:GetObjectAcl / s3:PutObjectAcl from s3:GetObject / s3:PutObject:
// only the {@code ?acl} query parameter does. Without this hook,
// an actor with s3:GetObject permission could read ACLs that their
// policy intends to forbid.
String s3SubAction = resolveS3SubResourceAction(method, ctx);
if (s3SubAction != null) {
return s3SubAction;
}
}
for (ActionRule rule : RULES) {
if (rule.matches(credentialScope, method, path, ctx)) {
return rule.action();
@@ -801,6 +726,22 @@ public class IamActionRegistry {
static final RouteMembers NONE = new RouteMembers(Map.of(), null);
}
/**
* Whether a REST request of the credential scope is taken alike by the routes of two operations, none outranking
* the other, as one naming two of S3's sub-resources is ({@code PUT /bucket?cors&policy}): no botocore client
* sends one, and it runs as whichever its handler picks, so no one action covers it.
*/
public static boolean ambiguousRoute(String credentialScope, ContainerRequestContext ctx) {
if (credentialScope == null || ctx.getMethod() == null || ctx.getUriInfo() == null
|| ctx.getUriInfo().getRequestUri() == null) {
return false;
}
String path = "s3".equals(credentialScope) ? sentPath(ctx.getUriInfo()) : routedPath(ctx);
return IamRestRoutes.vendored().ambiguous(credentialScope, ctx.getMethod().toUpperCase(),
withoutInternalPrefix(ctx, path), ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx),
ctx.getHeaders());
}
/** The route a request of the operation matches, {@link RouteMembers#NONE} for one it matches none of. */
public static RouteMembers routeMembers(String operation, ContainerRequestContext ctx) {
int separator = operation.indexOf(':');
@@ -946,225 +887,4 @@ public class IamActionRegistry {
&& "application".equalsIgnoreCase(mediaType.getType())
&& "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype());
}
private static boolean isFormUpload(MediaType mediaType) {
return mediaType != null
&& "multipart".equalsIgnoreCase(mediaType.getType())
&& "form-data".equalsIgnoreCase(mediaType.getSubtype());
}
/** One bucket sub-resource operation: the query parameter that selects it, and the IAM action. */
private record SubResourceAction(String queryParameter, String action) {}
private static SubResourceAction sub(String queryParameter, String action) {
return new SubResourceAction(queryParameter, action);
}
private static final List<SubResourceAction> GET_BUCKET_SUBRESOURCES = List.of(
sub("uploads", "s3:ListBucketMultipartUploads"),
sub("notification", "s3:GetBucketNotification"),
sub("versioning", "s3:GetBucketVersioning"),
sub("versions", "s3:ListBucketVersions"),
sub("location", "s3:GetBucketLocation"),
sub("tagging", "s3:GetBucketTagging"),
sub("object-lock", "s3:GetBucketObjectLockConfiguration"),
sub("website", "s3:GetBucketWebsite"),
sub("logging", "s3:GetBucketLogging"),
sub("policy", "s3:GetBucketPolicy"),
sub("policyStatus", "s3:GetBucketPolicyStatus"),
sub("cors", "s3:GetBucketCORS"),
sub("lifecycle", "s3:GetLifecycleConfiguration"),
sub("acl", "s3:GetBucketAcl"),
sub("encryption", "s3:GetEncryptionConfiguration"),
sub("publicAccessBlock", "s3:GetBucketPublicAccessBlock"),
sub("ownershipControls", "s3:GetBucketOwnershipControls"),
sub("requestPayment", "s3:GetBucketRequestPayment"),
sub("accelerate", "s3:GetAccelerateConfiguration"),
sub("replication", "s3:GetReplicationConfiguration"),
sub("metrics", "s3:GetMetricsConfiguration"),
sub("intelligent-tiering", "s3:GetIntelligentTieringConfiguration"),
sub("analytics", "s3:GetAnalyticsConfiguration"),
sub("inventory", "s3:GetInventoryConfiguration"));
private static final List<SubResourceAction> PUT_BUCKET_SUBRESOURCES = List.of(
sub("notification", "s3:PutBucketNotification"),
sub("versioning", "s3:PutBucketVersioning"),
sub("tagging", "s3:PutBucketTagging"),
sub("object-lock", "s3:PutBucketObjectLockConfiguration"),
sub("website", "s3:PutBucketWebsite"),
sub("logging", "s3:PutBucketLogging"),
sub("policy", "s3:PutBucketPolicy"),
sub("cors", "s3:PutBucketCORS"),
sub("lifecycle", "s3:PutLifecycleConfiguration"),
sub("acl", "s3:PutBucketAcl"),
sub("encryption", "s3:PutEncryptionConfiguration"),
sub("publicAccessBlock", "s3:PutBucketPublicAccessBlock"),
sub("ownershipControls", "s3:PutBucketOwnershipControls"),
sub("requestPayment", "s3:PutBucketRequestPayment"),
sub("accelerate", "s3:PutAccelerateConfiguration"),
sub("replication", "s3:PutReplicationConfiguration"),
sub("metrics", "s3:PutMetricsConfiguration"),
sub("intelligent-tiering", "s3:PutIntelligentTieringConfiguration"),
sub("analytics", "s3:PutAnalyticsConfiguration"),
sub("inventory", "s3:PutInventoryConfiguration"));
// AWS gives only DeleteBucketPolicy and DeleteBucketWebsite their own action; removing any other
// sub-resource is authorised by the same Put* action that sets it. ?accelerate is absent because
// S3Controller rejects DELETE on it with 405, so no mapping should claim the request.
private static final List<SubResourceAction> DELETE_BUCKET_SUBRESOURCES = List.of(
sub("tagging", "s3:PutBucketTagging"),
sub("website", "s3:DeleteBucketWebsite"),
sub("policy", "s3:DeleteBucketPolicy"),
sub("cors", "s3:PutBucketCORS"),
sub("lifecycle", "s3:PutLifecycleConfiguration"),
sub("encryption", "s3:PutEncryptionConfiguration"),
sub("publicAccessBlock", "s3:PutBucketPublicAccessBlock"),
sub("ownershipControls", "s3:PutBucketOwnershipControls"),
sub("replication", "s3:PutReplicationConfiguration"),
sub("metrics", "s3:PutMetricsConfiguration"),
sub("intelligent-tiering", "s3:PutIntelligentTieringConfiguration"),
sub("analytics", "s3:PutAnalyticsConfiguration"),
sub("inventory", "s3:PutInventoryConfiguration"));
private static String resolveS3SubResourceAction(String method, ContainerRequestContext ctx) {
MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
// /{bucket}?acl -> bucket-level; /{bucket}/{key}?acl -> object-level.
// A trailing slash is a valid key character, so /bucket/folder/?acl is an object request -
// we cannot use endsWith("/") to infer bucket-level.
String path = ctx.getUriInfo().getPath();
String stripped = path.startsWith("/") ? path.substring(1) : path;
int firstSlash = stripped.indexOf('/');
boolean isBucketLevel = firstSlash < 0 || firstSlash == stripped.length() - 1;
if (!isBucketLevel) {
return objectSubResourceAction(method, params);
}
if ("POST".equals(method)) {
// S3Controller runs DeleteObjects and a browser-form PostObject ahead of any other sub-resource and
// checks them per key; another sub-resource S3 defines for POST, such as ?metadataTable, it answers
// NotImplemented, so that request is checked as the operation it names.
return params.containsKey("delete") || isFormUpload(ctx.getMediaType())
? null : unservedSubresourceAction(method, params);
}
List<SubResourceAction> chain = switch (method) {
case "GET" -> GET_BUCKET_SUBRESOURCES;
case "PUT" -> PUT_BUCKET_SUBRESOURCES;
case "DELETE" -> DELETE_BUCKET_SUBRESOURCES;
default -> List.of();
};
for (SubResourceAction entry : chain) {
if (params.containsKey(entry.queryParameter())) {
return entry.action();
}
}
return chain.isEmpty() ? null : unservedSubresourceAction(method, params);
}
/**
* A sub-resource S3 defines for the method that the lists above, or POST's DeleteObjects, do not hold is one
* S3Controller does not serve: it answers the request NotImplemented rather than run the bucket's operation, so
* the request is checked as the operation it names, as AWS checks it. Null when it names none, or one S3 defines
* for other methods only, which S3Controller refuses as not allowed.
*/
private static String unservedSubresourceAction(String method, MultivaluedMap<String, String> params) {
S3BucketSubresources subresources = S3BucketSubresources.vendored();
for (String name : subresources.names()) {
List<String> operations = subresources.operations(method, name);
if (params.containsKey(name) && operations.size() == 1) {
return IamAuthorizedActions.actionFor("s3", operations.get(0));
}
}
return null;
}
/**
* The operation an object sub-resource selects, checked in the order S3Controller dispatches
* them: a request naming several runs the first, so it is checked as that one. A
* {@code versionId} selects the version action AWS checks in place of an action that has one
* (see {@link S3ObjectActions#forVersion}). Null where the controller falls through to the plain
* object operation on the current version, which the rules check.
*/
private static String objectSubResourceAction(String method, MultivaluedMap<String, String> params) {
String versionId = params.getFirst("versionId");
return switch (method) {
case "GET" -> {
if (params.containsKey("uploadId")) {
yield "s3:ListMultipartUploadParts";
}
if (params.containsKey("tagging")) {
yield S3ObjectActions.forVersion("s3:GetObjectTagging", versionId);
}
if (params.containsKey("annotation")) {
yield S3ObjectActions.forVersion(annotationReadAction(params), versionId);
}
if (params.containsKey("retention")) {
yield "s3:GetObjectRetention";
}
if (params.containsKey("legal-hold")) {
yield "s3:GetObjectLegalHold";
}
if (params.containsKey("acl")) {
yield S3ObjectActions.forVersion("s3:GetObjectAcl", versionId);
}
yield versionId != null ? "s3:GetObjectVersion" : null;
}
case "HEAD" -> {
if (params.containsKey("annotation")) {
yield S3ObjectActions.forVersion(annotationReadAction(params), versionId);
}
yield versionId != null ? "s3:GetObjectVersion" : null;
}
case "PUT" -> {
if (params.containsKey("tagging")) {
yield S3ObjectActions.forVersion("s3:PutObjectTagging", versionId);
}
if (params.containsKey("retention")) {
yield "s3:PutObjectRetention";
}
if (params.containsKey("legal-hold")) {
yield "s3:PutObjectLegalHold";
}
if (params.containsKey("acl")) {
yield S3ObjectActions.forVersion("s3:PutObjectAcl", versionId);
}
// A PUT naming an uploadId and a partNumber is UploadPart, which the rules check as
// s3:PutObject, as they do PutObject and CopyObject.
yield params.containsKey("annotation")
? S3ObjectActions.forVersion("s3:PutObjectAnnotation", versionId)
: null;
}
case "DELETE" -> {
if (params.containsKey("tagging")) {
yield S3ObjectActions.forVersion("s3:DeleteObjectTagging", versionId);
}
if (params.containsKey("annotation")) {
yield S3ObjectActions.forVersion("s3:DeleteObjectAnnotation", versionId);
}
if (params.containsKey("uploadId")) {
yield "s3:AbortMultipartUpload";
}
yield versionId != null ? "s3:DeleteObjectVersion" : null;
}
case "POST" -> {
if (params.containsKey("uploads")) {
yield "s3:PutObject";
}
if (params.containsKey("restore")) {
yield "s3:RestoreObject";
}
if (params.containsKey("select")) {
// S3Controller selects from the version a versionId names.
yield S3ObjectActions.forVersion("s3:GetObject", versionId);
}
yield params.containsKey("uploadId") ? "s3:PutObject" : null;
}
default -> null;
};
}
/** A named annotation is GetObjectAnnotation; an empty or absent name lists them, as S3Controller does. */
private static String annotationReadAction(MultivaluedMap<String, String> params) {
String name = params.getFirst("annotationName");
return name != null && !name.isEmpty() ? "s3:GetObjectAnnotation" : "s3:ListObjectAnnotations";
}
}
@@ -226,18 +226,47 @@ final class IamRestRoutes {
private Optional<Match> best(String scope, String method, String requestPath, MultivaluedMap<String, String> query,
boolean spanned, MultivaluedMap<String, String> headers) {
Route best = null;
for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) {
if (route.matches(requestPath, query, spanned) && route.carries(headers)
&& (best == null || route.outranks(best))) {
best = route;
}
}
Route best = ranked(scope, method, requestPath, query, spanned, headers).best();
return best == null ? Optional.empty()
: Optional.of(new Match(best.operation(), best.labelValues(requestPath, spanned), best.located(),
best.documented(), best.model()));
}
/**
* Whether the request is taken alike by the routes of two operations, none outranking the other: a request naming
* two of S3's sub-resources ({@code PUT /bucket?cors&policy}) matches both their routes, and no botocore client
* sends one, so which it is depends on the handler alone.
*/
boolean ambiguous(String scope, String method, String path, MultivaluedMap<String, String> query,
boolean movedUnderPrefix, MultivaluedMap<String, String> headers) {
String requestPath = IamActionRegistry.withoutTrailingSlash(path);
Ranked ranked = ranked(scope, method, requestPath, query, false, headers);
return ranked.best() == null && movedUnderPrefix
? ranked(scope, method, requestPath, query, true, headers).tied() : ranked.tied();
}
/** The route a request matches that outranks the others it matches, and whether another operation's ties it. */
private record Ranked(Route best, boolean tied) {
}
private Ranked ranked(String scope, String method, String requestPath, MultivaluedMap<String, String> query,
boolean spanned, MultivaluedMap<String, String> headers) {
List<Route> matching = new ArrayList<>();
Route best = null;
for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) {
if (route.matches(requestPath, query, spanned) && route.carries(headers)) {
matching.add(route);
if (best == null || route.outranks(best)) {
best = route;
}
}
}
Route winner = best;
boolean tied = winner != null && matching.stream().anyMatch(route -> route != winner
&& !winner.outranks(route) && !winner.operation().equals(route.operation()));
return new Ranked(best, tied);
}
/** The modelled denial status, or the existing protocol default when the model declares none. */
int accessDeniedStatus(String scope, int fallback) {
return scope == null ? fallback : accessDeniedStatuses.getOrDefault(scope, fallback);
@@ -7,17 +7,13 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsQueryServiceResolver;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.RequestPathLabels;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.core.common.SigV4CredentialScope;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.auth.SigV4Canonicalization;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.s3.S3ControlArnUtils;
import io.floci.aws.services.s3.S3ObjectKeys;
import io.floci.aws.services.s3.S3ResourceArns;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -26,10 +22,10 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -58,9 +54,6 @@ public class ResourceArnBuilder {
/** What a service-linked role deletion task identifier starts with; see its resolver. */
private static final String DELETION_TASK_PREFIX = "task" + ServiceLinkedRoles.PATH;
/** Where an S3 Control tagging route carries the ARN of the resource it acts on. */
private static final String S3_CONTROL_TAGS_PREFIX = "/v20180820/tags/";
/** The segment that starts an API Gateway v2 management path, and is not part of the resource it names. */
private static final String API_GATEWAY_V2_SEGMENT = "v2";
@@ -84,22 +77,21 @@ public class ResourceArnBuilder {
*/
private final Instance<StoredResourceArns> storedResourceArns;
/**
* The current request, for the path as the client sent it: an S3 key keeps its own slashes,
* which JAX-RS has collapsed out of {@code UriInfo} by the time this runs. Null outside a
* request, as in a unit test, where the request URI's raw path stands in.
* Looked up lazily as well, to read a path's labels as the namespace's handlers read them where the router's
* normalized path gives them otherwise (an S3 key's own slashes).
*/
private final CurrentVertxRequest currentVertxRequest;
private final Instance<RequestPathLabels> requestPathLabels;
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<KmsService> kmsService,
Instance<StoredResourceArns> storedResourceArns,
CurrentVertxRequest currentVertxRequest) {
Instance<RequestPathLabels> requestPathLabels) {
this.objectMapper = objectMapper;
this.iamService = iamService;
this.kmsService = kmsService;
this.storedResourceArns = storedResourceArns;
this.currentVertxRequest = currentVertxRequest;
this.requestPathLabels = requestPathLabels;
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
@@ -125,10 +117,6 @@ public class ResourceArnBuilder {
this(objectMapper, null, null);
}
ResourceArnBuilder(ObjectMapper objectMapper, CurrentVertxRequest currentVertxRequest) {
this(objectMapper, null, null, null, currentVertxRequest);
}
public String build(String credentialScope, ContainerRequestContext ctx,
String region, String accountId) {
List<String> list = buildResources(credentialScope, ctx, region, accountId);
@@ -163,10 +151,8 @@ public class ResourceArnBuilder {
if (operation != null && operation.startsWith(credentialScope + ":") && RequestResources.reads(operation)) {
return namedResources(credentialScope, operation, ctx, region, accountId, partition);
}
String path = "s3".equals(credentialScope) ? ctx.getUriInfo().getPath()
: IamActionRegistry.decodedPath(ctx);
String path = IamActionRegistry.decodedPath(ctx);
return switch (credentialScope) {
case "s3" -> buildS3Resources(operation, path, ctx, region);
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
case "iam" -> buildIamArns(ctx, region, accountId);
case "apigateway" -> List.of(buildApiGatewayArn(ctx, region, partition));
@@ -179,16 +165,40 @@ public class ResourceArnBuilder {
* The resources a request of a namespace this builder has no branch for names, from the vendored table of
* request resources (see {@link RequestResources}); {@code *} when it names none, or the operation is not one
* of the namespace. A resource whose service mints an id after its name, or as all of its ARN, is the one the
* namespace's {@link StoredResourceArns} finds under that name or the members naming it.
* namespace's {@link StoredResourceArns} finds under that name or the members naming it. A label of the
* request's path is read as the namespace's {@link RequestPathLabels} reads it, where it reads one otherwise.
*/
private List<String> namedResources(String credentialScope, String operation, ContainerRequestContext ctx,
String region, String accountId, String partition) {
List<String> named = operation == null || !operation.startsWith(credentialScope + ":") ? List.of()
: RequestResources.of(operation, ctx, partition, region, accountId, storedResourceArns(credentialScope),
IamActionRegistry.pathLabels(credentialScope, ctx));
if (operation == null || !operation.startsWith(credentialScope + ":")) {
return List.of("*");
}
Map<String, String> labels = IamActionRegistry.pathLabels(credentialScope, ctx);
RequestPathLabels read = requestPathLabels(credentialScope);
Map<String, String> otherwise = read == null ? Map.of() : read.labels(ctx, labels);
if (!otherwise.isEmpty()) {
Map<String, String> merged = new HashMap<>(labels);
merged.putAll(otherwise);
labels = Map.copyOf(merged);
}
List<String> named = RequestResources.of(operation, ctx, partition, region, accountId,
storedResourceArns(credentialScope), labels);
return named.isEmpty() ? List.of("*") : named;
}
/** The registered reader of the namespace's path labels; null when there is none. */
private RequestPathLabels requestPathLabels(String namespace) {
if (requestPathLabels == null || requestPathLabels.isUnsatisfied()) {
return null;
}
for (RequestPathLabels read : requestPathLabels) {
if (read.namespace().equals(namespace)) {
return read;
}
}
return null;
}
/**
* The requests the service of {@code operation}, the one the request is dispatched as, makes to another service as
* the caller on what the resources it is checked on hold (see {@link RequestResources#forwarded}), each resource
@@ -751,115 +761,6 @@ public class ResourceArnBuilder {
return stored.filter(entity -> entity.arn() != null && !entity.arn().isBlank());
}
// ── S3 ──────────────────────────────────────────────────────────────────────
/**
* The path of an S3 data-plane request, {@code path} as JAX-RS matched it, with its object key
* read from the path as the client sent it. {@code UriInfo} carries JAX-RS's collapsing of
* consecutive slashes, which drops a key's own leading slash and so names another object:
* {@code PUT /bucket//email.txt} stores the key {@code /email.txt} but would be checked on
* {@code arn:aws:s3:::bucket/email.txt}, so a grant on that object would cover this one and a
* statement naming {@code bucket//*} would match nothing it names. {@code S3Controller} stores
* the object under the key read here and the IAM condition resolver describes that same key,
* so all three agree on which object the request is about. The bucket comes from the matched
* path, which {@code S3VirtualHostFilter} has put it into for a virtual-hosted request.
*/
private String s3Path(String path, ContainerRequestContext ctx) {
String bucket = s3Bucket(path);
if (bucket == null) {
return path;
}
URI requestUri = ctx.getUriInfo().getRequestUri();
RoutingContext current = currentVertxRequest == null ? null : currentVertxRequest.getCurrent();
String sentPath = current != null && current.request() != null ? current.request().path()
: requestUri == null ? null : requestUri.getRawPath();
String key = S3ObjectKeys.objectKey(sentPath, requestUri == null ? null : requestUri.getPath(),
path, bucket);
return key == null ? path : "/" + bucket + "/" + key;
}
/**
* The bucket an S3 data-plane path names an object in, or null when the path names no object to
* read a key for: the root, and a bucket on its own or with one trailing slash, which the ARN
* reads as the bucket itself.
*/
private static String s3Bucket(String path) {
if (path == null) {
return null;
}
String stripped = path.startsWith("/") ? path.substring(1) : path;
int slash = stripped.indexOf('/');
return slash <= 0 || slash == stripped.length() - 1 ? null : stripped.substring(0, slash);
}
// Minted in the request's partition; IamEnforcementFilter re-mints an existing bucket's ARN
// in the bucket's own partition through S3ResourcePolicyProvider before any policy sees it.
private String buildS3Arn(String path, String region) {
// path: /bucket or /bucket/key
String partition = AwsRegions.partitionFor(region);
String stripped = path.startsWith("/") ? path.substring(1) : path;
if (stripped.isEmpty()) {
return S3ResourceArns.bucket(partition, "*");
}
// S3VirtualHostFilter rewrites a bucket-level virtual-hosted request (GET /) to
// /bucket/, and the empty key after that separator is not part of the resource.
// A policy names the bucket as arn:<partition>:s3:::bucket, so the trailing slash has to
// go or a bucket-level ARN never matches. A key that itself ends in a slash
// (a folder marker such as folder/) keeps it, because there the slash is key data.
int firstSlash = stripped.indexOf('/');
if (firstSlash < 0 || firstSlash == stripped.length() - 1) {
return S3ResourceArns.bucket(partition, firstSlash < 0 ? stripped : stripped.substring(0, firstSlash));
}
return S3ResourceArns.object(partition, stripped.substring(0, firstSlash), stripped.substring(firstSlash + 1));
}
/**
* The resources an s3-scope request names, which an S3 Control operation reads differently
* from an S3 data-plane path. S3 Control clients sign with the s3 scope and its operations
* are {@code s3:} actions (the Service Authorization Reference lists them under Amazon S3),
* so the operation, not the path, tells the two apart: a tagging route carries the ARN of the
* bucket or access point it acts on in its path, and the request is checked against that ARN
* as written, the way every ARN-carrying request is; the Service Authorization Reference
* gives ListAccessPoints and the account-level Block Public Access no resource type, so
* those are checked against the wildcard alone, as the no-resource actions of other
* namespaces are (the KMS list operations), and a bucket-scoped statement grants them
* nothing. Any other operation is the data plane, checked against the bucket or object its
* path names, even in a bucket named like the S3 Control prefix, {@code v20180820}.
*/
private List<String> buildS3Resources(String operation, String path, ContainerRequestContext ctx,
String region) {
if (operation == null) {
return List.of(buildS3Arn(s3Path(path, ctx), region));
}
return switch (operation) {
case "s3:ListTagsForResource", "s3:TagResource", "s3:UntagResource" ->
List.of(taggedS3ControlArn(path));
case "s3:ListAccessPoints", "s3:PutAccountPublicAccessBlock",
"s3:GetAccountPublicAccessBlock" -> List.of("*");
default -> List.of(buildS3Arn(s3Path(path, ctx), region));
};
}
/**
* The ARN an S3 Control tagging route names in its path, read with the one parse the handler
* and the policy lookup share: the Go SDK, and so Terraform's provider, percent-encodes the
* ARN's colons and slashes, so the path may still carry them. A path naming no ARN leaves
* the wildcard, which the handler answers {@code InvalidRequest} under, and nothing is
* rebuilt from the bucket it names: the ARN as the caller wrote it is the resource.
*/
private static String taggedS3ControlArn(String path) {
String tagged = path.startsWith(S3_CONTROL_TAGS_PREFIX)
? path.substring(S3_CONTROL_TAGS_PREFIX.length()) : null;
if (tagged == null) {
return "*";
}
try {
return S3ControlArnUtils.parse(tagged).map(AwsArnUtils.Arn::toString).orElse("*");
} catch (IllegalArgumentException malformedEncoding) {
return "*";
}
}
/**
* API Gateway authorizes a management call as its HTTP method on the path it names, in the Region serving
* it and with no account: {@code GET /restapis/abc/stages} acts on
@@ -2,8 +2,6 @@ package io.floci.aws.services.s3;
import io.floci.aws.core.common.AwsArnUtils;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
/**
@@ -25,16 +23,15 @@ public final class S3ControlArnUtils {
private S3ControlArnUtils() {}
/**
* The tagging route's ARN, decoded as its handler decodes it and parsed once. Empty when the
* value is null, blank or not an s3 ARN; {@link IllegalArgumentException} when its
* percent-encoding is malformed.
* The tagging route's ARN, as the router decoded its path parameter, once, the way IAM reads the route's label:
* the Go SDK, and so Terraform's provider, sends it percent-encoded once, so a value still percent-encoded after
* that names no ARN. Empty when the value is null, blank or not an s3 ARN.
*/
public static Optional<AwsArnUtils.Arn> parse(String resourceArn) {
if (resourceArn == null || resourceArn.isBlank()) {
return Optional.empty();
}
String decoded = URLDecoder.decode(resourceArn, StandardCharsets.UTF_8);
return AwsArnUtils.isArnFor(decoded, "s3") ? Optional.of(AwsArnUtils.parse(decoded)) : Optional.empty();
return AwsArnUtils.isArnFor(resourceArn, "s3") ? Optional.of(AwsArnUtils.parse(resourceArn)) : Optional.empty();
}
/**
@@ -28,7 +28,6 @@ import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
@@ -312,21 +311,14 @@ public class S3ControlController {
}
/**
* The bucket ARN a tagging route names, decoded and parsed the one way every reader of it
* The bucket ARN a tagging route names, decoded once and parsed the one way every reader of it
* shares: the handler here, the IAM resource the request is checked against, and the bucket
* policy lookup. The regional form carries the account and region of the bucket it names, and
* the global form the caller's own account, so a request naming another account's bucket acts
* on that account's bucket, never on the caller's same-named one.
*/
private static AwsArnUtils.Arn taggedBucketArn(String resourceArn) {
Optional<AwsArnUtils.Arn> arn;
try {
arn = S3ControlArnUtils.parse(resourceArn);
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidRequest",
"Malformed percent-encoding in resource ARN: " + e.getMessage(), 400);
}
return arn.filter(S3ControlArnUtils::namesBucket)
return S3ControlArnUtils.parse(resourceArn).filter(S3ControlArnUtils::namesBucket)
.orElseThrow(() -> new AwsException("InvalidRequest",
"Unsupported resource type. Only S3 bucket ARNs are supported " +
"(arn:aws:s3:<region>:<account>:bucket/<name> or arn:aws:s3:::<name>).", 400)); // partition-literal: AWS's message text
@@ -1080,10 +1080,9 @@ public class S3Controller {
return handleGetObjectTagging(bucket, key, versionId);
}
if (params.has("annotation")) {
String annotationNameParam = params.first("annotationName");
// An empty annotationName is not a Get request for the empty name: it falls
// through to ListObjectAnnotations, matching the blank-name put semantics.
if (annotationNameParam != null && !annotationNameParam.isEmpty()) {
// A request naming an annotation is GetObjectAnnotation, as botocore's model, which requires the
// name, reads it and IAM checks it: an empty name is refused as one, not listed.
if (params.first("annotationName") != null) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAnnotation", authorization);
return handleGetObjectAnnotation(bucket, key, uriInfo, httpHeaders);
}
@@ -1421,19 +1420,8 @@ public class S3Controller {
}
}
checkVersionId(bucket, params.first("versionId"));
// HEAD honors the annotation subresource so a HEAD probe reports the same status and
// annotation metadata a GET would, instead of falling through to the object's headers.
if (params.has("annotation")) {
String annotationNameParam = params.first("annotationName");
// An empty annotationName is not a Get request for the empty name: it falls
// through to ListObjectAnnotations, matching the blank-name put semantics.
if (annotationNameParam != null && !annotationNameParam.isEmpty()) {
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAnnotation", authorization);
return headOnlyResponse(handleGetObjectAnnotation(bucket, key, uriInfo, httpHeaders));
}
s3Service.authorizeObjectRead(bucket, key, versionId, "s3:ListObjectAnnotations", authorization);
return headOnlyResponse(handleListObjectAnnotations(bucket, key, uriInfo));
}
// Botocore models no HEAD of an annotation, so a HEAD is HeadObject whatever its query names, as IAM
// checks it.
s3Service.authorizeGetObject(bucket, key, versionId, authorization);
S3Object obj = s3Service.headObject(bucket, key, versionId);
@@ -1747,12 +1735,15 @@ public class S3Controller {
return started ? Response.accepted().build() : Response.ok().build();
}
if (hasQueryParam(uriInfo, "select")) {
s3Service.authorizeGetObject(bucket, key, versionId, authorization);
// SelectObjectContent is POST ?select&select-type=2, as botocore routes it and IAM checks it, and its
// request names no version, so it reads the current one.
if (hasQueryParam(uriInfo, "select")
&& "2".equals(ResteasyRequests.queryParameters(uriInfo).getFirst("select-type"))) {
s3Service.authorizeGetObject(bucket, key, null, authorization);
// The object and its metadata are opened as one snapshot, as for GetObject, and the
// query reads it as the response is written, so the object is never held in memory.
S3SelectService.EventStream events = s3SelectService.select(
s3Service.openObject(bucket, key, versionId), new String(body, StandardCharsets.UTF_8));
s3Service.openObject(bucket, key, null), new String(body, StandardCharsets.UTF_8));
StreamingOutput entity = events::writeTo;
return Response.ok(entity)
.type("application/octet-stream")
@@ -0,0 +1,51 @@
package io.floci.aws.services.s3;
import io.floci.aws.core.common.RequestPathLabels;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.net.URI;
import java.util.Map;
/**
* The key an S3 object request names, as {@link S3Controller} reads it ({@link S3ObjectKeys}): from the path as the
* client sent it, where the key's own slashes survive, which JAX-RS collapses out of the path the route's labels are
* read from. {@code PUT /bucket//email.txt} stores the key {@code /email.txt}, and would otherwise be checked on
* {@code arn:aws:s3:::bucket/email.txt}, so a grant on that object would cover this one. The object stored, the
* object the conditions describe and the object a policy is matched against are then the same one. A route naming no
* key, as every bucket and S3 Control route, is read as the router reads it.
*/
@ApplicationScoped
public class S3RequestPathLabels implements RequestPathLabels {
/** The current request, for its path as sent; null outside a request, where the request URI's raw path stands in. */
private final CurrentVertxRequest currentVertxRequest;
@Inject
public S3RequestPathLabels(CurrentVertxRequest currentVertxRequest) {
this.currentVertxRequest = currentVertxRequest;
}
@Override
public String namespace() {
return "s3";
}
@Override
public Map<String, String> labels(ContainerRequestContext ctx, Map<String, String> routed) {
String bucket = routed.get("Bucket");
if (bucket == null || !routed.containsKey("Key") || ctx.getUriInfo() == null) {
return Map.of();
}
URI requestUri = ctx.getUriInfo().getRequestUri();
RoutingContext current = currentVertxRequest == null ? null : currentVertxRequest.getCurrent();
String sentPath = current != null && current.request() != null ? current.request().path()
: requestUri == null ? null : requestUri.getRawPath();
String key = S3ObjectKeys.objectKey(sentPath, requestUri == null ? null : requestUri.getPath(),
ctx.getUriInfo().getPath(), bucket);
return key == null ? Map.of() : Map.of("Key", key);
}
}