Skip to content

13Compute and containersService 13 of 13

Cloud Run and Cloud Functionssecurity hardening

Harden Cloud Run and Cloud Run functions: runtime service accounts, ingress, invoker IAM, IAP, VPC egress, secrets, Binary Authorization, CMEK and org policies.

Baseline
11 controls
Category
Compute and containers
Updated
Reading
9 min read

Cloud Run runs containers as fully managed services, jobs and worker pools. Cloud Functions is now part of it: what used to be Cloud Functions (2nd gen) is called Cloud Run functions and is deployed as a Cloud Run service, either with gcloud run deploy --function or with the older gcloud functions deploy path, and the original runtime is now Cloud Run functions (1st gen). Because a service is one command away from a public HTTPS URL, the defaults deserve attention. Services run as the Compute Engine default service account, which in many projects still holds Editor, so a code injection bug becomes project-wide write access. A single --allow-unauthenticated grants roles/run.invoker to allUsers. Ingress is open to the internet, egress bypasses your VPC firewall, and database passwords sit in plaintext environment variables visible to anyone with Viewer. Each of these has a setting and, usually, an organization policy constraint to lock it.

Baseline controls

Set these per service, and enforce the ones that have constraints at the folder or organization level. CIS IDs refer to the CIS GCP Foundations Benchmark v5.0.1.

ControlWhyHow to checkCIS / SCC
Run each service as a dedicated service accountDefault compute SA often holds Editorgcloud run services describe SERVICE --format="value(spec.template.spec.serviceAccountName)"n/a
Require IAM authentication for invocationNo anonymous callersgcloud run services get-iam-policy SERVICEn/a
Restrict ingress to internal or load balancerRemoves direct internet exposuregcloud run services describe SERVICEALLOWED_INGRESS_ORG_POLICY
Put IAP in front of internal web appsPer-user access with contextgcloud run services describe SERVICE (Iap Enabled)n/a
Route all egress through your VPCFirewall rules and NAT applyvpc-access-egress annotation in describen/a
Inject secrets from Secret ManagerEnv vars are readable with Viewergcloud run services describe SERVICE --format=yamlCIS 1.18, SECRETS_IN_ENVIRONMENT_VARIABLES
Keep credentials out of imagesImage layers are easy to pull and readSCC findings for the projectSECRETS_IN_CLOUD_RUN
Enforce Binary AuthorizationOnly approved images deployrun.allowedBinaryAuthorizationPolicies policyn/a
Encrypt with CMEK where requiredKey revocation stops the service--key value in describen/a
Scan images in Artifact RegistryFind vulnerable packages before deploygcloud artifacts docker images describe IMAGE --show-package-vulnerabilityn/a
Enforce settings with org policyStops drift on new servicesgcloud org-policies list --project=PROJECT_IDn/a

Dedicated runtime service account

Every Cloud Run service, job and function runs as a service account and receives its tokens from the metadata server. If you do not choose one, Cloud Run and Cloud Run functions use the Compute Engine default service account (PROJECT_NUMBER-compute@developer.gserviceaccount.com), and 1st gen functions use the App Engine default service account (PROJECT_ID@appspot.gserviceaccount.com). Both received roles/editor automatically in older projects.

Create one service account per service, grant it only what the code calls, and attach it at deploy time:

gcloud iam service-accounts create website-run \
  --project=prj-website-prod --display-name="website Cloud Run runtime"

gcloud storage buckets add-iam-policy-binding gs://website-uploads \
  --member="serviceAccount:website-run@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/storage.objectUser"

gcloud run deploy website \
  --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/website:1.4.2 \
  --service-account=website-run@prj-website-prod.iam.gserviceaccount.com

The deployer (a person or a CI identity) needs roles/iam.serviceAccountUser on that one service account, not on the project, or it could deploy code running as any service account. Stop the automatic Editor grant to default service accounts with iam.automaticIamGrantsForDefaultServiceAccounts, as described on the IAM page.

Console: Cloud Run > service > Edit and deploy new revision > Security.

Authentication and ingress

Ingress and authentication are separate layers. Ingress decides which network paths can reach the service; the invoker IAM check decides which identities may call it. Configure both.

Require authentication

By default, a new service requires the caller to hold roles/run.invoker (permission run.routes.invoke). --allow-unauthenticated grants that role to allUsers. Keep it off for anything that is not a public website or a public API:

gcloud run deploy orders-api --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/orders:2.0.1 \
  --no-allow-unauthenticated

gcloud run services add-iam-policy-binding orders-api --region=europe-west1 \
  --member="serviceAccount:website-run@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/run.invoker"

Service-to-service callers send a Google-signed ID token whose audience is the receiving service URL. Pub/Sub push subscriptions, Cloud Scheduler and Eventarc triggers use their own service account with run.invoker on the target.

Find public services across the organization:

gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:allUsers policy:roles/run.invoker"

allUsers and domain restricted sharing

If you enforce iam.allowedPolicyMemberDomains (or iam.managed.allowedPolicyMembers), granting run.invoker to allUsers fails, which is the point. For the services that really must be public, Cloud Run offers a separate switch that disables the invoker IAM check without an allUsers binding:

