Skip to content

04Identity and secretsService 4 of 13

IAMsecurity hardening

Least privilege in Google Cloud IAM: basic roles, recommendations, deny policies, PAM, service accounts and keys, Workload Identity Federation, API keys.

Baseline
12 controls
Category
Identity and secrets
Updated
Reading
12 min read

Identity and Access Management decides which principals can do what on which Google Cloud resources. Left alone, it drifts toward too much access: someone needs to unblock a deployment and gets Editor, a service account fails with a permission error and gets Owner, the Compute Engine default service account keeps the Editor role it received at creation, and a user-managed service account key ends up in a CI variable or a public Git repository. Leaked service account keys and over-privileged default service accounts are among the most common starting points in Google Cloud intrusions, because an attacker who lands on any of those identities inherits everything they hold. Hardening IAM is a repeatable loop: find broad grants, replace them with narrow ones, remove long-lived credentials, and stop new broad grants from appearing.

Baseline controls

These controls cover human access, service accounts, credentials and API keys; enforce the preventive ones at the organization node. CIS IDs refer to the CIS GCP Foundations Benchmark v5.0.1.

ControlWhyHow to checkCIS / SCC
Remove Owner, Editor and Viewer bindingsBasic roles span every servicegcloud asset search-all-iam-policies --query="policy:roles/editor"PRIMITIVE_ROLES_USED
Keep service accounts off admin and basic rolesUnattended identities are prime targetsIAM page, filter by service accountCIS 1.6, ADMIN_SERVICE_ACCOUNT
Grant Service Account User and Token Creator per service accountProject-level grants allow acting as every SAgcloud projects get-iam-policy PROJECT_IDCIS 1.7, OVER_PRIVILEGED_SERVICE_ACCOUNT_USER
Separate service account admin from service account useOne person should not create and use SAsIAM page, filter by roleCIS 1.9, SERVICE_ACCOUNT_ROLE_SEPARATION
Restrict members to your own directoryBlocks Gmail accounts and allUsersgcloud org-policies describe iam.allowedPolicyMemberDomains --organization=ORG_IDCIS 1.2, NON_ORG_IAM_MEMBER
Stop the automatic Editor grant to default SAsNew projects otherwise start over-privilegedgcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --organization=ORG_IDn/a
Block user-managed service account keysKeys are long-lived bearer credentialsgcloud iam service-accounts keys list --managed-by=userCIS 1.5, USER_MANAGED_SERVICE_ACCOUNT_KEY
Expire or rotate keys that must remainLimits the life of a leaked keyiam.serviceAccountKeyExpiryHours policyCIS 1.8, SERVICE_ACCOUNT_KEY_NOT_ROTATED
Federate external workloads instead of using keysNo stored secret to leakgcloud iam workload-identity-pools list --location=globaln/a
Delete unused API keysEvery key is a credentialgcloud services api-keys listCIS 1.13, API_KEY_EXISTS
Restrict API keys to apps and APIsLimits what a leaked key can callgcloud services api-keys describe KEY_IDCIS 1.14, CIS 1.15
Rotate API keys every 90 daysBounds exposure of copied keyscreateTime in api-keys listCIS 1.16, API_KEY_NOT_ROTATED

Basic, predefined and custom roles

Google Cloud has three kinds of roles:

  • Basic roles: roles/owner, roles/editor, roles/viewer. They predate IAM and span almost every service. roles/editor contains thousands of permissions, and Google adds more as services ship. roles/viewer reads metadata across the whole project, which is broader than it sounds.
  • Predefined roles: maintained by Google per service, such as roles/storage.objectViewer or roles/compute.instanceAdmin.v1.
  • Custom roles: permission sets you define at organization or project level. Use them when no predefined role fits, and own their maintenance: custom roles do not receive new permissions automatically, and permissions in TESTING or NOT_SUPPORTED launch stages are not guaranteed to work.

Inventory who has what

Cloud Asset Inventory searches IAM policies across the whole organization in one call, which per-project get-iam-policy cannot do at scale. You need roles/cloudasset.viewer at the organization.

# Every Owner or Editor binding in the organization
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:(roles/owner OR roles/editor)" \
  --format="table(resource,policy.bindings.role,policy.bindings.members)"

# Public or all-authenticated bindings
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:(allUsers OR allAuthenticatedUsers)"

# Everything one identity can reach
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:deploy-sa@prj-ci.iam.gserviceaccount.com"

Export the results to BigQuery or a spreadsheet and give each binding an owner. You cannot fix access you cannot attribute.

Replace basic roles

For each basic role binding, find out what the principal actually does and grant the narrowest predefined role on the narrowest resource. A bucket binding beats a project binding, which beats a folder binding.

NeedInstead of Editor, grant
Deploy Cloud Run servicesroles/run.developer plus roles/iam.serviceAccountUser on the runtime service account
Manage VMsroles/compute.instanceAdmin.v1
Read and write objects in one bucketroles/storage.objectUser on that bucket
Query BigQueryroles/bigquery.jobUser on the project, roles/bigquery.dataViewer on the dataset
Read logsroles/logging.viewer
gcloud storage buckets add-iam-policy-binding gs://app-uploads \
  --member="serviceAccount:app@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/storage.objectUser"

gcloud projects remove-iam-policy-binding prj-website-prod \
  --member="serviceAccount:app@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/editor"

Bind roles to groups, not users

Grant roles to Google groups (group:gcp-app-developers@example.com) rather than individual users. Joiners and leavers are then handled in your directory, access reviews become a group membership review, and a departed employee does not leave orphaned bindings in dozens of projects. Reserve direct user: bindings for break-glass accounts.

Console: IAM and admin > IAM.

Role recommendations and unused access

The IAM role recommender compares granted permissions with permissions actually used over the last 90 days and suggests smaller roles or removal. It is the fastest way to shrink access for identities whose real usage nobody knows.

gcloud recommender recommendations list \
  --project=PROJECT_ID \
  --location=global \
  --recommender=google.iam.policy.Recommender \
  --format="table(name.basename(),description,stateInfo.state)"

gcloud recommender recommendations mark-claimed RECOMMENDATION_ID \
  --project=PROJECT_ID --location=global \
  --recommender=google.iam.policy.Recommender --etag=ETAG

Recommendations reflect observed usage, so a quarterly batch job may look unused. Review before applying, especially for service accounts. Project-level recommendations are available to everyone; organization and folder level recommendations require Security Command Center Premium or Enterprise.

Activity Analyzer shows when a service account or key last authenticated. Disable service accounts with no authentication in 90 days, then delete them after a grace period:

gcloud policy-intelligence query-activity \
  --activity-type=serviceAccountLastAuthentication \
  --project=PROJECT_ID

gcloud iam service-accounts disable unused-sa@PROJECT_ID.iam.gserviceaccount.com

Conditions, deny policies and just-in-time access

Cleaning up once is not enough. These three mechanisms stop the next emergency from reintroducing Editor everywhere.

IAM conditions

Conditional bindings limit a role to a time window, a resource name prefix or a tag:

gcloud projects add-iam-policy-binding prj-website-prod \
  --member="user:contractor@example.com" \
  --role="roles/compute.instanceAdmin.v1" \
  --condition='expression=request.time < timestamp("2026-12-31T00:00:00Z"),title=expires-end-2026'

Conditions cannot be used with basic roles, and not every service evaluates every attribute, so check the resource attribute support list before relying on a resource.name condition.

Deny policies

Deny policies are evaluated before allow policies and win regardless of the roles a principal holds. Attach them to the organization, a folder or a project. A common pattern is to deny IAM changes on production to everyone except a security group:

{
  "displayName": "Only security admins change IAM on production",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": ["principalSet://goog/public:all"],
        "exceptionPrincipals": [
          "principalSet://goog/group/gcp-security-admins@example.com"
        ],
        "deniedPermissions": [
          "cloudresourcemanager.googleapis.com/projects.setIamPolicy",
          "cloudresourcemanager.googleapis.com/folders.setIamPolicy"
        ]
      }
    }
  ]
}
gcloud iam policies create deny-iam-changes \
  --attachment-point="cloudresourcemanager.googleapis.com%2Ffolders%2FFOLDER_ID" \
  --kind=denypolicies \
  --policy-file=deny-iam-changes.json

Not every permission is supported in deny policies, so check the supported list first.

Privileged Access Manager

Some people genuinely need elevated access occasionally: an incident responder, an SRE during a migration. Privileged Access Manager (PAM) turns standing grants into entitlements that eligible users request for a bounded duration, with justification and optional approval. PAM removes the binding when the grant expires, and every request and approval is logged.

# entitlement.yaml
privilegedAccess:
  gcpIamAccess:
    resourceType: cloudresourcemanager.googleapis.com/Folder
    resource: //cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    roleBindings:
      - role: roles/resourcemanager.projectIamAdmin
maxRequestDuration: 7200s
eligibleUsers:
  - principals:
      - group:sre-oncall@example.com
approvalWorkflow:
  manualApprovals:
    requireApproverJustification: true
    steps:
      - approvalsNeeded: 1
        approvers:
          - principals:
              - group:gcp-security-admins@example.com
requesterJustificationConfig:
  unstructured: {}
gcloud pam entitlements create prod-iam-admin \
  --entitlement-file=entitlement.yaml \
  --location=global --folder=FOLDER_ID

# An eligible user requests a grant
gcloud pam grants create \
  --entitlement=prod-iam-admin \
  --requested-duration=3600s \
  --justification="INC-1234 rotate compromised binding" \
  --location=global --folder=FOLDER_ID

Service accounts

Service accounts are the identities your workloads run as. Three defaults cause most of the trouble.

Default service accounts. Enabling Compute Engine creates PROJECT_NUMBER-compute@developer.gserviceaccount.com, and App Engine creates PROJECT_ID@appspot.gserviceaccount.com. Unless prevented, both receive roles/editor on the project automatically, and many services (VMs, GKE nodes, Cloud Run, older Cloud Build setups) use them when you do not pick another identity. Any code running as them can modify almost anything in the project. Create a dedicated, narrowly scoped service account per workload instead (see Compute Engine and Cloud Run), and enforce the constraints that stop the automatic grant:

# Boolean constraint: no automatic role grant at creation
name: organizations/ORG_ID/policies/iam.automaticIamGrantsForDefaultServiceAccounts
spec:
  rules:
    - enforce: true
---
# Managed constraint: Editor or Owner can never be granted to the defaults
name: organizations/ORG_ID/policies/iam.managed.preventPrivilegedBasicRolesForDefaultServiceAccounts
spec:
  rules:
    - enforce: true
gcloud org-policies set-policy default-sa-grants.yaml

Neither constraint is retroactive. Remove the Editor binding from existing default service accounts yourself, after checking with Activity Analyzer and the role recommender what they really use.

Impersonation roles. roles/iam.serviceAccountUser (attach a service account to a resource) and roles/iam.serviceAccountTokenCreator (mint tokens for it) granted at project level let the holder act as every service account in the project, including the most privileged one. That is a classic privilege escalation path. Grant them on the individual service account:

gcloud iam service-accounts add-iam-policy-binding \
  runtime@prj-website-prod.iam.gserviceaccount.com \
  --member="group:app-deployers@example.com" \
  --role="roles/iam.serviceAccountUser"

Separation of duties. People who create and manage service accounts (roles/iam.serviceAccountAdmin) should not also be able to use them (roles/iam.serviceAccountUser), per CIS 1.9.

Impersonation for humans

Developers and Terraform operators should never download keys. Grant roles/iam.serviceAccountTokenCreator on one service account and impersonate it, which issues short-lived tokens and logs both the user and the service account:

gcloud config set auth/impersonate_service_account \
  terraform@prj-bootstrap.iam.gserviceaccount.com

Service account keys

A user-managed service account key is a long-lived credential, valid until someone deletes it, that grants whatever the service account can do. Keys end up in CI variables, download folders, container images and Git history. Google-managed keys rotate automatically and are not a concern; user-managed keys are.

Block key creation

Enforce the managed constraints at the organization. New organizations created since May 2024 receive them as part of the secure-by-default baseline; older organizations usually still rely on the legacy names iam.disableServiceAccountKeyCreation and iam.disableServiceAccountKeyUpload, which you will still see in existing policies.

name: organizations/ORG_ID/policies/iam.managed.disableServiceAccountKeyCreation
spec:
  rules:
    - enforce: true
