Generated banner for API Gateway Backend Security And Rate Limiting
Generated logo for API Gateway Backend Security And Rate Limiting

API Gateway Backend Security And Rate Limiting

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for securing backend services behind Google Cloud API Gateway. It covers the implementation of API key and JWT authentication, the configuration of dedicated service accounts for secure backend invocation, and the setup of per-project rate limits using OpenAPI 2.0 and 3.0 specifications. The skill includes a validation loop to prevent quota-related errors and ensures zero-downtime transitions when locking down backend services.

What it does

  • Configures API key and JWT authentication for API Gateway endpoints.
  • Implements secure gateway-to-backend communication using dedicated service accounts.
  • Sets per-project request quotas and rate limits via OpenAPI definitions.
  • Provides a validation script to check quota metrics before deployment.
  • Guides users through a zero-downtime lockdown process for backend services.
  • Supports configuration for both OpenAPI 2.0 and 3.0.x specifications.

When to use it

  • When you need to secure Cloud Run or Cloud Functions backends behind an API Gateway.
  • When implementing per-project rate limiting or request quotas.
  • When migrating to a more secure backend authentication model without causing downtime.
  • When diagnosing HTTP 429 or HTTP 500 Service Control Quota errors.
  • When configuring authentication for gateways with Model Context Protocol (MCP) enabled.

Advantages

  • Ensures zero-downtime transitions for production API security updates.
  • Prevents common configuration errors through a pre-deployment validation loop.
  • Promotes least-privilege access by using dedicated service accounts for backends.
  • Provides clear separation between client-facing authentication and backend security.

Usage examples

“How do I secure my Cloud Run backend behind API Gateway?”
The agent will guide you through creating a dedicated service account, granting it the run.invoker role, and updating your API config to use this account for backend authentication.
“I am getting HTTP 500 errors when updating my API Gateway quotas. How do I fix this?”
The agent will instruct you to run the quota validation script to identify misconfigured metrics and ensure your new API config maintains compatibility with existing gateways.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/google/api-gateway-backend-security-and-rate-limiting/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip api-gateway-backend-security-and-rate-limiting.zip -d .agents/skills

Documentation by Google

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

  1. Install the Google Cloud CLI and Python 3.10+ YAML parser:

    • Install or update the Google Cloud SDK.

    • Install PyYAML for the quota metric validation script:

      pip install "PyYAML>=6.0,<7.0"
  2. Authenticate your environment:

    • Local CLI session: gcloud auth login

    • Application Default Credentials (SDKs): gcloud auth application-default login

    • Service account key file (if required by CI): set GOOGLE_APPLICATION_CREDENTIALS={key_file_path}

  3. Select or create a project, verify billing, and pick a supported gateway location:

    • 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-central1 as the default --location for API Gateway commands. For the other supported regions, see API Gateway deployment model.

  4. Enable required Google Cloud APIs:

    gcloud services enable \
      apigateway.googleapis.com \
      servicemanagement.googleapis.com \
      servicecontrol.googleapis.com \
      iam.googleapis.com \
      apikeys.googleapis.com \
      --project={project_id}

    API Gateway does not need the Cloud Run API. If the backend runs on Cloud Run, that API is already enabled in the backend's project.

  5. Verify required IAM roles:

    • To manage API Gateway resources and enable services: roles/apigateway.admin and roles/serviceusage.serviceUsageAdmin

    • To create the gateway service account and attach it to an API config: roles/iam.serviceAccountAdmin and roles/iam.serviceAccountUser

    • To manage API keys in consumer projects: roles/serviceusage.apiKeysAdmin

    • For the gateway service account to invoke the backend: roles/run.invoker (Cloud Run or 2nd gen functions) or roles/cloudfunctions.invoker (1st gen functions)

Decision Matrix: Client Authentication, Backend Security, and Quotas

Select the layer that matches the security requirement:

