> ## 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 specific hosts and apps 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 Specific Hosts And Apps" for GCP using GCP console, follow the below steps:

        1. Open the GCP Console and navigate to the API Manager Dashboard.

        2. Select the API key that you want to restrict.

        3. Click on the "Edit" button to edit the API key.

        4. In the "Application restrictions" section, select the "HTTP referrers (web sites)" option.

        5. Add the hostnames or IP addresses of the specific hosts and apps that should be allowed to use the API key.

        6. Click on the "Save" button to save the changes.

        By following these steps, you have successfully restricted the API key to specific hosts and apps. Now, the API key will only work if the requests are made from the allowed hosts and apps.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Ensure API Keys Are Restricted To Specific Hosts And Apps" for GCP using GCP CLI, follow these steps:

        1. Open the Google Cloud Console and select the project for which you want to remediate the misconfiguration.

        2. Open the Cloud Shell by clicking on the icon at the top right corner of the console.

        3. In the Cloud Shell, enter the following command to list all the API keys in the project:

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

        4. Identify the API key that needs to be restricted and copy its name.

        5. Enter the following command to update the API key and restrict it to specific hosts and apps:

        ```
        gcloud beta services api-keys update [API_KEY_NAME] --allowed-ips=[IP_ADDRESS_RANGE] --allowed-apps=[APP_PACKAGE_NAME]
        ```

        Replace \[API\_KEY\_NAME] with the name of the API key you identified in step 4.

        Replace \[IP\_ADDRESS\_RANGE] with the IP address range that should be allowed to use the API key. For example, you can use "192.168.0.0/16" to allow all IP addresses in the range 192.168.0.0 to 192.168.255.255.

        Replace \[APP\_PACKAGE\_NAME] with the name of the app package that should be allowed to use the API key. For example, you can use "com.example.myapp" to allow only the app with that package name to use the API key.

        6. Verify that the API key has been updated by entering the following command:

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

        This will display the updated configuration for the API key.

        By following these steps, you have successfully remediated the misconfiguration "Ensure API Keys Are Restricted To Specific Hosts And Apps" for GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of ensuring API keys are restricted to specific hosts and apps in GCP using Python, follow these steps:

        1. First, you need to create a new API key or update an existing one using the Cloud Console or the Cloud SDK.

        2. Once you have the API key, you can restrict it to specific hosts and apps by creating a new API key restriction.

        3. To create an API key restriction, you can use the Google Cloud IAM API in Python. Here is a sample code snippet to create an API key restriction:

        ```python theme={null}
        import google.auth
        from google.oauth2.credentials import Credentials
        from google.auth.transport.requests import AuthorizedSession
        from google.cloud.iam_credentials_v1 import IAMCredentialsClient
        from google.cloud.iam_credentials_v1.types import GenerateAccessTokenRequest

        # Set the API key name and the list of allowed hosts and apps
        api_key_name = "my-api-key"
        allowed_hosts = ["example.com", "app.example.com"]
        allowed_apps = ["my-app"]

        # Get the IAM credentials client and the current credentials
        credentials, project = google.auth.default()
        iam_credentials_client = IAMCredentialsClient(credentials=credentials)

        # Get the API key metadata
        metadata_server_url = "http://metadata.google.internal/computeMetadata/v1/"
        metadata_flavor = {"Metadata-Flavor": "Google"}
        metadata_url = f"{metadata_server_url}/instance/service-accounts/default/token"
        metadata_response = AuthorizedSession().get(metadata_url, headers=metadata_flavor)
        metadata = metadata_response.json()
        access_token = metadata["access_token"]

        # Create the API key restriction
        parent = f"projects/-/serviceAccounts/{project}.iam.gserviceaccount.com"
        response = iam_credentials_client.generate_access_token(
            name=parent,
            delegates=[],
            scope=["https://www.googleapis.com/auth/cloud-platform"],
            audience=f"https://{api_key_name}.googleapis.com",
            include_email=True,
            options={"api_access_configs": [{"access_levels": [], "service": f"{api_key_name}.googleapis.com", "method": "*", "locations": allowed_hosts, "condition": {"expression": f"request.path.startsWith('/{app}/')"}}]},
            )

        # Print the new access token
        print(response.access_token)
        ```

        In this code snippet, we first set the API key name and the list of allowed hosts and apps. Then, we get the IAM credentials client and the current credentials using the `google.auth.default()` function. Next, we get the API key metadata and create the API key restriction using the `iam_credentials_client.generate_access_token()` method. Finally, we print the new access token.

        Note that you need to replace the `allowed_hosts` and `allowed_apps` lists with your own values. Also, make sure to replace `my-api-key` with the name of your API key.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_apikeys_key" "RESTRICTED_API_KEY" {
          # Substitute with your project ID
          project = "PROJECT_ID"

          # Substitute with a human‑readable name for the key
          display_name = "DISPLAY_NAME_FOR_KEY"

          # Option 1: Restrict to specific HTTP referrer hosts (browser-style usage)
          restrictions {
            browser_key_restrictions {
              # Substitute with the exact host patterns that are allowed to use this key
              # e.g. "https://app.example.com/*"
              allowed_referrers = [
                "ALLOWED_REFERRER_PATTERN_1",
                "ALLOWED_REFERRER_PATTERN_2",
              ]
            }

            # Optionally also restrict which Google APIs this key may call
            api_targets {
              # Substitute with API service names, e.g. "translate.googleapis.com"
              service = "ALLOWED_GOOGLE_API_SERVICE_1"
            }
            api_targets {
              service = "ALLOWED_GOOGLE_API_SERVICE_2"
            }
          }

          # ---------------------------------------------------------------------------
          # Alternative restriction modes (pick ONE type per key as appropriate):
          #
          # 1) Restrict by client IPs (server-side use only):
          # restrictions {
          #   server_key_restrictions {
          #     allowed_ips = [
          #       "ALLOWED_CIDR_OR_IP_1",
          #       "ALLOWED_CIDR_OR_IP_2",
          #     ]
          #   }
          #   api_targets {
          #     service = "ALLOWED_GOOGLE_API_SERVICE"
          #   }
          # }
          #
          # 2) Restrict to Android apps:
          # restrictions {
          #   android_key_restrictions {
          #     allowed_applications {
          #       sha1_fingerprint = "ANDROID_APP_SHA1_FINGERPRINT"
          #       package_name     = "ANDROID_PACKAGE_NAME"
          #     }
          #   }
          #   api_targets {
          #     service = "ALLOWED_GOOGLE_API_SERVICE"
          #   }
          # }
          #
          # 3) Restrict to iOS apps:
          # restrictions {
          #   ios_key_restrictions {
          #     allowed_bundle_ids = [
          #       "IOS_BUNDLE_ID_1",
          #       "IOS_BUNDLE_ID_2",
          #     ]
          #   }
          #   api_targets {
          #     service = "ALLOWED_GOOGLE_API_SERVICE"
          #   }
          # }
          # ---------------------------------------------------------------------------
        }
        ```

        This change updates the existing API key in place; it does not force replacement, but any clients not matching the configured hosts/apps or API targets will start failing once applied.

        For verification, `terraform plan` should show an update to `google_apikeys_key.RESTRICTED_API_KEY` adding a `restrictions` block (or tightening existing restrictions) and no `-/+` replacement of the key resource.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
