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

# Google.iam.admin.v1.disableserviceaccount

### Event Information

* **Event meaning and impact**
  * `google.iam.admin.v1.DisableServiceAccount` indicates a service account has been disabled via IAM Admin API (or equivalent console/CLI action).
  * All access tokens and credentials for that service account will fail for new requests; existing long‑lived connections may break depending on service.
  * This is often part of incident response, key rotation, or decommissioning workflows.

* **Operational and security considerations**
  * Correlate with actor and method: check `protoPayload.authenticationInfo.principalEmail`, `requestMetadata.callerIp`, and `resourceName` to validate it was an authorized change.
  * Review workloads using this service account (GCE, GKE, Cloud Run, CI/CD, etc.) to avoid unintended outages; if unintentional, re‑enable with `EnableServiceAccount` and rotate credentials.
  * Monitor for follow‑up errors (e.g., `PERMISSION_DENIED`, `SERVICE_ACCOUNT_DISABLED`) in logs of dependent services.

* **Compliance and governance (e.g., ISO 27001, SOC 2, PCI, HIPAA)**
  * Treat this event as a privileged identity lifecycle change; ensure it is logged in Cloud Audit Logs and retained per your evidence requirements.
  * Verify that disabling was performed by a role with least privilege (e.g., `roles/iam.serviceAccountAdmin`) and, if required, associated with a change ticket or approval record.
  * Include alerts on `DisableServiceAccount` in your SIEM to detect suspicious or mass disable actions that could indicate misuse or an ongoing security incident.

### Examples

* **Active workload or application identity disabled (outage + privilege confusion)**
  * Example: A production GKE cluster or Cloud Run service uses a service account for Datastore and Pub/Sub; disabling it breaks token issuance, causing 5xx errors and failed background jobs, violating availability requirements in SOC 2/ISO 27001.
  * Mitigation: Implement change control + break-glass accounts; monitor `DisableServiceAccount` via Cloud Audit Logs + SCC and alert on critical workload identities.

* **Security tooling / logging identity disabled (loss of detective controls)**
  * Example: A service account used by a SIEM forwarder or Cloud Logging export to a central security project is disabled; logs stop flowing, undermining PCI DSS/ISO 27001 logging, monitoring, and incident investigation requirements.
  * Mitigation: Tag security-critical service accounts; restrict who can disable them; configure log-based alerts for `DisableServiceAccount` on security + logging projects.

* **Incident response or key-rotation automation broken (response gaps + stale credentials)**
  * Example: A service account used by automation to rotate secrets in Secret Manager or revoke IAM keys is disabled; credentials remain active longer than policy allows, increasing exposure and violating CIS/GCP Benchmarks and NIST key-management controls.
  * Mitigation: Separate automation identities with strong RBAC; require approvals for disabling; periodically verify that security automations can authenticate and run.

### Remediation

#### Using Console

* **Immediately re‑enable or replace the disabled service account (restore availability & controls)**
  * In Console: go to **IAM & Admin → Service Accounts → (project)** → locate the account (filter by email / label), click the **three‑dot menu → Enable**.
  * If “Enable” is not available (e.g., deleted beyond recovery window), create a **new service account** with least privilege, reattach it to:
    * GKE: update **Workload Identity / node SA / imagePullSecrets** in `Deployment`/`StatefulSet` specs.
    * Cloud Run: edit service, set **Security → Service account**, redeploy.
    * Logging/SIEM exporters: edit **log sink / Pub/Sub subscriber / forwarding agent** configuration to use the new identity.
  * Validate: confirm requests succeed (no 5xx), logs/export flows resume, and automation (IR/key‑rotation) jobs authenticate and complete.

* **Harden controls to prevent accidental/unauthorized DisableServiceAccount (SOC2/ISO/PCI/NIST alignment)**
  * Restrict who can disable SAs:
    * In Console: **IAM & Admin → IAM**, remove broad roles like **Owner/Editor**; grant **Service Account Admin (roles/iam.serviceAccountAdmin)** only to a small change‑control group; for security/logging/automation SAs, use **Deny Policies** (Preview/GA):
      * **IAM & Admin → Deny policies → Create policy**, target project/folder, add rule:
        * **Condition**: resource is a critical service account (use `resource.name` or labels).
        * **Deny principals**: all except a security break‑glass group.
        * **Permissions**: `iam.serviceAccounts.disable`.
  * Tag critical SAs (workloads, logging, IR/rotation):
    * In **Service Accounts → (SA) → Edit**, add label like `critical=workload`, `critical=logging`, `critical=ir-automation`; document them in your asset inventory / CMDB for SOC 2 / ISO 27001 Annex A.5 & A.8.
  * Implement change control: require tickets/approvals for any SA lifecycle change; tie this to your CAB and evidence for SOC 2 CC9 / ISO 27001 A.8 & A.12.