GoalMechanism to ConfigureKey ConstraintDetailed Reference
Identify the calling consumer project for quotas and billingAPI 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 servicesJWT (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 serviceDedicated gateway service account (--backend-auth-service-account) + roles/run.invoker + backend --no-allow-unauthenticatedRoll 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-quotaNEVER 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: falsex-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:

  1. 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 granting roles/run.invoker on {backend_service}.

    • Update backend handler code to decode verified user claims from X-Apigateway-Api-Userinfo (base64url-encoded JSON) instead of Authorization.

  2. 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 on tools-list (also list a JWT scheme in the root security list), and review operation opt-outs using MCP Traffic Security.

  3. Run the quota metric validation loop BEFORE running api-configs create:

    • If neither the active specs nor {candidate_openapi_spec} define quota metrics (x-google-management.metrics or x-google-api-management.metrics), skip this step.

    • Request human approval before creating an API config that defines or modifies quotas, because api-configs create immediately replaces quota definitions across all gateways of the API.

    • By default, run scripts/check_quota_metrics.py against all active gateways deployed for {api_id} in {project_id}:

      python3 scripts/check_quota_metrics.py \
        --spec={candidate_openapi_spec} \
        --project={project_id} \
        --api={api_id}
    • Escape hatch for offline environments without gcloud access (pass --baseline-spec for every config currently served by a gateway of the API):

      python3 scripts/check_quota_metrics.py \
        --spec={candidate_openapi_spec} \
        --baseline-spec={previous_openapi_spec} \
        --dry-run
    • If scripts/check_quota_metrics.py exits with code 1 (status: "FAIL"), add the missing metrics and limits back to {candidate_openapi_spec}, move each x-google-quota listed in ignored_quota_extensions into the operations it applies to, and re-run the script until it exits with code 0 (status: "PASS"). If the user wants to remove a limit on purpose, confirm the removal with the user, because it removes that limit from every gateway of the API. If skipped_configs is not empty, tell the user that the script did not inspect those API configs (for example, gRPC configs), and check their quota metrics and limits manually. If it exits with code 2, fix the problem printed to stderr: the CLI arguments, gcloud authentication, or an API config that the script cannot inspect.

  4. Create the API config, update the gateway, enable the managed service, and lock down the backend:

    • Follow Steps 4–5 of Backend Security to run gcloud api-gateway api-configs create and gcloud api-gateway gateways update (request human approval before updating a production gateway), enable the API's managedService in consumer projects (Client Authentication), and then restrict {backend_service} with --no-allow-unauthenticated.

    • Verify that direct calls to the backend *.run.app URL return 403, unauthenticated calls to the gateway defaultHostname return 401, and authenticated calls return 200.

Pre-Deployment Checklist

  • [ ] Dedicated {gateway_sa_name} is granted roles/run.invoker (or roles/cloudfunctions.invoker), and --no-allow-unauthenticated is applied after the gateway config is active.

  • [ ] Backend code decodes X-Apigateway-Api-Userinfo for user claims.

  • [ ] Security enforcement does not depend solely on a load balancer or Google Cloud Armor in front of the gateway, because the gateway's defaultHostname (*.gateway.dev) cannot be disabled.

  • [ ] Every quota-enforced operation requires an API key (api_key: []), and the API's managedService is enabled and allowed on the API key in each consumer project.

  • [ ] python3 scripts/check_quota_metrics.py returns status: "PASS" (exit code 0) against active gateway configs or all baseline specs before api-configs create.

  • [ ] If MCP is enabled, x-google-api-management.mcp.tools-list.security names exactly one JWT or API key scheme (a JWT scheme is also in the root security list), and administrative endpoints are secured on REST in addition to x-google-mcp-tool: false.

Resource Cleanup

To avoid ongoing charges when tearing down a test or staging environment, request human approval and delete the gateway, all API configs, 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}

Files

references/mcp-traffic-security.md

MCP Traffic Security and Quotas Reference (Public Preview)

  • Authentication Model per MCP Method: Lines 8-35

  • Tool Discovery Security (tools/list): Lines 37-96

  • Shared REST and MCP Quota Enforcement: Lines 98-104

  • Sensitive Operations and Header Parameters on MCP: Lines 106-115

