fix(core): stop unknown-service REST requests falling through to S3 (#1967)

* fix(core): stop unknown-service REST requests falling through to S3

REST requests whose SigV4 credential scope names a service Floci does not
implement matched no JAX-RS resource and fell through to S3's path-style
wildcard routes, surfacing as misleading NoSuchBucket XML and triggering SDK
retry storms. Reject them with UnknownOperationException instead.

The guard fires only on positive identification: a parseable SigV4 scope
naming a service absent from the catalog. Unsigned, presigned, Bearer/Basic
and SigV4a requests are untouched.

Also declares the EKS read-only sub-resource lists the emulator does not
model (ListAccessEntries, ListAddons, ListIdentityProviderConfigs,
ListPodIdentityAssociations) as explicit routes, so they outrank the S3
catch-all and answer with each operation's model-exact empty result key,
or ResourceNotFoundException for a missing cluster.

Closes #1754

* fix(iam): normalise signing-scope aliases before IAM enforcement

S3 accepts requests signed under the s3express scope, but IAM action rules,
resource ARNs and condition keys are all keyed by the canonical signing name.
An alias therefore resolved to no action, which IamEnforcementFilter treats as
ALLOW, so policy-protected S3 operations were reachable without a policy check.

Resolve the scope through the catalog before enforcement runs. Only aliases are
rewritten: a service whose external key is not itself one of its credential
scopes (CloudWatch Logs signs as logs) is left unchanged, as is any scope the
catalog does not know.

Also documents why SigV4a stays outside the unknown-service guard — its
credential omits the region segment, so SigV4CredentialScope does not match it
— and pins that with a test, since widening the pattern would silently start
rejecting SigV4a traffic.

Refs #1754

* fix(iot): declare the iot-jobs-data signing scope so its routes stay reachable

The IoT Jobs Data Plane (GetPendingJobExecutions, DescribeJobExecution,
StartNextPendingJobExecution, UpdateJobExecution) signs under iot-jobs-data
while IotController serves its /things/{thing}/jobs routes. The scope was not
in the catalog, so the unknown-service guard rejected requests to routes Floci
does implement. The Go, Java and Python SDK compat suites all caught it on
GetPendingJobExecutions.

Audited the other sibling signing names for the same failure mode:
ssmmessages, eks-auth, ecr-public, cognito-identity and aoss have no Floci
routes, so rejecting those stays correct.

Refs #1754

* fix(iam): scope alias normalisation to an explicit table

Deriving the canonical scope from the descriptor's external key was wrong: the
external key is a routing key, not an IAM namespace. SES routes under email and
Bedrock Runtime under bedrock-runtime while their IAM namespaces are ses: and
bedrock:, so ses, sesv2 and bedrock were rewritten onto prefixes AWS never
issues. Every action would then resolve to null and enforcement would be
skipped for those services — the same bypass the s3express fix closed.

Replace the derivation with an explicit alias table holding the one case that
genuinely shares a namespace, s3express -> s3, and sweep every scope the catalog
declares in the test so any future rewrite has to be deliberate.

Refs #1754

* fix(core): make the unknown-service guard configurable and verify scope coverage

The guard is only as good as the catalog's scope list, and the iot-jobs-data
miss showed the list can be wrong. Two changes so that is recoverable and
detectable rather than a hard 404 nobody can work around.

Gate the rejection behind floci.protocols.reject-unknown-service-scope,
matching the other two abort paths in AwsProtocolClaimFilter, which are both
already gated. It defaults to true so #1754 stays fixed out of the box; turning
it off restores the previous fall-through for anyone blocked by a scope Floci
has not enumerated yet.

Add CredentialScopeCoverageTest, which walks botocore's models and fails when
Floci routes most of a service's operations without declaring the name that
service signs with. Removing iot-jobs-data from the catalog makes it fail with
'iot-jobs-data=2/3 routes served'. Thresholds are conservative because small
services share generic templates, so it is a tripwire rather than a proof, and
it skips where the gitignored botocore checkout is absent (CI runners).

Refs #1754

* fix(iam): resolve the iot-jobs-data signing scope to the iot namespace

Admitting iot-jobs-data to the catalog let the IoT Jobs Data Plane reach its
routes, but IAM enforcement still saw the raw scope. Its policy actions live
under iot: (iot:DescribeJobExecution and peers in the Service Authorization
Reference), so the scope belongs in the alias table next to s3express.

No behaviour change today: IamActionRegistry carries no iot rules at all, so
every IoT request resolves to no action and is allowed through regardless. This
makes the mapping correct ahead of those rules existing, rather than leaving a
scope that would silently escape them.

Refs #1754
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-07-27 22:23:32 -05:00
1 parent 2bea2c0aec
commit 836c162136
16 files changed
+774 -15

No files matched your search

@@ -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<String, String> 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;
}
}
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <p>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<String> declared = catalog.all().stream()
.flatMap(descriptor -> descriptor.credentialScopes().stream())
.collect(Collectors.toSet());
Set<String> flociRoutes = flociRouteTemplates();
Map<String, Set<String>> modelled = routeTemplatesBySigningName();
Map<String, String> 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<String> flociRouteTemplates() throws IOException {
try (Stream<Path> sources = Files.walk(Path.of("src/main/java"))) {
List<Path> controllers = sources
.filter(p -> p.getFileName().toString().endsWith("Controller.java"))
.toList();
Set<String> 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<String, Set<String>> routeTemplatesBySigningName() throws IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Set<String>> bySigningName = new HashMap<>();
try (Stream<Path> services = Files.list(BOTOCORE)) {
for (Path service : services.filter(Files::isDirectory).toList()) {
Optional<Path> 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<Path> latestModel(Path serviceDir) throws IOException {
try (Stream<Path> 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("/+$", "");
}
}
@@ -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.
@@ -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
// <key>/<date>/<service>/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());
}
}
@@ -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("<Code>NoSuchBucket</Code>"));
}
public static final class GuardDisabledProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.protocols.reject-unknown-service-scope", "false");
}
}
}
@@ -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("<Code>NoSuchBucket</Code>"));
}
@Test
void s3expressScopedRequestKeepsS3Behavior() {
given()
.header("Authorization", authorization("s3express"))
.when()
.get("/no-such-bucket-1754?list-type=2")
.then()
.statusCode(404)
.body(containsString("<Code>NoSuchBucket</Code>"));
}
@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("<Code>NoSuchBucket</Code>"));
}
@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("<Code>NoSuchBucket</Code>"));
}
@Test
void bearerAuthorizationIsUntouched() {
given()
.header("Authorization", "Bearer some-token")
.when()
.get("/no-such-bucket-1754?list-type=2")
.then()
.statusCode(404)
.body(containsString("<Code>NoSuchBucket</Code>"));
}
@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);
}
}
@@ -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);
}
}
@@ -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() {