This guide describes how you can set up Context-Aware Access to help secure service
account access to Google Cloud APIs, based on access levels that you
define.

## Limitations

The following limitations apply to Context-Aware Access policies for service
accounts:

- You can't use network-based or IP address-based attributes for service
  account bindings if the service account is used for workflow executions
  and Cloud Scheduler.

- Context-Aware Access policies can't block connections to private
  Google Kubernetes Engine (GKE) clusters using `kubectl`, or to Cloud SQL using
  the Auth Proxy.

- If an access level that you bind to a service account contains unsupported
  attributes, such as `Device` attributes, Context-Aware Access denies API access.

- Scoped access levels aren't supported for service accounts.

If you use Cloud Build and Cloud Run, we recommend that you
use the following built-in Virtual Private Cloud (VPC) features:

- For Cloud Run, use [Serverless VPC Access](https://docs.cloud.google.com/vpc/docs/serverless-vpc-access.md.txt).

- For Cloud Build, use [private pools](https://docs.cloud.google.com/build/docs/private-pools/private-pools-overview.md.txt).

> [!IMPORTANT]
> **Important:** You can use Context-Aware Access to restrict Google Cloud API access by service accounts to specific VPC networks. If you do, then you must configure all workloads that use those service accounts to use the same VPC networks. For example, a Cloud Run service that uses the service account must be [configured to run within the VPC network](https://docs.cloud.google.com/run/docs/configuring/vpc-direct-vpc.md.txt).

## Before you begin

1. Make sure that you have a [Google Cloud organization](https://docs.cloud.google.com/resource-manager/docs/creating-managing-organization.md.txt) and at least one [Google Cloud project](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects.md.txt).
2. Update Google Cloud CLI components:

   ```
   gcloud components update --quiet
   ```
3. [Create a service account](https://docs.cloud.google.com/iam/docs/service-accounts-create.md.txt) in your project if you don't already have one. This service account is the target of the Context-Aware Access policy.

## Required roles

This section describes the Identity and Access Management (IAM) roles that are required to
use Context-Aware Access.

### Project-level roles


To get the permission that
you need to at the project level,

ask your administrator to grant you the
[Service Account Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountAdmin) (`roles/iam.serviceAccountAdmin`) IAM role on the user account or service account.


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


This predefined role contains the
`the required permissions`
permission,
which is required to
at the project level.


You might also be able to get
this permission
with [custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles.md.txt) or
other [predefined roles](https://docs.cloud.google.com/iam/docs/roles-overview.md.txt#predefined).

### Organization-level roles


To get the permission that
you need to at the organization level,

ask your administrator to grant you the
following IAM roles on user account or service account:

- [Cloud Access Binding Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/accesscontextmanager.md.txt#accesscontextmanager.gcpAccessAdmin) (`roles/accesscontextmanager.gcpAccessAdmin`)
- [Access Context Manager Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/accesscontextmanager.md.txt#accesscontextmanager.policyAdmin) (`roles/accesscontextmanager.policyAdmin`)


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


This predefined role contains the
`the required permissions`
permission,
which is required to
at the organization level.


You might also be able to get
this permission
with [custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles.md.txt) or
other [predefined roles](https://docs.cloud.google.com/iam/docs/roles-overview.md.txt#predefined).

## Bind Context-Aware Access policies to different resource levels

You can bind Context-Aware Access policies with the same enforcement mode to
resources that are at different levels of the resource hierarchy. When a
resource attempts access, Context-Aware Access uses the policy that is bound to
that resource before it attempts to use a policy that is bound to a higher-level
resource.

For example, you can bind an enforcement-mode policy directly to a
service account and a different enforcement-mode policy to the project that
contains the service account. When the service account attempts to access
resources, Context-Aware Access evaluates the policy that is bound to the
service account. For other service accounts in the project that don't have
policies bound to them, Context-Aware Access evaluates the enforcement-mode
policy that is bound to the project. The same is true if the enforcement mode is
set to dry run for both the project-level policy and the service
account-level policy.

You can use multiple policies to incrementally and selectively deploy
policies---for example, you can do the following:

1. Bind a policy in dry-run mode at the project level and make sure that it's working as you expect by checking for access denied events in Cloud Audit Logs.
2. Bind the policy in enforcement mode only to specific service accounts.
3. Bind the policy in enforcement mode at the project level, and bind a less restrictive, enforcement-mode policy to specific service accounts as needed.

Context-Aware Access evaluates enforcement-mode policies and dry-run mode policies
independently across the resource hierarchy. Binding a dry-run mode policy alone
to a service account doesn't override an enforcement-mode policy that is bound
to the project. To exempt a specific service account from a project-level
enforcement-mode policy and evaluate a policy in dry-run mode for that service
account, bind an enforcement-mode custom access level that always evaluates to
`true` along with a dry-run mode access level to the service account. For
instructions, see
[Use dry-run mode for a service account in a project with an enforcement-mode policy](https://docs.cloud.google.com/access-context-manager/docs/set-up-caa-service-accounts.md.txt#dry-run-project-enforcement).

## Access level attributes for service accounts

This section lists the access level attributes that are supported for service
accounts.

> [!IMPORTANT]
> **Important:** You can bind only [organization-level Access Context Manager
> access levels](https://docs.cloud.google.com/access-context-manager/docs/create-access-policy#organization-access-policy) to service accounts. Scoped access levels aren't supported for service accounts.

The following attributes are supported for service accounts:

- IP subnetworks, which are based on the public IP address.
- VPC networks, which are based on the private IP address.
- Geolocation, which is based on the public IP address.


  When the service account makes any request to Google Cloud
  APIs, Context-Aware Access evaluates the request and compares the IP address
  of the request to the IP addresses specified in the Context-Aware Access
  policy. If the IP addresses match, Context-Aware Access allows the API call.
  If the IP addresses don't match, Context-Aware Access denies the API call.
-
  A custom access level with a Common Expression Language (CEL)
  expression. The expression must evaluate to `true` to
  allow access and `false` to deny access.


  The following CEL expression is useful for restricting access by service
  accounts.


  The expression evaluates to `true` if the request
  originated from one or more specified project numbers:

  ```yaml
      expression: "originatesFromProjects(origin, ['projects/PROJECT_NUMBER'])"
      
  ```


  `originatesFromProjects` checks whether the request comes from
  a network that is associated with the specified project and whether the
  request comes from a private IP address.
-
  Time of day, which is based on the time and date of the request in a
  specified time zone.


  For more information, see
  [Configuring time and day access conditions](https://docs.cloud.google.com/access-context-manager/docs/time-and-date-conditions.md.txt).

## Create an access level

This section describes how to create an access level within your organization.
Access levels define the conditions under which access is permitted.

1. Follow the instructions to [Create a basic access level](https://docs.cloud.google.com/access-context-manager/docs/create-basic-access-level.md.txt)
   or [Create a custom access level](https://docs.cloud.google.com/access-context-manager/docs/create-custom-access-level.md.txt).

2. Note the full name of the access level, which has the format:
   `accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME`.

## Create an access binding

Bind the access level to the selected service account. Doing so enforces the
conditions defined in the access level. You can bind the access level to a
single service account or all service accounts within a project.

### Bind the access level to a specific service account

This section describes how to bind the access level to a specific service
account.

### gcloud

Bind the access level to a service account using the gcloud CLI.

```sh
gcloud access-context-manager cloud-bindings create \
    --organization=ORGANIZATION_ID \
    --service-account=SERVICE_ACCOUNT_NAME@SERVICE_ACCOUNT_PROJECT_ID.iam.gserviceaccount.com \
    --level=accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME
```

Replace the following:

- `ORGANIZATION_ID`: your Google Cloud organization ID.
- `SERVICE_ACCOUNT_NAME`: the ID of the target service account (the part of the email address before the `@` symbol).
- `SERVICE_ACCOUNT_PROJECT_ID`: the ID of the project that contains the target service account.
- `POLICY_ID`: the ID of the Access Context Manager access policy.
- `ACCESS_LEVEL_NAME`: the name of the access level
  that you created.

  To use Context-Aware Access without enforcing the access level and
  disallowing access, you can [bind the access level in dry-run mode](https://docs.cloud.google.com/access-context-manager/docs/set-up-caa-service-accounts.md.txt#dry-run).

### REST API

To bind the access level to a specific service account using the
REST API, run the following command:

1. Create a `request.json` file with the following content:

   ```json
   {
     "principal": {
       "serviceAccount": "SERVICE_ACCOUNT_NAME@SERVICE_ACCOUNT_PROJECT_ID.iam.gserviceaccount.com"
     },
     "accessLevels": ["accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME"]
   }
   ```

   Replace the following:
   - `SERVICE_ACCOUNT_NAME`: the ID of the target
     service account (the part of the email address before the `@` symbol).

   - `SERVICE_ACCOUNT_PROJECT_ID`: the ID of the
     project that contains the target service account.

   - `POLICY_ID`: the ID of the Access Context Manager
     access policy.

   - `ACCESS_LEVEL_NAME`: the name of the access
     level that you created.

2. Run the following command:

   ```
   curl -H "X-Goog-User-Project: PROJECT_ID" -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d @request.json \
     "https://accesscontextmanager.googleapis.com/v1/organizations/ORGANIZATION_ID/gcpUserAccessBindings"
   ```

   Replace the following:
   - `PROJECT_ID`: the ID of the project that you are
     using to make the API calls.

   - `ORGANIZATION_ID`: your Google Cloud
     organization ID.

### Bind the access level to all service accounts in a project

This section describes how to bind the access level to all of the service
accounts in a project.

### gcloud

To bind the access level to all of the service accounts in a project using the
gcloud CLI, run the following command:

```sh
gcloud access-context-manager cloud-bindings create \
  --organization=ORGANIZATION_ID \
  --service-account-project-number=PROJECT_NUMBER \
  --level=accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME
```

Replace the following:

- `ORGANIZATION_ID`: your Google Cloud organization ID.
- `PROJECT_NUMBER`: the project number of the project that contains all of the service accounts that you want to bind access to.
- `POLICY_ID`: the ID of the Access Context Manager access policy.
- `ACCESS_LEVEL_NAME`: the name of the access level that you created.

### REST API

To bind the access level to all of the service accounts in a project using the
REST API, do the following:

1. Create a `request.json` file with the following content:

   ```json
   {
     "principal": {
       "serviceAccountProjectNumber": "PROJECT_NUMBER"
     },
     "accessLevels": ["accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME"]
   }
   ```

   Replace the following:
   - `PROJECT_NUMBER`: the project number of the project that contains all of the service accounts that you want to bind access to.
   - `POLICY_ID`: the ID of the Access Context Manager access policy.
   - `ACCESS_LEVEL_NAME`: the name of the access level that you created.
2. Run the following command:

   ```
   curl -H "X-Goog-User-Project: PROJECT_ID" -X POST \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "Content-Type: application/json; charset=utf-8" \
   -d @request.json \
   "https://accesscontextmanager.googleapis.com/v1/organizations/ORGANIZATION_ID/gcpUserAccessBindings"
   ```

   Replace the following:
   - `PROJECT_ID`: the ID of the project that you are using to make the API calls.
   - `ORGANIZATION_ID`: your Google Cloud organization ID.

To use Context-Aware Access without enforcing the access level and denying
access, you can [bind the access level in dry-run mode](https://docs.cloud.google.com/access-context-manager/docs/set-up-caa-service-accounts.md.txt#dry-run).

The API response for the create binding operation includes the name of the
binding, which contains the unique binding ID.

## Use dry-run mode

You can bind the access level in dry-run mode. When you use dry-run mode, your
service accounts can continue to access resources without enforcement. However,
if your service accounts attempt access that violates the access level,
Context-Aware Access logs the violation to Cloud Audit Logs.

### Bind the access level in dry-run mode

### gcloud

To bind the access level in dry-run mode, replace the `--level` parameter
with `--dry-run-level`, formatted as follows:

```sh
--dry-run-level=accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME
```

### REST API

To bind the access level in dry-run mode, create the `request.json` file with
the following content:

```json
{
"principal": {
  "serviceAccountProjectNumber": "TARGET_PROJECT_NUMBER"
},
"dryRunAccessLevels": ["accessPolicies/POLICY_ID/accessLevels/ACCESS_LEVEL_NAME"]
}
```

Replace the following:

- `TARGET_PROJECT_NUMBER`: the project number of the target project.
- `POLICY_ID`: the ID of the Access Context Manager access policy.
- `ACCESS_LEVEL_NAME`: the name of the access level.

### Use dry-run mode for a service account in a project with an enforcement-mode policy

Because Context-Aware Access evaluates enforcement-mode policies and dry-run mode
policies independently across the resource hierarchy, binding only a dry-run
mode access level to a service account doesn't override an enforcement-mode
policy that is bound to the project.

To exempt a specific service account from a project-level enforcement-mode
policy and evaluate an access level in dry-run mode for that service account,
create a custom access level that always evaluates to `true`, and then bind
that custom access level in enforcement mode along with the dry-run mode access
level to the service account:

### gcloud

1. Create an `always_allow.yaml` file with a CEL expression that always
   evaluates to `true`:

   ```yaml
   expression: "true"
   ```
2. Create the custom access level:

   ```sh
   gcloud access-context-manager levels create ALWAYS_ALLOW_LEVEL_NAME \
     --title="TITLE" \
     --custom-level-spec=always_allow.yaml \
     --policy=POLICY_ID
   ```

   Replace the following:
   - `ALWAYS_ALLOW_LEVEL_NAME`: a unique name for the
     custom access level that always allows access

   - `TITLE`: a short, human-readable title for the
     access level

   - `POLICY_ID`: the ID of the Access Context Manager
     access policy

3. Bind the custom access level in enforcement mode (`--level`) and the
   target access level in dry-run mode (`--dry-run-level`) to the service
   account:

   ```sh
   gcloud access-context-manager cloud-bindings create \
     --organization=ORGANIZATION_ID \
     --service-account=SERVICE_ACCOUNT_NAME@SERVICE_ACCOUNT_PROJECT_ID.iam.gserviceaccount.com \
     --level=accessPolicies/POLICY_ID/accessLevels/ALWAYS_ALLOW_LEVEL_NAME \
     --dry-run-level=accessPolicies/POLICY_ID/accessLevels/DRY_RUN_ACCESS_LEVEL_NAME
   ```

   Replace the following:
   - `ORGANIZATION_ID`: your Google Cloud
     organization ID

   - `SERVICE_ACCOUNT_NAME`: the name of the target
     service account, which is different from the service account's email

   - `SERVICE_ACCOUNT_PROJECT_ID`: the ID of the
     project that contains the target service account

   - `POLICY_ID`: the ID of the Access Context Manager
     access policy

   - `ALWAYS_ALLOW_LEVEL_NAME`: the name of the custom
     access level that always evaluates to `true`

   - `DRY_RUN_ACCESS_LEVEL_NAME`: the name of the
     access level that you want to evaluate in dry-run mode

   If you already bound the dry-run mode policy at the project level, or if
   you only want to exempt the service account from the project-level
   enforcement-mode policy, you can omit `--dry-run-level`.

### REST API

1. Create a
   [custom access level](https://docs.cloud.google.com/access-context-manager/docs/create-custom-access-level.md.txt)
   with the CEL expression `"expression": "true"`.

2. Create a `request.json` file that binds the custom access level in
   `accessLevels` and the target dry-run access level in
   `dryRunAccessLevels` for the service account:

   ```json
   {
   "principal": {
     "serviceAccount": "SERVICE_ACCOUNT_NAME@SERVICE_ACCOUNT_PROJECT_ID.iam.gserviceaccount.com"
   },
   "accessLevels": ["accessPolicies/POLICY_ID/accessLevels/ALWAYS_ALLOW_LEVEL_NAME"],
   "dryRunAccessLevels": ["accessPolicies/POLICY_ID/accessLevels/DRY_RUN_ACCESS_LEVEL_NAME"]
   }
   ```

   Replace the following:
   - `SERVICE_ACCOUNT_NAME`: the name of the target
     service account, which is different from the service account's email

   - `SERVICE_ACCOUNT_PROJECT_ID`: the ID of the
     project that contains the target service account

   - `POLICY_ID`: the ID of the Access Context Manager
     access policy

   - `ALWAYS_ALLOW_LEVEL_NAME`: the name of the custom
     access level that always evaluates to `true`

   - `DRY_RUN_ACCESS_LEVEL_NAME`: the name of the
     access level that you want to evaluate in dry-run mode

   If you already bound the dry-run mode policy at the project level, or if
   you only want to exempt the service account from the project-level
   enforcement-mode policy, you can omit `dryRunAccessLevels`.
3. Run the following command:

   ```
   curl -H "X-Goog-User-Project: PROJECT_ID" -X POST \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "Content-Type: application/json; charset=utf-8" \
   -d @request.json \
   "https://accesscontextmanager.googleapis.com/v1/organizations/ORGANIZATION_ID/gcpUserAccessBindings"
   ```

   Replace the following:
   - `PROJECT_ID`: the ID of the project that you are
     using to make the API calls

   - `ORGANIZATION_ID`: your Google Cloud
     organization ID

### Check Cloud Audit Logs

This section describes how you can check Cloud Audit Logs for dry-run mode
access denials for your service account. To learn more about searching for
dry-run mode entries in Cloud Audit Logs, see [View dry-run mode logs](https://docs.cloud.google.com/access-context-manager/docs/apply-policies-to-user-groups.md.txt#view-dry-run-logs).

### Console

To view Cloud Audit Logs dry-run mode service account access denials by
using the Google Cloud console, do the following:

In the Google Cloud console, go to the

**Logs Explorer** page:

[Go to **Logs Explorer**](https://console.cloud.google.com/logs/query)

<br />

If you use the search bar to find this page, then select the result whose subheading is
**Logging**.

1. In the Google Cloud console, select your project or organization.

2. In the **Log query** field, enter the following query:

   ```none
   protoPayload.serviceName="contextawareaccess.googleapis.com"
   protoPayload.metadata.dryRunEvaluationResult:DENIED
   SEARCH("SERVICE_ACCOUNT_NAME")
   ```
3. In the time range selector, choose from a predefined relative time,
   like **Last 30 minutes** , **Last 1 hour** , or **Last 24 hours**, or
   specify a custom range.

### gcloud

To view Cloud Audit Logs dry-run mode service account access denials by
using the gcloud CLI, do the following:

```sh
gcloud logging read \
'protoPayload.serviceName="contextawareaccess.googleapis.com" AND
 protoPayload.metadata.dryRunEvaluationResult:DENIED AND
 SEARCH("SERVICE_ACCOUNT_NAME")' \
  --organization=ORGANIZATION_ID
```

Replace the following:

- `ORGANIZATION_ID`: the ID of the organization.
- `SERVICE_ACCOUNT_NAME`: the ID of the service account (the part of the email address before the `@` symbol).

The `gcloud logging read` command supports the `--freshness` flag to view
logging information over relative timeframes. For example, by adding
`--freshness=3h` to the command, you can view dry-run mode log entries over
the last 3 hours.

## What's next

- [Manage access bindings](https://docs.cloud.google.com/access-context-manager/docs/manage-access-bindings.md.txt)
- [Troubleshoot Context-Aware Access for service accounts](https://docs.cloud.google.com/access-context-manager/docs/troubleshooting.md.txt#service-account-issues)