Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install api-gateway-backend-security-and-rate-limiting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin api-gateway-backend-security-and-rate-limiting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install api-gateway-backend-security-and-rate-limiting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/api-gateway-backend-security-and-rate-limiting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match api-gateway-backend-security-and-rate-limiting for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 15.2 KB
---
name: api-gateway-backend-security-and-rate-limiting
metadata:
version: "1.1.0"
category: Security
description: >-
Secures and rate limits backend services behind Google Cloud API Gateway
across OpenAPI 2.0 and OpenAPI 3.x API configurations, including MCP-enabled
gateways. Use when configuring API key or JWT authentication, locking down
Cloud Run or Cloud Run functions backends with a gateway service account,
reading authenticated claims from X-Apigateway-Api-Userinfo, setting
per-project request quotas, or changing quota metrics without the HTTP 500
"Failed to call Service Control Quota" error on older gateways. Do not use for
finding the cause of failing requests from gateway logs, such as an
unexplained HTTP 429 or 5xx (use api-gateway-troubleshooting), writing or
migrating a whole spec (use api-gateway-openapi-spec-authoring), MCP tool
setup (use api-gateway-mcp-server), Apigee, GKE Gateway API, Cloud Load
Balancing custom domain setup, or LLM model routing.
---
<!-- disableFinding(LINE_OVER_80) -->
# API Gateway Backend Security and Rate Limiting
This skill configures client authentication, gateway-to-backend authentication, and per-project rate limits (quotas) for Google Cloud API Gateway across OpenAPI 2.0 (`swagger: "2.0"`) and OpenAPI 3.x (3.0.x and 3.1.x, such as `openapi: 3.0.4`), including gateways with Model Context Protocol (MCP) enabled (Public Preview).
## 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).
## Prerequisites
1. **Install the Google Cloud CLI and Python 3.10+ YAML parser:**
- If `gcloud` is not installed, give the user the [Google Cloud CLI install guide](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt). Do not install it yourself. Until it is installed, give the user the commands to run, and continue from the output that they paste.
- If the gcloud CLI is old, ask the user before you run `gcloud components update`. An old gcloud CLI can fail when it uploads an OpenAPI 3.x spec.
- Install `PyYAML` for the quota metric validation script. Ask the user before you install it:
```bash
pip install "PyYAML>=6.0,<7.0"
```
2. **Authenticate your environment:**
- Local CLI session: `gcloud auth login`
- Application Default Credentials (SDKs): `gcloud auth application-default login`
- Service account key file (if required by CI): set `GOOGLE_APPLICATION_CREDENTIALS={key_file_path}`
3. **Select or create a project, verify billing, and pick a supported gateway location:**
- Ask the user which project to use, and use that ID as `{project_id}`. Pass `--project={project_id}` on every command. Do not run `gcloud config set project`, because it changes the default project for all other work of the user. If no project exists, create one with `gcloud projects create {project_id}` as an escape hatch.
- Verify that an active billing account is linked to `{project_id}` (required even when staying within the [API Gateway pricing free tier](https://cloud.google.com/api-gateway/pricing)).
- Use `us-central1` as the default `--location` for API Gateway commands. For the other supported regions, see [API Gateway deployment model](https://docs.cloud.google.com/api-gateway/docs/deployment-model.md.txt).
4. **Enable required Google Cloud APIs:**
```bash
gcloud services enable \
apigateway.googleapis.com \
servicemanagement.googleapis.com \
servicecontrol.googleapis.com \
iam.googleapis.com \
apikeys.googleapis.com \
--project={project_id}
```
API Gateway does not need the Cloud Run API. If the backend runs on Cloud Run, that API is already enabled in the backend's project.
5. **Verify required IAM roles:**
- To manage API Gateway resources and enable services: `roles/apigateway.admin` and `roles/serviceusage.serviceUsageAdmin`
- To create the gateway service account and attach it to an API config: `roles/iam.serviceAccountAdmin` and `roles/iam.serviceAccountUser`
- To manage API keys in consumer projects: `roles/serviceusage.apiKeysAdmin`
- To change the IAM policy of the Cloud Run backend (grant the invoker role, remove `allUsers`, and turn on the invoker IAM check): `roles/run.admin`, or another role with `run.services.get`, `run.services.getIamPolicy`, `run.services.setIamPolicy`, and `run.services.update`. For a 1st gen function backend: `roles/cloudfunctions.admin`
- For the gateway service account to invoke the backend: `roles/run.invoker` (Cloud Run or 2nd gen functions) or `roles/cloudfunctions.invoker` (1st gen functions)
## Decision Matrix: Client Authentication, Backend Security, and Quotas
Select the layer that matches the security requirement:
| Goal | Mechanism to Configure | Key Constraint | Detailed Reference |
| --- | --- | --- | --- |
| Identify the calling consumer project for quotas and billing | API key in the `x-api-key` header (use the `key` or `api_key` query parameter only as an escape hatch) | NEVER rely on an API key alone to authenticate end-user identity. **Rationale:** API keys identify a Google Cloud project rather than a user, and clients can extract them. API Gateway ignores an API key scheme with any other name or location, with no error, and the operation then accepts calls with no key. | [Client Authentication](references/client-authentication.md) |
| Authenticate end users or calling services | JWT (`oauth2` scheme with `x-google-issuer` / `x-google-jwks_uri` in OAS 2.0, or `x-google-auth` in OAS 3.x) | Operation-level `security` overrides root `security`. Include `api_key: []` and the JWT scheme in the same security requirement object when an endpoint needs both user identity and quotas. | [Client Authentication](references/client-authentication.md) |
| Block direct calls to the backend service | Dedicated gateway service account (`--backend-auth-service-account`) + `roles/run.invoker` + remove public invoker bindings from the backend and turn on its invoker IAM check | Every gateway of the API MUST serve a config with `--backend-auth-service-account` BEFORE you remove `allUsers` from a live backend. Otherwise those gateways get `403` errors. | [Backend Security](references/backend-security.md) |
| Rate limit requests per consumer project (`1/min/{project}`) | `x-google-management` (OAS 2.0) or `x-google-api-management` (OAS 3.x) + `x-google-quota` | Require the API key in every security alternative of a quota operation. NEVER rename or remove a quota metric when creating a new API config while any gateway of the API runs an older config referencing that metric. **Rationale:** Creating the config immediately overwrites API-wide quotas and causes `HTTP 500 Failed to call Service Control Quota` on older gateways. | [Quotas and Rate Limiting](references/quotas-and-rate-limiting.md) |
| Secure MCP `tools/list` and `tools/call` on `/mcp` (Public Preview) | `x-google-api-management.mcp.tools-list.security` (exactly one JWT or API key scheme) + operation `security` and `x-google-mcp-tool: false` | `x-google-mcp-tool: false` hides an operation from MCP only; the underlying REST route remains live unless secured or removed. An empty `tools-list.security` map leaves `tools/list` open. | [MCP Traffic Security](references/mcp-traffic-security.md) |
## Execution Workflow and Validation Loop
Follow this zero-downtime sequence when authoring or updating an API Gateway security or quota configuration:
1. **Create the gateway service account and grant backend invoker permissions:**
- Follow Steps 1–3 of [Backend Security](references/backend-security.md) to create `{gateway_sa_name}` and request human approval before granting `roles/run.invoker` on `{backend_service}`.
- If operations authenticate a JWT, update backend handler code to decode verified user claims from `X-Apigateway-Api-Userinfo` (`base64url`-encoded JSON) instead of `Authorization`. API Gateway sends this header only for operations with JWT auth.
2. **Author the OpenAPI authentication and quota definitions:**
- To write a whole spec, or to migrate a spec from OpenAPI 2.0 to 3.x, use the `api-gateway-openapi-spec-authoring` skill. If it is not installed, continue with this skill.
- Use the OpenAPI 2.0 or OpenAPI 3.x templates and provider tables in [Client Authentication](references/client-authentication.md) and [Quotas and Rate Limiting](references/quotas-and-rate-limiting.md).
- If the specification enables MCP (`x-google-api-management.mcp`), configure exactly one JWT or API key scheme on `tools-list` (also list a JWT scheme in the root `security` list), and review operation opt-outs using [MCP Traffic Security](references/mcp-traffic-security.md). To set up or name MCP tools, use the `api-gateway-mcp-server` skill. If it is not installed, see [Configure Model Context Protocol](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt).
3. **Run the quota metric validation loop BEFORE running `api-configs create`:**
- If neither the active specs nor `{candidate_openapi_spec}` define quota metrics (`x-google-management.metrics` or `x-google-api-management.metrics`), skip this step.
- Request human approval before creating an API config that defines or modifies quotas, because `api-configs create` immediately replaces quota definitions across all gateways of the API.
- By default, run `scripts/check_quota_metrics.py` against all active gateways deployed for `{api_id}` in `{project_id}`:
```bash
python3 scripts/check_quota_metrics.py \
--spec={candidate_openapi_spec} \
--project={project_id} \
--api={api_id}
```
- Escape hatch for offline environments without `gcloud` access (pass `--baseline-spec` for every config currently served by a gateway of the API):
```bash
python3 scripts/check_quota_metrics.py \
--spec={candidate_openapi_spec} \
--baseline-spec={previous_openapi_spec} \
--dry-run
```
- If `scripts/check_quota_metrics.py` exits with code `1` (`status: "FAIL"`), add the missing metrics and limits back to `{candidate_openapi_spec}`, move each `x-google-quota` listed in `ignored_quota_extensions` into the operations it applies to, and re-run the script until it exits with code `0` (`status: "PASS"`). If the user wants to remove a limit on purpose, confirm the removal with the user, because it removes that limit from every gateway of the API. If `skipped_configs` is not empty, tell the user that the script did not inspect those API configs (for example, gRPC configs), and check their quota metrics and limits manually. If it exits with code `2`, fix the problem printed to stderr: the CLI arguments, `gcloud` authentication, or an API config that the script cannot inspect.
4. **Create the API config, update the gateway, enable the managed service, and lock down the backend:**
- Follow Steps 4–5 of [Backend Security](references/backend-security.md) to run `gcloud api-gateway api-configs create` and `gcloud api-gateway gateways update` (request human approval before updating a production gateway), enable the API's `managedService` in consumer projects ([Client Authentication](references/client-authentication.md)), and then lock down `{backend_service}` (remove public invoker bindings and turn on the invoker IAM check).
- If `api-configs create` fails with an OpenAPI error, use the `api-gateway-openapi-spec-authoring` skill. If it fails with another error, such as an IAM or service account error, use the `api-gateway-troubleshooting` skill. If the skill is not installed, read the error text, and compare the spec with the templates in the references or the IAM roles in Prerequisites.
- Verify that direct calls to the backend URL (`*.run.app`, or `*.cloudfunctions.net` for a 1st gen function) return `403`, unauthenticated calls to the gateway `defaultHostname` return `401`, and authenticated calls return `200`.
- If you get another result, use the `api-gateway-troubleshooting` skill. If it is not installed, check which API config each gateway serves, and check the `roles/run.invoker` (or `roles/cloudfunctions.invoker`) binding of `{gateway_sa_name}` on `{backend_service}`.
## Pre-Deployment Checklist
- [ ] Dedicated `{gateway_sa_name}` is granted `roles/run.invoker` (or `roles/cloudfunctions.invoker`). Only after every gateway of the API serves a config with `--backend-auth-service-account`, public invoker bindings (`allUsers`, `allAuthenticatedUsers`) are removed and the invoker IAM check is on.
- [ ] If operations authenticate a JWT, backend code decodes `X-Apigateway-Api-Userinfo` for user claims.
- [ ] Security enforcement does not depend solely on a load balancer or Google Cloud Armor in front of the gateway, because the gateway's `defaultHostname` (`*.gateway.dev`) cannot be disabled.
- [ ] Every quota-enforced operation requires an API key (`api_key: []`) in every security alternative, and the API's `managedService` is enabled and allowed on the API key in each consumer project.
- [ ] `python3 scripts/check_quota_metrics.py` returns `status: "PASS"` (exit code `0`) against active gateway configs or all baseline specs before `api-configs create`.
- [ ] If MCP is enabled, `x-google-api-management.mcp.tools-list.security` names exactly one JWT or API key scheme (a JWT scheme is also in the root `security` list), and administrative endpoints are secured on REST in addition to `x-google-mcp-tool: false`.
## Resource Cleanup
To avoid ongoing charges when tearing down a test or staging environment, request human approval and delete the gateway, all API configs, and the API in dependency order:
```bash
gcloud api-gateway gateways delete {gateway_id} --location={region} --project={project_id}
gcloud api-gateway api-configs delete {config_id} --api={api_id} --project={project_id}
gcloud api-gateway apis delete {api_id} --project={project_id}
```
Delete the service account only if no other API config or gateway uses it. List the service account of every remaining API config in the project, and ask the user if other workloads use the account:
```bash
gcloud api-gateway api-configs list --project={project_id} --format="value(name,gatewayServiceAccount)"
```
If no remaining API config uses the account and the user confirms that no other workload uses it, delete it:
```bash
gcloud iam service-accounts delete {gateway_sa_name}@{project_id}.iam.gserviceaccount.com --project={project_id}
```
## Related skills
| Need | Skill |
| :--- | :--- |
| Write or migrate an OpenAPI spec, or fix an OpenAPI error from `api-configs create` | `api-gateway-openapi-spec-authoring` |
| Expose operations as MCP tools, or fix `/mcp` errors | `api-gateway-mcp-server` |
| Find why requests fail, including HTTP 401, 403, 429, and quota HTTP 500 errors | `api-gateway-troubleshooting` |
| Deploy or change the Cloud Run backend | `cloud-run-basics` |
| Put a load balancer, Cloud Armor, or a custom domain in front of the gateway | `google-cloud-global-frontend-configuration` |
If an API Gateway skill in this table is not 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}`.
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-backend-security-and-rate-limiting)" \
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-backend-security-and-rate-limiting)` 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-backend-security-and-rate-limiting)
```
- **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.
backend-security.md 9.5 KB
<!-- disableFinding(LINE_OVER_80) -->
# Backend Security and Header Forwarding Reference
- [Gateway Service Account and Zero-Downtime Lockdown](#gateway-service-account-and-zero-downtime-lockdown): Lines 10-66
- [Backend Authentication Extensions (OpenAPI 2.0 vs 3.x)](#backend-authentication-extensions-openapi-20-vs-3x): Lines 68-99
- [Header Override and X-Apigateway-Api-Userinfo](#header-override-and-x-apigateway-api-userinfo): Lines 101-109
- [Default Gateway Hostname and Load Balancer Limitation](#default-gateway-hostname-and-load-balancer-limitation): Lines 111-118
## Gateway Service Account and Zero-Downtime Lockdown
API Gateway signs outbound backend requests with an OpenID Connect (OIDC) ID token generated for the gateway service account configured on the API config. Execute the steps below in order so existing gateways do not receive `403 Forbidden` responses while transitioning to an OIDC-secured backend:
1. Create a dedicated service account for the gateway. NEVER use the Compute Engine default service account (`{project_number}-compute@developer.gserviceaccount.com`) in production. **Rationale:** The Compute Engine default service account often carries broad project permissions (`roles/editor`), which violates least privilege.
```bash
gcloud iam service-accounts create {gateway_sa_name} \
--display-name="API Gateway backend invoker" \
--project={project_id}
```
2. Grant the gateway service account only the invoker role on the target backend resource (request human approval before applying IAM bindings). A change to the IAM policy of a Cloud Run service needs `roles/run.admin`, or another role with `run.services.setIamPolicy`:
- **Cloud Run service or Cloud Run functions (2nd gen):** `roles/run.invoker`
```bash
gcloud run services add-iam-policy-binding {backend_service} \
--member="serviceAccount:{gateway_sa_name}@{project_id}.iam.gserviceaccount.com" \
--role="roles/run.invoker" \
--region={region} \
--project={project_id}
```
- **Cloud Run functions (1st gen):** `roles/cloudfunctions.invoker` (as used in legacy Cloud Functions setups).
3. Grant the deployment identity `roles/iam.serviceAccountUser` on `{gateway_sa_name}@{project_id}.iam.gserviceaccount.com` so it can attach the service account to an API config.
4. Create the API config with `--backend-auth-service-account` and roll it out to every gateway of the API (note that only one API config can be created for a given API at a time, and config creation can take several minutes):
```bash
gcloud api-gateway api-configs create {config_id} \
--api={api_id} \
--openapi-spec={candidate_openapi_spec} \
--backend-auth-service-account={gateway_sa_name}@{project_id}.iam.gserviceaccount.com \
--project={project_id}
gcloud api-gateway gateways update {gateway_id} \
--api={api_id} \
--api-config={config_id} \
--location={region} \
--project={project_id}
```
5. After every gateway of the API serves an API config with `--backend-auth-service-account`, request human approval and block unauthenticated direct calls to the backend. **Rationale:** A gateway that still serves an older config sends no ID token, or a token from a service account without the invoker role, so a lockdown before the switch breaks its live traffic with `403` errors. If you do not lock down the backend, callers can invoke `*.run.app` directly and bypass API Gateway.
- For a 1st gen function backend, skip the Cloud Run commands in this step. Run `gcloud functions remove-iam-policy-binding {function_name} --member=allUsers --role=roles/cloudfunctions.invoker --region={region} --project={project_id}`. If the function also has an `allAuthenticatedUsers` binding, run it again with `--member=allAuthenticatedUsers`.
- Remove the `allUsers` invoker binding:
```bash
gcloud run services remove-iam-policy-binding {backend_service} \
--member=allUsers \
--role=roles/run.invoker \
--region={region} \
--project={project_id}
```
If gcloud reports that the binding is not found, the service has no `allUsers` binding. Go to the next check.
- If `gcloud run services get-iam-policy {backend_service} --region={region} --project={project_id}` shows an `allAuthenticatedUsers` invoker binding, remove it with the same command and `--member=allAuthenticatedUsers`. **Rationale:** That binding lets any Google Account call the backend directly.
- For a Cloud Run or 2nd gen function backend, if the service has the invoker IAM check turned off (`gcloud run services describe {backend_service} --region={region} --project={project_id} --format=yaml` shows the annotation `run.googleapis.com/invoker-iam-disabled: 'true'`), turn the check on:
```bash
gcloud run services update {backend_service} \
--invoker-iam-check \
--region={region} \
--project={project_id}
```
- Do not use `gcloud run services update --no-allow-unauthenticated`. `gcloud run deploy` has that flag, but `services update` does not.
Reference: [Secure traffic to a service with the gcloud CLI](https://docs.cloud.google.com/api-gateway/docs/secure-traffic-gcloud.md.txt)
## Backend Authentication Extensions (OpenAPI 2.0 vs 3.x)
In OpenAPI 2.0, `x-google-backend` is an inline object with `snake_case` fields. In OpenAPI 3.x, you MUST define named backends inside the root `x-google-api-management.backends` map, and set `x-google-backend` to the string name of that backend. Use the documented `camelCase` field names (such as `jwtAudience` and `disableAuth`). **Rationale:** OpenAPI 3.x configs reject inline `x-google-backend` objects.
These fields control the ID token that the gateway sends to the backend:
| Setting | OpenAPI 2.0 (`x-google-backend`) | OpenAPI 3.x (`x-google-api-management.backends.{name}`) | Behavior |
| --- | --- | --- | --- |
| OIDC JWT Audience | `jwt_audience` | `jwtAudience` | Defaults to the full `address` value. Set this field to the OAuth 2.0 client ID when the backend is protected by Identity-Aware Proxy (IAP) or runs on App Engine. For a Cloud Run revision tag URL (`https://{tag}---{service_host}`), set it to `https://{service_host}`. |
| Disable Backend Auth | `disable_auth` | `disableAuth` | Defaults to `false`. Set to `true` to prevent the gateway proxy from obtaining and attaching an instance OIDC ID token (leaving any client `Authorization` header unreplaced by a gateway ID token). |
Set at most one of `jwtAudience` and `disableAuth` (`jwt_audience` and `disable_auth` in OpenAPI 2.0) on a backend. API Gateway rejects a backend that sets both.
For the other backend fields (`address`, `pathTranslation`, `deadline`, and `protocol`), use the `api-gateway-openapi-spec-authoring` skill. If it is not installed, see the reference link below.
### OpenAPI 3.x Backend Example
```yaml
openapi: 3.0.4
info:
title: Orders API
version: 1.0.0
x-google-api-management:
backends:
orders-backend:
address: https://{backend_service}-{hash}.a.run.app
jwtAudience: https://{backend_service}-{hash}.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
x-google-backend: orders-backend
```
Reference: [OpenAPI 3.x extensions in API Gateway](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)
## Header Override and X-Apigateway-Api-Userinfo
When `x-google-backend` routes a request to a backend with backend authentication enabled, API Gateway overrides the incoming `Authorization` header with the gateway's own OIDC ID token so the backend (such as Cloud Run) can authenticate the gateway.
- For an operation with JWT auth, backends MUST read the end-user or client JWT claims from the `X-Apigateway-Api-Userinfo` header rather than the `Authorization` header. **Rationale:** The `Authorization` header received by the backend carries the gateway service account token, whereas `X-Apigateway-Api-Userinfo` contains the `base64url`-encoded JSON payload of the client JWT verified by API Gateway.
- API Gateway sends `X-Apigateway-Api-Userinfo` only when the operation authenticated a JWT. An operation with only an API key, or with no `security`, gets no such header.
- Decode `X-Apigateway-Api-Userinfo` in the backend using standard `base64url` decoding (adding `=` padding if required by the language runtime) and parse the JSON claims (`sub`, `iss`, `aud`).
Reference: [Authenticate users with JWT - Receive authenticated results](https://docs.cloud.google.com/api-gateway/docs/authenticating-users-jwt.md.txt)
## Default Gateway Hostname and Load Balancer Limitation
API Gateway assigns every gateway a default hostname in `defaultHostname`, typically `https://{gateway_id}-{hash}.{region_code}.gateway.dev`. Read it with `gcloud api-gateway gateways describe {gateway_id} --location={region} --project={project_id} --format="value(defaultHostname)"` instead of building it from the gateway name.
- API Gateway does not support ingress restriction settings to disable direct access to the gateway's `defaultHostname`.
- If you place an External Application Load Balancer, Google Cloud Armor policy, or Identity-Aware Proxy (IAP) in front of API Gateway via a serverless Network Endpoint Group (NEG), NEVER rely on the load balancer alone to block unauthorized requests. **Rationale:** Clients that discover the gateway's `defaultHostname` (`*.gateway.dev`) can send requests directly to the gateway and bypass the load balancer and Google Cloud Armor. Always enforce JWT or API key security in the API Gateway OpenAPI specification and IAM on the backend.
Reference: [Use a load balancer with API Gateway](https://docs.cloud.google.com/api-gateway/docs/gateway-load-balancing.md.txt)
client-authentication.md 10.9 KB
<!-- disableFinding(LINE_OVER_80) -->
# Client Authentication Reference (API Keys and JWT)
- [API Key Configuration](#api-key-configuration): Lines 11-40
- [API Key Restrictions and Managed Service](#api-key-restrictions-and-managed-service): Lines 42-62
- [JWT Configuration in OpenAPI 2.0 and 3.x](#jwt-configuration-in-openapi-20-and-3x): Lines 64-115
- [Identity Provider JWT Settings Table](#identity-provider-jwt-settings-table): Lines 117-126
- [Security Composition and Override Rules](#security-composition-and-override-rules): Lines 128-148
## API Key Configuration
Use an API key to identify the calling Google Cloud consumer project for quota enforcement, billing, and usage tracking. Do not use an API key alone to authenticate end-user identity. **Rationale:** An API key identifies a Google Cloud project rather than a user or service principal, and callers can extract API keys from client applications.
API Gateway reads an API key only from the `x-api-key` header, or from the `key` or `api_key` query parameter. Pass the API key in the `x-api-key` HTTP header as the standard convention. Use a query parameter only as an escape hatch when the client cannot set custom HTTP headers. **Rationale:** URL query parameters appear in proxy logs, browser history, and access logs.
**Warning:** API Gateway ignores an `apiKey` scheme with any other `name` or `in` value, and it gives no error. An operation that requires only that scheme then accepts calls with no API key (the service config marks the operation `allowUnregisteredCalls: true`). Use one of the three names above, and test that a call with no key gets `401`.
### OpenAPI 2.0 (`securityDefinitions`)
```yaml
securityDefinitions:
api_key:
type: "apiKey"
name: "x-api-key"
in: "header"
```
### OpenAPI 3.x (`components.securitySchemes`)
```yaml
components:
securitySchemes:
api_key:
type: apiKey
name: x-api-key
in: header
```
Reference: [Authenticate with an API key](https://docs.cloud.google.com/api-gateway/docs/authenticate-api-keys.md.txt)
## API Key Restrictions and Managed Service
Before a consumer project can call an API with an API key, enable the managed service of the API in that consumer project and allow it on the API key:
1. Inspect the API to find its `managedService` value (note that a newly created managed service can take up to 30 minutes to appear in the Google Cloud API Library):
```bash
gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"
```
2. Enable the managed service in the consumer project (`{consumer_project_id}`):
```bash
gcloud services enable {managed_service_name} --project={consumer_project_id}
```
3. Add API restrictions and application restrictions to every production API key (request human approval before creating or updating production API keys). If a restricted API key gets HTTP `403` because its API restrictions do not include the API, add `{managed_service_name}` to the key's allowed API targets:
```bash
gcloud services api-keys update {key_id} \
--api-target=service={managed_service_name} \
--project={consumer_project_id}
```
4. If you restrict an API key by HTTP referrer (website), you MUST include the URL scheme (`https://{domain}/*` instead of `{domain}/*`). **Rationale:** Unrestricted API keys can be used against any enabled API in the project, and referrer entries without a scheme fail validation.
Reference: [Restrict API keys](https://docs.cloud.google.com/docs/authentication/api-keys.md.txt)
## JWT Configuration in OpenAPI 2.0 and 3.x
Use JSON Web Tokens (JWTs) to authenticate end users or calling service accounts.
- You MUST specify `x-google-jwks_uri` (OpenAPI 2.0) or `x-google-auth.jwksUri` (OpenAPI 3.x) on every `oauth2` security scheme, also on a scheme that no operation uses. **Rationale:** API Gateway requires the public key set URI to verify the signature of incoming JWTs. Without it, `api-configs create` fails with `JWKS provider "..." is missing a JWKS URI`. API Gateway caches the JWKS for 5 minutes (publish rotated signing keys at least 5 minutes before signing traffic).
- Give each JWT security scheme a unique `issuer` value. **Rationale:** API Gateway routes token verification by matching the `iss` claim to a unique security definition.
- Required JWT claims are `iss`, `sub`, `aud`, `iat`, and `exp`. The `aud` claim cannot be an internal address or an IPv4/IPv6 address.
- `audiences` (`x-google-audiences` in OpenAPI 2.0) is optional. If omitted, API Gateway accepts JWTs whose `aud` claim matches `https://{service_name}`, where `{service_name}` is the `managedService` name of the API (read it with `gcloud api-gateway apis describe`). In OpenAPI 3.x, a relative server URL such as `url: /v1` keeps the default name. In OpenAPI 2.0, specify multiple audiences as a single comma-separated string (`"aud1,aud2"`); in OpenAPI 3.x, specify a YAML list.
- API Gateway validates JWT claims and signatures, but does not check IAM permissions of a calling service account and ignores OAuth `scopes` declared in the OpenAPI document.
### OpenAPI 2.0 JWT Definition
```yaml
securityDefinitions:
service_jwt:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
x-google-issuer: "{service_account_email}"
x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/{service_account_email}"
x-google-audiences: "https://{managed_service_name}"
```
### OpenAPI 3.x JWT Definition (`x-google-auth`)
In OpenAPI 3.x, place `issuer`, `jwksUri`, `audiences`, and `jwtLocations` inside `x-google-auth` and remove the `x-google-` field prefixes used in OpenAPI 2.0:
```yaml
components:
securitySchemes:
service_jwt:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: "{service_account_email}"
jwksUri: "https://www.googleapis.com/robot/v1/metadata/x509/{service_account_email}"
audiences:
- "https://{managed_service_name}"
jwtLocations:
- header: X-Forwarded-Authorization
valuePrefix: "Bearer "
- query: auth_token
```
By default, API Gateway reads JWTs from `Authorization: Bearer `, `X-Goog-Iap-Jwt-Assertion`, or the `access_token` query parameter. Configure `jwtLocations` (`header` with optional `valuePrefix`, or `query`) only when the client sends the token in a custom header or query parameter.
References:
- [Authenticate users with JWT](https://docs.cloud.google.com/api-gateway/docs/authenticating-users-jwt.md.txt)
- [Authentication between services](https://docs.cloud.google.com/api-gateway/docs/authenticate-service-account.md.txt)
## Identity Provider JWT Settings Table
| Identity Provider | `issuer` (`x-google-issuer`) | `jwksUri` (`x-google-jwks_uri`) | `audiences` (`x-google-audiences`) |
| --- | --- | --- | --- |
| Firebase Authentication | `https://securetoken.google.com/{project_id}` | `https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com` | `{project_id}` |
| Auth0 | `https://{your_auth0_domain}/` (trailing slash required) | `https://{your_auth0_domain}/.well-known/jwks.json` | Auth0 API Identifier or Client ID |
| Okta | `https://{your_okta_domain}/oauth2/default` | `https://{your_okta_domain}/oauth2/default/v1/keys` | Okta Client ID or Audience |
| Google ID token (user sign-in with an OAuth client) | `https://accounts.google.com` | `https://www.googleapis.com/oauth2/v3/certs` | OAuth 2.0 Client ID |
| Google ID token for a service account (`gcloud auth print-identity-token --impersonate-service-account={caller_sa_email} --audiences={jwt_audience}`) | `https://accounts.google.com` | `https://www.googleapis.com/oauth2/v3/certs` | The same `{jwt_audience}` value. Any Google identity can mint such a token, so check the `email` claim in the backend (`X-Apigateway-Api-Userinfo`), or use the self-signed row to accept only one service account. |
| Service account self-signed JWT (`gcloud iam service-accounts sign-jwt`) | `{service_account_email}` | `https://www.googleapis.com/robot/v1/metadata/x509/{service_account_email}` | `https://{managed_service_name}` |
## Security Composition and Override Rules
**Operation-level `security` replaces root-level `security`:** If an operation declares its own `security` block with only a JWT scheme (`- service_jwt: []`), it overrides the document-level `security` block and removes any root `api_key` requirement. To preserve per-project quota tracking on an operation that overrides `security`, you MUST include `api_key: []` in the same security requirement object (`- api_key: []` and `service_jwt: []` together).
To drop the root requirement on one operation, set `security: []` on that operation. The operation then accepts calls with no credentials, so confirm with the user before you make an operation public. Do not do this on an operation with `x-google-quota`, because the quota needs the API key to find the consumer project.
| Requirement Pattern | OpenAPI Syntax | Supported in API Gateway |
| --- | --- | --- |
| Require API key AND JWT (conjunction) | Single list item with two keys: `- api_key: []` and `service_jwt: []` in the same object | Yes. Use this pattern when an operation requires both user authentication and consumer project quota tracking. |
| Require JWT scheme A OR JWT scheme B (disjunction) | Two list items: `- jwt_a: []` followed by `- jwt_b: []` | Yes. Each scheme must have a distinct `issuer`. |
| Require JWT scheme A AND JWT scheme B (conjunction) | Single list item with two OAuth2 schemes | No, in OpenAPI 2.0 and 3.x. API Gateway does not support conjunctions of multiple OAuth2 schemes unless the additional scheme is an API key. |
| Require the same API key with JWT scheme A OR JWT scheme B | Two list items, each with the API key: `- api_key: []` and `jwt_a: []`, then `- api_key: []` and `jwt_b: []` | Yes. |
| Require API key scheme A OR API key scheme B | Two list items: `- key_a: []` followed by `- key_b: []` | Yes. |
| Require API key OR JWT (disjunction where only some alternatives have the API key) | Two list items: `- api_key: []` followed by `- service_jwt: []` | OpenAPI 3.x: No. `api-configs create` fails with `Combining API key and OAuth security requirements with a logical OR is not supported.` OpenAPI 2.0: the config is accepted, but the public docs say that it is not supported, so do not rely on it. Put the API key in every alternative instead. |
| Optional API key | `- {}` alongside `- api_key: []` | Yes (special-case exception for API keys only). |
| Optional JWT | `- {}` alongside `- service_jwt: []` | OpenAPI 3.x: No. `api-configs create` fails with `Optional OAuth security requirement is not supported.` OpenAPI 2.0: the config is accepted, but the public docs say that it is not supported, so do not rely on it. |
References:
- [OpenAPI 3.x feature limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
- [OpenAPI 2.0 feature limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-limitations.md.txt)
mcp-traffic-security.md 8.6 KB
# MCP Traffic Security and Quotas Reference (Public Preview)
- [Authentication Model per MCP Method](#authentication-model-per-mcp-method): Lines 8-25
- [Tool Discovery Security (tools/list)](#tool-discovery-security-toolslist): Lines 27-87
- [Shared REST and MCP Quota Enforcement](#shared-rest-and-mcp-quota-enforcement): Lines 89-95
- [Sensitive Operations and Header Parameters on MCP](#sensitive-operations-and-header-parameters-on-mcp): Lines 97-106
## Authentication Model per MCP Method
Model Context Protocol (MCP) support on API Gateway is a **Public Preview** feature that requires an OpenAPI 3.x specification (`x-google-api-management.mcp`). It exposes a stateless JSON-RPC 2.0 endpoint at `POST https://{default_hostname}/mcp`, even when a `servers` base path is set (up to 1,000 tools per gateway, mutually exclusive with `x-google-model-router` in the same API config).
API Gateway applies distinct authentication rules to each MCP method:
| MCP Method | Default Authentication | Supported Security Schemes | Behavior |
| --- | --- | --- | --- |
| `initialize` | Unauthenticated | None | Handled directly by the gateway handshake layer; never reaches the backend. |
| `notifications/initialized` | Unauthenticated | None | Returns `HTTP 202 Accepted`; never reaches the backend. |
| `tools/list` | Unauthenticated by default | Exactly one JWT scheme (`oauth2` with `x-google-auth`) or one API key scheme (`apiKey`) | Configured via `x-google-api-management.mcp.tools-list.security`. An empty map (`security: {}`) leaves `tools/list` open. `tools/list` reads an API key only from the `x-api-key` header, not from query parameters. |
| `tools/call` | Inherits operation security | JWT (`oauth2`) and API keys (`apiKey`) | Transcoded into the underlying REST request and subject to the exact `security` and `x-google-quota` rules of that OpenAPI operation. |
If an MCP call fails, use the `api-gateway-mcp-server` skill. If it is not installed, see [Configure Model Context Protocol](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt). Check both the HTTP status and the JSON-RPC `error` field of the body, because an invalid API key on `tools/list` returns HTTP `200` with a JSON-RPC error.
If a gateway project is attached to Apigee API hub, MCP-enabled gateways are automatically published to API hub (`{api} (MCP)`) and Agent Registry.
Reference: [Configure Model Context Protocol](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt)
## Tool Discovery Security (`tools/list`)
By default, `tools/list` is unauthenticated, which allows any caller that reaches the gateway URL to enumerate all tool names, descriptions, and JSON input schemas.
- In production environments, ALWAYS configure `x-google-api-management.mcp.tools-list.security` with a JWT or API key security scheme defined in `components.securitySchemes`. **Rationale:** Leaving `tools/list` unauthenticated exposes internal API capabilities and parameter schemas to unauthenticated callers.
- Name **exactly one** scheme under `tools-list.security`. **Rationale:** API Gateway rejects a `tools-list.security` block that names more than one scheme. An empty block (`security: {}`) passes config creation with no error and leaves `tools/list` unauthenticated, so check that the block names a scheme.
- Prefer a JWT scheme when agents must prove who they are. An API key identifies a consumer project rather than a caller, so use an API key scheme on `tools/list` when the tools already require that API key and caller identity is not needed.
- If you use a JWT scheme, list the same scheme in the root `security` list. **Rationale:** API Gateway rejects a config whose JWT `tools-list.security` scheme is missing from the root `security` list. The root entry also requires the JWT on every REST operation that does not set its own `security`, so tell the user before you deploy.
- If you use an API key scheme, define it with `in: header` and `name: x-api-key`. **Rationale:** `tools/list` reads API keys only from the `x-api-key` header, not from query parameters.
- Setting `x-google-api-management.mcp` to an object (to configure `tools-list`) automatically enables MCP globally for all eligible `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` operations in the specification. Explicitly set `x-google-mcp-tool: false` on every operation that must not be exposed as an agent tool. Every exposed tool MUST resolve to a unique name matching `[A-Za-z0-9_.-]{1,128}` and a non-empty description.
```yaml
openapi: 3.0.4
info:
title: Orders Service
version: 1.0.0
x-google-api-management:
mcp:
tools-list:
security:
agent_jwt: []
backends:
orders-backend:
address: https://{backend_service}-{hash}.a.run.app
jwtAudience: https://{backend_service}-{hash}.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
x-google-backend: orders-backend
security:
- agent_jwt: []
components:
securitySchemes:
agent_jwt:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: "https://accounts.google.com"
jwksUri: "https://www.googleapis.com/oauth2/v3/certs"
audiences:
- "{oauth_client_id}"
```
For Google ID tokens that a service account gets with `gcloud auth print-identity-token --impersonate-service-account={caller_sa_email} --audiences={jwt_audience}`, set `audiences` to that same `{jwt_audience}` value. See the [Identity Provider JWT Settings Table](client-authentication.md#identity-provider-jwt-settings-table).
To require an API key on `tools/list` instead, name the API key scheme. An API key scheme does not need a root `security` entry:
```yaml
x-google-api-management:
mcp:
tools-list:
security:
api_key: []
components:
securitySchemes:
api_key:
type: apiKey
name: x-api-key
in: header
```
## Shared REST and MCP Quota Enforcement
When an agent invokes a tool via `tools/call`, API Gateway transcodes the call into the underlying REST operation. The transcoded backend request is indistinguishable from a direct REST call, so backends cannot apply MCP-only logic.
- **Shared quota bucket:** Direct REST requests and MCP `tools/call` invocations against the same operation draw from the exact same `x-google-quota` metric and per-project quota limit.
- **Passing credentials from MCP clients:** If the underlying REST operation uses `x-google-quota` (which requires an API key) and `tools/list` requires a JWT (`agent_jwt`), the MCP client MUST send both headers (`Authorization: Bearer {jwt}` and `x-api-key: {api_key}`) on requests to `/mcp`. **Rationale:** Omitting `x-api-key` causes `tools/call` to fail the operation's API key and quota check, while omitting `Authorization` causes `tools/list` to fail with `401`. If `tools-list.security` names the API key scheme instead, the same `x-api-key` header also authenticates `tools/list`.
- **Higher cost for write tools:** Because agent loops can issue rapid tool retries, assign higher `x-google-quota` metric costs or separate lower-limit metrics (`write-requests`) to mutating `POST`, `PUT`, `PATCH`, and `DELETE` operations exposed as MCP tools.
## Sensitive Operations and Header Parameters on MCP
API Gateway does not emit MCP tool annotations such as `destructiveHint` or `readOnlyHint` in `tools/list` responses during Public Preview, and operations returning empty bodies (`HTTP 204`) are not supported as MCP tools.
1. Set `x-google-mcp-tool: false` on administrative, bulk-delete, or internal health-check operations so agents cannot discover or invoke them via `/mcp`.
2. NEVER treat `x-google-mcp-tool: false` as an access control boundary for the operation itself. **Rationale:** Setting `x-google-mcp-tool: false` only omits the operation from MCP `tools/list` and blocks `tools/call`, while the underlying REST path remains live and callable on the gateway URL unless secured with a strict `security` requirement or removed from the OpenAPI specification.
3. NEVER declare trust-bearing identity headers (such as a custom user ID or tenant role header) as OpenAPI `in: header` parameters on an MCP-exposed operation. **Rationale:** API Gateway exposes OpenAPI `header` parameters as top-level properties in the MCP tool `arguments` schema and injects the agent-supplied values into the backend HTTP request headers. (Parameters cannot bind to reserved system headers or headers starting with `x-google-`).
4. For destructive operations that intentionally remain exposed as MCP tools, state in `x-google-mcp-tool.description` when the agent is permitted to call the tool and that the action cannot be undone.
Reference: [OpenAPI 3.x feature limitations - MCP limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
quotas-and-rate-limiting.md 9.3 KB
<!-- disableFinding(LINE_OVER_80) -->
# Quotas and Rate Limiting Reference
- [How API Gateway Quotas Work](#how-api-gateway-quotas-work): Lines 12-25
- [Critical Rule: Quotas Apply to the Whole API](#critical-rule-quotas-apply-to-the-whole-api): Lines 27-37
- [Unexpected HTTP 429 or HTTP 500 Errors](#unexpected-http-429-or-http-500-errors): Lines 39-54
- [OpenAPI 2.0 Quota Configuration](#openapi-20-quota-configuration): Lines 56-106
- [OpenAPI 3.x Quota Configuration](#openapi-3x-quota-configuration): Lines 108-163
- [Quota Migration from OpenAPI 2.0 to 3.x](#quota-migration-from-openapi-20-to-3x): Lines 165-174
## How API Gateway Quotas Work
API Gateway rate limits traffic as requests per minute per consumer Google Cloud project (`1/min/{project}`).
- **API key required:** Every quota-enforced operation MUST require an API key (`api_key: []`) in every security alternative. **Rationale:** Service Control uses the API key to identify the consumer Google Cloud project and increment its per-project request counter. A call that matches an alternative without the API key has no consumer project, so API Gateway cannot count it.
- **Operations only:** API Gateway reads `x-google-quota` only on operations, in OpenAPI 2.0 and 3.x. It ignores `x-google-quota` at the root and path levels with no error, so the limits for those metrics are never enforced.
- **Limit for each charged metric:** Give each metric that an operation charges a limit in `quota.limits`. Otherwise `api-configs create` fails with `Metric rule defined on metric '...', but has no quota limits defined.`
- **One project per consumer:** Because quotas are tracked per Google Cloud project rather than per end user, create or require a separate Google Cloud project for each API consumer tenant that needs an isolated rate limit. To override a quota limit for one specific consumer project, configure a consumer override using that consumer's project number under **IAM & Admin > Quotas & System Limits** in the Google Cloud console.
- **Runtime behavior (`HTTP 429`):** When a consumer project exceeds its configured limit, API Gateway rejects the request before forwarding it to the backend and returns `HTTP 429 Too Many Requests` (or gRPC `ResourceExhausted`). Instruct client applications to catch `429` responses and retry with exponential backoff.
- **Approximate enforcement:** The gateway aggregates and batches quota calls to keep request latency low, so quota enforcement is approximate. A consumer can get more or fewer requests than the configured limit, and the difference is not a fixed percentage. Do not use API Gateway quotas for exact billing ledgers, spike arrest, or high-accuracy rate limiting.
References:
- [About quotas in API Gateway](https://docs.cloud.google.com/api-gateway/docs/quotas-overview.md.txt)
- [About quotas in Cloud Endpoints](https://docs.cloud.google.com/endpoints/docs/openapi/quotas-overview.md.txt)
## Critical Rule: Quotas Apply to the Whole API
You declare quota `metrics` and `quota.limits` inside an API config, but API Gateway applies those definitions to the parent **API resource** across all gateways, not only to the gateway running that API config. **Each time you create an API config (`gcloud api-gateway api-configs create`), its metrics and limits immediately replace the ones declared by earlier API configs for the entire API.**
1. **Limit value changes affect all gateways immediately upon config creation:** Creating an API config with a changed limit value updates the rate limit for every gateway of that API, even before `gateways update` is called.
2. **Metric renames or removals cause HTTP 500 outages:** NEVER rename or remove a quota metric in a new API config while any gateway of the API still serves an older API config that references the old metric name in `x-google-quota`. **Rationale:** Creating the new API config overwrites the API's metric definitions in Service Control, leaving older gateways with an invalid quota configuration; every call to a quota-enforced method on those older gateways fails with `HTTP 500` and the message `Failed to call Service Control Quota`.
3. **Two safe paths for metric changes:**
- **Path A (Additive dual-metric transition, recommended for zero-downtime multi-gateway setups):** Run `python3 scripts/check_quota_metrics.py` against all active gateways (`--project` and `--api`). Keep both the old metric and the new metric defined in `metrics` and `quota.limits` in every newly created API config until all gateways of the API have been updated to configs that no longer reference the old metric.
- **Path B (Immediate uniform upgrade):** Update every gateway of the API to the newly created API config immediately so no gateway continues serving an earlier config that references the removed metric.
Reference: [Quotas apply to the whole API](https://docs.cloud.google.com/api-gateway/docs/quotas-overview.md.txt)
## Unexpected HTTP 429 or HTTP 500 Errors
To diagnose an unexpected HTTP 429 or HTTP 500, use the `api-gateway-troubleshooting` skill. If it is not installed, read the gateway log entry for the failed request:
```bash
gcloud logging read 'resource.type="apigateway.googleapis.com/Gateway" AND resource.labels.gateway_id="{gateway_id}" AND httpRequest.status>=429' \
--project={project_id} --freshness=1h --limit=20 \
--format="json(timestamp,httpRequest.status,httpRequest.requestUrl,jsonPayload.responseDetails,jsonPayload.apiConfig)"
```
`httpRequest.requestUrl` can contain an API key in the `key` query parameter. Redact it before you show the output.
If `jsonPayload.responseDetails` is `service_control_quota_error`:
- With status `429`, the consumer project exceeded the limit. This is the expected behavior. Tell client applications to retry with exponential backoff, or raise the limit.
- With status `500`, the gateway serves an API config with a quota metric that the newest API config of the API no longer defines. Fix it with Path A or Path B in [Critical Rule: Quotas Apply to the Whole API](#critical-rule-quotas-apply-to-the-whole-api).
## OpenAPI 2.0 Quota Configuration
In OpenAPI 2.0, declare `metrics` and `quota.limits` under root `x-google-management` as lists of objects, and attach costs on operations using `x-google-quota.metricCosts`. API Gateway ignores `x-google-quota` at the root and path levels:
```yaml
swagger: "2.0"
info:
title: Orders API
version: 1.0.0
x-google-backend:
address: https://{backend_service}-{hash}.a.run.app
x-google-management:
metrics:
- name: "read-requests"
displayName: "Read requests"
valueType: INT64
metricKind: DELTA
- name: "write-requests"
displayName: "Write requests"
valueType: INT64
metricKind: DELTA
quota:
limits:
- name: "read-limit"
metric: "read-requests"
unit: "1/min/{project}"
values:
STANDARD: 1000
- name: "write-limit"
metric: "write-requests"
unit: "1/min/{project}"
values:
STANDARD: 100
securityDefinitions:
api_key:
type: "apiKey"
name: "x-api-key"
in: "header"
security:
- api_key: []
paths:
/v1/orders:
get:
operationId: listOrders
x-google-quota:
metricCosts:
"read-requests": 1
responses:
200:
description: OK
```
## OpenAPI 3.x Quota Configuration
In OpenAPI 3.x, declare `metrics` and `quota.limits` as YAML maps under root `x-google-api-management`, and set `x-google-quota` on each operation as a `{metric_name}: {integer_cost}` map. As in OpenAPI 2.0, API Gateway ignores `x-google-quota` at the root and path levels:
```yaml
openapi: 3.0.4
info:
title: Orders API
version: 1.0.0
x-google-api-management:
backends:
orders-backend:
address: https://{backend_service}-{hash}.a.run.app
jwtAudience: https://{backend_service}-{hash}.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
metrics:
read-requests:
displayName: "Read requests"
write-requests:
displayName: "Write requests"
quota:
limits:
read-limit:
metric: read-requests
values: 1000
write-limit:
metric: write-requests
values: 100
x-google-backend: orders-backend
components:
securitySchemes:
api_key:
type: apiKey
name: x-api-key
in: header
security:
- api_key: []
paths:
/v1/orders:
get:
operationId: listOrders
x-google-quota:
read-requests: 1
responses:
"200":
description: OK
post:
operationId: createOrder
x-google-quota:
write-requests: 5
responses:
"201":
description: Created
```
Reference: [OpenAPI 3.x extensions - x-google-quota](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)
## Quota Migration from OpenAPI 2.0 to 3.x
When converting an OpenAPI 2.0 specification to OpenAPI 3.x:
1. Move `metrics` and `quota` from `x-google-management` into `x-google-api-management`.
2. Convert `metrics` and `quota.limits` from YAML arrays (`- name: ...`) into YAML maps keyed by metric and limit name, and preserve the exact metric keys.
3. Remove `valueType`, `metricKind`, `unit`, and `STANDARD:` wrapper keys (`values` in OpenAPI 3.x is a direct `int64` integer).
4. Replace `x-google-quota: { metricCosts: { ... } }` with `x-google-quota: { {metric_name}: {cost} }`.
Reference: [Modify a gateway to use OpenAPI 3.x](https://docs.cloud.google.com/api-gateway/docs/migrate-oasv3.md.txt)
check_quota_metrics.py 15.7 KB
#!/usr/bin/env python3
"""Validates that a candidate OpenAPI spec keeps the active quota metrics.
API Gateway applies quota metrics and limits to the entire API rather than to an
individual API config. When a new API config is created, its quota definitions
immediately replace the definitions for the whole API. If a new API config
renames or removes a quota metric or limit that is still referenced by an active
gateway serving an older API config, requests to quota-enforced methods on that
older gateway fail with HTTP 500 ("Failed to call Service Control Quota").
The script also flags a metric that has a limit in a baseline but no limit in
the candidate, because the candidate's limits replace the limits of every
gateway of the API and the metric would no longer be rate limited.
It also flags an x-google-quota extension outside an operation, because API
Gateway reads x-google-quota only on operations and ignores it at the root and
path levels without an error.
"""
from __future__ import annotations
import argparse
import base64
import json
import re
import subprocess
import sys
from typing import Any
try:
import yaml
_HAS_YAML = True
except ImportError:
_HAS_YAML = False
# Matches the API ID and the config ID in a gateway's API config resource name.
_API_CONFIG_NAME_RE = re.compile(
r'/apis/(?P<api>[^/]+)/configs/(?P<config>[^/]+)$'
)
# The maximum time, in seconds, to wait for each gcloud command.
_GCLOUD_TIMEOUT_SECONDS = 60
def _load_spec(content: str, source_name: str) -> dict[str, Any]:
"""Parses a YAML or JSON OpenAPI specification string into a dictionary."""
try:
data = json.loads(content)
if isinstance(data, dict):
return data
except json.JSONDecodeError:
pass
if not _HAS_YAML:
raise RuntimeError(
'PyYAML is required to parse YAML specifications. Install it with: '
'pip install "PyYAML>=6.0,<7.0"'
)
try:
data = yaml.safe_load(content)
except yaml.YAMLError as exc:
raise ValueError(
f'Specification {source_name} is not valid JSON or YAML: {exc}'
) from exc
if not isinstance(data, dict):
raise ValueError(f'Specification {source_name} did not parse as a mapping.')
return data
def _read_spec(path: str) -> dict[str, Any]:
"""Reads and parses the OpenAPI specification file at path."""
with open(path, 'r', encoding='utf-8') as f:
return _load_spec(f.read(), path)
def extract_quota_metrics(spec: dict[str, Any]) -> set[str]:
"""Extracts declared quota metric names from an OpenAPI 2.0 or 3.x dict."""
metrics: set[str] = set()
# OpenAPI 2.0: x-google-management.metrics is a list of {name: ...} objects.
oas2_management = spec.get('x-google-management')
if isinstance(oas2_management, dict):
oas2_metrics = oas2_management.get('metrics', [])
if isinstance(oas2_metrics, list):
for item in oas2_metrics:
if isinstance(item, dict) and item.get('name') is not None:
metrics.add(str(item['name']))
# OpenAPI 3.x: x-google-api-management.metrics is a map keyed by metric name.
oas3_management = spec.get('x-google-api-management')
if isinstance(oas3_management, dict):
oas3_metrics = oas3_management.get('metrics', {})
if isinstance(oas3_metrics, dict):
for key in oas3_metrics.keys():
if key is not None:
metrics.add(str(key))
return metrics
def extract_limited_metrics(spec: dict[str, Any]) -> set[str]:
"""Extracts metric names that have a limit in quota.limits."""
limited: set[str] = set()
oas2_management = spec.get('x-google-management')
if isinstance(oas2_management, dict):
quota = oas2_management.get('quota', {})
if isinstance(quota, dict):
limits = quota.get('limits', [])
if isinstance(limits, list):
for item in limits:
if isinstance(item, dict) and item.get('metric') is not None:
limited.add(str(item['metric']))
oas3_management = spec.get('x-google-api-management')
if isinstance(oas3_management, dict):
quota = oas3_management.get('quota', {})
if isinstance(quota, dict):
limits = quota.get('limits', {})
if isinstance(limits, dict):
for item in limits.values():
if isinstance(item, dict) and item.get('metric') is not None:
limited.add(str(item['metric']))
return limited
def _quota_extension_metrics(quota_extension: Any) -> set[str]:
"""Returns the metric names that one x-google-quota extension charges."""
if not isinstance(quota_extension, dict):
return set()
costs = quota_extension.get('metricCosts')
if isinstance(costs, dict):
return {str(metric_name) for metric_name in costs}
return {str(metric_name) for metric_name in quota_extension}
def extract_referenced_quota_metrics(spec: dict[str, Any]) -> set[str]:
"""Extracts metric names that x-google-quota references at any level."""
referenced = _quota_extension_metrics(spec.get('x-google-quota'))
paths = spec.get('paths', {})
if isinstance(paths, dict):
for path_item in paths.values():
if isinstance(path_item, dict):
referenced |= _quota_extension_metrics(path_item.get('x-google-quota'))
for operation in path_item.values():
if isinstance(operation, dict):
referenced |= _quota_extension_metrics(
operation.get('x-google-quota')
)
return referenced
def find_ignored_quota_extensions(spec: dict[str, Any]) -> list[str]:
"""Returns the locations of x-google-quota extensions outside an operation.
API Gateway reads x-google-quota only on operations. It ignores the extension
at the root and path levels without an error, so the metrics that it charges
are never counted.
Args:
spec: The parsed OpenAPI 2.0 or 3.x specification.
Returns:
The location of each ignored extension, such as "x-google-quota" or
"paths./v1/orders.x-google-quota".
"""
locations: list[str] = []
if 'x-google-quota' in spec:
locations.append('x-google-quota')
paths = spec.get('paths', {})
if isinstance(paths, dict):
for path, path_item in paths.items():
if isinstance(path_item, dict) and 'x-google-quota' in path_item:
locations.append(f'paths.{path}.x-google-quota')
return locations
def _decode_contents(b64_contents: str) -> str:
"""Decodes base64 or base64url API config contents."""
normalized = b64_contents.replace('-', '+').replace('_', '/')
normalized += '=' * (-len(normalized) % 4)
return base64.b64decode(normalized).decode('utf-8-sig')
def _fetch_live_config_metrics(
project: str, api: str
) -> tuple[dict[str, list[str]], dict[str, list[str]], list[str]]:
"""Reads the quota metrics of each active API config of an API.
Args:
project: The Google Cloud project ID of the gateways.
api: The API Gateway API ID.
Returns:
The metrics of each active API config, the limited metrics of each active
API config, and the IDs of the active configs that have no OpenAPI
documents (for example, gRPC configs), which the script cannot inspect.
Raises:
RuntimeError: If a gcloud command fails, or if no active API config has
OpenAPI documents.
"""
gateways_command = [
'gcloud',
'api-gateway',
'gateways',
'list',
f'--project={project}',
'--format=json',
]
gateways_result = subprocess.run(
gateways_command,
capture_output=True,
text=True,
check=False,
stdin=subprocess.DEVNULL,
timeout=_GCLOUD_TIMEOUT_SECONDS,
)
if gateways_result.returncode != 0:
raise RuntimeError(
f'Failed to list gateways via gcloud: {gateways_result.stderr.strip()}'
)
gateways = json.loads(gateways_result.stdout or '[]')
config_ids: set[str] = set()
for gateway in gateways:
match = _API_CONFIG_NAME_RE.search(gateway.get('apiConfig', ''))
if match and match.group('api') == api:
config_ids.add(match.group('config'))
metrics_by_source: dict[str, list[str]] = {}
limited_by_source: dict[str, list[str]] = {}
skipped_configs: list[str] = []
for config_id in sorted(config_ids):
config_command = [
'gcloud',
'api-gateway',
'api-configs',
'describe',
config_id,
f'--api={api}',
f'--project={project}',
'--view=FULL',
'--format=json',
]
config_result = subprocess.run(
config_command,
capture_output=True,
text=True,
check=False,
stdin=subprocess.DEVNULL,
timeout=_GCLOUD_TIMEOUT_SECONDS,
)
if config_result.returncode != 0:
raise RuntimeError(
f'Failed to describe API config {config_id}:'
f' {config_result.stderr.strip()}'
)
config_data = json.loads(config_result.stdout or '{}')
openapi_documents = config_data.get('openapiDocuments', [])
if not openapi_documents:
# One gRPC config must not block the check of the other configs.
skipped_configs.append(config_id)
continue
config_metrics: set[str] = set()
config_limited: set[str] = set()
for document_entry in openapi_documents:
document = document_entry.get('document', {})
b64_contents = document.get('contents', '')
if b64_contents:
raw_text = _decode_contents(b64_contents)
parsed = _load_spec(
raw_text, f'{config_id}:{document.get("path", "spec")}'
)
config_metrics.update(extract_quota_metrics(parsed))
config_metrics.update(extract_referenced_quota_metrics(parsed))
config_limited.update(extract_limited_metrics(parsed))
metrics_by_source[f'api-config:{config_id}'] = sorted(config_metrics)
limited_by_source[f'api-config:{config_id}'] = sorted(config_limited)
if skipped_configs and not metrics_by_source:
raise RuntimeError(
f'No active API config of API {api} has OpenAPI documents (for'
f' example, gRPC configs: {", ".join(skipped_configs)}), so the script'
' cannot inspect them. Check their quota metrics and limits manually'
' before rollout.'
)
return metrics_by_source, limited_by_source, skipped_configs
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=(
'Verify that a candidate OpenAPI specification retains all quota '
'metrics and limits required by baseline specs or active gateways.'
)
)
parser.add_argument(
'--spec',
required=True,
help='Path to the candidate OpenAPI 2.0 or 3.x specification file.',
)
parser.add_argument(
'--baseline-spec',
action='append',
default=[],
help=(
'Path to an existing OpenAPI spec currently served by a gateway. '
'Can be passed multiple times for offline comparison.'
),
)
parser.add_argument(
'--project',
help='Google Cloud project ID to inspect active gateways via gcloud.',
)
parser.add_argument(
'--api',
help='API Gateway API ID to inspect active gateways via gcloud.',
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Validate local --baseline-spec files only without calling gcloud.',
)
args = parser.parse_args(argv)
if args.dry_run and (args.project or args.api):
print(
'Error: Do not combine --dry-run with --project or --api. Use '
'--project and --api for live gateway checks, or --baseline-spec with '
'--dry-run for offline file comparisons.',
file=sys.stderr,
)
return 2
if (args.project or args.api) and not (args.project and args.api):
print(
'Error: Both --project and --api must be provided together when '
'querying live gateways.',
file=sys.stderr,
)
return 2
if not args.baseline_spec and not (args.project and args.api):
print(
'Error: Provide at least one baseline source via --project and --api '
'(live gateway check) or --baseline-spec (offline spec check).',
file=sys.stderr,
)
return 2
try:
candidate_spec = _read_spec(args.spec)
baseline_specs = {path: _read_spec(path) for path in args.baseline_spec}
live_sources, live_limited, skipped_configs = (
_fetch_live_config_metrics(args.project, args.api)
if args.project and args.api
else ({}, {}, [])
)
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(f'Error: {exc}', file=sys.stderr)
return 2
for config_id in skipped_configs:
print(
f'Warning: Skipped active API config {config_id} because it has no'
' OpenAPI documents (for example, a gRPC config). Check its quota'
' metrics and limits manually.',
file=sys.stderr,
)
candidate_metrics = extract_quota_metrics(candidate_spec)
candidate_limited = extract_limited_metrics(candidate_spec)
candidate_references = extract_referenced_quota_metrics(candidate_spec)
ignored_quota_extensions = find_ignored_quota_extensions(candidate_spec)
baseline_sources: dict[str, list[str]] = {}
baseline_limited: dict[str, list[str]] = {}
for base_path, base_spec in baseline_specs.items():
base_names = extract_quota_metrics(
base_spec
) | extract_referenced_quota_metrics(base_spec)
baseline_sources[base_path] = sorted(base_names)
baseline_limited[base_path] = sorted(extract_limited_metrics(base_spec))
baseline_sources.update(live_sources)
baseline_limited.update(live_limited)
missing_by_source: dict[str, list[str]] = {}
all_missing: set[str] = set()
missing_limits: set[str] = set()
undeclared_candidate_references = sorted(
candidate_references - candidate_metrics
)
for source, old_metrics in baseline_sources.items():
missing = sorted(set(old_metrics) - candidate_metrics)
if missing:
missing_by_source[source] = missing
all_missing.update(missing)
# Flag only limits that a baseline has and the candidate drops. A metric
# that never had a limit does not need one now.
for old_limited in baseline_limited.values():
missing_limits.update(set(old_limited) - candidate_limited)
has_failure = bool(
all_missing
or missing_limits
or undeclared_candidate_references
or ignored_quota_extensions
)
status = 'FAIL' if has_failure else 'PASS'
report = {
'status': status,
'candidate_spec': args.spec,
'candidate_metrics': sorted(candidate_metrics),
'candidate_limited_metrics': sorted(candidate_limited),
'undeclared_candidate_references': undeclared_candidate_references,
'ignored_quota_extensions': ignored_quota_extensions,
'skipped_configs': skipped_configs,
'baseline_sources': baseline_sources,
'baseline_limited_metrics': baseline_limited,
'missing_metrics': sorted(all_missing),
'missing_limits_for_metrics': sorted(missing_limits),
'missing_by_source': missing_by_source,
}
print(json.dumps(report, indent=2))
if all_missing or undeclared_candidate_references:
print(
'Quota metric validation failed. Creating this API config will '
'overwrite API-wide quota definitions and can cause HTTP 500 "Failed '
'to call Service Control Quota" on active gateways.',
file=sys.stderr,
)
if missing_limits:
print(
'Quota limit validation failed. Creating this API config removes the '
'limits for the metrics in "missing_limits_for_metrics" from every '
'gateway of the API, so those metrics are no longer rate limited.',
file=sys.stderr,
)
if ignored_quota_extensions:
print(
'Quota extension validation failed. API Gateway reads x-google-quota '
'only on operations and ignores the extensions in '
'"ignored_quota_extensions", so the metrics that they charge are never '
'counted. Move each x-google-quota into the operations it applies to.',
file=sys.stderr,
)
return 1 if has_failure 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