Commit Graph
18 Commits
Author SHA1 Message Date
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
Hector VenturaandMarcel Herhold 02385da37b feat(apigateway): support floci:override-id for v1 and v2 (#2045)
* feat(apigateway): support floci:override-id for v1 and v2

API IDs were generated randomly, so endpoint URLs changed on every
recreate. v1 accepted an undocumented `_custom_id_` tag and echoed it
back as a normal tag; v2 had no override at all. Other services already
pin IDs through the reserved `floci:override-id` tag.

Both CreateRestApi and CreateApi now accept `floci:override-id`, routed
through ReservedTags.getOverride so the value is validated rather than
used verbatim: non-blank, no whitespace or control characters, and no
`/`, `?`, `#`, since those break the endpoint URL. Override keys are
consumed rather than stored, so they no longer appear in the returned
tags, and supplying either key to TagResource is rejected because an ID
cannot change after creation.

`_custom_id_` keeps working as a deprecated fallback and is now stripped
the same way; `floci:override-id` wins when both are present so callers
can set both during a migration. The key stays API Gateway specific: the
shared strip and reject helpers are untouched, so KMS and Cognito still
treat `_custom_id_` as an ordinary tag.

Error code is BadRequestException, declared by CreateRestApi, CreateApi
and TagResource on both services. The shared reject helper's
ValidationException is declared by neither, which is why API Gateway gets
its own guard rather than reusing it.

Closes #1593

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>

* fix(apigateway): reject duplicate override ids with ConflictException

CreateRestApi (v1) and CreateApi (v2) now return 409 ConflictException
when the resolved API id already exists in the region, instead of
silently overwriting the existing API, matching how KMS and Cognito
treat duplicate override ids.

---------

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
2026-07-29 23:40:27 -05:00
Prakhar Kapoor 15720e2ee6 feat(apigateway): implement account management endpoints and models (#867)
* feat(apigateway): implement account management endpoints and models
* feat(apigateway): enhance patch operation validation and update throttle settings defaults
* feat(api-gateway): add account management operations to API Gateway v1
* feat(api-gateway): add compatibility tests for account management and update logic
* feat(api-gateway): add missing import for assertions in account compatibility test
2026-05-17 23:42:09 -05:00
Hector Ventura 9e35046647 Docs/enviroment instead yml (#764)
* docs: moving all config to env instead of yml
* docs: sync with main and new features
* docs: reverting docker-compose.yml
2026-05-10 11:53:31 -05:00
Dixit R Jain 3ae5c7b467 feat(apigatewayv2): Add WebSocket data-plane support (#712)
* feat: implement API Gateway v2 WebSocket data-plane support Implement full WebSocket data-plane for API Gateway v2, including: - Real WebSocket connection handling via Vert.x (ws://localhost:4566/ws/{apiId}/{stage}) - $connect/$disconnect/$default route lifecycle with Lambda integration - Custom route selection via routeSelectionExpression ($request.body.{field}) - @connections management API (POST/GET/DELETE) for server-to-client messaging - Lambda REQUEST authorizer support on $connect with identity source validation - Stage variable substitution in integration URIs - Multiple integration types: AWS_PROXY, AWS (VTL), HTTP_PROXY, HTTP (VTL), MOCK - Route response selection expression for bidirectional messaging - Binary frame support (isBase64Encoded: true) - 128 KB payload size limit enforcement (frames and @connections POST) - 10-minute idle timeout and 2-hour max connection duration - GoneException (410) for disconnected connections - $connect response headers propagation - Server-initiated close via @connections DELETE (skips $disconnect Lambda) Also includes: - Refactored LambdaArnUtils.extractFunctionNameFromUri as shared utility - Extended Authorizer/Integration/Stage models with new fields - Comprehensive Java integration tests (WebSocket lifecycle, routing, auth, etc.) - Node.js SDK compatibility tests using ws client and @aws-sdk/client-apigatewaymanagementapi - Updated documentation with full feature matrix

* test(apigatewayv2): support custom WebSocket endpoint via env var

- Update wsUrl helper to read FLOCI_ENDPOINT environment variable
- Convert http/https schemes to ws/wss for WebSocket compatibility
- Strip trailing slashes from endpoint URL for consistent formatting
- Enable testing against non-localhost endpoints for CI/CD flexibility

* fix: use AwsErrorResponse for @connections API error responses

Replace raw JSON string literals in handlePostToConnection,
handleGetConnectionInfo, and handleDeleteConnection with the
project-standard AwsErrorResponse record, which serialises to
the correct {"__type": ..., "message": ...} wire shape.

* fix: simplify extractFunctionNameFromUri using AwsArnUtils.parse

Adopt AwsArnUtils.parse() as the core of the implementation per
reviewer suggestion. One addition beyond the suggested snippet:
the API Gateway v1 integration URI format embeds a Lambda ARN
inside an apigateway ARN (resource starts with 'path/.../functions/'),
so we detect that pattern and recurse on the embedded ARN before
applying the standard function-name extraction. All 43
LambdaArnUtilsTest cases pass, including the API Gateway v1 style URI.
2026-05-08 17:15:35 -05:00
Dixit R Jain 8fe2bf4c97 feat(apigatewayv2): add WebSocket API support, Update ops, Route/Integration Responses, Models, and Tagging (#682)
Closes #526

Add 27 new API Gateway v2 operations (21 → 48 total):

- WebSocket protocol: CreateApi with WEBSOCKET, wss:// endpoints,
  routeSelectionExpression validation, routeResponseSelectionExpression
- Update operations: UpdateApi, UpdateRoute, UpdateIntegration,
  UpdateAuthorizer, UpdateStage, UpdateDeployment
- Route Responses: full CRUD (5 ops)
- Integration Responses: full CRUD (5 ops)
- Models: full CRUD (5 ops)
- Tagging: TagResource, UntagResource, GetTags
2026-05-02 07:53:13 -05:00
TiM a32b7f1f3b docs: comprehensive audit sweep + CHANGELOG backfill (1.1.0-1.5.2) (#326)
CHANGELOG.md was empty for the 1.1.0-1.5.2 release cycle and service docs
had drifted from code behaviour. This sweep reconciles docs against the
current codebase on upstream/main.

- Backfill CHANGELOG.md for 1.1.0 through 1.5.2 from git history
- Correct exact operation counts in docs/services/index.md: S3 (~30 -> 58),
  Lambda (~25 -> 30), API Gateway v1 (~24 -> 62). Counts now come from the
  actual dispatch handlers rather than @Path annotation counts.
- Rewrite README "Supported Services" table to drop per-service op counts
  (they drift too fast); point readers at docs/services/index.md
- Update 24 service docs for accuracy, add "Not Implemented" sections
  where relevant (s3.md, lambda.md, api-gateway.md)
- Refresh configuration and getting-started docs
- Add EventBridge Scheduler and AppConfig to mkdocs nav
- Add AppConfig / AppConfigData rows to README and services index
  following the 1.5.2 upstream release
2026-04-10 10:52:34 -05:00
Hector Ventura 61433f59ab firt commit 2026-03-15 17:43:56 -05:00