diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index d108265840..1c7e2bf679 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -55,6 +55,7 @@ See [TLS / HTTPS](./tls.md) for SDK configuration examples and WebSocket (`wss:/ | Variable | Default | Description | |---|---|---| | `FLOCI_PROTOCOLS_STRICT_CLAIMING` | `false` | Reject RPC-signaled requests that no supported wire protocol claims, per the [Smithy wire-protocol-selection guide](https://smithy.io/2.0/guides/wire-protocol-selection.html) (e.g. an unknown `Smithy-Protocol` header value or an unimplemented `rpc-v2-json` request). When disabled such requests are logged and pass through | +| `FLOCI_PROTOCOLS_REJECT_UNKNOWN_SERVICE_SCOPE` | `true` | Reject REST requests whose SigV4 credential scope names a service Floci does not implement, with `UnknownOperationException` instead of letting them fall through to S3's path-style routes and return a misleading `NoSuchBucket`. Set to `false` if Floci serves a route whose signing scope is not yet enumerated: the request then falls through as before instead of failing with a 404 | --- diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 83db3e778b..a3913efa89 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -86,6 +86,19 @@ public interface EmulatorConfig { */ @WithDefault("false") boolean strictClaiming(); + + /** + * When enabled, a REST request whose SigV4 credential scope names a service + * absent from the catalog is rejected with {@code UnknownOperationException} + * instead of falling through JAX-RS matching into S3's path-style routes, + * where it surfaces as a misleading {@code NoSuchBucket} (issue #1754). + * + *

On by default. Turn it off if Floci serves a route whose signing scope + * is not yet enumerated in the catalog: the request then falls through as it + * did before, rather than failing with a 404 that has no workaround. + */ + @WithDefault("true") + boolean rejectUnknownServiceScope(); } interface DnsConfig { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsProtocolClaimFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsProtocolClaimFilter.java index a72fd58d18..71d91af33b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsProtocolClaimFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsProtocolClaimFilter.java @@ -21,6 +21,17 @@ import java.util.Optional; * filter (SQS queue URLs, S3 virtual hosts, Lambda URLs — default priority * 5000) and {@link AwsCborContentTypeFilter} (3000) has already produced the * final path and stashed the original content type. + *

+ * Also rejects REST requests whose SigV4 credential scope names a service + * absent from the catalog: without this they fall through JAX-RS matching + * into S3's path-style wildcard routes and fail with misleading S3 XML + * errors. This is not a catch-all — it fires only on positive identification + * (a parseable SigV4 scope) of a service Floci does not enumerate; unsigned, + * presigned, Bearer/Basic and SigV4a requests are untouched. SigV4a falls out + * of scope because its credential omits the region segment + * ({@code ///aws4_request}), which + * {@link SigV4CredentialScope} does not match — widening that pattern would + * silently start rejecting SigV4a traffic. */ @Provider @PreMatching @@ -32,13 +43,16 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter { private static final Logger LOG = Logger.getLogger(AwsProtocolClaimFilter.class); private final ProtocolClaimer claimer; + private final ResolvedServiceCatalog catalog; // Lazily resolved: JAX-RS providers are instantiated before runtime config // mappings exist (same pattern as GlobalCorsFilter). private final jakarta.inject.Provider configProvider; @Inject - public AwsProtocolClaimFilter(ProtocolClaimer claimer, jakarta.inject.Provider configProvider) { + public AwsProtocolClaimFilter(ProtocolClaimer claimer, ResolvedServiceCatalog catalog, + jakarta.inject.Provider configProvider) { this.claimer = claimer; + this.catalog = catalog; this.configProvider = configProvider; } @@ -59,6 +73,24 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter { ProtocolClaim resolved = claim.get(); ctx.setProperty(CLAIM_PROPERTY, resolved); + if (resolved.protocol() == WireProtocol.REST) { + Optional scope = SigV4CredentialScope.serviceName(signals.authorization()); + if (scope.isPresent() && catalog.byCredentialScope(scope.get()).isEmpty()) { + // Gated like the other rejections in this filter. The guard is only as good as + // the catalog's scope list: if Floci serves a route whose signing scope is not + // enumerated, rejecting is a 404 with no workaround, so leave users a switch. + if (!configProvider.get().protocols().rejectUnknownServiceScope()) { + LOG.debugv("Unsupported service scope {0} on {1} {2}, rejection disabled by config", + scope.get(), signals.method(), signals.path()); + return; + } + LOG.infov("Rejecting request signed for unsupported service scope {0}: {1} {2}", + scope.get(), signals.method(), signals.path()); + ctx.abortWith(unknownOperationResponse(404, + "Unknown operation: " + signals.method() + " " + signals.path())); + return; + } + } if (resolved.protocol() == WireProtocol.RPCV2_JSON) { LOG.warnv("Received rpc-v2-json request for service {0} operation {1} — protocol not implemented", resolved.service() != null ? resolved.service().externalKey() : "unknown", @@ -79,6 +111,8 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter { return Response.status(status) .type(MediaType.APPLICATION_JSON) .header("x-amzn-query-error", "UnknownOperationException;Sender") + // rest-json SDKs resolve the error code from this header before the body __type + .header("X-Amzn-Errortype", "UnknownOperationException") .entity(new AwsErrorResponse("UnknownOperationException", message)) .build(); } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 5932a71baf..0f655098a4 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -59,6 +59,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private final IamConditionContextResolver conditionContextResolver; private final CloudTrailService cloudTrailService; private final CurrentVertxRequest currentVertxRequest; + private final ResolvedServiceCatalog catalog; @Inject public IamEnforcementFilter(EmulatorConfig config, @@ -70,7 +71,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { RequestContext requestContext, IamConditionContextResolver conditionContextResolver, CloudTrailService cloudTrailService, - CurrentVertxRequest currentVertxRequest) { + CurrentVertxRequest currentVertxRequest, + ResolvedServiceCatalog catalog) { this.config = config; this.accountResolver = accountResolver; this.iamService = iamService; @@ -81,6 +83,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { this.conditionContextResolver = conditionContextResolver; this.cloudTrailService = cloudTrailService; this.currentVertxRequest = currentVertxRequest; + this.catalog = catalog; } @Override @@ -99,10 +102,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return; // root bypass } - String credentialScope = extractCredentialScope(auth); - if (credentialScope == null) { + String rawScope = extractCredentialScope(auth); + if (rawScope == null) { return; } + // Normalise signing aliases (s3express → s3) before anything keyed by scope runs: + // action rules, ARN building and condition keys all match the canonical name, so an + // alias would resolve to no action and be allowed through without any policy check. + String credentialScope = catalog.canonicalCredentialScope(rawScope); String action = actionRegistry.resolve(credentialScope, ctx); if (action == null) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index afe8873f44..1affc4ec4f 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -32,6 +32,18 @@ import java.util.Set; @ApplicationScoped public class ResolvedServiceCatalog { + /** + * Signing scopes that share another service's IAM namespace. S3 Express One Zone clients sign + * directory-bucket requests as {@code s3express} while the actions, ARNs and condition keys + * remain {@code s3}; the IoT Jobs Data Plane signs as {@code iot-jobs-data} while its actions + * are {@code iot:} ({@code iot:DescribeJobExecution} and peers in the Service Authorization + * Reference). Keep this minimal: every entry suppresses a distinct IAM namespace. + */ + private static final java.util.Map CREDENTIAL_SCOPE_ALIASES = + java.util.Map.of( + "s3express", "s3", + "iot-jobs-data", "iot"); + private final ServiceCatalog catalog; @Inject @@ -51,7 +63,8 @@ public class ResolvedServiceCatalog { "s3", storageMode(config.storage().services().s3().mode(), config.storage().mode()), 5000L, AwsNamespaces.S3, ServiceProtocol.REST_XML, protocols(ServiceProtocol.REST_XML), - Set.of(), Set.of("s3"), Set.of(), Set.of()), + // s3express: directory-bucket (S3 Express One Zone) clients sign with it + Set.of(), Set.of("s3", "s3express"), Set.of(), Set.of()), descriptor("dynamodb", "dynamodb", config.services().dynamodb().enabled(), true, "dynamodb", storageMode(config.storage().services().dynamodb().mode(), config.storage().mode()), config.storage().services().dynamodb().flushIntervalMs(), null, ServiceProtocol.JSON, @@ -372,7 +385,11 @@ public class ResolvedServiceCatalog { descriptor("iot", "iot", config.services().iot().enabled(), true, "iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), - Set.of(), Set.of("iot", "execute-api"), Set.of(), Set.of(IotController.class)), + // iot-jobs-data: the IoT Jobs Data Plane (GetPendingJobExecutions, + // DescribeJobExecution, StartNextPendingJobExecution, UpdateJobExecution) + // signs under its own name while IotController serves its /things/*/jobs routes + Set.of(), Set.of("iot", "execute-api", "iot-jobs-data"), Set.of(), + Set.of(IotController.class)), descriptor("iotdata", "iotdata", config.services().iotdata().enabled(), true, "iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), @@ -400,6 +417,23 @@ public class ResolvedServiceCatalog { return catalog.byCredentialScope(credentialScope); } + /** + * Canonical IAM namespace for a credential scope. A service may answer requests signed + * under more than one scope (S3 also accepts {@code s3express}), but IAM action rules, + * resource ARNs and condition keys are all keyed by the canonical one — an alias left + * unnormalised resolves to no action, which the enforcement filter treats as ALLOW. + * + *

Deliberately an explicit table rather than something derived from the descriptor: + * a descriptor's external key is a routing key, not an IAM namespace. SES routes under + * {@code email} and Bedrock Runtime under {@code bedrock-runtime}, while their IAM + * namespaces are {@code ses:} and {@code bedrock:} — deriving from the external key would + * rewrite valid scopes onto prefixes AWS never issues, and silently skip enforcement for + * those services. Add an entry here only when two scopes genuinely share one namespace. + */ + public String canonicalCredentialScope(String credentialScope) { + return CREDENTIAL_SCOPE_ALIASES.getOrDefault(credentialScope, credentialScope); + } + public Optional byResourceClass(Class resourceClass) { return catalog.byResourceClass(resourceClass); } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java index 02dca3ab9b..0a90fa3e94 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java @@ -128,4 +128,37 @@ public class EksController { FargateProfile profile = eksService.deleteFargateProfile(name, fargateProfileName); return Response.ok(Map.of("fargateProfile", profile)).build(); } + + // Read-only sub-resource lists for resources the emulator does not model. Explicit routes + // so S3's path-style catch-all (@Path("/{bucket}/{key: .+}")) cannot swallow them + // (issue #1754, same family as #1137): validate the cluster, then return the documented + // empty list under each operation's model-exact result key. + + @GET + @Path("/clusters/{name}/access-entries") + public Response listAccessEntries(@PathParam("name") String name) { + eksService.describeCluster(name); + return Response.ok(Map.of("accessEntries", List.of())).build(); + } + + @GET + @Path("/clusters/{name}/addons") + public Response listAddons(@PathParam("name") String name) { + eksService.describeCluster(name); + return Response.ok(Map.of("addons", List.of())).build(); + } + + @GET + @Path("/clusters/{name}/identity-provider-configs") + public Response listIdentityProviderConfigs(@PathParam("name") String name) { + eksService.describeCluster(name); + return Response.ok(Map.of("identityProviderConfigs", List.of())).build(); + } + + @GET + @Path("/clusters/{name}/pod-identity-associations") + public Response listPodIdentityAssociations(@PathParam("name") String name) { + eksService.describeCluster(name); + return Response.ok(Map.of("associations", List.of())).build(); + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d6b135c4d8..debf832e56 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -179,6 +179,7 @@ floci: protocols: strict-claiming: false # FLOCI_PROTOCOLS_STRICT_CLAIMING — reject RPC-signaled requests that no supported wire protocol claims + reject-unknown-service-scope: true # FLOCI_PROTOCOLS_REJECT_UNKNOWN_SERVICE_SCOPE — reject REST requests signed for a service Floci does not implement docker: log-max-size: "10m" diff --git a/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java new file mode 100644 index 0000000000..82cb1933eb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.services.iam.IamActionRegistry; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.UriInfo; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A service may accept more than one signing scope (S3 also answers requests signed for + * {@code s3express}), but IAM action rules, ARN building and condition keys are keyed by the + * canonical name. An unnormalised alias resolves to no action, which the enforcement filter + * treats as ALLOW — so the alias must map back to the canonical scope before enforcement runs. + */ +@QuarkusTest +class CredentialScopeAliasTest { + + @Inject + ResolvedServiceCatalog catalog; + + @Inject + IamActionRegistry actionRegistry; + + @Test + void s3ExpressAliasNormalisesToS3() { + assertEquals("s3", catalog.canonicalCredentialScope("s3express")); + } + + @Test + void iotJobsDataAliasNormalisesToIot() { + // The IoT Jobs Data Plane signs as iot-jobs-data, but its policy actions live under the + // iot: namespace (iot:DescribeJobExecution and peers in the Service Authorization + // Reference), so enforcement has to resolve it there rather than invent iot-jobs-data:. + assertEquals("iot", catalog.canonicalCredentialScope("iot-jobs-data")); + } + + @Test + void canonicalScopeIsUnchanged() { + assertEquals("s3", catalog.canonicalCredentialScope("s3")); + assertEquals("dynamodb", catalog.canonicalCredentialScope("dynamodb")); + } + + @Test + void unknownScopeIsLeftAlone() { + assertEquals("securityhub", catalog.canonicalCredentialScope("securityhub")); + } + + @Test + void scopeWhoseExternalKeyIsNotItsIamNamespaceIsLeftAlone() { + // These are the traps: the catalog routes SES under "email" and Bedrock Runtime under + // "bedrock-runtime", but their IAM namespaces are "ses:" and "bedrock:". Deriving the + // canonical scope from the external key would rewrite valid scopes onto prefixes AWS + // never issues, so every action would resolve to null and enforcement would be skipped. + assertEquals("ses", catalog.canonicalCredentialScope("ses")); + assertEquals("sesv2", catalog.canonicalCredentialScope("sesv2")); + assertEquals("bedrock", catalog.canonicalCredentialScope("bedrock")); + assertEquals("logs", catalog.canonicalCredentialScope("logs")); + } + + @Test + void onlyExplicitlyAliasedScopesAreRewritten() { + // Sweep every scope the catalog declares. Anything that changes is a service whose + // IAM namespace we just moved, so it must be a deliberate alias, not a derivation. + Map rewritten = catalog.all().stream() + .flatMap(descriptor -> descriptor.credentialScopes().stream()) + .distinct() + .filter(scope -> !scope.equals(catalog.canonicalCredentialScope(scope))) + .collect(Collectors.toMap(scope -> scope, catalog::canonicalCredentialScope)); + + assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot"), rewritten); + } + + @Test + void normalisedAliasResolvesTheSameS3ActionAsTheCanonicalScope() { + ContainerRequestContext ctx = getObjectRequest(); + String viaAlias = actionRegistry.resolve(catalog.canonicalCredentialScope("s3express"), ctx); + String viaCanonical = actionRegistry.resolve("s3", ctx); + + assertEquals(viaCanonical, viaAlias); + assertEquals("s3:GetObject", viaAlias); + } + + @Test + void rawAliasResolvesNoActionWithoutNormalisation() { + assertEquals(null, actionRegistry.resolve("s3express", getObjectRequest())); + } + + private static ContainerRequestContext getObjectRequest() { + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getPath()).thenReturn("/my-bucket/my-key"); + when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>()); + + ContainerRequestContext ctx = mock(ContainerRequestContext.class); + when(ctx.getMethod()).thenReturn("GET"); + when(ctx.getUriInfo()).thenReturn(uriInfo); + when(ctx.getHeaderString("X-Amz-Target")).thenReturn(null); + return ctx; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeCoverageTest.java b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeCoverageTest.java new file mode 100644 index 0000000000..69fdacebdf --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeCoverageTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Tripwire for the failure mode behind issue #1754's guard: Floci serves a service's routes but + * never enumerates the name that service signs with, so the guard rejects requests to routes that + * do work. The IoT Jobs Data Plane hit exactly this — {@code IotController} serves + * {@code /things/{thing}/jobs} while the scope is {@code iot-jobs-data} — and only the SDK compat + * suites caught it. + * + *

The check walks botocore's models: for every AWS signing name the catalog does not declare, + * it measures how much of that service's REST surface Floci already routes. A service whose routes + * Floci overwhelmingly serves is one Floci effectively implements, so its signing name belongs in + * the catalog. + * + *

Thresholds are deliberately conservative. Small services share generic templates + * ({@code /tags/{id}}, {@code /jobs/{id}}) with dozens of unrelated APIs, so this is a heuristic + * tripwire rather than a proof of completeness — the SDK compat suites remain the real check. + * + *

Skips when the botocore checkout is absent, which is the case on CI runners: the reference + * models live in the gitignored {@code local/aws/} tree, so this runs for maintainers who have it. + */ +@QuarkusTest +class CredentialScopeCoverageTest { + + private static final Path BOTOCORE = Path.of("local/aws/botocore/botocore/data"); + private static final Pattern PATH_PARAM = Pattern.compile("\\{[^}]+}"); + private static final Pattern PATH_ANNOTATION = Pattern.compile("@Path\\(\"([^\"]*)\"\\)"); + private static final Pattern CLASS_PATH_ANNOTATION = + Pattern.compile("@Path\\(\"([^\"]*)\"\\)\\s*(?:@\\w+(?:\\([^)]*\\))?\\s*)*public\\s+class"); + + /** Below this many modelled routes a service is too small to tell coincidence from coverage. */ + private static final int MIN_ROUTES = 3; + /** Fraction of a service's routes Floci must already serve before its scope is expected. */ + private static final double MIN_COVERAGE = 0.6; + + @Inject + ResolvedServiceCatalog catalog; + + @Test + void everyServiceWhoseRoutesFlociServesHasItsSigningNameDeclared() throws IOException { + assumeTrue(Files.isDirectory(BOTOCORE), + "botocore checkout not present (see CLAUDE.md, local/aws/) — skipping"); + + Set declared = catalog.all().stream() + .flatMap(descriptor -> descriptor.credentialScopes().stream()) + .collect(Collectors.toSet()); + Set flociRoutes = flociRouteTemplates(); + Map> modelled = routeTemplatesBySigningName(); + + Map undeclared = new TreeMap<>(); + modelled.forEach((signingName, routes) -> { + if (declared.contains(signingName) || routes.size() < MIN_ROUTES) { + return; + } + long served = routes.stream().filter(flociRoutes::contains).count(); + double coverage = (double) served / routes.size(); + if (coverage >= MIN_COVERAGE) { + undeclared.put(signingName, served + "/" + routes.size() + " routes served"); + } + }); + + assertTrue(undeclared.isEmpty(), + "Floci routes these services' operations but never declares the name they sign with, " + + "so the unknown-service guard rejects requests that would otherwise work. " + + "Add each to the owning descriptor's credential scopes in ResolvedServiceCatalog: " + + undeclared); + } + + /** Path templates Floci's JAX-RS controllers declare, normalised to botocore's shape. */ + private static Set flociRouteTemplates() throws IOException { + try (Stream sources = Files.walk(Path.of("src/main/java"))) { + List controllers = sources + .filter(p -> p.getFileName().toString().endsWith("Controller.java")) + .toList(); + Set templates = new HashSet<>(); + for (Path controller : controllers) { + String source = Files.readString(controller); + Matcher classMatcher = CLASS_PATH_ANNOTATION.matcher(source); + String classPath = classMatcher.find() ? trimSlashes(classMatcher.group(1)) : ""; + Matcher methodMatcher = PATH_ANNOTATION.matcher(source); + while (methodMatcher.find()) { + String methodPath = trimSlashes(methodMatcher.group(1)); + if (methodPath.equals(classPath)) { + continue; + } + String full = classPath.isEmpty() ? "/" + methodPath : "/" + classPath + "/" + methodPath; + templates.add(normalise(full)); + } + } + return templates; + } + } + + /** Every AWS signing name mapped to the request-URI templates its operations declare. */ + private static Map> routeTemplatesBySigningName() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + Map> bySigningName = new HashMap<>(); + try (Stream services = Files.list(BOTOCORE)) { + for (Path service : services.filter(Files::isDirectory).toList()) { + Optional model = latestModel(service); + if (model.isEmpty()) { + continue; + } + JsonNode root = mapper.readTree(model.get().toFile()); + JsonNode metadata = root.path("metadata"); + String signingName = metadata.path("signingName").asText( + metadata.path("endpointPrefix").asText(null)); + if (signingName == null || signingName.isBlank()) { + continue; + } + root.path("operations").forEach(operation -> { + String uri = operation.path("http").path("requestUri").asText(null); + if (uri == null) { + return; + } + String template = normalise(uri.split("\\?")[0]); + if (template.chars().filter(c -> c == '/').count() < 2) { + return; + } + bySigningName.computeIfAbsent(signingName, k -> new HashSet<>()).add(template); + }); + } + } + return bySigningName; + } + + private static Optional latestModel(Path serviceDir) throws IOException { + try (Stream versions = Files.list(serviceDir)) { + return versions.filter(Files::isDirectory) + .map(version -> version.resolve("service-2.json")) + .filter(Files::isRegularFile) + .max(Path::compareTo); + } + } + + private static String normalise(String path) { + return PATH_PARAM.matcher(path).replaceAll("{}").replace("//", "/"); + } + + private static String trimSlashes(String path) { + return path.replaceAll("^/+", "").replaceAll("/+$", ""); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index d245ae6486..bfb328b62b 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; @@ -46,6 +47,7 @@ class IamEnforcementFilterTest { private ResourceArnBuilder arnBuilder; private RequestContext requestContext; private IamConditionContextResolver conditionContextResolver; + private ResolvedServiceCatalog catalog; @BeforeEach void setUp() { @@ -59,11 +61,23 @@ class IamEnforcementFilterTest { arnBuilder = mock(ResourceArnBuilder.class); requestContext = new RequestContext(); conditionContextResolver = mock(IamConditionContextResolver.class); + catalog = mock(ResolvedServiceCatalog.class); when(config.services()).thenReturn(services); when(services.iam()).thenReturn(iamConfig); when(iamConfig.enforcementEnabled()).thenReturn(true); when(config.defaultRegion()).thenReturn("us-east-1"); + // Default: scopes are already canonical. Alias handling is asserted explicitly below. + when(catalog.canonicalCredentialScope(anyString())).thenAnswer(inv -> inv.getArgument(0)); + } + + private IamEnforcementFilter newFilter() { + return new IamEnforcementFilter( + config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder, + requestContext, conditionContextResolver, + mock(CloudTrailService.class), + mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class), + catalog); } @Test @@ -97,10 +111,7 @@ class IamEnforcementFilterTest { when(conditionContextResolver.resolve("lambda", "lambda:InvokeFunction", containerRequest)) .thenReturn(null); - IamEnforcementFilter filter = new IamEnforcementFilter( - config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder, - requestContext, conditionContextResolver, - mock(CloudTrailService.class), mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class)); + IamEnforcementFilter filter = newFilter(); filter.filter(containerRequest); @@ -132,10 +143,7 @@ class IamEnforcementFilterTest { when(evaluator.evaluate(any(), isNull(), eq("s3:ListBucket"), eq("arn:aws:s3:::bucket"), eq(conditions))) .thenReturn(IamPolicyEvaluator.Decision.ALLOW); - IamEnforcementFilter filter = new IamEnforcementFilter( - config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder, - requestContext, conditionContextResolver, - mock(CloudTrailService.class), mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class)); + IamEnforcementFilter filter = newFilter(); filter.filter(containerRequest); @@ -143,6 +151,42 @@ class IamEnforcementFilterTest { eq("arn:aws:s3:::bucket"), eq(conditions)); } + @Test + void aliasScopeIsEnforcedUnderItsCanonicalName() { + // S3 Express clients sign with the s3express scope. Everything keyed by scope — action + // rules, ARN building, condition keys — knows only "s3", so without normalisation the + // action resolves to null and the filter allows the request through unchecked. + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + + String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260726/us-east-1/s3express/aws4_request, " + + "SignedHeaders=host, Signature=abc"; + requestContext.setAccountId("222233334444"); + requestContext.setRegion("us-east-1"); + + when(catalog.canonicalCredentialScope("s3express")).thenReturn("s3"); + when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION"); + when(containerRequest.getHeaderString("Authorization")).thenReturn(auth); + when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject"); + when(iamService.resolveCallerContext("ASIASESSION")) + .thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:PutObject","Resource":"*"} + ]}"""))); + when(arnBuilder.build(eq("s3"), eq(containerRequest), anyString(), anyString())) + .thenReturn("arn:aws:s3:::bucket/key"); + when(evaluator.evaluate(any(), any(), any(), any(), any())) + .thenReturn(IamPolicyEvaluator.Decision.DENY); + + newFilter().filter(containerRequest); + + // Everything keyed by scope must see the canonical name, not the alias. + verify(actionRegistry).resolve("s3", containerRequest); + verify(arnBuilder).build(eq("s3"), eq(containerRequest), anyString(), anyString()); + verify(conditionContextResolver).resolve("s3", "s3:GetObject", containerRequest); + // The policy above grants only s3:PutObject, so a GetObject signed as s3express is denied. + verify(containerRequest).abortWith(any(Response.class)); + } + @Test void queryProtocolGetsXmlErrorResponse() { // IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response. diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java new file mode 100644 index 0000000000..714a499083 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/SigV4CredentialScopeTest.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Pins the boundary the unknown-service guard relies on (issue #1754): the guard only fires + * on a scope this parser returns, so anything it declines to parse is left to normal routing. + */ +class SigV4CredentialScopeTest { + + @Test + void parsesSigV4Scope() { + assertEquals(Optional.of("s3"), SigV4CredentialScope.serviceName( + "AWS4-HMAC-SHA256 Credential=AKID/20260707/us-east-1/s3/aws4_request," + + " SignedHeaders=host;x-amz-date, Signature=deadbeef")); + } + + @Test + void lowercasesScope() { + assertEquals(Optional.of("dynamodb"), SigV4CredentialScope.serviceName( + "AWS4-HMAC-SHA256 Credential=AKID/20260707/us-east-1/DynamoDB/aws4_request," + + " SignedHeaders=host, Signature=deadbeef")); + } + + @Test + void ignoresSigV4aBecauseItsCredentialOmitsTheRegion() { + // SigV4a carries the region in X-Amz-Region-Set, so its credential is + // ///aws4_request — one segment shorter than SigV4. + assertTrue(SigV4CredentialScope.serviceName( + "AWS4-ECDSA-P256-SHA256 Credential=AKID/20260707/s3/aws4_request," + + " SignedHeaders=host;x-amz-region-set, Signature=deadbeef").isEmpty()); + } + + @Test + void ignoresMissingAndUnsignedHeaders() { + assertTrue(SigV4CredentialScope.serviceName(null).isEmpty()); + assertTrue(SigV4CredentialScope.serviceName("Bearer token").isEmpty()); + assertTrue(SigV4CredentialScope.serviceName("Basic dXNlcjpwYXNz").isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardDisabledIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardDisabledIntegrationTest.java new file mode 100644 index 0000000000..802ffb7648 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardDisabledIntegrationTest.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * The guard is only as good as the catalog's scope list, so it has an off switch: if Floci + * serves a route whose signing scope is not enumerated, rejecting it is a 404 with no + * workaround. Disabling restores the pre-#1754 fall-through rather than failing the request. + */ +@QuarkusTest +@TestProfile(UnknownServiceScopeGuardDisabledIntegrationTest.GuardDisabledProfile.class) +class UnknownServiceScopeGuardDisabledIntegrationTest { + + @Test + void unsupportedScopeFallsThroughWhenRejectionDisabled() { + given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260707/us-east-1/securityhub" + + "/aws4_request, SignedHeaders=host;x-amz-date, Signature=deadbeef") + .when() + .get("/accounts") + .then() + // Back to the old behaviour: S3's path-style catch-all answers for the bucket + // named "accounts", instead of the guard's UnknownOperationException. + .statusCode(404) + .body(containsString("NoSuchBucket")); + } + + public static final class GuardDisabledProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.protocols.reject-unknown-service-scope", "false"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java new file mode 100644 index 0000000000..8df629b875 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java @@ -0,0 +1,140 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * REST requests signed for a service Floci does not implement must be rejected with the + * clean UnknownOperationException shape instead of falling through JAX-RS matching into + * S3's path-style wildcard routes (issue #1754). The guard requires positive identification + * via the SigV4 credential scope: unsigned, presigned, and Bearer traffic stays untouched. + */ +@QuarkusTest +class UnknownServiceScopeGuardIntegrationTest { + + private static String authorization(String service) { + return "AWS4-HMAC-SHA256 Credential=test/20260707/us-east-1/" + service + + "/aws4_request, SignedHeaders=host;x-amz-date, Signature=deadbeef"; + } + + @Test + void accountScopedRestRequestGetsUnknownOperation() { + given() + .header("Authorization", authorization("account")) + .contentType("application/json") + .body("{}") + .when() + .post("/listRegions") + .then() + .statusCode(404) + .contentType(containsString("application/json")) + .header("X-Amzn-Errortype", "UnknownOperationException") + .header("x-amzn-query-error", "UnknownOperationException;Sender") + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void securityhubScopedRestRequestGetsUnknownOperation() { + given() + .header("Authorization", authorization("securityhub")) + .when() + .get("/accounts") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void s3ScopedRequestKeepsS3Behavior() { + given() + .header("Authorization", authorization("s3")) + .when() + .get("/no-such-bucket-1754?list-type=2") + .then() + .statusCode(404) + .contentType(containsString("xml")) + .body(containsString("NoSuchBucket")); + } + + @Test + void s3expressScopedRequestKeepsS3Behavior() { + given() + .header("Authorization", authorization("s3express")) + .when() + .get("/no-such-bucket-1754?list-type=2") + .then() + .statusCode(404) + .body(containsString("NoSuchBucket")); + } + + @Test + void iotJobsDataPlaneScopeReachesItsIotRoutes() { + // The IoT Jobs Data Plane signs as iot-jobs-data while IotController serves its + // /things/{thing}/jobs routes. The scope has to be enumerated or the guard rejects a + // route Floci does implement — the SDK compat suites caught exactly this on + // GetPendingJobExecutions. + given() + .header("Authorization", authorization("iot-jobs-data")) + .when() + .get("/things/guard-test-thing/jobs") + .then() + // IoT's own "thing not found", which only IotController can produce: the request + // reached the route. The guard's rejection would be UnknownOperationException instead. + .statusCode(404) + .body("message", containsString("guard-test-thing")) + .body("__type", not(equalTo("UnknownOperationException"))); + } + + @Test + void unsignedRequestIsUntouched() { + given() + .when() + .get("/no-such-bucket-1754?list-type=2") + .then() + .statusCode(404) + .body(containsString("NoSuchBucket")); + } + + @Test + void presignedStyleQueryCredentialIsUntouched() { + // No Authorization header: query-string credentials are presigned-URL territory, + // out of the guard's positive-identification scope even with a bogus service. + given() + .queryParam("X-Amz-Credential", "test/20260707/us-east-1/account/aws4_request") + .when() + .get("/no-such-bucket-1754") + .then() + .statusCode(404) + .body(containsString("NoSuchBucket")); + } + + @Test + void bearerAuthorizationIsUntouched() { + given() + .header("Authorization", "Bearer some-token") + .when() + .get("/no-such-bucket-1754?list-type=2") + .then() + .statusCode(404) + .body(containsString("NoSuchBucket")); + } + + @Test + void rootFormPostSignedForAbsentServiceKeepsQueryProtocolPath() { + // Form-encoded POST / claims AWS_QUERY, not REST — the guard must not intercept it. + given() + .header("Authorization", authorization("account")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListRegions") + .when() + .post("/") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", (String) null); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksSubResourceListsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksSubResourceListsIntegrationTest.java new file mode 100644 index 0000000000..a2f00de228 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksSubResourceListsIntegrationTest.java @@ -0,0 +1,84 @@ +package io.github.hectorvent.floci.services.eks; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; + +/** + * Read-only EKS sub-resource lists (issue #1754). These routes must be handled by EKS — + * previously the paths fell through to S3's path-style catch-all and returned NoSuchBucket + * XML. A missing cluster is the model-declared ResourceNotFoundException (404); an existing + * cluster returns the documented empty list under each operation's exact result key. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class EksSubResourceListsIntegrationTest { + + private static final String JSON = "application/json"; + private static final String CLUSTER = "subres-it-cluster"; + + @ParameterizedTest + @Order(1) + @CsvSource({ + "access-entries, accessEntries", + "addons, addons", + "fargate-profiles, fargateProfileNames", + "identity-provider-configs, identityProviderConfigs", + "pod-identity-associations, associations" + }) + void missingClusterReturnsResourceNotFound(String path, String key) { + given() + .when() + .get("/clusters/no-such-cluster/" + path) + .then() + .statusCode(404) + .contentType(containsString("application/json")) + .body("__type", equalTo("ResourceNotFoundException")) + .body("message", containsString("no-such-cluster")); + } + + @Test + @Order(2) + void createCluster() { + given().contentType(JSON) + .body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks-role\"," + + "\"version\":\"1.29\"}") + .when().post("/clusters") + .then().statusCode(200) + .body("cluster.name", equalTo(CLUSTER)); + } + + @ParameterizedTest + @Order(3) + @CsvSource({ + "access-entries, accessEntries", + "addons, addons", + "fargate-profiles, fargateProfileNames", + "identity-provider-configs, identityProviderConfigs", + "pod-identity-associations, associations" + }) + void existingClusterReturnsEmptyListUnderModelKey(String path, String key) { + given() + .when() + .get("/clusters/" + CLUSTER + "/" + path) + .then() + .statusCode(200) + .contentType(containsString("application/json")) + .body(key, hasSize(0)); + } + + @Test + @Order(4) + void deleteCluster() { + given().when().delete("/clusters/" + CLUSTER).then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java index 114909c29e..33f3b6fbb6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java @@ -322,7 +322,12 @@ class EventBridgeSchedulerIntegrationTest { @Override public EmulatorConfig.InitHooksConfig initHooks() { return null; } @Override - public ProtocolsConfig protocols() { return () -> false; } + public ProtocolsConfig protocols() { + return new ProtocolsConfig() { + @Override public boolean strictClaiming() { return false; } + @Override public boolean rejectUnknownServiceScope() { return true; } + }; + } @Override public TlsConfig tls() { return new TlsConfig() { diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 6558cad914..b1b7d59001 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -80,6 +80,7 @@ floci: protocols: strict-claiming: false + reject-unknown-service-scope: true docker: log-max-size: "10m"