Authentication Model per MCP Method

Model Context Protocol (MCP) support on API Gateway is a Public Preview feature that requires an OpenAPI 3.x specification (x-google-api-management.mcp). It exposes a stateless JSON-RPC 2.0 endpoint at POST https://{default_hostname}/mcp, even when a servers base path is set (up to 1,000 tools per gateway, mutually exclusive with x-google-model-router in the same API config).

API Gateway applies distinct authentication rules to each MCP method:

MCP MethodDefault AuthenticationSupported Security SchemesBehavior
initializeUnauthenticatedNoneHandled directly by the gateway handshake layer; never reaches the backend.
notifications/initializedUnauthenticatedNoneReturns HTTP 202 Accepted; never reaches the backend.
tools/listUnauthenticated by defaultExactly one JWT scheme (oauth2 with x-google-auth) or one API key scheme (apiKey)Configured via x-google-api-management.mcp.tools-list.security. tools/list reads an API key only from the x-api-key header, not from query parameters.
tools/callInherits operation securityJWT (oauth2) and API keys (apiKey)Transcoded into the underlying REST request and subject to the exact security and x-google-quota rules of that OpenAPI operation.

API Gateway reports an MCP authentication failure in the HTTP status, in the JSON-RPC error field of the body, or in both. Check both, because one case returns HTTP 200:

Method and schemeRequestHTTP statusBody
tools/list with a JWT schemeMissing or invalid token401, with a WWW-Authenticate headerJSON-RPC error (today -32000)
tools/list with a JWT schemeToken with a wrong audience403, with a WWW-Authenticate headerJSON-RPC error (today -32000)
tools/list with an API key schemeMissing key401JSON-RPC error, no tools
tools/list with an API key schemeInvalid key200 (current behavior)JSON-RPC error, no tools
tools/callCredentials that fail the operation's security401 or 403A REST error (for example {"code":401,"message":"Jwt is missing"}) or a JSON-RPC result with isError: true

Today the tools/list JSON-RPC error has code -32000 and the message Tool list response is invalid or has error status code., which does not name the cause. The code and the message can change, so check the HTTP status and the WWW-Authenticate header first. For a JWT failure, the WWW-Authenticate header points at the protected resource metadata.

If a gateway project is attached to Apigee API hub, MCP-enabled gateways are automatically published to API hub ({api} (MCP)) and Agent Registry.

Reference: Configure Model Context Protocol

Tool Discovery Security (tools/list)

By default, tools/list is unauthenticated, which allows any caller that reaches the gateway URL to enumerate all tool names, descriptions, and JSON input schemas.

  • In production environments, ALWAYS configure x-google-api-management.mcp.tools-list.security with a JWT or API key security scheme defined in components.securitySchemes. Rationale: Leaving tools/list unauthenticated exposes internal API capabilities and parameter schemas to unauthenticated callers.

  • Name exactly one scheme under tools-list.security. Rationale: API Gateway rejects a tools-list.security block that names more than one scheme. An empty block (security: {}) passes config creation with no error and leaves tools/list unauthenticated, so check that the block names a scheme.

  • Prefer a JWT scheme when agents must prove who they are. An API key identifies a consumer project rather than a caller, so use an API key scheme on tools/list when the tools already require that API key and caller identity is not needed.

  • If you use a JWT scheme, list the same scheme in the root security list. Rationale: API Gateway rejects a config whose JWT tools-list.security scheme is missing from the root security list. The root entry also requires the JWT on every REST operation that does not set its own security, so tell the user before you deploy.

  • If you use an API key scheme, define it with in: header and name: x-api-key. Rationale: tools/list reads API keys only from the x-api-key header, not from query parameters.

  • Setting x-google-api-management.mcp to an object (to configure tools-list) automatically enables MCP globally for all eligible GET, POST, PUT, PATCH, and DELETE operations in the specification. Explicitly set x-google-mcp-tool: false on every operation that must not be exposed as an agent tool. Every exposed tool MUST resolve to a unique name matching [A-Za-z0-9_.-]{1,128} and a non-empty description.