gcloud run services update website --region=europe-west1 --no-invoker-iam-check

That switch bypasses your domain restriction, so control it with the managed constraint run.managed.requireInvokerIam, enforced everywhere and relaxed only on the projects that host public frontends:

name: folders/FOLDER_ID/policies/run.managed.requireInvokerIam
spec:
  rules:
    - enforce: true

Ingress settings

--ingress accepts all (default), internal, and internal-and-cloud-load-balancing. internal admits traffic from VPC networks in the project or Shared VPC, from the same VPC Service Controls perimeter, and from some Google services such as Pub/Sub, Eventarc and Cloud Scheduler in the same project or perimeter. internal-and-cloud-load-balancing adds an external Application Load Balancer, where you attach Cloud Armor and your own certificate.

gcloud run services update website --region=europe-west1 \
  --ingress=internal-and-cloud-load-balancing \
  --no-default-url

--no-default-url disables the run.app URL, so the load balancer is the only way in. Enforce allowed values org-wide with run.allowedIngress (Cloud Run and Cloud Run functions) and cloudfunctions.allowedIngressSettings (1st gen only):

name: folders/FOLDER_ID/policies/run.allowedIngress
spec:
  rules:
    - values:
        allowedValues:
          - internal
          - internal-and-cloud-load-balancing
---
name: folders/FOLDER_ID/policies/cloudfunctions.allowedIngressSettings
spec:
  rules:
    - values:
        allowedValues:
          - ALLOW_INTERNAL_ONLY
          - ALLOW_INTERNAL_AND_GCLB
gcloud org-policies set-policy run-allowed-ingress.yaml

Existing services that violate run.allowedIngress keep working until their ingress is changed, so audit them separately.

IAP for internal web apps

For browser-based internal tools, Identity-Aware Proxy can be enabled directly on a Cloud Run service, no load balancer required. IAP authenticates the user with your identity provider, applies IAM and context-aware access, and then calls the service as the IAP service agent:

gcloud run deploy admin-portal --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/admin:1.0.0 \
  --no-allow-unauthenticated --iap

gcloud run services add-iam-policy-binding admin-portal --region=europe-west1 \
  --member="serviceAccount:service-PROJECT_NUMBER@gcp-sa-iap.iam.gserviceaccount.com" \
  --role="roles/run.invoker"

gcloud iap web add-iam-policy-binding \
  --member="group:support-team@example.com" \
  --role="roles/iap.httpsResourceAccessor" \
  --region=europe-west1 --resource-type=cloud-run --service=admin-portal

You cannot enable IAP on both a load balancer and the Cloud Run service it fronts; pick one. Because IAP replaces the caller identity, services that authenticate machine callers (Pub/Sub push, for example) belong behind a separate service. Verify with gcloud run services describe admin-portal --region=europe-west1, which shows Iap Enabled: true.

VPC egress

Without VPC configuration, outbound traffic leaves directly to the internet and your VPC firewall rules, Cloud NAT addresses and egress controls do not apply. Direct VPC egress places instances on a subnet in your VPC (a /26 or larger). With --vpc-egress=all-traffic, every outbound connection, including to public IPs, goes through the VPC:

gcloud run deploy website --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/website:1.4.2 \
  --network=vpc-prod --subnet=snet-run-europe-west1 \
  --network-tags=run-website \
  --vpc-egress=all-traffic

Then write egress firewall rules against the network tag, and use Cloud NAT if partners need a stable source IP. Serverless VPC Access connectors still work and are the only option for 1st gen functions (--vpc-connector and --egress-settings=all), but Direct VPC egress needs no extra VMs. Enforce the setting with run.allowedVPCEgress (which also requires a VPC connection), and for 1st gen with cloudfunctions.requireVPCConnector and cloudfunctions.allowedVpcConnectorEgressSettings:

name: folders/FOLDER_ID/policies/run.allowedVPCEgress
spec:
  rules:
    - values:
        allowedValues:
          - all-traffic

See VPC and firewall rules for the egress firewall design.

Secrets from Secret Manager

CIS 1.18 asks that function secrets are not stored in environment variables. Plaintext env vars are part of the service configuration and readable by anyone with run.services.get. Reference Secret Manager instead; Cloud Run resolves the value with the runtime service account, which needs roles/secretmanager.secretAccessor on that secret only:

gcloud run services update website --region=europe-west1 \
  --remove-env-vars=DB_PASSWORD \
  --set-secrets="DB_PASSWORD=db-password:5,/secrets/stripe/key=stripe-key:latest"

Environment variables are resolved at instance start, so pin a version and redeploy on rotation; mounted files with latest are fetched on read and follow rotation. Old revisions still carry old plaintext env vars, so delete revisions that hold them. Security Command Center reports SECRETS_IN_ENVIRONMENT_VARIABLES (after enabling the Sensitive Data Protection discovery for it) and SECRETS_IN_CLOUD_RUN for credentials found inside container images. Rotation, CMEK and access logging for the secrets themselves are on the Secret Manager page.

Supply chain: Artifact Registry and Binary Authorization

