API Gateway
OCI API Gateway, API version 20190501 (SDK package apigateway, clients GatewayClient,
DeploymentClient and WorkRequestsClient, CLI oci api-gateway). Real OCI serves the management
API on apigateway.{region}.oci.{domain}; floci-oci serves it on port 4599 under /20190501.
Each gateway also gets a hostname, and requests to that hostname are the data plane: floci-oci
routes them through the gateway's deployments to stock responses, HTTP backends and Functions. No
container is started; the service runs in-process and has no mock flag.
Supported operations
| Area | Operations |
|---|---|
| Gateways | CreateGateway, GetGateway, ListGateways, UpdateGateway, DeleteGateway, ChangeGatewayCompartment, AddGatewayLock, RemoveGatewayLock |
| Deployments | CreateDeployment, GetDeployment, ListDeployments, UpdateDeployment, DeleteDeployment, ChangeDeploymentCompartment, AddDeploymentLock, RemoveDeploymentLock |
| Work requests | ListWorkRequests, GetWorkRequest, ListWorkRequestErrors, ListWorkRequestLogs, CancelWorkRequest |
| Data plane | Any method on <gateway hostname>/<pathPrefix>/<route path> |
APIs, SDKs, certificates, usage plans and subscribers are not implemented.
Wire notes
- Create answers with the gateway or deployment, its
etagandopc-work-request-id. Update, Delete and ChangeCompartment answer202with onlyopc-work-request-id. AddLock and RemoveLock answer with the resource and itsetag. - Writes finish before they return. A gateway or deployment is
ACTIVEas soon as it is created, and its work request isSUCCEEDEDwithtimeFinishedset. The work request's resource hasentityTypegatewayordeploymentandactionTypeCREATED,UPDATEDorDELETED, which is what the Terraform provider matches. A compartment change isUPDATED. - Delete keeps the resource with
lifecycleStateDELETED, the state Terraform waits for. A deleted resource still answers Get, refuses every other operation with404 NotAuthorizedOrNotFound, and leaves the lists unlesslifecycleState=DELETEDis asked for. - Lists are
{"items": [...]}collections paged withlimit,pageandopc-next-page.compartmentIdis required and must be a known compartment. They sort bytimeCreated(the default) ordisplayName,DESCby default. ListWorkRequests returns WorkRequestSummary items, which carry the OCID asworkRequestIdand no resources. - Gateway create requires
compartmentId,endpointType(PUBLICorPRIVATE) andsubnetId. The subnet and thenetworkSecurityGroupIdsmust exist in Networking (otherwise400 RelatedResourceNotAuthorizedOrNotFound), and a subnet or NSG a gateway uses cannot be deleted.certificateId,responseCacheDetails,caBundles,ipModeand the address configurations are stored and returned as sent;ipModedefaults toIPV4andresponseCacheDetailsto{"type": "NONE"}.ipAddressesis[{"ipAddress": "127.0.0.1"}]. - Deployment create requires
gatewayId,compartmentId,pathPrefixandspecification. The gateway must exist and not be deleted (400 RelatedResourceNotAuthorizedOrNotFound).pathPrefixstarts with/. Thespecificationis stored and returned exactly as sent, so every policy reads back unchanged. - Specification checks. Each route needs a
pathstarting with/and abackendwhosetypeis one of the six ApiSpecificationRouteBackend types oci-go-sdk knows (HTTP_BACKEND,ORACLE_FUNCTIONS_BACKEND,STOCK_RESPONSE_BACKEND,DYNAMIC_ROUTING_BACKEND,OAUTH2_LOGIN_BACKEND,OAUTH2_LOGOUT_BACKEND). Any other type, an unknown method, a parameter that is not a whole path segment, or a wildcard that is not the last segment is400 InvalidParameter. A missingurl,functionIdorstatusis400 MissingParameter. - Authentication checks.
requestPolicies.authenticationmust have atypeofJWT_AUTHENTICATION,TOKEN_AUTHENTICATIONorCUSTOM_AUTHENTICATION, and the fields oci-go-sdk marks mandatory:issuers,audiencesandpublicKeysfor JWT,validationPolicyfor TOKEN,functionIdfor CUSTOM,urifor aREMOTE_JWKSkey set,kidandformatfor each static key. A static key must parse (an RSA JSON Web Key withnande, or a PEM public key or certificate), andmaxClockSkewInSecondsmust be between 0 and 120. A route'srequestPolicies.authorizationmust beANONYMOUS,AUTHENTICATION_ONLYorANY_OF, andANY_OFneedsallowedScope. A missing field is400 MissingParameter, anything else400 InvalidParameter. - Locks. A
FULLlock refuses every change and the delete, aDELETElock only the delete, with409 ResourceLocked, unless the request setsisLockOverride=true. - Validation. An update or lock request is checked in full before anything changes: a
400leaves the resource, its specification and its etag as they were. - Conflicts. A second deployment with the same
pathPrefixon one gateway, and deleting a gateway that still has deployments, are409 Conflict.
Data plane
A gateway's hostname is <label>.apigateway.<region>.oci.localhost.floci.io, where the label is
26 lowercase base32 characters derived from the gateway's OCID. It has the shape OCI documents,
<gatewayidentifier>.apigateway.<region-identifier>.oci.customer-oci.com, with floci-oci's
domain, which resolves to 127.0.0.1. A deployment's endpoint is
http://<hostname>:4599<pathPrefix> (the scheme and port floci-oci was reached on).
floci-oci tells a data-plane request apart by its Host header alone: any host that starts with
<label>.apigateway.<region>. is routed to that gateway, whatever the domain after it. So a client
that cannot resolve localhost.floci.io can call floci-oci by any address and send the gateway's
hostname as Host. Data-plane requests are never signed and pass even with
FLOCI_OCI_AUTH_REQUIRE_SIGNATURE=true. A route such as /v2/... stays on the gateway and never
reaches the Container Registry's /v2 API.
A request goes to the gateway's ACTIVE deployment with the longest pathPrefix that matches,
then to the most specific route of its specification: segment by segment, a literal beats
{param}, and {param} beats a trailing {param*}. A route with no methods accepts every
method, as does ANY. No match is 404 and a path that matches only with another method is 405.
| Backend | What floci-oci does |
|---|---|
STOCK_RESPONSE_BACKEND |
Answers with the stored status, headers and body |
HTTP_BACKEND |
Forwards the method, headers and body to url, after substituting ${request.path[...]}, ${request.query[...]}, ${request.headers[...]}, ${request.auth[...]} and ${request.host[...]}; the request's query string is passed on. Hop-by-hop headers, the fixed RFC 7230 list and any header a Connection header names, are dropped both ways. A DELETE forwards its body like POST, PUT and PATCH. connectTimeoutInSeconds, sendTimeoutInSeconds, readTimeoutInSeconds and isSslVerifyDisabled apply. An unreachable backend is 502, a timeout 504 |
ORACLE_FUNCTIONS_BACKEND |
Invokes the function with the request in Fn's HTTP trigger encoding (Fn-Http-Method, Fn-Http-Request-Url, Fn-Http-H-*); the function's Fn-Http-Status and Fn-Http-H-* set the status and headers of the answer. A missing function, a failed invocation or a disabled Functions service is 502. In Functions mock mode the answer is the synthetic {"message": "mock invocation of <name>"} |
DYNAMIC_ROUTING_BACKEND, OAUTH2_LOGIN_BACKEND, OAUTH2_LOGOUT_BACKEND |
Stored, but the route answers 501 |
The context variable syntax comes from the API Gateway docs
(local/oracle/oci-docs/apigw-context-variables.md): a key the table does not hold becomes the
empty string, only the first value of a repeated parameter is used, and encoded values are
substituted as they arrived. request.auth holds what the authentication policy saved (see below)
and request.host the request's Host header. request.body is only passed to authorizer
functions. request.cert, request.subdomain and request.usage_plan are not filled and always
substitute the empty string.
CORS policies are enforced: a route's requestPolicies.cors replaces the deployment's. A
preflight (OPTIONS with Origin and Access-Control-Request-Method) takes the policy of the
route a request with the requested method would reach, or the deployment's when no route serves
that method; to an allowed origin it answers 204 with Access-Control-Allow-Origin, -Allow-Methods, -Allow-Headers, -Max-Age
and -Allow-Credentials from the policy; an origin the policy does not allow gets a 204 with no
CORS headers. Other responses to an allowed origin carry Access-Control-Allow-Origin,
-Expose-Headers and -Allow-Credentials. floci-oci's own EXTRA_CORS_ALLOWED_ORIGINS never
applies to a gateway hostname.
Authentication and route authorization are enforced; see the next section.
Every other policy is stored but not enforced: dynamic authentication (dynamicAuthentication),
the OAUTH2 validation failure policy, rate limiting, usage plans, mutual TLS, header, query and
body validations, header and query transformations, response caching and logging. A deployment
that sets any of them logs one warning naming them.
Authentication and authorization
The deployment's requestPolicies.authentication decides who the caller is, and each route's
requestPolicies.authorization what that caller may reach. Sources: the oci-go-sdk models and
Oracle's pages snapshotted under local/oracle/oci-docs/ (apigw-jwt*.md,
apigw-authorizer-*.md, apigw-authn-authz.md).
| Policy | What floci-oci does |
|---|---|
TOKEN_AUTHENTICATION, JWT_AUTHENTICATION |
Takes the token from tokenHeader (after the tokenAuthScheme, such as Bearer) or from tokenQueryParam, and validates it as a JWT: an RS256, RS384 or RS512 signature from a key with the token's kid, exp (required), nbf (when present), iss in issuers, aud in audiences and every verifyClaims entry, with maxClockSkewInSeconds of tolerance. TOKEN takes issuers, audiences and verifyClaims from validationPolicy.additionalValidationPolicy, and checks none of them when it is absent. Every claim is saved in request.auth, and the scope claim (a space-separated string or an array) gives the caller's access scopes |
STATIC_KEYS |
RSA JSON Web Keys (kty, n, e, optional alg) and PEM keys (-----BEGIN PUBLIC KEY----- or a certificate, line breaks optional) |
REMOTE_JWKS |
Fetches the JWKS at uri and caches it for maxCacheDurationInHours (1 to 24). A token whose kid the cached set lacks refetches it, at most once a minute. A JWKS that cannot be fetched answers every request 500, as the docs say. isSslVerifyDisabled accepts any certificate |
REMOTE_DISCOVERY |
Approximated: floci-oci reads the jwks_uri of the OpenID Connect discovery document at sourceUriDetails.uri and validates the token as a JWT against that JWKS. The introspection endpoint and clientDetails are not used, so opaque (non-JWT) tokens are refused |
CUSTOM_AUTHENTICATION |
Invokes the authorizer function through the Functions service. With parameters it sends {"type": "USER_DEFINED", "data": {...}}, each argument the value of its context variable (an array when a header or query parameter repeats, left out when the request does not carry it); without them {"type": "TOKEN", "token": ...} from tokenHeader or tokenQueryParam. A 200 answer with "active": true authenticates the caller: scope (array or space-separated string) gives the access scopes and context fills request.auth. "active": false, or no active, is 401 with the answer's wwwAuthenticate as WWW-Authenticate. A 5xx answer, any other status, a body that is not JSON or a failed invocation is 502. Answers are cached by the cacheKey arguments (all but request.body ones by default; the token for a single-argument authorizer) until expiresAt, at least 60 seconds and at most an hour |
Route authorization, after authentication:
- No authorization policy behaves as
AUTHENTICATION_ONLY, as the docs say. AUTHENTICATION_ONLYlets every authenticated caller through.ANY_OFlets through an authenticated caller holding one ofallowedScope; one without is403.ANONYMOUSlets everyone through, but only when the authentication policy setsisAnonymousAccessAllowed: true; otherwise it behaves asAUTHENTICATION_ONLY. A caller with a valid token still getsrequest.authfilled.
A missing or invalid token, or an authorizer's "active": false, is 401 with
{"code": 401, "message": "Unauthorized"} and a WWW-Authenticate header (Bearer for a missing
JWT, Bearer error="invalid_token" for an invalid one, the scheme following tokenAuthScheme). A
request without a token never reaches an authorizer function. A MODIFY_RESPONSE
validationFailurePolicy replaces the 401: responseCode is a status or a context variable
such as request.auth[responseCode] (the authorizer's context on an "active": false answer),
responseMessage becomes a text/plain body with ${...} context variables substituted, and
responseHeaderTransformations.setHeaders adds headers. Its renameHeaders and filterHeaders
are stored only. The field is responseHeaderTransformations, as in oci-go-sdk and the Python SDK;
the docs' examples write responseTransformations.headerTransformations.
A deployment without an authentication policy lets every request through, whatever its routes' authorization policies say. CORS preflights are answered before authentication.
Quickstart
The subnet has to exist first: create one as in the Networking quickstart.
E="--endpoint http://localhost:4599"
TENANCY=ocid1.tenancy.oc1..flocilocaltenancy0000000000000000000000000000000000000000
oci api-gateway gateway create $E --compartment-id "$TENANCY" \
--endpoint-type PUBLIC --subnet-id <subnetId> --display-name demo-gw
cat > spec.json <<'JSON'
{"routes": [
{"path": "/hello", "methods": ["GET"],
"backend": {"type": "STOCK_RESPONSE_BACKEND", "status": 200, "body": "hello from floci-oci"}},
{"path": "/fn", "methods": ["POST"],
"backend": {"type": "ORACLE_FUNCTIONS_BACKEND", "functionId": "<fnId>"}}
]}
JSON
oci api-gateway deployment create $E --compartment-id "$TENANCY" --gateway-id <gatewayId> \
--path-prefix /v1 --specification file://spec.json
oci api-gateway deployment get $E --deployment-id <deploymentId> --query 'data.endpoint'
curl http://<hostname>:4599/v1/hello
# Without DNS for localhost.floci.io, send the hostname as Host:
curl -H "Host: <hostname>" http://localhost:4599/v1/hello
Inferred behavior
These points are not stated by the OCI SDK models, the CLI, the Terraform provider or the
snapshotted Oracle documentation under local/oracle. They are floci-oci's best reading:
- Create answers
200with the body; Update, Delete and ChangeCompartment answer202. - Deleting a gateway that still has deployments is refused, with
409 Conflict. - Deleted resources leave the lists unless
lifecycleState=DELETEDis requested. - A resource keeps at most one lock of each type; adding a type it has replaces the message, and removing a type it does not have changes nothing.
- The default
displayNameisgateway<yyyyMMddHHmm>ordeployment<yyyyMMddHHmm>. - Route precedence, and a route with no
methodsaccepting every method. - The data plane's own errors are
{"code": <status>, "message": "Not Found"}(andMethod Not Allowed,Bad Gateway,Gateway Timeout), a preflight answers204, andallowedOriginsentries may hold*wildcards. - The request's query string reaches an HTTP backend; no forwarding headers
(
X-Forwarded-For,Forwarded) are added. - The HTTP backend timeouts default to 60 seconds to connect and 10 seconds each to send and read.
- Authentication: a caller without an
ANY_OFscope is403 {"code": 403, "message": "Forbidden"}; theWWW-Authenticatevalues for JWT failures; a token in a header with another scheme thantokenAuthSchemecounts as missing; a JWT must be signed with RS256, RS384 or RS512, and one withoutkidis tried against every key; claims that are not strings are saved inrequest.authas JSON text; aREMOTE_JWKScache lasts one hour whenmaxCacheDurationInHoursis unset; an authorizer answering a status other than200or5xxis502; a multi-argument authorizer is not invoked when the request carries none of its arguments; a deployment without an authentication policy ignores route authorization policies; the MODIFY_RESPONSE body istext/plainand keeps theWWW-Authenticateheader.
Notes & limitations
- Gateways have no TLS front end: the data plane is served on floci-oci's own port and scheme,
and
certificateIdandcaBundlesare stored only. PUBLICandPRIVATEgateways behave the same; nothing checks that a public gateway sits in a public subnet.- A function that writes no
Fn-Http-Statusanswers200, as with fnserver's HTTP triggers. - Authorizer functions are invoked through the same HTTP trigger encoding as function backends,
with the authorizer input as a
POSTbody. In Functions mock mode the synthetic answer has noactivefield, so aCUSTOM_AUTHENTICATIONdeployment authenticates nobody: onlyANONYMOUSroutes withisAnonymousAccessAllowedanswer. dynamicAuthentication(several authentication servers picked by a request element) and theOAUTH2validation failure policy (the OpenID Connect login flow) are stored only.