---
name: organizations/ORG_ID/policies/iam.managed.disableServiceAccountKeyUpload
spec:
  rules:
    - enforce: true

Managed constraints support dryRunSpec, so you can log would-be violations for a week before enforcing. For the rare integration that only supports keys, grant a project-level exception and set iam.serviceAccountKeyExpiryHours (allowed values from 1h to 2160h) so keys created there expire. That constraint must replace the parent policy (inheritFromParent: false) and does not affect keys that already exist.

Respond to exposed keys

Google scans public repositories for service account keys. The iam.serviceAccountKeyExposureResponse constraint decides what happens next: DISABLE_KEY disables the exposed key automatically and writes an audit log entry, while WAIT_FOR_ABUSE opts out. Set it explicitly to DISABLE_KEY:

name: organizations/ORG_ID/policies/iam.serviceAccountKeyExposureResponse
spec:
  inheritFromParent: false
  rules:
    - values:
        allowedValues:
          - DISABLE_KEY

When a key leaks anyway: disable it, check the service account's activity in the audit logs from the key's creation onward (filter on protoPayload.authenticationInfo.serviceAccountKeyName), look for new keys, role bindings or service accounts created by it, then delete the key and rotate any secrets it could read.

Find and retire existing keys

# Organization-wide inventory
gcloud asset search-all-resources \
  --scope=organizations/ORG_ID \
  --asset-types=iam.googleapis.com/ServiceAccountKey \
  --format="table(name,parentFullResourceName,createTime)"

# User-managed keys in one project
for sa in $(gcloud iam service-accounts list --project=PROJECT_ID --format="value(email)"); do
  gcloud iam service-accounts keys list --iam-account="$sa" --managed-by=user
done

# Last use per key
gcloud policy-intelligence query-activity \
  --activity-type=serviceAccountKeyLastAuthentication \
  --project=PROJECT_ID

Retire keys in two steps: disable first (reversible), wait a week or two for breakage, then delete.

gcloud iam service-accounts keys disable KEY_ID \
  --iam-account=sa@PROJECT_ID.iam.gserviceaccount.com
gcloud iam service-accounts keys delete KEY_ID \
  --iam-account=sa@PROJECT_ID.iam.gserviceaccount.com

Workload Identity Federation

Most workloads never need a key. Code on Compute Engine, Cloud Run or GKE gets tokens from the metadata server or Workload Identity Federation for GKE (GKE). For code outside Google Cloud (GitHub Actions, GitLab CI, AWS, Azure, on-premises), Workload Identity Federation exchanges the platform's own short-lived token for a short-lived Google credential through the Security Token Service. Nothing secret is stored.

You create a workload identity pool, a provider describing the external issuer and its claim mapping, and IAM bindings for the federated principals.

GitHub Actions with OIDC

gcloud iam workload-identity-pools create github \
  --project=prj-ci --location=global \
  --display-name="GitHub Actions"

gcloud iam workload-identity-pools providers create-oidc github-oidc \
  --project=prj-ci --location=global \
  --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_owner_id=assertion.repository_owner_id,attribute.ref=assertion.ref" \
  --attribute-condition="assertion.repository_owner_id == '123456789' && assertion.ref == 'refs/heads/main'"

The attribute condition is the most important security setting. Without it, any GitHub repository could exchange a token against your pool, which is why Google now requires a condition for shared issuers such as GitHub. Prefer the numeric repository_owner_id and repository_id claims: they do not change when a repository is renamed, and a deleted organization name cannot be taken over to match them.

Grant access to one repository, either directly to the federated principal or through a service account it impersonates:

# Direct resource access
gcloud projects add-iam-policy-binding prj-website-prod \
  --role="roles/run.developer" \
  --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/my-org/website"

# Or impersonation of a deployer service account
gcloud iam service-accounts add-iam-policy-binding \
  deployer@prj-website-prod.iam.gserviceaccount.com \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/my-org/website"

PROJECT_NUMBER is the number of the project holding the pool. The workflow needs id-token: write:

permissions:
  contents: read
  id-token: write
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-oidc
          service_account: deployer@prj-website-prod.iam.gserviceaccount.com
      - uses: google-github-actions/setup-gcloud@v3
      - run: gcloud run deploy website --image=europe-docker.pkg.dev/prj-website-prod/app/website:${{ github.sha }} --region=europe-west1

