diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 28c4b3db30..a2cf209fb5 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -50,6 +50,14 @@ See [TLS / HTTPS](./tls.md) for SDK configuration examples and WebSocket (`wss:/ --- +## Wire Protocols + +| 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 | + +--- + ## Storage | Variable | Default | Description | 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 35f1503ed0..b3187c88b7 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -72,6 +72,21 @@ public interface EmulatorConfig { TlsConfig tls(); + ProtocolsConfig protocols(); + + interface ProtocolsConfig { + /** + * When enabled, requests carrying an RPC protocol signal that no + * supported wire protocol claims are rejected per the Smithy + * wire-protocol-selection guide (e.g. an unknown Smithy-Protocol header + * value, a recognized-but-unimplemented rpc-v2-json request, or an + * X-Amz-Target post with a foreign content type). When disabled such + * requests are only logged and pass through to JAX-RS matching. + */ + @WithDefault("false") + boolean strictClaiming(); + } + interface DnsConfig { /** * Additional hostname suffixes the embedded DNS server will resolve to Floci's diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java index d3714bf344..e4478d7bad 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java @@ -19,11 +19,33 @@ public class AwsCborContentTypeFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext ctx) { String contentType = ctx.getHeaderString("Content-Type"); - if (contentType == null || !contentType.startsWith(AWS_CBOR_1_1_MEDIA_TYPE)) { + if (contentType != null && contentType.startsWith(AWS_CBOR_1_1_MEDIA_TYPE)) { + normalize(ctx, contentType); return; } - ctx.getHeaders().putSingle(ORIGINAL_CONTENT_TYPE_HEADER, contentType); + // The Smithy-Protocol header is the definitive rpcv2Cbor claim signal; + // normalize the content type so @Consumes matches even if it drifts + // during a protocol transition. Scoped to rpcv2-shaped requests only — + // this filter runs before the path-rewriting filters, and rewriting the + // content type on other paths would erase the signal filters like + // S3VirtualHostFilter use to bypass non-S3 management traffic. + String smithyProtocol = ctx.getHeaderString(ProtocolClaimer.SMITHY_PROTOCOL_HEADER); + boolean rpcV2Cbor = smithyProtocol != null + && ProtocolClaimer.SMITHY_RPC_V2_CBOR.equals(smithyProtocol.trim()); + boolean rpcV2Request = rpcV2Cbor + && "POST".equalsIgnoreCase(ctx.getMethod()) + && ProtocolClaimer.isRpcV2Path(ctx.getUriInfo().getPath()); + boolean alreadyGenericCbor = contentType != null && contentType.startsWith(GENERIC_CBOR_MEDIA_TYPE); + if (rpcV2Request && !alreadyGenericCbor) { + normalize(ctx, contentType); + } + } + + private void normalize(ContainerRequestContext ctx, String originalContentType) { + if (originalContentType != null) { + ctx.getHeaders().putSingle(ORIGINAL_CONTENT_TYPE_HEADER, originalContentType); + } ctx.getHeaders().putSingle("Content-Type", GENERIC_CBOR_MEDIA_TYPE); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java index d3394fb36c..d5e40bff8a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java @@ -23,12 +23,11 @@ import java.util.Iterator; import java.util.Map; /** - * Generic dispatcher for all AWS services that use the application/cbor protocol. - * Routes requests to the appropriate service handler based on the X-Amz-Target header prefix. + * Generic dispatcher for all AWS services that use the application/cbor protocol, + * via either smithy-rpc-v2-cbor path routing or the legacy X-Amz-Target header. *

- * Currently supported services: - * - DynamoDB (DynamoDB_20120810.*) - * - SQS (AmazonSQS.*) + * Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis, + * Step Functions, and CloudWatch Metrics. */ @Path("/") public class AwsJsonCborController { @@ -164,10 +163,11 @@ public class AwsJsonCborController { } /** - * Handles AWS smithy-rpc-v2-cbor protocol requests. - * AWS SDK v2 sends to POST /service/{sdkId}/operation/{op} - * with a CBOR content type and no X-Amz-Target header. - * Supported services: DynamoDB, SQS, SNS, StepFunctions, CloudWatch. + * Handles AWS smithy-rpc-v2-cbor protocol requests: + * POST /service/{serviceName}/operation/{operation} with a CBOR content type, + * the smithy-protocol header, and no X-Amz-Target. The {serviceName} segment + * is the Smithy service shape name — for AWS services the X-Amz-Target prefix + * without its trailing dot (e.g. DynamoDB_20120810, GraniteServiceVersion20100801). */ @POST @Path("service/{serviceId}/operation/{operation}") @@ -291,13 +291,14 @@ public class AwsJsonCborController { } return switch (descriptor.externalKey()) { case "dynamodb" -> { - if ("DynamoDB Streams".equals(serviceId)) { + if ("DynamoDB Streams".equals(serviceId) || serviceId.startsWith("DynamoDBStreams")) { yield dynamoDbStreamsJsonHandler.handle(operation, request, region); } yield dynamoDbJsonHandler.handle(operation, request, region); } case "sqs" -> sqsJsonHandler.handle(operation, request, region); case "sns" -> snsJsonHandler.handle(operation, request, region); + case "kinesis" -> kinesisJsonHandler.handle(operation, request, region); case "states" -> sfnJsonHandler.handle(operation, request, region); case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region); default -> null; 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 new file mode 100644 index 0000000000..a72fd58d18 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsProtocolClaimFilter.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import jakarta.annotation.Priority; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.Provider; +import org.jboss.logging.Logger; + +import java.util.Optional; + +/** + * Claims each request's wire protocol via {@link ProtocolClaimer} and exposes + * the result as a request property for downstream filters and controllers. + *

+ * Runs pre-matching at priority 6000 so every path-rewriting pre-matching + * 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. + */ +@Provider +@PreMatching +@Priority(6000) +public class AwsProtocolClaimFilter implements ContainerRequestFilter { + + public static final String CLAIM_PROPERTY = "floci.protocol.claim"; + + private static final Logger LOG = Logger.getLogger(AwsProtocolClaimFilter.class); + + private final ProtocolClaimer claimer; + // 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) { + this.claimer = claimer; + this.configProvider = configProvider; + } + + @Override + public void filter(ContainerRequestContext ctx) { + ClaimSignals signals = ClaimSignals.from(ctx); + Optional claim = claimer.claim(signals); + + if (claim.isEmpty()) { + LOG.warnv("Unclaimable RPC-signaled request: {0} {1} Content-Type={2} Smithy-Protocol={3}", + signals.method(), signals.path(), signals.contentType(), signals.smithyProtocol()); + if (configProvider.get().protocols().strictClaiming()) { + ctx.abortWith(unknownOperationResponse(404, + "Unable to determine the wire protocol for this request")); + } + return; + } + + ProtocolClaim resolved = claim.get(); + ctx.setProperty(CLAIM_PROPERTY, resolved); + 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", + resolved.operation()); + if (configProvider.get().protocols().strictClaiming()) { + ctx.abortWith(unknownOperationResponse(400, + "The rpc-v2-json protocol is not supported")); + } + } else if (resolved.protocol() != WireProtocol.REST) { + LOG.debugv("Protocol claim: {0} service={1} operation={2}", + resolved.protocol(), + resolved.service() != null ? resolved.service().externalKey() : null, + resolved.operation()); + } + } + + private Response unknownOperationResponse(int status, String message) { + return Response.status(status) + .type(MediaType.APPLICATION_JSON) + .header("x-amzn-query-error", "UnknownOperationException;Sender") + .entity(new AwsErrorResponse("UnknownOperationException", message)) + .build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 66f5e45523..e8dc40f127 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -33,8 +33,6 @@ import org.jboss.logging.Logger; import java.util.Set; import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * Generic dispatcher for all AWS services that use the Query Protocol (form-encoded POST, XML response). @@ -57,10 +55,6 @@ public class AwsQueryController { private static final Logger LOG = Logger.getLogger(AwsQueryController.class); - // Extracts service name: Credential=AKID/20260227/us-east-1/iam/aws4_request → "iam" - private static final Pattern SERVICE_PATTERN = - Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/"); - private static final Set STS_ACTIONS = Set.of( "AssumeRole", "AssumeRoleWithWebIdentity", "AssumeRoleWithSAML", "GetCallerIdentity", "GetSessionToken", "GetFederationToken", @@ -407,15 +401,11 @@ public class AwsQueryController { ); private String resolveService(String authorization, String action) { - if (authorization != null && !authorization.isEmpty()) { - Matcher m = SERVICE_PATTERN.matcher(authorization); - if (m.find()) { - String scope = m.group(1).toLowerCase(); - ServiceDescriptor descriptor = catalog.byCredentialScope(scope).orElse(null); - if (descriptor != null && descriptor.supportsProtocol(ServiceProtocol.QUERY)) { - return descriptor.externalKey(); - } - } + ServiceDescriptor descriptor = SigV4CredentialScope.serviceName(authorization) + .flatMap(catalog::byCredentialScope) + .orElse(null); + if (descriptor != null && descriptor.supportsProtocol(ServiceProtocol.QUERY)) { + return descriptor.externalKey(); } return inferServiceFromAction(action); } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ClaimSignals.java b/src/main/java/io/github/hectorvent/floci/core/common/ClaimSignals.java new file mode 100644 index 0000000000..04dc8db83c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ClaimSignals.java @@ -0,0 +1,34 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.container.ContainerRequestContext; + +/** + * The non-payload identification signals a request's wire protocol is claimed + * from: HTTP method, path, and the claim-relevant headers. The entity stream + * is deliberately absent — claiming must never touch it. + * + * @param method the HTTP method + * @param path the request path, after any pre-matching rewrites + * @param contentType the raw Content-Type header, preferring the original + * value stashed by {@link AwsCborContentTypeFilter} + * @param smithyProtocol the raw Smithy-Protocol header, or null + * @param xAmzTarget the raw X-Amz-Target header, or null + * @param authorization the raw Authorization header, or null + */ +public record ClaimSignals(String method, String path, String contentType, + String smithyProtocol, String xAmzTarget, String authorization) { + + static ClaimSignals from(ContainerRequestContext ctx) { + String contentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER); + if (contentType == null) { + contentType = ctx.getHeaderString("Content-Type"); + } + return new ClaimSignals( + ctx.getMethod(), + ctx.getUriInfo().getPath(), + contentType, + ctx.getHeaderString(ProtocolClaimer.SMITHY_PROTOCOL_HEADER), + ctx.getHeaderString("X-Amz-Target"), + ctx.getHeaderString("Authorization")); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaim.java b/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaim.java new file mode 100644 index 0000000000..3597af4aff --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaim.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.core.common; + +/** + * The result of claiming an inbound request's wire protocol from its + * non-payload signals. + * + * @param protocol the claimed wire protocol + * @param service the resolved service descriptor, or null when the claim + * signals identify a protocol but not a known service + * @param operation the operation name from the rpcv2 path or the X-Amz-Target + * suffix, or null when not derivable from the claim signals + * @param target the raw X-Amz-Target header value, or null when absent + */ +public record ProtocolClaim(WireProtocol protocol, ServiceDescriptor service, String operation, String target) { + + static ProtocolClaim rest() { + return new ProtocolClaim(WireProtocol.REST, null, null, null); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaimer.java b/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaimer.java new file mode 100644 index 0000000000..6e4e508bb2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ProtocolClaimer.java @@ -0,0 +1,158 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Locale; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Identifies the wire protocol of an inbound request per the Smithy + * wire-protocol-selection guide: protocols are checked in precision order + * (rpcv2Cbor, rpcv2Json, awsJson1_0, awsJson1_1, awsQuery, then REST) and the + * first protocol whose "identification for claiming" signals match claims the + * request. + *

+ * Claiming uses non-payload signals only (method, path, headers) so it is safe + * to run in a pre-matching filter without touching the entity stream. As a + * consequence the awsQuery claim is narrowed to POST {@code /} with the form + * content type; the spec's body-level {@code Action}/{@code Version} checks + * stay downstream in {@code AwsQueryController}, which already rejects a + * missing {@code Action} with the AWS {@code MissingAction} error. Nothing + * below awsQuery in the precision order claims such requests, so the narrowed + * claim is decision-equivalent. + *

+ * An empty result means the request carries an RPC signal that no supported + * protocol claims — per the guide such input must be rejected (enforced only + * when {@code floci.protocols.strict-claiming} is enabled). + *

+ * Intentional deviation from pure precedence iteration: a present + * Smithy-Protocol header is treated as an exclusive rpcv2 signal. If its value + * is unknown or the method/path does not match the rpcv2 shape, the request is + * unclaimable rather than falling through to lower-precedence protocols. No + * real client sends the header accidentally, and failing loud beats silently + * serving a protocol the client did not ask for. + * + * @see Smithy wire protocol selection + */ +@ApplicationScoped +public class ProtocolClaimer { + + static final String SMITHY_PROTOCOL_HEADER = "Smithy-Protocol"; + static final String SMITHY_RPC_V2_CBOR = "rpc-v2-cbor"; + static final String SMITHY_RPC_V2_JSON = "rpc-v2-json"; + + /** + * The rpcv2 spec routes on the last four path segments, so an arbitrary + * prefix before {@code /service/{serviceName}/operation/{operationName}} + * must be tolerated. The {serviceName} segment is the Smithy service shape + * name, which for AWS services equals the X-Amz-Target prefix without its + * trailing dot. + */ + private static final Pattern RPC_V2_PATH = Pattern.compile("(?:.*/)?service/([^/]+)/operation/([^/]+)/?$"); + private static final String CONTENT_TYPE_JSON_1_0 = "application/x-amz-json-1.0"; + private static final String CONTENT_TYPE_JSON_1_1 = "application/x-amz-json-1.1"; + private static final String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"; + private static final String CONTENT_TYPE_CBOR = "application/cbor"; + private static final String CONTENT_TYPE_CBOR_1_1 = "application/x-amz-cbor-1.1"; + + private final ResolvedServiceCatalog catalog; + + @Inject + public ProtocolClaimer(ResolvedServiceCatalog catalog) { + this.catalog = catalog; + } + + public Optional claim(ClaimSignals signals) { + boolean post = "POST".equalsIgnoreCase(signals.method()); + String mediaType = baseMediaType(signals.contentType()); + String path = signals.path(); + Matcher rpcV2Path = RPC_V2_PATH.matcher(path == null ? "" : path); + boolean rpcV2PathMatches = rpcV2Path.matches(); + + String smithy = signals.smithyProtocol() == null ? null : signals.smithyProtocol().trim(); + if (smithy != null && !smithy.isEmpty()) { + if (!post || !rpcV2PathMatches) { + return Optional.empty(); + } + if (SMITHY_RPC_V2_CBOR.equals(smithy)) { + return Optional.of(rpcV2Claim(WireProtocol.RPCV2_CBOR, rpcV2Path)); + } + if (SMITHY_RPC_V2_JSON.equals(smithy)) { + return Optional.of(rpcV2Claim(WireProtocol.RPCV2_JSON, rpcV2Path)); + } + return Optional.empty(); + } + + // Header-less rpcv2Cbor carve-out: pre-header SDK releases and existing + // clients post CBOR to the rpcv2 path without the Smithy-Protocol header. + if (post && rpcV2PathMatches && isCbor(mediaType)) { + return Optional.of(rpcV2Claim(WireProtocol.RPCV2_CBOR, rpcV2Path)); + } + + if (post && isRootPath(path)) { + String target = signals.xAmzTarget(); + if (target != null) { + if (CONTENT_TYPE_JSON_1_0.equals(mediaType)) { + return Optional.of(targetClaim(WireProtocol.AWS_JSON_1_0, target)); + } + if (CONTENT_TYPE_JSON_1_1.equals(mediaType)) { + return Optional.of(targetClaim(WireProtocol.AWS_JSON_1_1, target)); + } + if (isCbor(mediaType)) { + return Optional.of(targetClaim(WireProtocol.AWS_CBOR_TARGET, target)); + } + return Optional.empty(); + } + if (CONTENT_TYPE_FORM_URLENCODED.equals(mediaType)) { + ServiceDescriptor service = SigV4CredentialScope.serviceName(signals.authorization()) + .flatMap(catalog::byCredentialScope) + .orElse(null); + return Optional.of(new ProtocolClaim(WireProtocol.AWS_QUERY, service, null, null)); + } + } + + return Optional.of(ProtocolClaim.rest()); + } + + private ProtocolClaim rpcV2Claim(WireProtocol protocol, Matcher rpcV2Path) { + String serviceName = rpcV2Path.group(1); + String operation = rpcV2Path.group(2); + ServiceDescriptor service = catalog.byCborSdkServiceId(serviceName).orElse(null); + return new ProtocolClaim(protocol, service, operation, null); + } + + private ProtocolClaim targetClaim(WireProtocol protocol, String target) { + return catalog.matchTarget(target) + .map(match -> new ProtocolClaim(protocol, match.descriptor(), match.action(), target)) + .orElseGet(() -> new ProtocolClaim(protocol, null, null, target)); + } + + static boolean isRpcV2Path(String path) { + return path != null && RPC_V2_PATH.matcher(path).matches(); + } + + private static boolean isRootPath(String path) { + return path == null || path.isEmpty() || "/".equals(path); + } + + private static boolean isCbor(String mediaType) { + return CONTENT_TYPE_CBOR.equals(mediaType) || CONTENT_TYPE_CBOR_1_1.equals(mediaType); + } + + /** + * Normalizes a Content-Type header to its lowercase base type, dropping + * media-type parameters such as {@code ; charset=utf-8}. Works on the raw + * header string because malformed values must not throw during claiming. + */ + private static String baseMediaType(String contentType) { + if (contentType == null) { + return null; + } + int paramsStart = contentType.indexOf(';'); + String base = paramsStart >= 0 ? contentType.substring(0, paramsStart) : contentType; + return base.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java index 3ae242fd1f..92cac8deee 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCatalog.java @@ -48,6 +48,15 @@ public class ServiceCatalog { } for (String prefix : descriptor.targetPrefixes()) { targets.add(Map.entry(prefix, descriptor)); + // The smithy-rpc-v2 request path is /service/{serviceName}/operation/{op}, + // where {serviceName} is the Smithy service shape name — for AWS services + // this equals the X-Amz-Target prefix without its trailing dot (verified + // against aws-sdk-java-v2 SmithyRpcV2CborProtocolProcessor and live + // CloudWatch traffic). Explicit cborSdkServiceIds take precedence. + String rpcV2ServiceName = prefix.endsWith(".") + ? prefix.substring(0, prefix.length() - 1) + : prefix; + cborSdkServiceIds.putIfAbsent(rpcV2ServiceName, descriptor); } } targets.sort(Comparator.comparingInt((Map.Entry entry) -> entry.getKey().length()) diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java index 4ccd4617b7..d700d12876 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java @@ -11,15 +11,10 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - @Provider public class ServiceEnabledFilter implements ContainerRequestFilter { private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); - private static final Pattern AUTH_SERVICE_PATTERN = - Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/"); @Context ResourceInfo resourceInfo; @@ -45,13 +40,16 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { } private ResolvedRequest resolveService(ContainerRequestContext ctx) { - String target = ctx.getHeaderString("X-Amz-Target"); - if (target != null) { - return catalog.byTarget(target) - .map(descriptor -> new ResolvedRequest( - descriptor.externalKey(), - inferProtocol(ctx).orElse(ServiceProtocol.JSON))) - .orElse(null); + ProtocolClaim claim = (ProtocolClaim) ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY); + if (claim != null && claim.service() != null) { + return new ResolvedRequest(claim.service().externalKey(), protocolFor(claim, claim.service())); + } + // A claimed RPC request whose service is unknown (unmatched X-Amz-Target + // or rpcv2 service name) stays unresolved so the protocol controllers + // keep producing their own not-found responses. + if (claim != null && claim.protocol() != WireProtocol.REST + && claim.protocol() != WireProtocol.AWS_QUERY) { + return null; } var resourceMatch = catalog.byResourceClass(resourceClass()); @@ -60,45 +58,24 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { return new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol()); } - String auth = ctx.getHeaderString("Authorization"); - if (auth != null) { - Matcher m = AUTH_SERVICE_PATTERN.matcher(auth); - if (m.find()) { - return catalog.byCredentialScope(m.group(1).toLowerCase()) - .map(descriptor -> new ResolvedRequest( - descriptor.externalKey(), - inferProtocol(ctx).orElse(descriptor.defaultProtocol()))) - .orElse(null); - } - } + return SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization")) + .flatMap(catalog::byCredentialScope) + .map(descriptor -> new ResolvedRequest( + descriptor.externalKey(), protocolFor(claim, descriptor))) + .orElse(null); + } - return null; + private ServiceProtocol protocolFor(ProtocolClaim claim, ServiceDescriptor descriptor) { + if (claim != null && claim.protocol().legacy() != null) { + return claim.protocol().legacy(); + } + return descriptor.defaultProtocol(); } private Class resourceClass() { return resourceInfo != null ? resourceInfo.getResourceClass() : null; } - private java.util.Optional inferProtocol(ContainerRequestContext ctx) { - // Use the raw header string to avoid IllegalArgumentException when Content-Type is empty. - String contentType = ctx.getHeaderString("Content-Type"); - if (contentType == null) contentType = ""; - if (contentType.contains("cbor")) { - return java.util.Optional.of(ServiceProtocol.CBOR); - } - if (contentType.contains("x-www-form-urlencoded")) { - return java.util.Optional.of(ServiceProtocol.QUERY); - } - if (ctx.getHeaderString("X-Amz-Target") != null) { - return java.util.Optional.of(ServiceProtocol.JSON); - } - String accept = ctx.getHeaderString("Accept"); - if (accept != null && accept.contains("cbor")) { - return java.util.Optional.of(ServiceProtocol.CBOR); - } - return java.util.Optional.empty(); - } - private Response disabledResponse(ResolvedRequest request) { String message = "Service " + request.serviceKey() + " is not enabled."; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java new file mode 100644 index 0000000000..f01c1d6ca0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.Locale; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Extracts the SigV4 signing service name from an Authorization header's + * credential scope ({@code Credential=////aws4_request}). + */ +final class SigV4CredentialScope { + + private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/"); + + private SigV4CredentialScope() { + } + + static Optional serviceName(String authorization) { + if (authorization == null) { + return Optional.empty(); + } + Matcher matcher = SERVICE_PATTERN.matcher(authorization); + if (matcher.find()) { + return Optional.of(matcher.group(1).toLowerCase(Locale.ROOT)); + } + return Optional.empty(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/WireProtocol.java b/src/main/java/io/github/hectorvent/floci/core/common/WireProtocol.java new file mode 100644 index 0000000000..3b906a9bae --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/WireProtocol.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.core.common; + +/** + * Concrete AWS wire protocols, declared in the Smithy wire-protocol-selection + * precision order so claiming can iterate {@link #values()} highest-first. + * Maps down to the coarser {@link ServiceProtocol} used by service descriptors, + * which does not distinguish JSON versions or rpcv2 variants. + * + * @see Smithy wire protocol selection + */ +public enum WireProtocol { + + RPCV2_CBOR(ServiceProtocol.CBOR), + RPCV2_JSON(null), + AWS_JSON_1_0(ServiceProtocol.JSON), + AWS_JSON_1_1(ServiceProtocol.JSON), + AWS_QUERY(ServiceProtocol.QUERY), + /** + * Floci extension outside the Smithy precedence list: CBOR body with + * X-Amz-Target routing at the root path, as sent by e.g. the Java SDK for + * Kinesis (application/x-amz-cbor-1.1) before rpcv2 path-based routing. + */ + AWS_CBOR_TARGET(ServiceProtocol.CBOR), + /** restJson1/restXml traffic, delegated to JAX-RS path matching. */ + REST(null); + + private final ServiceProtocol legacy; + + WireProtocol(ServiceProtocol legacy) { + this.legacy = legacy; + } + + /** The coarse descriptor-level protocol, or null when none applies. */ + public ServiceProtocol legacy() { + return legacy; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b12432d201..32e47239d7 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -159,6 +159,9 @@ floci: self-signed: true # FLOCI_TLS_SELF_SIGNED — auto-generate a self-signed cert if no cert-path provided aws-https-port: 443 # FLOCI_TLS_AWS_HTTPS_PORT — also bind 443 so CDK cfn-response/AWS-on-443 callbacks reach Floci (0 disables) + protocols: + strict-claiming: false # FLOCI_PROTOCOLS_STRICT_CLAIMING — reject RPC-signaled requests that no supported wire protocol claims + docker: log-max-size: "10m" log-max-file: "3" diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ProtocolClaimerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ProtocolClaimerIntegrationTest.java new file mode 100644 index 0000000000..c075983ced --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ProtocolClaimerIntegrationTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ProtocolClaimerIntegrationTest { + + private static final String SQS_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260702/us-east-1/sqs/aws4_request, " + + "SignedHeaders=host;x-amz-date, Signature=abc"; + + @Inject + ProtocolClaimer claimer; + + private Optional claim(String method, String path, String contentType, + String smithyProtocol, String xAmzTarget, String authorization) { + return claimer.claim(new ClaimSignals(method, path, contentType, smithyProtocol, xAmzTarget, authorization)); + } + + @Test + void smithyProtocolHeaderClaimsRpcV2CborAheadOfEverything() { + // All signals at once: the Smithy-Protocol header wins by precedence. + ProtocolClaim claim = claim("POST", "/service/DynamoDB_20120810/operation/ListTables", + "application/x-amz-json-1.1", "rpc-v2-cbor", "DynamoDB_20120810.ListTables", null).orElseThrow(); + + assertEquals(WireProtocol.RPCV2_CBOR, claim.protocol()); + assertEquals("dynamodb", claim.service().externalKey()); + assertEquals("ListTables", claim.operation()); + } + + @Test + void rpcV2PathToleratesPrefixSegments() { + ProtocolClaim claim = claim("POST", "/v1/service/Kinesis_20131202/operation/ListStreams", + "application/cbor", "rpc-v2-cbor", null, null).orElseThrow(); + + assertEquals(WireProtocol.RPCV2_CBOR, claim.protocol()); + assertEquals("kinesis", claim.service().externalKey()); + } + + @Test + void headerlessCborOnRpcV2PathStillClaims() { + ProtocolClaim claim = claim("POST", "/service/DynamoDB/operation/GetItem", + "application/cbor", null, null, null).orElseThrow(); + + assertEquals(WireProtocol.RPCV2_CBOR, claim.protocol()); + assertEquals("dynamodb", claim.service().externalKey()); + } + + @Test + void rpcV2JsonIsRecognized() { + ProtocolClaim claim = claim("POST", "/service/AmazonSQS/operation/ListQueues", + "application/json", "rpc-v2-json", null, null).orElseThrow(); + + assertEquals(WireProtocol.RPCV2_JSON, claim.protocol()); + assertEquals("sqs", claim.service().externalKey()); + } + + @Test + void malformedRpcV2SignalsAreUnclaimable() { + // Valid header value but wrong method. + assertTrue(claim("GET", "/service/DynamoDB_20120810/operation/ListTables", + null, "rpc-v2-cbor", null, null).isEmpty()); + // Valid header value but wrong path shape. + assertTrue(claim("POST", "/", "application/cbor", "rpc-v2-cbor", null, null).isEmpty()); + // Unknown header value. + assertTrue(claim("POST", "/service/DynamoDB_20120810/operation/ListTables", + "application/cbor", "rpc-v2-msgpack", null, null).isEmpty()); + // Header value comparison is exact per spec (header NAME is case-insensitive, value is not). + assertTrue(claim("POST", "/service/DynamoDB_20120810/operation/ListTables", + "application/cbor", "RPC-V2-CBOR", null, null).isEmpty()); + } + + @Test + void jsonVersionsSplitOnContentType() { + ProtocolClaim json10 = claim("POST", "/", "application/x-amz-json-1.0", + null, "DynamoDB_20120810.ListTables", null).orElseThrow(); + assertEquals(WireProtocol.AWS_JSON_1_0, json10.protocol()); + assertEquals("dynamodb", json10.service().externalKey()); + assertEquals("ListTables", json10.operation()); + + ProtocolClaim json11 = claim("POST", "/", "application/x-amz-json-1.1", + null, "AmazonSSM.DescribeParameters", null).orElseThrow(); + assertEquals(WireProtocol.AWS_JSON_1_1, json11.protocol()); + assertEquals("ssm", json11.service().externalKey()); + } + + @Test + void mediaTypeParametersAndCasingAreNormalized() { + ProtocolClaim claim = claim("POST", "/", "Application/X-Amz-Json-1.1; charset=utf-8", + null, "AmazonSSM.DescribeParameters", null).orElseThrow(); + + assertEquals(WireProtocol.AWS_JSON_1_1, claim.protocol()); + } + + @Test + void legacyCborWithTargetAtRootClaimsCborTarget() { + // Kinesis via aws-sdk-java: x-amz-cbor-1.1 + X-Amz-Target at root, no smithy header. + ProtocolClaim claim = claim("POST", "/", "application/x-amz-cbor-1.1", + null, "Kinesis_20131202.ListStreams", null).orElseThrow(); + + assertEquals(WireProtocol.AWS_CBOR_TARGET, claim.protocol()); + assertEquals("kinesis", claim.service().externalKey()); + assertEquals("ListStreams", claim.operation()); + } + + @Test + void targetWithForeignContentTypeIsUnclaimable() { + assertTrue(claim("POST", "/", "text/plain", + null, "AmazonSSM.DescribeParameters", null).isEmpty()); + } + + @Test + void unknownTargetStillClaimsProtocolWithoutService() { + ProtocolClaim claim = claim("POST", "/", "application/x-amz-json-1.1", + null, "NoSuchService.DoThing", null).orElseThrow(); + + assertEquals(WireProtocol.AWS_JSON_1_1, claim.protocol()); + assertNull(claim.service()); + assertEquals("NoSuchService.DoThing", claim.target()); + } + + @Test + void formPostAtRootClaimsQueryAndResolvesServiceFromCredentialScope() { + ProtocolClaim withAuth = claim("POST", "/", + "application/x-www-form-urlencoded; charset=utf-8", null, null, SQS_AUTH).orElseThrow(); + assertEquals(WireProtocol.AWS_QUERY, withAuth.protocol()); + assertEquals("sqs", withAuth.service().externalKey()); + + ProtocolClaim withoutAuth = claim("POST", "/", + "application/x-www-form-urlencoded", null, null, null).orElseThrow(); + assertEquals(WireProtocol.AWS_QUERY, withoutAuth.protocol()); + assertNull(withoutAuth.service()); + } + + @Test + void nonRpcTrafficFallsThroughAsRest() { + Optional get = claim("GET", "/", null, null, null, null); + assertEquals(WireProtocol.REST, get.orElseThrow().protocol()); + + Optional s3Post = claim("POST", "/my-bucket", + "multipart/form-data; boundary=x", null, null, null); + assertEquals(WireProtocol.REST, s3Post.orElseThrow().protocol()); + + Optional lambdaPath = claim("POST", "/2015-03-31/functions", + "application/json", null, null, null); + assertEquals(WireProtocol.REST, lambdaPath.orElseThrow().protocol()); + } + + @Test + void queryFormOnNonRootPathIsRest() { + // Form posts on non-root paths (e.g. before SQS queue-URL rewriting) are + // not query claims; the router filter rewrites them to "/" before this + // claimer runs in the filter chain. + ProtocolClaim claim = claim("POST", "/123456789012/my-queue", + "application/x-www-form-urlencoded", null, null, null).orElseThrow(); + + assertEquals(WireProtocol.REST, claim.protocol()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java index eb8d4cb585..b32e8ce80b 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java @@ -37,6 +37,18 @@ class ServiceCatalogRoutingIntegrationTest { assertEquals("monitoring", catalog.byCborSdkServiceId("GraniteServiceVersion20100801").orElseThrow().externalKey()); } + @Test + void rpcV2ServiceNamesDeriveFromTargetPrefixes() { + // The smithy-rpc-v2 path segment is the service shape name == target prefix + // without the trailing dot (what the AWS SDKs actually send on the wire). + assertEquals("dynamodb", catalog.byCborSdkServiceId("DynamoDB_20120810").orElseThrow().externalKey()); + assertEquals("dynamodb", catalog.byCborSdkServiceId("DynamoDBStreams_20120810").orElseThrow().externalKey()); + assertEquals("kinesis", catalog.byCborSdkServiceId("Kinesis_20131202").orElseThrow().externalKey()); + assertEquals("sqs", catalog.byCborSdkServiceId("AmazonSQS").orElseThrow().externalKey()); + assertEquals("sns", catalog.byCborSdkServiceId("SNS_20100331").orElseThrow().externalKey()); + assertEquals("states", catalog.byCborSdkServiceId("AWSStepFunctions").orElseThrow().externalKey()); + } + @Test void queryProtocolAliasesAreDeclaredOnDescriptors() { assertTrue(catalog.byCredentialScope("sesv2").orElseThrow().supportsProtocol(ServiceProtocol.QUERY)); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SmithyRpcV2RoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SmithyRpcV2RoutingIntegrationTest.java new file mode 100644 index 0000000000..e1204973c1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/SmithyRpcV2RoutingIntegrationTest.java @@ -0,0 +1,189 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Exercises the smithy-rpc-v2-cbor wire format exactly as the AWS SDKs send it: + * POST /service/{serviceShapeName}/operation/{operation} where the service name + * segment is the X-Amz-Target prefix without its trailing dot (e.g. + * DynamoDB_20120810, Kinesis_20131202, GraniteServiceVersion20100801), with the + * smithy-protocol request header and a generic application/cbor content type. + * Also covers the sibling legacy format (x-amz-cbor-1.1 + X-Amz-Target at the + * root path) and content-type normalization during protocol transitions. + * Captured from aws-sdk-java 2.46.7 — see local/plan/smithy/captured/SUMMARY.md. + */ +@QuarkusTest +class SmithyRpcV2RoutingIntegrationTest { + + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void dynamoDbRoutesViaTargetPrefixServiceName() throws Exception { + JsonNode createRequest = JSON_MAPPER.readTree(""" + { + "TableName": "RpcV2WireTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1} + } + """); + + byte[] created = given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(createRequest)) + .when() + .post("/service/DynamoDB_20120810/operation/CreateTable") + .then() + .statusCode(200) + .header("smithy-protocol", equalTo("rpc-v2-cbor")) + .contentType("application/cbor") + .extract().asByteArray(); + + assertThat(CBOR_MAPPER.readTree(created) + .path("TableDescription").path("TableName").asText(), equalTo("RpcV2WireTable")); + + given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.readTree(""" + {"TableName": "RpcV2WireTable"} + """))) + .when() + .post("/service/DynamoDB_20120810/operation/DeleteTable") + .then() + .statusCode(200); + } + + @Test + void kinesisRoutesViaTargetPrefixServiceName() throws Exception { + byte[] response = given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/service/Kinesis_20131202/operation/ListStreams") + .then() + .statusCode(200) + .header("smithy-protocol", equalTo("rpc-v2-cbor")) + .contentType("application/cbor") + .extract().asByteArray(); + + assertThat(CBOR_MAPPER.readTree(response).path("StreamNames"), notNullValue()); + } + + @Test + void cloudWatchRoutesViaGraniteServiceName() throws Exception { + byte[] response = given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/service/GraniteServiceVersion20100801/operation/ListMetrics") + .then() + .statusCode(200) + .header("smithy-protocol", equalTo("rpc-v2-cbor")) + .contentType("application/cbor") + .extract().asByteArray(); + + assertThat(CBOR_MAPPER.readTree(response).path("Metrics"), notNullValue()); + } + + @Test + void unknownServiceNameReturns404() throws Exception { + given() + .contentType("application/cbor") + .accept("application/cbor") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/service/NoSuchService/operation/DoThing") + .then() + .statusCode(404); + } + + @Test + void legacyCborTargetAtRootEchoesAmzCborContentType() throws Exception { + // The live Kinesis format from aws-sdk-java: x-amz-cbor-1.1 body with + // X-Amz-Target at the root path, no smithy-protocol request header. + byte[] response = given() + .contentType("application/x-amz-cbor-1.1") + .header("X-Amz-Target", "Kinesis_20131202.ListStreams") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/x-amz-cbor-1.1") + .extract().asByteArray(); + + assertThat(CBOR_MAPPER.readTree(response).path("StreamNames"), notNullValue()); + } + + @Test + void smithyProtocolHeaderNormalizesDriftedContentType() throws Exception { + // A rpcv2Cbor request whose Content-Type drifted away from application/cbor + // must still route: the smithy-protocol header is the definitive claim + // signal and AwsCborContentTypeFilter normalizes the media type for it. + given() + .contentType("application/octet-stream") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/service/Kinesis_20131202/operation/ListStreams") + .then() + .statusCode(200) + .header("smithy-protocol", equalTo("rpc-v2-cbor")); + } + + @Test + void straySmithyHeaderOutsideRpcV2PathDoesNotRewriteContentType() { + // A Smithy-Protocol header on a non-rpcv2 path must not trigger content + // type normalization: later filters (e.g. S3VirtualHostFilter) rely on + // seeing the original management content type, and the request must + // still reach its normal JSON controller. + given() + .contentType("application/x-amz-json-1.1") + .header("Smithy-Protocol", "rpc-v2-cbor") + .header("X-Amz-Target", "AmazonSSM.DescribeParameters") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void amzCbor11OnRpcV2PathEchoesOriginalContentType() throws Exception { + given() + .contentType("application/x-amz-cbor-1.1") + .header("smithy-protocol", "rpc-v2-cbor") + .body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.createObjectNode())) + .when() + .post("/service/Kinesis_20131202/operation/ListStreams") + .then() + .statusCode(200) + .contentType("application/x-amz-cbor-1.1"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/StrictProtocolClaimingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/StrictProtocolClaimingIntegrationTest.java new file mode 100644 index 0000000000..e6244f2550 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/StrictProtocolClaimingIntegrationTest.java @@ -0,0 +1,110 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +/** + * Verifies the floci.protocols.strict-claiming enforcement: RPC-signaled + * requests that no supported wire protocol claims are rejected per the Smithy + * wire-protocol-selection guide, while REST and well-formed RPC traffic is + * untouched. + */ +@QuarkusTest +@TestProfile(StrictProtocolClaimingIntegrationTest.StrictClaimingProfile.class) +class StrictProtocolClaimingIntegrationTest { + + public static final class StrictClaimingProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.protocols.strict-claiming", "true"); + } + } + + @BeforeAll + static void configureContentTypes() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void rpcV2JsonIsRecognizedAndRejected() { + given() + .contentType("application/json") + .header("Smithy-Protocol", "rpc-v2-json") + .body("{}") + .when() + .post("/service/AmazonSQS/operation/ListQueues") + .then() + .statusCode(400) + .header("x-amzn-query-error", equalTo("UnknownOperationException;Sender")) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void unknownSmithyProtocolValueIsRejected() { + given() + .contentType("application/cbor") + .header("Smithy-Protocol", "rpc-v2-msgpack") + .body(new byte[]{(byte) 0xbf, (byte) 0xff}) + .when() + .post("/service/DynamoDB_20120810/operation/ListTables") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void targetPostWithForeignContentTypeIsRejected() { + given() + .contentType("text/plain") + .header("X-Amz-Target", "AmazonSSM.DescribeParameters") + .body("{}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + @Test + void wellFormedRpcTrafficIsUnaffected() { + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AmazonSSM.DescribeParameters") + .body("{}") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void restTrafficIsUnaffected() { + // S3 list-buckets at root bypasses claiming enforcement. + given() + .when() + .get("/") + .then() + .statusCode(200); + + // A POST on a REST path reaches its normal handler (here S3's + // /{bucket}/{key} catch-all) instead of the claimer's rejection, + // which would carry the x-amzn-query-error header. + given() + .contentType("application/json") + .body("{}") + .when() + .post("/no/such/rest/path") + .then() + .header("x-amzn-query-error", nullValue()); + } +} \ No newline at end of file diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbCborIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbCborIntegrationTest.java index 89ce49ab0e..03b9d6bdbd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbCborIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbCborIntegrationTest.java @@ -15,8 +15,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** - * Tests the smithy-rpc-v2-cbor protocol for DynamoDB. - * AWS SDK v2 sends DynamoDB requests as CBOR to /service/DynamoDB/operation/{op}. + * Tests the smithy-rpc-v2-cbor protocol for DynamoDB using the legacy + * /service/DynamoDB/... alias. The AWS SDKs actually send the service shape + * name (the target prefix without its trailing dot, i.e. DynamoDB_20120810) — + * that wire format is covered by SmithyRpcV2RoutingIntegrationTest; this alias + * remains supported via the explicit cborSdkServiceIds declaration. */ @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) 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 4fc6bbde6b..114909c29e 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,6 +322,8 @@ class EventBridgeSchedulerIntegrationTest { @Override public EmulatorConfig.InitHooksConfig initHooks() { return null; } @Override + public ProtocolsConfig protocols() { return () -> false; } + @Override public TlsConfig tls() { return new TlsConfig() { @Override public boolean enabled() { return false; } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index d9847fb5a9..3601e217af 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -72,6 +72,9 @@ floci: enabled: false self-signed: true + protocols: + strict-claiming: false + docker: log-max-size: "10m" log-max-file: "3"