mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(core): claim wire protocols reactively per Smithy selection guide (#1712)
* feat(core): claim wire protocols reactively per Smithy selection guide AWS services will adopt additional wire protocols without advance notice starting April 2026, so the protocol must be identified per request rather than assumed per service. Adds a ProtocolClaimer that claims each request from its non-payload signals (Smithy-Protocol header, content type, X-Amz-Target, method, path) in Smithy precision order, exposed to downstream filters by a pre-matching claim filter and consumed by the service-enablement filter in place of its duplicated sniffing. Also fixes smithy-rpc-v2 path routing: the service segment AWS SDKs send is the target prefix (Kinesis_20131202, DynamoDB_20120810, ...), not the SDK serviceId, so rpcv2 service names are now derived from the catalog's target prefixes and the path-based CBOR dispatcher gains the missing Kinesis case. Opt-in strict mode (FLOCI_PROTOCOLS_STRICT_CLAIMING) rejects RPC-signaled requests that no supported protocol claims, including the recognized but unimplemented rpc-v2-json. Default wire behavior is unchanged. Refs #156 * fix(core): scope Smithy-Protocol content-type normalization to rpcv2 paths The normalization filter runs before the path-rewriting filters, so rewriting Content-Type on arbitrary paths erased the signal filters like S3VirtualHostFilter use to bypass non-S3 management traffic. Only normalize POST requests whose path matches the rpcv2 shape — the only requests the rpcv2Cbor claim can succeed for.
This commit is contained in:
1 parent
ac96a7d292
commit
38bf55d323
21 files changed
+946
-73
No files matched your search
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
* <p>
|
||||
* 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;
|
||||
|
||||
@@ -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.
|
||||
* <p>
|
||||
* 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<EmulatorConfig> configProvider;
|
||||
|
||||
@Inject
|
||||
public AwsProtocolClaimFilter(ProtocolClaimer claimer, jakarta.inject.Provider<EmulatorConfig> configProvider) {
|
||||
this.claimer = claimer;
|
||||
this.configProvider = configProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
ClaimSignals signals = ClaimSignals.from(ctx);
|
||||
Optional<ProtocolClaim> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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);
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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).
|
||||
* <p>
|
||||
* 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 <a href="https://smithy.io/2.0/guides/wire-protocol-selection.html">Smithy wire protocol selection</a>
|
||||
*/
|
||||
@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<ProtocolClaim> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, ServiceDescriptor> entry) -> entry.getKey().length())
|
||||
|
||||
@@ -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<ServiceProtocol> 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.";
|
||||
|
||||
|
||||
@@ -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=<key>/<date>/<region>/<service>/aws4_request}).
|
||||
*/
|
||||
final class SigV4CredentialScope {
|
||||
|
||||
private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
|
||||
private SigV4CredentialScope() {
|
||||
}
|
||||
|
||||
static Optional<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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 <a href="https://smithy.io/2.0/guides/wire-protocol-selection.html">Smithy wire protocol selection</a>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user