Join our Newsletter — 33% off our NHI Course
Home› Guides› Google Cloud Service Account Keys Security Guide: Eliminating,…
Guide Non-Human Identity (NHI)

Google Cloud Service Account Keys Security Guide: Eliminating, Restricting and Rotating Keys

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 16 min read
On this page

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.disableServiceAccountKeyCreation and iam.managed.disableServiceAccountKeyUpload stop 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 typeWho holds the private keyRotationTypical use
Google-owned and managed (SYSTEM_MANAGED)Google, in escrow; you can never read itRotated by Google, probabilistically, for actively used signing keysShort-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 APIYou: Google returns the private key once and stores only the public partYour responsibility; no expiry unless a constraint sets oneDownloaded JSON key files used by client libraries, scripts and third-party tools
User-managed, uploaded public keyYou: the key pair is generated outside Google, so Google never sees the private keyYour responsibility; the X.509 certificate can carry a Valid To dateHosts 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 use gcloud --impersonate-service-account or gcloud auth application-default login --impersonate-service-account instead 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 todayKeyless replacementWatch for
Workload on Compute Engine, Cloud Run, Cloud Functions or App EngineAttached service account and Application Default CredentialsDo not reuse the default compute service account; attach a dedicated one per workload
Pod on GKEWorkload Identity Federation for GKENode service account permissions still apply to anything that reaches the metadata server
GitHub Actions or GitLab CIWorkload Identity Federation with an OIDC provider and an attribute condition on repository and branchA provider with no attribute condition can accept tokens from any repository on the platform
Workload on AWS or AzureWorkload Identity Federation with the AWS or Azure provider typeSeparate pools for development, staging and production
On-premises serverFederation via AD FS, OIDC or X.509 certificates; otherwise an uploaded HSM or TPM keyCertificate lifecycle becomes the new dependency
Developer laptopUser credentials plus impersonationToken Creator grants should be scoped to specific service accounts, not the project
Third-party SaaS that only accepts a JSON keyAsk the vendor for federation support; otherwise a documented exceptionKeys 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.create governs 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.serviceAccountTokenCreator is 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.automaticIamGrantsForDefaultServiceAccounts stops 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.

ConstraintEffectRecommended setting
iam.managed.disableServiceAccountKeyCreation (legacy iam.disableServiceAccountKeyCreation)Blocks creation of new service account keys; the legacy constraint also blocks Cloud Storage HMAC keysEnforce at the organisation root; exceptions at project level only. Google recommends the managed versions
iam.managed.disableServiceAccountKeyUpload (legacy iam.disableServiceAccountKeyUpload)Blocks uploading external public keysEnforce at the root; lift only where an HSM or TPM upload pattern is approved
constraints/iam.serviceAccountKeyExpiryHoursSets validity for newly created keys; allowed values 1h, 8h, 24h, 168h, 336h, 720h, 1440h, 2160hSet on exception projects; cannot be merged with a parent policy
iam.serviceAccountKeyExposureResponseWhat Google does when it detects a publicly exposed key: DISABLE_KEY or WAIT_FOR_ABUSEDISABLE_KEY (the default when unset since 16 June 2024); never set WAIT_FOR_ABUSE
constraints/iam.allowServiceAccountCredentialLifetimeExtensionAllows listed service accounts to request access tokens of up to 43,200 seconds (12 hours) instead of 3,600Leave empty unless a batch job genuinely needs it
iam.disableCrossProjectServiceAccountUsagePrevents attaching a service account to resources in other projectsEnforce 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

  1. 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.
  2. One key per machine, one service account per application. Audit log entries carry principalEmail and serviceAccountKeyName, so dedicated keys let you trace activity to a host.
  3. Store it deliberately. Write the key straight to its destination with gcloud iam service-accounts keys create rather 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.
  4. Never in code, images or binaries. Keep keys out of source repositories (history keeps copies) and out of application binaries and container layers.
  5. 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.

SourceWhat it showsDetail
Cloud Audit Logs, Admin ActivityKey lifecycle eventsprotoPayload.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_countAuthentication 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 serviceAccountKeyLastAuthenticationLast authentication date per keyQuery with gcloud policy-intelligence query-activity; Pre-GA; timestamps fixed at 07:00 UTC; domain-wide delegation use is not tracked
Service account insightsService accounts unused for 90 daysCandidates for disabling the account, which removes all its keys from use
Security Command Center, Event Threat DetectionThreat findings such as Persistence: Service Account Key Created, Initial Access: Leaked Service Account Key Used and Initial Access: Dormant Service Account Key CreatedAvailability depends on the Security Command Center tier
Key exposure responseKeys Google detected as public and disabledDisabled 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:

  1. Inventory. For each project, list keys with gcloud iam service-accounts keys list --iam-account=SA_EMAIL or the REST method with keyTypes=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.
  2. Measure use. Join the inventory with the key authentication metric and Activity Analyzer. Classify every key as active, dormant or never used.
  3. Freeze growth. Enforce the managed creation and upload constraints at the organisation root and set iam.serviceAccountKeyExposureResponse to DISABLE_KEY. Create exception projects for the remaining known uses so teams are not blocked; set key expiry there.
  4. 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.
  5. 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.
  6. 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

FrameworkReferenceHow keys relate
OWASP Non-Human Identities Top 10NHI7 Long-Lived Secrets; NHI2 Secret LeakageNon-expiring JSON keys are the textbook long-lived secret; see the OWASP NHI Top 10 NHI7 Long-Lived Secrets Guide
NIST CSF 2.0PR.AA-01, PR.AA-05Credentials for services are managed; permissions follow least privilege
NIST SP 800-53 Rev. 5IA-5 Authenticator Management; AC-2 Account Management; AC-6 Least Privilege; SC-12 Cryptographic Key Establishment and Management; AU-6 Audit Record ReviewKey lifecycle, ownership, scope of the bound service account and review of key events
CIS Controls v8.1Control 5 Account Management; Control 6 Access Control ManagementService accounts and their credentials are accounts to inventory and govern; see the CIS Control 5 Account Management Guide

Practitioner checklist

  • Enforce iam.managed.disableServiceAccountKeyCreation and iam.managed.disableServiceAccountKeyUpload at the organisation root, with project-level exceptions only.
  • Confirm iam.serviceAccountKeyExposureResponse is DISABLE_KEY everywhere 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

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.