api-gateway-backend-security-and-rate-limiting
Secures and rate limits backend services behind Google Cloud API Gateway across OpenAPI 2.0 and OpenAPI 3.0.x API configurations, including MCP-enabled gateways. Use when configuring API key or JWT authentication, locking down Cloud Run or Cloud Run functions backends with a gateway service account, reading authenticated claims from X-Apigateway-Api-Userinfo, setting per-project request quotas, or diagnosing HTTP 429 and HTTP 500 Service Control Quota errors. Do not use for Apigee, GKE Gateway API, Cloud Load Balancing custom domain setup, or LLM model routing.
- License 许可
- Apache-2.0
- 所属仓库
- google/skills
- 最近更新
- 2026-11-14
- Stars
- ★ 2.4w
- Forks
- 2.0k
01 前言 Front Matter
- name
- api-gateway-backend-security-and-rate-limiting
- metadata
- { "version": "1.0.1", "category": "Security" }
- description
- Secures and rate limits backend services behind Google Cloud API Gateway across OpenAPI 2.0 and OpenAPI 3.0.x API configurations, including MCP-enabled gateways. Use when configuring API key or JWT authentication, locking down Cloud Run or Cloud Run functions backends with a gateway service account, reading authenticated claims from X-Apigateway-Api-Userinfo, setting per-project request quotas, or diagnosing HTTP 429 and HTTP 500 Service Control Quota errors. Do not use for Apigee, GKE Gateway API, Cloud Load Balancing custom domain setup, or LLM model routing.
02 资源文件 6
- 参考文档references/attribution.md1.9 KB
- 参考文档references/backend-security.md7.8 KB
- 参考文档references/client-authentication.md9.0 KB
- 参考文档references/mcp-traffic-security.md9.5 KB
- 参考文档references/quotas-and-rate-limiting.md7.5 KB
- 脚本scripts/check_quota_metrics.py15.7 KB
03 SKILL.md 正文
API Gateway Backend Security and Rate Limiting
This skill configures client authentication, gateway-to-backend authentication, and per-project rate limits (quotas) for Google Cloud API Gateway across OpenAPI 2.0 (swagger: "2.0") and OpenAPI 3.0.x (openapi: 3.0.4), including gateways with Model Context Protocol (MCP) enabled (Public Preview).
Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read Usage Attribution. For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix gcloud with
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:api-gateway-backend-security-and-rate-limiting)"
and append agent-skills/1.0 (skill:api-gateway-backend-security-and-rate-limiting) to User-Agent headers.
Prerequisites
- Install the Google Cloud CLI and Python 3.10+ YAML parser:
- Install or update the Google Cloud SDK.
- Install
PyYAMLfor the quota metric validation script:pip install "PyYAML>=6.0,<7.0"
- Authenticate your environment:
- Local CLI session:
gcloud auth login - Application Default Credentials (SDKs):
gcloud auth application-default login - Service account key file (if required by CI): set
GOOGLE_APPLICATION_CREDENTIALS={key_file_path}
- Local CLI session:
- Select or create a project, verify billing, and pick a supported gateway location:
- Select an existing project (
gcloud config set project {project_id}) or create one (gcloud projects create {project_id}as an escape hatch). - Verify that an active billing account is linked to
{project_id}(required even when staying within the API Gateway pricing free tier). - Use
us-central1as the default--locationfor API Gateway commands. For the other supported regions, see API Gateway deployment model.
- Select an existing project (
- Enable required Google Cloud APIs:
API Gateway does not need the Cloud Run API. If the backend runs on Cloud Run, that API is already enabled in the backend's project.gcloud services enable \ apigateway.googleapis.com \ servicemanagement.googleapis.com \ servicecontrol.googleapis.com \ iam.googleapis.com \ apikeys.googleapis.com \ --project={project_id} - Verify required IAM roles:
- To manage API Gateway resources and enable services:
roles/apigateway.adminandroles/serviceusage.serviceUsageAdmin - To create the gateway service account and attach it to an API config:
roles/iam.serviceAccountAdminandroles/iam.serviceAccountUser - To manage API keys in consumer projects:
roles/serviceusage.apiKeysAdmin - For the gateway service account to invoke the backend:
roles/run.invoker(Cloud Run or 2nd gen functions) orroles/cloudfunctions.invoker(1st gen functions)
- To manage API Gateway resources and enable services:
Decision Matrix: Client Authentication, Backend Security, and Quotas
Select the layer that matches the security requirement:
| Goal | Mechanism to Configure | Key Constraint | Detailed Reference |
|---|---|---|---|
| Identify the calling consumer project for quotas and billing | API key (x-api-key header convention; key query parameter escape hatch) |
NEVER rely on an API key alone to authenticate end-user identity. Rationale: API keys identify a Google Cloud project rather than a user, and clients can extract them. | Client Authentication |
| Authenticate end users or calling services | JWT (oauth2 scheme with x-google-issuer / x-google-jwks_uri in OAS 2.0, or x-google-auth in OAS 3.x) |
Operation-level security overrides root security. Include api_key: [] and the JWT scheme in the same security requirement object when an endpoint needs both user identity and quotas. |
Client Authentication |
| Block direct calls to the backend service | Dedicated gateway service account (--backend-auth-service-account) + roles/run.invoker + backend --no-allow-unauthenticated |
Roll out the gateway config with --backend-auth-service-account BEFORE setting --no-allow-unauthenticated on a live backend to avoid 403 downtime. |
Backend Security |
Rate limit requests per consumer project (1/min/{project}) |
x-google-management (OAS 2.0) or x-google-api-management (OAS 3.x) + x-google-quota |
NEVER rename or remove a quota metric when creating a new API config while any gateway of the API runs an older config referencing that metric. Rationale: Creating the config immediately overwrites API-wide quotas and causes HTTP 500 Failed to call Service Control Quota on older gateways. |
Quotas and Rate Limiting |
Secure MCP tools/list and tools/call on /mcp (Public Preview) |
x-google-api-management.mcp.tools-list.security (exactly one JWT or API key scheme) + operation security and x-google-mcp-tool: false |
x-google-mcp-tool: false hides an operation from MCP only; the underlying REST route remains live unless secured or removed. |
MCP Traffic Security |
Execution Workflow and Validation Loop
Follow this zero-downtime sequence when authoring or updating an API Gateway security or quota configuration:
- Create the gateway service account and grant backend invoker permissions:
- Follow Steps 1–3 of Backend Security to create
{gateway_sa_name}and request human approval before grantingroles/run.invokeron{backend_service}. - Update backend handler code to decode verified user claims from
X-Apigateway-Api-Userinfo(base64url-encoded JSON) instead ofAuthorization.
- Follow Steps 1–3 of Backend Security to create
- Author the OpenAPI authentication and quota definitions:
- Use the OpenAPI 2.0 or OpenAPI 3.0.x templates and provider tables in Client Authentication and Quotas and Rate Limiting.
- If the specification enables MCP (
x-google-api-management.mcp), configure exactly one JWT or API key scheme ontools-list(also list a JWT scheme in the rootsecuritylist), and review operation opt-outs using MCP Traffic Security.
- Run the quota metric validation loop BEFORE running
api-configs create:- If neither the active specs nor
{candidate_openapi_spec}define quota metrics (x-google-management.metricsorx-google-api-management.metrics), skip this step. - Request human approval before creating an API config that defines or modifies quotas, because
api-configs createimmediately replaces quota definitions across all gateways of the API. - By default, run
scripts/check_quota_metrics.pyagainst all active gateways deployed for{api_id}in{project_id}:python3 scripts/check_quota_metrics.py \ --spec={candidate_openapi_spec} \ --project={project_id} \ --api={api_id} - Escape hatch for offline environments without
gcloudaccess (pass--baseline-specfor every config currently served by a gateway of the API):python3 scripts/check_quota_metrics.py \ --spec={candidate_openapi_spec} \ --baseline-spec={previous_openapi_spec} \ --dry-run - If
scripts/check_quota_metrics.pyexits with code1(status: "FAIL"), add the missing metrics and limits back to{candidate_openapi_spec}, move eachx-google-quotalisted inignored_quota_extensionsinto the operations it applies to, and re-run the script until it exits with code0(status: "PASS"). If the user wants to remove a limit on purpose, confirm the removal with the user, because it removes that limit from every gateway of the API. Ifskipped_configsis not empty, tell the user that the script did not inspect those API configs (for example, gRPC configs), and check their quota metrics and limits manually. If it exits with code2, fix the problem printed to stderr: the CLI arguments,gcloudauthentication, or an API config that the script cannot inspect.
- If neither the active specs nor
- Create the API config, update the gateway, enable the managed service, and lock down the backend:
- Follow Steps 4–5 of Backend Security to run
gcloud api-gateway api-configs createandgcloud api-gateway gateways update(request human approval before updating a production gateway), enable the API'smanagedServicein consumer projects (Client Authentication), and then restrict{backend_service}with--no-allow-unauthenticated. - Verify that direct calls to the backend
*.run.appURL return403, unauthenticated calls to the gatewaydefaultHostnamereturn401, and authenticated calls return200.
- Follow Steps 4–5 of Backend Security to run
Pre-Deployment Checklist
- [ ] Dedicated
{gateway_sa_name}is grantedroles/run.invoker(orroles/cloudfunctions.invoker), and--no-allow-unauthenticatedis applied after the gateway config is active. - [ ] Backend code decodes
X-Apigateway-Api-Userinfofor user claims. - [ ] Security enforcement does not depend solely on a load balancer or Google Cloud Armor in front of the gateway, because the gateway's
defaultHostname(*.gateway.dev) cannot be disabled. - [ ] Every quota-enforced operation requires an API key (
api_key: []), and the API'smanagedServiceis enabled and allowed on the API key in each consumer project. - [ ]
python3 scripts/check_quota_metrics.pyreturnsstatus: "PASS"(exit code0) against active gateway configs or all baseline specs beforeapi-configs create. - [ ] If MCP is enabled,
x-google-api-management.mcp.tools-list.securitynames exactly one JWT or API key scheme (a JWT scheme is also in the rootsecuritylist), and administrative endpoints are secured on REST in addition tox-google-mcp-tool: false.
Resource Cleanup
To avoid ongoing charges when tearing down a test or staging environment, request human approval and delete the gateway, all API configs, the API, and the service account in dependency order:
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}
gcloud iam service-accounts delete {gateway_sa_name}@{project_id}.iam.gserviceaccount.com --project={project_id}
04 同仓库更多 Skills
sign-in-with-google-web
Implement, configure, and secure Sign In With Google (SiwG) using Google Identity Services (GIS / `https://accounts.google.com/gsi/client`) across web architectures. Use when creating Google sign-in buttons, implementing Google One Tap with FedCM, integrating GIS in React/Next.js/Angular/HTML, verifying ID tokens on backend runtimes (Python/Node.js/Go/Java), enforcing Google Workspace domain restrictions (`hd`), securing client-side ID tokens via WebCrypto nonces or encrypted IndexedDB, embedding in cross-origin iframes via the Intermediate Iframe API (`https://accounts.google.com/gsi/intermediate`), configuring Content Security Policy (CSP), COOP, and Permissions Policy (`identity-credentials-get`) headers, or handling sign-out and revocation. Don't use for legacy Google Sign-In (`gapi.auth2`), Google Cloud IAM service accounts, or Android/iOS native Credential Manager.
dpop-adoption
Implement and debug OAuth 2.0 DPoP (RFC 9449) refresh token sender-constraining for WebCrypto, Node.js ES6, and browser runtimes integrating with Google's OAuth platform. Use when configuring non-extractable asymmetric key pairs (P-256), generating DPoP Proof JWTs for authorization code exchange and token refresh, or handling 400 use_dpop_nonce challenge retry loops at oauth2.googleapis.com/token. Don't use for unconstrained OAuth 2.0 flows (where refresh tokens are not bound to a client key pair), or for Google Cloud IAM / service account authentication.
retrieving-developer-knowledge
Searches, retrieves, and synthesizes official Google developer documentation across Google Cloud, AI/Gemini, Android, Chrome, Web, Flutter, Go, Firebase, and other Google developer platforms. Integrates with the Developer Knowledge MCP server (search_documents, get_documents, answer_query) or the Developer Knowledge REST API fallback. Use when searching for gcloud CLI commands, API syntax, IAM permissions, official documentation, architectural comparisons, or product choice overviews. Don't use for local filesystem lookups or non-Google documentation.
migrate-to-rust
Clones, analyzes, plans, and migrates legacy codebases (C++, Fortran, Java, Python, C, Shell) from a GitHub URL or local directory to a modern, high-performance, deterministic, 100% Safe Rust architecture, tracking live telemetry across every task bucket, test failure/fix cycle, and Profile-Guided Optimization (PGO) stage, and producing a first-person AI storytelling report and interactive HTML infographic. Use when migrating a GitHub repository or local codebase to Rust, porting legacy C++, Fortran, Python, or Java workloads to memory-safe Rust, designing Struct-of-Arrays (SoA) or SIMD Rust architectures, or optimizing Rust ports with LLVM PGO. Don't use for unrelated non-Rust refactoring or single-line syntax questions.
finding-google-skills
Google platform decision and setup guidance, loaded on demand from Google's skill catalog. Use when a developer is choosing or setting up part of their stack, such as where to run a service, a database, storage, messaging, authentication, analytics, ads, or AI model serving, and a Google product is a reasonable candidate - whether or not a vendor is named - or when a request names a Google product or API. Brings in the matching Google skill so the answer can weigh Google options, their trade-offs, and when they are not the right fit. Skip when the stack is already settled on another provider and no Google product is named, or the task involves no platform choice.
workload-manager-basics
Use this skill to manage Google Cloud Workload Manager evaluations, rules, scanned resources, and validation results by using public client libraries and the REST API. Use when you need to inspect workload best-practice rules, create and run evaluations for Google Cloud general best practices, SAP, SQL Server, or custom organizational rules, review violations, export results to BigQuery, or automate Workload Manager through client libraries because no service-specific public CLI or MCP server is available. Don't use for general Google Compute Engine instance management, VPC configuration, or standard IAM auditing.