Commit Graph
57 Commits
Author SHA1 Message Date
Andre Kurait 4b3681eb90 fix(apigateway): preserve API ownership across integration invocations (#6001)
Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-10-19 19:58:19 -04:00
Alessandro Lattao 28799ed352 fix(apigatewayv2): answer an HTTP API's Lambda proxy body it cannot read with 500 (#6012)
* fix(apigatewayv2): answer an HTTP API's Lambda proxy body it cannot read with 500

Review of #5985: the catch at the end of buildProxyResponse still
answered an HTTP API with 502 and the function's output, for example
when isBase64Encoded is set on a body that is not base64.

Measured on HTTP APIs (eu-west-1), with payload formats 1.0 and 2.0:
API Gateway answers 500 with {"message":"Internal Server Error"} a body
that is an object or a list, an isBase64Encoded it cannot read as a
boolean, and a body said to be base64 that does not decode. It reads
isBase64Encoded's text as Go's strconv.ParseBool does: "True", "TRUE",
"t" and 1 are true, "F" and 0 false, and "tRuE", "yes", 2 and 1.5 are
not read. Floci read true, the text "true" and any integer but 0 as
true, so it relayed "True" and "t" bodies undecoded, "yes" ones as
plain text, decoded a body under 2, and answered an object body 200
with an empty body. A number or a boolean body is still its text.

The catch now answers an HTTP API with the same 500 for a result Floci
cannot parse at all; a REST API keeps its 502.

* refactor(apigatewayv2): decode an HTTP API's base64 body once

Review of #6012: the readability check decoded a base64 body that the
response then decoded again, a second decode and array for every
encoded reply. The catch at the end of buildProxyResponse already
answers an HTTP API with 500 and the generic message, so the check now
looks only at the body's shape, and a body said to be base64 that does
not decode fails where it is decoded and reaches that catch.
2026-10-19 16:40:26 -04:00
Alessandro Lattao 49d2d74f3f fix(apigatewayv2): answer the Lambda proxy results an HTTP API cannot read with 500 (#5985)
* fix(apigatewayv2): answer the Lambda proxy results an HTTP API cannot read with 500

Measured on HTTP APIs (eu-west-1), with payload formats 1.0 and 2.0:
a function that raises is answered 500 with {"message":"Internal Server
Error"}, not the 502 Floci sent. The same 500 answers what API Gateway
cannot read as a response: in format 1.0 a result that is not an object
with a statusCode (a result without one, a string, a number, null), and
in either format a statusCode that is not a whole number from 100 to 599
(99, 600, 201.5, "abc"); a statusCode given as text that spells one,
"201", is taken, and headers that are not an object are left out.
Format 2.0 keeps inferring a 200 for a result without a statusCode.

Floci answered a format 1.0 result without a statusCode with 200 and
its headers and body, as HttpApiLambdaProxyResponseInferenceIntegrationTest
pinned since #5153; AWS answers 500, and that test and the unit tests
that pinned 502 now expect what AWS answers. A REST API's Lambda proxy
keeps its own 502, untouched.

The HTTP API's generic error responses come from one helper, which the
invocation failures from #5935 (500, or 503 when Lambda throttles) use
too.

* test(compat): skip the HTTP API proxy cases unless the API reaches Lambda

Review of #5985: the test checked only that Lambda can be invoked, not
that API Gateway dispatches to it. It now sends a readable result through
the API first, as ApiGatewayV2ExecuteTest does, and skips the cases when
that does not come back.
2026-10-19 09:18:20 -04:00
Alessandro Lattao dd832b45dc fix(apigatewayv2): apply an HTTP API's CORS configuration to its actual responses (#5935)
* fix(apigatewayv2): apply an HTTP API's CORS configuration to its actual responses

An HTTP API with a CorsConfiguration answered the preflight from it, but the
responses of its integrations went out with no Access-Control-Allow-Origin, so
a browser refused to hand the page any answer of the API. AWS documents both
halves ("Configuring CORS for an HTTP API"): for a CORS request API Gateway
adds the configured headers to the integration's response, and once an API
has a CORS configuration it ignores the CORS headers the integration returns.

Measured on HTTP APIs (eu-west-1, 2026-10-16 and 2026-10-18):
- API Gateway's own refusals on a matched route get the same headers: a JWT
  authorizer's 401 and its 403 for a missing scope, an unsigned call to an
  AWS_IAM route's 403, a Lambda authorizer's 401 (no identity) and 403
  (isAuthorized false); so does a function that is gone, which answers 500
  Internal Server Error (Floci answered 404 "Function not found" without
  them).
- A preflight a route matches (an OPTIONS or ANY route, $default) goes
  through that route, its authorizer and its integration, and gets the
  preflight headers on whatever answers; only a preflight no route matches
  is answered 204 by API Gateway. Floci answered every preflight itself, so
  a route behind an authorizer looked open to a browser's preflight.
- A preflight gets the preflight headers only when its origin, its method
  and every header it asks for are allowed, and never the exposed headers;
  otherwise, or for an OPTIONS without Access-Control-Request-Method, no CORS
  header at all. An actual request gets them whatever its method. Lists are
  joined with a bare comma.
- A preflight that gets the headers always carries
  Access-Control-Allow-Headers, empty when none are configured, and
  Vary: origin unless AllowOrigins is a single exact origin or "*" (two
  origins, the "https://*" prefix, and "*" beside an exact origin all
  vary). No other response gets a Vary; an integration's own is kept.
  Floci sent no Allow-Headers when none were configured, and Vary: Origin
  on every preflight that echoed the origin.
- A route without a target answers 404 Not Found with no CORS header, as an
  unmatched route does (Floci answered 500).

The configuration is now applied once, by withHttpApiCors, on whatever the
matched route answers, so no response path can miss it: it drops the six
headers the configuration owns from the response and, when the Origin is
allowed (exactly, by "*", or by a prefix wildcard such as https://*), adds
Access-Control-Allow-Origin, plus Credentials and Expose-Headers when
configured, or the preflight's set for a preflight. An API without a
configuration still leaves CORS to its integrations.

Tests: ApiGatewayExecuteControllerTest for the headers withHttpApiCors
sets and when a preflight varies, HttpApiCorsIntegrationTest for the
routing, the refusals and the custom domain;
HttpApiJwtAuthorizerScopesTest and HttpApiRequestAuthorizerTest for the
measured refusals of a JWT scope and of a Lambda authorizer, on their own
fixtures; ApiGatewayV2CorsTest in sdk-test-java for the refusals, an
unmatched preflight and a two-origin API's Vary through the SDK;
ApiGatewayV2UnsignedAccountRoutingTest now tells a route found in its
account by AWS's 500 instead of Floci's "Function not found".

* fix(apigatewayv2): answer a failed invocation with API Gateway's own status and CORS headers

Review of #5935 (Qodo). Measured on an HTTP API with a CORS configuration
(eu-west-1, 2026-10-18), with an allowed Origin:
- a Lambda integration API Gateway may not invoke, and a function that
  raises, answer 500 {"message":"Internal Server Error"}; a function Lambda
  throttles (reserved concurrency 0) answers 503 {"message":"Service
  Unavailable"}; each carries Access-Control-Allow-Origin and
  Access-Control-Expose-Headers;
- an OPTIONS request no route matches is answered 204 with no CORS header
  whether or not it carries Origin or Access-Control-Request-Method, so the
  unmatched OPTIONS answer stays as it is, now pinned by a test.

Any AwsException from the invocation now becomes API Gateway's answer
inside the matched route, so the CORS configuration reaches it: 503 for
Lambda's throttling, 500 otherwise. Only the function that is gone did
before; the others escaped to the exception mapper without the headers.

A configured list with a null entry no longer fails a preflight: the
entry matches nothing and is left out of the header.

Tests: HttpApiCorsIntegrationTest gains a throttled function's 503 and an
unmatched OPTIONS that is not a preflight, ApiGatewayExecuteControllerTest
a null entry, and ApiGatewayV2CorsTest in sdk-test-java both new cases
through the SDK; the throttled and null cases fail on the previous head.

* test(apigatewayv2): share the HTTP_PROXY API fixture and the Lambda zip helper

Review of #5935. HttpApiCorsIntegrationTest.createProxyApi repeated the
API, stage, HTTP_PROXY integration and route sequence of
HttpApiHttpProxyMultiValueIntegrationTest.createProxyApi: both now call
HttpProxyApiFixtures.createProxyApi, which takes the API's extra fields,
the stage, the backend port and the path. The stage is auto-deployed for
both, as an API needs to be served on AWS.

The throttled function is a Node.js one built with
WebSocketTestSupport.createLambdaZip; it never runs, so its runtime does
not matter.
2026-10-18 12:05:07 -04:00
Alessandro Lattao a90482f030 fix(apigatewayv2): trust Floci's own CA when fetching a JWT issuer's keys (#5933)
With TLS on, an issuer Floci serves itself, a Floci Cognito user pool for
one, presents a certificate of Floci's local CA. The JWT verifier fetched
its discovery document and JWKS with the JVM's default trust store, which
does not hold that CA, so every token of a Floci pool was refused with 401
by an HTTP API JWT authorizer (and by an AppSync OIDC provider), where the
same authorizer on a Cognito pool verifies on AWS.
FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS only lets the fetch reach the
private address; the handshake still failed.

The verifier now trusts the CA bundle Floci already writes for the
containers it launches: the JVM's roots followed by Floci's own trust
anchor (the local CA, or the user's certificate file). ContainerCaBundle
gains sslContext(), an SSL context over that bundle, empty when TLS is off
or the bundle cannot be read, in which case the JVM's roots alone are
trusted as before. A readable bundle with no certificate in it is refused
the same way, since a trust store over it would trust nothing, public
issuers included. The warning for a missing bundle now also says that JWT
authorizers will refuse an issuer Floci serves.

The TLS server context of a certificate this CA issues moves from the RDS
proxy into FlociCertificateAuthority.serverSslContext, so the proxy and
the test that serves an issuer over HTTPS build it one way.

Tests: JwtSignatureVerifierTest serves an issuer over HTTPS with a
certificate Floci's CA issues, the bundle written by ContainerCaBundle and
the verifier built through its injected constructor, as in production:
refused by the JVM's roots, verified with the bundle (it fails on main).
ContainerCaBundleTest pins that the bundle's context still trusts every
JVM root and the anchor, and that an empty bundle falls back.
OidcAuthValidatorTest's mocked config now answers tls().
2026-10-18 09:46:40 -04:00
TATSUNO “Taz” Yasuhiro 4f4db89d8f fix(apigateway): refuse a long-term access key sent with a session token (#5875)
* fix(apigateway): refuse a long-term access key sent with a session token

AWS answers 403 "The security token included in the request is invalid"
when a long-term key comes with X-Amz-Security-Token, signed or not. The
same message without the period answers a temporary key with a wrong token.

The session token check moves to core.common.auth, and Lambda Web IamAuth
uses it too.

Closes #5858

* fix(apigateway): read the session token where the signature is and refuse an empty one

AWS ignores a token in the query of a header-signed request and a token
header on a presigned one. It refuses an empty token with any key.
2026-10-17 09:30:35 -04:00
Andre Kurait 5a72b4f561 fix(apigateway): validate imported models in their deployment context (#5645)
* fix(apigateway): resolve imported request model references

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): snapshot request model schemas for deployments

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): match the default body validation error

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(apigateway): expect the AWS default validation message

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): address model snapshot review findings

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): resolve model URLs from deployment snapshots

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(apigateway): make model reference cases collectable

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): accept canonical model URLs in every partition

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-10-15 06:50:46 -04:00
Andre Kurait 63e0302c12 fix(apigateway): validate and normalize imported integration types (#5543)
Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-10-13 23:48:12 -04:00
vamsiakandVamsi Akavarapu 1acedaf068 feat(apigateway): export deployed REST APIs as OpenAPI (#5131)
* feat(apigateway): export deployed REST APIs as OpenAPI

* fix(apigateway): reject lossy export round trips

* fix(apigateway): preserve native export round trips

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
2026-10-13 16:40:50 -04:00
Alessandro Lattao 85e0061a6f feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping (#5038)
* refactor(apigateway): move the v2 domain and API mapping rules into the service

CreateDomainName and CreateApiMapping on /v2/domainnames kept their rules in
ApiGatewayController: the one-configuration check, the refusal of inputs Floci
does not emulate, the flattening onto the shared custom-domain store, the API
and stage existence check, the mapping key conflict check, the API type the
mapping is routed as, and the mapping id. A CloudFormation provisioner cannot
reach a controller, so it would have had to copy them.

They now live in ApiGatewayService. createV2DomainName validates the body and
creates the domain; createApiMapping checks the API and stage, refuses a key
that is taken and routes the mapping as the API's protocol type; getApiMapping,
deleteApiMapping and apiMappingId follow. ApiGatewayService takes
ApiGatewayV2Service for the API and stage lookup, so the whole rule sits in one
place and a caller needs one service. Nothing on the v2 side depends on the v1
service, so this adds no cycle. Leaving the lookup in ApiGatewayV2Service was
tried first, but then every caller had to resolve the API before calling into
ApiGatewayService, and the rule was split across two classes again.

The code is moved, not rewritten: messages, error codes, the order of the
checks and the id scheme are unchanged, and the controller delegates.

* feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping

Both types were left to the stub arm. A stack reported CREATE_COMPLETE, but no
domain or mapping existed, Fn::GetAtt on the domain resolved to literals such
as DomainResource.RegionalDomainName (so a Route 53 alias built from it pointed
nowhere), and with allow-stub-unsupported-resource-types off the stack rolled
back.

ApiGatewayV2DomainCfnProvisioner creates them through the v2 rules in
ApiGatewayService and injects only that service. Ref on a domain is its name
and Fn::GetAtt returns DomainNameArn, RegionalDomainName and
RegionalHostedZoneId as GetDomainName reports them. Ref on a mapping is its
ApiMappingId, which is also its only attribute.

Updates follow AWS. DomainName is the only createOnly property of either type,
and everything else changes in place: the domain's configuration is replaced as
a whole, as DomainNameConfigurations is on AWS, and a mapping's ApiId, Stage and
ApiMappingKey change without a new id. To keep the id across a key change, a
mapping now stores the apiMappingId it was given instead of deriving it from
its key on every read. A record persisted before is still read under the
derived id, and a new mapping gets the id it always had unless another mapping
holds it. Deriving the id and documenting the difference was the first version;
it was dropped because Ref changed where AWS keeps it, and the change set
already reported the key change as an update.

A replacement creates the new entity and leaves the displaced one to
ReplacementCleanup, so it is deleted in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS,
kept under UpdateReplacePolicy: Retain, and put back when a later resource
fails the update. The first version deleted the old domain inside provision, as
the v1 provisioner does, and a failed rename then ended in
UPDATE_ROLLBACK_FAILED with the original domain and its mappings already gone.
A mapping moved to another domain gets an id the displaced mapping does not
hold, since two mappings under one physical id cannot be told apart, and the
domain of each displaced id is recorded beside the cleanup. An in-place update
snapshots what it changes, so a failed stack update restores it instead of
ending in UPDATE_ROLLBACK_FAILED.

CDK templates needed the v2 rules to match AWS in two more places.
apigateway.DomainName with a multi-level basePath maps a REST API through
AWS::ApiGatewayV2::ApiMapping, so a mapping now accepts a REST API stage. And
the restrictions AWS documents for API mappings are enforced, in the API and in
templates alike: no v2 call on an edge-optimized domain, with AWS's message;
TLS_1_2 for an HTTP API or a multi-level key, which also keeps such a domain on
TLS_1_2; no WebSocket API beside an HTTP or REST API; and AWS's key characters
and length.

The id-only delete accepts <ApiMappingId>|<DomainName>, the type's primary
identifier, which is how Cloud Control names a mapping; a bare id still answers
NotFoundException, so Cloud Control cannot report a delete that did not happen.
The integration test deploys two templates aws-cdk-lib 2.272.0 synthesized,
checked in with the app that produced them, and compat-cdk deploys the same
shapes.

* fix(apigateway): answer v2 domain and API mapping calls as API Gateway does

The review of this PR found four places where Floci answered differently
from API Gateway. Each was measured against API Gateway in eu-west-1 on
2026-10-04, with an imported certificate on a throwaway domain.

An HTTP API custom domain is regional. CreateDomainName and
UpdateDomainName with an endpoint type of PRIVATE, or one API Gateway does
not know, give a REGIONAL domain, where Floci refused the first and stored
the type on an update. EDGE is refused with "EDGE endpoint type is not
supported for APIGatewayV2 domainName", not the message for v2 calls on an
existing edge-optimized domain.

API mapping keys are checked as API Gateway checks them, with its messages:
a key does not end with '/', does not start with '/' or hold '//', holds
letters, digits and $-_.+!*'(), between its levels, and is at most 300
characters. No key, an empty one, or on a create one of whitespace only, is
the root; an update refuses whitespace only. Floci took "/" for the root and
had its own message for the characters, without the comma.

UpdateApiMapping and UpdateDomainName answer over the v2 HTTP API, not only
from CloudFormation. What an UpdateApiMapping leaves out keeps its value.

Cloud Control identifies an AWS::ApiGatewayV2::ApiMapping by the type's
primary identifier, <ApiMappingId>|<DomainName>, while CloudFormation's Ref
stays the bare id: CloudControlService derives the identifier from the
desired state, as it already names primary identifier fields by type, and
the provisioner deletes by it with the create-time attributes too.

* fix(apigateway): refuse a v2 update of an edge domain, and recover a compound identifier whole

The second review pass found three gaps in the previous commit.

UpdateDomainName through the v2 API converted a v1-created edge-optimized
domain to REGIONAL. The v2 API does not manage an edge-optimized domain, so
the update is refused with the message every other v2 call on one gets, and
the CloudFormation in-place update goes through the same check.

A v2 UpdateDomainName without a configuration returned the domain unchanged
without looking at the rest of the body, so a mutual TLS request was
silently dropped. ApiGatewayService.updateV2DomainName now refuses what
Floci does not emulate, and the edge-optimized domain, either way.

Cloud Control's recovery of a create that finished just before a restart
took the identifier after the last '|' of its key, which for an API
mapping's <ApiMappingId>|<DomainName> left only the domain. It now takes
everything after the key's third separator.

A later review pass found four more points.
UpdateApiMapping fills in what its body leaves out under the lock the update
takes, so two partial updates of one mapping cannot write back each other's
old values. A v2 domain's certificate is stored as the v1 API's regional
certificate, which is what a regional domain reports through both APIs; a
domain the v2 API wrote before still reports the one it holds until its
configuration is replaced. The domain ARN both APIs and both CloudFormation
provisioners build comes from ApiGatewayService.domainNameArn, the Cloud
Control test waits with the awaitSuccess helper main has since gained, and
requireMappingAllowed's javadoc is back on it.
2026-10-12 11:28:04 -04:00
Aniket Shukla 04621d8444 fix(apigatewayv2): honor payload format 1.0 (#5338)
* fix(apigatewayv2): honor payload format 1.0

* fix(apigatewayv2): preserve v1 stage variables

* fix(apigatewayv2): preserve v1 authorization header

* docs(apigateway): document v1 IAM identity context
2026-10-11 09:10:07 -04:00
Hector Ventura a1f90453fb fix(apigateway): refuse EDGE REST APIs outside the commercial partition (#5397)
Edge-optimized endpoints exist only in the commercial partition.
CreateRestApi and an UpdateRestApi switch of /endpointConfiguration/types
now run the same check custom domains already use, so an EDGE REST API in
China, GovCloud, ISO or EUSC is a BadRequestException. REGIONAL APIs, and
a move away from EDGE, are still accepted everywhere.
2026-10-10 12:07:42 -04:00
Hector Ventura da53fc1c05 docs(partition): document deployment, test coverage and known gaps (#5292)
* docs(partition): document deployment, test coverage and known gaps

partitions.md said every partition-dependent rule had integration tests
over all eight partitions and that the China compat allowlist only
shrinks. Neither is accurate now: most services are tested in China
alone, and the allowlist is empty. The page now states the coverage as
it is (unit tests over every partition, IAM, Step Functions and the
cross-service smoke test through the emulator, China end to end), gives
a recipe for running a China, GovCloud, ISO or EUSC deployment, and
lists the known gaps: global state shared across partitions in one
process (now naming the Identity Center instance, which the smoke
test's inventory exempts for that reason), the commercial managed-policy
catalog, and client tooling untested outside the commercial partition.

API Gateway, IAM and Step Functions gain a Partitions section, and the
WAFv2 scope note names the partition's CloudFront region and where the
CLOUDFRONT scope exists.

* docs(partition): say only custom domains refuse EDGE, and when FLOCI_HOSTNAME is enough

The API Gateway Partitions section said EDGE was refused outside the
commercial partition and that REGIONAL and PRIVATE worked everywhere.
Only custom domains are checked: createRestApi and the REST API update
path accept EDGE in any partition, and createDomainName refuses PRIVATE
in all of them. The section now says so.

The deployment recipe offered FLOCI_HOSTNAME for a different port, but
it replaces only the host and keeps FLOCI_BASE_URL's port, so a
different port needs FLOCI_BASE_URL.
2026-10-07 23:47:52 -04:00
vamsiakandVamsi Akavarapu d508a4e197 fix(apigateway): return embedded resource methods (#5109)
* fix(apigateway): return embedded resource methods

* fix(apigateway): guard method maps during concurrent reads

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
2026-10-05 11:44:40 -04:00
Abhigya 1320995d70 fix(apigatewayv2): evaluate HTTP and WebSocket authorizer policies (#5020)
* fix(apigateway): evaluate Lambda authorizer policies with one evaluator

HTTP API (payload 1.0 and 2.0) and WebSocket $connect authorizers now
evaluate every policy statement against the execute-api ARN, instead of
reading only the first statement's Effect.

REST, HTTP and WebSocket APIs share AuthorizerPolicyEvaluator: one
validator and one set of condition keys (aws:SourceIp from the transport
address, aws:SecureTransport, aws:CurrentTime). IAM CIDR conditions now
match IPv6 ranges.

* fix(apigateway): reject malformed authorizer policy conditions

A Condition operator IAM does not know, an operator without keys, or a key
without values evaluated as a non-match or an unconditional match, so a
malformed Deny could be skipped and a malformed Allow could grant access.
Validate each operator and its values and return 500 instead. Numeric and
boolean condition values are now compared rather than dropped.

* fix(iam): leave scalar condition values to #5086

The numeric and boolean condition-value parsing moves to its own pull
request, together with the numeric and date comparison fixes it needs.

* docs: update the IAM operation count in the Service Matrix
2026-10-04 20:59:04 -05:00
Aymen JAMAAOUI 2c544fdb9f feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink (#5008)
* feat(apigatewayv2): implement UpdateVpcLink and VPC link tagging

* feat(cloudformation): provision AWS::ApiGatewayV2::VpcLink

* fix(cloudformation): keep VPC link and integration connection state on updates

* fix(cloudformation): restore the integration connection when its own update fails
2026-10-04 09:09:18 -04:00
Abhigya 3f591f853d fix(apigateway): share REST request context and complete mappings (#5035)
* fix(apigateway): share REST request context and complete parameter mappings

* fix(apigateway): resolve wildcard request body mappings

* fix(apigateway): distinguish scalar and multi-value mapping sources
2026-10-04 06:02:49 -04:00
Abhigya ae3adfe992 fix(apigateway): validate and cache REST Lambda authorizers (#5002)
* fix: evaluate and cache REST Lambda authorizer policies

* fix: share REST request context and complete parameter mappings

* fix: prevent stale REST authorizer caching after stage flush

* fix: use valid authorizer policies in REST import tests

* chore: align API Gateway imports with repository style

* fix(apigateway): isolate authorizer contracts and validate cached identities

* chore(apigateway): align restored context code with style guide

* chore: order API Gateway SDK test imports
2026-10-03 21:54:36 -04:00
Aniket Shukla 27bfb54c6e fix(apigateway): return integration defaults and patch timeout (#4798)
* fix(apigateway): return integration defaults and patch timeout

* fix(apigateway): read defaults for legacy integrations

* fix(apigateway): preserve response transfer mode in configuration

* fix(apigateway): reject malformed response transfer mode

* fix(apigateway): restrict stored stream mode to proxy integrations
2026-10-03 14:18:16 -04:00
Abhigya 036f55b196 fix(apigateway): map authorizer context in HTTP integrations (#4992)
* fix(apigateway): map authorizer context in HTTP integrations

HTTP backends need verified authorizer context from parameter mappings. Resolve scalar context values and replace mapped headers regardless of casing so client claims cannot remain beside verified values.

* fix(apigateway): drop unresolved context headers

Remove inbound context-mapped headers even when verified context is absent or non-scalar. Cover missing authorizer claims, forged repeated headers, OPTIONS and unresolved method mappings.

* fix(apigateway): preserve original mapping inputs

Keep HTTP proxy header, query and path mapping sources separate from outgoing destinations. Cover both mapping orders with present and missing authorizer claims through both REST execution endpoints.
2026-10-02 23:17:57 -04:00
Abhigya 12e9cbd78b fix(apigateway): capture HTTP proxy greedy suffixes (#4980) 2026-10-02 21:49:47 -04:00
Michał Łomnicki cbc4cf9b91 fix(apigatewayv2): allow an idempotent override-id tag on UpdateApi (#4602)
* fix(apigatewayv2): allow an idempotent override-id tag on UpdateApi

A CloudFormation update resends the template's full tag set, so an
AWS::ApiGatewayV2::Api that pinned its id with floci:override-id failed
every stack update with "Reserved tag key floci:override-id can only be
supplied during resource creation" and rolled back.

UpdateApi now passes the api id to the reserved-tag guard, which already
treats an override equal to the existing id as a no-op (as TagResource
does since #3430), and stores the tags with the override keys stripped.
A different override value is still rejected.

docs/services/api-gateway.md now says a changed override is rejected on
TagResource and UpdateApi while resending the current id is accepted.
The TagResource half has been true since #3430 but was never documented.
CloudFormationIntegrationTest covers a stack update that resends the
pinned id and one that changes it.

* fix(apigatewayv2): validate UpdateApi tags before applying any field

UpdateApi set the name, description and other fields before the
reserved-tag guard ran, so a request it rejected had already changed the
stored API. A CloudFormation update that changed an api's override id
rolled back with the stack reporting UPDATE_ROLLBACK_COMPLETE while the
api kept the rejected update's description.

The guard now runs first, so a rejected update leaves the api as it was.
The CloudFormation test checks the description and tags after the
rollback.
2026-10-01 19:54:15 -04:00
danielxoi 5000bcd041 fix(apigateway): accept a region label before the built-in execute-api suffixes (#4705)
* fix(apigateway): accept a region label before the built-in execute-api suffixes

extractApiId accepted a region label only before localhost, the configured hostname, or an AWS DNS suffix, so <apiId>.execute-api.<region>.localhost.floci.io (the shape a client derives from a stage's invoke URL) was never claimed and fell through to S3's path routes, answering NoSuchBucket for the stage segment. Accept the built-in localhost.floci.io and localhost.localstack.cloud suffixes after a region label too, for REST and HTTP APIs alike.

Closes #4701

* fix(apigateway): accept every published region label on execute-api hosts

extractApiId validated the region label with a two-letter-geo pattern, so eusc-de-east-1 was rejected before the suffix was checked and the request fell through to S3, on every tail including amazonaws.eu. Check the label against the published region ids with AwsRegions.isRegionId, the same test RegionResolver.resolveRegionFromHost applies, so the hosts the filter claims match the regions it can resolve.

* fix(apigateway): accept execute-api region labels not yet in the partition catalog

isRegionId accepts only regions in the vendored published list, so a region launched after that data was generated was rejected on its execute-api host even though signed requests accept it. Use RegionResolver.isKnownRegion, which falls back to each partition's botocore region regex; an unrecognized label such as zz-nowhere-9 is still rejected.
2026-10-01 12:31:35 -04:00
Mario Toffia b5c428319f fix(apigateway): create API keys disabled unless enabled is set (#4731)
* fix(apigateway): create API keys disabled unless enabled is set

AWS creates an API Gateway API key disabled when the CreateApiKey request has no enabled field, and the AWS::ApiGateway::ApiKey CloudFormation schema declares Enabled with a default of false. Floci created such keys enabled, and a CloudFormation update whose template omitted Enabled switched the key on. AWS SDKs that model enabled as a plain boolean, such as the AWS SDK for Go v2, leave the field out of the request when it is false, so a client asking for a disabled key received an enabled one.

* fix(cloudformation): restore an API key when its stack update rolls back

When a stack update changed an AWS::ApiGateway::ApiKey and a later
resource in the same update failed, the stack ended in
UPDATE_ROLLBACK_FAILED and the key kept the new customer id,
description, enabled flag and tags. The provisioner had no rollback.

The provisioner now records those four values on the stack resource
before it changes the key, and puts them back when the stack update
rolls back. It also replaces the tags before patching the other
fields, so a refused tag change leaves the key untouched.

* fix(cloudformation): delete an API key an update recreated when the update rolls back

When a stack update found that its API key had been deleted outside
CloudFormation, it created a new key. If a later resource then failed
the update, the rollback reported success and left the new key live,
while the stack resource still named it.

The update now records the key it created, and the rollback deletes
that key and points the stack resource back at the previous key id.

The API key CloudFormation integration test now waits for the stack
to reach a final status before checking it, because stack create and
update run in the background.

* fix(cloudformation): put an API key's tags back when its own update fails

An API key update replaces the tags first and then patches the other
fields. If the patch failed after the tags were replaced, the stack
rolled back but the key kept the new tags. For a resource whose own
update fails, the stack restores the stored resource record and does
not call the provisioner's rollback, so nothing put the tags back.

The update now copies the tags before replacing them and puts the copy
back when the patch fails, then rethrows the original error.

* fix(cloudformation): undo the whole API key when its own update fails

An API key update replaces the tags and then patches the customer id,
description and enabled flag. Either call can fail after it has
already changed the stored key. Before, a failure only put the tags
back, and a failure to put them back was hidden, so the stack could
report a clean rollback while the key kept the failed update's values.

Now any failure in either call puts the key's four values back from
the snapshot taken before the update. If that restore also fails, the
resource is marked so the stack ends in UPDATE_ROLLBACK_FAILED, and
the original error is rethrown with the restore error attached.

* fix(cloudformation): roll an API key back by writing only what changed

Rolling back an API key update wrote every saved value back, even when
the update had changed nothing. For example, the service refuses a
reserved tag change before it writes anything, yet the rollback still
rewrote the tags and fields. That changed the key's last-updated time
for no reason, and if one of those writes failed, the stack reported
UPDATE_ROLLBACK_FAILED for an update that had not changed the key.

The rollback now reads the key as it is and writes back only the tags
and fields that differ from the saved values. The update and the
rollback share one function to decide which fields differ.

Also, when the rollback fails with the same exception object as the
update, it is no longer attached to itself, which threw an
IllegalArgumentException and hid the original error.

* fix(cloudformation): put back a reserved API key tag when an update rolls back

An API key can be created with a reserved tag, such as the id-override
tag _custom_id_. A stack update may remove that tag. When a later
resource failed the update, the rollback tried to put the tag back
through the same call the update uses, which refuses a reserved tag
that is being added. The stack then ended in UPDATE_ROLLBACK_FAILED
and the key stayed without its tag.

The API Gateway service gains a call that sets a key's tags exactly as
given, without the reserved-tag check. The rollback uses it. Tag
changes from a template still go through the checked call.

The test helper that applies patches now uses a switch expression, as
the repository's code style asks.
2026-09-30 15:48:46 -04:00
Mario Toffia 560de5c13f fix(tagging): find resources by the tags their own service holds (#4563)
* fix(tagging): list resources by the tags their own service holds

GetResources, GetTagKeys and GetTagValues merge the tagging store with every
ResourceProvider, so SQS, Lambda and Logs tags are discoverable. Resource type
filters now parse colon and leading-slash ARNs (function:f, log-group:x, /apikeys/k),
and TagResources/UntagResources write through to the owning TagHandler.

* fix(apigateway): expose tagged resources and API key tags to the tagging API

ApiGatewayService is a ResourceProvider for REST APIs, stages, API keys, usage plans and
domain names, and ApiGatewayTagHandler serves /apikeys/<id> ARNs, so GetResources finds
API Gateway resources by tag and tagging-API writes land on the API key itself.

* fix(cloudformation): forward AWS::Lambda::Function Tags

CreateFunction now receives the template Tags; an in-place UpdateStack untags dropped keys and retags the desired set, mirroring SqsCfnProvisioner.

* fix(tagging): scope global-ARN resources by region and clamp stale page tokens

Provider resources with an empty ARN region use their own region, stale page tokens
past the end return an empty page, and provider tags are copied inside the skip guard.

* test(compat): discover SQS, Lambda, Logs and API Gateway resources by tag

* docs(tagging): describe owning-service discovery

* fix(tagging): forward tags only for resources the owning service lists

* fix(apigateway): report the calling account and tag usage plans

* docs(cloudformation): note Lambda tag reconciliation on update

* fix(tagging): match declared resource types and scope owner writes to the request

API Gateway API key and usage plan ARNs must now name the key or plan at the
start of the resource part, so a nested /apikeys/ segment no longer tags the key.

* fix(tagging): match AWS type filters, regions and failure codes

Compared against a live AWS account: type filters, IAM listing, cross-region
TagResources and FailedResourcesMap entries now answer as AWS does.

* fix(cloudformation): keep Lambda tags added outside the template

* fix(tagging): route TagResources to V1 tag handlers too

* fix(apigateway): reject sub-resource ARNs when tagging a REST API

* fix(tagging): write tagging API tags through to SQS, Lambda and Logs

TagResources and UntagResources now reach the queue, function or log group's own tags through TagHandler beans qualified @TaggingApiOnly, so ListQueueTags, Lambda ListTags and Logs ListTagsForResource show them. The qualifier keeps these handlers off the /tags/{arn} and /v1/tags/{arn} paths, since each service defines tags in its own protocol.

* fix(cloudformation): forward SSM parameter tags

AWS::SSM::Parameter now applies its Tags after the overwriting put. On UpdateStack only the keys the previous template set and the new one drops are removed, tracked in the internal FlociSsmTemplateTagKeys attribute, so tags added outside the template are kept.

* fix(tagging): hide tagging-store copies of global resources

GetResources no longer lists an IAM role or user tagged through TagResources, since AWS never lists global resources.

* fix(tagging): reject every wildcard log group ARN

TagResources and UntagResources now send a log group ARN ending in :* to CloudWatch Logs even when the group does not exist, so it is rejected as in AWS instead of stored.

* fix(tagging): clear store tags on every untag

UntagResources now removes the keys from the tagging store for every ARN, even one the owning service rejects, so a copy stored earlier can always be cleared.

* fix(cloudformation): tag an adopted Lambda function

When CreateFunction conflicts and the provisioner adopts the existing function, the template's tags are now applied to it.

* fix(apigateway): tag only exact domain and stage ARNs

A domain or stage segment nested elsewhere in an API Gateway ARN, such as /restapis/<id>/domainnames/<d>, is now rejected instead of tagging that domain or stage.

* fix(cloudformation): leave an adopted Lambda function's tags alone

Adoption uses the existing function as it is, as before, so a function outside the stack keeps its tags.

* fix(cloudformation): record no template tag keys for an adopted Lambda function

An adopted function keeps its own tags, so a later update adds the template's tags without removing any it never set.

* fix(tagging): never list IAM ARNs from the tagging store

A role tagged through TagResources stays hidden after DeleteRole, as AWS never lists IAM resources.

* fix(tagging): fail a write when an owning service cannot be read

A provider that fails while routing TagResources or UntagResources now returns InternalServiceException instead of writing the tagging store and reporting success.

* fix(tagging): fail only unresolved ARNs when a provider cannot be read

A provider failure no longer fails the whole TagResources or UntagResources call; only ARNs whose owner could not be resolved are reported in FailedResourcesMap.

* fix(tagging): report another account's ARN instead of storing it

TagResources and UntagResources report an ARN from another account in FailedResourcesMap with AccessDeniedException, as AWS reports it per ARN, and never write it to the tagging store.

* fix(tagging): keep stored tags for an ARN an untag could not resolve

UntagResources leaves the tagging store unchanged for an ARN it reports as unresolved or from another account; an ARN its owner rejected is still cleared.

* fix(tagging): fail an unresolved ARN only when its own service cannot be read

A provider failure now only affects unlisted ARNs of the services that provider declares.

* fix(tagging): copy stored tags under the writers' lock

GetResources, GetTagKeys and GetTagValues no longer race a concurrent TagResources on a stored mapping.

* fix(apigateway): reject reserved tags when tagging a usage plan

TagResources on a usage plan now refuses floci:override-id as the other API Gateway tag paths do, instead of dropping it and reporting success.

* fix(apigateway): reject tag ARNs with an account or another region

The /tags path now answers an ARN with an account segment with BadRequestException and one naming another region with NotFoundException, as AWS does, instead of resolving the id in the caller's region.

* fix(ssm,lambda): reject tag keys outside the AWS pattern

AddTagsToResource, PutParameter, TagResource and CreateFunction now reject a tag key outside the AWS pattern or 1 to 128 characters with ValidationException, as AWS does, which also keeps the CloudFormation managed-key attributes lossless.

* fix(ssm,lambda): validate CloudFormation tag keys before changing the resource

* docs(tagging): say every handled ARN ending in :* reaches its service

* fix(tagging): read a negative pagination token as the first page
2026-09-30 06:10:27 -04:00
vamsiakandVamsi Akavarapu af3d387140 fix(apigateway): route REST execute-api virtual hosts (#4553)
* fix(apigateway): route REST execute-api virtual hosts

* fix(apigateway): preserve REST connection paths

* fix(apigateway): prioritize WebSocket connection routes

* fix(apigateway): honor explicit REST domain routes

* fix(apigateway): preserve WebSocket domain connections

* fix(apigateway): scope base path routes to REST APIs

* fix(apigateway): retain API type for domain mappings

* fix(apigateway): find WebSocket connection routes across accounts

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
2026-09-30 06:07:57 -04:00
vamsiakandVamsi Akavarapu 0383ecf53e fix(apigateway): resolve AWS variables on REST import (#4547)
* fix(apigateway): resolve AWS variables on REST import

* fix(apigateway): preserve OpenAPI mapping templates

* fix(apigateway): resolve imported authorizer variables

* chore(ci): retry Docker Hub limited tests

* fix(apigateway): resolve import variables across definitions

* test(apigateway): cover variable imports with AWS SDK

* refactor(apigateway): remove unused import validation region

* style(apigateway): sort OpenAPI parser import

* fix(apigateway): preserve imported authorizer merge behavior

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
2026-09-29 15:32:17 -04:00
Langning Zhang cfc9a440c1 fix(apigateway): merge OpenAPI imports in PutRestApi (#4570)
* fix(apigateway): merge OpenAPI imports in PutRestApi

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): preserve authorization across API merges

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): preserve authorization across API merges

Signed-off-by: zhanglangning <zln1905391059@163.com>

* fix(apigateway): reject invalid PutRestApi modes

Signed-off-by: boulea7 <zln1905391059@163.com>

---------

Signed-off-by: zhanglangning <zln1905391059@163.com>
Signed-off-by: boulea7 <zln1905391059@163.com>
2026-09-29 07:37:44 -04:00
stodan 2ec5300029 fix(apigateway): drop the SigV4 Authorization header before REST integrations (#4567)
* fix(apigateway): drop the SigV4 Authorization header before REST integrations

API Gateway drops the inbound Authorization header on its way to a REST
Lambda or HTTP integration when the method is AWS_IAM, or on any method
when the header carries a SigV4 signature. Floci forwarded it into the
AWS_PROXY event and the HTTP_PROXY request, so a function serving both
Bearer-token users and IAM-signed services saw "AWS4-HMAC-SHA256 ..."
where AWS delivers no header at all.

X-Amz-Date, X-Amz-Security-Token and every other header still pass
through, a Bearer token on a non-IAM method is unchanged, and REQUEST
authorizer events keep the header. HTTP API (v2) is unchanged: AWS
documents no such stripping there.

* test(apigateway): cover method.request.header.Authorization mappings on AWS_IAM routes

* test(apigateway): fold the Authorization header tests into ProxyEventIamIdentityTest
2026-09-29 07:29:26 -04:00
Aniket Shukla b9efda8606 fix(apigateway): honor import warnings and strict rollback (#4531) 2026-09-27 18:22:48 -04:00
Niels Kootstra ea60f70ad2 fix(apigatewayv2): cap HTTP_PROXY integration responses at the 10 MB payload quota (#4226)
HttpProxyInvoker read the whole integration response into memory with no
limit. Stop reading once a response passes API Gateway's 10 MB payload quota
and return 413 Request Entity Too Large, for Content-Length, chunked and
close-delimited bodies alike. REST and HTTP APIs share this invoker, so both
get the limit.
2026-09-23 17:08:11 -04:00
stodan c083aad12b fix(apigateway): verify AWS_IAM signatures against the custom-domain path (#4092)
* fix(apigateway): verify AWS_IAM signatures against the custom-domain path

The custom domain filter rewrites a request onto /execute-api/... before
dispatch but, unlike the execute-api host filter, never recorded the path
the caller actually signed. SigV4 verification then rebuilt the canonical
request from the rewritten path, so every AWS_IAM method invoked through a
custom domain was rejected with InvalidSignatureException.

Record the original raw path on ApiGatewayExecuteRouteContext, matching
ApiGatewayExecuteApiHostFilter, and give the filter an explicit
ApplicationScoped scope so the request-scoped context injects through a
client proxy. Covers both REST and HTTP API custom domains, since v2 API
mappings are stored as base path mappings and routed by the same filter.

* test(apigateway): cover AWS_IAM through an HTTP API custom domain

A v2 API mapping is stored as a base path mapping and routed by the same
custom domain filter as REST APIs, so the fix applies to HTTP APIs too. Prove
it rather than assert it: a signed request through the domain reaches the
integration, and unsigned, rewritten-path and other-path signatures are
rejected with v2's flat 403 Forbidden.
2026-09-21 16:11:06 -04:00
Attila Kis ad20699a6b fix(apigateway): complete API Gateway API key responses (#3817)
Return timestamps, stage keys, tags, and customer ID across create, get, list,
and update operations to prevent Terraform provider crashes and state drift.
Generate opaque IDs by default while preserving legacy generateDistinctId=false behavior.
Keep API key values hidden unless explicitly requested.
Add REST, SDK, and CloudFormation regression coverage.
2026-09-17 16:01:43 -04:00
Abhigya f7565dff3e feat(apigateway): honour the remaining REST integration settings (#3434)
* feat(apigateway): honour the remaining REST integration settings

PutIntegration persisted 6 of the 16 fields AWS documents. The rest were
accepted without error and silently dropped, so an integration could be created
exactly as intended and then behave as though the configuration were absent.

- timeoutInMillis is applied to the backend call and defaults to AWS's 29,000ms
  rather than the previously hardcoded 30s. Values below AWS's 50ms floor are
  rejected; the 29s ceiling is an edge-optimized limit, so Regional APIs may
  exceed it.
- tlsConfig.insecureSkipVerification skips backend certificate and hostname
  verification. Without it an HTTPS backend behind a private CA or a self-signed
  certificate was unreachable with no way to opt out.
- contentHandling converts payloads in both directions: CONVERT_TO_TEXT
  base64-encodes a binary request for mapping templates, CONVERT_TO_BINARY
  decodes a base64 text request before it is sent. Integration responses accept
  it too, applied as an output conversion after response templates.
- binaryMediaTypes on the RestApi marks content types as binary. A binary body
  now reaches an AWS_PROXY integration base64-encoded with isBase64Encoded set;
  previously it was read as a UTF-8 string, which corrupted it.
- connectionType VPC_LINK requires connectionId to name a link that exists and
  is available. The five REST VPC Link operations are implemented at /vpclinks.
  Floci has no real VPC, so a valid link routes straight to the integration URI;
  what is enforced is the misconfiguration AWS also rejects.
- cacheNamespace and cacheKeyParameters drive response caching, gated on both
  switches AWS requires: cacheClusterEnabled on the stage and caching/enabled on
  the method. Only successful responses are cached, expiring after the method's
  ttlInSeconds.
- credentials is persisted and returned. Floci does not enforce IAM, so the role
  is not actually assumed.

The same fields are now carried through an OpenAPI import, which previously
dropped them from x-amazon-apigateway-integration.

* fix(apigateway): align TLS, cache keys and VPC link patches with AWS

Three review findings on the REST integration settings, all cases where the
local behaviour was looser than the contract AWS documents.

tlsConfig.insecureSkipVerification installed a trust-all X509TrustManager, so an
expired certificate, a broken chain or a chain with no root reached the backend
happily. AWS skips only the check that the certificate was issued by a supported
certificate authority; it still performs basic validation of the expiration
date, the hostname and the presence of a root certificate authority. A backend
that would fail in AWS therefore worked here, which is the direction that hides
a production TLS misconfiguration. The trust manager now verifies validity,
checks that the chain holds together and terminates in a self-signed root, and
requires cA=true on that root when it actually issued a leaf. Hostname
verification is now requested explicitly rather than being switched off: note
that java.net.http.HttpClient always applies HTTPS endpoint identification and
ignored the previous null algorithm, so the hostname was in fact still checked,
but the code and its documentation both claimed otherwise.

The response cache key appended the method and request path to cacheNamespace.
AWS allows one cacheNamespace across several resources exactly so those
resources return the same cached data, and no two resources share a path, so the
setting could never do what it exists for. The key is now the namespace plus the
declared cacheKeyParameters. The namespace still defaults to the resource id, so
resources that did not opt into sharing stay separate.

UpdateVpcLink never looked at op. Any operation on /name or /description was
applied, so op=remove,path=/name set the name instead of being rejected, and
every other path was silently ignored and reported as success. AWS's patch table
supports only replace on those two paths; anything else is now a
BadRequestException.

Also removes the em dashes AGENTS.md disallows from the test files this branch
adds, which the Documentation Style check flagged.

* fix(apigateway): enforce keyCertSign and name constraints under insecureSkipVerification

The comment on CaIssuanceSkippingTrustManager claimed the root check matched
AWS's two requirements on a private root, cA=true together with a keyUsage
including keyCertSign, but only getBasicConstraints() was ever consulted. A root
with CA:TRUE and no keyCertSign was accepted here and rejected by real API
Gateway, which is the direction that hides a broken certificate authority until
deployment. The keyUsage bit is now checked alongside basicConstraints. An
absent keyUsage extension is still accepted: RFC 5280 leaves the key
unrestricted when it is missing, and PKIX reads it the same way.

The rest of the chain walk is now the platform's PKIX validator, anchored on the
chain's own root, which is exactly the "stop checking that the root is one we
trust, keep checking everything else" semantic this setting has in AWS. That
brings X509v3 name constraints with it, which the hand-rolled walk did not
implement at all, along with basicConstraints and keyCertSign on intermediates
and pathLenConstraint. The anchor's own extensions are not examined by PKIX, so
the root's checks stay explicit, and its NameConstraints extension is passed
through to the TrustAnchor. Expiration stays explicit too, because PKIX exempts
a trust anchor from it and AWS does not.

A lone self-signed certificate keeps its own path: it is its own root and is the
plain self-signed-server case the setting exists to enable, so CA extensions are
not demanded of it.

Three tests against real HTTPS backends: a well-formed private CA chain is
reached, a root declaring CA:TRUE without keyCertSign is rejected, and a root
that permits itself only internal.example while issuing for localhost is
rejected. The latter two return 200 without this change.

* fix(apigateway): require keyUsage on a private root and evaluate name constraints properly

Two corrections to the previous round's TLS work.

AWS states the root constraint as "x509 extension keyUsage must have
keyCertSign", which a root carrying no keyUsage extension at all does not
satisfy. The previous commit read a missing extension as leaving the key
unrestricted, which is generic RFC 5280 semantics but not this API
Gateway-specific requirement, and so accepted a certificate authority real API
Gateway turns away. A root without the extension is now rejected.

The name constraints handling was also wrong, in a way its own test hid.
Constraints were unwrapped from the root and handed to the TrustAnchor, but the
platform validator refuses to process anchor-supplied constraints and fails with
"name constraints in trust anchor not supported". So a root carrying the
extension was rejected blindly, never evaluated, and the test asserting a
violated constraint passed on that unrelated error.

Root-level constraints are now rejected deliberately, with an error that says
so, rather than as a side effect of a validator limitation. That is also the
documented behaviour: AWS tells operators hitting validation errors under
insecureSkipVerification to check their CA certificates for Name Constraints
extensions and reissue without them. Constraints on an intermediate sit inside
the certification path, where the validator does read them, and those are
enforced for real: the log now shows "name constraints check failed" rather than
"not supported".

Tests follow the same split. A three-certificate chain whose intermediate
permits only internal.example while issuing for localhost is rejected, a chain
whose intermediate permits localhost is reached, so the first is failing on the
constraint rather than on chain length, and a root carrying constraints is
rejected as its own documented case. Plus a root with CA:TRUE and no keyUsage
extension, which returns 200 without this change.

* fix(apigateway): match binaryMediaTypes literally apart from the catch-all

The matcher expanded a subtype wildcard, so an image/* entry covered
image/png. Nothing in the AWS documentation establishes that as a
pattern: */* is documented concretely ("To support all binary media
types, specify */*"), while every other example names one exact media
type at a time, and the browser walkthrough tells you to register the
concrete image/webp even though the request's Accept header carries
image/*. Expanding it made Floci treat a payload as binary where AWS
would compare the entry as a literal string and treat it as text.

Entries are now compared literally, ignoring the charset parameter,
with */* as the one wildcard. The wildcard branch keeps its coverage
through a */* test, and a second test pins the subtype wildcard as
not expanded so the behaviour cannot drift back silently.
2026-09-17 00:18:49 -04:00
Niels Kootstra ef03c59864 fix(apigateway): prevent JWT issuer and JWKS SSRF (#3743)
* fix(apigateway): prevent JWT issuer and JWKS SSRF

* fix(apigateway): import verifier types
2026-09-16 18:00:01 -04:00
Ovidiu (Ovi) f99e507916 feat(apigateway): implement GetUsage (#3561)
* feat(apigateway): implement GetUsage

GetUsage had no implementation, so a caller asking a usage plan what it
had consumed hit an unsupported action.

This returns the real envelope with zeroed numbers rather than metering
anything. Shape captured from real API Gateway: an items map of API key id
to one pair per day of the inclusive range, alongside usagePlanId,
startDate and endDate, and no position element when there is no further
page.

The pair is [used, remaining], not [used, quota]. Measured on a live usage
plan, the second element is the quota limit minus cumulative use in the
period: a plan with a 1,000,000 limit reported 999863 after 137 calls, then
999740 after 123 more. Anything reading that element as a quota is reading
it wrong.

Both elements are zero here, deliberately. Nothing counts requests per API
key, and a usage plan carries no quota to subtract from, so there is no
limit to report against. Throttle settings are already accepted and stored
without being enforced, so this is consistent with how the service treats
the rest of that surface. Storing a quota on the usage plan and counting on
the execute path are the two pieces still missing, and both the javadoc and
the service docs say so.

A caller that sums the used counts therefore gets zero, which is what it
already got when the action did not exist, without having to special-case a
missing endpoint.

Validation follows the captured errors: an unknown plan is NotFoundException
and an end date before the start date is BadRequestException, "Usage end
date must be after start date".

* fix(apigateway): paginate GetUsage

GetUsage takes limit and position, which this did not accept at all: every
attached key came back in one response, so the implementation only matched
the single-page case the original capture happened to exercise.

Pagination now runs over the API key entries, defaulting to 25 a page. The
token is the last key id already returned rather than a positional offset,
so a page resumes after a known key and a concurrent key attachment cannot
shift it. No position is emitted on the terminal page, matching the shape
captured from real AWS.

Two edges deliberately differ from real API Gateway, because it is not a
good guide there. It answers limit=0 with an InternalFailure, which is a
fault rather than a contract, so a page size below one is a
BadRequestException here. It also accepts a limit past the documented
maximum of 500, so anything larger is clamped rather than refused. Both
choices are written down in the service docs.

An unrecognised position is a BadRequestException, "Invalid position
parameter", which is the message real API Gateway returns.

The existing tests looked keys up with a dotted GPath. API key ids are
random and can begin with a digit, which Groovy then parses as a number, so
every lookup into items now uses bracket notation. That was luck rather
than correctness before.

* fix(apigateway): stop inventing a GetUsage limit ceiling

The previous head clamped any limit above 500 to 500, extrapolated from a
single observation that 501 was accepted. One accepted value does not
establish a rule.

Probed properly against real API Gateway: 500, 501, 1000, 5000, 100000 and
2147483647 are all accepted without error. The documented maximum is not a
rejection boundary, so no ceiling is imposed here either and the regression
asserts the observed rule across that ladder rather than an emulator
specific clamp.

Whether the service caps the page it actually returns above 500 is not
observable without a usage plan holding more than 500 keys, so nothing is
assumed about it and the docs say as much.

The lower bound stays a deliberate divergence, now with both values
measured: limit=0 and limit=-1 both answer InternalFailure on real API
Gateway. That is a fault rather than a contract, so a page size below one
is a bad request here instead of a reproduced 500.

* fix(apigateway): cap the GetUsage page at 500 while still accepting more

Removing the ceiling entirely went too far the other way. The probe shows
real API Gateway accepts a limit above 500, so rejecting one would be
wrong, but it never showed the service returning more than 500 entries in a
single page, and the documented contract caps a page at 500. Returning more
than 500 was therefore as unevidenced as rejecting the request.

Request acceptance and response page size are now separate: a larger limit
is honoured as a request, and the page stays capped at 500 until a real
result with more than 500 keys shows otherwise.

resolveUsageLimit becomes package-private so the distinction can be
asserted directly rather than needing a usage plan with 500 keys behind it.

* fix(apigateway): return GetUsage key usage under the values wire key

The response serialised the per-key usage map as "items", which is the
SDK-side member name, not the wire key. The Usage shape models that
member with locationName "values", so a real client parsing a body keyed
"items" finds the field absent and reads no usage at all.

Verified with botocore's own rest-json parser against the apigateway
service model: a body keyed "values" populates the member, a body keyed
"items" leaves it None.

Assertions and the service docs move with it. Only GetUsage is affected;
the sibling list actions are a different shape and are untouched.
2026-09-16 09:20:30 -04:00
Niels Kootstra 144b90e6fa fix(apigateway,appsync): sandbox VTL rendering with SecureUberspector and execution limits (#3542)
* fix(apigateway,appsync): sandbox VTL rendering with SecureUberspector and execution limits

VtlTemplateEngine and AppSyncVtlEngine rendered templates with Velocity's
default UberspectImpl introspector, which allows arbitrary reflection
through any context object (e.g. $util.getClass().forName('java.lang.Runtime')),
and had no cap on #foreach iterations, output size, or execution time,
making them vulnerable to both sandbox escapes and denial of service via
runaway loops or #set string doubling.

Add a shared VtlSandbox helper that both engines call to switch to
SecureUberspector and restrict introspection on java.lang.Class,
ClassLoader, Runtime, ProcessBuilder, System, Thread, java.io.File and
related reflection/scripting/process packages, plus three independent
limit layers: a native #foreach loop cap that truncates the loop without
failing the template, a cooperative execution deadline checked from a new
SandboxedForeach directive before each loop iteration, and a BoundedWriter
output-size cap. The latter two throw the new VtlLimitExceededException,
an unchecked RuntimeException that flows through each engine's existing
error handling exactly like any other Velocity evaluation failure, with
no new error shape. Limits are configurable via EmulatorConfig
(vtlMaxLoops, vtlMaxOutputChars, vtlTimeoutMillis; application.yml keys
vtl-max-loops, vtl-max-output-chars, vtl-timeout-millis), mirroring the
project's existing per-service numeric-tunable config pattern, and
documented in api-gateway.md and appsync.md.

The classpath-shadowed velocity.properties resource is kept for any
embedding that resolves it normally, but is not the actual enforcement
point: under this project's test/runtime classloader, Velocity's own
getResourceAsStream lookup for that exact resource path can resolve to
the copy bundled inside the velocity-engine-core jar instead of this
project's shadowed copy, silently leaving the insecure UberspectImpl
active even with a correct properties file on disk. VtlSandbox configures
SecureUberspector and swaps in SandboxedForeach directly via the
VelocityEngine Java API instead, which is unaffected by that ambiguity.

* docs(apigateway): correct foreach registration documentation
2026-09-15 13:03:51 -04:00
Matheus André 2ee3aa67c0 feat(apigateway): support Gateway Responses on REST APIs (#3326) (#3585)
Add the PutGatewayResponse / GetGatewayResponse / GetGatewayResponses /
UpdateGatewayResponse / DeleteGatewayResponse family, keyed per REST API by
responseType across the 21 AWS types. Uncustomised types are reported with
defaultResponse=true, their AWS default statusCode and the default
{"message":$context.error.messageString} template; UpdateGatewayResponse
patches /statusCode, /responseParameters/<name> and
/responseTemplates/<content-type>, and DeleteGatewayResponse restores the
default.

ImportRestApi and PutRestApi read the x-amazon-apigateway-gateway-responses
extension, and AWS::ApiGateway::GatewayResponse is provisioned by a new
CloudFormation provisioner whose Ref / Fn::GetAtt Id is
<restApiId>-<responseType>.

On the execute plane every gateway-generated answer (unmatched path or
method, AWS_IAM and Lambda authorizer rejections, missing API key, request
validation, unsupported media type, integration configuration errors and
Lambda proxy failures) resolves the customisation for its type, then
DEFAULT_4XX / DEFAULT_5XX, and applies the configured statusCode, the
gatewayresponse.header.* parameters (static, method.request.*, context.*,
stageVariables.*) and the response templates, with $context.error.* exposed
to VTL. An expired SigV4 signature selects EXPIRED_TOKEN and a malformed or
mismatching one INVALID_SIGNATURE, as AWS keeps those two contracts apart.
This is what puts Access-Control-Allow-Origin on a browser-visible
401/403/400 so the frontend can read the real status instead of a CORS
failure. Without a customisation every answer is unchanged.

Closes #3326
2026-09-15 07:44:45 -04:00
Abhigya 96707f6d5a feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs (#3433)
* feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs

PutIntegration already accepted type HTTP_PROXY and HTTP, but dispatch handled
only AWS_PROXY, AWS and MOCK and fell through to a 500 "Unsupported integration
type". A REST API fronting an HTTP microservice - the shape CDK's HttpIntegration
and addProxy emit - could be created but never invoked.

HTTP_PROXY is a passthrough: the request goes to the integration URI with {param}
placeholders resolved from the matched resource's path parameters, and the
backend's status, headers and body are relayed unchanged. AWS applies neither
request templates nor integration-response selection to HTTP_PROXY, so a backend
4xx or 5xx reaches the caller verbatim rather than being remapped into a gateway
error. An unreachable backend yields 502.

HTTP is the non-proxy form and transforms in both directions. The request body is
the rendered requestTemplates entry chosen by the incoming Content-Type, and only
headers and query parameters named by integration.request.* mappings are
forwarded - unmapped inbound headers are deliberately not passed through, which
is what separates it from HTTP_PROXY. The backend's reply then runs through the
method's integration responses, where selectionPattern is matched against the
backend's HTTP status code rather than against an error message as it is for
AWS/Lambda integrations.

Both reuse the existing v2 HttpProxyInvoker for transport, so hop-by-hop header
stripping, chunked decoding and the 502-on-failure behaviour are shared. The
request-template negotiation and integration-response mapping that AWS
integrations already performed are extracted so both types use one implementation.

* fix(apigateway): preserve repeated headers and query parameters through HTTP_PROXY

A REST HTTP_PROXY integration passes the request through, and AWS supports
multi-valued headers and query strings on that path. The adapter collapsed both
into one comma-joined value before handing the request to the shared transport,
so "?tag=a&tag=b" reached the backend as "tag=a,b" and a header sent twice
arrived once. Those are not interchangeable: most servers parse the joined form
as a single value containing a comma.

The relayed response had the same defect. A backend returning two Set-Cookie
headers produced one joined header, which the client cannot split back apart,
since an Expires attribute contains a comma of its own.

The transport already stored headers and query parameters as multimaps
internally; only its boundary types flattened them. RequestContext now carries a
multi-valued view alongside the single-valued one that $request.* expressions
resolve against, ProxyResult returns multi-valued headers, and the REST proxy
path emits one header line per value. An explicit integration.request.* mapping
still overwrites, replacing repeated inbound values with the mapped one.

Non-proxy HTTP is unchanged: its integration responses resolve
integration.response.header.X to a single value, so it collapses the backend's
headers at that point instead.

* fix(apigateway): preserve repeated parameters through HTTP API HTTP_PROXY too

dispatchHttpProxyV2 is the second entry point into the HttpProxyInvoker /
RequestContext / ProxyResult transport, and it still built its request context
from comma-joined single-value maps. So after the REST path was fixed, an HTTP
API (v2) with an HTTP_PROXY integration still sent "?tag=a,b" for "?tag=a&tag=b",
and repeated request headers still arrived joined: the transport's multi-value
support was there but never populated from here.

It now builds the same two views the REST path does. The multi-value maps are
what reaches the backend, and the joined single-value maps stay the lookup
surface for $request.header.X / $request.querystring.X, which resolve to one
value in AWS. The response relay already iterated multi-valued headers, so
repeated Set-Cookie was already correct on this path; it is pinned by a test
now rather than left implicit.

Also drops ProxyResult.firstHeader(), which nothing called, puts braces on the
conditionals in RequestContext.expand(), and imports LinkedHashMap in
ApiGatewayExecuteController instead of spelling it out in full at each use.
2026-09-13 18:06:04 -04:00
Matheus André 8d011cb983 fix(apigateway): implement MOCK integration response selection based on status code (#3327)
Signed-off-by: Matheus André <matheusandr2@gmail.com>
2026-09-11 12:11:12 -04:00
Mario Toffia 67bbd2cf13 feat: serve custom domains over TLS as soon as they are created (#3086)
* feat(tls): record runtime-learned hostnames in the certificate metadata

* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime

Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.

* feat(tls): keep runtime-learned hostnames across a boot regeneration

* test(tls): ensureHost is visible to the next TLS handshake without a restart

* docs(tls): custom domains learned at runtime

* test(tls): pin the certificate contracts of a runtime reissue

The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.

* fix(tls): retry a failed listener reload and keep served names across a boot

A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.

At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.

The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.

Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.

* fix(tls): carry a name whose reload failed into later reissues and resets

The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.

Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.

* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA

RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.

The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.

AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.

* refactor(acm): drop the cosmetic Amazon issuer generator

CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.

* docs(acm): certificates chain to the local CA

Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.

* test(acm): the SDK compatibility suite validates the certificate against its chain

GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.

* docs(acm): say when the CA is created and what Issuer reports

ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.

* test(acm): pin key size, an imported chain and the persisted chain

The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.

* test(acm): the python compatibility suite verifies the certificate against its chain

The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.

* fix(acm): write EC private keys as PKCS#8 and classify keys by interface

JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.

Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.

* test(acm): AcmServiceTest pins issuance from the local CA

Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.

* feat(apigateway): serve a custom domain over TLS as soon as it is created

CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.

* feat(iot): serve a customer-managed domain over TLS as soon as it is configured

CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.

* feat(cognito): serve a custom domain over TLS as soon as it is created

CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.

* docs: custom domains are served over TLS on creation

One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.

* test(compat): custom domain reachable over TLS trusting only the ACM chain

RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.

* docs(tls): say which ensureHost outcomes are logged as warnings

* test: pin the custom domain TLS hooks against the service contracts

Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.

* test(acm): build the InUseBy test service with the local CA

AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.

* test(cognito): request an issued ACM certificate in the custom domain TLS tests

Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.

* test(cognito): a concurrent create does not wait for the TLS reload

The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
2026-09-05 22:05:40 -04:00
Mario Toffia c3d977a3e3 feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping (#3040)
* feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping

Both types were stubs: the stack turned green while no domain or mapping
existed, Fn::GetAtt on the domain resolved to the literal attribute name, and
a request sent to the custom domain was not routed. The new provisioner calls
the existing CreateDomainName and CreateBasePathMapping. Ref and every
Fn::GetAtt attribute return what GetDomainName reports, a changed DomainName
or BasePath replaces the resource (created before the prior one is deleted),
and everything else is patched in place.

The physical id of a mapping is the compound identifier CloudFormation uses
for the type, <DomainName>|<BasePath>, with (none) for an empty base path.

Service fixes needed so the provisioned values can be read back through the
API: CreateDomainName keeps regionalCertificateArn and regionalCertificateName
(both were dropped), an EDGE domain gets a distributionDomainName and the fixed
CloudFront hosted zone, GetDomainName returns domainNameArn,
endpointConfiguration.types and tags, UpdateDomainName accepts the
/endpointConfiguration/types/EDGE patch path, domain tags are managed through
the tag API on the domain ARN, and CreateDomainName checks the name and stores
the domain under one lock so two concurrent creates cannot both succeed.

* fix(apigateway): keep the distribution in step with a domain's endpoint type

A move to EDGE through UpdateDomainName left the domain without a
distributionDomainName, and a move back to REGIONAL kept the old one, so
GetDomainName and Fn::GetAtt reported CloudFront fields that did not match the
endpoint type. Both create and update now go through one helper that puts a
distribution in front of an EDGE domain and drops it for a REGIONAL one.

* fix(apigateway): serialize domain and mapping changes, refuse a taken base path, validate the endpoint patch path

The stores hand out live objects, so a domain patch, a tag write and a
mapping patch were read-modify-write steps that concurrent calls could lose
or corrupt: eight concurrent tag writes on one domain kept four tags. Every
change to a custom domain or a base path mapping now runs under one lock, and
a tag write replaces the tag map instead of changing the one a reader may be
iterating.

CreateBasePathMapping on a base path that already has a mapping answers
ConflictException as AWS does; before, the new mapping silently replaced the
old one, so eight concurrent creates of one base path all succeeded.

UpdateDomainName accepted any /endpointConfiguration/types/<x> path; the path
must now name the type the domain has, as on AWS.

The provisioner sends the PATCH before it reconciles the tags, so a rejected
update leaves the tags as they were. Tests cover every case above, the
remaining cells of the update matrix (a prior resource gone under a new name),
and the REGIONAL to EDGE move end to end through a stack.

* fix(apigateway): refuse an endpoint type other than REGIONAL or EDGE on CreateDomainName

UpdateDomainName already rejected any other value, but CreateDomainName stored
whatever string the request carried, so a PRIVATE or misspelled type produced a
domain that was neither regional nor edge-optimized and that nothing could
route or describe. Private custom domains are not emulated, so the create now
answers BadRequestException with the same message as the update, and nothing
is stored. Adds the two remaining provisioner matrix cells as tests: a taken
domain name fails the resource without deleting anything, and a resource
without Properties is rejected.
2026-09-04 22:45:24 -04:00
Matheus Oliveira 06349c8d88 fix(apigateway): enforce AWS_IAM authorization on the execute-api data plane (#2895)
A method (REST) or route (HTTP API) with authorizationType AWS_IAM was
recorded but never enforced, so an unsigned request reached the integration as
if it were NONE. ExecuteApiSigV4Authorizer now verifies the caller's signature
over the request as it arrived, for both the Authorization header and the
presigned query string, and surfaces the verified caller on the proxy event:
requestContext.identity on REST, requestContext.authorizer.iam on HTTP API.
The signature must cover host, and expired or inactive credentials are
rejected.

Temporary credentials must also present the session token STS issued with
them, compared against the value the session store records since #2912.

Authentication only: execute-api:Invoke is not evaluated against IAM policies.

Closes #2810

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-09-03 22:23:44 -04:00
Brian Taylorandlocal 881695ea3b feat(apigatewayv2): OpenAPI import and Terraform-visible API/stage attributes (#2714)
* feat(apigatewayv2): implement ImportApi and ReimportApi

HTTP APIs had no PUT route on /v2/apis or /v2/apis/{apiId}, so ImportApi and
ReimportApi fell through JAX-RS matching to the S3 path-style handler and came
back as NoSuchBucket. Terraform's aws_apigatewayv2_api calls ReimportApi
whenever `body` is set, so any HTTP API defined by an OpenAPI document failed
to apply.

Add an OpenAPI importer for the v2 object model, reusing the swagger-parser
already used by ImportRestApi/PutRestApi on the v1 side. It materialises
routes, integrations and authorizers from x-amazon-apigateway-integration,
x-amazon-apigateway-authorizer, x-amazon-apigateway-any-method and
x-amazon-apigateway-cors, honouring document- and operation-level security.

ReimportApi replaces routes, integrations and authorizers as AWS does, but
leaves API settings an OpenAPI document cannot express (CORS when the spec
carries no x-amazon-apigateway-cors, tags, disableExecuteApiEndpoint) intact,
so a Terraform resource whose cors_configuration lives outside body does not
flap.

Both actions are wired for the restJson1 and JSON 1.1 protocols.

* fix(apigatewayv2): tag stages, not just APIs

TagResource, UntagResource and GetTags read the API id from the last segment of
the resource ARN, so a stage ARN (/apis/{apiId}/stages/{stageName}) yielded the
stage name as the API id and failed with "Invalid API id specified". Parse the
resource path by segment instead, and route the operation to the stage when the
ARN names one.

Stage had no tags field at all, so tags supplied to CreateStage were dropped and
never returned on read. Add it, populate it on create, and serialise it in both
the restJson1 and JSON 1.1 stage representations.

Terraform's aws_apigatewayv2_stage sets tags on create and then reconciles them,
so both halves were needed for a stage with tags to converge.

* feat(apigatewayv2): stage access logging, throttling and API version

Four attributes were accepted on write but dropped on read, so Terraform
re-proposed them on every plan and an aws_apigatewayv2_api/aws_apigatewayv2_stage
pair never converged:

- Api.version, also carried across from an imported document's info.version, as
  AWS does
- Stage.accessLogSettings (CloudWatch destination and format)
- Stage.defaultRouteSettings and per-route Stage.routeSettings (throttling,
  data trace, detailed metrics, logging level)

Throttling and logging fields are boxed rather than primitive: AWS omits unset
knobs instead of defaulting them, and emitting a zero would leave Terraform
seeing a changed value forever.

Stage also gains description, which CreateStage accepted and discarded.

Serialised for both the restJson1 and JSON 1.1 protocols.

* feat(apigatewayv2): honour basepath and failOnWarnings on OpenAPI import

ImportApi and ReimportApi accepted both documented query parameters and then
discarded them, so basepath=prepend or split produced routes at the wrong paths
with no error, and failOnWarnings never rolled anything back.

- basepath now resolves the base path the OpenAPI 3 way — a "basePath" server
  variable first (the first one, if several are declared), otherwise the path
  carried by server.url — and applies ignore, prepend or split. An unrecognised
  value is a BadRequestException rather than silence.
- failOnWarnings turns swagger-parser messages into a 400. Parsing and
  validation now happen before ReimportApi deletes anything, so a rejected
  reimport leaves the existing routes, integrations and authorizers untouched
  instead of gutting the API it was going to replace.
- The Api resource carries the warnings and importInfo the AWS model defines,
  the latter noting definition properties the import ignored.

* fix(apigatewayv2): validate authorizers before reimport mutates, warn on unenforceable security

Two review findings on the OpenAPI importer:

- Authorizer resolution ran while the spec was being applied, so a definition
  that parsed cleanly but declared an unsupported authorizer type — or a REQUEST
  authorizer with caching and no identitySource — was rejected only after
  ReimportApi had already deleted the previous routes, integrations and
  authorizers. Resolution now happens in the planning phase, side-effect free, so
  the rejection leaves the existing definition untouched. This mirrors
  validateImportedAuthorizers on the v1 side.
- A security requirement naming a scheme with no AWS binding — a plain bearer or
  apiKey scheme, or a misspelling — silently produced authorizationType NONE, so
  a document that declares security could yield a publicly invokable route. That
  now raises a warning naming the route and the schemes, which failOnWarnings
  escalates to a 400.

Also adds the braces AGENTS.md requires to the conditionals introduced by the
earlier commits in this branch.

* fix(apigatewayv2): examine ANY-method routes and compound security on import

Two more review findings, both in the warning collection added by the previous
commit:

- The diagnostic passes walked PathItem.readOperationsMap(), which does not
  include x-amazon-apigateway-any-method. An ANY route whose security named an
  unbindable scheme therefore produced no warning, failOnWarnings could not
  reject it, and it was still imported as NONE — the same silent-public-route
  hole the previous commit closed for ordinary operations, left open for the
  route type that matches every method. Route creation and both collectors now
  share one forEachImportedOperation enumeration so they cannot diverge again.
- Several schemes inside a single SecurityRequirement is OpenAPI's AND. A route
  carries one authorizer, so resolveSecurity enforced the first resolvable
  scheme and dropped the rest silently. That now warns, naming the dropped
  schemes and the one actually enforced.

* fix(apigatewayv2): report that imported AWS_IAM routes are not enforced

A sigv4 security scheme imports to an AWS_IAM route, which is what AWS records,
but HTTP API dispatch enforces only JWT and CUSTOM. A document declaring SigV4
therefore produced a route that looks authenticated and is not.

The route keeps AWS_IAM — downgrading it to NONE would misreport the definition
to anything reading the control plane — and the import now warns that the
emulator records the type without enforcing it. The dispatch gap itself predates
this change: CreateRoute has always accepted AWS_IAM unvalidated, and
ApiGatewayExecuteController already notes that v1 dispatch does not implement
AWS_IAM either.

* fix(apigatewayv2): validate jwtConfiguration shape before reimport mutates

jwtConfiguration was copied out of the authorizer extension unchecked, but
audience reaches the store as a List<String> and is cast as one. A scalar
audience — the form the extension is commonly written with — therefore threw a
ClassCastException inside createAuthorizer, after ReimportApi had already
deleted the previous routes, integrations and authorizers.

Normalise it during planning instead: a scalar audience becomes a single-element
list, a list is copied element-wise, and any other shape (or a non-string issuer)
is a BadRequestException raised before anything is deleted.

This was the last unvalidated field in authorizerSpecs; type, identitySource,
result-TTL caching and jwtConfiguration are now all resolved in the planning
phase, so no authorizer defect can reach the mutating half.

---------

Co-authored-by: local <local@example.com>
2026-08-30 17:16:25 -04:00
Sam Fakhreddine 9b9e7f56a2 feat(apigateway): API key import/usage-plan fidelity and update-operation fixes (#2631)
* feat(apigateway): complete the REST API resource lifecycle

Adds the missing delete and update operations across authorizers,
integrations, integration responses, methods, method responses, models,
request validators, resources, rest APIs, stages, deployments, domain names
and base path mappings, plus tag/untag, usage plan and usage plan key CRUD,
and ImportApiKeys backed by a new ApiKeyCsvParser.

Each operation has a wire-level integration test.

* feat(apigatewayv2): allow clearing an HTTP API CORS configuration

deleteCorsConfiguration unsets the optional CORS block on a stored API so
the response omits it rather than echoing a stale configuration.

* fix(apigateway): accept the AWS-native ImportApiKeys CSV format

The header validator required exactly `name,value,enabled` in lowercase and
read every row by fixed position. Real AWS ships `Name,Key,Description,
Enabled,UsagePlanIds`, so the CLI, SDKs and Terraform all took a 400 on their
first call. Columns are now resolved case-insensitively by name into an index
map, `value` is kept as an alias for `Key`, a missing or blank `Enabled`
defaults to true as AWS does, and rows shorter than the header no longer throw.

Imported keys are also created with generateDistinctId, because the CSV `Key`
column is the key VALUE and AWS generates the id separately — reusing the value
as the id let one row silently clobber an existing key and detach its usage
plan associations.

ImportApiKeys now reports warnings for real: a row whose key value duplicates an
earlier row in the same import raises one, and `failonwarnings=true` turns those
warnings into a BadRequestException instead of being ignored.

* fix(apigateway): honour the patchOperations envelope on UpdateModel and UpdateUsagePlan

Both handlers parsed the PATCH body as a flat map. Real AWS sends
`{"patchOperations":[{"op":"replace","path":"/description","value":"x"}]}`, so
the flat parse succeeded, matched nothing, and returned the untouched resource
with a 200 — a silent no-op. Both now walk the ops list the way the six sibling
endpoints in this controller already do.

UpdateModel supports /description, /schema and /contentType, and rejects /name
with a BadRequestException: AWS treats a model name as an immutable identifier.
That also removes the delete-then-put rename, which had no existence check on
the target key and so destroyed any model already using the new name.

UpdateUsagePlan supports /name, /description and add/remove of /apiStages as
"apiId:stage", covering what the flat handler could do. UsagePlan carries no
throttle or quota state, so those paths are left unsupported rather than faked.

UpdateAuthorizer now parses /authorizerResultTtlInSeconds before mutating
anything. A non-numeric value used to be written straight to the store, after
which serialisation threw on the PATCH and on every later GetAuthorizer and
GetAuthorizers for that resource — unrecoverable short of delete and recreate.

* fix(apigateway): reject duplicate sibling paths and bad parentId on resources

UpdateResource pointed at an unknown /parentId surfaced getResource's 404
"Invalid resource id specified", which reads as though the resource being
patched is missing; the `parent == null` guard beneath it was unreachable for
the same reason. AWS answers 400, so the lookup failure is now rethrown as a
BadRequestException naming the offending value.

Neither CreateResource nor UpdateResource checked for a sibling collision, so
two children of one parent could end up with the same path and request routing
became order-dependent. Both now go through a shared guard that raises
ConflictException (409) when another child of the effective parent already uses
that pathPart.

UpdateResource also stopped mutating as it goes. The store hands back live
objects, so applying ops in-place meant a later rejected op left the earlier
ones visible in memory; the patch is now resolved into pending parentId and
pathPart values, validated, and only then applied.

* style(apigateway): put HttpHeaders first in deleteAuthorizer

Every other handler in the controller takes @Context HttpHeaders as its first
parameter. No behaviour change.

* fix(apigateway): answer BadRequestException for a malformed patchOperations envelope

The PATCH handlers parsed the envelope with convertValue(node, List.class)
inside a catch that only covered IOException. convertValue throws
IllegalArgumentException, which no mapper handles, so a non-array
patchOperations returned 500 instead of the modelled BadRequestException.
The raw List.class conversion also deferred a structured operation value
into the service layer as a ClassCastException, a second 500.

Extract one parsePatchOperations helper that converts through a
TypeReference<List<Map<String, String>>> and widens the catch, so scalar
values coerce and structured ones are rejected at the boundary.

* fix(apigateway): dispatch ImportApiKeys on mode, not on media type

ImportApiKeys was annotated @Consumes("text/csv"), but botocore sends the
operation with no Content-Type header at all — only Accept: application/json.
A request with no Content-Type is application/octet-stream to JAX-RS, so it
never matched, and fell through to the sibling CreateApiKey handler, which
fed the CSV body to the JSON parser and answered a spurious
BadRequestException. Every existing test hid this by setting text/csv
explicitly, a header no client sends.

Fold both operations into one POST /apikeys handler that consumes any media
type and tells them apart by the mode query parameter, the way AWS does, and
cover it with a raw-client case that sends no Content-Type.

* docs(apigateway): document the operations this branch added

The branch added 13 v1 management operations and DeleteCorsConfiguration on
v2 without touching docs, and the Not Implemented list still named
UpdateAuthorizer, DeleteAuthorizer, ImportApiKeys, GetUsagePlan,
UpdateUsagePlan and UpdateModel as absent. GetDeployment and DeleteDeployment
were already implemented but had never been listed either.

api-gateway.md is hand-maintained — ApiGatewayController is a REST controller
and is not registered in tools/docs/services.yaml — so the tables are updated
by hand and the index counts follow the tables: v1 64 -> 79, v2 48 -> 49.
Also record how CreateApiKey and ImportApiKeys share POST /apikeys.

* fix(apigateway): extend the patchOperations boundary parse to the inherited handlers

Six PATCH handlers predate this branch and still parsed the envelope with
convertValue(node, List.class) inside an IOException-only catch, so
updateRestApi, updateResource, updateMethod, updateIntegration, updateStage
and updateApiKey kept answering 500 for a malformed envelope while the eight
handlers this branch added answered 400. A reviewer would rightly ask why
only some of the surface agrees with AWS.

This is a deliberate scope extension beyond the audit's finding: point all
six at the existing parsePatchOperations helper so every PATCH operation on
the service shares one boundary contract. updateAccount stays as it is — it
validates each operation itself and already raises a modelled 400.

* docs(apigatewayv2): correct the VPC Link operations, which are implemented

The v2 Not Implemented list named all five VPC Link operations as absent, but
CreateVpcLink, GetVpcLink, GetVpcLinks and DeleteVpcLink have been routed on
/v2/vpclinks and backed by ApiGatewayV2Service since before this branch. Only
UpdateVpcLink is genuinely missing — there is no PATCH route for it.

Verified each claimed route against ApiGatewayController before editing. Adds
the VPC Links row the v2 table never had and carries the four operations into
the index count: 49 -> 53.

* fix(apigateway): enforce the modelled op enum on patchOperations

Botocore models PatchOperation.op as an enum of add, remove, replace,
move, copy and test. The boundary parse read the envelope's shape but
never the op value, and the handlers behind it disagree about what to do
with an unrecognised one: UpdateModel throws, UpdateApiKey and UpdateStage
skip it. On the skipping handlers an unmodelled op was answered 200 with
the resource untouched, which reads to the caller as an applied patch.

Check op against the enum in parsePatchOperations, the boundary this
branch already made responsible for the envelope on every PATCH handler.
The set is the model's, not the intersection of what the handlers
implement: whether a handler supports move is its own business, but a
value outside the enum should never reach one.

* fix(apigateway): reject a null element in the patchOperations envelope

parsePatchOperations silently skipped a null element in the patchOperations
array instead of rejecting it. Several handlers that predate the shared
boundary parse (updateRestApi, updateStage, updateApiKey, updateMethod) have
no null guard of their own and call op.get("op") directly, so a null element
reached them as an unhandled NullPointerException -- a 500 instead of AWS's
modelled BadRequestException.

Reject the null at the boundary all handlers already share, the same place
that already validates the op enum.

* fix(apigateway): apply patchOperations atomically instead of partially

updateAuthorizer, updateUsagePlan, updateRequestValidator, updateModel,
updateDomainName and updateBasePathMapping mutated the live stored object as
each op was validated. The store hands back live objects (no defensive
copy), so a valid op followed by an invalid one left the valid op's change
visible even though the request answered 400 -- the same partial-apply bug
already fixed for updateResource in an earlier commit on this branch, which
established the fix: resolve every op into pending local values, validate
the whole list, and only mutate the stored object once the patch is known
to be entirely good.

Each handler also now rejects a null patchOperations element explicitly, on
top of the shared boundary's own rejection, matching the defensive style
already used by updateRequestValidator and updateModel before this change.

* fix(apigateway): translate a malformed ImportApiKeys CSV into BadRequestException

ApiKeyCsvParser.parse throws IllegalArgumentException on an unterminated
quoted field, but only AwsException is registered with an ExceptionMapper.
The unmapped exception escaped as a 500 instead of AWS's modelled 400,
letting a malformed import request past the error boundary entirely.

Catch the parser's IllegalArgumentException at the one call site and
translate it into the same BadRequestException every other CSV validation
failure in this method already raises.

* style(apigateway): brace the new conditionals this branch added

New single-line if statements in the domain-name serialization, CSV import
column/cell handling, and resource sibling-collision check violated the
repository's mandatory conditional-brace convention. No behaviour change.

* fix(apigateway): validate all UpdateIntegration patch ops before applying any

updateIntegration mutated the live stored integration inside the same loop that validated later operations, so a PATCH with a valid op followed by an unsupported path left the earlier op applied even though the request as a whole was rejected with 400.
2026-08-27 16:59:59 -04:00
Tedd 72dfa634f7 fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header (#2049)
* fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header

Integration tests for AWS type lambda integration with apigateway and duplicate content-type headers

Addressing Greptile review the qualifier is now preserved end to end and covered by tests

* fix(apigateway): resolving review feedback, adding in comment to LambdaArnUtils re lastIndexOf fallback, and updating DOCs with Line re v1 execution plane integration type behaviour
2026-08-24 17:24:09 -04:00
Michal Schreiber 74da157681 feat(apigatewayv2): support custom domain names and API mappings (#2390)
* feat(apigatewayv2): support custom domain names and API mappings

POST /v2/domainnames was not routed, so it matched the S3 controller's catch-all
and answered with an S3 XML error about multipart uploads, which an SDK
expecting JSON cannot deserialize. The same was true of the API mappings a
domain is used through.

Adds the eight actions over the records the REST endpoints already keep, since a
custom domain is one resource in AWS reachable through both APIs. A domain
created here is therefore visible to the v1 endpoints and resolves through the
Host-header routing that already exists:

- CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName
- CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping
- the mapping id is derived from what identifies the mapping, so it survives a
  restart and is the same id whichever API created it

Taken from a live AWS account rather than the service model alone, which the
model does not tell you:

- every domain reports RoutingMode API_MAPPING_ONLY and an ipv4 IpAddressType
- a create without exactly one configuration is "Invalid input. Expected one
  domain name configuration"
- a duplicate domain is BadRequestException, not a conflict — for the REST API
  too, so the shared code and the test that asserted 409 were both wrong
- deleting an API that a domain still maps to is refused: "Please remove all API
  mappings for the API from your custom domain names"
- an unknown domain is "Invalid domain name identifier specified"

Tags are stored and returned rather than dropped, which would have left
terraform with a diff it could never settle. Mutual TLS, ownership verification
certificates, routing rules and non-ipv4 address types are refused rather than
accepted and ignored, so nothing is answered with a domain that behaves
differently from the one that was asked for.

* fix(apigatewayv2): make api mapping ids unique and validate what a mapping points at

Five problems from review of the previous commit.

Mapping ids were derived by hashing the base path, so two keys sharing a Java
hash shared an id and a read or delete by that id picked between them. The base
path is encoded rather than hashed, which cannot collide.

An omitted mapping key and an explicit empty one produced two different records,
where the shared store keeps the root mapping under "(none)" and could no longer
find either from v1. Both spellings now canonicalise to the one record, and a
second attempt is the ConflictException AWS answers: "ApiMapping key already
exists for this domain name".

A mapping was accepted for an API or stage that does not exist, returning 201
for something that routes nowhere. Both are looked up first, and answer as AWS
does: "Invalid API identifier specified: <id>" and "Invalid stage identifier
specified".

The delete guard scanned only the caller's region, so an API could still be
deleted out from under a mapping made in another region. It scans every region,
since a mapping is keyed under the region of its domain rather than of its API.

A domainNameConfigurations entry that was not an object passed the size check and
then failed an unchecked cast, answering 500 instead of the AWS-shaped 400.

* fix(apigateway): canonicalise base paths on write, key mapping ids off what is stored

Canonicalising only where the v2 mapping id was derived left the collision it was
meant to remove: the store could hold "(none)", "/" and "" as separate records
that all mean the root, and folding them together at id time gave them one id for
a read or a delete to choose between.

Base paths are canonicalised where they are written instead, matching what reads
have always done. The store can no longer gain a second record meaning the root,
and a v1 mapping created as "" can now be read back as "", which it could not
before: the write kept the raw value while the read looked for the canonical one.

The id is derived from the path a record is stored under rather than its
canonical form, so state persisted before this change keeps one id per record
rather than several records sharing one. No endpoint can create such a record
now, so that property is asserted directly against the records deserialization
can restore.

* fix(apigateway): delete the mapping record that was selected, not its canonical twin

The v2 endpoints select a mapping by an id derived from the path its record is
stored under, then deleted it through the lookup that normalises the root. For a
record left under "/" or "" by state written before writes were canonicalised,
that deleted the canonical root instead and left the selected record in place.

Deletion by record now addresses the stored path exactly, so the record that
answered the lookup is the record that goes. The normalising delete stays for
callers that pass a key to look one up by, which is what the REST endpoint does.

* fix(apigatewayv2): identify a mapping by its stored key, not by the field it reports

BasePathMapping normalises an empty base path to "(none)" in its constructor, so
a record the old write path left under the key "" reports "(none)" from its own
field. Deriving the mapping id from that field gave it the canonical root's id,
and deleting by it removed the canonical root while leaving the record behind —
the collision the previous commit was meant to close, through the one door it
left open.

The service exposes mappings keyed by the base path each record is stored under,
and the v2 endpoints derive ids, resolve lookups and delete through that key. The
key is the only thing that identifies a record; the field can disagree with it.

Seeded through the storage backend the service uses, since no endpoint creates
such a record any more: the test asserts the two records keep separate ids, each
id resolves to its own record, and deleting one leaves the other.
2026-08-18 20:27:44 -04:00
Dixit R Jain 45bb37f1fb feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)
Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the
existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler,
instead of adding a second host filter.

- @connections (#1846): ApiGatewayExecuteApiHostFilter now also rewrites a WebSocket
  API's @connections management calls (.../{stage}/@connections/{id}) to the canonical
  /execute-api/{apiId}/{stage}/... route, behind the same disableExecuteApiEndpoint->404
  check. It previously bailed for non-HTTP APIs, so @connections on the execute-api host
  was swallowed by the S3 controller.
- $connect (#1871): WebSocketHandler accepts the execute-api host for the WS handshake
  and resolves the API region -- from the host's region label when present, else a
  cross-region apiId lookup (ApiGatewayV2Service.resolveApiRegion) -- fixing the 403 for
  APIs created in a non-default region.
- Widen the filter host regex to accept the region-bearing AWS form
  ({apiId}.execute-api.{region}.localhost|amazonaws.com) alongside Floci's regionless
  built-in suffixes (.execute-api.localhost.floci.io / .localstack.cloud).
- Fix RegionResolver.resolveRegionFromHost to treat only a real region label as the
  region and return null for the built-in suffixes -- the old pattern parsed "localhost"
  as the region and broke the lookup.
- Remove the separate ExecuteApiSubdomainFilter; host parsing is shared via
  ApiGatewayExecuteApiHostFilter.extractApiId.
- Update docs and add Java unit + Node SDK compatibility coverage for both host forms.

Closes #1871
Closes #1846
2026-08-13 14:40:50 -04:00
Alex BannaandAlexander Banna 33ba5ac59c feat(apigateway): route execute-api hostnames for HTTP APIs (#2054)
* feat(apigateway): route execute-api hostnames for HTTP APIs

* fix(apigateway): disambiguate execute-api routing

* fix(apigateway): make the execute-api host filter idempotent

Host matching alone cannot tell whether a request has already been rewritten,
because the Host header still names the execute-api subdomain afterwards. If any
other filter rewrites first, this one rewrites again and produces
/execute-api/{apiId}/execute-api/{apiId}/... which routes to nothing.

Bail out when the path is already under /execute-api/. This keeps the filter
correct regardless of where it sits in the provider chain.

* fix(apigateway): enforce disableExecuteApiEndpoint on the direct execute-api path

The setting was only checked in ApiGatewayExecuteApiHostFilter, which sees the
host-based route (*.execute-api.localhost.*). A request to the direct
/execute-api/{apiId}/{stageName}/... form reaches dispatchV2 without passing the
filter, so the same disabled HTTP API answered 403 by host and 200 by path.

Move the check into dispatchV2, the single choke point both entry points funnel
through, so they cannot disagree. A missing API is left to findMatchingRoute's 404
rather than reported from here.

* test(dynamodb): retain Quarkus port for cleanup

* fix(apigateway): match disabled HTTP API response

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:26:24 -04:00
Dennis O'Connor b6765b3056 feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey

Adds the two missing API key lifecycle operations for API Gateway v1:

- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
  operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
  absent

Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.

Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.

* feat(apigateway): persist and return UsagePlan tags

CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.

A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.

The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.

* fix(apigateway): treat an absent generateDistinctId as id == value

CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.

A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.

Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.

* refactor(apigateway): route UsagePlan custom IDs through ReservedTags

The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.

Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.

Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.

* fix(apigateway): stop deleted and disabled API keys authenticating

A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:

- DeleteApiKey removed the key from apiKeyStore but left every usage
  plan association behind, so a deleted key stayed listed by
  GetUsagePlanKeys and kept being recognised on the data plane. It now
  detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
  saying it matched enabled keys, so patching /enabled to false changed
  nothing about request handling. It now requires the key to still exist
  and be enabled, via a new non-throwing findApiKey lookup.

Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
2026-08-12 00:02:32 -04:00