> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Api keys restricted to necessary apis remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "Ensure API Keys Are Restricted To Necessary APIs" for GCP using GCP console, please follow the below steps:

        1. Login to GCP console ([https://console.cloud.google.com/](https://console.cloud.google.com/)).
        2. Select the project for which you want to remediate the misconfiguration.
        3. In the left-hand menu, click on "APIs & Services" and then click on "Credentials".
        4. Select the API key that you want to restrict.
        5. Under "Key restriction", select "HTTP referrers (web sites)".
        6. In the "Website restrictions" section, add the domain name(s) of the websites that are allowed to use this API key.
        7. In the "API restrictions" section, select the APIs that are allowed to use this API key.
        8. Click on "Save" to apply the changes.

        By following these steps, the API key will be restricted to only the necessary APIs and the risk of unauthorized access will be reduced.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of ensuring API keys are restricted to necessary APIs in GCP using GCP CLI, follow the below steps:

        1. First, identify the API keys that are not restricted to necessary APIs. You can use the following command to list all the API keys in your project:

        ```
        gcloud beta services api-keys list
        ```

        2. Once you have identified the API keys that are not restricted to necessary APIs, you can use the following command to update the API key and restrict it to specific APIs:

        ```
        gcloud beta services api-keys update [API_KEY_NAME] --restrict-referer=[REFERER_URL] --allowed-apis=[API_LIST]
        ```

        Replace the \[API\_KEY\_NAME] with the name of the API key that you want to update, \[REFERER\_URL] with the URL of the referring website, and \[API\_LIST] with the list of APIs that you want to allow for this API key.

        3. If you want to restrict the API key to a specific IP address, use the following command:

        ```
        gcloud beta services api-keys update [API_KEY_NAME] --restrict-ip=[IP_ADDRESS] --allowed-apis=[API_LIST]
        ```

        Replace \[IP\_ADDRESS] with the IP address that you want to allow for this API key.

        4. Finally, verify that the API key is now restricted to the necessary APIs by using the following command:

        ```
        gcloud beta services api-keys describe [API_KEY_NAME]
        ```

        This command will display the details of the API key, including the allowed APIs and the restricted referer or IP address.

        By following the above steps, you can remediate the misconfiguration of ensuring API keys are restricted to necessary APIs in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Ensure API Keys Are Restricted To Necessary APIs" for GCP using Python, follow these steps:

        1. Identify the API keys that are not restricted to necessary APIs. You can do this by using the following command in the GCP Cloud Shell:

           ```
           gcloud beta iam service-accounts keys list --iam-account [SA-NAME] --filter="keyRestrictions.type:unspecified"
           ```

           Replace \[SA-NAME] with the name of the service account that you want to check.

        2. Create a new API key with restricted access. You can do this by using the following Python code:

           ```
           from google.oauth2 import service_account
           from googleapiclient.discovery import build

           SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
           SERVICE_ACCOUNT_FILE = '[PATH TO YOUR SERVICE ACCOUNT JSON FILE]'

           credentials = service_account.Credentials.from_service_account_file(
               SERVICE_ACCOUNT_FILE, scopes=SCOPES)

           service = build('iamcredentials', 'v1', credentials=credentials)

           response = service.projects().serviceAccounts().keys().create(
               name='projects/-/serviceAccounts/[SA-NAME]',
               body={
                   'keyAlgorithm': 'KEY_ALG_RSA_2048',
                   'keyRestrictions': {
                       'allowedRegions': ['us-central1'],
                       'allowedServices': ['storage.googleapis.com']
                   }
               }
           ).execute()

           print(response)
           ```

           Replace \[PATH TO YOUR SERVICE ACCOUNT JSON FILE] with the path to your service account JSON file, and \[SA-NAME] with the name of the service account that you want to create the API key for.

           This code creates an API key with restricted access to the Storage API in the us-central1 region.

        3. Delete the old API key. You can do this by using the following command in the GCP Cloud Shell:

           ```
           gcloud beta iam service-accounts keys delete [KEY-ID] --iam-account [SA-NAME]
           ```

           Replace \[KEY-ID] with the ID of the old API key that you want to delete, and \[SA-NAME] with the name of the service account that the API key belongs to.

        4. Verify that the new API key has restricted access. You can do this by using the following command in the GCP Cloud Shell:

           ```
           gcloud beta iam service-accounts keys list --iam-account [SA-NAME] --filter="keyRestrictions.type:asymmetric_public"
           ```

           Replace \[SA-NAME] with the name of the service account that you created the new API key for. This command should return the new API key that you just created with restricted access.

        By following these steps, you can remediate the misconfiguration "Ensure API Keys Are Restricted To Necessary APIs" for GCP using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_apikeys_key" "RESTRICTED_API_KEY" {
          project      = "PROJECT_ID"          # replace with your GCP project ID
          name         = "API_KEY_RESOURCE_ID" # replace with the key’s resource ID or leave for Terraform to create
          display_name = "HUMAN_READABLE_NAME" # optional

          restrictions {
            # Restrict this key so it can only call the specific APIs it needs.
            # Replace/duplicate api_targets blocks as required.
            api_targets {
              service = "translate.googleapis.com" # replace with the required API, e.g. maps.googleapis.com
              # methods = ["google.cloud.translation.v3.TranslationService.TranslateText"] # optional: restrict to specific methods
            }

            # Keep or add other restriction types as appropriate (HTTP referrers, IPs, Android/iOS, etc.),
            # but do not remove needed existing restrictions when editing.
            # browser_key_restrictions { ... }
            # server_key_restrictions  { ... }
            # android_key_restrictions { ... }
            # ios_key_restrictions     { ... }
          }
        }
        ```

        This change does not force replacement of the API key; the `restrictions.api_targets` field is updated in place by the API.

        To verify, run `terraform plan` and ensure it shows an in-place update on `google_apikeys_key.RESTRICTED_API_KEY` adding or modifying the `restrictions.api_targets` block so that only the intended services (and optionally methods) are allowed.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
