Nov 19, 20267 min read

Cloud Run Service-to-Service Authentication

How one Cloud Run service calls another with a Google-signed ID token, the IAM grant the receiver needs, working Go and Python callers, and the causes behind 401 and 403 responses.

Illustration for Cloud Run Service-to-Service Authentication

When one Cloud Run service calls another, the receiver should reject anything that does not come from a known caller. Cloud Run handles this with IAM: the caller sends a Google-signed ID token, and the platform checks it before your container sees the request.

This guide sets that up end to end with dedicated service accounts, the invoker grant, Go and Python callers, and a checklist for the 401 and 403 errors you will likely hit.

The pieces at a glance

PieceWhat it doesWhere it is set
Service account on the callerIdentity the token is issued for--service-account on deploy
Public access disabled on the receiverCloud Run requires a valid token--no-allow-unauthenticated
roles/run.invokerLets the caller's identity invoke the receiverIAM policy on the receiving service
ID token with the right audienceProves who is calling and for which serviceFetched in the caller's code
Internal ingress (optional)Limits which networks can reach the receiver--ingress=internal

How does Cloud Run service-to-service authentication work?

The caller fetches an ID token from the metadata server, where the token's aud claim is the receiving service's URL, and sends it as Authorization: Bearer <token>. Cloud Run validates the signature, expiry and audience, then checks that the token's service account holds roles/run.invoker on the receiving service. Requests that fail get a 401 or 403 from Cloud Run, and your code never runs.

The service-to-service guide in the Cloud Run docs covers the same flow. The steps below use a checkout service calling an orders service.

Step 1: Give each service its own service account

A Cloud Run service without an explicit identity runs as the Compute Engine default service account, which usually holds broad project roles. Create one account per service, so the invoker grant names exactly one caller, as the service identity docs recommend:

~
$ gcloud iam service-accounts create checkout-sa$ gcloud iam service-accounts create orders-sa$ gcloud run deploy checkout --source . --region europe-west1 \ --service-account checkout-sa@my-project.iam.gserviceaccount.com

Step 2: Lock down the receiving service and grant the invoker role

Deploy orders without public access, then grant roles/run.invoker to the caller's service account on that service only, rather than at the project level:

~
$ gcloud run deploy orders --source . --region europe-west1 \ --service-account orders-sa@my-project.iam.gserviceaccount.com \ --no-allow-unauthenticated$ gcloud run services add-iam-policy-binding orders --region europe-west1 \ --member serviceAccount:checkout-sa@my-project.iam.gserviceaccount.com \ --role roles/run.invoker

A plain curl to the orders URL now returns 403, and that is the expected result.

Step 3: Fetch an ID token in the calling service

In Go, the idtoken package returns an http.Client that fetches a token for the audience from the metadata server, caches it until shortly before expiry and attaches it to every request:

package main import ( "context" "fmt" "io" "log" "net/http" "os" "google.golang.org/api/idtoken" ) // ordersURL is the receiving service's URL, which is also the token audience. var ordersURL = os.Getenv("ORDERS_URL") // e.g. https://orders-abc123-ew.a.run.app func getOrder(ctx context.Context, client *http.Client, id string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, ordersURL+"/orders/"+id, nil) if err != nil { return nil, err } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("orders returned %s", resp.Status) } return io.ReadAll(resp.Body) } func main() { ctx := context.Background() // Fetches a Google-signed ID token for the audience from the metadata // server, caches it and adds "Authorization: Bearer <token>". client, err := idtoken.NewClient(ctx, ordersURL) if err != nil { log.Fatal(err) } http.HandleFunc("/checkout/{id}", func(w http.ResponseWriter, r *http.Request) { body, err := getOrder(r.Context(), client, r.PathValue("id")) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.Write(body) }) log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil)) }

In Python, google.oauth2.id_token.fetch_id_token from the google-auth package does the same lookup. It does not cache, so a busy caller should keep the token until close to its one-hour expiry:

import os import google.auth.transport.requests import google.oauth2.id_token import requests ORDERS_URL = os.environ["ORDERS_URL"] # also the token audience def get_order(order_id: str) -> dict: auth_req = google.auth.transport.requests.Request() token = google.oauth2.id_token.fetch_id_token(auth_req, ORDERS_URL) resp = requests.get( f"{ORDERS_URL}/orders/{order_id}", headers={"Authorization": f"Bearer {token}"}, timeout=10, ) resp.raise_for_status() return resp.json()

Step 4: Restrict the network with internal ingress

