Prepare and test your skills
Prepare and test your skills
Enforcing organizational guardrails and keyless alternatives replaces long-lived user-managed service account keys (opens in a new tab) with preventative policy and short-lived authentication. A user-managed key pair is a powerful credential where Google stores only the public portion and anyone holding the private key can act as the service account. Each service account can have up to 10 such keys. Keys are created either when the Identity and Access Management (IAM) API generates the pair and returns the private key, or when you generate the pair yourself and upload only the public key.
Organization Policy constraints are preventative guardrails that block user-managed key creation and upload across an organization, folder, or project hierarchy. The constraint constraints/iam.disableServiceAccountKeyCreation prevents principals from creating user-managed service account keys, while constraints/iam.disableServiceAccountKeyUpload prevents principals from uploading a public key for a service account. Because policy is inherited through the resource hierarchy, enforcement at the organization or folder level protects all child projects unless explicitly overridden. If an organization was created on or after May 3, 2024, both constraints are enforced by default as part of secure-by-default organization resources.
When key creation is blocked because federation is the intended path, additional organization policy constraints for workload identity federation control which external identity providers are allowed. The federation trust sits outside the service account: the external identity provider authenticates the workload, Google Cloud exchanges that proof for short-lived Google credentials, and no downloadable private key ever flows to the workload. Credentials acquired from an external source must still be validated before use.
The key-expiry guardrail limits how long newly created user-managed keys remain valid when temporary key use cannot yet be eliminated. By default a newly created user-managed key never expires, but the constraint constraints/iam.serviceAccountKeyExpiryHours sets an expiry time in hours that applies to all newly created keys under the project, folder, or organization where it is enforced. Existing keys are not affected, so the control constrains only future issuance. As a best practice, use short expiry times for temporary access:
Use expiry times for temporary cases such as developing code in a non-production environment for an application that can only authenticate with service account keys, or using a third-party tool that can only authenticate with service account keys. Avoid expiry times for production workloads where an expired key could cause an outage, for non-production workloads that need permanent access such as a continuous integration (CI) pipeline, and for key-rotation systems that already prevent use after a specified time. To help prevent outages, do not set an expiry time unless constraints/iam.disableServiceAccountKeyCreation has already been in place for an extended period, and work closely with users to confirm that no existing resource requires permanent keys.
Exam tip: Setting constraints/iam.serviceAccountKeyExpiryHours requires stopping enforcement of constraints/iam.disableServiceAccountKeyCreation, because expiry only applies when new keys can still be created.
Keyless authentication with Workload Identity Federation lets external and cross-cloud workloads obtain short-lived Google Cloud credentials without a service account key. The workload first authenticates to its external identity provider, then Workload Identity Federation exchanges that external proof for a short-lived Google access token, often combined with service account impersonation to act as a specific service account. The client library flow depends on a generated credential configuration file: the path to that file is stored in the GOOGLE_APPLICATION_CREDENTIALS environment variable, and Application Default Credentials (ADC) then selects the correct external-account client type from the configuration context. Never use a credential configuration that was not generated with the gcloud CLI unless the token_url, token_info_url, and service_account_impersonation_url fields are verified to point to a googleapis.com domain.
Service account impersonation generates short-lived credentials for a service account without holding its private key. The caller needs the iam.serviceAccounts.getAccessToken permission, which is included in the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator). For local development, the gcloud CLI can impersonate for all calls with gcloud config set auth/impersonate_service_account SERVICE_ACCT_EMAIL, or create a local ADC file with gcloud auth application-default login --impersonate-service-account=SERVICE_ACCT_EMAIL. The local ADC-file approach with impersonation is supported only for the Go, Java, Node.js, and Python client libraries. On Google Cloud, code running on a compute resource should instead use the credentials of the service account attached to that resource, which is the preferred method and avoids keys entirely.
Short-lived credential lifetimes create explicit tradeoffs between security and token-exchange cost. Configuring a short lifetime, for example 10 minutes, causes the library to initiate the entire token exchange flow every 10 minutes and calls the third-party token provider even if the third-party token is not expired. If a lifetime greater than one hour is required, the service account must be added as an allowed value in an Organization Policy Service that enforces the constraints/iam.allowServiceAccountCredentialLifetimeExtension constraint. For workforce identities, browser-based external account authorized user credentials created by gcloud auth application-default login --login-config=LOGIN_CONFIG store a refresh token at the well-known ADC location with a default lifetime of one hour, extendable to as high as 12 hours by changing the session duration of the workforce pool.
Auditing service account key inventory, activity, and usage patterns joins three signals — what keys exist, whether keys are still used, and who used a key for what. In Google Cloud, Cloud Asset Inventory provides the organization-wide list of keys, Cloud Monitoring and Policy Intelligence provide usage and privilege signals, and Cloud Audit Logs provide the attributable activity record. Together these signals let teams find unused, aged, or anomalous user-managed service account keys (opens in a new tab) and track unauthorized creation and out-of-band use across projects.
Cloud Asset Inventory is the source for discovering every user-managed service account key across an organization, because service accounts themselves belong to a single Google Cloud project and native insights must otherwise be checked project by project. A deployable reference architecture runs a daily data pipeline that queries Cloud Asset Inventory for keys, then combines that inventory with key-usage data and permission-usage data for the associated service account. The pipeline writes the joined result to a date-partitioned BigQuery table named sa_key_usage, which can be queried for specific keys or visualized in a dashboard tool to track migration and cleanup progress.
The sa_key_usage table answers the core inventory questions that drive prioritization and ownership assignment. The table shows how many persistent keys have been created as a high-level progress metric, and which projects and service accounts use keys so workload owners can be identified. The table flags inactive keys that can likely be deleted without owner review, and flags keys attached to overly privileged service accounts — especially those with Owner, Editor, or Viewer roles — by joining in role recommendations. Teams can enrich this base data with ownership information from a configuration management database (CMDB), governance information from project labels such as team or cost center, and environment information for keys used outside Google Cloud.
| Audit signal | Source system | Audit question answered |
|---|---|---|
| Key inventory | Cloud Asset Inventory export to BigQuery | Which persistent keys exist and in which projects and service accounts |
| Usage and privilege | Policy Intelligence insights, Key Authentication Events metric, role recommendations | Which keys are inactive and which keys are high-risk due to excess permissions |
| Activity and attribution | Cloud Audit Logs with principalEmail and serviceAccountKeyName | Which identity and key performed an action and from where |
Policy Intelligence and authentication metrics detect unused and risky keys by measuring last use, frequency, and excess privilege. Service account insights identify service accounts that have not authenticated in the past 90 days, while the Key Authentication Events metric in Cloud Monitoring shows when an individual service account key was last used and how often it was used to authenticate. Because both insights and metrics are scoped to the project that owns the service account, teams must aggregate them per project or rely on the centralized BigQuery export for an organization view before deciding a key is safe to disable.
Keys that show no recent usage or belong to inactive resources are quick-win candidates for disable-then-delete, after confirming there is no infrequent use case such as emergency production access. Keys attached to service accounts with role recommendations for unused or excessive permissions receive higher priority, since a leaked key for an over-privileged account enables broader privilege escalation and harder-to-repudiate actions. Applying the role recommendation first reduces the blast radius, then the key can be migrated to a keyless alternative or removed.
Exam tip: Service account insights cover 90 days of inactivity and Key Authentication Events show per-key last use, but both must be tracked individually for each project — only an aggregated Cloud Asset Inventory export gives an organization-wide view.
Cloud Audit Logs reconstruct which application and machine used a service account key by recording identity fields on every API action. All relevant log records contain principalEmail to identify the service account that initiated the activity, and many services also add serviceAccountKeyName to identify the exact key that authenticated the call. Attribution only works when teams isolate identity: a dedicated service account for each application keeps principalEmail from blending multiple applications together, and a dedicated key for each machine running the same application keeps serviceAccountKeyName from blending multiple hosts together.
Token-generation and impersonation activity requires specific log configuration and fields. Methods on iamcredentials.googleapis.com such as GenerateAccessToken, GenerateIdToken, and SignJwt audit service account token creation, but these logs flow only when Data Access audit logs are enabled. The field protoPayload.authenticationInfo.serviceAccountDelegationInfo.firstPartyPrincipal.principalEmail audits user and service account impersonation, while sts.googleapis.com exchange requests audit anomalous external identity assertions from workload identity federation. Data flows from the calling workload to the IAM Credentials or Security Token Service APIs, then into Cloud Audit Logs where alerts can trigger on unexpected methods, principals, or assertion patterns.
Security Command Center (SCC) with Event Threat Detection and Cloud Monitoring provide continuous tracking for unauthorized key creation and use outside expected boundaries. Cloud Monitoring watches for anomalies in service account key usage, including authentication from unexpected locations or clients, while logs from Chrome Enterprise Premium and VPC Service Controls detect out-of-perimeter access attempts made with stolen tokens. User-login signals from Google Workspace and Cloud Identity, exported to Cloud Logging, help distinguish a legitimate operator from an attacker reusing a leaked key, and findings can be forwarded to a security information and event management (SIEM) system or Google Security Operations for central response.
In Security Command Center, Event Threat Detection findings that matter for key auditing include:
Each finding links to recommended investigation steps, and the security operations center (SOC) needs prompt notification plus playbooks, tools, and cross-console access to act before a leaked key is exploited for persistence or privilege escalation.
Key lifecycle management for service accounts creates, distributes, rotates, disables, and deletes user-managed service account keys (opens in a new tab) so long-lived credentials remain usable only for as long as needed. Identity and Access Management (IAM) service account keys persist until they are explicitly removed, so any copy left in source code, application configuration, or a downloaded JSON file can be reused by an attacker even after access to the project is removed. A secure lifecycle therefore designs applications for non-disruptive rotation, automates renewal through managed secret systems and delivery pipelines, and pairs rapid disable and delete actions with containment of downstream authorization.
Rotation designed for non-disruptive replacement creates the successor credential before removing its predecessor so dependent workloads never lose authentication. Projects must be designed to allow this pattern for project-level credentials such as service account keys, OAuth client secrets, and database root passwords, and teams must inventory copies outside Google Cloud tools such as source repositories and application configuration files. When a person with access to those secrets leaves, changes roles, or is suspected of compromise, all exposed project credentials must be rotated and every dependent application and service must be updated to the new value.
The documented rotation sequence for a service account key preserves availability in order:
Exam tip: Create, deploy, and verify the new service account key before deleting the old key — deleting first causes an outage, while verifying first preserves authentication during rotation.
Automated rotation with Secret Manager and delivery pipelines replaces manual key handling with scheduled renewal, workload identity authentication, and controlled promotion across environments. On Google Kubernetes Engine (GKE), the Secret Manager provider can be enabled on new and existing clusters with auto-rotation configured by a rotation interval in seconds, with a minimum allowed value of 120s. Pods that mount those secrets authenticate to the Secret Manager API through the workload identity of the Pod, using a Kubernetes ServiceAccount bound to an IAM principal identifier, so no long-lived key file needs to be copied into the cluster.
Delivery pipelines extend the same lifecycle discipline to build and release credentials. Cloud Build triggers run under dedicated, user-managed service accounts granted only minimum IAM permissions such as Artifact Registry Writer and Logs Writer, with private pools peered to a private VPC network for sensitive enterprise builds. Cloud Deploy then separates build from release by restricting CI tools to the Cloud Deploy Releaser role, requiring manual approval with requireApproval: true on staging and production targets, using target-specific execution service accounts, and enforcing Binary Authorization policies so the admission controller cryptographically verifies container image digests and rejects untrusted artifacts. For Cloud Key Management Service (Cloud KMS) keys used by these systems, keys do not expire by default, so perform manual rotation only when organizational requirements demand it and avoid automatic rotation where it would disrupt running workloads.
Compromise response for service account keys is an ordered containment workflow that first stops the credential, then removes its authorization, then limits what stolen tokens can still do. Service account key disable provides immediate containment by blocking authentication without permanently removing the key object, while deletion permanently removes the key so it can never be used again. To determine the blast radius, use Policy Analyzer to find every project, folder, organization, and resource where the identity holds IAM allow policies, then remove the user account from IAM permissions, move role-changers to a different Google Group, and delete or suspend the identity in the federated identity provider with automatic provisioning where configured.
Immediate key action alone is not sufficient because long-lived OAuth refresh tokens, access tokens, SSH keys, browser cookies, and federated tokens can persist after endpoint access is removed and let an attacker impersonate the user or service account, bypass password and 2-Step Verification, and hide malicious API traffic as legitimate activity. The response must therefore rotate every exposed project credential, including unrestricted API keys that are visible to roles such as Viewer, and search external copies that IAM cannot revoke centrally.
| Control | How it limits a compromised credential |
|---|---|
| Google Cloud session length | Forces periodic reauthentication for the gcloud CLI on a 1 to 24 hour policy, with 16 hours enforced by default for new customers, which shortens how long a stolen token remains usable |
| VPC Service Controls | Defines a service perimeter around supported resources so API traffic originating from attacker-controlled endpoints outside the perimeter is blocked even when it presents valid credentials |
| Chrome Enterprise Premium | Evaluates attributes such as IP-based access or certificate-based mutual TLS on every API request and rejects requests that use compromised authorization credentials but do not meet the access-level conditions |
Validate rotation and revocation procedures before an actual incident occurs, enable centralized collection of audit logs and Data Access audit logs for key systems, and treat exposed keys as compromised until rotation, disable or delete, and downstream containment are all confirmed.
constraints/iam.disableServiceAccountKeyCreation and constraints/iam.disableServiceAccountKeyUpload block creation and upload of user-managed service account keys through hierarchy inheritance, and both are enforced by default for organizations created on or after May 3, 2024.sa_key_usage table provides the organization-wide key inventory, while service account insights cover 90 days of inactivity and Cloud Audit Logs fields principalEmail and serviceAccountKeyName attribute actions to a specific account and key.The constraint constraints/iam.disableServiceAccountKeyCreation prevents principals from creating user-managed service account keys while constraints/iam.disableServiceAccountKeyUpload prevents principals from uploading a public key for a service account. Both are inherited through the resource hierarchy so enforcement at the organization or folder level protects all child projects unless explicitly overridden, and both are enforced by default for organizations created on or after May 3, 2024.
Use the constraint constraints/iam.serviceAccountKeyExpiryHours to set an expiry in hours that applies only to newly created keys when temporary key use cannot yet be eliminated. Best practice examples are 8 hours for short development or testing work, 24 hours for day-long access, and 168 hours for week-long access such as developing code in a non-production environment or using a third-party tool that can only authenticate with service account keys. Avoid expiry times for production workloads where an expired key could cause an outage, for non-production workloads that need permanent access such as a continuous integration (CI) pipeline, and for key-rotation systems that already prevent use after a specified time.
Create, deploy, and verify the new key before deleting the old key to preserve authentication during rotation. The sequence is to add and create the new JSON key, deploy it to every application that needs it, confirm it works as expected in all dependent workloads, and only then return to the credentials page and delete the old key.
Cloud Asset Inventory exported to the BigQuery table named sa_key_usage provides the organization-wide inventory because service accounts belong to a single project and native insights must otherwise be checked project by project. The export joins inventory with key-usage data and permission-usage data to show which persistent keys exist, which keys are inactive, and which keys are attached to overly privileged service accounts, while Cloud Audit Logs fields principalEmail and serviceAccountKeyName attribute actions to a specific account and key.
An enterprise wants to establish a comprehensive auditing and monitoring framework for user-managed service account keys across hundreds of projects in its Google Cloud organization. The security operations team has defined the following technical requirements:
Which combination of Google Cloud services and configurations should the security team deploy to satisfy these requirements?
Last updated