* **Monitor and test: log‑based alerts on DisableServiceAccount + periodic SA health checks**
  * Create log‑based alert on `DisableServiceAccount` (Cloud Audit Logs → Logging):
    * Go to **Logging → Logs Explorer** and use:
      ```text theme={null}
      protoPayload.methodName="google.iam.admin.v1.IAM.DisableServiceAccount"
      ```
    * Click **Create alert**, scope to org/folder/project; set **Notification channels** (email, SMS, webhook, PagerDuty).
    * For security/logging projects, refine filter to critical SAs (by email or label) and set severity to **CRITICAL** to meet PCI DSS / ISO 27001 logging & monitoring requirements.
  * In **Security Command Center** (if enabled): create **custom module / detector** on the same log pattern and wire to incident response workflows (playbooks, SOAR).
  * Schedule periodic “can‑I‑auth” tests (e.g., Cloud Scheduler → Cloud Run/Functions) that:
    * Use each security / logging / key‑rotation SA to perform a minimal action (`secrets.versions.access`, `logging.sinks.get`, etc.).
    * Fail and alert if tokens cannot be issued or calls fail with `PERMISSION_DENIED` or `SERVICE_ACCOUNT_DISABLED`, providing evidence for CIS/GCP Benchmarks and NIST key‑management/IR controls.

#### Using CLI

* **Prevent & detect risky `DisableServiceAccount` operations (all scenarios)**
  * Enforce change control (e.g., via tickets) and least privilege: create a custom IAM role without `iam.serviceAccounts.disable` and only grant the **Service Account Admin** role (`roles/iam.serviceAccountAdmin`) to a small break-glass/admin group.
  * Create an org/folder log-based metric on `DisableServiceAccount` and alert (SOC 2, ISO 27001, PCI):
    ```bash theme={null}
    gcloud logging metrics create sa_disable_count \
      --description="Count of DisableServiceAccount calls" \
      --log-filter='resource.type="service_account"
        protoPayload.methodName="google.iam.admin.v1.IAM.DisableServiceAccount"'
    gcloud alpha monitoring policies create \
      --notification-channels="projects/PROJECT_ID/notificationChannels/CHANNEL_ID" \
      --conditions='metric.type="logging.googleapis.com/user/sa_disable_count", aggregations.alignmentPeriod="60s", comparison="COMPARISON_GT", thresholdValue=0'
    ```
  * Periodically enumerate disabled service accounts and review against change records (CIS / NIST CM):
    ```bash theme={null}
    gcloud iam service-accounts list --filter="disabled:true" --format="table(email, disabled, description)"
    ```

* **Protect production workload & security/logging identities (availability + detective controls)**
  * Tag critical SAs via description/labels and use IAM Conditions to restrict who can disable them (SOC 2/ISO A.12/A.16):
    ```bash theme={null}
    gcloud iam service-accounts update SA_NAME@PROJECT_ID.iam.gserviceaccount.com \
      --description="CRITICAL: prod-gke-datastore-pubsub"

    gcloud organizations set-iam-policy ORG_ID policy.yaml
    # Example in policy.yaml: deny disabling critical SAs
    # - members: ["user:admin@example.com"]
    #   role: "roles/iam.serviceAccountAdmin"
    #   condition:
    #     title: "NoDisableCriticalSA"
    #     expression: '!(request.resource.description.startsWith("CRITICAL:"))'
    ```
  * For security/logging SAs, verify export pipelines regularly (PCI DSS / ISO logging):
    ```bash theme={null}
    # Check if logging sink SA exists and is enabled
    gcloud logging sinks list
    gcloud iam service-accounts describe SINK_SA@PROJECT_ID.iam.gserviceaccount.com
    ```
  * If a critical SA was disabled, re-enable, then do a post-incident review:
    ```bash theme={null}
    gcloud iam service-accounts enable SA_NAME@PROJECT_ID.iam.gserviceaccount.com
    gcloud logging read \
      'protoPayload.methodName="google.iam.admin.v1.IAM.DisableServiceAccount"
       protoPayload.request.name:"SA_NAME@PROJECT_ID.iam.gserviceaccount.com"' \
      --limit=10 --format="json"
    ```

* **Validate incident-response / key-rotation automation & implement health checks**
  * Separate automation SAs (key rotation, IR) from app SAs and grant minimal roles aligned with CIS/NIST key management; keep a dedicated break-glass SA stored offline.
  * Implement scheduled authentication checks for automation SAs (e.g., Cloud Scheduler + Cloud Function) to detect disabled/broken automation:
    ```bash theme={null}
    # As each automation SA: run a trivial call to ensure it works
    gcloud secrets versions list SOME_SECRET --project=PROJECT_ID \
      --impersonate-service-account=AUTOMATION_SA@PROJECT_ID.iam.gserviceaccount.com
    ```
  * After re-enabling automation SAs, immediately run manual key/secret rotations to close gaps:
    ```bash theme={null}
    gcloud secrets versions add SECRET_ID --data-file=/path/new_secret
    gcloud iam service-accounts keys create key.json \
      --iam-account=AUTOMATION_SA@PROJECT_ID.iam.gserviceaccount.com
    ```

#### Using Python

* **Detect & alert on `DisableServiceAccount` (critical workloads, logging, IR automation)**

  ```python theme={null}
  # Detect recently disabled service accounts via Cloud Asset Inventory (requires CAI API)
  from google.cloud import asset_v1
  from datetime import datetime, timedelta, timezone

  project_id = "my-project-id"
  scope = f"projects/{project_id}"
  client = asset_v1.AssetServiceClient()

  window_minutes = 60
  now = datetime.now(timezone.utc)
  time_window = now - timedelta(minutes=window_minutes)

  # Query IAM policies for disabled service accounts via Asset Search
  # Note: This uses a basic filter on "disabled: true" in the asset IAM policy bindings.
  request = asset_v1.SearchAllResourcesRequest(
      scope=scope,
      query='assetType="iam.googleapis.com/ServiceAccount" AND state:DISABLED'
  )

  print(f"Disabled service accounts in last {window_minutes} minutes:")
  for resp in client.search_all_resources(request=request):
      # You can extend below to filter by resp.update_time to match time_window
      print(resp.name, resp.additional_attributes)
  ```

  ```python theme={null}
  # Example of a Log-based alert filter for Cloud Audit Logs (configure via console/Terraform):
  # resource.type="project"
  # protoPayload.methodName="google.iam.admin.v1.IAM.DisableServiceAccount"
  # AND
  # (protoPayload.request.name:"projects/my-critical-project/serviceAccounts/" OR
  #  protoPayload.request.name:"projects/my-logging-project/serviceAccounts/" OR
  #  protoPayload.request.name:"projects/my-ir-project/serviceAccounts/")
  #
  # Use this filter in:
  # - Log-based alerting policy (to page on-call)
  # - Log sink to SCC / SIEM for correlation with outage/log-drop events
  ```

* **Protect & classify critical service accounts (workload, logging, IR/rotation)**

  ```python theme={null}
  # Tag/annotate critical SAs and restrict disable permissions
  from google.cloud import iam_admin_v1

  project_id = "my-project-id"
  critical_sas = [
      "workload-prod@datastore-sa.iam.gserviceaccount.com",
      "logging-forwarder@logging-sa.iam.gserviceaccount.com",
      "sec-automation@key-rotation-sa.iam.gserviceaccount.com",
  ]

  client = iam_admin_v1.IAMClient()

  for sa_email in critical_sas:
      name = f"projects/{project_id}/serviceAccounts/{sa_email}"
      sa = client.get_service_account(name=name)
      # Use SA.display_name / description to mark critical function & owners for change control
      sa.display_name = f"[CRITICAL] {sa.display_name}"
      sa.description = (
          (sa.description or "") +
          " | Do NOT disable. Subject to SOC2/ISO27001/PCI DSS logging & IR controls."
      )[:256]
      client.update_service_account(service_account=sa)
      print(f"Updated metadata for {sa_email}")
  ```

  * IAM hardening (via console/Terraform/Deployment Manager):
    * Create a custom role without `iam.serviceAccounts.disable` / `iam.serviceAccounts.update` and use it for routine operators.
    * Limit `roles/iam.serviceAccountAdmin` to a small CAB/break-glass group only.
    * For security/logging projects, enforce IAM Conditions on `DisableServiceAccount` operations (where possible) and align with SOC 2 / ISO 27001 change-control policies.

* **Continuity checks & break-glass for workloads, logging, and automation**

  ```python theme={null}
  # Simple Python health-check: verify that critical SAs can still obtain tokens
  # Run periodically from Cloud Run / Cloud Functions with Security Admin privileges.
  from google.oauth2 import service_account
  from google.auth.transport.requests import Request
  import json
  import sys

  CRITICAL_SA_KEYS = [
      "/secure-path/workload-prod-sa.json",
      "/secure-path/logging-forwarder-sa.json",
      "/secure-path/ir-automation-rotation-sa.json",
  ]

  def check_sa_token(path):
      try:
          creds = service_account.Credentials.from_service_account_file(
              path,
              scopes=["https://www.googleapis.com/auth/cloud-platform"],
          )
          creds.refresh(Request())
          return True, None
      except Exception as e:
          return False, str(e)

  failures = []
  for key_path in CRITICAL_SA_KEYS:
      ok, err = check_sa_token(key_path)
      if not ok:
          failures.append((key_path, err))
          print(f"[FAIL] {key_path}: {err}", file=sys.stderr)
      else:
          print(f"[OK] {key_path}")

  if failures:
      # Integrate with Cloud Monitoring custom metric or Pub/Sub -> PagerDuty
      # This supports CIS / NIST key-management & IR automation availability controls.
      sys.exit(1)
  ```

  * Maintain a dedicated “break-glass” project + SA with tightly controlled access and pre-approved process to re-enable or re-key disabled SAs to restore production workloads, SIEM/log forwarding, and IR automation within RTO/RPO requirements.
  * Periodically (e.g., monthly) test:
    * Workload service accounts can call Datastore/Pub/Sub;
    * Logging/SIEM SAs are exporting logs;
    * Secret Manager / key-rotation automation can still authenticate and rotate secrets (evidence for SOC 2 / ISO 27001 / PCI DSS / CIS controls).