Image scanning

Store images in Artifact Registry and enable Artifact Analysis scanning, which scans images on push and keeps re-analyzing them as new vulnerabilities are published:

gcloud services enable containerscanning.googleapis.com --project=prj-website-prod

gcloud artifacts docker images describe \
  europe-docker.pkg.dev/prj-website-prod/app/website:1.4.2 \
  --show-package-vulnerability

Deploy by digest (@sha256:...) rather than by mutable tag in production, so what was scanned is what runs. For source and function deployments, --base-image with automatic base image updates lets Google patch the OS and language runtime layers without a rebuild.

Binary Authorization

Binary Authorization checks each deployment against a policy (for example, require an attestation from your CI pipeline after tests and scanning passed):

gcloud run deploy website --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/website@sha256:DIGEST \
  --binary-authorization=default

Make it mandatory with run.allowedBinaryAuthorizationPolicies set to default, so services without Binary Authorization cannot be deployed. Emergency deploys use --breakglass=JUSTIFICATION, which is logged and should page someone. For functions, exempt the build repository (REGION-docker.pkg.dev/PROJECT_ID/cloud-run-source-deploy/** for gcloud run deploy, .../gcf-artifacts/** for gcloud functions deploy) or attest those images too.

CMEK and data protection

By default, Cloud Run encrypts container images and data at rest with Google-managed keys. With CMEK, the service uses your Cloud KMS key, and you decide what happens when the key is revoked:

gcloud kms keys add-iam-policy-binding run-key \
  --keyring=run --location=europe-west1 --project=prj-kms \
  --member="serviceAccount:service-PROJECT_NUMBER@serverless-robot-prod.iam.gserviceaccount.com" \
  --role="roles/cloudkms.cryptoKeyEncrypterDecrypter"

gcloud run deploy website --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/website:1.4.2 \
  --key=projects/prj-kms/locations/europe-west1/keyRings/run/cryptoKeys/run-key \
  --post-key-revocation-action-type=shut-down \
  --encryption-key-shutdown-hours=2

Require CMEK with gcp.restrictNonCmekServices listing run.googleapis.com and cloudfunctions.googleapis.com, and restrict which key projects may be used with gcp.restrictCmekCryptoKeyProjects. Key management is covered on the Cloud KMS page.

Organization policy summary

ConstraintEffect
run.allowedIngressAllowed ingress values for Cloud Run and Cloud Run functions
run.allowedVPCEgressRequires VPC egress and allowed values
run.allowedBinaryAuthorizationPoliciesRequires Binary Authorization
run.managed.requireInvokerIamBlocks disabling the invoker IAM check
cloudfunctions.allowedIngressSettingsIngress values for 1st gen functions
cloudfunctions.allowedVpcConnectorEgressSettingsEgress values for 1st gen functions
cloudfunctions.requireVPCConnector1st gen functions must use a connector
cloudfunctions.restrictAllowedGenerationsSet to 2ndGen to stop new 1st gen functions
iam.allowedPolicyMemberDomainsBlocks allUsers invoker bindings

Rollout and dry-run guidance is on the Organization Policy page. Placing run.googleapis.com inside a VPC Service Controls perimeter adds a further layer: images must come from Artifact Registry inside the perimeter, and with internal ingress only callers inside it can reach services (see VPC Service Controls).

Logging and detection

Admin Activity logs (always on) record service creation, updates, deletions and IAM changes on run.googleapis.com and cloudfunctions.googleapis.com. Request logs for each service land in Cloud Logging under run.googleapis.com/requests. Alert on public invoker grants:

protoPayload.serviceName=("run.googleapis.com" OR "cloudfunctions.googleapis.com")
protoPayload.methodName:"SetIamPolicy"
protoPayload.request.policy.bindings.members=("allUsers" OR "allAuthenticatedUsers")

Also alert on:

  • service updates that change ingress to all, disable the invoker IAM check, or remove VPC egress;
  • deployments that use --breakglass for Binary Authorization;
  • a service's runtime service account changing to a default service account;
  • dry-run and enforcement violations of the run.* and cloudfunctions.* constraints in the audit logs.

In Security Command Center, route SECRETS_IN_ENVIRONMENT_VARIABLES, SECRETS_IN_CLOUD_RUN and container vulnerability findings for Cloud Run to the owning team (see Security Command Center).

Common mistakes

  • Deploying with the default compute service account because it "just works", which hands the code Editor in older projects.
  • Setting ingress=internal-and-cloud-load-balancing but leaving the run.app URL enabled and allUsers as invoker, then assuming Cloud Armor protects the service.
  • Granting deployers roles/iam.serviceAccountUser at project level, letting them run code as any service account.
  • Moving secrets to Secret Manager but keeping old revisions that still hold plaintext environment variables.
  • Using Direct VPC egress with private-ranges-only and believing egress firewall rules cover internet traffic.
  • Enabling IAP on the service and on the load balancer at the same time, or putting machine-to-machine endpoints behind IAP.
  • Leaving 1st gen functions outside the policy set because the run.* constraints do not apply to them.

References

About the author

Security engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.

Related services

All services