GitLab uses the same OIDC flow (condition on assertion.namespace_path and assertion.ref_protected). AWS uses providers create-aws with a condition on the assumed role ARN. Once federation works, delete the old key from the CI secret store and from Google Cloud. To control which external issuers can be configured at all, use iam.workloadIdentityPoolProviders and iam.workloadIdentityPoolAwsAccounts.

API keys

API keys identify a project, not a user, and many Google APIs accept them as the only credential. A leaked unrestricted key can run up costs or read data from any API it can call. CIS 1.13 to 1.16 cover them.

# Inventory
gcloud services api-keys list --project=PROJECT_ID \
  --format="table(uid,displayName,createTime,restrictions)"

# Restrict to one API and one website
gcloud services api-keys update KEY_ID \
  --api-target=service=maps-backend.googleapis.com \
  --allowed-referrers="https://www.example.com/*"

# Rotate: create the replacement, deploy it, then delete the old key
gcloud services api-keys create --display-name="maps-web-2026-11" \
  --api-target=service=maps-backend.googleapis.com \
  --allowed-referrers="https://www.example.com/*"
gcloud services api-keys delete OLD_KEY_ID

Delete keys for services you no longer use, use server-side restrictions (--allowed-ips) for backend keys, and prefer service account authentication wherever the API supports it. The managed constraint iam.managed.disableServiceAccountApiKeyCreation blocks API keys bound to service accounts unless they are limited to allowed services.

Restrict who can be granted access

iam.allowedPolicyMemberDomains limits bindings to principals from your Cloud Identity customer IDs, which also blocks allUsers and allAuthenticatedUsers. Its managed successor iam.managed.allowedPolicyMembers takes principal sets and individual members as parameters. Details and rollout advice live on the Organization Policy page. Public endpoints that must stay open (a public website on Cloud Run, for example) use service-specific mechanisms such as disabling the Cloud Run invoker check, not an exception to this constraint.

Logging and detection

Admin Activity audit logs record every SetIamPolicy call, service account and key change, and are always on. Security Token Service exchanges and GenerateAccessToken impersonation calls on iamcredentials.googleapis.com are Data Access logs, which you must enable (see Cloud Logging). Alert on:

-- New Owner or Editor binding anywhere
protoPayload.methodName="SetIamPolicy"
protoPayload.serviceData.policyDelta.bindingDeltas.action="ADD"
protoPayload.serviceData.policyDelta.bindingDeltas.role=("roles/owner" OR "roles/editor")
-- Service account key created or uploaded
protoPayload.serviceName="iam.googleapis.com"
protoPayload.methodName=("google.iam.admin.v1.CreateServiceAccountKey" OR "google.iam.admin.v1.UploadServiceAccountKey")

Also alert on changes to workload identity pools and providers (UpdateWorkloadIdentityPoolProvider, especially attribute condition edits), custom role changes (CIS 2.7), and impersonation of highly privileged service accounts by unexpected principals. In Security Command Center, route PRIMITIVE_ROLES_USED, ADMIN_SERVICE_ACCOUNT, USER_MANAGED_SERVICE_ACCOUNT_KEY and NON_ORG_IAM_MEMBER findings to the owning team (see Security Command Center). MITRE ATT&CK tracks new role bindings and extra credentials as account manipulation (T1098).

Common mistakes

  • Granting roles/iam.serviceAccountUser or roles/iam.serviceAccountTokenCreator at project level, which lets the holder become every service account in the project, including the most privileged.
  • Enforcing iam.automaticIamGrantsForDefaultServiceAccounts and assuming the job is done: existing default service accounts keep their Editor binding until you remove it.
  • Creating a Workload Identity Federation provider for GitHub without a tight attribute condition, or conditioning on a repository name instead of the numeric ID.
  • Applying role recommendations blindly to service accounts used by infrequent jobs, then breaking the quarterly run.
  • Deleting service account keys without disabling them first, so the first sign of a dependency is a production outage.
  • Leaving API keys unrestricted because "it is only for Maps", then paying for someone else's traffic.
  • Binding roles to individual users, so offboarding misses access granted directly in projects.

References

About the author

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

Related services

All services