# Run the gateway

> Run the gateway beside your API or MCP server, and every request is checked for its token, revocations and policies before anything reaches your service.

The gateway is the realm's own enforcement point. You run it next to your API or MCP server, and every request passes
through it first: it checks the caller's token, refuses anything the realm has revoked, decides the request against
your policies, and forwards only an allow. Your API needs no change. It sees only the requests the realm allows, and
reads who is calling from a header the gateway sets.

**The gateway's image isn't published yet:** ask your Cvyūh contact for it. This page describes the gateway as it
runs once you have it. What's limited is listed under [Limits and defaults](#limits-and-defaults).

The gateway [decides locally](/gateway/decisions/decide-locally/): it holds its own copies of the realm's keys,
policies and revocations, and calls the realm only to refresh them, so it adds no round trip to the realm per request.

## Before you begin

- **A realm administrator's session** in a group that holds the realm's `RealmOwner` privilege, to activate the
  gateway's client and write policies. [Call the API](/develop/api/) shows how to get `$CVYUH_SESSION`. The gateway's
  client is set up with the API.
- **The gateway's container image**, from your Cvyūh contact, and a host or cluster to run it on, next to your API.
- **A TLS front end** in front of the gateway, such as your load balancer or ingress: the gateway itself listens on
  plain HTTP. See [Limits and defaults](#limits-and-defaults).

## How it works

### What each request goes through

1. **The path.** A path your API might read differently, with dot segments, empty segments, a backslash or an encoded
   letter or slash, is refused before anything else: `400 path_not_canonical`.
2. **The token.** Signed by the realm with ES256, typed `at+jwt`, from the realm's issuer, for your API's audience,
   with a `sub` and a `jti`. A token bound to a key or a certificate is taken only with its proof: see
   [Bound tokens at the gateway](/gateway/protect-apis/bound-tokens/).
3. **Revocations.** The token itself, every token it was exchanged from, its refresh family, its session, the user's
   grant to its client, its subject and every agent acting in it, and any delegation the user took back. Any one of
   them refuses it: see [What can be revoked](/gateway/revocation/what-can-be-revoked/).
4. **Policies.** The policy set you name, decided on the method and on the address the request will reach: your API's
   own host and port, never the one the client named. On an MCP path, the MCP call is decided instead: see
   [MCP tool calls](/gateway/mcp-servers/mcp-tool-calls/).
5. **Forwarding.** Only an allow goes on, to your API, with `x-agent-id` set to the token's `sub`. An `x-agent-id`
   the client sent is removed. With [token swap](/gateway/protect-apis/token-swap/) on, the call goes on under a
   token meant for your API, never the caller's.

What callers see when they're refused, and what your API sees when they're not, is on
[Requests and refusals](/gateway/protect-apis/requests-and-refusals/).

### Inline or behind your proxy

The gateway decides the same way however a request reaches it:

- **Inline.** Clients call the gateway, and it forwards to your API.
- **Behind your own proxy.** A proxy you already run keeps forwarding for itself, and first asks the gateway's
  `ext_authz` check, the external-authorization call many proxies support. It sends the request's method, its
  `Authorization` and `DPoP` headers, its path beneath `/ext_authz`, and the request's host in `x-forwarded-host`. An
  allow is `200` with `x-agent-id`; a refusal is the same refusal the inline proxy gives. A check without
  `x-forwarded-host` is refused `400`.

```http
GET /ext_authz/orders/42 HTTP/1.1
Host: gateway.internal:8080
x-forwarded-host: api.example.com
Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9…
```

[Put the gateway behind your proxy](/gateway/guides/put-the-gateway-behind-your-proxy/) walks through what to forward
and what to copy back.

### Staying current

The gateway signs in to the realm as its own client, with an assertion signed by its own key, so it holds no shared
secret. It then refreshes the realm's keys every 5 minutes, its policies every minute and its revocations every 10
seconds, by default. A token signed with a key the gateway hasn't seen yet makes it fetch the keys at once, so the
realm's key rotation needs no restart. A failed refresh keeps the last good copy. Policies and revocations are fetched
with an entity tag, so an unchanged answer costs almost nothing.

### Fails closed

The gateway never lets a request through on a guess:

- **No policies, no allow.** Until its first policies arrive, and whenever it holds none for a request, everything
  is refused `403 no_policies_loaded`.
- **No current revocation list, no allow.** Until its first revocation poll lands, and once polls have failed for three
  intervals in a row (30 seconds by default), every request with a token is refused `503 revocations_stale`. The next
  good poll ends it.
- **No answer from the realm, no allow.** A token carries no groups, so a policy about the caller's groups can't be
  decided locally. The gateway then [asks the realm](/gateway/decisions/ask-the-realm/) with the same request, and the
  realm's answer is the verdict. If the realm doesn't answer within 3 seconds, or answers anything but `200`, the
  request is refused `403 upstream_unavailable`. Nothing is cached.

Other pages link here rather than repeat this.

## Set it up

[Get started with Gateway](/gateway/get-started/) walks through it, with every call: give the gateway its client in
the realm, write a policy, and run the gateway's container beside your API with the settings in
[Gateway configuration](/gateway/configuration/).

The gateway's client in the realm needs `private_key_jwt` with the gateway's public key, the `client_credentials`
grant, the scopes `policies:read`, `revocations:read` and `access:evaluate`, and the resources
`https://foobar.cvyuh.com/policies/v1` and `https://foobar.cvyuh.com/access/v1`. Every realm is born with one such
client, `floor`, inactive, holding the three scopes and no key or resource. Add the key and the resources and activate
it, or make your own:

```sh
curl -X PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client/floor \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
  -H "Content-Type: application/json" \
  -d '{ "status": "active",
        "jwks": { "keys": [ { "kty": "EC", "crv": "P-256", "kid": "gateway-1", "x": "…", "y": "…" } ] },
        "allowedResources": ["https://foobar.cvyuh.com/policies/v1", "https://foobar.cvyuh.com/access/v1"],
        "defaultAudience": "https://foobar.cvyuh.com/policies/v1" }'
```

Then put a TLS front end before the gateway, make sure your API can't be reached except through it, and read
[Run it in production](/gateway/protect-apis/run-in-production/) before real traffic arrives.

## Limits and defaults

| What | Today |
|---|---|
| Image | Not published yet: ask your Cvyūh contact |
| Protocol | HTTP/1.1 on plain HTTP. Put a TLS front end before the gateway. WebSocket, gRPC, HTTP/2 and other upgraded connections aren't carried |
| APIs per gateway | One. The gateway forwards every allowed request to one `BACKEND`: run one gateway per API |
| Waiting on your API | 5 seconds to connect, 60 seconds for its answer. Neither can be changed, and a failed call isn't retried |
| Request bodies | Up to 1 MiB on an MCP path. Any other body streams through with no limit, so cap sizes at your TLS front end |
| Address conditions | Decided on the address that connected to the gateway. Behind a TLS front end, that's the front end's, not the caller's |
| Tokens taken | The realm's own, ES256-signed access tokens. A token from another identity provider must be exchanged at the realm first |
| Key refresh | Every 5 minutes, and at once for a key the gateway hasn't seen (`JWKS_REFRESH`) |
| Policy refresh | Every minute (`POLICY_REFRESH`) |
| Revocation refresh | Every 10 seconds; three missed in a row and requests are refused (the revocation poll interval in [Gateway configuration](/gateway/configuration/#how-current-it-stays)) |
| A decision asked of the realm | 3 seconds, then refused |
| Your own decisions on the audit trail | Not yet: the gateway logs them where it runs. See [Audit record](#audit-record) |

## Good to know

- **Decides as the realm decides.** The same policies, the same matching and the same rule for turning a decision into
  an answer as the realm's decision API, so the two never disagree.
- **Address conditions see the connecting address.** A policy condition on the caller's IPv4 or IPv6 address
  ([Policies](/workforce-identity/authorization/policies/)) is decided on the address of whatever connected to the
  gateway. A forwarded client address, such as `X-Forwarded-For`, isn't read. Behind a TLS front end, write address
  conditions for your front end's address, or apply caller address rules at the front end itself.
- **Several replicas share one nonce key.** Running more than one replica? Give every replica the same
  `DPOP_NONCE_KEY`, so a nonce one replica gives is good at all of them, and keep each client on one replica: see
  [Run it in production](/gateway/protect-apis/run-in-production/#several-replicas).
- **Only the realm's own tokens.** The gateway verifies tokens from the realm's issuer alone. A token from another
  identity provider must be exchanged at the realm first.
- **Health and logging.** A second listener answers health probes and changes the log level while the gateway runs:
  see [Health and logging](/gateway/configuration/#health-and-logging). On stop, the gateway finishes the requests in
  flight.

## Audit record

The gateway's own allows and refusals aren't on the realm's audit trail yet. Each is a line in the gateway's own log:
see [Logs and tracing](/gateway/configuration/#logs-and-tracing). What does reach the trail:

| What | Record |
|---|---|
| A decision the gateway asks the realm for | `POLICY_DECIDED`, as the realm's decision: every deny, and every decision an agent is in |
| A [token swap](/gateway/protect-apis/token-swap/) | `TOKEN_EXCHANGED` |
| The gateway's own token | `TOKEN_ISSUED`, for the `floor` client |
| Activating `floor`, writing or linking a policy | `PATCHED`, `CREATED`, as any change: see [Change history](/audit-reports/audit-trail/change-history/) |

Every record is described in [What is recorded](/audit-reports/audit-trail/what-is-recorded/).

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Every request with a token is `503 revocations_stale` | The gateway has no current revocation list: it can't sign in to the realm, or can't reach it | Check that the gateway's client is `active`, holds the public half of `CLIENT_KEY`, and names `https://foobar.cvyuh.com/policies/v1` in `allowedResources`. Check that the gateway reaches the realm: see [Where it listens and forwards](/gateway/configuration/#where-it-listens-and-forwards). The log says why each refresh failed |
| Every request is `403 no_policies_loaded` | The gateway holds no policies of the request's type: it can't sign in, `POLICY_SET` names an empty or missing set, or no policy is linked to the `url` type (or, on an MCP path, the MCP types) | Fix the client as above, check `POLICY_SET`, and link each policy to its set and its type |
| Every allow is `403 policies_excluded` | A policy in the set is incomplete, such as linked to the set but not to a resource type, so the realm leaves it out and the set allows nothing | Link the policy to its type, or delete it |
| A request you expect allowed is `403 no_matching_policy` | No policy covers the method and address the gateway decides on: your API's own host and port (`BACKEND`), not the host the client called | Write the policy's `resources` for the backend's host and port, or with `*://*:*/` as the examples do |
| Every token is `401 invalid_token` | The token's `aud` isn't the gateway's `JWT_AUDIENCE`, its `iss` isn't `ISSUER`, or it isn't an access token | Ask for the token with `resource` set to the gateway's audience, from the same realm |
| A token is `401 invalid_token` just after the realm's keys rotate | The gateway fetches the keys again for an unknown key at most once every 10 seconds | Retry after a few seconds |
| A check from your proxy is `400` | The check carries no `x-forwarded-host` | Have the proxy send the request's host in `x-forwarded-host`: see [Put the gateway behind your proxy](/gateway/guides/put-the-gateway-behind-your-proxy/) |
| An MCP call for `Get_Weather` is refused, though `get_weather` is allowed | A `regex` policy set matches case | Use the tool's exact name, or start the pattern with `(?i)` |
| Requests are slow or `403 upstream_unavailable` | A policy about groups sends each request to the realm, which answered late or not at all | Write the policy on a claim the token carries, or check that the gateway reaches the realm |
| `502`, `503` or `504` from the gateway for an allowed call | Your API refused the connection (`503`), failed (`502`) or didn't answer within 60 seconds (`504`) | Check `BACKEND` and your API |

To see more, turn up the log while the gateway runs, then turn it back:

```sh
curl -X PUT "http://127.0.0.1:8802/admin/log?level=debug"
curl -X PUT "http://127.0.0.1:8802/admin/log?level=info"
```

At `debug`, every allow is logged too, with the caller and the path.

## Coming next

- **A published image**, **its decisions on the realm's audit trail**, and **tokens from other issuers** verified
  directly: see [What's next for protecting APIs](/gateway/protect-apis/whats-next/).
- **Revocations pushed** the moment they happen: see [What's next for revocation](/gateway/revocation/whats-next/).

## Reference

### Settings

The settings this page relies on. Every one is in [Gateway configuration](/gateway/configuration/).

| Setting | What it does |
|---|---|
| `ISSUER` | The realm's issuer, whose tokens the gateway takes |
| `JWT_AUDIENCE` | Your API's audience: every token must name it |
| `CLIENT_ID`, `CLIENT_KEY` | The gateway's client in the realm, and its private key |
| `POLICY_SET` | The policy set the gateway enforces |
| `BACKEND` | Your API's own address, where allowed requests go and the host requests are decided on |
| `LISTEN`, `ADMIN_LISTEN` | Where callers reach the gateway, and where health and logging are served |

- [Gateway API](/gateway/api/): the gateway's own endpoints, and the realm's it reads.

## Related

- [Get started with Gateway](/gateway/get-started/): the gateway in front of an API, end to end.
- [Run it in production](/gateway/protect-apis/run-in-production/): replicas, health probes and stopping.
- [Requests and refusals](/gateway/protect-apis/requests-and-refusals/): what callers and your API see.
- [MCP tool calls](/gateway/mcp-servers/mcp-tool-calls/): deciding each tool by name.
- [Decide locally](/gateway/decisions/decide-locally/): the rules any local enforcement point holds to.
