Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install api-gateway-openapi-spec-authoring@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin api-gateway-openapi-spec-authoring v1.0.0 follows the Agent Plugins spec.
gh skills-hub install api-gateway-openapi-spec-authoring Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/api-gateway-openapi-spec-authoring/ Extract the ZIP to .github/skills/ in your repo. The folder name must match api-gateway-openapi-spec-authoring for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 18.2 KB
---
name: api-gateway-openapi-spec-authoring
metadata:
version: "1.1.0"
category: ApplicationDevelopment
description: >-
Writes, migrates, and fixes OpenAPI specs for Google Cloud API Gateway. Use
when converting an OpenAPI 2.0 (Swagger) spec to OpenAPI 3.x, writing a new
OpenAPI 3.x spec, or fixing a failed "gcloud api-gateway api-configs create",
such as "extension is only supported in OpenAPI 2.x". Also use when quotas
set with x-google-quota are never enforced, or when a backend receives path
parameters as query parameters. Don't use for adding or debugging MCP tools
(use api-gateway-mcp-server), adding or changing API key, JWT, or quota
settings in a working spec, or backend lockdown (use
api-gateway-backend-security-and-rate-limiting), failing requests or service
account and concurrency errors (use api-gateway-troubleshooting), Cloud
Endpoints, Apigee, or GKE Gateway API.
---
<!-- disableFinding(LINE_OVER_80) -->
# API Gateway OpenAPI Spec Authoring
API Gateway accepts API configs in OpenAPI 2.0, 3.0.x, and 3.1.x. The Google extensions in OpenAPI 3.x have a different structure from the OpenAPI 2.0 extensions:
- A required root `x-google-api-management` block names the backends.
- `x-google-backend` is a string that references one of these backends.
- The JWT settings move into `x-google-auth`. The metrics and quotas move into `x-google-api-management`.
Use this skill to migrate an OpenAPI 2.0 spec, write a new OpenAPI 3.x spec, or fix an API config that fails to create.
## 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 tools:**
- If the Google Cloud CLI is not installed, give the user the [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 CLI is old, ask the user before you run `gcloud components update`. **Rationale:** an old CLI can fail when it uploads an OpenAPI 3.x API config.
- Install Python 3.10 or later and PyYAML for the validator script. A JSON spec does not need PyYAML. Ask the user before you install it.
```bash
pip install "PyYAML>=6.0,<7.0"
```
2. **Authenticate, and select the project, billing, and location:**
- Run `gcloud auth login`.
- Ask the user which project to use, and use that ID as `{project_id}`. If no project exists, create one with `gcloud projects create {project_id}`. Pass `--project={project_id}` on every `gcloud` command. Do not change the default project of the user with `gcloud config set project`.
- Make sure that an active billing account is linked to `{project_id}`. API Gateway has a free monthly allowance of API calls, but it still needs an active billing account. For current prices, see [API Gateway pricing](https://cloud.google.com/api-gateway/pricing).
- Use `us-central1` as the default `--location` for gateway commands. For the other supported regions, see [API Gateway deployment model](https://docs.cloud.google.com/api-gateway/docs/deployment-model.md.txt).
3. **Enable the required Google Cloud APIs:**
```bash
gcloud services enable \
apigateway.googleapis.com \
servicemanagement.googleapis.com \
servicecontrol.googleapis.com \
--project={project_id}
```
4. **Verify the IAM roles (use the most restrictive role for each step):**
- To create and update the API, API configs, and gateways: API Gateway Admin (`roles/apigateway.admin`) on `{project_id}`.
- To run the `gcloud services enable` commands: Service Usage Admin (`roles/serviceusage.serviceUsageAdmin`) on `{project_id}`.
- To reference the gateway service account in an API config: Service Account User (`roles/iam.serviceAccountUser`) on `{gateway_sa_email}`.
- For a Cloud Run backend that requires authentication: grant `{gateway_sa_email}` the Cloud Run Invoker role (`roles/run.invoker`) on the service.
## Decision Matrix
| Task | Required Mechanism | Critical Guardrail | Detailed Reference |
| --- | --- | --- | --- |
| Migrate an OpenAPI 2.0 (`swagger: "2.0"`) config | Convert the standard fields, then move each Google extension to its OpenAPI 3.x form. | A converter such as Swagger Editor leaves every `x-google-*` extension in its OpenAPI 2.0 form. It also writes `servers` without `x-google-endpoint`, so the API loses its base path. **Rationale:** API Gateway rejects most OpenAPI 2.0 extensions in a 3.x spec with `The '{extension}' extension is only supported in OpenAPI 2.x`. | [OpenAPI 2.0 to 3.x Migration](references/openapi-2-to-3-migration.md) |
| Route requests to backends | Root `x-google-api-management.backends.{backend_name}` + `x-google-backend: {backend_name}` at the root or on an operation | Set `pathTranslation` on every backend. **Rationale:** the default is `APPEND_PATH_TO_ADDRESS` for a root `x-google-backend`, but `CONSTANT_ADDRESS` for an operation-level one. `CONSTANT_ADDRESS` sends every request to the address unchanged, and sends path parameters as query parameters. `APPEND_PATH_TO_ADDRESS` appends the full request path, with the base path. NEVER set `x-google-backend` on a path item: API Gateway rejects it. | [Extensions and Limits](references/openapi-3-extensions-and-limits.md#backends) |
| Authenticate callers | JWT: `type: oauth2` scheme with `x-google-auth` (`issuer`, `jwksUri`, `audiences`). API key: `type: apiKey` scheme with `x-api-key` in a header, or `key` or `api_key` in the query. | API Gateway does not check OAuth scopes. In a `security` list, put an API key in every alternative (OR) or in none. NEVER put two JWT schemes in one requirement object (AND). **Rationale:** API Gateway rejects these combinations. If the user asks for one of them, such as a JWT or an API key as alternatives, do not write it in the spec. Explain the rule, and write a supported option, such as an API key in every alternative or a separate path for each kind of caller. For API key, JWT provider, or backend lockdown setup beyond the spec, use the `api-gateway-backend-security-and-rate-limiting` skill. If it is not installed, use this row. | [Extensions and Limits](references/openapi-3-extensions-and-limits.md#security) |
| Add quotas | `x-google-api-management.metrics` and `quota.limits` + `x-google-quota: {metric_name: cost}` on each operation | NEVER rely on `x-google-quota` at the root or path level. **Rationale:** API Gateway ignores it there without an error, in OpenAPI 3.x and in OpenAPI 2.0. Require an API key on each operation that has a quota, and keep each metric name the same in every API config. For quota setup beyond the spec, use the `api-gateway-backend-security-and-rate-limiting` skill. If it is not installed, use this row. | [Extensions and Limits](references/openapi-3-extensions-and-limits.md#quotas) |
| Set the base path and CORS | One `servers` entry with `x-google-endpoint`, such as `url: /v1` | API Gateway ignores `servers` entries without `x-google-endpoint`. `allowCors: true` only passes CORS requests to the backend. **Rationale:** the gateway does not add CORS headers, so the backend must answer them. | [Extensions and Limits](references/openapi-3-extensions-and-limits.md#servers-base-path-and-cors) |
| Fix a failed `api-configs create` | Match the error text to the error table, and fix the spec. | Fix the spec before you retry, unless the error is about IAM or another `api-configs create` that runs. **Rationale:** API Gateway returns the same error for the same spec. For a service account, IAM, or concurrency error, use the `api-gateway-troubleshooting` skill. If it is not installed, read the [troubleshoot page](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt), but do not grant the Editor role. | [API Config Errors](references/api-config-errors.md) |
| Expose operations as MCP tools, or fix `/mcp` errors | The `api-gateway-mcp-server` skill | MCP adds rules for tool names, descriptions, and `tools/list` security. If that skill is not installed, use this skill for the OpenAPI 3.x spec, and follow the [Configure MCP](https://docs.cloud.google.com/api-gateway/docs/mcp-configure.md.txt) guide for the MCP extensions. | - |
## Execution Workflow and Validation Loop
1. **Get the current spec:**
- Use the spec file in the user's repository. If there is no file, find the active API config of the gateway:
```bash
gcloud api-gateway gateways describe {gateway_id} --location={region} --project={project_id} --format="value(apiConfig)"
```
- The output is `projects/{project}/locations/global/apis/{api_id}/configs/{config_id}`. Print the spec of that config:
```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
```
- gcloud prints the contents in URL-safe base64, so `tr` changes two characters before `base64 --decode`. If the config has more than one OpenAPI document, change `[0]` to `[1]`, `[2]`, and so on.
2. **Write or fix the spec:**
- If the user only wants to fix a failed OpenAPI 2.0 spec and does not want to migrate it, keep it in OpenAPI 2.0, and fix it with the error table. The validator in step 3 checks only OpenAPI 3.x specs, so skip it for that spec.
- For an OpenAPI 2.0 spec that you migrate, follow [OpenAPI 2.0 to 3.x Migration](references/openapi-2-to-3-migration.md), and compare your result with its complete converted example.
- For a new spec, start from the template in [Extensions and Limits](references/openapi-3-extensions-and-limits.md#new-spec-template).
- Set `openapi` to a 3.0.x or 3.1.x version. The examples use `3.0.4`. In OpenAPI 3.1, give each schema one `type`. **Rationale:** API Gateway rejects a type list such as `type: ["string", "null"]`.
- Give every operation a unique `operationId` and a `responses` object, use only local `$ref` values, and do not use a YAML alias to a mapping or a sequence. **Rationale:** API Gateway rejects an operation without `operationId` or `responses`, two `operationId` values that give the same method name, such as `getItem` and `get-Item`, a `$ref` to a URL or to a file that the API config does not include, and such an alias. In OpenAPI 2.0, API Gateway rejects a file `$ref` also when the API config includes the file.
- If the API uses MCP, use the `api-gateway-mcp-server` skill for the MCP extensions. Keep all MCP operations in one document. The MCP endpoint `/mcp` stays at the host root, and the `servers` base path does not change it.
3. **Run the deterministic validation loop on every OpenAPI 3.x spec that you write or change, before you answer or create the API config:**
```bash
python3 scripts/validate_apigw_openapi.py --spec={spec_file}
```
- The script path is relative to the directory of this skill. If you only return the spec in your reply, write it to a temporary file, and run the script on that file before you answer.
- If the script exits with code `1` (`"status": "FAIL"`), fix every error in `{spec_file}`, and run the script again. Continue until it exits with code `0` (`"status": "PASS"`).
- If the script exits with code `2`, fix the file path or the YAML/JSON syntax error that stderr shows, or install PyYAML.
- Read every warning, such as a backend without `pathTranslation`, a quota on an operation without an API key, or `allowCors`. Fix it, or tell the user why you keep it.
- The script does not check every rule. A PASS means that it found none of the API Gateway problems that this skill describes. It does not check general OpenAPI validity, such as a `$ref` to a schema that does not exist. **Rationale:** only `api-configs create` in step 5 shows that API Gateway accepts the spec. Do not tell the user that the spec deploys because the script passed.
4. **Summarize the spec for the user, and get approval before you deploy.** State each of these points:
- Each OpenAPI 2.0 extension that you moved or removed, such as `x-google-allow`, which OpenAPI 3.x does not support. Also state each other change, such as an added `operationId` or a fixed address.
- The `pathTranslation` of each backend (`backend_path_translation` in the script output), and each operation whose path parameters now go to the backend as query parameters (`path_parameters_as_query`). With `APPEND_PATH_TO_ADDRESS`, the backend also receives the base path.
- Which operations need a JWT or an API key, which backends receive an ID token and with which audience, and that API Gateway does not check OAuth scopes.
- The quota metrics and limits, and that each metric name matches the current API config.
5. **Create a new API config and update the gateway** (request human approval before you update a production gateway):
```bash
gcloud api-gateway api-configs create {new_config_id} \
--api={api_id} \
--openapi-spec={spec_file} \
--backend-auth-service-account={gateway_sa_email} \
--project={project_id}
gcloud api-gateway gateways update {gateway_id} \
--api={api_id} \
--api-config={new_config_id} \
--location={region} \
--project={project_id}
```
- Before `api-configs create`, if the spec has quota metrics, load the `api-gateway-backend-security-and-rate-limiting` skill, and run its `scripts/check_quota_metrics.py`. It compares the metrics of the new spec with the API configs that gateways serve. If that skill is not installed, keep every metric and its quota limit that a running API config uses.
- For a new gateway, run `gcloud api-gateway gateways create {gateway_id}` with the same flags instead of `gateways update`. `api-configs create` creates the API if it does not exist.
- If an operation requires an API key, enable the managed service of the API. Get its name with `gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"`, and then run `gcloud services enable {managed_service} --project={project_id}`. Also enable it in each project that creates API keys for the API.
- Use a new config ID for each change, because you cannot change the spec of an existing API config.
- Run one `api-configs create` at a time for each API, and wait for it to finish. A large API config can take up to ten minutes to create.
- If `api-configs create` fails, find the error text in [API Config Errors](references/api-config-errors.md), fix the spec, and go back to step 3. For an OpenAPI 2.0 spec that you keep in 2.0, skip step 3 and create the API config again. For a service account, IAM, or concurrency error, use the `api-gateway-troubleshooting` skill. If it is not installed, read the [troubleshoot page](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt), but do not grant the Editor role.
- Keep the previous API config until the new one serves traffic. To roll back, run `gateways update` with the previous config ID.
6. **Verify the gateway:**
- Run `gcloud api-gateway gateways describe {gateway_id} --location={region} --project={project_id} --format="value(state,defaultHostname)"`, and wait until the state is `ACTIVE`.
- Send a request to each changed path at `https://{default_hostname}{base_path}{path}`, with the credential that the operation requires. Check that the backend receives the path and parameters that you expect.
- An HTML `404 Page not found` means that the gateway is not ready. Check that the last create or update finished, and retry before you change the config. During a gateway update, some requests can still reach the previous API config. A JSON 404 (`The current request is not defined by this API.`) means that the active API config does not define the path.
- For a 401, 403, 429, or 5xx response, or a timeout, after the deploy, use the `api-gateway-troubleshooting` skill. If it is not installed, read the [troubleshoot page](https://docs.cloud.google.com/api-gateway/docs/troubleshoot.md.txt). Do not grant the Editor role, and do not make the backend public, even if the page suggests it.
## Pre-Deployment Checklist
The items below apply to an OpenAPI 3.x spec. For an OpenAPI 2.0 spec that the user keeps in 2.0, check each changed setting against [API Config Errors](references/api-config-errors.md) instead.
- [ ] `openapi` is `3.0.x` or `3.1.x`, and the spec has no OpenAPI 2.0 extension, such as `x-google-management`, `x-google-endpoints`, `x-google-api-name`, `x-google-allow`, or `x-google-issuer` on a security scheme.
- [ ] `x-google-api-management.backends` defines every backend, every `x-google-backend` is a string that names one, and no path item sets `x-google-backend`.
- [ ] Every backend sets `pathTranslation`.
- [ ] Every operation has a unique `operationId` and a `responses` object, and each path variable has a parameter with `in: path` and `required: true`.
- [ ] Every `x-google-quota` is on an operation that requires an API key, and every metric name matches the current API config.
- [ ] At most one `servers` entry has `x-google-endpoint`, and its URL has no custom port.
- [ ] `python3 scripts/validate_apigw_openapi.py --spec={spec_file}` returns `"status": "PASS"` (exit code `0`).
## Resource Cleanup
To avoid ongoing charges when you tear down a test environment, request human approval, and delete the resources 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}
```
## Related skills
| Need | Skill |
| :--- | :--- |
| Expose operations as MCP tools, or fix `/mcp` errors | `api-gateway-mcp-server` |
| Set up API keys, JWT providers, backend lockdown, or quota limits, and check quota metrics before `api-configs create` | `api-gateway-backend-security-and-rate-limiting` |
| Find why requests fail after the deploy, or fix a service account, IAM, or concurrency error from `api-configs create` | `api-gateway-troubleshooting` |
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
```
api-config-errors.md 14.7 KB
<!-- disableFinding(LINE_OVER_80) -->
# API Config Errors and Silent Behaviors
- [Errors from api-configs create](#errors-from-api-configs-create): Lines 10-68
- [Silent Behaviors](#silent-behaviors): Lines 70-85
`gcloud api-gateway api-configs create` returns the first problems that it finds. Fix every error in the output. For an OpenAPI 3.x spec, run `python3 scripts/validate_apigw_openapi.py --spec={spec_file}` again. Then create a new API config.
## Errors from api-configs create
Match a part of the error text. The text in braces changes with the spec. Some errors have one text for OpenAPI 3.x and another text for OpenAPI 2.0.
| Error text | Cause | Fix |
| --- | --- | --- |
| `The 'x-google-management' extension is only supported in OpenAPI 2.x, please replace it with 'x-google-api-management'.` | An OpenAPI 2.0 metrics and quota block in an OpenAPI 3.x spec. | Move the metrics and limits into `x-google-api-management` as maps. See [Extension Mapping Table](openapi-2-to-3-migration.md#extension-mapping-table). |
| `The 'x-google-endpoints' extension is only supported in OpenAPI 2.x, please replace it with 'servers[*].x-google-endpoint'.` | An OpenAPI 2.0 endpoint block. | Move the settings to one `servers` entry with `x-google-endpoint`, and remove `name`. |
| `The 'x-google-api-name' extension is only supported in OpenAPI 2.x, please replace it with 'x-google-api-management.apiName'.` | An OpenAPI 2.0 API name. | Move the value to `x-google-api-management.apiName`. |
| `The '{extension}' extension is only supported in OpenAPI 2.x, please replace it with 'x-google-auth.{field}'.` | `x-google-issuer`, `x-google-jwks_uri`, `x-google-audiences`, `x-google-jwt-locations`, `x-issuer`, or `x-jwks_uri` on a security scheme. | Nest the values in `x-google-auth` (`issuer`, `jwksUri`, `audiences` as a list, `jwtLocations`). |
| `The 'x-google-allow' extension is only supported in OpenAPI 2.x.` | `x-google-allow` in an OpenAPI 3.x spec. | Remove it, and list every path. See the `x-google-allow` row of the [Swagger 2.0 Construct Conversion Map](openapi-2-to-3-migration.md#swagger-20-construct-conversion-map). |
| `The '{extension}' extension is only supported in OpenAPI 2.x, please replace it with 'x-google-api-management.backends'.` | `x-google-backend-url` or `x-google-backend-deadline` on an operation. At the root, API Gateway ignores them. | Define the backend in `x-google-api-management.backends`, with `address` and `deadline`, and set `x-google-backend` to its name. |
| `The 'x-security' extension is only supported in OpenAPI 2.x, please replace it with 'OpenAPI security'.` | `x-security` at the root or on an operation. | Use the OpenAPI `security` field. |
| `The '{extension}' extension is only supported in OpenAPI 2.x.` | `x-google-deprecated` or `x-google-experimental-authorization`. | Follow the "Other OpenAPI 2.0 extensions" row of the [Extension Mapping Table](openapi-2-to-3-migration.md#extension-mapping-table). |
| `Extension x-google-api-management cannot be converted into proto type` | A field that OpenAPI 3.x does not support, such as `valueType`, `metricKind`, `unit`, or `name` from OpenAPI 2.0, or both `jwtAudience` and `disableAuth` on one backend. The `Details` text names the field. | Remove the field. A metric has only `displayName`. A limit has only `metric` and `values`. Set only one of `jwtAudience` and `disableAuth`. |
| `Extension x-google-backend does not have a valid value. {value} is not defined in x-google-api-management.` | An inline `x-google-backend` object (the OpenAPI 2.0 form), a name that `backends` does not define, or an `x-google-api-management` block that failed to parse. | Fix the `cannot be converted into proto type` error first, if there is one. Define the backend in `x-google-api-management.backends`, and set `x-google-backend` to its name. |
| `Extension {extension} was specified at a path level, which is not supported.` | `x-google-backend`, `x-google-backend-url`, or `x-google-backend-deadline` on a path item. | Set `x-google-backend` at the root or on each operation. Move a URL or a deadline to a backend in `x-google-api-management.backends`. |
| `has no backend configured at the operation or API level` | An operation without an operation-level or root `x-google-backend`. | Set a root `x-google-backend`, or set `x-google-backend` on the operation. |
| `Address field in extension x-google-backend must use the HTTP or HTTPS protocol` or `is not a valid URL` | A backend `address` that is not an HTTP(S) URL. | Use the full `https://` URL of the backend. |
| `Backend URL ... cannot route requests to localhost`, `by IP Address`, `to a metadata server`, or `to an internal address` | A backend `address` with `localhost`, an IP address, a metadata server, or an `.internal` hostname. | Use a public hostname, such as the Cloud Run service URL. |
| `hostname must have more than one part to be fully qualified` | A backend `address` with a one-part hostname, often a `{placeholder}` that you did not replace. | Use the fully qualified hostname of the backend. |
| `Backend URL ... hostname contains a segment larger than 63 characters` | A hostname label longer than 63 characters. | Use a shorter hostname. |
| `Protocol field in extension x-google-backend must be 'http/1.1' or 'h2'` | Another `protocol` value. | Use `http/1.1` or `h2`. |
| `Protocol field in extension x-google-backend is only configurable to 'h2' for 'https' backends` | `protocol: h2` with an `http://` address. | Use an `https://` address, or `http/1.1`. |
| `Quota Extension for method '{method}' references undefined metric(s) '{metric}'` | An `x-google-quota` metric that `x-google-api-management.metrics` does not define. | Define the metric, or fix the name. Keep the name that the current API config uses. |
| `Metric rule defined on metric '{metric}', but has no quota limits defined.` | An `x-google-quota` metric without a quota limit. | Add a limit for the metric in `x-google-api-management.quota.limits`. |
| `Metric '{metric}' referenced by quota limit '{limit}' does not exist.` | A quota limit that names an undefined metric. | Define the metric, or fix the name in the limit. |
| `Schema has multiple types defined. More than one type is not supported, please define only one type.` | An OpenAPI 3.1 type list, such as `type: ["string", "null"]`. | Give the schema one `type`. |
| `OpenAPI spec has more than one server with x-google-endpoint extension.` | Two or more `servers` entries with `x-google-endpoint`. | Keep `x-google-endpoint` on one entry. |
| `server url '{url}' ... relative path starting with '/'` | A server URL without a scheme that does not start with `/`, such as `v1`. | Use `/v1` or an `https://` URL. |
| `is ill formed and cannot be parsed due to invalid server url` | A server variable, such as `https://{region}.example.com/v1`, or a space in the server URL. | Replace each `{variable}` with its value. |
| `has a server url '{url}' with a custom port. Custom ports are not supported.` | A port in the server URL. | Remove the port. |
| `Service name must be provided either explicitly or in OpenAPI 'host' value.` | A relative server URL in an API that uses a managed service that you chose. | Use `url: https://{managed_service}{base_path}`. |
| `'$ref' fields must be local references and cannot contain an external URL.` | A `$ref` to a URL. | Copy the schema into `components.schemas`, and use `#/components/schemas/{name}`. If you cannot get the schema, ask the user for it. |
| `Type definition reference path '{ref}' must begin with '#/components/schemas/'` | A schema `$ref` with another path, such as `#/definitions/{name}` from OpenAPI 2.0. | Move the schema to `components.schemas`, and use `#/components/schemas/{name}`. |
| `found, but no Definitions section in OpenApi File` | A file `$ref` in OpenAPI 2.0. API Gateway rejects it also when the API config includes the file. | Copy the schema into `definitions`, and use `#/definitions/{name}`. |
| `Security Scheme '{name}' that does not exist` | A `security` requirement that names an undefined scheme. | Define the scheme in `components.securitySchemes`, or fix the name. |
| `Combining API key and OAuth security requirements with a logical OR is not supported.` | A `security` list with an API key in only some alternatives, such as `[{firebase: []}, {api_key: []}]`. | Put the API key in every alternative, or in none. |
| `Optional OAuth security requirement is not supported.` | An empty requirement (`{}`) with a JWT scheme, such as `[{firebase: []}, {}]`. | Remove `{}`, or use it only with API key schemes. |
| `contains multiple security definitions` ... `that get logically ANDed` | Two JWT schemes in one requirement object. | Put each JWT scheme in its own requirement object (OR). |
| `required property 'responses' not found` (OpenAPI 3.x) or `missing required properties (["responses"])` (OpenAPI 2.0) | An operation without `responses`. | Add the responses that the backend returns. |
| `Operation does not have the required 'operationId' field` | An operation without `operationId`. | Give the operation a unique `operationId`. |
| `has duplicate entry` or `is considered equivalent to operationId` | Two equal `operationId` values, or two values that are equal after API Gateway removes the characters other than letters, digits, and underscores and capitalizes the first letter, such as `getItem` and `GetItem`. | Make the `operationId` values differ after that change. |
| `unrecognized input at '{'` or `expected '}'` | A path variable that is not a whole segment, such as `/items/prefix_{id}` or `/{a}{b}`. | Make each variable a whole segment. |
| `Declared path parameter {name} needs to be defined as a path parameter` | A path variable without a parameter with `in: path`, or a `{name=*}` or `{name=**}` path from OpenAPI 2.0. | Add a parameter with `name: {name}`, `in: path`, and `required: true`. For `{name=**}`, write `{name}`, and set `x-google-parameter: {pattern: "**"}` on the parameter. |
| `Parameter is defined in the parameters list but is not in the path.` | A parameter with `in: path` that the path does not contain. | Remove the parameter, or add `{name}` to the path. |
| `Parameter names must start with a letter` (OpenAPI 3.x) or `parameter name contains invalid characters` (OpenAPI 2.0) | A path variable name that does not start with a letter, or that has other characters. | Use letters, digits, underscores, dots, and dashes, and start with a letter. |
| `Parameter names cannot exceed 30 characters.` (OpenAPI 3.x) or `is too long (max length: 100)` (OpenAPI 2.0) | A path variable name that is too long. | Shorten the name. |
| `Too many path parameters. Maximum allowed is 15` (OpenAPI 3.x) or `exceeds maximum allowed parameters of 60` (OpenAPI 2.0) | A path with too many path parameters. | Use fewer path parameters, or split the operation. |
| `paths must be 512 characters or less` | A path that is too long. | Shorten the path. |
| `Only ** is supported.` or `must be the last segment in the path because it uses pattern: **` | An `x-google-parameter` pattern other than `**`, or `**` on a parameter that is not the last segment. | Use `pattern: "**"` only on the last path segment. |
| `does not have a value in the enumeration ["path"]` | A parameter with `in: body` or `in: formData` from OpenAPI 2.0. | Move the body or form data to `requestBody`. |
| `JWKS ... cannot route requests to localhost` | An `x-google-auth.jwksUri` that breaks the backend address rules, such as `localhost`. | Use the public key URL of the token issuer. |
| `JWKS provider "{name}" is missing a JWKS URI` | A `type: oauth2` security scheme without `x-google-auth.jwksUri`, also a scheme that no operation uses. | Set `jwksUri` in `x-google-auth`, or remove the unused scheme. |
| `which exceeds the maximum of 600 seconds supported by this Gateway` | A backend `deadline` above 600 seconds. `gateways create` or `gateways update` returns this error, not `api-configs create`. | Set `deadline` to 600 or less. A streaming gateway accepts up to 3600. |
| `string found, object expected` or `string found, array expected` (OpenAPI 2.0: `instance type (string) does not match any allowed primitive type (allowed: ["object"])` or `["array"]`) | Often a YAML alias (`*anchor`) to a mapping (`object expected`) or to a sequence (`array expected`). An alias to a scalar is accepted. | Replace the alias with a `$ref`, or copy the mapping or the sequence. |
| `Invalid API name '{name}'` | An `apiName` that is not a lowercase letter followed by at most 39 lowercase letters or digits. | Use a name such as `orders`. |
| `OpenAPI files includes conflicting API versions` | Two files in one API config with the same `apiName`, or without `apiName`, and the same major version. | Merge the files, or give each file its own `x-google-api-management.apiName`. |
| `maximum allowed number of 50 files` or `maximum allowed size of 10MB` | Too many or too large OpenAPI files. | Merge or shrink the files. |
## Silent Behaviors
API Gateway accepts these specs without an error, but does not do what the author often expects. The validator script reports the first row as an error and the other rows as warnings.
| Spec | What API Gateway does | Fix |
| --- | --- | --- |
| `x-google-quota` at the root or on a path item | Ignores it, in OpenAPI 3.x and in OpenAPI 2.0. No quota applies. | Set `x-google-quota` on each operation. |
| An operation-level `x-google-backend` whose backend has no `pathTranslation` | Uses `CONSTANT_ADDRESS`: it sends each request to the `address` unchanged, and sends path parameters as query parameters. | Set `pathTranslation: APPEND_PATH_TO_ADDRESS` on the backend if the backend routes by path. |
| A Cloud Run `address` with a path, and no `jwtAudience` | Sends an ID token whose audience is the full address. Cloud Run rejects the token. | Set `jwtAudience` to the service URL without the path. |
| `servers` entries without `x-google-endpoint` | Ignores them, and applies no base path. | Add `x-google-endpoint: {}` to the entry with the base path. |
| `allowCors: true` | Passes CORS requests to the backend. It does not add CORS headers. | Make the backend answer preflight `OPTIONS` requests and add the CORS headers. |
| OAuth scopes in a security scheme | Does not check them. | Check the scopes in the backend. |
| An API key scheme with a name other than `x-api-key` in a header, or `key` or `api_key` in the query | Ignores the scheme. Operations that require only this scheme accept calls without a key. | Use one of the supported names and locations. |
| `x-google-quota` on an operation that does not require an API key | Accepts calls without an API key, and cannot identify the consumer project that the quota counts. | Require an API key in every security alternative of the operation. |
API Gateway also does not check required parameters, parameter types, or request body schemas. It forwards each request, so the backend must validate the input.
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-openapi-spec-authoring)" \
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-openapi-spec-authoring)` 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-openapi-spec-authoring)
```
- **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.
openapi-2-to-3-migration.md 16.6 KB
# OpenAPI 2.0 to 3.x Migration for API Gateway
- [Migration Steps](#migration-steps): Lines 9-18
- [Extension Mapping Table](#extension-mapping-table): Lines 20-35
- [Extension Examples](#extension-examples): Lines 37-151
- [Swagger 2.0 Construct Conversion Map](#swagger-20-construct-conversion-map): Lines 153-170
- [Complete Converted Example](#complete-converted-example): Lines 172-384
## Migration Steps
1. Get the OpenAPI 2.0 spec: the file in the user's repository, or the spec of the active API config of the gateway (see step 1 of the workflow in `SKILL.md`). If the spec has no `x-google-backend`, ask the user for the backend URL. Do not invent an address.
2. Convert the standard fields. The conversion utility in [Swagger Editor](https://editor-next.swagger.io/) changes `swagger` to `openapi`, `securityDefinitions` to `components.securitySchemes`, `definitions` to `components.schemas`, and `in: body` parameters to `requestBody`. To convert by hand, use the [Swagger 2.0 Construct Conversion Map](#swagger-20-construct-conversion-map).
3. Move each Google extension with the [Extension Mapping Table](#extension-mapping-table). **Rationale:** a converter leaves every `x-google-*` extension in its OpenAPI 2.0 form, and API Gateway rejects most of them in an OpenAPI 3.x spec.
4. Add `x-google-endpoint: {}` to the `servers` entry that has the base path. **Rationale:** a converter writes `servers` without `x-google-endpoint`, and API Gateway ignores such entries, so calls to the base path return HTTP 404.
5. Set `pathTranslation` on every backend. Keep the behavior of the OpenAPI 2.0 spec: OpenAPI 2.0 has the same defaults (`APPEND_PATH_TO_ADDRESS` for a root backend, `CONSTANT_ADDRESS` for an operation-level backend).
6. Run `python3 scripts/validate_apigw_openapi.py --spec={spec_file}`. Fix every error. Fix every warning, or tell the user why you keep it.
Reference: [Modify a gateway to use OpenAPI 3.x](https://docs.cloud.google.com/api-gateway/docs/migrate-oasv3.md.txt)
## Extension Mapping Table
| Feature | OpenAPI 2.0 | OpenAPI 3.x | Required change |
| --- | --- | --- | --- |
| Backends | Inline `x-google-backend` object at the root or on an operation, with `snake_case` fields (`address`, `jwt_audience`, `disable_auth`, `path_translation`, `deadline`, `protocol`) | Root `x-google-api-management.backends.{backend_name}` with `camelCase` fields (`address`, `jwtAudience`, `disableAuth`, `pathTranslation`, `deadline`, `protocol`) + `x-google-backend: {backend_name}` | Define one named backend for each distinct backend object, and replace each object with the name. Compare all fields, not only `address`. If the root and an operation use the same object without `path_translation`, define two backends: one with `APPEND_PATH_TO_ADDRESS` for the root, and one with `CONSTANT_ADDRESS` for the operation. API Gateway rejects an inline object in OpenAPI 3.x. |
| JWT authentication | `x-google-issuer`, `x-google-jwks_uri`, `x-google-audiences` (a comma-separated string), and `x-google-jwt-locations` on the security definition. Older specs use `x-issuer` and `x-jwks_uri`. | `x-google-auth: {issuer, jwksUri, audiences, jwtLocations}` in `components.securitySchemes.{scheme_name}` | Nest the values in `x-google-auth`. Change `audiences` to a YAML list: split the string at the commas, and remove the spaces. In each JWT location, `value_prefix` becomes `valuePrefix`. |
| API key | `securityDefinitions` entry with `type: apiKey` | `components.securitySchemes` entry with `type: apiKey` | No change other than the move. |
| Metrics and quota limits | `x-google-management.metrics` and `quota.limits` lists, with `name`, `valueType`, `metricKind`, `unit`, and `values: {STANDARD: N}` | `x-google-api-management.metrics` and `quota.limits` maps, keyed by name, with `values: N` | Make each list a map keyed by the old `name`. Keep only `displayName` on each metric, and only `metric` and `values` on each limit. API Gateway rejects the other fields, such as `valueType`, `metricKind`, and `unit`, and it uses the unit `1/min/{project}`. Keep each metric name exactly the same. |
| Quota cost | `x-google-quota: {metricCosts: {metric_name: cost}}` | `x-google-quota: {metric_name: cost}` on each operation | Remove the `metricCosts` wrapper. API Gateway ignores `x-google-quota` at the root or path level, in OpenAPI 3.x and in OpenAPI 2.0. |
| Base path | `basePath` | `servers: [{url: {basePath}, x-google-endpoint: {}}]` | Make sure that one `servers` entry has `x-google-endpoint`, even an empty `{}`. A converter does not add it. |
| Endpoint and CORS | Root `x-google-endpoints: [{name, allowCors}]` | `servers: [{url, x-google-endpoint: {allowCors}}]` | Move `allowCors` (and `target`, if set) to one `servers` entry, and remove `name`. |
| API name | `x-google-api-name` | `x-google-api-management.apiName` | Move the value. |
| Catch-all routing | `x-google-allow: all` | Not supported | Remove it, and list every path. To forward every other path as OpenAPI 2.0 did, see the `x-google-allow` row of the [Swagger 2.0 Construct Conversion Map](#swagger-20-construct-conversion-map). |
| Other OpenAPI 2.0 extensions | `x-google-deprecated`, `x-google-experimental-authorization`, `x-google-backend-url`, `x-google-backend-deadline`, and `x-security` | Not supported | Remove `x-google-deprecated` and `x-google-experimental-authorization`. Move a backend URL or deadline to `x-google-api-management.backends`, and move `x-security` to the OpenAPI `security` field. |
Reference: [OpenAPI 3.x extensions in API Gateway](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)
## Extension Examples
Backend, OpenAPI 2.0:
```yaml
x-google-backend:
address: https://orders-abc123-uc.a.run.app
path_translation: APPEND_PATH_TO_ADDRESS
```
Backend, OpenAPI 3.x:
```yaml
x-google-api-management:
backends:
orders-backend:
address: https://orders-abc123-uc.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
x-google-backend: orders-backend
```
JWT scheme, OpenAPI 2.0:
```yaml
securityDefinitions:
firebase:
type: oauth2
flow: implicit
authorizationUrl: ""
x-google-issuer: "https://securetoken.google.com/{firebase_project_id}"
x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
x-google-audiences: "{firebase_project_id}"
```
JWT scheme, OpenAPI 3.x:
```yaml
components:
securitySchemes:
firebase:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: "https://securetoken.google.com/{firebase_project_id}"
jwksUri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
audiences:
- "{firebase_project_id}"
```
Quota, OpenAPI 2.0:
```yaml
x-google-management:
metrics:
- name: read-requests
displayName: Read requests
valueType: INT64
metricKind: DELTA
quota:
limits:
- name: read-limit
metric: read-requests
unit: "1/min/{project}"
values:
STANDARD: 600
paths:
/orders:
get:
x-google-quota:
metricCosts:
read-requests: 1
```
Quota, OpenAPI 3.x:
```yaml
x-google-api-management:
metrics:
read-requests:
displayName: Read requests
quota:
limits:
read-limit:
metric: read-requests
values: 600
paths:
/orders:
get:
x-google-quota:
read-requests: 1
```
Endpoint, base path, and API name, OpenAPI 2.0:
```yaml
basePath: /v1
x-google-endpoints:
- name: "orders-api-1a2b3c.apigateway.{project_id}.cloud.goog"
allowCors: true
x-google-api-name: orders
```
Endpoint, base path, and API name, OpenAPI 3.x:
```yaml
servers:
- url: /v1
x-google-endpoint:
allowCors: true
x-google-api-management:
apiName: orders
```
## Swagger 2.0 Construct Conversion Map
| Swagger 2.0 construct | OpenAPI 3.x for API Gateway |
| --- | --- |
| `host`, `basePath: /v1`, and `schemes` | `servers: [{url: /v1, x-google-endpoint: {}}]`. Remove `host` and `schemes`. Use `url: https://{managed_service}/v1` instead if the API uses a managed service that you chose, and not the default `*.apigateway.{project_id}.cloud.goog` service, because API Gateway then reads the service name from the URL host. Use it also if the user shares the spec with API consumers. `{managed_service}` is the output of `gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"`. |
| Root `x-google-backend` object | A named backend in `x-google-api-management.backends` + root `x-google-backend: {backend_name}`. |
| Operation `x-google-backend` object | A named backend + operation `x-google-backend: {backend_name}`. If the object has no `path_translation`, set `pathTranslation: CONSTANT_ADDRESS` to keep the OpenAPI 2.0 behavior. Do not share this backend with the root if the root object has no `path_translation` either. |
| `in: body` parameter | `requestBody.content.application/json.schema`. |
| `in: formData` parameters | `requestBody` with the `application/x-www-form-urlencoded` or `multipart/form-data` media type. |
| Parameter `type`, `format`, and `items` | Move them into the parameter `schema`. |
| `collectionFormat: csv` | `style: form` and `explode: false` (query), or `style: simple` (path or header), with an array `schema` of a primitive type. API Gateway does not check or split the value. The backend gets the comma-separated string and must parse it. |
| `definitions` and `#/definitions/{name}` | `components.schemas` and `#/components/schemas/{name}`. |
| Root `parameters` and `responses` | `components.parameters` and `components.responses`. |
| `securityDefinitions` | `components.securitySchemes`. An oauth2 `flow: implicit` with `authorizationUrl: {url}` becomes `flows: {implicit: {authorizationUrl: {url}, scopes: {}}}`. Map `accessCode` to `authorizationCode`, `application` to `clientCredentials`, and `password` to `password`, and keep `tokenUrl`. |
| `consumes` and `produces` | The media types in `requestBody.content` and in each `responses.{code}.content`. |
| Response `schema` | `responses.{code}.content.application/json.schema`. You can quote each status code key, such as `"200"`, to keep the keys strings. |
| Path template `{name=**}` | `{name}`, with `x-google-parameter: {pattern: "**"}` on the path parameter. OpenAPI 3.x rejects the `{name=*}` and `{name=**}` syntax. |
| `x-google-allow: all` | Remove it. To keep the OpenAPI 2.0 behavior, add a path such as `/{path}` whose `path` parameter has `in: path`, `required: true`, and `x-google-parameter: {pattern: "**"}`. Add one operation for each of `get`, `post`, `put`, `patch`, and `delete`, each with a unique `operationId` and `security: []`. **Rationale:** OpenAPI 2.0 passed these calls to the backend without an API key or a JWT. Remove `security: []` only if the user wants the gateway to check credentials on these paths. If the spec enables MCP, set `x-google-mcp-tool: false` on these catch-all operations, so that they do not become MCP tools. |
## Complete Converted Example
The OpenAPI 2.0 input has a base path, a root Cloud Run backend, an operation-level Cloud Run functions backend, an API key, a Firebase JWT, a quota, and `x-google-allow`:
```yaml
swagger: "2.0"
info:
title: Inventory API
version: 1.2.0
host: "inventory-api-1a2b3c.apigateway.{project_id}.cloud.goog"
basePath: /v1
schemes:
- https
x-google-allow: all
x-google-backend:
address: https://inventory-abc123-uc.a.run.app
path_translation: APPEND_PATH_TO_ADDRESS
deadline: 30.0
x-google-management:
metrics:
- name: read-requests
displayName: Read requests
valueType: INT64
metricKind: DELTA
quota:
limits:
- name: read-limit
metric: read-requests
unit: "1/min/{project}"
values:
STANDARD: 600
securityDefinitions:
api_key:
type: apiKey
name: key
in: query
firebase:
type: oauth2
flow: implicit
authorizationUrl: ""
x-google-issuer: "https://securetoken.google.com/{firebase_project_id}"
x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
x-google-audiences: "{firebase_project_id}"
security:
- api_key: []
paths:
/items/{itemId}:
get:
operationId: getItem
x-google-quota:
metricCosts:
read-requests: 1
parameters:
- name: itemId
in: path
required: true
type: string
responses:
200:
description: The item.
schema:
$ref: "#/definitions/Item"
/items:
post:
operationId: createItem
security:
- api_key: []
firebase: []
parameters:
- name: item
in: body
required: true
schema:
$ref: "#/definitions/Item"
responses:
200:
description: The created item.
schema:
$ref: "#/definitions/Item"
/reports/daily:
get:
operationId: getDailyReport
x-google-backend:
address: "https://us-central1-{project_id}.cloudfunctions.net/dailyReport"
responses:
200:
description: The daily report.
definitions:
Item:
type: object
required:
- sku
properties:
sku:
type: string
quantity:
type: integer
format: int32
```
The OpenAPI 3.x output:
```yaml
openapi: 3.0.4
info:
title: Inventory API
version: 1.2.0
servers:
- url: /v1
x-google-endpoint: {}
x-google-api-management:
backends:
inventory-backend:
address: https://inventory-abc123-uc.a.run.app
pathTranslation: APPEND_PATH_TO_ADDRESS
deadline: 30.0
daily-report-fn:
address: "https://us-central1-{project_id}.cloudfunctions.net/dailyReport"
pathTranslation: CONSTANT_ADDRESS
metrics:
read-requests:
displayName: Read requests
quota:
limits:
read-limit:
metric: read-requests
values: 600
x-google-backend: inventory-backend
security:
- api_key: []
components:
securitySchemes:
api_key:
type: apiKey
name: key
in: query
firebase:
type: oauth2
flows:
implicit:
authorizationUrl: ""
scopes: {}
x-google-auth:
issuer: "https://securetoken.google.com/{firebase_project_id}"
jwksUri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
audiences:
- "{firebase_project_id}"
schemas:
Item:
type: object
required:
- sku
properties:
sku:
type: string
quantity:
type: integer
format: int32
paths:
/items/{itemId}:
get:
operationId: getItem
x-google-quota:
read-requests: 1
parameters:
- name: itemId
in: path
required: true
schema:
type: string
responses:
"200":
description: The item.
content:
application/json:
schema:
$ref: "#/components/schemas/Item"
/items:
post:
operationId: createItem
security:
- api_key: []
firebase: []
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/Item"
responses:
"200":
description: The created item.
content:
application/json:
schema:
$ref: "#/components/schemas/Item"
/reports/daily:
get:
operationId: getDailyReport
x-google-backend: daily-report-fn
responses:
"200":
description: The daily report.
```
What changed:
- `x-google-allow` is gone. The spec lists every path that clients call. Requests to other paths now return HTTP 404. In OpenAPI 2.0, they went to the backend without an API key.
- `host`, `basePath`, and `schemes` became one `servers` entry with `x-google-endpoint`.
- Each inline `x-google-backend` object became a named backend. The Cloud Run functions backend sets `pathTranslation: CONSTANT_ADDRESS`, which is the OpenAPI 2.0 default for an operation-level backend.
- The metrics and limits became maps without `valueType`, `metricKind`, and `unit`, and `x-google-quota` lost its `metricCosts` wrapper. The metric name `read-requests` did not change. `getItem` keeps its API key requirement from the root `security`, because API Gateway uses the API key to identify the consumer project for the quota.
- The JWT settings moved into `x-google-auth`, and `audiences` became a list.
- `in: body` became `requestBody`, `definitions` became `components.schemas`, and each response schema moved into `content`.
openapi-3-extensions-and-limits.md 14.7 KB
<!-- disableFinding(LINE_OVER_80) -->
# OpenAPI 3.x Extensions and Limits in API Gateway
- [New Spec Template](#new-spec-template): Lines 13-71
- [x-google-api-management](#x-google-api-management): Lines 73-87
- [Backends](#backends): Lines 89-115
- [Security](#security): Lines 117-147
- [Quotas](#quotas): Lines 149-159
- [Servers, Base Path, and CORS](#servers-base-path-and-cors): Lines 161-170
- [Paths, Operations, and Schemas](#paths-operations-and-schemas): Lines 172-186
## New Spec Template
Replace each `{placeholder}`. The template has a Cloud Run backend, an API key on every operation, and one quota.
```yaml
openapi: 3.0.4
info:
title: "{api_title}"
version: 1.0.0
servers:
- url: /v1
x-google-endpoint: {}
x-google-api-management:
backends:
main-backend:
address: "https://{cloud_run_service_url_host}"
pathTranslation: APPEND_PATH_TO_ADDRESS
metrics:
read-requests:
displayName: Read requests
quota:
limits:
read-limit:
metric: read-requests
values: 600
x-google-backend: main-backend
security:
- api_key: []
components:
securitySchemes:
api_key:
type: apiKey
name: x-api-key
in: header
paths:
/items/{itemId}:
get:
operationId: getItem
summary: Get one item by ID.
x-google-quota:
read-requests: 1
parameters:
- name: itemId
in: path
required: true
schema:
type: string
responses:
"200":
description: The item.
```
With this template, a request to `/v1/items/42` reaches the backend as `/v1/items/42`, because `APPEND_PATH_TO_ADDRESS` keeps the base path. The Cloud Run service must serve the `/v1` paths.
API keys work only after you enable the managed service of the API:
1. Get the name of the managed service with `gcloud api-gateway apis describe {api_id} --project={project_id} --format="value(managedService)"`.
2. Run `gcloud services enable {managed_service} --project={project_id}`.
3. Enable the managed service also in each project that creates API keys for the API. **Rationale:** API Gateway rejects an API key unless the API is enabled in the project that created the key.
## x-google-api-management
Put this required extension at the root of the spec.
| Field | Required | Use |
| --- | --- | --- |
| `backends` | Yes | A map from each backend name to its settings. See [Backends](#backends). |
| `metrics` | No | A map from each quota metric name to `{displayName}`. See [Quotas](#quotas). |
| `quota` | No | `limits`: a map from each limit name to `{metric, values}`. See [Quotas](#quotas). |
| `apiName` | No | A name for the operations in this document: a lowercase letter, then at most 39 lowercase letters or digits, such as `orders`. API Gateway also accepts a dotted name of at most 40 characters, such as `example.orders`. API Gateway rejects two documents in one API config with the same `apiName` and the same major `info.version`. A document without `apiName` uses the name of the managed service, so give each document of an API config its own `apiName`. |
| `mcp` | No | Enables MCP tools. Use the `api-gateway-mcp-server` skill. |
| `ai` | No | Model routing. An API config cannot have both MCP and model routing. It also cannot have model-routing operations and other operations, in one file or across files. |
| `modelRouter` | No | The default model router of the API, for a request without an operation-level `x-google-model-router`. |
API Gateway rejects the whole block if it has another field, such as the OpenAPI 2.0 field `unit` on a quota limit.
## Backends
| Field | Default | Rules |
| --- | --- | --- |
| `address` | None | Required. An `https://` or `http://` URL with a fully qualified hostname. API Gateway rejects an IP address, `localhost`, a metadata server, an `.internal` hostname, and a hostname segment longer than 63 characters. |
| `jwtAudience` | The full `address`, with its path | The audience of the Google ID token that the gateway sends to the backend. Set it to the OAuth client ID for an App Engine or IAP backend. For a Cloud Run address that has a path, set it to the service URL without the path, because Cloud Run expects its service URL. |
| `disableAuth` | `false` | Set `true` only for a backend that does not check tokens. Then the gateway sends no ID token. Set only one of `jwtAudience` and `disableAuth`. |
| `pathTranslation` | `APPEND_PATH_TO_ADDRESS` for a root `x-google-backend`, `CONSTANT_ADDRESS` for an operation-level one | Always set it. If the root and an operation reference one backend without `pathTranslation`, each reference uses its own default. |
| `deadline` | `15.0` | Seconds to wait for a full response. Some gateways reject a value above `600` when you create or update the gateway. A streaming gateway accepts up to `3600`. |
| `protocol` | `http/1.1` | `http/1.1` or `h2`. Use `h2` only with an `https://` address. gRPC needs `h2`, and WebSockets need `http/1.1`. |
Path translation examples:
| `pathTranslation` | `address` | Server `url` | Request | Backend request |
| --- | --- | --- | --- | --- |
| `APPEND_PATH_TO_ADDRESS` | `https://inventory-abc123-uc.a.run.app` | none | `/items/42` | `https://inventory-abc123-uc.a.run.app/items/42` |
| `APPEND_PATH_TO_ADDRESS` | `https://inventory-abc123-uc.a.run.app` | `/v1` | `/v1/items/42` | `https://inventory-abc123-uc.a.run.app/v1/items/42` |
| `CONSTANT_ADDRESS` | `https://us-central1-{project_id}.cloudfunctions.net/getItem` | none | `/items/42` | `https://us-central1-{project_id}.cloudfunctions.net/getItem?itemId=42` |
The OpenAPI path in each row is `/items/{itemId}`.
- Use `APPEND_PATH_TO_ADDRESS` for a backend that routes by path, such as a Cloud Run service, a GKE service, or an App Engine app. The backend gets the full request path, with the base path.
- Use `CONSTANT_ADDRESS` for a backend that serves one operation at a fixed URL, such as a Cloud Run function.
- Set `x-google-backend` at the root or on an operation, never on a path item. **Rationale:** API Gateway rejects `x-google-backend` at the path level.
- For a Cloud Run backend that requires authentication, keep the default token, and grant the gateway service account the Cloud Run Invoker role (`roles/run.invoker`) on the service.
Reference: [OpenAPI 3.x extensions: Backends](https://docs.cloud.google.com/api-gateway/docs/oasv3-extensions.md.txt)
## Security
JWT scheme fields (`x-google-auth` in a `type: oauth2` security scheme):
| Field | Rules |
| --- | --- |
| `issuer` | The `iss` claim of the token, such as `https://accounts.google.com` for Google ID tokens or `https://securetoken.google.com/{firebase_project_id}` for Firebase. |
| `jwksUri` | Required, also in a scheme that no operation uses. The URL of the public keys, in JWK set or X509 format, such as `https://www.googleapis.com/oauth2/v3/certs` for Google ID tokens. API Gateway applies the same hostname rules as for a backend `address`. |
| `audiences` | A YAML list of the accepted `aud` values. |
| `jwtLocations` | A list of `{header, valuePrefix}` or `{query}` entries. By default, API Gateway reads the token from the `Authorization: Bearer` header, the `X-Goog-Iap-Jwt-Assertion` header, or the `access_token` query parameter. |
Give the scheme an OAuth flow, such as `flows: {implicit: {authorizationUrl: "", scopes: {}}}`. API Gateway reads the JWT settings only from `x-google-auth`. It adds a JWT provider for every `oauth2` scheme, also for a scheme that no operation uses, and it rejects a provider without `jwksUri`. Remove the `oauth2` schemes that you do not use, such as documentation-only schemes from a converter.
API key scheme: `type: apiKey` with `in: header` and `name: x-api-key`, or with `in: query` and `name: key` or `api_key`. API Gateway ignores every other API key scheme, with only a warning. Then an operation that requires only that scheme accepts calls without a key.
Security requirement rules:
| Rule | Example |
| --- | --- |
| AND of an API key and a JWT is supported. | `security: [{api_key: [], firebase: []}]` |
| AND of two JWT schemes is not supported. | Do not write `security: [{firebase: [], google_id_token: []}]`. |
| OR of JWT schemes is supported. | `security: [{firebase: []}, {google_id_token: []}]` |
| OR is supported only if every alternative has the API key, or none has it. | `security: [{api_key: [], firebase: []}, {api_key: [], google_id_token: []}]`. Do not write `security: [{firebase: []}, {api_key: []}]`. |
| Optional security (`{}`) works only for an API key. | `security: [{api_key: []}, {}]` |
| Every named scheme must exist in `components.securitySchemes`. | API Gateway rejects the API config otherwise. |
- The root `security` list applies to every operation that does not set its own `security`. To remove the root requirement from one operation, set `security: []` on it.
- API Gateway does not check OAuth scopes. Check scopes in the backend.
- API Gateway checks the token claims against the scheme. It does not check the IAM roles of the caller. A Google ID token scheme accepts every caller that can get a token with an accepted audience. To accept only some callers, check the claims in the backend: API Gateway forwards the JWT payload in the `X-Apigateway-Api-Userinfo` header.
Reference: [OpenAPI 3.x feature limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
## Quotas
1. Define each metric in `x-google-api-management.metrics`, such as `read-requests: {displayName: Read requests}`.
2. Define each limit in `x-google-api-management.quota.limits`, such as `read-limit: {metric: read-requests, values: 600}`. `values` is the number of requests per minute for each consumer Google Cloud project. Give each metric that an operation uses a limit, because API Gateway rejects a charged metric without a limit.
3. Set `x-google-quota: {read-requests: 1}` on each operation that counts against the metric. The value is the cost of one request. **Rationale:** API Gateway ignores `x-google-quota` at the root or path level, without an error, in OpenAPI 3.x and in OpenAPI 2.0, even where a documentation example shows it at the root.
4. Require an API key in every security alternative of each operation that has `x-google-quota`. **Rationale:** API Gateway uses the API key to identify the consumer project that the quota counts.
5. Keep the metric and limit names the same in every API config of the API. **Rationale:** metrics and limits apply to the whole API, and the newest API config replaces them. If you rename or remove a metric, a gateway that still serves an older API config returns HTTP 500 (`Failed to call Service Control Quota`) on its quota-enforced operations.
For per-consumer limits, consumer overrides, and HTTP 429 handling, use the `api-gateway-backend-security-and-rate-limiting` skill if it is installed.
Reference: [Quotas apply to the whole API](https://docs.cloud.google.com/api-gateway/docs/quotas-overview.md.txt)
## Servers, Base Path, and CORS
- Put `x-google-endpoint` on one `servers` entry. Its URL path is the base path of the API. **Rationale:** API Gateway permits only one such entry, and it ignores every `servers` entry without `x-google-endpoint`. With no such entry, the API has no base path.
- Use a relative URL, such as `url: /v1`. If the API has a managed service that you chose, and not the default `*.apigateway.{project_id}.cloud.goog` service, use `url: https://{managed_service}/v1`. **Rationale:** API Gateway reads the service name from the URL host for such an API.
- A relative URL must start with `/`. Do not set `url` to null, and do not use a custom port or a server variable such as `{region}`. **Rationale:** API Gateway rejects these URLs. An empty `url` or `/` gives no base path.
- If an API config has several OpenAPI files, give each file a server with the same `x-google-endpoint` settings and the same host, and give each file its own `apiName`. The base path can differ.
- If the API uses MCP, the MCP endpoint `/mcp` stays at the host root, and the base path does not change it. Keep all MCP operations in one document. **Rationale:** API Gateway fails to create an API config that has MCP extensions in more than one document, and the error does not say why.
- `allowCors: true` makes API Gateway pass CORS requests, including preflight `OPTIONS` requests, to the backend. API Gateway does not add CORS headers. Make the backend answer each preflight request and add the CORS response headers.
Reference: [OpenAPI 3.x feature limitations: Servers](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt)
## Paths, Operations, and Schemas
- Give every operation a unique `operationId` and a `responses` object. API Gateway removes the characters other than letters, digits, and underscores from each `operationId`, and capitalizes the first letter. The results must also be unique. For example, `getItem` and `GetItem` conflict, but `get_item` and `getItem` do not.
- Make each path variable a whole segment, such as `/items/{itemId}`. API Gateway rejects a partial segment, such as `/items/prefix_{id}` or `/{a}{b}`.
- Give each path variable a parameter with `in: path` and `required: true`.
- Start each variable name with a letter, and use only letters, digits, underscores, dots, and dashes, with at most 30 characters. Use at most 15 path parameters in a path. Keep the names unique after API Gateway converts them to snake_case: `bookId` and `book_id` conflict. Keep each path at 512 characters or less.
- For a variable that matches several segments, write `{name}` and set `x-google-parameter: {pattern: "**"}` on the parameter. Use it only on the last segment of the path. OpenAPI 3.x rejects `{name=*}` and `{name=**}`.
- Give each schema one `type`. API Gateway rejects an OpenAPI 3.1 type list, such as `type: ["string", "null"]`. In OpenAPI 3.0, use `nullable: true` for a field that can be null.
- Use a primitive type or an array of a primitive type for a request parameter. API Gateway rejects an object parameter.
- API Gateway does not check required parameters, parameter types, request bodies, or content types. It forwards each request to the backend, so the backend must validate the input.
- Use local references, such as `$ref: "#/components/schemas/Item"`. API Gateway rejects a `$ref` to a URL. It also rejects a `$ref` to another file, unless you pass that file in the same API config. Keep the schemas in the same file.
- Use `$ref` instead of YAML anchors and aliases. API Gateway rejects an alias to a mapping or to a sequence, and the error (`string found, object expected` or `string found, array expected`) does not name the alias. An alias to a scalar works, but avoid it.
- Keep the files of one API config at 10 MB in total, and at most 50 files.
Reference: [OpenAPI 3.x feature limitations](https://docs.cloud.google.com/api-gateway/docs/openapi-v3-limitations.md.txt) and [Path templating](https://docs.cloud.google.com/api-gateway/docs/path-templating.md.txt)
validate_apigw_openapi.py 57.7 KB
#!/usr/bin/env python3
"""Checks an OpenAPI 3.x spec for the API Gateway problems in this skill.
The script checks only the API Gateway rules that the skill describes. It does
not check general OpenAPI validity, such as a $ref to a schema that does not
exist. A PASS does not mean that API Gateway accepts the spec.
"gcloud api-gateway api-configs create" is the final check.
Errors are rules that make API Gateway reject the API config. An x-google-quota
at the root or path level is also an error: API Gateway accepts it but ignores
it, so no quota applies. Warnings are settings that API Gateway accepts but
applies in a way that the author often does not expect.
The checks cover:
- The OpenAPI version, and the OpenAPI 2.0 extensions and fields that a
migration leaves, such as x-google-management or a parameter "type".
- x-google-api-management: the fields of each part, the backends, the metrics,
and the quota limits.
- x-google-backend and x-google-quota: where they are and the names that they
use, the backend path translation, and the path parameters that the backend
gets as query parameters.
- Security: the requirement combinations that API Gateway rejects, the
x-google-auth fields, and the API key schemes that API Gateway ignores.
- The server with x-google-endpoint, path templates, path parameters,
operationIds, schema type lists, $ref targets, and YAML aliases.
"""
from __future__ import annotations
import argparse
from collections.abc import Iterator
import dataclasses
import ipaddress
import json
import re
import sys
import types
from typing import Any
from urllib import parse
try:
import yaml
_HAS_YAML = True
except ImportError:
_HAS_YAML = False
_OAS3_RE = re.compile(r'3\.[01]\.\d+')
_HTTP_METHODS = frozenset(
{'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'}
)
# A path variable, such as {itemId}. A whole path segment must match it.
_PATH_VARIABLE_RE = re.compile(r'\{([^{}]*)\}')
# A custom verb at the end of the last path segment, such as {shelf}:merge.
_CUSTOM_VERB_RE = re.compile(r'(?<=\}):[^/{}]+$')
# The characters that API Gateway removes from an operationId before it
# derives a method name. It keeps letters, digits, and underscores.
_SPECIAL_CHARACTERS_RE = re.compile(r'[^A-Za-z0-9_]')
_MAX_DEADLINE_SECONDS = 3600
_MAX_NON_STREAMING_DEADLINE_SECONDS = 600
_MAX_ALIAS_LINES = 5
_PATH_TRANSLATIONS = frozenset({'APPEND_PATH_TO_ADDRESS', 'CONSTANT_ADDRESS'})
_PROTOCOLS = frozenset({'http/1.1', 'h2'})
_URL_SCHEMES = frozenset({'http', 'https'})
# OpenAPI 2.0 parameter fields. In OpenAPI 3.x, they move into "schema", or
# "style" and "explode" replace them.
_V2_PARAMETER_FIELDS = frozenset(
{'collectionFormat', 'format', 'items', 'type'}
)
# OpenAPI 2.0 root extensions that API Gateway rejects in OpenAPI 3.x, and the
# change to make for each.
_V2_ROOT_EXTENSIONS = types.MappingProxyType({
'x-google-management': (
'Move the metrics and limits into x-google-api-management as maps.'
),
'x-google-endpoints': (
'Move the settings to one servers entry with x-google-endpoint.'
),
'x-google-api-name': 'Move the value to x-google-api-management.apiName.',
'x-google-allow': 'Remove it, and list every path that clients call.',
'x-google-deprecated': 'Remove it.',
'x-google-experimental-authorization': 'Remove it.',
'x-security': 'Use the OpenAPI "security" field.',
})
# OpenAPI 2.0 backend extensions. API Gateway rejects them on a path item or an
# operation in OpenAPI 3.x, and it ignores them at the root.
_V2_BACKEND_EXTENSIONS = types.MappingProxyType({
'x-google-backend-url': (
'Define a backend in x-google-api-management.backends, and set'
' x-google-backend to its name.'
),
'x-google-backend-deadline': (
'Set "deadline" on the backend in x-google-api-management.backends.'
),
})
# OpenAPI 2.0 security scheme extensions, and the x-google-auth field of each.
_V2_AUTH_EXTENSIONS = types.MappingProxyType({
'x-google-issuer': 'issuer',
'x-issuer': 'issuer',
'x-google-jwks_uri': 'jwksUri',
'x-jwks_uri': 'jwksUri',
'x-google-audiences': 'audiences',
'x-google-jwt-locations': 'jwtLocations',
})
# The OpenAPI 2.0 field names of a backend, and the OpenAPI 3.x name of each.
_SNAKE_CASE_BACKEND_FIELDS = types.MappingProxyType({
'jwt_audience': 'jwtAudience',
'disable_auth': 'disableAuth',
'path_translation': 'pathTranslation',
})
# The fields that API Gateway accepts in each Google extension object. It
# reads each object strictly, so another field makes the API config fail.
_MANAGEMENT_FIELDS = frozenset({
'ai',
'apiName',
'api_name',
'backends',
'mcp',
'metrics',
'modelRouter',
'model_router',
'quota',
})
_BACKEND_FIELDS = frozenset(
{'address', 'deadline', 'protocol'}
| set(_SNAKE_CASE_BACKEND_FIELDS)
| set(_SNAKE_CASE_BACKEND_FIELDS.values())
)
_METRIC_FIELDS = frozenset({'displayName', 'display_name'})
_QUOTA_FIELDS = frozenset({'limits'})
_LIMIT_FIELDS = frozenset({'metric', 'values'})
_ENDPOINT_FIELDS = frozenset({'allowCors', 'allow_cors', 'target'})
_AUTH_FIELDS = frozenset({
'audiences',
'issuer',
'jwksUri',
'jwks_uri',
'jwtLocations',
'jwt_locations',
})
# The API key forms that API Gateway reads, as (location, lowercase name).
_API_KEY_FORMS = frozenset(
{('query', 'key'), ('query', 'api_key'), ('header', 'x-api-key')}
)
# Keys whose values are data, not schemas, such as examples. The walk over the
# spec skips them, and it also skips vendor extensions (x-*).
_DATA_KEYS = frozenset({'const', 'default', 'enum', 'example', 'examples'})
# Maps whose keys are names that the author chooses. The walk skips no key in
# them, because a property or a response can have the name "default".
_NAMED_MAPS = frozenset({'properties', 'responses', 'schemas'})
# The part of API Gateway that reports an error. The OpenAPI importer reads the
# spec. The control plane checks the API config after the importer.
_IMPORTER = 'importer'
_CONTROL_PLANE = 'control plane'
# The error is a setting that API Gateway accepts but ignores.
_IGNORED = 'ignored'
_NOTE = (
'This script checks only the API Gateway rules in this skill. It does not'
' check general OpenAPI validity. A PASS does not mean that API Gateway'
' accepts the spec. Run "gcloud api-gateway api-configs create" to'
' confirm.'
)
@dataclasses.dataclass
class _Validation:
"""The spec, the results, and the values that the checks share."""
spec: dict[str, Any]
errors: list[str] = dataclasses.field(default_factory=list)
# The part of API Gateway that reports each error, in the order of errors.
error_sources: list[str] = dataclasses.field(default_factory=list)
warnings: list[str] = dataclasses.field(default_factory=list)
base_path: str = ''
backends: dict[str, dict[str, Any]] = dataclasses.field(default_factory=dict)
path_translations: dict[str, str] = dataclasses.field(default_factory=dict)
metric_names: set[str] = dataclasses.field(default_factory=set)
limited_metrics: set[str] = dataclasses.field(default_factory=set)
charged_metrics: set[str] = dataclasses.field(default_factory=set)
schemes: dict[str, Any] = dataclasses.field(default_factory=dict)
api_key_schemes: set[str] = dataclasses.field(default_factory=set)
method_names: dict[str, str] = dataclasses.field(default_factory=dict)
root_backend: str | None = None
operation_backends: set[str] = dataclasses.field(default_factory=set)
router_backends: set[str] = dataclasses.field(default_factory=set)
query_operations: list[str] = dataclasses.field(default_factory=list)
operation_count: int = 0
def error(self, message: str, source: str = _IMPORTER) -> None:
"""Adds an error, and the part of API Gateway that reports it."""
self.errors.append(message)
self.error_sources.append(source)
def _load_spec(path: str) -> tuple[dict[str, Any], list[int]]:
"""Reads the spec file at path as JSON or YAML.
Args:
path: The path of the OpenAPI spec file.
Returns:
The parsed spec, and the line numbers of the YAML aliases to mappings.
Raises:
OSError: The file cannot be read.
RuntimeError: The file is not JSON, and PyYAML is not installed.
ValueError: The file is not a JSON or YAML mapping.
"""
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
try:
data = json.loads(content)
except json.JSONDecodeError:
pass
else:
if isinstance(data, dict):
return data, []
if not _HAS_YAML:
raise RuntimeError(
'PyYAML is required to parse YAML files. Install with: '
'pip install "PyYAML>=6.0,<7.0". A JSON spec does not need PyYAML.'
)
# The C loader is much faster on a large spec. Both loaders are safe.
loader_class = getattr(yaml, 'CSafeLoader', yaml.SafeLoader)
try:
data = yaml.load(content, Loader=loader_class)
alias_lines = _mapping_alias_lines(content, loader_class)
except yaml.YAMLError as exc:
raise ValueError(f'{path} is not valid JSON or YAML: {exc}') from exc
if not isinstance(data, dict):
raise ValueError(f'{path} did not parse as a YAML/JSON mapping.')
return data, alias_lines
def _mapping_alias_lines(content: str, loader_class: Any) -> list[int]:
"""Returns the line numbers of the YAML aliases to mappings in content."""
if '*' not in content:
return []
is_mapping: dict[str, bool] = {}
lines = []
for event in yaml.parse(content, Loader=loader_class):
if isinstance(event, yaml.AliasEvent):
if is_mapping.get(event.anchor):
lines.append(event.start_mark.line + 1)
elif isinstance(event, yaml.NodeEvent) and event.anchor:
is_mapping[event.anchor] = isinstance(event, yaml.MappingStartEvent)
return lines
def _escape_pointer(key: str) -> str:
"""Escapes a mapping key for use in a JSON pointer."""
return key.replace('~', '~0').replace('/', '~1')
def _is_data_key(key: str) -> bool:
"""Returns whether the value of key is data or a vendor extension."""
return key in _DATA_KEYS or key.startswith('x-')
def _walk(node: Any) -> Iterator[tuple[str, dict[Any, Any]]]:
"""Yields the JSON pointer and the value of each mapping in node.
The walk skips data values, such as examples, and vendor extensions. It
visits each mapping and list one time, so YAML aliases cannot make it slow,
and a recursive alias cannot make it loop.
Args:
node: A part of the OpenAPI spec.
Yields:
The JSON pointer and the value of each mapping.
"""
seen: set[int] = set()
stack: list[tuple[str, str, Any]] = [('', '', node)]
while stack:
location, container_key, current = stack.pop()
if not isinstance(current, (dict, list)) or id(current) in seen:
continue
seen.add(id(current))
if isinstance(current, list):
children = [(str(index), item) for index, item in enumerate(current)]
else:
yield location or '/', current
children = [
(str(key), value)
for key, value in current.items()
if container_key in _NAMED_MAPS or not _is_data_key(str(key))
]
for key, value in reversed(children):
stack.append((f'{location}/{_escape_pointer(key)}', key, value))
def _resolve(spec: dict[str, Any], obj: Any) -> Any:
"""Follows local '#/...' $ref pointers. Returns obj if it cannot resolve."""
seen: set[str] = set()
while isinstance(obj, dict) and isinstance(obj.get('$ref'), str):
reference = obj['$ref']
if not reference.startswith('#/') or reference in seen:
return obj
seen.add(reference)
target: Any = spec
for part in reference[2:].split('/'):
part = part.replace('~1', '/').replace('~0', '~')
if not isinstance(target, dict) or part not in target:
return obj
target = target[part]
obj = target
return obj
def _as_number(value: Any) -> float | None:
"""Returns value as a number, or None if it is not a number."""
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value)
except ValueError:
return None
return None
def _as_integer(value: Any) -> int | None:
"""Returns value as an integer, or None if it is not an integer.
API Gateway reads the protobuf JSON format. It also accepts an integral
number, such as 100.0, and a number in a string, such as "100".
Args:
value: A value from the spec.
Returns:
The integer, or None.
"""
if isinstance(value, int) and not isinstance(value, bool):
return value
number = _as_number(value)
if number is None or not number.is_integer():
return None
return int(number)
def _method_name(operation_id: str) -> str:
"""Returns the method name that API Gateway derives from an operationId.
API Gateway removes the characters other than letters, digits, and
underscores, and then capitalizes the first letter. For example, getItem,
GetItem, and get-Item all give GetItem.
Args:
operation_id: The operationId of an operation.
Returns:
The method name.
"""
cleaned = _SPECIAL_CHARACTERS_RE.sub('', operation_id)
return cleaned[:1].upper() + cleaned[1:]
def _unknown_fields(
config: dict[Any, Any], allowed: frozenset[str]
) -> list[str]:
"""Returns the sorted keys of config that are not in allowed."""
return sorted(str(key) for key in config if str(key) not in allowed)
def _unknown_fields_error(label: str, fields: list[str], hint: str) -> str:
"""Returns the error for fields that x-google-api-management rejects."""
return (
f'{label} has the fields {fields}, which OpenAPI 3.x does not support.'
' API Gateway then rejects the whole x-google-api-management block, and'
f' it also reports each backend as not defined. {hint}'
)
def _field(config: dict[str, Any], name: str, snake_name: str) -> Any:
"""Returns a field by its OpenAPI 3.x name or by its snake_case name."""
return config[name] if name in config else config.get(snake_name)
def _check_url(
check: _Validation, url: str, label: str, scheme_source: str
) -> bool:
"""Checks a backend address or a JWKS URI for the common mistakes.
The control plane rejects more addresses than the script checks.
Args:
check: The validation state.
url: The URL to check.
label: The location of the URL, for the messages.
scheme_source: The part of API Gateway that checks the URL scheme.
Returns:
Whether the URL passed the checks.
"""
if '{' in url or '}' in url:
check.error(
f'{label} "{url}" has a {{placeholder}}. Replace it with the real'
' hostname.',
_CONTROL_PLANE,
)
return False
parsed = parse.urlparse(url)
if parsed.scheme.lower() not in _URL_SCHEMES or not parsed.hostname:
check.error(
f'{label} must be an HTTP or HTTPS URL with a hostname, got "{url}".',
scheme_source,
)
return False
host = parsed.hostname.rstrip('.')
try:
ipaddress.ip_address(host)
except ValueError:
pass
else:
check.error(
f'{label} "{url}" uses an IP address. API Gateway routes only to a'
' hostname.',
_CONTROL_PLANE,
)
return False
if '.' not in host:
check.error(
f'{label} "{url}" has a hostname with only one part, such as'
' localhost. Use a fully qualified hostname.',
_CONTROL_PLANE,
)
return False
return True
def _requirement_types(
check: _Validation, requirement: dict[Any, Any], where: str
) -> list[Any]:
"""Returns the scheme types of one security requirement.
Args:
check: The validation state. It gets an error for each undefined scheme.
requirement: One requirement object of a "security" list.
where: The location of the "security" list, for the error messages.
Returns:
The type of each defined scheme in the requirement.
"""
scheme_types = []
for raw_name in requirement:
scheme = check.schemes.get(str(raw_name))
if isinstance(scheme, dict):
scheme_types.append(scheme.get('type'))
else:
check.error(
f'The "security" list of {where} names the security scheme'
f' "{raw_name}", which components.securitySchemes does not define.'
' API Gateway rejects the API config.'
)
return scheme_types
def _check_security_list(check: _Validation, security: Any, where: str) -> None:
"""Checks a security list against the API Gateway rules.
Args:
check: The validation state.
security: The value of a "security" list.
where: The location of the "security" list, for the error messages.
"""
if not isinstance(security, list):
return
requirements = [
_requirement_types(check, requirement, where)
for requirement in security
if isinstance(requirement, dict) and requirement
]
if any(scheme_types.count('oauth2') > 1 for scheme_types in requirements):
check.error(
f'The "security" list of {where} puts two JWT (oauth2) schemes in one'
' requirement object (AND). API Gateway rejects it. Put each JWT'
' scheme in its own requirement object (OR).'
)
has_empty = any(
isinstance(requirement, dict) and not requirement
for requirement in security
)
if has_empty:
if any('oauth2' in scheme_types for scheme_types in requirements):
check.error(
f'The "security" list of {where} has an empty requirement ({{}})'
' that makes a JWT (oauth2) scheme optional. API Gateway supports'
' optional security only for API keys.'
)
return
with_key = ['apiKey' in scheme_types for scheme_types in requirements]
if any(with_key) and not all(with_key):
check.error(
f'The "security" list of {where} has alternative (OR) requirements,'
' and only some of them have an API key scheme. API Gateway supports'
' an OR only if every alternative has an API key scheme, or none of'
' them has one.'
)
def _requires_api_key(security: Any, api_key_schemes: set[str]) -> bool:
"""Returns whether every alternative of a security list has an API key."""
if not isinstance(security, list) or not security:
return False
return all(
isinstance(requirement, dict)
and any(str(name) in api_key_schemes for name in requirement)
for requirement in security
)
def _path_variables(path: str) -> list[str]:
"""Returns the variables of a path template, such as itemId or name=**."""
return [match.group(1) for match in _PATH_VARIABLE_RE.finditer(path)]
def _check_path_template(check: _Validation, path: str) -> None:
"""Checks that each path variable is a whole segment in the 3.x syntax."""
segments = path.split('/')
segments[-1] = _CUSTOM_VERB_RE.sub('', segments[-1])
for segment in segments:
if ('{' in segment or '}' in segment) and not _PATH_VARIABLE_RE.fullmatch(
segment
):
check.error(
f'Path "{path}" has the segment "{segment}". A path variable must'
' be a whole segment, such as /items/{itemId}. API Gateway rejects'
' a partial segment, such as /items/prefix_{id}.'
)
for variable in _path_variables(path):
if '=' in variable:
check.error(
f'Path "{path}" uses "{{{variable}}}". OpenAPI 3.x does not support'
' the {var=*} or {var=**} syntax. Write {var}, and for a double'
' wildcard, set x-google-parameter: {pattern: "**"} on the'
' parameter.'
)
def _check_structure(check: _Validation) -> None:
"""Checks that the main parts of the spec have the right JSON types.
A part with the wrong type gets one error, and the other checks skip it.
Args:
check: The validation state.
"""
spec = check.spec
parts = (
('paths', spec.get('paths'), dict),
('servers', spec.get('servers'), list),
('components', spec.get('components'), dict),
)
for name, value, expected in parts:
if name in spec and not isinstance(value, expected):
kind = 'a mapping' if expected is dict else 'a list'
check.error(f'"{name}" must be {kind}. API Gateway rejects the spec.')
components = spec.get('components')
if isinstance(components, dict) and 'securitySchemes' in components:
if not isinstance(components['securitySchemes'], dict):
check.error(
'"components.securitySchemes" must be a map from each scheme name'
' to the scheme. API Gateway rejects the spec.'
)
def _check_version_and_root_extensions(check: _Validation) -> None:
"""Checks the openapi version and the extensions at the root."""
version = str(check.spec.get('openapi', ''))
if not _OAS3_RE.fullmatch(version):
check.error(
'Expected openapi version 3.0.x or 3.1.x (for example, 3.0.4 or'
f' 3.1.0), got "{version}".'
)
for extension, change in _V2_ROOT_EXTENSIONS.items():
if extension in check.spec:
check.error(
f'Found the OpenAPI 2.0 extension "{extension}" at the root. API'
f' Gateway rejects it in OpenAPI 3.x. {change}'
)
for extension, change in _V2_BACKEND_EXTENSIONS.items():
if extension in check.spec:
check.warnings.append(
f'Found the OpenAPI 2.0 extension "{extension}" at the root. API'
f' Gateway ignores it there in OpenAPI 3.x. {change}'
)
if 'x-google-quota' in check.spec:
check.error(
'Found x-google-quota at the root. API Gateway accepts it in OpenAPI'
' 3.x, but ignores it, so no quota applies. Set x-google-quota on'
' each operation.',
_IGNORED,
)
def _check_schemas_and_refs(check: _Validation, alias_lines: list[int]) -> None:
"""Checks schema type lists, $ref values, and YAML aliases."""
for location, node in _walk(check.spec):
node_type = node.get('type')
if isinstance(node_type, list) and len(node_type) > 1:
check.error(
f'The schema at {location} has more than one type'
f' ({json.dumps(node_type)}). API Gateway rejects a type list. Give'
' the schema one type.'
)
reference = node.get('$ref')
if isinstance(reference, str):
_check_ref(check, location, reference)
if alias_lines:
lines = ', '.join(str(line) for line in alias_lines[:_MAX_ALIAS_LINES])
more = ', and more' if len(alias_lines) > _MAX_ALIAS_LINES else ''
check.error(
f'Found {len(alias_lines)} YAML alias(es) to a mapping, at lines'
f' {lines}{more}. API Gateway rejects an alias to a mapping with'
' "string found, object expected", and the error does not name the'
' alias. Use a $ref, or copy the mapping. If a program writes the'
' YAML, turn off aliases, for example with a PyYAML Dumper whose'
' ignore_aliases() returns True.'
)
def _check_ref(check: _Validation, location: str, reference: str) -> None:
"""Checks one $ref value."""
if reference.startswith('#/definitions/'):
check.error(
f'The $ref "{reference}" at {location} uses the OpenAPI 2.0 path'
' #/definitions/. Move the schema to components.schemas, and use'
' #/components/schemas/{name}.'
)
return
if reference.startswith('#'):
return
parsed = parse.urlparse(reference)
if parsed.scheme or parsed.netloc:
check.error(
f'The $ref "{reference}" at {location} points to a URL. API Gateway'
' accepts only local references. Copy the schema into'
' components.schemas.'
)
else:
check.warnings.append(
f'The $ref "{reference}" at {location} points to another file.'
' Prefer a local #/components/schemas reference. If you keep it,'
' upload that file in the same --openapi-spec list.'
)
def _check_servers(check: _Validation) -> None:
"""Checks the servers list, and records the base path."""
servers = check.spec.get('servers')
if not isinstance(servers, list) or not servers:
return
if not all(isinstance(server, dict) for server in servers):
check.error(
'Each "servers" entry must be a mapping with a "url". API Gateway'
' rejects the spec.'
)
return
endpoint_servers = [
server for server in servers if 'x-google-endpoint' in server
]
if not endpoint_servers:
check.warnings.append(
'No servers entry has x-google-endpoint, so API Gateway ignores'
' "servers" and applies no base path. Add "x-google-endpoint: {}" to'
' the server whose URL path is the base path.'
)
return
if len(endpoint_servers) > 1:
check.error(
f'Found {len(endpoint_servers)} servers with "x-google-endpoint". API'
' Gateway permits at most one.'
)
server = endpoint_servers[0]
if 'url' in server:
check.base_path = _server_base_path(check, server['url'])
endpoint = server.get('x-google-endpoint')
if endpoint is None:
return
if not isinstance(endpoint, dict):
check.error(
'x-google-endpoint must be a mapping, such as {} or {allowCors:'
' true}. API Gateway rejects another value.'
)
return
unknown = _unknown_fields(endpoint, _ENDPOINT_FIELDS)
if unknown:
check.error(
f'x-google-endpoint has the fields {unknown}. API Gateway rejects the'
' API config. In OpenAPI 3.x, x-google-endpoint has only allowCors'
' and target. Remove the other fields, such as the OpenAPI 2.0'
' "name".'
)
if _field(endpoint, 'allowCors', 'allow_cors'):
check.warnings.append(
'x-google-endpoint sets allowCors: true. API Gateway then passes CORS'
' requests, including OPTIONS preflight requests, to the backend. It'
' does not add CORS headers, so the backend must answer them.'
)
def _server_base_path(check: _Validation, url: Any) -> str:
"""Checks the URL of the server with x-google-endpoint.
Args:
check: The validation state.
url: The value of the "url" field of the server.
Returns:
The base path that the URL gives, without a trailing "/".
"""
if not isinstance(url, str):
check.error(
'The server with x-google-endpoint has a null url. Set it to a base'
' path, such as /v1, or to an HTTPS URL.'
)
return ''
if '{' in url or '}' in url or any(char.isspace() for char in url):
check.error(
f'The server url "{url}" has a {{variable}} or a space. API Gateway'
' does not support server variables. Replace each {placeholder} with'
' its value.'
)
return ''
if not url or url.startswith('/'):
return url.rstrip('/')
parsed = parse.urlparse(url)
if parsed.scheme.lower() not in _URL_SCHEMES or not parsed.hostname:
check.error(
f'The server url "{url}" must be an HTTPS URL or a relative path'
' that starts with "/", such as /v1.'
)
return ''
try:
port = parsed.port
except ValueError:
port = -1
if port is not None:
check.error(
f'The server url "{url}" has a custom port. API Gateway does not'
' support custom ports.'
)
return ''
return parsed.path.rstrip('/')
def _check_management(check: _Validation) -> None:
"""Checks the root x-google-api-management extension."""
if 'x-google-api-management' not in check.spec:
check.error(
'Missing the required root "x-google-api-management" mapping with'
' "backends".',
_CONTROL_PLANE,
)
return
management = check.spec['x-google-api-management']
if not isinstance(management, dict):
check.error('x-google-api-management must be a mapping.')
return
unknown = _unknown_fields(management, _MANAGEMENT_FIELDS)
if unknown:
check.error(
_unknown_fields_error(
'x-google-api-management',
unknown,
'Use backends, metrics, quota, apiName, mcp, ai, or modelRouter.',
)
)
_check_backends(check, management.get('backends'))
_check_metrics(check, management.get('metrics'))
_check_limits(check, management.get('quota'))
check.router_backends = _router_backends(management.get('ai'))
if 'mcp' in management:
check.warnings.append(
'x-google-api-management.mcp enables MCP tools. MCP has more rules.'
' Check them with the api-gateway-mcp-server skill.'
)
def _router_backends(ai: Any) -> set[str]:
"""Returns the backend names that the model routers in ai use.
Args:
ai: The value of x-google-api-management.ai.
Returns:
The value of each "backend" field in ai.
"""
names: set[str] = set()
seen: set[int] = set()
stack = [ai]
while stack:
node = stack.pop()
if not isinstance(node, (dict, list)) or id(node) in seen:
continue
seen.add(id(node))
if isinstance(node, list):
stack.extend(node)
continue
if isinstance(node.get('backend'), str):
names.add(node['backend'])
stack.extend(node.values())
return names
def _check_backends(check: _Validation, backends: Any) -> None:
"""Checks x-google-api-management.backends, and records the valid ones."""
if not backends:
check.error(
'"x-google-api-management.backends" must define at least one named'
' backend.',
_CONTROL_PLANE,
)
return
if not isinstance(backends, dict):
check.error(
'"x-google-api-management.backends" must be a map from each backend'
' name to its settings, not a list.'
)
return
for raw_name, config in backends.items():
name = str(raw_name)
if not isinstance(config, dict):
check.error(f'Backend "{name}" must be a mapping.')
continue
check.backends[name] = config
_check_backend_fields(check, name, config)
_check_backend_address(check, name, config)
_check_backend_settings(check, name, config)
def _check_backend_fields(
check: _Validation, name: str, config: dict[str, Any]
) -> None:
"""Checks the field names of one backend."""
unknown = _unknown_fields(config, _BACKEND_FIELDS)
if unknown:
check.error(
_unknown_fields_error(
f'Backend "{name}"',
unknown,
'A backend has only address, jwtAudience, disableAuth,'
' pathTranslation, deadline, and protocol.',
)
)
for snake_field, camel_field in _SNAKE_CASE_BACKEND_FIELDS.items():
if snake_field in config:
check.warnings.append(
f'Backend "{name}" uses the OpenAPI 2.0 field name'
f' "{snake_field}". Use "{camel_field}", as the OpenAPI 3.x'
' documentation shows.'
)
if (
_field(config, 'jwtAudience', 'jwt_audience') is not None
and _field(config, 'disableAuth', 'disable_auth') is not None
):
check.error(
f'Backend "{name}" sets both jwtAudience and disableAuth. API Gateway'
' rejects the API config. Set only one of them.'
)
def _check_backend_address(
check: _Validation, name: str, config: dict[str, Any]
) -> None:
"""Checks the address of one backend, and the settings that use it."""
address = config.get('address')
if not isinstance(address, str) or not address:
check.error(
f'Backend "{name}" is missing a required "address".', _CONTROL_PLANE
)
return
parsed = parse.urlparse(address)
protocol = str(config.get('protocol', '')).lower()
if protocol == 'h2' and parsed.scheme.lower() == 'http':
check.error(
f'Backend "{name}" sets protocol "h2" with an http:// address. API'
' Gateway allows "h2" only for https:// backends.'
)
if not _check_url(
check, address, f'The address of backend "{name}"', _IMPORTER
):
return
hostname = parsed.hostname or ''
if (
hostname.endswith('.run.app')
and parsed.path.strip('/')
and _field(config, 'jwtAudience', 'jwt_audience') is None
and not _field(config, 'disableAuth', 'disable_auth')
):
check.warnings.append(
f'Backend "{name}" has a path in its Cloud Run address and no'
' jwtAudience. The default audience is the full address, but Cloud'
' Run expects its service URL. Set jwtAudience to'
f' "{parsed.scheme}://{hostname}".'
)
def _check_backend_settings(
check: _Validation, name: str, config: dict[str, Any]
) -> None:
"""Checks the pathTranslation, protocol, and deadline of one backend."""
path_translation = _field(config, 'pathTranslation', 'path_translation')
if (
path_translation is not None
and path_translation not in _PATH_TRANSLATIONS
):
check.error(
f'Backend "{name}" has pathTranslation "{path_translation}". Use'
' APPEND_PATH_TO_ADDRESS or CONSTANT_ADDRESS.'
)
protocol = config.get('protocol')
if protocol is not None and str(protocol).lower() not in _PROTOCOLS:
check.error(
f'Backend "{name}" has protocol "{protocol}". Use "http/1.1" or "h2".'
)
if 'deadline' not in config:
return
deadline = _as_number(config['deadline'])
if deadline is None:
check.error(f'Backend "{name}" deadline must be a number.')
elif deadline > _MAX_DEADLINE_SECONDS:
check.error(
f'Backend "{name}" deadline is {deadline:g} seconds. The maximum is'
f' {_MAX_DEADLINE_SECONDS}.',
_CONTROL_PLANE,
)
elif deadline > _MAX_NON_STREAMING_DEADLINE_SECONDS:
check.warnings.append(
f'Backend "{name}" deadline is {deadline:g} seconds. Some gateways'
f' reject a value above {_MAX_NON_STREAMING_DEADLINE_SECONDS} when you'
' create or update the gateway. A streaming gateway accepts up to'
f' {_MAX_DEADLINE_SECONDS}.'
)
def _check_metrics(check: _Validation, metrics: Any) -> None:
"""Checks x-google-api-management.metrics, and records the metric names."""
if metrics is None:
return
if not isinstance(metrics, dict):
check.error(
'"x-google-api-management.metrics" must be a map from each metric'
' name to its settings, such as {read-requests: {displayName: "Read'
' requests"}}, not a list (the OpenAPI 2.0 form).'
)
return
for raw_name, config in metrics.items():
name = str(raw_name)
check.metric_names.add(name)
if config is None:
continue
if not isinstance(config, dict):
check.error(f'Metric "{name}" must be a mapping.')
continue
unknown = _unknown_fields(config, _METRIC_FIELDS)
if unknown:
check.error(
_unknown_fields_error(
f'Metric "{name}"',
unknown,
'A metric has only displayName. The map key is the metric'
' name, and API Gateway sets the value type and the kind.',
)
)
def _check_limits(check: _Validation, quota: Any) -> None:
"""Checks x-google-api-management.quota.limits."""
if quota is None:
return
if not isinstance(quota, dict):
check.error('"x-google-api-management.quota" must be a mapping.')
return
unknown = _unknown_fields(quota, _QUOTA_FIELDS)
if unknown:
check.error(
_unknown_fields_error(
'x-google-api-management.quota', unknown, 'Use only "limits".'
)
)
limits = quota.get('limits')
if limits is None:
return
if not isinstance(limits, dict):
check.error(
'"x-google-api-management.quota.limits" must be a map from each limit'
' name to {metric, values}, not a list (the OpenAPI 2.0 form).'
)
return
for raw_name, limit in limits.items():
_check_limit(check, str(raw_name), limit)
def _check_limit(check: _Validation, name: str, limit: Any) -> None:
"""Checks one quota limit, and records the metric that it limits."""
if not isinstance(limit, dict):
check.error(f'Quota limit "{name}" must be a mapping.')
return
unknown = _unknown_fields(limit, _LIMIT_FIELDS)
if unknown:
check.error(
_unknown_fields_error(
f'Quota limit "{name}"',
unknown,
'A quota limit has only metric and values. API Gateway uses the'
' unit 1/min/{project}.',
)
)
metric = str(limit.get('metric'))
if metric in check.metric_names:
check.limited_metrics.add(metric)
else:
check.error(
f'Quota limit "{name}" names the metric "{metric}", which'
' x-google-api-management.metrics does not define.'
)
values = limit.get('values')
if isinstance(values, dict):
check.error(
f'Quota limit "{name}" sets values as a map {values}. In OpenAPI 3.x,'
' values is a plain integer, such as "values: 100".'
)
elif _as_integer(values) is None:
check.error(f'Quota limit "{name}" must set values to an integer.')
def _check_security(check: _Validation) -> None:
"""Checks the security schemes and the root security list."""
components = check.spec.get('components')
schemes = (
components.get('securitySchemes')
if isinstance(components, dict)
else None
)
check.schemes = schemes if isinstance(schemes, dict) else {}
for raw_name, scheme in check.schemes.items():
name = str(raw_name)
if not isinstance(scheme, dict):
check.error(f'Security scheme "{name}" must be a mapping.')
continue
for old_extension, new_field in _V2_AUTH_EXTENSIONS.items():
if old_extension in scheme:
check.error(
f'Security scheme "{name}" uses the OpenAPI 2.0 extension'
f' "{old_extension}". API Gateway rejects it in OpenAPI 3.x. Move'
f' the value to "x-google-auth.{new_field}".'
)
if scheme.get('type') == 'apiKey':
_check_api_key_scheme(check, name, scheme)
elif scheme.get('type') == 'oauth2':
_check_oauth_scheme(check, name, scheme)
_check_security_list(check, check.spec.get('security'), 'the root')
def _check_api_key_scheme(
check: _Validation, name: str, scheme: dict[str, Any]
) -> None:
"""Records an API key scheme that API Gateway reads, or warns."""
location = str(scheme.get('in', ''))
key_name = str(scheme.get('name', ''))
if (location.lower(), key_name.lower()) in _API_KEY_FORMS:
check.api_key_schemes.add(name)
return
check.warnings.append(
f'API key scheme "{name}" uses the name "{key_name}" in "{location}".'
' API Gateway ignores this scheme, so an operation that requires only'
' this scheme accepts calls without a key. Use x-api-key in a header,'
' or key or api_key in the query.'
)
def _check_oauth_scheme(
check: _Validation, name: str, scheme: dict[str, Any]
) -> None:
"""Checks the scopes and the x-google-auth extension of a JWT scheme."""
flows = scheme.get('flows')
if isinstance(flows, dict) and any(
isinstance(flow, dict) and flow.get('scopes') for flow in flows.values()
):
check.warnings.append(
f'Security scheme "{name}" defines OAuth scopes. API Gateway does'
' not check scopes. Check them in the backend if you need them.'
)
auth = scheme.get('x-google-auth')
if auth is None:
if not any(old in scheme for old in _V2_AUTH_EXTENSIONS):
check.error(
f'Security scheme "{name}" is oauth2 without x-google-auth. API'
' Gateway adds a JWT provider for every oauth2 scheme, also for a'
' scheme that no operation uses, and it rejects a provider without'
' a JWKS URI. Add x-google-auth with issuer, jwksUri, and'
' audiences, or remove the scheme.',
_CONTROL_PLANE,
)
return
label = f'x-google-auth of security scheme "{name}"'
if not isinstance(auth, dict):
check.error(f'{label} must be a mapping.')
return
unknown = _unknown_fields(auth, _AUTH_FIELDS)
if unknown:
check.error(
f'{label} has the fields {unknown}. API Gateway rejects the API'
' config. x-google-auth has only issuer, jwksUri, audiences, and'
' jwtLocations.'
)
audiences = auth.get('audiences')
if audiences is not None and not isinstance(audiences, list):
check.error(
f'{label}: audiences must be a list, not a comma-separated string'
' (the OpenAPI 2.0 form).'
)
jwks_uri = _field(auth, 'jwksUri', 'jwks_uri')
if not jwks_uri:
check.error(
f'{label} has no jwksUri. API Gateway rejects a JWT provider without'
' a JWKS URI, also for a scheme that no operation uses. Set jwksUri'
' to the URL of the public keys of the issuer.',
_CONTROL_PLANE,
)
elif isinstance(jwks_uri, str):
_check_url(check, jwks_uri, f'The jwksUri of {label}', _CONTROL_PLANE)
def _check_root_backend(check: _Validation) -> None:
"""Checks the root x-google-backend, and records the backend name."""
root_backend = check.spec.get('x-google-backend')
if root_backend is None:
return
if isinstance(root_backend, dict):
check.error(
'The root "x-google-backend" is an inline object (the OpenAPI 2.0'
' form). Define the backend under x-google-api-management.backends,'
' and set x-google-backend to its name.'
)
return
check.root_backend = str(root_backend)
if check.root_backend not in check.backends:
check.error(
f'The root x-google-backend "{root_backend}" is not defined in'
' x-google-api-management.backends.'
)
def _check_paths(check: _Validation) -> None:
"""Checks every path item and operation in the spec."""
paths = check.spec.get('paths')
if not isinstance(paths, dict):
return
for raw_path, path_item in paths.items():
path = str(raw_path)
_check_path_template(check, path)
if not isinstance(path_item, dict):
check.error(f'Path "{path}" must map to a path item object.')
continue
for extension in ('x-google-backend', *_V2_BACKEND_EXTENSIONS):
if extension in path_item:
check.error(
f'Path "{path}" sets {extension} at the path level. API Gateway'
' rejects it. Set x-google-backend at the root or on each'
' operation.'
)
if 'x-google-quota' in path_item:
check.error(
f'Path "{path}" sets x-google-quota at the path level. API Gateway'
' accepts it, but ignores it, so no quota applies. Set it on each'
' operation.',
_IGNORED,
)
for raw_method, operation in path_item.items():
method = str(raw_method).lower()
if method not in _HTTP_METHODS:
continue
if not isinstance(operation, dict):
check.error(f'Operation {method.upper()} {path} must be a mapping.')
continue
_check_operation(
check, method, path, operation, path_item.get('parameters')
)
def _check_operation(
check: _Validation,
method: str,
path: str,
operation: dict[str, Any],
path_parameters: Any,
) -> None:
"""Checks one operation of a path item.
Args:
check: The validation state.
method: The lowercase HTTP method of the operation.
path: The path key of the operation.
operation: The operation object.
path_parameters: The "parameters" list of the path item.
"""
check.operation_count += 1
label = f'{method.upper()} {path}'
_check_operation_id(check, label, operation.get('operationId'))
for extension, change in _V2_BACKEND_EXTENSIONS.items():
if extension in operation:
check.error(
f'Operation {label} uses the OpenAPI 2.0 extension "{extension}".'
f' API Gateway rejects it in OpenAPI 3.x. {change}'
)
if 'x-security' in operation:
check.error(
f'Operation {label} uses the OpenAPI 2.0 extension "x-security". API'
' Gateway rejects it in OpenAPI 3.x. Use the OpenAPI "security"'
' field.'
)
if 'security' in operation:
_check_security_list(check, operation['security'], f'operation {label}')
_check_operation_quota(check, label, operation)
# A model router operation has no x-google-backend.
if 'x-google-model-router' not in operation:
_check_operation_backend(check, label, path, operation)
_check_parameters(
check,
label,
path,
_operation_parameters(check, path_parameters, operation),
)
def _check_operation_id(check: _Validation, label: str, raw_id: Any) -> None:
"""Checks that an operationId is present and unique."""
operation_id = str(raw_id or '').strip()
if not operation_id:
check.error(
f'Operation {label} has no operationId. API Gateway rejects every'
' operation without one.'
)
return
method_name = _method_name(operation_id)
other = check.method_names.get(method_name)
if other is None:
check.method_names[method_name] = operation_id
elif other == operation_id:
check.error(f'The operationId "{operation_id}" is not unique.')
else:
check.error(
f'The operationIds "{other}" and "{operation_id}" both give the'
f' method name "{method_name}". API Gateway removes the characters'
' other than letters, digits, and underscores, and capitalizes the'
' first letter. Make the operationIds differ after that change.'
)
def _check_operation_quota(
check: _Validation, label: str, operation: dict[str, Any]
) -> None:
"""Checks the x-google-quota extension of one operation."""
quota = operation.get('x-google-quota')
if quota is None:
return
if not isinstance(quota, dict):
check.error(
f'x-google-quota on {label} must be a map from each metric name to'
' its cost.'
)
return
if 'metricCosts' in quota:
check.error(
f'x-google-quota on {label} uses the OpenAPI 2.0 "metricCosts"'
' wrapper. Remove the wrapper, such as "x-google-quota:'
' {read-requests: 1}".'
)
return
for raw_metric, cost in quota.items():
metric = str(raw_metric)
check.charged_metrics.add(metric)
if metric not in check.metric_names:
check.error(
f'x-google-quota on {label} names the metric "{metric}", which'
' x-google-api-management.metrics does not define.'
)
integer_cost = _as_integer(cost)
if integer_cost is None or integer_cost < 0:
check.error(
f'x-google-quota on {label} gives the metric "{metric}" the cost'
f' {cost!r}. Use a non-negative integer.'
)
security = operation.get('security', check.spec.get('security'))
if not _requires_api_key(security, check.api_key_schemes):
check.warnings.append(
f'Operation {label} has x-google-quota, but it does not require an'
' API key. API Gateway uses the API key to identify the consumer'
' project that the quota counts. Require an API key in every'
' security alternative of the operation.'
)
def _check_operation_backend(
check: _Validation, label: str, path: str, operation: dict[str, Any]
) -> None:
"""Checks the backend of one operation, and records its path translation."""
operation_backend = operation.get('x-google-backend')
if isinstance(operation_backend, dict):
check.error(
f'Operation {label} uses an inline "x-google-backend" object (the'
' OpenAPI 2.0 form). Set x-google-backend to the name of a backend in'
' x-google-api-management.backends.'
)
return
if operation_backend is not None:
backend_name = str(operation_backend)
default_translation = 'CONSTANT_ADDRESS'
check.operation_backends.add(backend_name)
if backend_name not in check.backends:
check.error(
f'Operation {label} references the backend "{backend_name}", which'
' x-google-api-management.backends does not define.'
)
elif 'x-google-backend' in check.spec:
backend_name = check.root_backend
default_translation = 'APPEND_PATH_TO_ADDRESS'
else:
check.error(
f'Operation {label} has no x-google-backend, and the spec has no root'
' x-google-backend. API Gateway rejects an operation that has no'
' backend configured at the operation or API level.',
_CONTROL_PLANE,
)
return
config = check.backends.get(backend_name or '')
if config is None:
return
translation = (
_field(config, 'pathTranslation', 'path_translation')
or default_translation
)
if translation == 'CONSTANT_ADDRESS' and _path_variables(path):
check.query_operations.append(label)
def _operation_parameters(
check: _Validation, path_parameters: Any, operation: dict[str, Any]
) -> list[dict[str, Any]]:
"""Returns the parameters of an operation, with path-level parameters.
An operation parameter replaces a path-level parameter that has the same
name and location.
Args:
check: The validation state.
path_parameters: The "parameters" list of the path item.
operation: The operation object.
Returns:
The resolved parameter objects.
"""
merged: dict[tuple[str, str], dict[str, Any]] = {}
for parameter_list in (path_parameters, operation.get('parameters')):
if not isinstance(parameter_list, list):
continue
for raw_parameter in parameter_list:
parameter = _resolve(check.spec, raw_parameter)
if isinstance(parameter, dict):
key = (str(parameter.get('name', '')), str(parameter.get('in', '')))
merged[key] = parameter
return list(merged.values())
def _check_parameters(
check: _Validation,
label: str,
path: str,
parameters: list[dict[str, Any]],
) -> None:
"""Checks the parameters of one operation.
Args:
check: The validation state.
label: The method and path of the operation, for the messages.
path: The path key of the operation.
parameters: The resolved parameters of the operation.
"""
path_names = {variable.split('=')[0] for variable in _path_variables(path)}
declared = set()
for parameter in parameters:
name = str(parameter.get('name', ''))
location = str(parameter.get('in', ''))
if location in ('body', 'formData'):
check.error(
f'Parameter "{name}" of {label} has "in: {location}". OpenAPI 3.x'
' has no body or formData parameters. Move the body to'
' requestBody.'
)
continue
old_fields = sorted(_V2_PARAMETER_FIELDS & set(parameter))
if old_fields:
check.error(
f'Parameter "{name}" of {label} has the OpenAPI 2.0 fields'
f' {old_fields}. Move type, format, and items into the parameter'
' "schema", and replace collectionFormat with "style" and'
' "explode".'
)
if location != 'path':
continue
declared.add(name)
_check_path_parameter(check, label, path, name, parameter, path_names)
for variable in _path_variables(path):
if '=' not in variable and variable not in declared:
check.error(
f'The path of {label} has {{{variable}}}, but the operation has no'
f' path parameter "{variable}". API Gateway rejects it. Add a'
f' parameter with name: {variable}, in: path, and required: true.'
)
def _check_path_parameter(
check: _Validation,
label: str,
path: str,
name: str,
parameter: dict[str, Any],
path_names: set[str],
) -> None:
"""Checks one path parameter against the path template."""
if name not in path_names:
check.error(
f'Parameter "{name}" of {label} is a path parameter, but the path has'
f' no {{{name}}}. API Gateway rejects it. Add {{{name}}} to the path,'
' or remove the parameter.'
)
required = parameter.get('required')
if not isinstance(required, bool) or not required:
check.error(
f'Path parameter "{name}" of {label} must set "required: true".'
' OpenAPI 3.x requires it.'
)
extension = parameter.get('x-google-parameter')
if extension is None:
return
if not isinstance(extension, dict):
check.error(
f'x-google-parameter of parameter "{name}" of {label} must be a'
' mapping, such as {pattern: "**"}.'
)
return
pattern = extension.get('pattern')
if not pattern:
return
if pattern != '**':
check.error(
f'Parameter "{name}" of {label} sets x-google-parameter.pattern to'
f' {pattern!r}. The only allowed value is "**".'
)
elif not path.endswith(f'{{{name}}}'):
check.error(
f'Parameter "{name}" of {label} uses x-google-parameter: {{pattern:'
' "**"}, so it must be the last segment of the path.'
)
def _check_charged_metrics(check: _Validation) -> None:
"""Checks that each metric that an operation charges has a quota limit."""
charged = check.charged_metrics & check.metric_names
for metric in sorted(charged - check.limited_metrics):
check.error(
f'x-google-quota charges the metric "{metric}", but no quota limit'
' uses it. API Gateway rejects the API config. Add a limit in'
' x-google-api-management.quota.limits.'
)
def _default_path_translation(
name: str, at_root: bool, on_operation: bool
) -> tuple[str, str]:
"""Describes the default path translation of a backend.
Args:
name: The backend name.
at_root: Whether the root x-google-backend uses the backend.
on_operation: Whether an operation-level x-google-backend uses it.
Returns:
The path translation for the report, and a warning.
"""
if at_root and on_operation:
return (
(
'APPEND_PATH_TO_ADDRESS at the root, CONSTANT_ADDRESS on operations'
' (defaults)'
),
(
f'Backend "{name}" has no pathTranslation, and both the root and an'
' operation-level x-google-backend use it. It uses'
' APPEND_PATH_TO_ADDRESS for the root and CONSTANT_ADDRESS for the'
' operation. Set pathTranslation, or define two backends.'
),
)
if on_operation:
return (
'CONSTANT_ADDRESS (default for an operation-level x-google-backend)',
(
f'Backend "{name}" has no pathTranslation, and an operation-level'
' x-google-backend uses it. There, the default is'
' CONSTANT_ADDRESS: API Gateway sends every request to the address'
' as it is, and sends path parameters as query parameters. Set'
' pathTranslation on the backend.'
),
)
if at_root:
return (
'APPEND_PATH_TO_ADDRESS (default for the root x-google-backend)',
(
f'Backend "{name}" has no pathTranslation. At the root, the default'
' is APPEND_PATH_TO_ADDRESS. Set it explicitly, because the default'
' changes to CONSTANT_ADDRESS if an operation uses this backend.'
),
)
return (
'not set (not used)',
(
f'Backend "{name}" is not used by any x-google-backend. Remove it, or'
' set pathTranslation on it before you use it.'
),
)
def _check_backend_usage(check: _Validation) -> None:
"""Records the path translation of each backend, and warns about defaults."""
for name, config in check.backends.items():
explicit = _field(config, 'pathTranslation', 'path_translation')
if explicit is not None:
check.path_translations[name] = str(explicit)
elif name in check.router_backends:
check.path_translations[name] = 'not set (model router backend)'
else:
translation, warning = _default_path_translation(
name,
at_root=name == check.root_backend,
on_operation=name in check.operation_backends,
)
check.path_translations[name] = translation
check.warnings.append(warning)
def _swagger_error(spec: dict[str, Any]) -> str:
"""Returns the error for an OpenAPI 2.0 spec, with its Google extensions."""
extensions = sorted(
str(key)
for key in spec
if str(key).startswith('x-google-') or str(key) == 'x-security'
)
message = (
'This is an OpenAPI 2.0 (swagger) spec. Convert it to OpenAPI 3.0.x or'
' 3.1.x first, then run this validator on the converted spec.'
)
if extensions:
message += (
f' Move these root extensions to their OpenAPI 3.x form: {extensions}.'
)
return message
def _validate(spec: dict[str, Any], alias_lines: list[int]) -> _Validation:
"""Runs every check on a parsed spec, and returns the validation state."""
check = _Validation(spec=spec)
if 'swagger' in spec:
check.error(_swagger_error(spec))
return check
_check_structure(check)
_check_version_and_root_extensions(check)
_check_schemas_and_refs(check, alias_lines)
_check_servers(check)
_check_management(check)
_check_security(check)
_check_root_backend(check)
_check_paths(check)
_check_charged_metrics(check)
_check_backend_usage(check)
return check
def validate_spec(
spec: dict[str, Any], alias_lines: list[int] | None = None
) -> tuple[list[str], list[str], dict[str, Any]]:
"""Validates an OpenAPI spec against the API Gateway rules in this skill.
Args:
spec: The parsed OpenAPI spec.
alias_lines: The line numbers of the YAML aliases to mappings in the file.
Returns:
The errors, the warnings, and a summary of the backends and operations.
"""
check = _validate(spec, alias_lines or [])
summary = {
'base_path': check.base_path,
'backends': check.path_translations,
'path_parameters_as_query': check.query_operations,
'operations': check.operation_count,
}
return check.errors, check.warnings, summary
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=(
'Check an OpenAPI 3.x spec for the Google Cloud API Gateway problems'
' in this skill. Prints a JSON report on stdout. It does not check'
' general OpenAPI validity.'
),
epilog=(
'Exit codes: 0 = PASS (read the warnings), 1 = FAIL (fix the'
' errors), 2 = the file cannot be read or parsed, or PyYAML is not'
' installed. Example, from the skill directory: python3'
' scripts/validate_apigw_openapi.py --spec=/path/to/openapi.yaml'
),
)
parser.add_argument(
'--spec',
required=True,
help='Path to the OpenAPI YAML or JSON spec file to validate.',
)
args = parser.parse_args(argv)
try:
spec, alias_lines = _load_spec(args.spec)
except (OSError, RuntimeError, ValueError) as exc:
print(f'Error: {exc}', file=sys.stderr)
return 2
errors, warnings, summary = validate_spec(spec, alias_lines)
report = {
'status': 'FAIL' if errors else 'PASS',
'spec': args.spec,
'openapi': str(spec.get('openapi', spec.get('swagger', ''))),
'base_path': summary['base_path'],
'backend_path_translation': summary['backends'],
'path_parameters_as_query': summary['path_parameters_as_query'],
'operation_count': summary['operations'],
'errors': errors,
'warnings': warnings,
'note': _NOTE,
}
print(json.dumps(report, indent=2))
if errors:
print(
f'API Gateway OpenAPI validation failed with {len(errors)} error(s).',
file=sys.stderr,
)
return 1
return 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