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.
| Control | Why | How to check | CIS / SCC |
|---|---|---|---|
| Remove Owner, Editor and Viewer bindings | Basic roles span every service | gcloud asset search-all-iam-policies --query="policy:roles/editor" | PRIMITIVE_ROLES_USED |
| Keep service accounts off admin and basic roles | Unattended identities are prime targets | IAM page, filter by service account | CIS 1.6, ADMIN_SERVICE_ACCOUNT |
| Grant Service Account User and Token Creator per service account | Project-level grants allow acting as every SA | gcloud projects get-iam-policy PROJECT_ID | CIS 1.7, OVER_PRIVILEGED_SERVICE_ACCOUNT_USER |
| Separate service account admin from service account use | One person should not create and use SAs | IAM page, filter by role | CIS 1.9, SERVICE_ACCOUNT_ROLE_SEPARATION |
| Restrict members to your own directory | Blocks Gmail accounts and allUsers | gcloud org-policies describe iam.allowedPolicyMemberDomains --organization=ORG_ID | CIS 1.2, NON_ORG_IAM_MEMBER |
| Stop the automatic Editor grant to default SAs | New projects otherwise start over-privileged | gcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --organization=ORG_ID | n/a |
| Block user-managed service account keys | Keys are long-lived bearer credentials | gcloud iam service-accounts keys list --managed-by=user | CIS 1.5, USER_MANAGED_SERVICE_ACCOUNT_KEY |
| Expire or rotate keys that must remain | Limits the life of a leaked key | iam.serviceAccountKeyExpiryHours policy | CIS 1.8, SERVICE_ACCOUNT_KEY_NOT_ROTATED |
| Federate external workloads instead of using keys | No stored secret to leak | gcloud iam workload-identity-pools list --location=global | n/a |
| Delete unused API keys | Every key is a credential | gcloud services api-keys list | CIS 1.13, API_KEY_EXISTS |
| Restrict API keys to apps and APIs | Limits what a leaked key can call | gcloud services api-keys describe KEY_ID | CIS 1.14, CIS 1.15 |
| Rotate API keys every 90 days | Bounds exposure of copied keys | createTime in api-keys list | CIS 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/editorcontains thousands of permissions, and Google adds more as services ship.roles/viewerreads metadata across the whole project, which is broader than it sounds. - Predefined roles: maintained by Google per service, such as
roles/storage.objectViewerorroles/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
TESTINGorNOT_SUPPORTEDlaunch 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.
| Need | Instead of Editor, grant |
|---|---|
| Deploy Cloud Run services | roles/run.developer plus roles/iam.serviceAccountUser on the runtime service account |
| Manage VMs | roles/compute.instanceAdmin.v1 |
| Read and write objects in one bucket | roles/storage.objectUser on that bucket |
| Query BigQuery | roles/bigquery.jobUser on the project, roles/bigquery.dataViewer on the dataset |
| Read logs | roles/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.serviceAccountUserorroles/iam.serviceAccountTokenCreatorat project level, which lets the holder become every service account in the project, including the most privileged. - Enforcing
iam.automaticIamGrantsForDefaultServiceAccountsand 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
- IAM roles and permissions overview, Google Cloud documentation
- Searching IAM policies with Cloud Asset Inventory, Google Cloud documentation
- Deny policies overview, Google Cloud documentation
- Privileged Access Manager overview, Google Cloud documentation
- Best practices for managing service account keys, Google Cloud documentation
- Configure Workload Identity Federation with deployment pipelines, Google Cloud documentation
- About security hardening with OpenID Connect, GitHub Docs
- CIS Google Cloud Platform Foundation Benchmark, Center for Internet Security
- T1098 Account Manipulation, MITRE ATT&CK
- NIST SP 800-53 Rev. 5, AC-6 Least Privilege, NIST
About the author
Florian AmetteSecurity engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.