Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install api-gateway-troubleshooting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin api-gateway-troubleshooting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install api-gateway-troubleshooting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/api-gateway-troubleshooting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match api-gateway-troubleshooting for Copilot to auto-discover it.
Skill Files (9)
SKILL.md 20.1 KB
---
name: api-gateway-troubleshooting
metadata:
version: "1.1.0"
category: Serverless
description: >-
Diagnoses failing requests and deployment errors on Google Cloud API Gateway.
Use when calls through a gateway return 4xx or 5xx errors, including 429 and
other quota errors, time out, or fail a CORS preflight; when
`api-configs create` fails with a service account, concurrency, or limit
error, or `gateways create` or `gateways update` fails; when a custom domain,
load balancer, or TLS finding involves a gateway; or when the user asks if
Google is at fault. Don't use for Apigee, Cloud Endpoints, or GKE Gateway API.
For OpenAPI errors from `api-configs create`, use
api-gateway-openapi-spec-authoring; for setting up or changing API keys,
JWTs, or quotas, use api-gateway-backend-security-and-rate-limiting; for MCP
`/mcp` errors, use api-gateway-mcp-server.
---
# API Gateway Troubleshooting
Use this skill to find out why requests to a deployed Google Cloud API Gateway
fail and how to fix them. Work only from three sources of evidence:
1. Public Google Cloud documentation, linked from this skill.
2. The user's own project, read with the user's own credentials.
3. Files and output that the user provides, such as an OpenAPI document, an
error response, or a pasted log entry.
## Scope
This skill covers only Google Cloud API Gateway. If the question is about
Apigee, Cloud Endpoints, or GKE Gateway API, reply that this skill covers only
Google Cloud API Gateway, and don't run its steps or commands.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Ground rules
| Rule | Why |
| :--- | :--- |
| Stay read-only until the user approves a change. While you diagnose, run only `list`, `describe`, `get-iam-policy`, and `logging read` commands, plus `nslookup` and `curl` `GET` requests to a path that's safe to call. | Gateways serve production traffic, and the quota metrics and limits of the most recently created API config apply to every gateway of the API. |
| Before any change, show the exact command, what it changes, and how to undo it, then wait for an explicit yes. Changes include IAM grants, `api-configs create`, `gateways update`, Cloud Run ingress changes, and `gcloud services enable`. | The user owns the project and the change. |
| Never fix a `401` or `403` by making a backend public (`--allow-unauthenticated`, `--no-invoker-iam-check`, `allUsers`) or by granting a basic role such as Editor. | Grant the gateway's service account the invoker role on the one backend instead, which keeps least privilege. |
| Keep every log read bounded: filter on the gateway, set `--freshness` or a timestamp window, and set `--limit`. | Unbounded reads are slow and pull in caller data that the diagnosis doesn't need. |
| Redact API keys, bearer tokens, and JWTs before you show log entries, commands, or files. | Request logs and pasted output can contain credentials. |
| Base every limit, default, and error meaning on a linked public doc or on output from the user's project. If neither explains the problem, say so and escalate. | Guessing about undocumented behavior leads to wrong fixes. |
| Use the user's existing `gcloud` login. Never ask for passwords, API key values, or service account key files. | Credentials don't belong in a chat transcript. |
| For Preview features (streaming, MCP, model routing), check the [release notes](https://docs.cloud.google.com/api-gateway/docs/release-notes.md.txt) before answering. | Preview behavior changes between releases. |
## Prerequisites
1. **Google Cloud CLI.** Use a recent `gcloud` (the commands here were
checked with version 591.0.0); see
[Install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt).
Don't install or update software without the user's approval. If
`gcloud` isn't available or the user says not to run commands, work in
*evidence mode*: give the user the read-only commands to run, and diagnose
from the output, response bodies, and log entries they paste.
2. **Authentication.** Use the user's existing `gcloud auth login` session;
this skill doesn't need application-default credentials.
3. **Project.** Ask which project hosts the gateway and pass
`--project={project_id}` on every command. Don't run `gcloud config set`,
because it changes the user's environment. This skill troubleshoots
existing gateways and never creates projects.
4. **Billing.** The project needs an active billing account even when usage
stays in the free tier; see
[API Gateway pricing](https://cloud.google.com/api-gateway/pricing).
5. **APIs.** API Gateway requires `apigateway.googleapis.com`,
`servicemanagement.googleapis.com`, and `servicecontrol.googleapis.com`. A
gateway can keep responding while one of them is missing, and its logs then
stay empty, so check with
`gcloud services list --enabled --project={project_id}`. Enabling a missing
API is a change that needs approval.
6. **IAM roles for diagnosis (read-only):** `roles/apigateway.viewer`,
`roles/logging.viewer`, `roles/serviceusage.serviceUsageViewer`, and
`roles/iam.serviceAccountViewer` (to check the gateway's service account).
For Cloud Run backends, add `roles/run.viewer`; to trace a custom domain
through its load balancer, add `roles/compute.viewer`; to check an API key's
project, `roles/serviceusage.serviceUsageViewer` is also needed there.
7. **IAM roles for fixes (only after approval):** `roles/apigateway.admin`;
`roles/iam.serviceAccountUser` on the gateway's service account, because
creating or updating an API config or a gateway requires
`iam.serviceAccounts.actAs`;
`roles/run.admin` to change a Cloud Run service's IAM policy or ingress;
`roles/serviceusage.serviceUsageAdmin` to enable an API or a managed
service, plus `roles/servicemanagement.serviceConsumer` on the API's
managed service to enable it in another project; and
`roles/iam.serviceAccountAdmin` to re-enable a disabled service account.
8. **Region.** Gateways are regional. Use the region that
`gateways list` reports. When a fix needs a new gateway, create it in the
original gateway's region, or in `us-central1` if the user has no
preference; see
[API Gateway deployment model](https://docs.cloud.google.com/api-gateway/docs/deployment-model.md.txt)
and [Cloud locations](https://cloud.google.com/about/locations).
## Workflow
Copy this checklist into your notes and tick it off as you go:
```
- [ ] 1. Context collected
- [ ] 2. Gateway identified by defaultHostname
- [ ] 3. Expected or transient states ruled out
- [ ] 4. Gateway log entry read (bounded query)
- [ ] 5. One branch chosen from the classification table
- [ ] 6. Root cause stated with redacted evidence and a doc link
- [ ] 7. Fix proposed, approved, and applied (or handed to the user)
- [ ] 8. Fix verified
- [ ] 9. Escalated, if the evidence points to Google Cloud
```
### 1. Collect context
Extract these from the conversation first, and ask only for what's missing:
| Needed | Why |
| :--- | :--- |
| `{project_id}` of the gateway | Every command is scoped to it. |
| Failing URL (host and path) or `{gateway_id}` and `{region}` | Identifies the gateway. |
| HTTP method, status code, and response body | Separates gateway errors from backend errors. |
| Approximate time of the failure, in UTC | Bounds the log query. |
| What changed recently (new API config, IAM, backend deploy, DNS) | Recent changes are the first place to look. |
| Authentication used by the caller (API key, JWT, none) | Selects the auth branch. |
If the project or the host is unknown, stop and ask before you run any
`gcloud` command. Don't guess project IDs, and don't use the active `gcloud`
project instead.
### 2. Identify the gateway
List the project's gateways:
```bash
gcloud api-gateway gateways list --project={project_id} \
--format="table(name.basename():label=GATEWAY,name.segment(3):label=REGION,defaultHostname,state,apiConfig)"
```
Match the request host against `defaultHostname`. Don't decide from the URL
suffix: a gateway's hostname can use either of two `gateway.dev` formats or,
for older streaming and model-routing gateways, a `run.app` format. Don't
guess the owning project from numbers in the hostname either; list the
gateways in the project the user names. A custom domain points at a load
balancer whose serverless NEG targets the gateway. See
[references/triage-and-logs.md](references/triage-and-logs.md) for the
hostname formats and how to trace a custom domain.
If no gateway in the project matches, confirm the product before going on
(see [Scope](#scope)).
Then read the gateway's details, including its API config and streaming mode:
```bash
gcloud api-gateway gateways describe {gateway_id} \
--location={region} --project={project_id}
```
### 3. Rule out expected and transient states
- **Gateway `state` isn't `ACTIVE`:** `CREATING` or `UPDATING` means an
operation is still running, so wait and check again. `FAILED` means
creation failed; read the error of the failed operation. `DELETING` means
the gateway is being removed.
- **API config just created:** creating a complex API config can take up to
ten minutes, and only one config can be created for an API at a time.
- **First requests after an idle period:** API Gateway has cold-start
latency.
- **Google Cloud incident:** check the
[Service Health dashboard](https://docs.cloud.google.com/service-health/docs/overview.md.txt).
### 4. Read the gateway log entry
Use a bounded query that prints only the fields you need. Replace
`{status_code}` with the status the caller saw:
```bash
gcloud logging read 'resource.type="apigateway.googleapis.com/Gateway" AND resource.labels.gateway_id="{gateway_id}" AND resource.labels.location="{region}" AND httpRequest.status={status_code}' \
--project={project_id} --freshness=1h --limit=20 \
--format="json(timestamp,httpRequest.status,httpRequest.latency,httpRequest.requestUrl,jsonPayload.responseDetails,jsonPayload.apiConfig,jsonPayload.apiMethod)"
```
If you know the failure time, replace `--freshness` with a
`timestamp>="{start_utc}" AND timestamp<="{end_utc}"` filter that spans about
30 minutes around it. Read `httpRequest.status`, `httpRequest.requestUrl`,
`jsonPayload.responseDetails`, `jsonPayload.apiConfig`, and
`jsonPayload.apiMethod`. Keep the `--format` field list, because a full entry
can contain the caller's credentials, and redact credentials before you quote
any field, including a `key` query parameter in `httpRequest.requestUrl`.
To compare API configs, compare only the `apis/{api_id}/configs/{config_id}`
part: the same config can appear as a full resource name
(`//apigateway.googleapis.com/projects/...`) and with either the project
number or the project ID.
`jsonPayload.responseDetails` decides the branch: `via_upstream` means the
backend produced the response; any other value means the gateway produced it.
The troubleshooting page explains `via_upstream` and
`service_control_quota_error`, and the model routing page explains the
`model_router_*` values that model-routing gateways log. Quote any other value
as-is, and don't explain how the gateway works internally.
### 5. Classify and follow one branch
Pick the first row that matches, and load only the reference file it names.
| What you see | Likely cause | Reference |
| :--- | :--- | :--- |
| The request path ends in `/mcp`, or the response is a JSON-RPC error | The MCP setup | Hand off to `api-gateway-mcp-server`; if it isn't installed, read the MCP troubleshooting table in [Configure MCP](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt) |
| `401` or `403` with `via_upstream` | The backend rejected the gateway: invoker role, audience, or deleted service account | [auth-errors.md](references/auth-errors.md) |
| A `4xx` produced by the gateway whose body names a credential problem (for example `UNAUTHENTICATED`) | The API key or JWT was rejected; quote the body | [auth-errors.md](references/auth-errors.md) |
| `500` with **no** gateway log entry, after log exclusions and a wrong scope are ruled out | The gateway's service account may be deleted or disabled | [auth-errors.md](references/auth-errors.md) |
| `500` with `service_control_quota_error` | Quota metric missing from the newest API config | [config-deployment-errors.md](references/config-deployment-errors.md) |
| `429` with `service_control_quota_error` | The caller exceeded the API's quota | [limits-and-escalation.md](references/limits-and-escalation.md) |
| `404`, `502`, `503`, or `504`, an oversized request, or a timeout | Routing, backend errors, size limits, or the deadline. The docs don't name the status codes for size or deadline failures, so confirm with `responseDetails` and the body. | [backend-routing-and-timeouts.md](references/backend-routing-and-timeouts.md) |
| CORS preflight fails or latency is high | CORS pass-through or slow backend | [backend-routing-and-timeouts.md](references/backend-routing-and-timeouts.md) |
| `api-configs create` fails with an error about the OpenAPI document, such as an unsupported extension or an invalid path, parameter, server, or security requirement | A spec problem | Hand off to `api-gateway-openapi-spec-authoring`; if it isn't installed, see [OpenAPI pre-flight check](#openapi-pre-flight-check) |
| `api-configs create` fails with a service account, concurrency, or limit error, or `gateways create` or `gateways update` fails | Service account, concurrent creates, limits, or the backend deadline | [config-deployment-errors.md](references/config-deployment-errors.md) |
| `400` "The request was malformed" from an old TLS client, TLS scan findings, custom domain, or no log entry at all | TLS enforcement, DNS, load balancer, or wrong host | [networking-domains-tls.md](references/networking-domains-tls.md) |
| Errors on several gateways, or on an unchanged config, with healthy backends | Possible Google Cloud issue | [limits-and-escalation.md](references/limits-and-escalation.md) |
If the request also needs log queries or backend inspection commands, use
[triage-and-logs.md](references/triage-and-logs.md).
### 6. State the root cause
Give the cause, the evidence (redacted, quoted verbatim from logs or command
output), and the public doc section that explains it. If the evidence fits
more than one cause, list at most three, say what would tell them apart, and
collect that evidence before proposing a fix.
### 7. Propose the fix
Show the exact command, the resource it changes, its effect on live traffic,
and how to undo it. Wait for approval, then run it, or hand it to the user if
they prefer. Keep these rules in mind:
- To change the OpenAPI document, create a new API config and deploy it with
`gcloud api-gateway gateways update`. The newest API config's quota metrics
apply to every gateway of the API. Before you run `api-configs create`,
load the `api-gateway-backend-security-and-rate-limiting` skill and run its
`scripts/check_quota_metrics.py`. It compares the new spec's quota metrics
with the API configs that gateways serve. If that skill isn't installed,
keep every quota metric and its limit that a running API config uses.
- Before you create a new API config, check the OpenAPI document with the
linter (see [OpenAPI pre-flight check](#openapi-pre-flight-check)).
### 8. Verify
Read the logs again for new entries after the change, or repeat the failing
request. Repeat a request yourself only if it's safe to repeat, such as a
`GET`; otherwise ask the user to repeat it, because a repeated `POST` can
change data in their backend. After `gateways update`, wait until the
gateway's `state` is `ACTIVE` before you test.
### 9. Escalate when the evidence points to Google Cloud
Escalate to [Cloud Customer Care](https://cloud.google.com/support) when the
service account is active, the required APIs are enabled, and no log exclusion
or wrong scope explains it, but requests get `500` errors with no gateway log
entry; when several gateways fail at once without a config change; when errors
are intermittent on an unchanged config while the backend logs stay clean;
when control-plane operations keep failing with internal errors; or when
Service Health reports an incident. Draft the case text with the evidence
bundle in [limits-and-escalation.md](references/limits-and-escalation.md). The
user files the case.
## OpenAPI pre-flight check
Run the linter on every OpenAPI file before creating an API config. Run it;
don't read its source. If you don't have the file, give the user the command
to run:
```bash
python3 scripts/lint_openapi_for_gateway.py {spec_path} [{spec_path} ...]
```
It reads the files only, makes no network calls, and prints JSON findings that
each link to the public doc for the limitation. Exit code `0` means no errors,
`1` means at least one `ERROR` finding, and `2` means a usage, parse, or
dependency error. The linter needs Python 3.8 or later. YAML input needs
PyYAML; ask the user before you install it with
`pip install "PyYAML>=6.0,<7.0"`. JSON input doesn't. Fix the `ERROR`
findings, and then create the API config. If `api-configs create` still fails
on the OpenAPI document, hand off to `api-gateway-openapi-spec-authoring`, or
use the error message if that skill isn't installed. Show `WARNING` findings
to the user and explain them.
## Output format
Report findings in this form:
```
**Problem:** <one sentence in the user's terms>
**Failed hop:** <gateway or backend, and the evidence for it>
**Evidence:** <redacted log fields or command output, verbatim>
**Root cause:** <one or two sentences> (<public doc link>)
**Fix:** <exact command or spec change; approval needed: yes/no>
**Verify:** <how to confirm the fix>
**Open questions:** <anything you couldn't confirm>
```
## Related skills
| Need | Skill |
| :--- | :--- |
| Write or change API key, JWT, backend authentication, or quota configuration | `api-gateway-backend-security-and-rate-limiting` |
| Write, migrate, or fix an OpenAPI spec, including OpenAPI errors from `api-configs create` | `api-gateway-openapi-spec-authoring` |
| MCP `/mcp` JSON-RPC errors on an MCP-enabled gateway | `api-gateway-mcp-server` |
| Deep IAM analysis, such as deny policies or role discovery | `iam-helper-for-troubleshooting` |
| Build a load balancer, Cloud Armor policy, or custom domain front end | `google-cloud-global-frontend-configuration` |
| Deploy or reconfigure a Cloud Run backend | `cloud-run-basics` |
If an API Gateway skill in this table isn't installed, give the user this
command to install the four API Gateway skills. Until it is installed, use the
fallback in this skill.
```bash
npx skills add google/skills --skill api-gateway-mcp-server --skill api-gateway-backend-security-and-rate-limiting --skill api-gateway-openapi-spec-authoring --skill api-gateway-troubleshooting
```
For another skill in this table, give the user the same command with
`--skill {skill_name}`.
## Reference files
- [references/attribution.md](references/attribution.md): usage attribution
rules for every command you run.
- [references/triage-and-logs.md](references/triage-and-logs.md): hostname
formats, log queries, log fields, metrics, and backend inspection
commands.
- [references/auth-errors.md](references/auth-errors.md): `401` and `403` on
either hop, API keys, JWTs, and the gateway service account.
- [references/backend-routing-and-timeouts.md](references/backend-routing-and-timeouts.md):
`404`, size limits, backend `5xx`, `504` and deadlines, CORS, and streaming.
- [references/config-deployment-errors.md](references/config-deployment-errors.md):
API config and gateway create, update, and delete failures other than
OpenAPI errors, and quota metric conflicts.
- [references/networking-domains-tls.md](references/networking-domains-tls.md):
custom domains, load balancers, TLS, and requests that never reach the
gateway.
- [references/limits-and-escalation.md](references/limits-and-escalation.md):
product limits, quota increases, unsupported features, and the Cloud
Customer Care evidence bundle.
- [scripts/lint_openapi_for_gateway.py](scripts/lint_openapi_for_gateway.py):
offline linter for documented OpenAPI limitations.
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:api-gateway-troubleshooting)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:api-gateway-troubleshooting)` in the `User-Agent`
header. If a `User-Agent` header is already specified, append this string to
the end of it rather than overwriting existing `User-Agent` data — the
collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:api-gateway-troubleshooting)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
auth-errors.md 10.4 KB
# 401 and 403 errors
- [Find the hop that failed](#find-the-hop-that-failed): Lines 9-19
- [Gateway rejected the caller: API keys](#gateway-rejected-the-caller-api-keys): Lines 21-67
- [Gateway rejected the caller: JWTs](#gateway-rejected-the-caller-jwts): Lines 69-93
- [Backend rejected the gateway](#backend-rejected-the-gateway): Lines 95-170
- [Fixes to avoid](#fixes-to-avoid): Lines 172-176
## Find the hop that failed
A request crosses two hops, and each has its own credentials:
| Hop | Credential | Evidence |
| :--- | :--- | :--- |
| Caller to gateway | API key or JWT defined in the API config | Gateway log entry whose `responseDetails` isn't `via_upstream` |
| Gateway to backend | ID token minted for the gateway's service account | Gateway log entry with `responseDetails` set to `via_upstream` |
Read the log entry first (see [triage-and-logs.md](triage-and-logs.md)). Don't
change IAM on the backend for a caller-side failure, or the reverse.
## Gateway rejected the caller: API keys
When an API config requires an API key, a request without one gets an error
like the one the API Gateway quickstart shows
([Secure traffic with gcloud](https://docs.cloud.google.com/api-gateway/docs/secure-traffic-gcloud.md.txt)):
```
UNAUTHENTICATED:Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.
```
Check, in order
([Authenticate with API keys](https://docs.cloud.google.com/api-gateway/docs/authenticate-api-keys.md.txt)):
1. **The key is sent where the spec expects it** (header or query parameter
name in the security definition).
2. **The key's project can use the API.** API Gateway rejects requests unless
the API key was generated in the gateway's project or in another project
where the API's managed service is enabled. Get the managed service name,
then check whether it's enabled in the key's project:
```bash
gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"
gcloud services list --enabled --project={consumer_project} \
--filter="config.name={managed_service}"
```
The fix, after approval, is
`gcloud services enable {managed_service} --project={consumer_project}`.
The person who runs it needs `roles/serviceusage.serviceUsageAdmin` in the
consumer project and `roles/servicemanagement.serviceConsumer` on the
managed service, which the API owner grants
([API access overview](https://docs.cloud.google.com/api-gateway/docs/api-access-overview.md.txt)).
3. **The key's restrictions allow the call.** API restrictions must include
the managed service, and application restrictions (IP addresses, referrers,
apps) must match the caller
([Manage API keys](https://docs.cloud.google.com/docs/authentication/api-keys.md.txt)).
Managing keys needs `roles/serviceusage.apiKeysAdmin`.
4. **The security requirements are supported.** The OpenAPI 2.0 and 3.x
limitations pages say that API Gateway doesn't support alternative (logical
OR) security requirements when one of them is an API key; API key and JWT
can only be combined with AND
([OpenAPI 2.0 limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-limitations.md.txt),
[OpenAPI 3.x limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)).
API Gateway accepts a list in which every alternative has an API key
scheme, so such a list isn't the cause.
Refer to keys by key ID or display name only. Never print a key value.
## Gateway rejected the caller: JWTs
Don't ask for the token: it's a live credential. Ask the user to decode its
header and payload on their own machine (both are base64url-encoded) and paste
only the `iss`, `aud`, `exp`, and `iat` claims. If they paste a token anyway,
don't repeat it. Compare the claims with the security definition
([Authenticate users with JWT](https://docs.cloud.google.com/api-gateway/docs/authenticating-users-jwt.md.txt)):
| Claim | Must match |
| :--- | :--- |
| `iss` | `x-google-issuer` (OpenAPI 2.0) or the issuer in `x-google-auth` (OpenAPI 3.x) |
| `aud` | `x-google-audiences` (2.0) or `audiences` (3.x), which are optional. When they aren't set, the OpenAPI 2.0 extensions page says `aud` should match the document's `host` field, and the JWT page says API Gateway accepts JWTs whose `aud` is `https://SERVICE_NAME`. If the token fits neither, set the audiences explicitly. |
| `exp` | A required claim; check that the token hasn't expired |
| Signature | A key published at `x-google-jwks_uri` (2.0) or `jwksUri` (3.x) |
Also check:
- Each security definition must use a different issuer.
- Method-level security settings override API-level settings.
- The `jwks_queries` log shows whether the gateway could fetch the signing
keys ([Platform logs](https://docs.cloud.google.com/api-gateway/docs/platform-logging.md.txt)).
If the response body names the failing check, quote it verbatim (redacted) and
map it to the table above. Don't infer meanings for messages that the public
docs don't describe.
## Backend rejected the gateway
`via_upstream` means the backend returned the `401` or `403`. Work through the
causes that match the backend type
([Securing backend services](https://docs.cloud.google.com/api-gateway/docs/securing-backend-services.md.txt)):
| Backend | Gateway service account needs |
| :--- | :--- |
| Cloud Run | `roles/run.invoker` (or a role with `run.routes.invoke`) on the service |
| Cloud Run functions | An invoker binding on the function. The API Gateway page names `roles/cloudfunctions.invoker`; the current [Cloud Run functions access page](https://docs.cloud.google.com/functions/docs/securing/managing-access-iam.md.txt) grants `roles/run.invoker` on the function with `gcloud run services add-iam-policy-binding`. Read the function's IAM policy first; if neither binding exists, propose the role from the access page that matches how the function is deployed, and ask the user if that's unclear. |
| App Engine behind IAP | `IAP-secured Web App User`, plus the extra permissions listed on the page, and a `jwt_audience` override (see below) |
1. **Missing invoker role.** Read the backend's IAM policy (see
[triage-and-logs.md](triage-and-logs.md#inspect-the-backend)). Cloud Run
documents the messages its callers see
([Cloud Run troubleshooting](https://docs.cloud.google.com/run/docs/troubleshooting.md.txt)),
for example `HTTP 403: Forbidden: Your client does not have permission to
get URL from this server.` Fix, after approval, on the one service:
```bash
gcloud run services add-iam-policy-binding {service} \
--region={backend_region} \
--member=serviceAccount:{service_account_email} \
--role=roles/run.invoker --project={backend_project}
```
2. **Wrong audience.** If an operation doesn't set `jwt_audience` or
`disable_auth`, the gateway sets the token audience to the backend
`address`
([OpenAPI 2.0 extensions](https://docs.cloud.google.com/api-gateway/docs/oasv2-extensions.md.txt)).
App Engine and IAP expect their OAuth client ID instead, so those backends
need `jwt_audience` (`jwtAudience` in
[OpenAPI 3.x](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)).
Set only one of `jwt_audience` and `disable_auth`.
3. **Deleted or disabled service account.** Right after the account is deleted
or disabled, the gateway may log `401` with `via_upstream`, and callers may
also get `500` with no gateway log entry at all
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
Check with `gcloud iam service-accounts describe {service_account_email}`.
Then read the gateway log from just before the `500`s began, without a
status filter, and quote any `401` entries with `via_upstream` as evidence
of when the account stopped working.
Fix, after approval: re-enable a disabled account with
`gcloud iam service-accounts enable {service_account_email}`, or create a
new API config with
`--backend-auth-service-account={active_service_account_email}` (an active
account that has the invoker role) and deploy it with `gateways update`.
4. **Backend is a Google Cloud API (`*.googleapis.com`).** These APIs require
an access token and reject the ID token that the gateway sends to other
backends, so it depends on the gateway's `effectiveStreamingMode`
([Securing backend services](https://docs.cloud.google.com/api-gateway/docs/securing-backend-services.md.txt)):
- `EFFECTIVE_STREAMING_MODE_DISABLED`: the gateway doesn't support calling
Google Cloud APIs, and calls can fail with `401`. Tell the user this is
a product limitation of non-streaming gateways.
- `EFFECTIVE_STREAMING_MODE_ENABLED`: the gateway sends an access token
for its service account, with only the `cloud-platform` scope, to
backends whose host ends in `.googleapis.com` or `.vertexai.goog`.
Grant that service account the role that the target API requires. A
backend with `disable_auth` (`disableAuth` in OpenAPI 3.x) gets no
token. A streaming gateway that doesn't send access tokens yet switches
at the next gateway rollout, or right away after an update to a new API
config.
For model routing to Agent Platform endpoints such as
`aiplatform.googleapis.com`, the gateway's service account needs
`roles/aiplatform.user`
([Configure model routing](https://docs.cloud.google.com/api-gateway/docs/model-routing-configure.md.txt)).
5. **Backend reads the caller's JWT.** When backend authentication is on and
the caller sent `Authorization`, the gateway copies it to
`X-Forwarded-Authorization` and replaces `Authorization` with its own ID
token. If the API config doesn't define JWT authentication, the backend
must verify the JWT from `X-Forwarded-Authorization` itself. If it does,
the JWT page says the gateway sends the authentication result in
`X-Apigateway-Api-Userinfo` (the OpenAPI 2.0 extensions page names
`X-Endpoint-API-UserInfo` instead). For changes to this setup, hand off
to `api-gateway-backend-security-and-rate-limiting`.
## Fixes to avoid
- Don't set `disable_auth: true` unless the backend allows unauthenticated
calls by design, or it needs the caller's original `Authorization` header
and can't use `X-Forwarded-Authorization`.
backend-routing-and-timeouts.md 7.4 KB
# Routing, size limits, backend errors, timeouts, and CORS
- [404 Not Found](#404-not-found): Lines 10-47
- [Request and header size limits](#request-and-header-size-limits): Lines 49-59
- [502 and 503](#502-and-503): Lines 61-70
- [504 and slow responses](#504-and-slow-responses): Lines 72-105
- [CORS](#cors): Lines 107-119
- [Streaming and gRPC notes](#streaming-and-grpc-notes): Lines 121-129
## 404 Not Found
Read `responseDetails` first (see [triage-and-logs.md](triage-and-logs.md)).
**`via_upstream`, and no matching entry in the Cloud Run request log.** The
Cloud Run service's ingress setting is probably blocking the gateway, or the
service's default `run.app` URL is disabled while the gateway's `address`
still uses it. With
ingress set to *Internal*, only the sources listed on the ingress page can reach
the service, and requests from other sources can't reach it at the `run.app`
URL, a custom URL, or a custom domain
([Cloud Run ingress](https://docs.cloud.google.com/run/docs/securing/ingress.md.txt)).
Cloud Run documents that requests blocked by these ingress settings, or sent
to a disabled `run.app` URL, get `404` and don't appear in its request log
([Cloud Run troubleshooting](https://docs.cloud.google.com/run/docs/troubleshooting.md.txt)).
Read the `run.googleapis.com/ingress` annotation to confirm. Fix, after
approval: `gcloud run services update {service} --ingress=all
--region={backend_region} --project={backend_project}`, and keep the service
private through IAM: grant `roles/run.invoker` to the gateway's service account
only (see [auth-errors.md](auth-errors.md)).
**`via_upstream`, and the backend logged the `404`.** The backend received a
path it doesn't serve. Check path translation in `x-google-backend`
([OpenAPI 2.0 extensions](https://docs.cloud.google.com/api-gateway/docs/oasv2-extensions.md.txt)):
| Where `x-google-backend` is set | Default `path_translation` | Effect |
| :--- | :--- | :--- |
| Top level of the spec | `APPEND_PATH_TO_ADDRESS` | The request path is appended to `address`. |
| On an operation | `CONSTANT_ADDRESS` | The request goes to `address` as-is, and path parameters are sent as query parameters. |
**Produced by the gateway.** By default, API Gateway serves only the methods
listed in the OpenAPI document (`x-google-allow: configured` in OpenAPI 2.0),
so the request's path or method is probably missing from the API config that
the gateway serves. Print the deployed OpenAPI document (see
[triage-and-logs.md](triage-and-logs.md#inspect-the-deployed-api-config)) and
compare its paths, methods, and base path with the request. Confirm the gateway
serves the config you expect by comparing the config ID in
`jsonPayload.apiConfig` with the gateway's `apiConfig`.
## Request and header size limits
API Gateway allows requests up to 32 megabytes, responses up to 32 megabytes
(streamed and chunked responses are exempt), and 60 kilobytes of request
headers. gRPC transcoding requests and responses are limited to 1 megabyte
each. The backend may have lower limits
([Quotas and limits](https://docs.cloud.google.com/api-gateway/docs/quotas.md.txt)).
The docs list these limits but not the status codes returned when a limit is
exceeded, so confirm from the response body and `responseDetails`. Compare the
request's body and header sizes with the limits, then suggest smaller payloads,
fewer or smaller headers, or streaming for large responses.
## 502 and 503
- **`via_upstream`:** the backend returned the error. Troubleshoot the
backend directly, starting with its own request logs; this skill's scope
ends once the backend is identified.
- **Produced by the gateway:** the gateway, not the backend, generated the
error. Check that `address` uses `https` for serverless backends, that the
backend host resolves, and that the backend is healthy in its own logs and
metrics. If all three hold and the errors continue, escalate (see
[limits-and-escalation.md](limits-and-escalation.md)).
## 504 and slow responses
- **Deadline.** The default backend `deadline` is 15.0 seconds. It can be
raised up to 3600 seconds, but a non-streaming gateway rejects values above
600 seconds when the gateway is created or updated, not when the API config
is created
([OpenAPI 2.0 extensions](https://docs.cloud.google.com/api-gateway/docs/oasv2-extensions.md.txt)).
Check `effectiveStreamingMode` before you propose a value above 600. The
docs don't name the status code returned when the deadline expires, and a
`504` with `via_upstream` can come from the backend's own request
timeout instead.
- **Default fix.** On a non-streaming gateway, set `deadline` to at most 600
seconds in a new API config and deploy it with `gateways update`. Requests
that need longer require a new streaming-enabled gateway, which gets a new
hostname that callers must switch to (see
[Streaming and gRPC notes](#streaming-and-grpc-notes)). Give the commands
for the existing gateway even when you also propose a new gateway.
- **Trade-off.** The docs warn that long deadlines can overload the proxy with
TCP connections when the backend is slow, and short deadlines can make
expensive requests fail consistently. Propose the smallest deadline that
covers the backend's normal response time.
- **Backend timeout.** The backend's own request timeout also limits the
response. For example, the streaming guide notes that a Cloud Run service
deployed with `--timeout 600` ends its streams after 10 minutes, so a
3,600-second deadline also needs `--timeout 3600` on the service.
- **Streaming endpoints.** On an SSE or chunked-transfer path, the deadline
bounds the whole response, so a stream is cut when it elapses. On a gRPC
or WebSocket endpoint, it bounds the gap between messages
([OpenAPI 2.0 extensions](https://docs.cloud.google.com/api-gateway/docs/oasv2-extensions.md.txt),
[Configure streaming](https://docs.cloud.google.com/api-gateway/docs/streaming-configure.md.txt)).
- **Cold starts.** After 15 to 20 minutes without traffic, the first
requests can see added latency. If latency persists after warm-up, check the
backend's request logs
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
## CORS
To let the backend handle CORS, including `OPTIONS` preflight requests, turn on
CORS pass-through, then make sure the backend answers preflight requests with
the right `Access-Control-*` headers:
| OpenAPI version | Setting |
| :--- | :--- |
| 2.0 | Top-level `x-google-endpoints` with `allowCors: True` ([extensions](https://docs.cloud.google.com/api-gateway/docs/oasv2-extensions.md.txt)) |
| 3.x | `allowCors: true` in the `x-google-endpoint` extension on the server ([extensions](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)) |
After the change, create a new API config and deploy it, then repeat the
browser request and inspect the preflight response.
## Streaming and gRPC notes
- You can't update a gateway to change its streaming mode; create a new
gateway, which gets a new hostname
([Deploy an API to a gateway](https://docs.cloud.google.com/api-gateway/docs/deploying-api.md.txt)).
- Gateways with streaming enabled can't sit behind a load balancer or
serverless NEG, so they can't use custom domains during Public Preview
([Configure streaming](https://docs.cloud.google.com/api-gateway/docs/streaming-configure.md.txt)).
- Terraform can't enable streaming yet.
config-deployment-errors.md 4.9 KB
# API config and gateway errors
- [api-configs create fails](#api-configs-create-fails): Lines 9-47
- [Quota metric conflicts across API configs](#quota-metric-conflicts-across-api-configs): Lines 49-74
- [Deleting an API config fails](#deleting-an-api-config-fails): Lines 76-80
- [gateways create or update fails](#gateways-create-or-update-fails): Lines 82-90
- [gcloud api-gateway commands fail](#gcloud-api-gateway-commands-fail): Lines 92-97
## api-configs create fails
**Service account does not exist.** An error in this form means the config
needs an explicit backend service account
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)):
```
ERROR: (gcloud.api-gateway.api-configs.create) FAILED_PRECONDITION:
Service Account "projects/-/serviceAccounts/service_account_email" does not exist
```
Rerun the command with
`--backend-auth-service-account={service_account_email}`. Without that flag,
API Gateway uses the project's default Compute Engine service account
(`{project_number}-compute@developer.gserviceaccount.com`), which is created
when the Compute Engine API is enabled. The person who creates or updates an
API config or a gateway needs `iam.serviceAccounts.actAs` on the account, which
the `roles/iam.serviceAccountUser` role includes
([Configure your development environment](https://docs.cloud.google.com/api-gateway/docs/configure-dev-env.md.txt)).
**The OpenAPI document is rejected.** Hand off errors about the OpenAPI
document, such as an unsupported extension or an invalid path, parameter,
server, or security requirement, to the `api-gateway-openapi-spec-authoring`
skill, which matches the error text and fixes the spec. If that skill isn't
installed, fix what the error message names, run
`python3 scripts/lint_openapi_for_gateway.py {spec_path}`, and fix the `ERROR`
findings
([OpenAPI 2.0 limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-limitations.md.txt),
[OpenAPI 3.x limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)).
**Two configs at once.** If a second config was started before the first
finished, one or both may not be usable in a gateway; create the config again
after the first finishes
([Create an API config](https://docs.cloud.google.com/api-gateway/docs/creating-api-config.md.txt)).
**Limits.** API Gateway allows 50 APIs, 100 API configs per API, and 50
gateways per region
([Quotas and limits](https://docs.cloud.google.com/api-gateway/docs/quotas.md.txt)).
Suggest deleting unused configs (after approval) before requesting more.
## Quota metric conflicts across API configs
Symptom: requests to quota-enforced methods fail with
`{"code":500,"message":"Failed to call Service Control Quota."}`, and the
gateway logs show `jsonPayload.responseDetails="service_control_quota_error"`
with `httpRequest.status=500`. The same `responseDetails` with status `429`
means a caller legitimately exceeded the quota
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
Cause: quota metrics and limits apply to the whole API, and only the values
from the most recently created API config are enforced. A gateway that still
serves an older config fails if its methods charge a metric that the newest
config renamed or removed
([About quotas](https://docs.cloud.google.com/api-gateway/docs/quotas-overview.md.txt)).
Confirm by comparing the newest config with each config that a gateway still
serves (commands in
[triage-and-logs.md](triage-and-logs.md#inspect-the-deployed-api-config)).
The documented fixes, both changes that need approval:
1. Update every gateway of the API to the most recently created API config.
2. Create a new API config that declares every metric used by the configs
still deployed.
For changes to quota definitions, hand off to the
`api-gateway-backend-security-and-rate-limiting` skill.
## Deleting an API config fails
A config that a gateway still uses can't be deleted. First deploy a different
config to the gateway, or delete the gateway
([Create an API config](https://docs.cloud.google.com/api-gateway/docs/creating-api-config.md.txt)).
## gateways create or update fails
- **Deadline above 600 seconds.** A non-streaming gateway rejects it at create
or update time, even though the API config was accepted. See
[backend-routing-and-timeouts.md](backend-routing-and-timeouts.md#504-and-slow-responses).
- **Streaming mode change.** You can't update a gateway to change its
streaming mode; create a new gateway
([Deploy an API to a gateway](https://docs.cloud.google.com/api-gateway/docs/deploying-api.md.txt)).
- **Gateway limit.** A region allows 50 gateways.
## gcloud api-gateway commands fail
Running `gcloud api-gateway` commands needs an up-to-date Google Cloud CLI and
the required services enabled
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
Check the CLI version and the enabled services before you look further.
limits-and-escalation.md 4.4 KB
# Limits, quotas, unsupported features, and escalation
- [Product limits](#product-limits): Lines 9-24
- [429 from the API's own quota](#429-from-the-apis-own-quota): Lines 26-33
- [Requesting a quota increase](#requesting-a-quota-increase): Lines 35-42
- [Documented limitations](#documented-limitations): Lines 44-55
- [Escalate to Cloud Customer Care](#escalate-to-cloud-customer-care): Lines 57-77
## Product limits
From [Quotas and limits](https://docs.cloud.google.com/api-gateway/docs/quotas.md.txt):
| Limit | Value |
| :--- | :--- |
| APIs | 50 total |
| API configs | 100 per API |
| Gateways | 50 per region |
| Request size | 32 megabytes |
| Response size | 32 megabytes; streamed and chunked responses are exempt |
| gRPC transcoding request or response | 1 megabyte |
| Request headers | 60 kilobytes |
| OpenAPI 3.x upload | 10 MB in total and 50 files ([OpenAPI 3.x limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)) |
Quote limits from the live page when you answer, because they change.
## 429 from the API's own quota
A `429` with `jsonPayload.responseDetails="service_control_quota_error"` means
the caller exceeded one of the API's quota limits. The limits enforced for
every gateway are the ones in the most recently created API config
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
Identify the method from `jsonPayload.apiMethod`, then hand off to the
`api-gateway-backend-security-and-rate-limiting` skill to change limits.
## Requesting a quota increase
Product quotas are adjusted through Cloud Quotas: in the Google Cloud console,
go to **IAM & Admin > Quotas & System Limits**, select the quota, and choose
**Edit**. Adjustment requests are subject to review, and if the console can't
submit the request, ask Cloud Customer Care
([Quotas and limits](https://docs.cloud.google.com/api-gateway/docs/quotas.md.txt)).
The user submits the request; don't submit it for them.
## Documented limitations
Explain these as product limitations rather than misconfigurations:
| Limitation | Source |
| :--- | :--- |
| Non-streaming gateways can't call Google Cloud APIs (`*.googleapis.com` backends can fail with `401`); streaming gateways can, with an access token that has only the `cloud-platform` scope | [Securing backend services](https://docs.cloud.google.com/api-gateway/docs/securing-backend-services.md.txt) |
| No ingress control settings; the gateway's own hostname can't be disabled | [Load balancing for API Gateway](https://docs.cloud.google.com/api-gateway/docs/gateway-load-balancing.md.txt) |
| Streaming gateways can't use a load balancer, serverless NEG, or custom domain (Public Preview) | [Configure streaming](https://docs.cloud.google.com/api-gateway/docs/streaming-configure.md.txt) |
| Streaming mode can't be changed after the gateway is created | [Deploy an API to a gateway](https://docs.cloud.google.com/api-gateway/docs/deploying-api.md.txt) |
| No partial-segment path templates; no OR between an API key and another scheme | [OpenAPI 2.0 limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-limitations.md.txt) |
| Scopes, parameters, and schemas are accepted but not enforced | [OpenAPI 2.0 limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-limitations.md.txt) |
## Escalate to Cloud Customer Care
Don't speculate about Google's internal systems. Draft the case text with this
evidence bundle, redact all credentials, and let the user file it at
[Cloud Customer Care](https://cloud.google.com/support):
```
Product: API Gateway
Project ID and number: {project_id} / {project_number}
Gateway ID and region: {gateway_id} / {region}
API ID and API config ID: {api_id} / {config_id}
Gateway hostname: {default_hostname}
Time window (UTC): {start_utc} to {end_utc}
Sample failing requests: {timestamp_utc} {method} {path} -> {status_code}
Log query used: gcloud logging read 'resource.type="apigateway.googleapis.com/Gateway" AND resource.labels.gateway_id="{gateway_id}" AND timestamp>="{start_utc}" AND timestamp<="{end_utc}"' --project={project_id} --limit=50 --format="json(timestamp,httpRequest.requestMethod,httpRequest.status,httpRequest.requestUrl,jsonPayload.responseDetails)"
responseDetails values: {response_details}
Failed operation IDs (control plane): {operation_ids}
Recent changes: {changes}
Steps already taken: {steps}
Reproduction (no credentials): curl -i https://{default_hostname}/{path}
```
networking-domains-tls.md 4.8 KB
# Custom domains, load balancers, TLS, and unreachable gateways
- [The request never reaches the gateway](#the-request-never-reaches-the-gateway): Lines 8-22
- [Custom domains and load balancers](#custom-domains-and-load-balancers): Lines 24-47
- [TLS versions and scanner findings](#tls-versions-and-scanner-findings): Lines 49-68
- [Network restrictions](#network-restrictions): Lines 70-85
## The request never reaches the gateway
If the caller gets an error but the gateway has no matching log entry, and the
service account and required APIs check out (see
[triage-and-logs.md](triage-and-logs.md#when-the-logs-are-empty)), and log
exclusions and a wrong scope are ruled out, the request probably stopped
before the gateway. Check, with read-only commands on the caller's machine:
1. **Host.** The URL's host matches a gateway's `defaultHostname`, or a custom
domain that routes to the gateway.
2. **DNS.** The host resolves (`nslookup {host}`). For a custom domain, it
resolves to the load balancer's IP address.
3. **TLS.** `curl -v https://{host}/{path}` completes the handshake. Use a
`GET` on a path that's safe to call, and note the TLS version the client
negotiates.
## Custom domains and load balancers
A custom domain for a gateway goes through a global external (or classic)
Application Load Balancer with a serverless NEG
([Use a custom domain](https://docs.cloud.google.com/api-gateway/docs/using-custom-domains.md.txt),
[Get started with load balancing for API Gateway](https://docs.cloud.google.com/api-gateway/docs/gateway-serverless-neg.md.txt)).
Check these documented constraints
([Load balancing for API Gateway](https://docs.cloud.google.com/api-gateway/docs/gateway-load-balancing.md.txt)):
- The domain's DNS A or AAAA record must point to the load balancer's IP
address. DNS changes can take from seconds to hours to propagate.
- A serverless NEG can point only to gateways in the NEG's own region, and
only to gateways in the same project as the load balancer. One NEG can
target several gateways through a URL mask.
- Gateways with streaming enabled can't sit behind a load balancer or
serverless NEG, so they can't use custom domains during Public Preview.
- API Gateway doesn't support ingress control settings, so the gateway's own
hostname stays reachable even when a load balancer is in front of it.
Callers can reach that hostname directly and bypass the load balancer's
controls, such as Cloud Armor, so keep API key or JWT authentication on
the gateway.
For building or changing the load balancer itself, hand off to the
`google-cloud-global-frontend-configuration` skill.
## TLS versions and scanner findings
API Gateway enforces TLS 1.2 or later. Clients that connect with TLS 1.1 or
earlier complete the handshake and then get
`400 Bad Request - The request was malformed`. External SSL-checking sites may
see the successful handshake and wrongly report that TLS 1.1 and earlier are
supported
([Release notes, July 23, 2025](https://docs.cloud.google.com/api-gateway/docs/release-notes.md.txt)).
- For a scanner finding, repeat the test with a client pinned to TLS 1.1, and
show the `400` response as evidence that the request is refused.
- For control over minimum TLS versions and cipher suites, put a global
external Application Load Balancer with an SSL policy in front of the
gateway
([Use SSL policies](https://docs.cloud.google.com/load-balancing/docs/use-ssl-policies.md.txt)).
The SSL policy applies only to the load balancer's frontend; the gateway's
own hostname keeps API Gateway's TLS settings, so a scanner pointed at it
gives the same result. This doesn't apply to streaming gateways.
- The release note says that an opt-out from TLS 1.2+ enforcement is
available through Cloud Customer Care.
## Network restrictions
- **Callers by IP address.** The gateway's hostname can't be closed to the
internet. To filter callers, use authentication on the gateway and, if
needed, Cloud Armor on a load balancer in front of it.
- **Backends that only accept private or allowlisted traffic.** The public
API Gateway docs describe serverless backends reached at an `https`
address and secured with IAM. They don't document fixed outbound IP
addresses or private network connectivity for gateways. Recommend
IAM-based backend authentication (see [auth-errors.md](auth-errors.md)),
and escalate if the design depends on private connectivity.
- **VPC Service Controls.** Check the
[supported products page](https://docs.cloud.google.com/vpc-service-controls/docs/supported-products.md.txt)
before you assume a perimeter covers API Gateway. Model routing gateways
don't support VPC Service Controls
([Model routing overview](https://docs.cloud.google.com/api-gateway/docs/model-routing-overview.md.txt)).
triage-and-logs.md 7.6 KB
# Triage, logs, and inspection commands
- [Identify the gateway](#identify-the-gateway): Lines 13-47
- [Read the gateway logs](#read-the-gateway-logs): Lines 49-84
- [When the logs are empty](#when-the-logs-are-empty): Lines 86-99
- [Metrics](#metrics): Lines 101-106
- [Inspect the deployed API config](#inspect-the-deployed-api-config): Lines 108-128
- [Inspect the backend](#inspect-the-backend): Lines 130-161
All commands are read-only. Prefix each `gcloud` command as described in
[attribution.md](attribution.md).
## Identify the gateway
Match the request host against the `defaultHostname` of each gateway. The
release notes put it plainly: to get a gateway's URL, read its
`defaultHostname` property. Hostnames come in these shapes
([Configure streaming](https://docs.cloud.google.com/api-gateway/docs/streaming-configure.md.txt),
[Deploy an API to a gateway](https://docs.cloud.google.com/api-gateway/docs/deploying-api.md.txt)):
| Gateway | `defaultHostname` shape |
| :--- | :--- |
| Non-streaming | `{gateway_id}-{hash}.{region_code}.gateway.dev`, for example `my-gateway-a12bcd345e67f89g0h.uc.gateway.dev`. The deploy and streaming pages name the parts differently, so match the whole hostname. |
| Streaming, and model-routing gateways that got the newer format (possible for gateways created on or after September 3, 2026) | `{gateway_id}-{project_number}.{region}.gateway.dev` |
| Older streaming gateways, and model-routing gateways created earlier | A `*.run.app` hostname, kept permanently |
A `run.app` host can therefore be a gateway, not a Cloud Run service. Check
`gateways list` before you treat it as Cloud Run.
**Custom domain.** A custom domain's DNS A or AAAA record points at a global
external (or classic) Application Load Balancer. Its serverless NEG targets a
gateway, or several gateways through a URL mask, in the NEG's own region and
the load balancer's project
([Use a custom domain](https://docs.cloud.google.com/api-gateway/docs/using-custom-domains.md.txt),
[Load balancing for API Gateway](https://docs.cloud.google.com/api-gateway/docs/gateway-load-balancing.md.txt)).
To trace it, match the domain's IP address to a forwarding rule, then find the
NEG and the gateway it targets:
```bash
gcloud compute forwarding-rules list --project={project_id}
gcloud compute network-endpoint-groups list --project={project_id}
gcloud compute network-endpoint-groups describe {neg_name} --region={region} --project={project_id}
```
**Streaming mode.** `gateways describe` reports `effectiveStreamingMode`; see
[backend-routing-and-timeouts.md](backend-routing-and-timeouts.md#streaming-and-grpc-notes)
for what it limits.
## Read the gateway logs
API Gateway writes these platform logs. The first three use the
`apigateway.googleapis.com/Gateway` resource; produced API logs use
`resource.type="api"`
([Platform logs](https://docs.cloud.google.com/api-gateway/docs/platform-logging.md.txt)):
| Log | Use it for |
| :--- | :--- |
| `apigateway.googleapis.com%2Frequests` | One entry per request: status, latency, `responseDetails`, sizes |
| `apigateway.googleapis.com%2Fjwks_queries` | Failed or successful fetches of the JWT signing keys (`x-google-jwks_uri`) |
| `apigateway.googleapis.com%2Fservice_control_queries` | Written only when a Service Control `check` or `report` call fails (API keys, quota) |
| Produced API logs (`resource.type="api"`) | All gateways that serve one managed service |
Base filter (add one of the lines below it):
```
resource.type="apigateway.googleapis.com/Gateway"
resource.labels.gateway_id="{gateway_id}"
resource.labels.location="{region}"
```
| Goal | Extra filter line |
| :--- | :--- |
| One status code | `httpRequest.status={status_code}` |
| A time window | `timestamp>="{start_utc}" AND timestamp<="{end_utc}"` |
| JWT key fetches | `logName="projects/{project_id}/logs/apigateway.googleapis.com%2Fjwks_queries"` |
| Service Control failures | `logName="projects/{project_id}/logs/apigateway.googleapis.com%2Fservice_control_queries"` |
| Quota rejections | `jsonPayload.responseDetails="service_control_quota_error"` |
Run it with `gcloud logging read '{filter}' --project={project_id}
--freshness=1h --limit=20`. For the `requests` log, add the `--format` field
list from step 4 of SKILL.md. In each entry, `jsonPayload.apiConfig` and
`jsonPayload.apiMethod` identify the API config and method that served the
request
([Troubleshooting overview](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt)).
## When the logs are empty
- **Required APIs missing.** When the API responds but the logs have no data,
the usual cause is that not all of `apigateway.googleapis.com`,
`servicemanagement.googleapis.com`, and `servicecontrol.googleapis.com` are
enabled.
- **Client got `500` and there's no entry.** The gateway's service account
may be deleted or disabled; see [auth-errors.md](auth-errors.md).
- **Logs excluded.** A log sink exclusion filter can drop entries before
they're stored; check the project's sinks
([Routing overview](https://docs.cloud.google.com/logging/docs/routing/overview.md.txt)).
- **Wrong scope.** Recheck the project, region, and gateway ID from step 2.
- **The request never reached the gateway.** See
[networking-domains-tls.md](networking-domains-tls.md).
## Metrics
In Metrics Explorer, select **API Gateway > Proxy > Request Count**, and group
by `response_code_class`, `api_config`, `gateway_id`, or `location` to see when
errors started and which API config was serving
([Monitoring your API](https://docs.cloud.google.com/api-gateway/docs/monitoring.md.txt)).
## Inspect the deployed API config
List an API's configs, newest first:
```bash
gcloud api-gateway api-configs list --api={api_id} --project={project_id} \
--format="table(name.basename(),createTime:sort=1:reverse)"
```
Print the OpenAPI document a config was created from. The `tr` step is needed
because the `contents` field is base64url encoded:
```bash
gcloud api-gateway api-configs describe {config_id} --api={api_id} --project={project_id} \
--view=FULL --format="value(openapiDocuments[0].document.contents)" \
| tr '_-' '/+' | base64 --decode
```
Get the API's managed service name (used for API keys and produced API logs)
with `gcloud api-gateway apis describe {api_id} --project={project_id}
--format="value(managedService)"`.
## Inspect the backend
Find the service account that the gateway uses to call backends:
```bash
gcloud api-gateway api-configs describe {config_id} --api={api_id} --project={project_id} \
--format="value(gatewayServiceAccount)"
```
The value has the form `projects/-/serviceAccounts/{service_account_email}`.
If it's empty, rerun the command with `--view=FULL`. Pass only the email to
`gcloud iam service-accounts describe {service_account_email}`.
For a Cloud Run backend, read its ingress annotation
(`run.googleapis.com/ingress`) and its IAM policy:
```bash
gcloud run services describe {service} --region={backend_region} --project={backend_project} --format=yaml
gcloud run services get-iam-policy {service} --region={backend_region} --project={backend_project}
```
To check whether a request reached Cloud Run, read its request log:
```bash
gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.service_name="{service}" AND log_name="projects/{backend_project}/logs/run.googleapis.com%2Frequests" AND httpRequest.status={status_code}' \
--project={backend_project} --freshness=1h --limit=20 \
--format="json(timestamp,httpRequest.status,httpRequest.latency,httpRequest.requestUrl)"
```
Cloud Run documents that a request blocked by ingress settings returns `404`
and doesn't appear in this log
([Cloud Run troubleshooting](https://docs.cloud.google.com/run/docs/troubleshooting.md.txt)).
lint_openapi_for_gateway.py 25.2 KB
#!/usr/bin/env python3
"""Lints OpenAPI documents for documented API Gateway limitations.
The linter works offline and only reads the files that it is given. It reports
the OpenAPI features that the public API Gateway documentation describes as
unsupported, rejected, or ignored, so that you can fix them before you create
an API config. Each finding links to the page that documents the limitation.
Pass all OpenAPI files of one API config together. JSON input needs only the
Python standard library. YAML input needs PyYAML.
"""
from __future__ import annotations
import argparse
import collections
from collections.abc import Iterator
import json
import os
import re
import sys
from typing import Any
from urllib import parse
try:
import yaml # pylint: disable=g-import-not-at-top
_HAS_YAML = True
except ImportError:
_HAS_YAML = False
_DOCS = 'https://docs.cloud.google.com/api-gateway/docs/'
# LIMITS and EXTENSIONS resolve to the page for the OpenAPI version of a file.
_PAGES = {
('LIMITS', False): _DOCS + 'openapi-limitations.md.txt',
('LIMITS', True): _DOCS + 'openapi-v3-limitations.md.txt',
('EXTENSIONS', False): _DOCS + 'oasv2-extensions.md.txt',
('EXTENSIONS', True): _DOCS + 'oasv3-extensions.md.txt',
}
_V3_LIMITS = _PAGES[('LIMITS', True)]
_BACKENDS = _DOCS + 'securing-backend-services.md.txt'
_OVERVIEW = _DOCS + 'openapi-overview.md.txt'
# Documented limits. The messages in _FINDINGS repeat them.
_MAX_YAML_ALIASES = 200
_MAX_DEADLINE_SECONDS = 3600
_MAX_NON_STREAMING_DEADLINE_SECONDS = 600
_OAS3_MAX_FILES = 50
# The documented limit is 10MB. The binary reading is the larger one, so the
# check never flags files that are within the limit under either reading.
_OAS3_MAX_BYTES = 10 * 1024 * 1024
# Rule ID, with an optional ":variant" suffix: (severity, page, message).
# fmt: off
_FINDINGS = {
'PARTIAL_SEGMENT_PATH_TEMPLATE': ('ERROR', 'LIMITS', (
'Make each parameter in path {path} an entire path segment, such as'
' /items/{{itemId}}, because API Gateway rejects partial segments.')),
'EXTERNAL_REF': ('ERROR', 'LIMITS', (
'Replace $ref {ref} with a local reference (#/...), because API Gateway'
' does not support references outside the provided OpenAPI document.')),
'EXTERNAL_REF:between_files': ('WARNING', 'LIMITS', (
'Prefer a local reference (#/...) over $ref {ref}, because the docs do'
' not say whether references between uploaded files are supported.')),
'HOST_CUSTOM_PORT': ('ERROR', 'LIMITS', (
'Remove the port from {field} {value}, because API Gateway does not'
' allow custom ports in {field}.')),
'API_KEY_IN_LOGICAL_OR': ('ERROR', 'LIMITS', (
'Put the API key in every alternative (logical OR), because API'
' Gateway supports alternatives with an API key only if every'
' alternative has one.')),
'API_KEY_IN_LOGICAL_OR:oas2': ('WARNING', 'LIMITS', (
'Put the API key in every alternative (logical OR), because API'
' Gateway supports alternatives with an API key only if every'
' alternative has one.')),
'OAUTH_LOGICAL_AND': ('ERROR', 'LIMITS', (
'Keep one of the OAuth2 schemes {names} or make them alternatives,'
' because API Gateway does not support a logical AND of OAuth2'
' schemes.')),
'OPTIONAL_SECURITY_WITH_OAUTH': ('ERROR', 'LIMITS', (
'Remove the empty requirement ({{}}) from this list, because API'
' Gateway supports optional security for API keys but not for OAuth.')),
'OPTIONAL_SECURITY_WITH_OAUTH:oas2': ('WARNING', 'LIMITS', (
'Remove the empty requirement ({{}}) from this list, because API'
' Gateway supports optional security for API keys but not for OAuth.')),
'UNDEFINED_SECURITY_SCHEME': ('ERROR', 'LIMITS', (
'Define security scheme {name} in {definitions} or remove it, because'
' API Gateway rejects a requirement without a matching definition.')),
'UNDEFINED_SECURITY_SCHEME:oas2': ('WARNING', 'LIMITS', (
'Define security scheme {name} in {definitions} or remove it. The docs'
' say that API Gateway rejects an undefined scheme in OpenAPI 3.x, and'
' they don\'t say what happens in OpenAPI 2.0.')),
'SCOPES_NOT_ENFORCED': ('INFO', 'LIMITS', (
'Enforce the scopes of {name} in your backend if you need them, because'
' API Gateway does not check or enforce scopes.')),
'YAML_ALIAS_LIMIT': ('ERROR', 'LIMITS', (
'Reduce the YAML alias nodes from {count} to 200 or fewer, because API'
' Gateway accepts at most 200 per document.')),
'DEADLINE_ABOVE_MAX': ('ERROR', 'EXTENSIONS', (
'Lower deadline {deadline} to 3600 seconds or less, because 3600'
' seconds is the maximum configurable deadline.')),
'DEADLINE_ABOVE_NON_STREAMING_MAX': ('WARNING', 'EXTENSIONS', (
'Lower deadline {deadline} to 600 seconds or less unless all gateways'
' for this config are streaming-enabled, because a non-streaming'
' gateway rejects it at gateway create or update.')),
'GOOGLEAPIS_BACKEND': ('ERROR', _BACKENDS, (
'Route this backend to your own service instead of {host}, because API'
' Gateway does not support proxying to other Google Cloud APIs.')),
'JWT_AUDIENCE_AND_DISABLE_AUTH': ('ERROR', 'EXTENSIONS', (
'Set only one of {audience} and {disable} on this backend.')),
'WRONG_VERSION_EXTENSION': ('WARNING', 'EXTENSIONS', (
'{fix}, because {extension} is documented only for OpenAPI'
' {other}.')),
'X_GOOGLE_ALLOW_IN_OAS3': ('ERROR', _V3_LIMITS, (
'Remove x-google-allow and define every path the gateway serves,'
' because API Gateway does not support x-google-allow for OpenAPI'
' 3.x.')),
'MULTIPLE_X_GOOGLE_ENDPOINT_SERVERS': ('ERROR', _V3_LIMITS, (
'Keep x-google-endpoint on only one of {servers}, because API Gateway'
' permits only one server with x-google-endpoint.')),
'INVALID_SERVER_URL': ('ERROR', _V3_LIMITS, (
'Change server URL {url!r} to a URL with a scheme or a base path that'
' begins with /, because API Gateway rejects other server URLs.')),
'OAS3_SIZE_OR_FILE_COUNT': ('ERROR', _V3_LIMITS, (
'Reduce the OpenAPI 3.x files ({count} files, {size} bytes) to at most'
' 50 files and 10 MB in total, because API Gateway enforces both.')),
'UNSUPPORTED_OPENAPI_VERSION': ('ERROR', _OVERVIEW, (
'Declare swagger: "2.0", openapi: 3.0.x, or openapi: 3.1.x (found'
' {found}), because API Gateway supports only these versions.')),
}
# fmt: on
_SEVERITY_RANK = {'ERROR': 0, 'WARNING': 1, 'INFO': 2}
_SUMMARY_KEYS = {'errors': 'ERROR', 'warnings': 'WARNING', 'info': 'INFO'}
# Extensions that only the extensions page of one OpenAPI version documents,
# mapped to the fix in a document of the other version, or None if the other
# version has no replacement.
_V2_ONLY_EXTENSIONS = {
'x-google-api-name': 'Use x-google-api-management.apiName instead',
'x-google-audiences': 'Use x-google-auth.audiences instead',
'x-google-endpoints': 'Use x-google-endpoint on a server object instead',
'x-google-issuer': 'Use x-google-auth.issuer instead',
'x-google-jwks_uri': 'Use x-google-auth.jwksUri instead',
'x-google-jwt-locations': 'Use x-google-auth.jwtLocations instead',
'x-google-management': 'Use x-google-api-management instead',
}
_V3_ONLY_EXTENSIONS = {
'x-google-api-management': (
'Use x-google-management, x-google-backend, and x-google-api-name'
),
'x-google-auth': (
'Use x-google-issuer, x-google-jwks_uri, x-google-audiences, and'
' x-google-jwt-locations instead'
),
'x-google-endpoint': 'Use a top-level x-google-endpoints list instead',
'x-google-mcp-tool': None,
'x-google-model-router': None,
'x-google-parameter': 'Use the {name=**} path template syntax instead',
}
_HTTP_METHODS = 'get put post delete options head patch trace'.split()
_PARAM_RE = re.compile(r'\{[^{}]*\}')
_EPILOG = """\
examples:
python3 scripts/lint_openapi_for_gateway.py openapi.yaml
python3 scripts/lint_openapi_for_gateway.py main.yaml extra.yaml --format text
stdout: {files, openapi_version, findings, summary}; each finding has rule,
severity, file, location, message, and doc. Diagnostics go to stderr.
exit codes:
0 no ERROR findings (WARNING and INFO findings are allowed)
1 at least one ERROR finding
2 usage, file, parse, or dependency error
"""
class InputError(Exception):
"""A file, parse, or dependency problem that ends the run with exit code 2."""
def _child(location: str, key: Any) -> str:
return f'{location}.{key}' if location else str(key)
def _items(node: Any) -> list[tuple[Any, Any]]:
return list(node.items()) if isinstance(node, dict) else []
def _list(node: Any) -> list[Any]:
return node if isinstance(node, list) else []
def _get(node: Any, *keys: str) -> Any:
"""Returns node[key1][key2]..., or None if a level is not a mapping."""
for key in keys:
node = node.get(key) if isinstance(node, dict) else None
return node
def _mappings(node: Any) -> Iterator[tuple[str, dict[Any, Any]]]:
"""Yields (location, mapping) for each mapping in node, in document order.
The walk is iterative and visits each object once, so YAML aliases and
recursive anchors cannot make it loop or repeat work.
Args:
node: A parsed document, or any part of one.
Yields:
A (location, mapping) tuple for each mapping, where location is the
dotted path of the mapping in the document.
"""
seen: set[int] = set()
stack: list[tuple[str, Any]] = [('', node)]
while stack:
location, current = stack.pop()
if not isinstance(current, (dict, list)) or id(current) in seen:
continue
seen.add(id(current))
if isinstance(current, dict):
yield location, current
children = [(_child(location, k), v) for k, v in current.items()]
else:
children = [(f'{location}[{i}]', v) for i, v in enumerate(current)]
stack.extend(reversed(children))
def _operations(doc: dict[str, Any]) -> Iterator[tuple[str, dict[str, Any]]]:
for path, item in _items(doc.get('paths')):
for method in _HTTP_METHODS:
if isinstance(_get(item, method), dict):
yield f'paths.{path}.{method}', item[method]
def _is_partial_segment(path: str) -> bool:
"""Returns whether a parameter of a path template is a partial segment.
The last segment can end with a custom method, such as /items/{id}:undelete.
Args:
path: A path template from the paths object, such as /items/{id}.
"""
if re.search(r'[{}]', _PARAM_RE.sub('', path)):
return True # Nested or unbalanced braces.
for match in _PARAM_RE.finditer(path):
starts_segment = path[: match.start()].endswith('/')
rest = path[match.end() :]
custom_method = rest[:1] == ':' and '/' not in rest
if not starts_segment or not (rest[:1] in ('', '/') or custom_method):
return True
return False
def _host(url: str) -> str:
"""Returns the lowercase host of a URL, which may omit its scheme."""
try:
host = parse.urlsplit(url if '://' in url else '//' + url).hostname
except ValueError:
return ''
return (host or '').rstrip('.')
def _has_port(url: str) -> bool:
try:
return parse.urlsplit(url).port is not None
except ValueError:
return False
def _version(doc: dict[str, Any]) -> str:
"""Returns '2.0', '3.0.x', '3.1.x', or 'unknown' for a parsed document."""
if str(doc.get('swagger')) == '2.0':
return '2.0'
match = re.fullmatch(r'3\.([01])(\.\d+)?', str(doc.get('openapi')))
return f'3.{match.group(1)}.x' if match else 'unknown'
def _model_router_backends(doc: dict[str, Any]) -> set[str]:
"""Returns the names of the backends that model routers send requests to."""
routers = _get(
doc, 'x-google-api-management', 'ai', 'models', 'routing', 'routers'
)
names = set()
for _, router in _items(routers):
names.add(_get(router, 'defaultModel', 'backend'))
names.update(_get(rule, 'backend') for rule in _list(_get(router, 'rules')))
return {name for name in names if isinstance(name, str)}
def load_spec(path: str) -> tuple[dict[str, Any], int, int | None]:
"""Returns the parsed document, its size, and its YAML alias count.
Args:
path: The path of a JSON or YAML OpenAPI file.
Returns:
A tuple of the parsed document, its size in bytes, and its YAML alias
count. The alias count is None for JSON input.
Raises:
InputError: If the file cannot be read or parsed, or if it is YAML and
PyYAML is not installed.
"""
try:
with open(path, 'rb') as f:
raw = f.read()
text = raw.decode('utf-8-sig')
except (OSError, UnicodeDecodeError) as exc:
raise InputError(f'Cannot read {path}: {exc}') from exc
aliases = None
try:
doc = json.loads(text)
except (ValueError, RecursionError) as exc:
if path.lower().endswith('.json'):
raise InputError(f'{path} is not valid JSON: {exc}') from exc
if not _HAS_YAML:
raise InputError(
f'{path} is not JSON, and reading YAML requires PyYAML. Install it'
' with: pip install "PyYAML>=6.0,<7.0"'
) from exc
try:
events = yaml.parse(text, Loader=yaml.SafeLoader)
aliases = sum(isinstance(event, yaml.AliasEvent) for event in events)
doc = yaml.safe_load(text)
except (yaml.YAMLError, RecursionError) as yaml_exc:
raise InputError(f'{path} is not valid YAML: {yaml_exc}') from yaml_exc
if not isinstance(doc, dict):
raise InputError(f'{path} must contain a JSON object or a YAML mapping.')
return doc, len(raw), aliases
class Linter:
"""Collects the findings for the OpenAPI files of one API config."""
def __init__(self, paths: list[str]):
self.findings: list[dict[str, Any]] = []
self._all_files = {os.path.abspath(path) for path in paths}
self._multi_file = len(paths) > 1
self._file: str | None = None
self._v3 = False
def _add(self, finding: str, location: str, /, **values: Any) -> None:
severity, page, message = _FINDINGS[finding]
self.findings.append({
'rule': finding.split(':')[0],
'severity': severity,
'file': self._file,
'location': location,
'message': message.format(**values),
'doc': _PAGES.get((page, self._v3), page),
})
def lint_file(
self, path: str, doc: dict[str, Any], version: str, aliases: int | None
) -> None:
"""Checks one parsed file that declares the given OpenAPI version."""
self._file, self._v3 = path, version.startswith('3')
if version == 'unknown':
found = {k: doc[k] for k in ('swagger', 'openapi') if k in doc}
self._add(
'UNSUPPORTED_OPENAPI_VERSION',
'(document)',
found=found or 'no version field',
)
if aliases is not None and aliases > _MAX_YAML_ALIASES:
self._add('YAML_ALIAS_LIMIT', '(document)', count=aliases)
for template, _ in _items(doc.get('paths')):
if isinstance(template, str) and _is_partial_segment(template):
self._add(
'PARTIAL_SEGMENT_PATH_TEMPLATE', f'paths.{template}', path=template
)
self._check_keys(doc, version != 'unknown')
if version == 'unknown':
return
self._check_security(doc)
if self._v3:
self._check_servers(doc)
model_backends = _model_router_backends(doc)
backends = _get(doc, 'x-google-api-management', 'backends')
for name, backend in _items(backends):
self._check_backend(
f'x-google-api-management.backends.{name}',
backend,
('jwtAudience', 'disableAuth'),
name in model_backends,
)
return
host = doc.get('host')
if isinstance(host, str) and re.search(r':\d+$', host):
self._add('HOST_CUSTOM_PORT', 'host', field='host', value=host)
backends = [('x-google-backend', doc.get('x-google-backend'))] + [
(f'{location}.x-google-backend', operation.get('x-google-backend'))
for location, operation in _operations(doc)
]
for location, backend in backends:
self._check_backend(
location, backend, ('jwt_audience', 'disable_auth'), False
)
def lint_set(self, sizes: list[int]) -> None:
"""Checks the limits for the OpenAPI 3.x files of an API config."""
self._file, self._v3 = None, True
if len(sizes) > _OAS3_MAX_FILES or sum(sizes) > _OAS3_MAX_BYTES:
self._add(
'OAS3_SIZE_OR_FILE_COUNT',
'(all files)',
count=len(sizes),
size=sum(sizes),
)
def _check_keys(self, doc: dict[str, Any], known_version: bool) -> None:
"""Checks $ref values and version-specific extensions in all mappings."""
if self._v3:
wrong, other, backend_form = _V2_ONLY_EXTENSIONS, '2.0', (dict, 'object')
backend_fix = (
'Set x-google-backend to the name of a backend in'
' x-google-api-management.backends'
)
else:
wrong, other, backend_form = _V3_ONLY_EXTENSIONS, '3.x', (str, 'string')
backend_fix = 'Set x-google-backend to an object with an address field'
for location, mapping in _mappings(doc):
for key, value in mapping.items():
where = _child(location, key)
if key == '$ref' and isinstance(value, str) and value[:1] != '#':
self._check_ref(where, value)
elif not known_version:
continue
elif key == 'x-google-allow' and self._v3:
self._add('X_GOOGLE_ALLOW_IN_OAS3', where)
elif key in wrong:
self._add(
'WRONG_VERSION_EXTENSION',
where,
fix=wrong[key] or f'Remove {key} or migrate to OpenAPI 3.x',
extension=key,
other=other,
)
elif key == 'x-google-backend' and isinstance(value, backend_form[0]):
self._add(
'WRONG_VERSION_EXTENSION',
where,
fix=backend_fix,
extension=f'its {backend_form[1]} form',
other=other,
)
def _check_ref(self, location: str, ref: str) -> None:
"""Checks a $ref that does not point inside the same document."""
base = os.path.dirname(os.path.abspath(self._file or ''))
target = os.path.normpath(os.path.join(base, ref.split('#', 1)[0]))
if self._multi_file and '://' not in ref and target in self._all_files:
self._add('EXTERNAL_REF:between_files', location, ref=ref)
else:
self._add('EXTERNAL_REF', location, ref=ref)
def _check_security(self, doc: dict[str, Any]) -> None:
"""Checks the top-level and operation-level security requirements."""
if self._v3:
definitions = 'components.securitySchemes'
schemes = _get(doc, 'components', 'securitySchemes')
else:
definitions = 'securityDefinitions'
schemes = doc.get('securityDefinitions')
types = {name: _get(scheme, 'type') for name, scheme in _items(schemes)}
# The limitations pages document these rejections for OpenAPI 3.x only.
variant = '' if self._v3 else ':oas2'
lists = [('security', doc.get('security'))] + [
(f'{location}.security', operation.get('security'))
for location, operation in _operations(doc)
]
scoped = set()
for location, requirements in lists:
for index, requirement in enumerate(_list(requirements)):
for name, scopes in _items(requirement):
where = f'{location}[{index}].{name}'
if name not in types:
self._add(
'UNDEFINED_SECURITY_SCHEME' + variant,
where,
name=name,
definitions=definitions,
)
if _list(scopes) and name not in scoped:
scoped.add(name)
self._add('SCOPES_NOT_ENFORCED', where, name=name)
oauth = [
str(name)
for name, _ in _items(requirement)
if types.get(name) == 'oauth2'
]
if len(oauth) > 1:
self._add(
'OAUTH_LOGICAL_AND',
f'{location}[{index}]',
names=', '.join(oauth),
)
objects = [r for r in _list(requirements) if isinstance(r, dict)]
alternatives = [r for r in objects if r]
kinds = set()
with_api_key = 0
for alternative in alternatives:
alternative_kinds = {types.get(name) for name in alternative}
kinds.update(alternative_kinds)
with_api_key += 'apiKey' in alternative_kinds
if len(alternatives) == len(objects) and (
0 < with_api_key < len(alternatives)
):
self._add('API_KEY_IN_LOGICAL_OR' + variant, location)
if len(alternatives) < len(objects) and 'oauth2' in kinds:
self._add('OPTIONAL_SECURITY_WITH_OAUTH' + variant, location)
def _check_servers(self, doc: dict[str, Any]) -> None:
"""Checks the server URLs and x-google-endpoint of an OpenAPI 3.x file."""
endpoints = []
for index, server in enumerate(_list(doc.get('servers'))):
if not isinstance(server, dict):
continue
if 'x-google-endpoint' in server:
endpoints.append(f'servers[{index}]')
url, where = server.get('url'), f'servers[{index}].url'
if not isinstance(url, str) or not (url[:1] == '/' or '://' in url):
self._add('INVALID_SERVER_URL', where, url=url)
elif _has_port(url):
self._add('HOST_CUSTOM_PORT', where, field='servers.url', value=url)
if len(endpoints) > 1:
self._add(
'MULTIPLE_X_GOOGLE_ENDPOINT_SERVERS',
'servers',
servers=', '.join(endpoints),
)
def _check_backend(
self,
location: str,
backend: Any,
auth_keys: tuple[str, str],
model_backend: bool,
) -> None:
"""Checks an OpenAPI 2.0 x-google-backend or an OpenAPI 3.x backend."""
if not isinstance(backend, dict):
return
deadline = backend.get('deadline')
if isinstance(deadline, (int, float)) and not isinstance(deadline, bool):
if deadline > _MAX_DEADLINE_SECONDS:
self._add(
'DEADLINE_ABOVE_MAX', f'{location}.deadline', deadline=deadline
)
elif deadline > _MAX_NON_STREAMING_DEADLINE_SECONDS:
self._add(
'DEADLINE_ABOVE_NON_STREAMING_MAX',
f'{location}.deadline',
deadline=deadline,
)
address = backend.get('address')
host = _host(address) if isinstance(address, str) else ''
# The documented model routing example uses a googleapis.com backend.
if not model_backend and (
host == 'googleapis.com' or host.endswith('.googleapis.com')
):
self._add('GOOGLEAPIS_BACKEND', f'{location}.address', host=host)
audience, disable = auth_keys
if audience in backend and disable in backend:
self._add(
'JWT_AUDIENCE_AND_DISABLE_AUTH',
location,
audience=audience,
disable=disable,
)
def _format_text(report: dict[str, Any]) -> str:
"""Returns the report as human-readable text, for --format text."""
lines = []
for finding in report['findings']:
where = finding['location']
if finding['file']:
where = f'{finding["file"]}: {where}'
lines.append(f'{finding["severity"]} {finding["rule"]} at {where}')
lines.append(f' {finding["message"]}\n {finding["doc"]}')
summary = report['summary']
lines.append(
f'{len(report["files"])} file(s), OpenAPI {report["openapi_version"]}:'
f' {summary["errors"]} error(s), {summary["warnings"]} warning(s),'
f' {summary["info"]} info finding(s).'
)
return '\n'.join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=__doc__,
epilog=_EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'specs',
nargs='+',
metavar='SPEC',
help='OpenAPI file of the API config (JSON, or YAML with PyYAML).',
)
parser.add_argument(
'--format',
choices=('json', 'text'),
default='json',
help='Output format on stdout (default: json).',
)
args = parser.parse_args(argv)
paths = list(dict.fromkeys(args.specs))
try:
loaded = [(path, *load_spec(path)) for path in paths]
except InputError as exc:
print(f'Error: {exc}', file=sys.stderr)
return 2
versions = {path: _version(doc) for path, doc, _, _ in loaded}
known = sorted(set(versions.values()) - {'unknown'})
if len(known) > 1:
print(
f'Error: This linter checks one OpenAPI version per run ({versions}).'
' Lint files that use different versions in separate runs.',
file=sys.stderr,
)
return 2
version = known[0] if known else 'unknown'
linter = Linter(paths)
for path, doc, _, aliases in loaded:
linter.lint_file(path, doc, versions[path], aliases)
if version.startswith('3'):
linter.lint_set([size for _, _, size, _ in loaded])
findings = sorted(
linter.findings, key=lambda finding: _SEVERITY_RANK[finding['severity']]
)
counts = collections.Counter(finding['severity'] for finding in findings)
summary = {key: counts[severity] for key, severity in _SUMMARY_KEYS.items()}
report = {'files': paths, 'openapi_version': version, 'findings': findings}
report['summary'] = summary
if args.format == 'json':
print(json.dumps(report, indent=2))
else:
print(_format_text(report))
if summary['errors']:
print(
f'Found {summary["errors"]} ERROR finding(s). Fix them before you'
' create the API config.',
file=sys.stderr,
)
return 1 if summary['errors'] else 0
if __name__ == '__main__':
sys.exit(main())
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE