A Google Cloud service account key is a private key that never expires by default, works from anywhere on the internet and carries every permission its service account holds. Keys turn up in Git history, container images, CI variables, laptops and backup archives, and a leaked key usually works until someone notices. This guide focuses on one narrow question: how to get user-managed keys out of an organisation, lock down the few that must remain, and detect misuse. It is written for cloud platform engineers, Google Cloud administrators, security architects and the teams who own CI/CD and multicloud integrations.
This is an independent guide from NHI Mgmt Group, based on Google Cloud's public documentation as of November 2026. It is not sponsored or reviewed by Google Cloud. Product features change, so confirm settings against Google Cloud's current documentation.
Key takeaways
- The goal is zero keys, not better keys. Attached service accounts, impersonation and Workload Identity Federation issue short-lived tokens (one hour by default) and remove the long-lived secret altogether.
- Block keys at the organisation root. The constraints
iam.managed.disableServiceAccountKeyCreationandiam.managed.disableServiceAccountKeyUploadstop new keys; they are enforced by default only for organisations created on or after 3 May 2024, and they are not retroactive. - Existing keys need an inventory and a usage check. List user-managed keys per service account, then use the key authentication metric and Activity Analyzer to separate live keys from dead ones before you disable anything.
- Disabling a key does not revoke tokens already minted from it. For a confirmed compromise, disable the key and also contain the service account, because short-lived credentials issued earlier remain valid until they expire.
- Exceptions must be narrow and expiring. Where a key is unavoidable, use an uploaded public key generated on the target host or in an HSM or TPM, a project-level exception, a set expiry and a named owner.
How identity and access work in Google Cloud service accounts
A service account is a Google Cloud principal for a workload. It authenticates with key pairs, and Google documents two kinds:
| Key pair type | Who holds the private key | Rotation | Typical use |
|---|---|---|---|
Google-owned and managed (SYSTEM_MANAGED) | Google, in escrow; you can never read it | Rotated by Google, probabilistically, for actively used signing keys | Short-lived credentials via the Service Account Credentials API, attached service accounts on Compute Engine, App Engine and other services |
User-managed (USER_MANAGED), created by the IAM API | You: Google returns the private key once and stores only the public part | Your responsibility; no expiry unless a constraint sets one | Downloaded JSON key files used by client libraries, scripts and third-party tools |
| User-managed, uploaded public key | You: the key pair is generated outside Google, so Google never sees the private key | Your responsibility; the X.509 certificate can carry a Valid To date | Hosts that generate keys in an HSM or TPM, or where private keys must not travel between people |
Each service account can hold up to 10 user-managed keys. Anyone holding a key file can mint OAuth 2.0 access tokens as the service account, from any network, until the key is disabled, deleted or expires.
The alternatives all end in the same place, a short-lived OAuth 2.0 access token that expires after one hour by default:
- Attached service account: a Compute Engine VM, Cloud Run service, Cloud Functions function or GKE node uses a service account attached to the resource, and Application Default Credentials fetch tokens from the metadata server. No key file exists.
- Impersonation: a human or workload that already has an identity calls the Service Account Credentials API. It needs
iam.serviceAccounts.getAccessToken, usually through the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) granted on the target service account. Developers usegcloud --impersonate-service-accountorgcloud auth application-default login --impersonate-service-accountinstead of downloading a key. - Workload Identity Federation: workloads on AWS, Azure, on-premises Active Directory (AD FS), GitHub, GitLab, Kubernetes or any OIDC or SAML 2.0 provider exchange their native credential with the Security Token Service for a federated token. X.509 client certificates are also supported. See the Workload Identity Federation Guide.
- Workload Identity Federation for GKE: Kubernetes service accounts map to Google Cloud identities, removing the need to mount key files into pods. See the GKE Identity Hardening Guide.
Choosing a replacement for each key
| Where the key is used today | Keyless replacement | Watch for |
|---|---|---|
| Workload on Compute Engine, Cloud Run, Cloud Functions or App Engine | Attached service account and Application Default Credentials | Do not reuse the default compute service account; attach a dedicated one per workload |
| Pod on GKE | Workload Identity Federation for GKE | Node service account permissions still apply to anything that reaches the metadata server |
| GitHub Actions or GitLab CI | Workload Identity Federation with an OIDC provider and an attribute condition on repository and branch | A provider with no attribute condition can accept tokens from any repository on the platform |
| Workload on AWS or Azure | Workload Identity Federation with the AWS or Azure provider type | Separate pools for development, staging and production |
| On-premises server | Federation via AD FS, OIDC or X.509 certificates; otherwise an uploaded HSM or TPM key | Certificate lifecycle becomes the new dependency |
| Developer laptop | User credentials plus impersonation | Token Creator grants should be scoped to specific service accounts, not the project |
| Third-party SaaS that only accepts a JSON key | Ask the vendor for federation support; otherwise a documented exception | Keys held by a vendor sit outside your monitoring; see the OWASP NHI Top 10 NHI3 Vulnerable Third-Party NHI Guide |
Admin roles and privileged access
Key risk is often a role problem. Google warns that a principal who can create or upload keys for a service account can act as that service account, so key permissions are privilege escalation paths.
- Editor and Owner: Google advises against using the Editor role in projects that allow key creation or upload, because it lets a user create keys and escalate access. Replace basic roles with predefined or custom roles, or block keys in that project.
- Key creation permission:
iam.serviceAccountKeys.creategoverns both creating and uploading keys. Grant it to as few principals as possible and only on specific service accounts, never at folder or organisation level. - Token Creator:
roles/iam.serviceAccountTokenCreatoris the keyless equivalent of holding a key. Grant it on individual service accounts and review it like any privileged entitlement. - Organisation policy administration: changing the key constraints needs
orgpolicy.policy.set, which Owner and Editor do not include. Keep the Organization Policy Administrator role with a small platform team so project owners cannot quietly lift the block. - Default service accounts: the constraint
iam.automaticIamGrantsForDefaultServiceAccountsstops the automatic Editor grant to default service accounts (enforced by default for organisations created on or after 3 May 2024). A key on a default service account with Editor is one of the worst combinations you can find.
See the Google Cloud IAM and Service Accounts Guide for role design, IAM conditions and deny policies, and the OWASP NHI Top 10 NHI5 Overprivileged NHI Guide for the over-privilege pattern.
Integrations, API tokens and service accounts
The constraints below are the main control plane for keys. All are set in Organization Policy and none are retroactive: they govern new keys, not keys that already exist.
| Constraint | Effect | Recommended setting |
|---|---|---|
iam.managed.disableServiceAccountKeyCreation (legacy iam.disableServiceAccountKeyCreation) | Blocks creation of new service account keys; the legacy constraint also blocks Cloud Storage HMAC keys | Enforce at the organisation root; exceptions at project level only. Google recommends the managed versions |
iam.managed.disableServiceAccountKeyUpload (legacy iam.disableServiceAccountKeyUpload) | Blocks uploading external public keys | Enforce at the root; lift only where an HSM or TPM upload pattern is approved |
constraints/iam.serviceAccountKeyExpiryHours | Sets validity for newly created keys; allowed values 1h, 8h, 24h, 168h, 336h, 720h, 1440h, 2160h | Set on exception projects; cannot be merged with a parent policy |
iam.serviceAccountKeyExposureResponse | What Google does when it detects a publicly exposed key: DISABLE_KEY or WAIT_FOR_ABUSE | DISABLE_KEY (the default when unset since 16 June 2024); never set WAIT_FOR_ABUSE |
constraints/iam.allowServiceAccountCredentialLifetimeExtension | Allows listed service accounts to request access tokens of up to 43,200 seconds (12 hours) instead of 3,600 | Leave empty unless a batch job genuinely needs it |
iam.disableCrossProjectServiceAccountUsage | Prevents attaching a service account to resources in other projects | Enforce unless a shared-services design needs it |
Note the trade-off on expiry. Google suggests key expiry for temporary access, such as non-production development or third-party tools that only support keys, and warns against relying on it in production or CI pipelines, where an unexpected expiry causes an outage. In production, prefer removing the key over setting a timer on it.
When a key cannot be avoided
- Generate the key pair where it will be used. Create a self-signed RSA 2048-bit certificate on the target machine, send only the certificate to the person who can upload it, and upload it to the service account. Where possible generate the key in an HSM or TPM so the private key is never in clear text.
- One key per machine, one service account per application. Audit log entries carry
principalEmailandserviceAccountKeyName, so dedicated keys let you trace activity to a host. - Store it deliberately. Write the key straight to its destination with
gcloud iam service-accounts keys createrather than leaving it in a downloads folder. Avoid general file systems; if you must, restrict access, enable file access auditing and encrypt the disk. Google advises against putting service account keys in Secret Manager or other cloud secret stores: the application needs a Google Cloud identity to read the secret, and that identity can authenticate directly instead. - Never in code, images or binaries. Keep keys out of source repositories (history keeps copies) and out of application binaries and container layers.
- Rotate on a schedule and on suspicion. Keep a tested rotation procedure so you can replace a key quickly. See the Secrets Rotation Runbook Template.
Logging and detection
Three telemetry sources answer different questions: who changed keys, which keys are still used, and whether a key has leaked.
| Source | What it shows | Detail |
|---|---|---|
| Cloud Audit Logs, Admin Activity | Key lifecycle events | protoPayload.methodName values google.iam.admin.v1.CreateServiceAccountKey, UploadServiceAccountKey and DeleteServiceAccountKey; GetServiceAccountKey and ListServiceAccountKeys appear in Data Access logs |
Cloud Monitoring metric iam.googleapis.com/service_account/key/authn_events_count | Authentication events per key (filter on metric.labels.key_id) | Retained for 6 weeks; export to BigQuery for longer. Disabled keys are excluded; listing keys during some flows (for example signed URLs) can register events without real use |
Activity Analyzer, activity type serviceAccountKeyLastAuthentication | Last authentication date per key | Query with gcloud policy-intelligence query-activity; Pre-GA; timestamps fixed at 07:00 UTC; domain-wide delegation use is not tracked |
| Service account insights | Service accounts unused for 90 days | Candidates for disabling the account, which removes all its keys from use |
| Security Command Center, Event Threat Detection | Threat findings such as Persistence: Service Account Key Created, Initial Access: Leaked Service Account Key Used and Initial Access: Dormant Service Account Key Created | Availability depends on the Security Command Center tier |
| Key exposure response | Keys Google detected as public and disabled | Disabled keys carry disable_reason, extended_status and extended_status_message; Google does not guarantee detection |
High-value alerts: any CreateServiceAccountKey or UploadServiceAccountKey outside an approved exception project; any change to the key constraints; key authentication from an unexpected network or region for a key bound to one host; and use of a key that Activity Analyzer had reported as dormant. In MITRE ATT&CK terms, creating a new key is T1098.001 Additional Cloud Credentials, harvesting key files is T1552.001 Credentials In Files and using them is T1078.004 Cloud Accounts.
Metrics that show progress
- User-managed keys: total count, trending to zero, broken down by project and owner.
- Key age: number of keys older than 90 days, and the oldest key in the estate.
- Dormant keys: keys with no authentication in the last 30 or 90 days that are still enabled.
- Policy coverage: percentage of projects inheriting the creation and upload blocks without an exception.
- Exception hygiene: exceptions with a named owner, a review date and an expiry setting.
- Federation adoption: share of CI/CD pipelines and external workloads authenticating through Workload Identity Federation.
Hardening baseline
Retiring keys in the wrong order breaks production. Work in this sequence:
- Inventory. For each project, list keys with
gcloud iam service-accounts keys list --iam-account=SA_EMAILor the REST method withkeyTypes=USER_MANAGED. Record key ID, created and expiry times,keyOrigin(generated or uploaded), the service account's roles and an owner. Feed the result into your NHI inventory; see the Service Account Inventory Template. - Measure use. Join the inventory with the key authentication metric and Activity Analyzer. Classify every key as active, dormant or never used.
- Freeze growth. Enforce the managed creation and upload constraints at the organisation root and set
iam.serviceAccountKeyExposureResponsetoDISABLE_KEY. Create exception projects for the remaining known uses so teams are not blocked; set key expiry there. - Remove dead keys. Disable dormant and never-used keys with
gcloud iam service-accounts keys disable(the console can view but not disable keys). Disabling is reversible; wait at least one full business cycle, including month-end and quarterly jobs, then delete. - Migrate active keys. Move each workload to the replacement in the table above, starting with CI/CD and anything holding high-privilege roles. Run old and new authentication side by side, confirm the key's authentication count falls to zero, then disable and later delete it.
- Close exceptions. Review each exception project quarterly; when the last key is gone, remove the project from the exception so it inherits the block.
Rollback: if a disabled key turns out to be needed, re-enable it with gcloud iam service-accounts keys enable, record the owner and the use, and put it on the migration list. Never lift the root constraint to fix one workload.
Decision guidance
- Small organisations with one organisation node can usually enforce the block immediately, because the number of keys is small enough to migrate by hand in a sprint.
- Large or older organisations (created before May 2024) should expect hundreds of legacy keys. Freeze growth first, then work through dead keys before active ones, since dead keys are pure risk with no migration cost.
- Uploaded versus generated keys: where a key must exist, an uploaded key from an HSM or TPM is stronger because the private key never leaves hardware; Google notes such keys may only need rotation on suspected compromise.
- Federation versus impersonation chain: Google recommends granting roles directly to federated principals where the API supports it; impersonating a service account (requiring
roles/iam.workloadIdentityUser) is the fallback and adds a second identity to govern.
Common misconfigurations
- Keys baked into images and build artefacts. A credential inside a container image or build output is readable by anyone who can pull it.
- Keys in Git history. Deleting the file does not delete the commit. Google's guidance is to delete the key in IAM as soon as it has been committed, and to scan with tools such as GitHub secret scanning or truffleHog in pre-commit hooks and CI. See the OWASP NHI Top 10 NHI2 Secret Leakage Guide and the Git Secret Scanning Guide.
- Assuming the constraint cleaned up old keys. The creation block is not retroactive. Organisations that enforced it in 2024 and stopped there often still hold years-old keys with Editor.
- Disabling the key and declaring the incident closed. Short-lived credentials already issued from the key remain valid. Google's guidance is that revoking them requires disabling or deleting the service account itself. See the Cloud Access Key Leak Playbook.
- Federation without attribute conditions. An OIDC provider for a CI platform with no condition on repository or organisation lets other tenants on the same platform present valid tokens. Google describes attribute conditions as the guard against this confused deputy problem.
- Shared keys across hosts and teams. One key copied to many machines destroys attribution in audit logs and makes rotation a coordinated outage, which is why it never happens. See the OWASP NHI Top 10 NHI9 NHI Reuse Guide.
Framework mapping
| Framework | Reference | How keys relate |
|---|---|---|
| OWASP Non-Human Identities Top 10 | NHI7 Long-Lived Secrets; NHI2 Secret Leakage | Non-expiring JSON keys are the textbook long-lived secret; see the OWASP NHI Top 10 NHI7 Long-Lived Secrets Guide |
| NIST CSF 2.0 | PR.AA-01, PR.AA-05 | Credentials for services are managed; permissions follow least privilege |
| NIST SP 800-53 Rev. 5 | IA-5 Authenticator Management; AC-2 Account Management; AC-6 Least Privilege; SC-12 Cryptographic Key Establishment and Management; AU-6 Audit Record Review | Key lifecycle, ownership, scope of the bound service account and review of key events |
| CIS Controls v8.1 | Control 5 Account Management; Control 6 Access Control Management | Service accounts and their credentials are accounts to inventory and govern; see the CIS Control 5 Account Management Guide |
Practitioner checklist
- Enforce
iam.managed.disableServiceAccountKeyCreationandiam.managed.disableServiceAccountKeyUploadat the organisation root, with project-level exceptions only. - Confirm
iam.serviceAccountKeyExposureResponseisDISABLE_KEYeverywhere and that no project overrides it. - Inventory every user-managed key with owner, age, origin, roles and last authentication date.
- Disable keys unused for 90 days, wait a full business cycle, then delete them.
- Move CI/CD to Workload Identity Federation with attribute conditions on repository and branch.
- Replace developer key downloads with impersonation and scope Token Creator to individual service accounts.
- Remove Editor and Owner from projects that still allow keys, and from every default service account.
- Set key expiry on exception projects and review each exception quarterly.
- Alert on key creation, key upload and changes to key constraints; export key usage metrics to BigQuery for history.
- Rehearse a leaked-key response that contains the service account, not only the key.
Standards and references
- Google Cloud: Best practices for managing service account keys
- Google Cloud: Service account credentials
- Google Cloud: Restricting service account usage
- Google Cloud: Monitor usage patterns for service accounts and keys
- Google Cloud: View recent usage for service accounts and keys (Activity Analyzer)
- Google Cloud: Workload Identity Federation
- Google Cloud: Use service account impersonation
- NIST: SP 800-53 Rev. 5
Related NHI Mgmt Group resources: Google Cloud IAM and Service Accounts Guide · Google Cloud Organization Policy Guide · Workload Identity Federation Guide · OWASP NHI Top 10 NHI7 Long-Lived Secrets Guide · Secrets Management Guide