Prepare and test your skills
Prepare and test your skills
Enterprise governance for service account impersonation combines traceable auditing with preventive controls that force short-lived impersonation instead of long-lived keys. In this model, Cloud Audit Logs (opens in a new tab) records who acted through which service account, Organization Policy Service (opens in a new tab) blocks key creation and upload, and temporary group membership limits how long elevated access lasts. Data flows from the originating principal to the service account impersonation (opens in a new tab) token service to the target resource, and audit data flows from those APIs to logging and long-term export.
Service account impersonation occurs when an authenticated principal, such as a user or another service account, authenticates as a service account to gain that service account's permissions. An impersonating principal can access whatever the service account can access, such as a sensitive Cloud Storage bucket, so a service account is effectively as valuable as the resources it can reach. Privilege escalation involving service accounts typically falls into three peer categories:
Permissions that enable impersonation or attachment include iam.serviceAccounts.getAccessToken, iam.serviceAccounts.getOpenIdToken, iam.serviceAccounts.actAs, iam.serviceAccounts.implicitDelegation, iam.serviceAccounts.signBlob, iam.serviceAccounts.signJwt, iam.serviceAccountKeys.create, deploymentmanager.deployments.create, and cloudbuild.builds.create. Roles containing some of these permissions include Owner, Editor, Service Account User (roles/iam.serviceAccountUser), Service Account Token Creator (roles/iam.serviceAccountTokenCreator), Service Account Key Admin, Service Account Admin, and Workload Identity User.
Cloud Audit Logs is the record that links an impersonated operation back to its originating principal through service account delegation info. When a member of a privileged group generates a short-lived token for a service account and calls an API as that service account, the log entry for the resource operation and the token-generation event together show both the service account identity and the user or group member that requested it. Administrators review privileged access patterns and detect anomalies by analyzing these requests and access patterns, and enterprises export the logs to persist them for audit purposes. Governance requires that privileged access either expires automatically or is reviewed periodically, so audit review closes the loop on temporary elevation.
Enabling audit logs for privileged access ensures that use of an impersonated service account is logged and available for review and analysis. For Compute Engine privileged access, administrators enable Data Access audit logs on the project with an ordered update to the project IAM policy:
gcloud projects get-iam-policy PROJECT_ID > /tmp/policy.yaml to capture the existing allow policy.auditConfigs block for service: compute.googleapis.com with logType: ADMIN_READ, logType: DATA_READ, and logType: DATA_WRITE.gcloud projects set-iam-policy PROJECT_ID /tmp/policy.yaml to enforce logging for Compute Engine API requests.After logging is enabled, administrators analyze privileged access requests in Cloud Logging and export logs for long-term retention. Export is important because Data Access logs can be voluminous and audit investigations need history beyond default retention to trace which originating principal impersonated which service account and when.
Organization Policy Service constraints mandate impersonation patterns by removing the key-based alternative that enables credential exfiltration. When a service account key is used, the key value is stored in gcloud CLI configuration files separately from the downloaded key file, and an attacker with access to the environment can copy the key from the configuration, local file system, or internal code repository. To prevent this, enforce constraints/iam.disableServiceAccountKeyCreation and constraints/iam.disableServiceAccountKeyUpload to disable key creation and upload, which forces developers, external applications with Workload Identity Federation, and operators to use service account impersonation with short-lived credentials instead. This control directly supports least privilege because impersonation grants are scoped to specific service accounts, can use role recommendations to remove unused roles, and can be combined with 2-Step Verification and Access Context Manager conditions such as requiring the corporate network.
Temporary elevated access through impersonation centralizes privilege in a service account and distributes only short-lived use through group membership. In the enterprise pattern, an administrator creates a Google group such as elevated-compute-access, creates a service account such as elevated-compute-access with a scoped role like Compute Admin (roles/compute.admin), grants the group Service Usage Consumer (roles/serviceusage.serviceUsageConsumer) on the project, and grants the group Service Account Token Creator (roles/iam.serviceAccountTokenCreator) on that service account. A user requests membership in the group, a group administrator approves expiring membership per Cloud Identity guidance, and the member then generates short-lived OAuth 2.0 access tokens or OpenID Connect ID tokens to act as the service account. Related options include Privileged Access Manager for just-in-time elevation with justifications, IAM Conditions for expiring allow-policy bindings, and the open-source Just-In-Time Access app that replaces rather than accumulates conditional bindings to control policy size.
Containment for compromised service account tokens and keys prioritizes blocking active tokens while preserving the ability to investigate. To block a compromised token, disable the service account that the credential represents, apply an Identity and Access Management (IAM) deny policy for the service account principal principal://iam.googleapis.com/projects/-/serviceAccounts/SA_EMAIL_ADDRESS on projects or folders, or delete the service account. The deny policy denies access to sensitive APIs for active tokens and workloads so investigation can continue without destroying the service account, whereas disabling or deleting immediately removes access from all workloads using the service account. Full response then revokes roles/iam.serviceAccountTokenCreator from unauthorized principals, rotates any compromised key by creating and deploying a new key before disabling and deleting the old key, and waits before re-enabling.
Exam tip: Wait at least 60 minutes after disabling a service account before re-enabling it so compromised tokens expire; if constraints/iam.allowServiceAccountCredentialLifetimeExtension sets an extended lifetime, wait that specified time instead.
Service account impersonation in Google Cloud is the process where an authenticated principal, such as a user, group, or another service account, authenticates as a service account to gain the service account's permissions. The model has two sides that must be configured separately: the service account receives Identity and Access Management (IAM) (opens in a new tab) roles that define what resources it can access, and the impersonating principal receives an IAM role on that service account that defines permission to mint credentials for it. When impersonation succeeds, data and API requests flow from the impersonator through short-lived credentials to the target resources under the service account's identity.
Binding impersonation roles on the target service account resource means granting the role in the allow policy of the service account itself, not on the project, folder, or organization. The secure pattern uses gcloud iam service-accounts add-iam-policy-binding with the service account email as the resource, the user or group as the member, and Service Account Token Creator (opens in a new tab) (roles/iam.serviceAccountTokenCreator) as the role. Because the grant applies only to that one service account, the principal can impersonate only that identity and cannot mint tokens for every service account in the project. A project-wide grant has the opposite effect, because a member with roles/iam.serviceAccountTokenCreator on the project inherits token-creation ability for all service accounts in that project, including highly privileged ones.
A complete delegation flow follows this order:
roles/iam.serviceAccountTokenCreator on the service account email to a Google group, so membership controls who can impersonate.The documented elevated-access pattern keeps the two grants at different scopes: the service account gets roles/compute.admin on the project so it can administer Compute Engine instances, while the delegate group gets roles/iam.serviceAccountTokenCreator only on the elevated-compute-access service account. The pattern also grants the group Service Usage Consumer (roles/serviceusage.serviceUsageConsumer) on the project so group members can use the IAM Service Account Credentials API (iamcredentials.googleapis.com) to request the short-lived token.
Short-lived credential roles and attachment roles control different paths to using a service account's permissions. Credential roles let a principal mint tokens and impersonate the service account directly, while the attachment role lets a principal attach the service account to a compute resource and then run code as that single service account identity. Running code on an attached resource is not impersonation in the IAM sense, because only the service account authenticates, but it still gives the user the service account's access.
| Role | What it allows | Choose when |
|---|---|---|
Service Account Token Creator (roles/iam.serviceAccountTokenCreator) | Create short-lived OAuth 2.0 access tokens and other short-lived service account credentials for the target service account | The user or application needs to impersonate the service account for API calls, local development, or Workload Identity Federation without using long-lived keys |
Service Account OpenID Connect Identity Token Creator (roles/iam.serviceAccountOpenIdTokenCreator) | Create short-lived OpenID Connect (OIDC) ID tokens for the target service account | The workload needs an OIDC identity token, for example for federated authentication with a custom audience |
Service Account User (roles/iam.serviceAccountUser) | Attach the service account to a resource, such as a Compute Engine instance or Vertex AI Workbench environment, via iam.serviceAccounts.actAs behavior | The user needs to deploy or configure compute that runs as the service account, rather than calling APIs directly as the service account |
Underlying permissions that enable these paths include iam.serviceAccounts.getAccessToken, iam.serviceAccounts.getOpenIdToken, iam.serviceAccounts.actAs, iam.serviceAccounts.implicitDelegation, iam.serviceAccounts.signBlob, and iam.serviceAccounts.signJwt, plus iam.serviceAccountKeys.create for key-based authentication. Broader roles such as Owner (roles/owner), Editor (roles/editor), Service Account Admin (roles/iam.serviceAccountAdmin), Service Account Key Admin (roles/iam.serviceAccountKeyAdmin), and Workload Identity User (roles/iam.workloadIdentityUser) contain some of these permissions. Additional creation paths such as deploymentmanager.deployments.create and cloudbuild.builds.create can also lead to indirect use of a service account, so they must be controlled alongside direct impersonation grants.
Exam tip: Grant roles/iam.serviceAccountTokenCreator on the service account when the principal must impersonate it directly; grant roles/iam.serviceAccountUser on the service account only when the principal must attach it to compute resources.
Least-privilege configuration for impersonation narrows both who can impersonate and what the impersonated identity can do. A service account with access to sensitive resources is as valuable as those resources themselves, because taking over the service account gives an attacker the same access. Privilege escalation through service accounts typically falls into authenticating as the service account, using a resource that already has a privileged service account attached, or modifying allow policies, groups, or custom roles to grant oneself impersonation rights. For example, a user with SSH access to a Compute Engine virtual machine (VM) can run code on that VM to reach any resource the VM's attached service account can reach, even without formal impersonation permission.
sudo.These rules keep the trust boundary tight: the caller stays outside the privilege until it mints a short-lived token, and the service account carries only the permissions its task requires.
Secure delegation depends on group membership, audit trails, and rapid revocation of impersonation rights. A Google group such as elevated-compute-access holds the roles/iam.serviceAccountTokenCreator binding on the service account, so adding a user to the group grants impersonation and removing the user or letting time-limited membership expire removes it. IAM Conditions and Privileged Access Manager can add expiring or justified elevation, but expired conditional bindings are not automatically removed from allow policies, so policies must be periodically cleaned to stay under size limits. Audit and revocation rely on separate administrative permissions from impersonation itself, so administrators enable Cloud Audit Logs data-access logs for services such as compute.googleapis.com and token-creation calls through the IAM Credentials API.
To revoke impersonation after a compromise, an administrator removes roles/iam.serviceAccountTokenCreator from unauthorized principals, which requires resourcemanager.projects.setIamPolicy on the project and iam.serviceAccounts.setIamPolicy on the service account's project, held by Project IAM Admin (roles/resourcemanager.projectIamAdmin) and Service Account Admin (roles/iam.serviceAccountAdmin). For active-token incidents, the response also uses service account disable or delete, IAM deny policies for the compromised service account tokens (opens in a new tab), and key rotation, with at least a 60-minute wait before re-enabling to allow compromised tokens to expire.
Generating short-lived credentials by impersonation replaces long-lived service account keys in development and CI/CD pipelines. In this model, an authenticated caller uses the IAM Credentials API (opens in a new tab) to mint an OAuth 2.0 access token, an OpenID Connect (OIDC) (opens in a new tab) ID token, or a cryptographic signature that carries only the permissions of a privilege-bearing service account. The minted credential expires without a refresh token, so the caller must repeat impersonation to obtain a new one, which limits exposure if a token is leaked.
The two-principal impersonation model always involves a caller principal and a separate privilege-bearing service account. The caller principal represents the user or workload making the request, while the privilege-bearing service account lends its permissions temporarily. The caller authenticates first with its own identity through Application Default Credentials (ADC) (opens in a new tab), then requests a credential for the privilege-bearing service account, and finally presents that credential to the target Google Cloud API or service. The privilege-bearing service account must already hold the IAM roles needed on the target resource, while the caller must hold an impersonation role on the service account itself.
Exam tip: Never configure a service account to impersonate itself, because self-impersonation lets the account create an access token that can be refreshed in perpetuity.
Short-lived OAuth 2.0 access tokens are the credential type accepted for authentication by most Google Cloud APIs. The IAM Credentials API generates the access token for the privilege-bearing service account without issuing a refresh token, so data flows from the caller to the IAM Credentials API to the target API, and the flow stops when the token reaches its expired state. To authorize this flow, the caller must hold the iam.serviceAccounts.getAccessToken permission on the privilege-bearing service account, which is included in the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator). Choose access tokens when code needs to call Google Cloud APIs with the service account's permissions for a bounded task, then discard the token and repeat impersonation for the next task.
An OIDC ID token authenticates identity to a specific audience, such as a Cloud Run service URL, rather than authorizing broad API calls. The privilege-bearing service account must hold the invoker role on the target service, and the caller must hold the Service Account OpenID Connect Identity Token Creator role (roles/iam.serviceAccountOpenIdTokenCreator) on that service account. The audience value binds the token to one destination, so a token minted for one URL cannot be replayed against another application.
To generate an ID token by impersonation, complete the steps in order:
roles/run.invoker) for Cloud Run services or Cloud Functions Invoker (roles/cloudfunctions.invoker) for Cloud Run functions.iamcredentials.googleapis.com with the target audience URI and the service account email, and receive an ID token scoped to that audience.gcloud impersonation for development and testing lets the gcloud CLI act as a service account without downloading a private key. Running gcloud config set auth/impersonate_service_account makes subsequent gcloud commands act as the specified service account, while the caller still authenticates with its own user or attached service account credentials. Running gcloud auth application-default login --impersonate-service-account writes a local ADC file that causes client libraries to obtain short-lived tokens for the impersonated account automatically. That local ADC impersonation file is supported only for the Go, Java, Node.js, and Python client libraries and is not supported for other languages. A separate development-only path uses gcloud auth print-identity-token to mint a generic ID token from user credentials for any Cloud Run service or Cloud Run function the caller is permitted to invoke, and that generic token carries the caller's own permissions, works only for those Cloud Run targets, and must be kept secure and never used in production.
Temporary privilege elevation uses the Service Account Credentials API to ensure each part of an application holds only the access it needs at the moment it needs it. Instead of granting one service account access to all resources, the design splits ownership so a supervisor identity brokers short-lived tokens for narrowly scoped workload identities. The token broker is the only component that uses the supervisor credentials, and downstream components receive only short-lived tokens that expire after use. Credential Access Boundaries can further downscope an access token, so the downscoped token carries a subset of the privilege-bearing account's permissions across the trust boundary to the workload.
The supervisor pattern depends on each side holding the correct role:
Delegation chains extend this pattern when a caller impersonates an intermediate service account that in turn impersonates the final privilege-bearing account, which is useful when CI/CD or multi-tier workloads cannot directly reach the final account. Several connecting services can automatically attach the correct ID token, with the appropriate aud claim, when they initiate a call, so the workflow depends on the connecting service rather than custom token code:
The choice of short-lived credential depends on whether the destination authorizes API operations or verifies identity for a single audience. Both types are minted by the caller through the IAM Credentials API for the privilege-bearing service account, and both expire without renewal.
| Credential | Authenticates to | Audience and permission model |
|---|---|---|
| OAuth 2.0 access token | Most Google Cloud APIs | Carries the service account's API permissions; caller needs Service Account Token Creator on the account |
| OIDC ID token | Cloud Run services, Cloud Run functions, and other OIDC-accepting targets | Bound to one audience URI; service account needs Invoker on the target and caller needs OpenID Connect Identity Token Creator on the account |
Choose an access token when the work is calling Google Cloud APIs, and choose an ID token when the work is proving identity to a service that validates the audience. For signing payloads without transmitting a private key, use the same API to create self-signed JSON Web Tokens (JWTs) or sign binary blobs with the service account's Google-managed key.
constraints/iam.disableServiceAccountKeyCreation and constraints/iam.disableServiceAccountKeyUpload force impersonation by blocking service account key creation and upload.Service Account Token Creator (roles/iam.serviceAccountTokenCreator) lets a principal mint short-lived credentials to directly impersonate a service account for API calls, while Service Account User (roles/iam.serviceAccountUser) lets a principal attach the service account to a compute resource such as a Compute Engine instance to run code as that identity. Token Creator should be granted on the target service account when direct impersonation is needed, and Service Account User should be granted only when compute must run as the service account.
Use a short-lived OAuth 2.0 access token when calling most Google Cloud APIs with the privilege-bearing service account permissions, and use an OpenID Connect (OIDC) ID token when proving identity to a single audience such as a Cloud Run service or Cloud Run function. The access token path requires Service Account Token Creator on the service account, while the ID token path requires Service Account OpenID Connect Identity Token Creator on the service account and an Invoker role for the service account on the target.
Enforcing constraints/iam.disableServiceAccountKeyCreation and constraints/iam.disableServiceAccountKeyUpload blocks creation and upload of service account keys, which forces developers and external applications to use impersonation with short-lived credentials. This removes the key-based alternative that enables credential exfiltration from configuration files, file systems, or code repositories and keeps impersonation grants scoped to specific service accounts.
A security operations team is investigating unauthorized modifications made to sensitive cloud storage buckets. The actions were executed directly by a privileged deployment service account. The team needs to trace the authentic originating human principal who initiated the impersonated session and prevent future credential exfiltration risks by enforcing short-lived impersonation workflows enterprise-wide.
Which combination of Cloud Audit Log inspection and Organization Policy enforcement should the security engineer implement?
Inspect protoPayload.serviceData.policyDelta to trace the token generation permissions, and enforce the compute.setNewProjectDefaultToZonalDNSOnly organization policy constraint.
Inspect protoPayload.authenticationInfo.principalEmail to view the originating caller, and enforce the iam.disableCrossProjectServiceAccountUsage organization policy constraint.
Inspect protoPayload.authenticationInfo.serviceAccountDelegationInfo in Cloud Audit Logs to identify the originating principal in the delegation chain, and enforce the iam.disableServiceAccountKeyCreation organization policy constraint.
Inspect protoPayload.requestMetadata.callerIp to correlate the human identity via external IdP logs, and enforce the iam.allowedPolicyMemberDomains organization policy constraint.
Last updated