* 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>
17 KiB
API Gateway
Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs).
Custom API IDs
API IDs are generated randomly, which means endpoint URLs change every time you recreate an API. To pin
one, pass the reserved floci:override-id tag on creation and Floci uses its value as the API ID. This
works for both v1 (CreateRestApi) and v2 (CreateApi), and matches the tag other services such as KMS
and Cognito already use.
aws apigateway create-rest-api \
--name my-api \
--tags '{"floci:override-id":"my-fixed-id","env":"test"}' \
--endpoint-url http://localhost:4566
# the API is now reachable at the stable id "my-fixed-id"
The override key is consumed rather than stored, so it never appears in the tags the API returns. Any
other tags in the same request are kept. Because an ID cannot change after creation, supplying either
override key to TagResource is rejected with BadRequestException.
Values must be non-blank and must not contain whitespace, control characters, or /, ?, #, since
those would break the endpoint URL. An invalid value is rejected with BadRequestException.
Creating a second API with an override ID that already exists in the region is rejected with
ConflictException instead of overwriting the existing API, matching how KMS and Cognito treat
duplicate override IDs.
Note
API Gateway previously used a
_custom_id_tag for this. It still works so existing setups keep running, and it is now stripped from the returned tags the same way, but it is deprecated: preferfloci:override-id. If both are present,floci:override-idwins, which lets you set both during a migration. The_custom_id_key is API Gateway specific and is not reserved for any other service.
API Gateway v1 (REST APIs)
Protocol: REST JSON
Endpoint: http://localhost:4566/restapis/...
Supported Operations
| Category | Operations |
|---|---|
| APIs | CreateRestApi, ImportRestApi, PutRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi |
| Resources | CreateResource, GetResource, GetResources, UpdateResource, DeleteResource |
| Methods | PutMethod, GetMethod, UpdateMethod, DeleteMethod |
| Method Responses | PutMethodResponse, GetMethodResponse, DeleteMethodResponse |
| Integrations | PutIntegration, GetIntegration, UpdateIntegration, DeleteIntegration |
| Integration Responses | PutIntegrationResponse, GetIntegrationResponse, UpdateIntegrationResponse, DeleteIntegrationResponse |
| Deployments | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
| Stages | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
| Authorizers | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer |
| API Keys | CreateApiKey, ImportApiKeys, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey |
| Usage Plans | CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan |
| Usage Plan Keys | CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey |
| Request Validators | CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator |
| Models | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| Domain Names | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
| Base Path Mappings | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping |
| Account | GetAccount, UpdateAccount |
| Tags | TagResource, UntagResource, GetTags (ListTagsForResource) |
API Key Behaviour Notes
CreateApiKey and ImportApiKeys share one route
Both operations are POST /apikeys, and AWS tells them apart by the query string, not by
Content-Type: ImportApiKeys carries ?mode=import&format=csv and a CSV body, CreateApiKey
carries no query parameters and a JSON body. The SDKs send ImportApiKeys with no Content-Type
header at all, so Floci accepts any media type on this route and dispatches on mode.
The CSV header row is addressed by name, not position. AWS's own column set is
Name,Key,Description,Enabled,UsagePlanIds; a Key column is required, and a missing Enabled
column defaults to true. Duplicate key values are reported in the warnings array, and
failonwarnings=true turns those warnings into a BadRequestException.
generateDistinctId
Controls whether the key's id and value fields are distinct. AWS's undocumented default behaviour is that they are the same string unless generateDistinctId=true is explicitly requested.
generateDistinctId |
id |
value |
|---|---|---|
| absent (default) | same as value |
caller-supplied value, or a generated UUID-derived string |
false |
same as value |
caller-supplied value, or a generated UUID-derived string |
true |
opaque short token (shortId) |
caller-supplied value, or a generated UUID-derived string |
When generateDistinctId is absent or false, a single shared string is used for both id and value. If the caller supplies a value in the request body, that string is used for both; otherwise a UUID-derived string is generated and assigned to both.
When generateDistinctId=true, id is set to an opaque short token independent of value.
Revocation
DeleteApiKey detaches the key from every usage plan before removing it, matching AWS. A usage plan key
stores its own copy of the key value, so without that sweep a deleted key would stay listed by
GetUsagePlanKeys and keep being recognised on the data plane.
requestContext.identity.apiKey is only populated when the x-api-key header matches a key that still
exists and has enabled set to true, so disabling a key through UpdateApiKey takes effect
immediately.
Note
Floci does not implement the
apiKeyRequiredgate on methods, so a request carrying an unknown, disabled, or deleted key is still executed — it simply arrives with a nullidentity.apiKeyrather than being rejected with403.
Not Implemented
These management-plane operations have no handler in v1. Calls will return 404 or an error:
- Authorizer testing:
TestInvokeAuthorizer - Model templates:
GetModelTemplate - Gateway Responses (the entire family:
PutGatewayResponse,GetGatewayResponse, etc.) - Documentation parts and versions (the entire family, 10 operations)
- VPC Links (5 operations)
- Client Certificates (5 operations)
GetExport/ImportDocumentationParts
The execute plane (actual proxied HTTP traffic via /restapis/{id}/{stage}/_user_request_/…) is implemented separately and is not counted as management-plane operations. It supports AWS_PROXY (Lambda proxy), AWS (Lambda with VTL request/response templates), and MOCK integrations; other integration types return an error.
Examples
export AWS_ENDPOINT_URL=http://localhost:4566
# Create a REST API
API_ID=$(aws apigateway create-rest-api \
--name "My API" \
--query id --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Get the root resource
ROOT_ID=$(aws apigateway get-resources \
--rest-api-id $API_ID \
--query 'items[?path==`/`].id' --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Create a resource
RESOURCE_ID=$(aws apigateway create-resource \
--rest-api-id $API_ID \
--parent-id $ROOT_ID \
--path-part users \
--query id --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Add a GET method
aws apigateway put-method \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--authorization-type NONE \
--endpoint-url $AWS_ENDPOINT_URL
# Add a Lambda integration
aws apigateway put-integration \
--rest-api-id $API_ID \
--resource-id $RESOURCE_ID \
--http-method GET \
--type AWS_PROXY \
--integration-http-method POST \
--uri "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:my-function/invocations" \
--endpoint-url $AWS_ENDPOINT_URL
# Deploy to a stage
aws apigateway create-deployment \
--rest-api-id $API_ID \
--stage-name dev \
--endpoint-url $AWS_ENDPOINT_URL
# Call the deployed API
curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users
Usage Plan Tags and Custom IDs
Usage plans accept arbitrary tags, and the same reserved floci:override-id tag used for
custom API IDs pins the plan's id:
# Create a usage plan with a custom ID and additional tags
aws apigateway create-usage-plan \
--name "my-plan" \
--tags '{"floci:override-id":"my-plan-id","env":"staging"}' \
--endpoint-url $AWS_ENDPOINT_URL
# The plan is now accessible at its custom ID
aws apigateway get-usage-plans --endpoint-url $AWS_ENDPOINT_URL
The override key is validated and consumed exactly as it is for CreateRestApi, so it never appears in
the tags a usage plan returns. The deprecated _custom_id_ key is still honored on create for existing
setups, and floci:override-id wins when both are present. Every other tag is persisted and returned in
CreateUsagePlan and GetUsagePlans responses.
Configuration
| Variable | Default | Description |
|---|---|---|
FLOCI_SERVICES_APIGATEWAY_ENABLED |
true |
Enable or disable API Gateway v1 (REST APIs) |
FLOCI_SERVICES_APIGATEWAYV2_ENABLED |
true |
Enable or disable API Gateway v2 (HTTP and WebSocket APIs) |
API Gateway v2 (HTTP and WebSocket APIs)
Protocol: REST JSON
Endpoint: http://localhost:4566/v2/apis/...
Both HTTP and WebSocket protocol types are fully supported, including the WebSocket data-plane (real connection handling, message routing, and the @connections management API).
HTTP API data-plane
API Gateway v2 advertises HTTP APIs through Floci's local execute-api domain:
curl http://{apiId}.execute-api.localhost.floci.io:4566/{stageName}/{path}
When an API has a $default stage, callers may omit the stage segment:
curl http://{apiId}.execute-api.localhost.floci.io:4566/{path}
APIs created or updated with disableExecuteApiEndpoint reject requests to
this default hostname with 404 Not Found, matching AWS HTTP API behavior.
Supported Operations
| Category | Operations |
|---|---|
| APIs | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, DeleteCorsConfiguration, ImportApi, ReimportApi |
| Routes | CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute |
| Route Responses | CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse |
| Integrations | CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration |
| Integration Responses | CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse |
| Authorizers | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer |
| Stages | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
| Deployments | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
| Models | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| Domain Names | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName |
| API Mappings | CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping |
| VPC Links | CreateVpcLink, GetVpcLink, GetVpcLinks, DeleteVpcLink |
| Tags | TagResource, UntagResource, GetTags |
WebSocket Data-Plane
Floci supports real WebSocket connections for API Gateway v2 WebSocket APIs. Clients connect via:
ws://localhost:4566/ws/{apiId}/{stageName}
Supported Features
| Feature | Status |
|---|---|
$connect route with Lambda integration |
✅ |
$disconnect route with Lambda integration |
✅ |
$default route (fallback) |
✅ |
Custom routes via routeSelectionExpression |
✅ |
| Route response selection expression | ✅ |
Lambda REQUEST authorizer on $connect |
✅ |
| Identity source validation (header/querystring) | ✅ |
@connections POST (send message to client) |
✅ |
@connections GET (get connection info) |
✅ |
@connections DELETE (disconnect client) |
✅ |
| Stage variable substitution in integration URIs | ✅ |
| AWS_PROXY integration (Lambda) | ✅ |
| AWS integration (Lambda with VTL templates) | ✅ |
| HTTP_PROXY integration | ✅ |
| HTTP integration (with VTL templates) | ✅ |
| MOCK integration | ✅ |
| GoneException (410) for disconnected connections | ✅ |
Binary frame support (isBase64Encoded: true) |
✅ |
$connect response headers propagation |
✅ |
| 128 KB payload size limit enforcement | ✅ |
| 10-minute idle timeout | ✅ |
| 2-hour max connection duration | ✅ |
@connections Management API
The @connections API allows server-side code (e.g., Lambda functions) to send messages to connected clients, retrieve connection metadata, or disconnect clients:
POST /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Send message
GET /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Get connection info
DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconnect client
Behavior Notes
-
Connection URL: Floci accepts the AWS-style execute-api host as well as the path form. All of these reach the same WebSocket API:
ws://{apiId}.execute-api.{region}.localhost:4566/{stage}— region-bearing, mirroring AWS'swss://{api-id}.execute-api.{region}.amazonaws.com/{stage}ws://{apiId}.execute-api.localhost.floci.io:4566/{stage}— Floci's built-in execute-api domain (regionless; the region is resolved by an apiId lookup)ws://localhost:4566/ws/{apiId}/{stage}— the explicit path form
The
@connectionsmanagement API is likewise reachable on the execute-api host (http://{apiId}.execute-api.{region}.localhost:4566/{stage}/@connections/{connectionId}). -
Idle timeout: 10 minutes (matching AWS default). Not configurable per-API.
-
Max connection duration: 2 hours (matching AWS). Connections are closed automatically.
-
Payload size limit: 128 KB per frame (matching AWS). Oversized messages receive an error frame.
Not Implemented
ExportApi,UpdateDomainName,UpdateApiMappingUpdateVpcLink— the other four VPC Link operations are implemented; see the table above
Examples
export AWS_ENDPOINT_URL=http://localhost:4566
# Create an HTTP API
API_ID=$(aws apigatewayv2 create-api \
--name "My HTTP API" \
--protocol-type HTTP \
--query ApiId --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Create a Lambda integration
INTEGRATION_ID=$(aws apigatewayv2 create-integration \
--api-id $API_ID \
--integration-type AWS_PROXY \
--integration-uri "arn:aws:lambda:us-east-1:000000000000:function:my-function" \
--payload-format-version 2.0 \
--query IntegrationId --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Create a route
aws apigatewayv2 create-route \
--api-id $API_ID \
--route-key "GET /users" \
--target "integrations/$INTEGRATION_ID" \
--endpoint-url $AWS_ENDPOINT_URL
# Deploy
aws apigatewayv2 create-stage \
--api-id $API_ID \
--stage-name dev \
--auto-deploy \
--endpoint-url $AWS_ENDPOINT_URL
WebSocket API
export AWS_ENDPOINT_URL=http://localhost:4566
# Create a WebSocket API
WS_API_ID=$(aws apigatewayv2 create-api \
--name "My WebSocket API" \
--protocol-type WEBSOCKET \
--route-selection-expression '$request.body.action' \
--query ApiId --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Create a Lambda integration
WS_INTEGRATION_ID=$(aws apigatewayv2 create-integration \
--api-id $WS_API_ID \
--integration-type AWS_PROXY \
--integration-uri "arn:aws:lambda:us-east-1:000000000000:function:my-ws-handler" \
--query IntegrationId --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Create $connect, $disconnect, and $default routes
aws apigatewayv2 create-route \
--api-id $WS_API_ID \
--route-key '$connect' \
--target "integrations/$WS_INTEGRATION_ID" \
--endpoint-url $AWS_ENDPOINT_URL
aws apigatewayv2 create-route \
--api-id $WS_API_ID \
--route-key '$disconnect' \
--target "integrations/$WS_INTEGRATION_ID" \
--endpoint-url $AWS_ENDPOINT_URL
aws apigatewayv2 create-route \
--api-id $WS_API_ID \
--route-key '$default' \
--route-response-selection-expression '$default' \
--target "integrations/$WS_INTEGRATION_ID" \
--endpoint-url $AWS_ENDPOINT_URL
# Deploy
aws apigatewayv2 create-stage \
--api-id $WS_API_ID \
--stage-name prod \
--endpoint-url $AWS_ENDPOINT_URL
# Connect via WebSocket (using wscat or any WebSocket client)
# wscat -c ws://localhost:4566/ws/$WS_API_ID/prod
# Send a message to a connected client via @connections API
# curl -X POST http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID \
# -d "Hello from server"
# Get connection info
# curl http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID
# Disconnect a client
# curl -X DELETE http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID