> ## 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.

# User managed service no admin remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using GCP console, follow the below steps:

        1. Login to the Google Cloud Console with your credentials.
        2. Navigate to the "IAM & Admin" section of the console.
        3. Select "Service Accounts" from the left-hand menu.
        4. Locate the user-managed service account that has admin privileges.
        5. Click on the service account to open its details page.
        6. Click on the "Permissions" tab.
        7. Scroll down to the "Role" section and click the "Edit" button.
        8. Remove the admin role from the service account by unchecking the box next to the role.
        9. Click "Save" to save the changes.
        10. Verify that the service account no longer has admin privileges by checking the "Permissions" tab.

        By following these steps, you have successfully remediated the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using GCP console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using GCP CLI, follow the below steps:

        1. Identify the user-managed service account that has admin privileges using the following command:

        ```
        gcloud iam service-accounts list
        ```

        2. Once you have identified the service account, remove the admin role from the service account using the following command:

        ```
        gcloud projects remove-iam-policy-binding [PROJECT_ID] --member=serviceAccount:[SERVICE_ACCOUNT_EMAIL] --role=roles/owner
        ```

        Replace `[PROJECT_ID]` with your project ID and `[SERVICE_ACCOUNT_EMAIL]` with the email address of the service account.

        3. Verify that the admin role has been removed from the service account using the following command:

        ```
        gcloud projects get-iam-policy [PROJECT_ID] --flatten="bindings[].members" --format='table(bindings.role)' --filter="bindings.members:serviceAccount:[SERVICE_ACCOUNT_EMAIL]"
        ```

        Replace `[PROJECT_ID]` with your project ID and `[SERVICE_ACCOUNT_EMAIL]` with the email address of the service account.

        This should remediate the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using Python, you can follow the below steps:

        1. First, you need to identify all the user-managed service accounts that have admin privileges. You can use the following code to do this:

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

        # Set the required scopes
        SCOPES = ['https://www.googleapis.com/auth/cloud-platform']

        # Set the credentials using the service account key file
        credentials = service_account.Credentials.from_service_account_file(
            'path/to/service_account_key.json', scopes=SCOPES)

        # Build the IAM Service client object
        iam_service = build('iam', 'v1', credentials=credentials)

        # Get all the IAM policies for the project
        policy = iam_service.projects().getIamPolicy(resource='projects/PROJECT_ID').execute()

        # Get all the user-managed service accounts with admin privileges
        for binding in policy['bindings']:
            if 'roles/owner' in binding['role']:
                for member in binding['members']:
                    if 'user-managed' in member:
                        print(f"{member} has admin privileges")
        ```

        Replace `path/to/service_account_key.json` with the path to your service account key file and `PROJECT_ID` with your GCP project ID.

        2. Once you have identified the user-managed service accounts with admin privileges, you can remove the admin role from them using the following code:

        ```
        from googleapiclient.errors import HttpError

        # Set the user-managed service account email
        user_managed_service_account = 'user-managed-service-account@PROJECT_ID.iam.gserviceaccount.com'

        # Set the role to be removed
        role = 'roles/owner'

        # Build the IAM Service client object
        iam_service = build('iam', 'v1', credentials=credentials)

        # Get the current IAM policy for the project
        policy = iam_service.projects().getIamPolicy(resource='projects/PROJECT_ID').execute()

        # Remove the role from the user-managed service account
        for binding in policy['bindings']:
            if role in binding['role'] and user_managed_service_account in binding['members']:
                binding['members'].remove(user_managed_service_account)

        # Update the IAM policy for the project
        try:
            updated_policy = iam_service.projects().setIamPolicy(resource='projects/PROJECT_ID', body={'policy': policy}).execute()
            print(f"{user_managed_service_account} no longer has admin privileges")
        except HttpError as e:
            print(f"Error updating IAM policy: {e}")
        ```

        Replace `PROJECT_ID` with your GCP project ID and set the `user_managed_service_account` variable to the email address of the user-managed service account that you want to remove the admin role from.

        These steps will remediate the misconfiguration "User Managed Service Account Should Not Have Admin Privileges" in GCP using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Service account definition (already exists in your config)
        resource "google_service_account" "APP_SERVICE_ACCOUNT" {
          account_id   = "APP_SERVICE_ACCOUNT_ID"   # e.g. "my-app-sa"
          display_name = "APP_SERVICE_ACCOUNT_NAME" # e.g. "My App Service Account"
        }

        # REMOVE any high-privilege bindings like owner/admin/editor from this service account.
        # Delete or edit existing bindings/members that look like this:

        # EXAMPLE: overly permissive binding to Owner (REMOVE or change role)
        # resource "google_project_iam_member" "app_sa_owner" {
        #   project = "GCP_PROJECT_ID"
        #   role    = "roles/owner"
        #   member  = "serviceAccount:${google_service_account.APP_SERVICE_ACCOUNT.email}"
        # }

        # EXAMPLE: overly permissive binding to Editor (REMOVE or change role)
        # resource "google_project_iam_member" "app_sa_editor" {
        #   project = "GCP_PROJECT_ID"
        #   role    = "roles/editor"
        #   member  = "serviceAccount:${google_service_account.APP_SERVICE_ACCOUNT.email}"
        # }

        # EXAMPLE: overly permissive admin role (REMOVE or change role)
        # resource "google_project_iam_member" "app_sa_admin" {
        #   project = "GCP_PROJECT_ID"
        #   role    = "roles/compute.admin" # or any other *admin role
        #   member  = "serviceAccount:${google_service_account.APP_SERVICE_ACCOUNT.email}"
        # }

        # If the service account still needs access, re-grant only the minimal roles required.
        # For example, a read-only role instead of admin:
        resource "google_project_iam_member" "app_sa_viewer" {
          project = "GCP_PROJECT_ID" # replace with your project ID
          role    = "roles/viewer"   # replace with the least-privilege role actually needed
          member  = "serviceAccount:${google_service_account.APP_SERVICE_ACCOUNT.email}"
        }
        ```

        Removing or changing IAM bindings does not replace the service account itself, but it can immediately affect what that service account is allowed to do (potential runtime impact for workloads using it).

        For verification, `terraform plan` should show the `google_project_iam_member` resources with admin/owner/write roles being destroyed or having their `role` argument changed, and only least-privilege roles remaining attached to the service account.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
