Skip to content

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 etag and opc-work-request-id. Update, Delete and ChangeCompartment answer 202 with only opc-work-request-id. AddLock and RemoveLock answer with the resource and its etag.
  • Writes finish before they return. A gateway or deployment is ACTIVE as soon as it is created, and its work request is SUCCEEDED with timeFinished set. The work request's resource has entityType gateway or deployment and actionType CREATED, UPDATED or DELETED, which is what the Terraform provider matches. A compartment change is UPDATED.
  • Delete keeps the resource with lifecycleState DELETED, the state Terraform waits for. A deleted resource still answers Get, refuses every other operation with 404 NotAuthorizedOrNotFound, and leaves the lists unless lifecycleState=DELETED is asked for.
  • Lists are {"items": [...]} collections paged with limit, page and opc-next-page. compartmentId is required and must be a known compartment. They sort by timeCreated (the default) or displayName, DESC by default. ListWorkRequests returns WorkRequestSummary items, which carry the OCID as workRequestId and no resources.
  • Gateway create requires compartmentId, endpointType (PUBLIC or PRIVATE) and subnetId. The subnet and the networkSecurityGroupIds must exist in Networking (otherwise 400 RelatedResourceNotAuthorizedOrNotFound), and a subnet or NSG a gateway uses cannot be deleted. certificateId, responseCacheDetails, caBundles, ipMode and the address configurations are stored and returned as sent; ipMode defaults to IPV4 and responseCacheDetails to {"type": "NONE"}. ipAddresses is [{"ipAddress": "127.0.0.1"}].
  • Deployment create requires gatewayId, compartmentId, pathPrefix and specification. The gateway must exist and not be deleted (400 RelatedResourceNotAuthorizedOrNotFound). pathPrefix starts with /. The specification is stored and returned exactly as sent, so every policy reads back unchanged.
  • Specification checks. Each route needs a path starting with / and a backend whose type is 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 is 400 InvalidParameter. A missing url, functionId or status is 400 MissingParameter.
  • Authentication checks. requestPolicies.authentication must have a type of JWT_AUTHENTICATION, TOKEN_AUTHENTICATION or CUSTOM_AUTHENTICATION, and the fields oci-go-sdk marks mandatory: issuers, audiences and publicKeys for JWT, validationPolicy for TOKEN, functionId for CUSTOM, uri for a REMOTE_JWKS key set, kid and format for each static key. A static key must parse (an RSA JSON Web Key with n and e, or a PEM public key or certificate), and maxClockSkewInSeconds must be between 0 and 120. A route's requestPolicies.authorization must be ANONYMOUS, AUTHENTICATION_ONLY or ANY_OF, and ANY_OF needs allowedScope. A missing field is 400 MissingParameter, anything else 400 InvalidParameter.
  • Locks. A FULL lock refuses every change and the delete, a DELETE lock only the delete, with 409 ResourceLocked, unless the request sets isLockOverride=true.
  • Validation. An update or lock request is checked in full before anything changes: a 400 leaves the resource, its specification and its etag as they were.
  • Conflicts. A second deployment with the same pathPrefix on one gateway, and deleting a gateway that still has deployments, are 409 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_ONLY lets every authenticated caller through.
  • ANY_OF lets through an authenticated caller holding one of allowedScope; one without is 403.
  • ANONYMOUS lets everyone through, but only when the authentication policy sets isAnonymousAccessAllowed: true; otherwise it behaves as AUTHENTICATION_ONLY. A caller with a valid token still gets request.auth filled.

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 200 with the body; Update, Delete and ChangeCompartment answer 202.
  • Deleting a gateway that still has deployments is refused, with 409 Conflict.
  • Deleted resources leave the lists unless lifecycleState=DELETED is 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 displayName is gateway<yyyyMMddHHmm> or deployment<yyyyMMddHHmm>.
  • Route precedence, and a route with no methods accepting every method.
  • The data plane's own errors are {"code": <status>, "message": "Not Found"} (and Method Not Allowed, Bad Gateway, Gateway Timeout), a preflight answers 204, and allowedOrigins entries 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_OF scope is 403 {"code": 403, "message": "Forbidden"}; the WWW-Authenticate values for JWT failures; a token in a header with another scheme than tokenAuthScheme counts as missing; a JWT must be signed with RS256, RS384 or RS512, and one without kid is tried against every key; claims that are not strings are saved in request.auth as JSON text; a REMOTE_JWKS cache lasts one hour when maxCacheDurationInHours is unset; an authorizer answering a status other than 200 or 5xx is 502; 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 is text/plain and keeps the WWW-Authenticate header.

Notes & limitations

  • Gateways have no TLS front end: the data plane is served on floci-oci's own port and scheme, and certificateId and caBundles are stored only.
  • PUBLIC and PRIVATE gateways behave the same; nothing checks that a public gateway sits in a public subnet.
  • A function that writes no Fn-Http-Status answers 200, 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 POST body. In Functions mock mode the synthetic answer has no active field, so a CUSTOM_AUTHENTICATION deployment authenticates nobody: only ANONYMOUS routes with isAnonymousAccessAllowed answer.
  • dynamicAuthentication (several authentication servers picked by a request element) and the OAUTH2 validation failure policy (the OpenID Connect login flow) are stored only.