openapi: 3.0.4
info:
  title: Orders Service
  version: 1.0.0
x-google-api-management:
  mcp:
    tools-list:
      security:
        agent_jwt: []
  backends:
    orders-backend:
      address: https://{backend_service}-{hash}.a.run.app
      jwtAudience: https://{backend_service}-{hash}.a.run.app
x-google-backend: orders-backend
security:
  - agent_jwt: []
components:
  securitySchemes:
    agent_jwt:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: ""
          scopes: {}
      x-google-auth:
        issuer: "https://accounts.google.com"
        jwksUri: "https://www.googleapis.com/oauth2/v3/certs"
        audiences:
          - "{oauth_client_id}"

For Google ID tokens that a service account gets with gcloud auth print-identity-token --impersonate-service-account={caller_sa_email} --audiences={jwt_audience}, set audiences to that same {jwt_audience} value. See the Identity Provider JWT Settings Table.

To require an API key on tools/list instead, name the API key scheme. An API key scheme does not need a root security entry:

x-google-api-management:
  mcp:
    tools-list:
      security:
        api_key: []
components:
  securitySchemes:
    api_key:
      type: apiKey
      name: x-api-key
      in: header

Shared REST and MCP Quota Enforcement

When an agent invokes a tool via tools/call, API Gateway transcodes the call into the underlying REST operation. The transcoded backend request is indistinguishable from a direct REST call, so backends cannot apply MCP-only logic.

  • Shared quota bucket: Direct REST requests and MCP tools/call invocations against the same operation draw from the exact same x-google-quota metric and per-project quota limit.

  • Passing credentials from MCP clients: If the underlying REST operation uses x-google-quota (which requires an API key) and tools/list requires a JWT (agent_jwt), the MCP client MUST send both headers (Authorization: Bearer {jwt} and x-api-key: {api_key}) on requests to /mcp. Rationale: Omitting x-api-key causes tools/call to fail the operation's API key and quota check, while omitting Authorization causes tools/list to fail with 401. If tools-list.security names the API key scheme instead, the same x-api-key header also authenticates tools/list.

  • Higher cost for write tools: Because agent loops can issue rapid tool retries, assign higher x-google-quota metric costs or separate lower-limit metrics (write-requests) to mutating POST, PUT, PATCH, and DELETE operations exposed as MCP tools.

Sensitive Operations and Header Parameters on MCP

API Gateway does not emit MCP tool annotations such as destructiveHint or readOnlyHint in tools/list responses during Public Preview, and operations returning empty bodies (HTTP 204) are not supported as MCP tools.

  1. Set x-google-mcp-tool: false on administrative, bulk-delete, or internal health-check operations so agents cannot discover or invoke them via /mcp.

  2. NEVER treat x-google-mcp-tool: false as an access control boundary for the operation itself. Rationale: Setting x-google-mcp-tool: false only omits the operation from MCP tools/list and blocks tools/call, while the underlying REST path remains live and callable on the gateway URL unless secured with a strict security requirement or removed from the OpenAPI specification.

  3. NEVER declare trust-bearing identity headers (such as a custom user ID or tenant role header) as OpenAPI in: header parameters on an MCP-exposed operation. Rationale: API Gateway exposes OpenAPI header parameters as top-level properties in the MCP tool arguments schema and injects the agent-supplied values into the backend HTTP request headers. (Parameters cannot bind to reserved system headers or headers starting with x-google-).

  4. For destructive operations that intentionally remain exposed as MCP tools, state in x-google-mcp-tool.description when the agent is permitted to call the tool and that the action cannot be undone.

Reference: OpenAPI 3.x feature limitations - MCP limitations

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs a command-line tool, Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/api-gateway-backend-security-and-rate-limiting · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google or Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download api-gateway-backend-security-and-rate-limiting.zip