IAM decides who may call, while ingress settings decide from where. Setting --ingress=internal on orders rejects traffic from the public internet, so the caller has to reach it through a VPC, typically with Direct VPC egress or a connector routing all traffic. Internal ingress does not replace the token, because anything inside the VPC could otherwise call the service.

Why does service-to-service auth return 401 or 403?

  • 401 with no token. The caller sent no Authorization header, or sent it to a redirect that dropped the header. Log the outgoing request headers once to confirm.
  • 401 with an access token. OAuth access tokens from gcloud auth print-access-token or the default token source are not accepted. Cloud Run needs an ID token.
  • 403 with the wrong audience. The audience must be the service URL as Cloud Run reports it, without a path. Calls through a custom domain still need the run.app URL as the audience unless you configure custom audiences on the service.
  • 403 with the wrong identity. The caller runs as a different service account than the one you granted. Check the deployed revision's service account in the console or with gcloud run services describe.
  • Errors from a laptop. Client libraries cannot mint ID tokens from user credentials. Use service account impersonation for local tests, or call with gcloud auth print-identity-token if your user holds the invoker role.

Service-to-service calls with Encore

Encore

Encore is a backend framework with built-in infrastructure, and calling another service is a typed function call rather than an HTTP request with a token. You mark an endpoint private, which means it is never exposed to the outside world and can only be called by other services in the app and by cron jobs.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir inventory checkout
// inventory/inventory.go package inventory import ( "context" "encore.dev/beta/errs" ) type StockResponse struct { SKU string `json:"sku"` Available int `json:"available"` } var stock = map[string]int{"tee-black-m": 12} // Stock is private: only other services in the app (and cron jobs) can call it. // //encore:api private method=GET path=/inventory/:sku func Stock(ctx context.Context, sku string) (*StockResponse, error) { n, ok := stock[sku] if !ok { return nil, &errs.Error{Code: errs.NotFound, Message: "unknown sku"} } return &StockResponse{SKU: sku, Available: n}, nil }
// checkout/checkout.go package checkout import ( "context" "encore.dev/beta/errs" "encore.app/inventory" ) type CheckParams struct { SKU string `json:"sku"` Quantity int `json:"quantity"` } type CheckResponse struct { CanOrder bool `json:"can_order"` } //encore:api public method=POST path=/checkout/check func Check(ctx context.Context, p *CheckParams) (*CheckResponse, error) { // A typed call to another service, routed by Encore. s, err := inventory.Stock(ctx, p.SKU) if err != nil { if errs.Code(err) == errs.NotFound { return &CheckResponse{CanOrder: false}, nil } return nil, err } return &CheckResponse{CanOrder: s.Available >= p.Quantity}, nil }

Service-to-service calls keep their types and errors, so errs.NotFound from inventory arrives as the same code in checkout. Locally, encore run serves both services and still lets you call the private endpoint from your machine for testing.

On GCP, Encore deploys each service to Cloud Run or GKE in a private network. Encore provisions an IAM role for the service, or a service account on GCP, and private endpoints stay unreachable from the internet.

A coding agent that splits a service in two only has to move code and mark the inner endpoint private. There are no service accounts, invoker bindings or audience strings to get right in the same change.

Best fit: Go and TypeScript teams on GCP that want internal endpoints protected by default, without managing ID tokens and invoker grants per pair of services.

Frequently asked questions

How do Cloud Run services authenticate to each other?

The calling service runs as a service account, fetches a Google-signed ID token from the metadata server with the receiving service's URL as the audience, and sends it as a Bearer token. The receiving service is deployed without public access, and the caller's service account holds roles/run.invoker on it, so Cloud Run checks the token before your code runs.

Why does my Cloud Run service return 403 to another service?

A 403 means the token was valid but the caller's service account does not have roles/run.invoker on the receiving service, or the token's audience does not match the service URL or a configured custom audience. Check which service account the caller runs as, since a service without one set uses the Compute Engine default account.

Do I need to verify the ID token in my code?

No. When public access is disabled, Cloud Run validates the token signature, expiry, audience and IAM permission before the request reaches your container. You only verify it yourself if you need the caller's identity in application logic, and you can then read the email claim from the token.

Is internal ingress enough to secure service-to-service calls?

No. Internal ingress limits which networks can reach the service, but it does not identify the caller. Use it together with IAM authentication, so a request must come from an allowed network and carry a token from a service account with the invoker role. Encore applies the same idea with private endpoints that are never exposed outside the app.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders