diff --git a/.github/workflows/alert-delivery-check.yml b/.github/workflows/alert-delivery-check.yml new file mode 100644 index 000000000..6b12095ba --- /dev/null +++ b/.github/workflows/alert-delivery-check.yml @@ -0,0 +1,109 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Independent Scheduled Alert-Delivery Verification (POAM-2026-230 Property 4) +# +# Runs outside GKE, Cloud Monitoring, and Cloud Pub/Sub using keyless GitHub OIDC +# Workload Identity Federation (`google_service_account.alert_verifier` in +# `infra/targets/gcp-gke/wif.tf`). Any failure in: +# - runtime AlertPolicy channel bindings or channel-set equality, +# - synthetic `alert_pipeline_heartbeat` delivery to the terminal Pub/Sub sink, or +# - periodic in-cluster `compliance-bridge` notifier heartbeat freshness +# fails this GitHub Actions workflow run directly — surfacing through GitHub's +# independent workflow-failure channel rather than depending on the alert +# channels under test. + +name: Scheduled Alert Delivery Verification + +on: + schedule: + - cron: "17 */6 * * *" + workflow_dispatch: + inputs: + emit_ondemand_bridge_probe: + description: "Also publish an immediate synthetic compliance-bridge probe to CAGE_ALERT_VERIFY_PUBSUB_TOPIC" + required: false + type: boolean + default: false + +permissions: + contents: read + id-token: write + +concurrency: + group: alert-delivery-check + cancel-in-progress: false + +jobs: + verify-alert-delivery: + name: Verify Cloud Monitoring & Notifier Pub/Sub Delivery + if: github.repository == 'google/cybernetic-agent-governance-engine' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Fail closed if verifier WIF or target variables are unset + env: + WIF_PROVIDER: ${{ vars.CAGE_ALERT_VERIFIER_WIF_PROVIDER }} + WIF_SA: ${{ vars.CAGE_ALERT_VERIFIER_SERVICE_ACCOUNT }} + TARGET_PROJECT: ${{ vars.CAGE_ALERT_VERIFY_GCP_PROJECT }} + TARGET_SUBSCRIPTION: ${{ vars.CAGE_ALERT_VERIFY_PUBSUB_SUBSCRIPTION }} + run: | + set -euo pipefail + missing=() + [[ -z "${WIF_PROVIDER}" ]] && missing+=("CAGE_ALERT_VERIFIER_WIF_PROVIDER") + [[ -z "${WIF_SA}" ]] && missing+=("CAGE_ALERT_VERIFIER_SERVICE_ACCOUNT") + [[ -z "${TARGET_PROJECT}" ]] && missing+=("CAGE_ALERT_VERIFY_GCP_PROJECT") + [[ -z "${TARGET_SUBSCRIPTION}" ]] && missing+=("CAGE_ALERT_VERIFY_PUBSUB_SUBSCRIPTION") + if (( ${#missing[@]} > 0 )); then + echo "::error::[POAM-2026-230] Missing required repository variables for independent alert-delivery verification: ${missing[*]}" + exit 1 + fi + + - name: Mint short-lived GCP access token via keyless WIF + id: gcp_auth + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 + with: + workload_identity_provider: ${{ vars.CAGE_ALERT_VERIFIER_WIF_PROVIDER }} + service_account: ${{ vars.CAGE_ALERT_VERIFIER_SERVICE_ACCOUNT }} + token_format: access_token + create_credentials_file: false + export_environment_variables: false + + - name: Verify runtime AlertPolicy bindings and terminal Pub/Sub heartbeat delivery + env: + GOOGLE_OAUTH_ACCESS_TOKEN: ${{ steps.gcp_auth.outputs.access_token }} + TARGET_PROJECT: ${{ vars.CAGE_ALERT_VERIFY_GCP_PROJECT }} + TARGET_CLUSTER: ${{ vars.CAGE_ALERT_VERIFY_CLUSTER_NAME || 'cage-staging' }} + TARGET_SUBSCRIPTION: ${{ vars.CAGE_ALERT_VERIFY_PUBSUB_SUBSCRIPTION }} + EXPECTED_CHANNEL: ${{ vars.CAGE_ALERT_VERIFY_EXPECTED_CHANNEL }} + TARGET_TOPIC: ${{ vars.CAGE_ALERT_VERIFY_PUBSUB_TOPIC }} + EMIT_PROBE: ${{ inputs.emit_ondemand_bridge_probe || false }} + run: | + set -euo pipefail + extra_args=() + if [[ -n "${EXPECTED_CHANNEL}" ]]; then + extra_args+=(--expected-channel "${EXPECTED_CHANNEL}") + fi + if [[ "${EMIT_PROBE}" == "true" && -n "${TARGET_TOPIC}" ]]; then + extra_args+=(--emit-bridge-heartbeat-topic "${TARGET_TOPIC}") + fi + python3 scripts/verify_alert_delivery.py \ + --project "${TARGET_PROJECT}" \ + --cluster-name "${TARGET_CLUSTER}" \ + --subscription "${TARGET_SUBSCRIPTION}" \ + "${extra_args[@]}" diff --git a/CHANGELOG.md b/CHANGELOG.md index a85a973ea..669169bc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Changed +- **Enforcing postures fail closed on unbound or disabled Cloud Monitoring channels and console `compliance-bridge` notifiers, single-replica rollout scrape noise and orphaned pod-series incidents are eliminated, and an independent scheduled CI workflow verifies Pub/Sub destination delivery** (`fix(infra)!`, [`alert_routing.tf`](infra/targets/gcp-gke/alert_routing.tf), [`lula_alerting.tf`](infra/targets/gcp-gke/lula_alerting.tf), [`metrics_alerting.tf`](infra/targets/gcp-gke/metrics_alerting.tf), [`wif.tf`](infra/targets/gcp-gke/wif.tf), [`compliance_bridge/main.tf`](infra/modules/compliance_bridge/main.tf), [`notifier.py`](src/compliance_bridge/notifier.py), [`verify_alert_delivery.py`](scripts/verify_alert_delivery.py), [`alert-delivery-check.yml`](.github/workflows/alert-delivery-check.yml), [`POAM.md`](docs/POAM.md)). + - Renames `lula_alert_notification_channels` and `lula_alert_owner` to target-wide `var.alert_notification_channels` and `var.alert_owner_label`, resolves every bound channel at plan time via `data.google_monitoring_notification_channel.bound`, and places an enforcing-posture `lifecycle` `precondition` directly on all nine `google_monitoring_alert_policy` resources (including the new synthetic `alert_pipeline_heartbeat` policy). + - Adds `PubSubNotifier` (`ALERT_CHANNEL=pubsub`, CAGE's reference-architecture terminal sink), enforces external notifier configuration at both Terraform plan time (`kubernetes_deployment.compliance_bridge`) and pod startup (`validate_notifier_config()` / `create_notifier()` raising `NotifierConfigError` with zero silent fallback to `ConsoleNotifier`), records `alerted` / `remediation_sent` strictly from observed destination acknowledgement (`bool`), and emits periodic non-paging SLA heartbeats. + - Eliminates orphaned per-pod incidents after ReplicaSet rotation (`REDUCE_SUM` / `REDUCE_MAX` pod-series aggregation plus `alert_strategy.auto_close = "1800s"` across all policies) and single-replica rolling-deploy scrape-liveness alert fatigue (`max by (job, namespace) (up == 0)`, `[10m]` `absent_over_time` lookback, `duration = "600s"`), which accounted for 69% (`24/35`) of `cage-staging` notifications. + - Adds pure-stdlib [`verify_alert_delivery.py`](scripts/verify_alert_delivery.py) and keyless OIDC workflow [`alert-delivery-check.yml`](.github/workflows/alert-delivery-check.yml) (`cage-alert-verifier` GSA) to verify runtime channel-set equality and observe both Cloud Monitoring and `compliance-bridge` heartbeats at the terminal Pub/Sub subscription without consuming operational alerts. + - **BREAKING — Terraform variables & notifier startup:** `lula_alert_notification_channels` (`list(string)`) and `lula_alert_owner` are replaced by `alert_notification_channels` (`list(object)`) and `alert_owner_label`, enforcing postures require `compliance_alert_channel` (`pubsub`, `slack`, `webhook`, or `pagerduty`), and `send_critical_alert()` / `send_remediation_followup()` return `bool`. See `AL-01` in [`BREAKING_CHANGES.md`](docs/BREAKING_CHANGES.md). + - **Committing runs seal, evidence and return the params the stages evaluated, and an approval is consumed only by a run whose evaluated params it covers** (`fix(governance)!`, [`governor.py`](src/gateway/governance/governor/governor.py), [`sealing.py`](src/gateway/governance/governor/sealing.py), [`approval.py`](src/gateway/governance/governor/approval.py), [`defer_queue.py`](src/gateway/governance/defer_queue.py), [`governance_envelope.py`](src/gateway/governance/governance_envelope.py), [`governance_middleware.py`](src/gateway/server/governance_middleware.py), [`cage_finance/tools/tool_provider.py`](src/cage_finance/tools/tool_provider.py), [`cage_healthcare/tools/tool_provider.py`](src/cage_healthcare/tools/tool_provider.py), [`ADR-008`](docs/adr/ADR-008-wire-phantom-gates-into-production-call-paths.md)). - Committing runs sealed and evidenced the caller's pre-binding params instead of the params the stages evaluated. `govern()` and `revalidate_post_hitl()` now bind the action's server inputs exactly once; the stages, the seal, the `GOVERNANCE_DECISION` record, refusal receipts and deferral snapshots all name the resulting evaluated params, and the run returns them with the seal as `SealedAction(action, seal, params)`. Tools verify the seal against, and actuate, `SealedAction.params`; the finance tool no longer binds before governance and refuses a NARROW receipt that names other params. - `revalidate_post_hitl()` checks `PostHitlApproval.covers(evaluated)` before any stage runs, refusing an uncovered request `[APPROVAL_NOT_REDEEMABLE]` without spending the approval, and spends it with `PostHitlApproval.spend(evaluated)`, whose `DeferQueue.consume_approval()` compare-and-swap re-checks coverage of the same params. The gateway's `DeferQueue.redeemable_approval()` pre-check is state-only. diff --git a/compliance/lula/lula-validation-ir6.yaml b/compliance/lula/lula-validation-ir6.yaml index 6f17f6719..f000a5ed0 100644 --- a/compliance/lula/lula-validation-ir6.yaml +++ b/compliance/lula/lula-validation-ir6.yaml @@ -17,9 +17,11 @@ # # Asserts that the compliance-bridge service is running and ready in the cluster. # The compliance-bridge (src/compliance_bridge/) handles incident notification -# via audit_workflow.py and notifier.py — it is the primary incident reporting -# mechanism for this system, sending alerts to Slack/PagerDuty on critical -# compliance failures (ISO 42001 A.9.2, SC-4, AU-12 violations). +# via audit_workflow.py, sla_monitor.py, and notifier.py — in CAGE's reference +# architecture it publishes critical compliance alerts to GCP Cloud Pub/Sub +# (PubSubNotifier, verified terminal sink; POAM-2026-230), with optional +# Slack/Webhook/PagerDuty downstream fan-out, and refuses to start in enforcing +# postures if ALERT_CHANNEL is unset or set to console/mock. # # Domain: kubernetes → compliance-bridge Deployment # Provider: opa (inline Rego) @@ -36,15 +38,15 @@ component-definition: uuid: af8c8932-9540-5dda-8799-2696a2adf618 metadata: title: CAGE Validation — IR6 - last-modified: '2026-07-01T13:18:54Z' - version: 1.0.0 + last-modified: '2026-11-22T21:45:00Z' + version: 1.0.1 oscal-version: 1.1.2 remarks: |- Auto-converted from standalone lula validation format. Region: US_FED. Posture: nist-sp800-53. Notes: NIST SP 800-53 Rev 5 IR-6: Incident Reporting. Namespace: governance-stack (confirmed from live cluster deployment snapshot). Automated verification that the compliance-bridge incident reporting service is live and operational. The compliance-bridge (src/compliance_bridge/) provides: - - Real-time Slack/PagerDuty alerting via notifier.py - - Compliance audit workflow with critical-failure alerting via audit_workflow.py + - Verified GCP Cloud Pub/Sub alert publishing (reference-architecture terminal sink) plus optional Slack/Webhook/PagerDuty fan-out via notifier.py, enforced fail-closed at pod startup in enforcing postures (POAM-2026-230) + - Compliance audit workflow with observed-delivery critical-failure alerting via audit_workflow.py - The /v1/metrics/* API endpoints consumed by other Lula validations IR-6 requires that security incidents be reported to appropriate organizational officials and external authorities within defined timeframes — the compliance-bridge is the automated first-responder for this requirement. See: compliance/continuous-monitoring/ISCM_STRATEGY.md — IR-6 monitoring cadence. See: docs/operations/JURISDICTION_INVENTORY.md — ISSO/ISSM incident response chain. components: diff --git a/docs/BREAKING_CHANGES.md b/docs/BREAKING_CHANGES.md index 246e9c365..1745db5bb 100644 --- a/docs/BREAKING_CHANGES.md +++ b/docs/BREAKING_CHANGES.md @@ -1417,4 +1417,35 @@ All six authenticated gateway surfaces now enforce out-of-band `SC-7` workload q --- -**Last updated:** November 21, 2026 +## Unreleased — Fail-Closed Cloud Monitoring Alert Channel Resolution & Compliance-Bridge Notifier Startup Contract (`POAM-2026-230`) + +`infra/targets/gcp-gke/` and `src/compliance_bridge/notifier.py` remove silent empty-channel and console-fallback alerting in enforcing postures, rename the misleadingly Lula-prefixed target-wide alert variables, and return observed boolean delivery confirmations from notifier methods. + +| Item | Area | Clean Break Description | Architectural Rationale | Failure Mode on Stale Caller | +|---|---|---|---|---| +| **AL-01** | Target-wide Cloud Monitoring channel resolution, `compliance-bridge` notifier startup validation, and observed delivery return types ([`variables.tf`](../infra/targets/gcp-gke/variables.tf), [`alert_routing.tf`](../infra/targets/gcp-gke/alert_routing.tf), [`lula_alerting.tf`](../infra/targets/gcp-gke/lula_alerting.tf), [`metrics_alerting.tf`](../infra/targets/gcp-gke/metrics_alerting.tf), [`compliance_bridge/main.tf`](../infra/modules/compliance_bridge/main.tf), [`notifier.py`](../src/compliance_bridge/notifier.py)) | Renames `lula_alert_notification_channels` (`list(string)`) to `var.alert_notification_channels` (`list(object({ display_name, type, labels, name }))`), resolved at plan time via `data.google_monitoring_notification_channel.bound` and guarded by a `lifecycle` `precondition` on all nine `google_monitoring_alert_policy` resources. Renames `lula_alert_owner` to `var.alert_owner_label`. Requires `var.compliance_alert_channel` (`pubsub`, `slack`, `webhook`, or `pagerduty`) plus its destination topic/secret in enforcing postures at both Terraform plan time (`kubernetes_deployment.compliance_bridge` precondition) and pod startup (`validate_notifier_config()` / `create_notifier()` raising `NotifierConfigError`, with zero silent fallback to `ConsoleNotifier`). `send_critical_alert()` and `send_remediation_followup()` now return `bool` (`ConsoleNotifier` returns `False`). | Defaulting `lula_alert_notification_channels = []` without plan-time resolution and pinning `alert_channel = "console"` shipped silent alerting across every enforcing profile (`POAM-2026-230`), handing adopters enabled policies that route nowhere and `alerted = True` audit records backed only by stdout logs. | 1. **Stale variable names (`lula_alert_notification_channels` / `lula_alert_owner`):** Passing `-var=lula_alert_notification_channels=...` or `-var=lula_alert_owner=...` on the CLI fails with `Error: Value for undeclared variable` (`The root module does not declare a variable named "lula_alert_notification_channels"`). Keeping either key in `.tfvars` / `terraform.auto.tfvars` emits `Warning: Value for undeclared variable` and ignores the value, leaving `var.alert_notification_channels = []` so `terraform plan` fails closed on the `[POAM-2026-230]` `google_monitoring_alert_policy` preconditions. Migrate to the structured object list below. 2. **Out-of-band channel deletion or disablement:** If a channel listed in `alert_notification_channels` is deleted out-of-band in GCP, `data.google_monitoring_notification_channel.bound` fails plan refresh with `Cannot find notification channel with display_name=...`; recreate the channel (`gcloud beta monitoring channels create`) to apply, or pass `-var='alert_notification_channels=[]'` to `terraform destroy` during teardown. If disabled (`enabled = false`), re-enable via `gcloud beta monitoring channels update --enabled`. 3. **Unset / `console` notifier in `staging` or `prod`:** Fails at `terraform plan` (`kubernetes_deployment.compliance_bridge` precondition) and at pod startup (`NotifierConfigError`). 4. **Test doubles:** `send_critical_alert()` / `send_remediation_followup()` mocks must return `True` (`AsyncMock(return_value=True)`) when simulating confirmed delivery. | + +**Migration (gitignored `terraform.auto.tfvars`, see [`terraform.auto.tfvars.example`](../infra/targets/gcp-gke/terraform.auto.tfvars.example)):** +```hcl +# Before (retired — triggers 'Value for undeclared variable' + [POAM-2026-230] precondition): +# lula_alert_owner = "secops-oncall" +# lula_alert_notification_channels = ["projects//notificationChannels/"] + +# After (AL-01): +alert_owner_label = "secops-oncall" +alert_notification_channels = [ + { + display_name = "cage-staging-alerts-pubsub" + type = "pubsub" + name = "projects//notificationChannels/" # optional pin + } +] +compliance_alert_channel = "pubsub" +alert_pubsub_topic = "projects//topics/cage-staging-alerts" +alert_verify_pubsub_subscription = "cage-staging-alerts-verify" +``` + +--- + +**Last updated:** November 22, 2026 + diff --git a/docs/POAM.md b/docs/POAM.md index d3267ab50..a04aad9d6 100644 --- a/docs/POAM.md +++ b/docs/POAM.md @@ -125,8 +125,8 @@ The following findings are tracked as open items with target remediation dates. | POAM-2026-222 | CA-7 / RA-3 / SI-4 / PM-9 | **Threshold Traceability Matrix monitoring column cites telemetry that was never emitted; RA-001–RA-004 held unsigned until every row has a disposition.** The `Langfuse Metric` column and Appendix B of [`THRESHOLD_TRACEABILITY_MATRIX.md`](../compliance/risk_acceptance/THRESHOLD_TRACEABILITY_MATRIX.md) (CAGE-TTM-001, dated `2026-03-06`, present in root commit `1902c92c`) name 26 `cage.*` metrics for 23 thresholds. None has ever been emitted by `src/` or `infra/`; the column describes a Langfuse custom-metric backend that was never built (the first metric emitter landed `2026-08-15`, and every emitted metric is a `cage_*` Prometheus series). `#769` withdrew one name under `POAM-2026-010`; the remaining 25 names across 22 rows each need an owner disposition (implement, re-point, or withdraw and reopen), and THR-LAT-001 also misnames the quantity it bounds: FIN-2 enforces quote age at receipt, not trade round-trip latency. Zero OSCAL statements or census rows cite the column, and RA-001–RA-004 are unsigned. **The Moderate rating rests on the signing hold, not on that timing:** RA-001–RA-004 and the CAGE-TTM-001 approval block must not be signed until every row has a recorded disposition, and a signature applied earlier raises this item to High. Owner: Authorizing Official, the signatory of RA-001–RA-004 (detail section) | Moderate | 2026-12-31 | | POAM-2026-224 | CA-2 / CA-7 / PL-2 | **Gate G9's `KNOWN_DOCUMENTED_GAPS` waiver hid citations of artifacts that never existed, `DOC_SCOPE` leaves most of `docs/` unverified, and G9 does not verify `#heading-slug` anchors.** The waiver in [`check_doc_references.py`](../scripts/check_doc_references.py) excused 160 targets: 129 never existed in any commit, 28 were retired, and 3 exist at HEAD. It was described as deliberate NIST RMF gap citations but applied to every document in scope, so it hid the 2026-Q1 SAR and the authorization boundary document citing a security assessment plan at a path that exists in no commit (re-pointed there by `a2a338b8` after the draft plan they first cited was deleted in `00442dec`), and the SSP outline citing never-existent OSCAL assessment-plan and POA&M files. A hand sweep of the `2026-03-06` document cohort found them; the gate did not. Without the waiver, at `eca0c553` the current `DOC_SCOPE` (69 documents) had 17 broken references in 9 documents, and all of `docs/` except `docs/partners/**` had 299 in 52. **Remediated in part (`2026-11-15`):** the waiver is deleted, the 17 references are corrected or pinned, the SAR is retracted under a verified notice ([`SAR_2026Q1.md`](../compliance/archive/retracted/SAR_2026Q1.md)), and `AGENTS.md` states the real scope. **Anchor gap (`2026-11-19`, `#822`):** `check_doc_references.py` checks file paths and Python symbols but ignores `#heading-slug` fragments (e.g., `AGENTS.md#external-vendor-adapter-standards-plugin-architecture` in [`EVALUATOR_GUIDE.md`](EVALUATOR_GUIDE.md)), passing as long as the target file exists even if restructuring deletes the heading. **Agent-context size gate (`2026-11-20`):** [`check_agents_size.py`](../scripts/check_agents_size.py) previously hard-coded [`AGENTS.md`](../AGENTS.md) alone against binary `24,576` B (576 B above the observed ~`24,000` B truncation point, leaving [`.agents/rules/reasoning.md`](../.agents/rules/reasoning.md), [`.agents/rules/security.md`](../.agents/rules/security.md), [`.agents/workflows/enforce_cloud_build.md`](../.agents/workflows/enforce_cloud_build.md), and the `24,001..24,576` B band unchecked) and was unwired in CI and pre-commit hooks; it now discovers all repo-scoped agent-injected files via `discover_injected_agent_files()` (`MAX_BYTES = 24000`, `MIN_INJECTED_FILES = 3`) and runs in `ci.yml::lint`, [`setup_git_hooks.sh`](../scripts/setup_git_hooks.sh), and `Makefile::docs-check` ([`test_check_agents_size.py`](../tests/unit/test_check_agents_size.py)); host-level instruction files under `~/.gemini/config/rules/` are also injected into agent context and sit outside any repo-scoped gate. Open until `DOC_SCOPE` covers all of `docs/` except `docs/partners/**` and G9 validates `#heading-slug` anchors (detail section) | Moderate | 2026-12-31 | | POAM-2026-228 | SI-10 / SC-24 / AU-3 / CA-7 | **Advisor `GatewayClient`, `safety_node`, `explainer_node`, `server.py` `QueryCache`, and `provider_02` adapter misclassify un-evidenced `HTTP 403`s and `GATEWAY_ERROR`s across four human/operational/latent surfaces (plus un-evidenced policy-drift replay).** While [`CageClient._handle_deny_response()`](../packages/cage-client/src/cage_client/core.py) rejects any `HTTP 403` lacking `proof_hash`/`audit_id` with `CageGatewayError`, [`_raise_unrouted()`](../src/governed_financial_advisor/infrastructure/gateway_client.py) and [`_route_trade()`](../src/governed_financial_advisor/graph/nodes/safety_node.py) collapsed every `status_code == 403` into `PermissionError` / `GOVERNANCE_DENIED` (`recoverable=True`), [`_is_policy_drift()`](../src/governed_financial_advisor/infrastructure/gateway_client.py) in [`_AdvisorTransport.handle_async_request()`](../src/governed_financial_advisor/infrastructure/gateway_client.py) triggered a `/governance/policy-version` refresh + trade replay on un-evidenced `403`s mentioning `"Substrate Policy Drift Detected"`, and [`_blocked()`](../src/governed_financial_advisor/graph/nodes/safety_node.py) (plus [`LangGraphHarness.tla`](../proof/LangGraphHarness.tla) `SafetyDeny`) incremented `consecutive_denials` on `GATEWAY_ERROR`, polluting four surfaces: **(1)** `POST /agent/query` user-facing reply in [`explainer_node()`](../src/governed_financial_advisor/graph/nodes/explainer_node.py) (false policy-probing violation after two infrastructure failures), **(2)** 30-day Cloud Logging operational `ERROR` records (non-custody operational logs, not WORM audit evidence), **(3)** [`query_agent()`](../src/governed_financial_advisor/server.py) `QueryCache` guard (skipping `query_cache.set()` only on `guardrail_blocked`), and **(4)** [`_classify_terminal_path()`](../src/integrations/provider_02/adapter.py) in [`Provider02AttestationCallback`](../src/integrations/provider_02/adapter.py) (classifying `GATEWAY_ERROR` as `"cbf_block"`). **Qualification & boundary (`2026-11-16`):** The `0`-of-`27` count in `cage-staging` `cage:evidence:stream` (`2026-11-09`–`2026-11-16`) is an empirical observation over low-volume synthetic traffic, **not** a structural guarantee; while neither the advisor nor Linkerd emits `GOVERNANCE_REFUSAL` records, this client-side split cannot catch false refusals that the gateway itself signs with a valid `proof_hash` during internal dependency outages (tracked separately in `POAM-2026-233`). **Remediated in code (`2026-11-16`):** first-class `safety_status = "GATEWAY_ERROR"` ([`state.py`](../src/governed_financial_advisor/graph/state.py), [`agent_state_schema.json`](../compliance/schemas/agent_state_schema.json)), refusal-evidence-gated `_is_policy_drift()`, invariant `consecutive_denials` in [`_gateway_error()`](../src/governed_financial_advisor/graph/nodes/safety_node.py) and [`LangGraphHarness.tla`](../proof/LangGraphHarness.tla) `SafetyTransportError` (`83,729` TLC states, `0` violations), deterministic `GATEWAY_ERROR` halt in `explainer_node()`, `QueryCache` approval filter, and `provider_02` `"unknown"` terminal-path guard, verified by [`test_poam_228_gateway_error_split.py`](../tests/unit/test_poam_228_gateway_error_split.py); remains Open pending mainline squash-merge SHA (detail section) | Moderate | 2026-11-30 | -| POAM-2026-230 | SI-4 / AU-5 / AU-12 / CA-7 / IR-4 / IR-6 / ISO 42001 A.5.3 | **Every Cloud Monitoring alert policy routes nowhere: all eight bind `var.lula_alert_notification_channels`, which defaults to `[]`, has no validation, and is set by no committed profile; the compliance-bridge notifier writes only log lines.** The eight `google_monitoring_alert_policy` resources in [`lula_alerting.tf`](../infra/targets/gcp-gke/lula_alerting.tf) and [`metrics_alerting.tf`](../infra/targets/gcp-gke/metrics_alerting.tf) (Lula audit failure and dead-man, Lula auditor restart, metrics scrape liveness, sustained refusal ratio, zero permitted requests, canary probes absent, canary pod health, evidence-append reconciliation) take their channels from [`variables.tf`](../infra/targets/gcp-gke/variables.tf) L788–792, and none of the eight committed tfvars profiles or `terraform.auto.tfvars.example` sets it, so every enforcing profile (`staging`, `prod`, `eu-prod`, `apac-prod`, `eu-dev`, `apac-dev`) creates all eight with no recipient. Live `cage-staging` read on `2026-11-16`: all eight enabled, `0` channels each, `0` notification channels in the project. The `owner` user label is a label, not a recipient, and [`lula_cron.tftest.hcl`](../infra/targets/gcp-gke/tests/lula_cron.tftest.hcl) proves propagation of a channel no profile supplies, so the control looked operational. **Folded in `2026-11-16`:** the compliance-bridge notifier is pinned to `alert_channel = "console"` ([`main.tf`](../infra/targets/gcp-gke/main.tf) L937) in every profile, so `notifier.send_critical_alert()` writes a log line while the SSP, the SP 800-53 profile and several documents describe Slack and PagerDuty delivery. **Defect window** opens per policy from `#704` (`600de728`, `2026-11-09`) to `#749` (`05275d02`, `2026-11-14`) and covers `prod`; **impact window** is `cage-staging` and the two Gate W clean-room projects built from the staging profile, synthetic traffic only (no production deployment exists), and **realised on `2026-11-16`**: the staging canary crash-looped from creation and `lula-audit` failed every run (24/26 satisfied); their alert policies held their conditions and nobody was notified — and for the Lula dead-man, compliance-bridge pod restarts independently re-armed the 6h `STARTUP_GRACE_HOURS` window across 9h (`15:01Z`–`00:12Z`), silencing `_check_lula_audit_deadman()` so even a wired notification channel would not have paged (`POAM-2026-234`, two independent failures in the alarm path). Text saying these alerts page, notify or alert an owner or on-call is false for every committed profile: the documentation and compliance artifacts carry a dated `2026-11-16` correction, and the Terraform comments and alert `documentation` strings are corrected in the remediation PR. The planned canary (`POAM-2026-231`) and fiscal `UNKNOWN`-resolution (`POAM-2026-232`) items depend on this one. Closes on plan-time channel validity and, for the notifier, start-time alert-config validity, plan- and run-time bindings on every policy and alert emitter, heartbeat delivery observed at every bound channel's destination, and a check failure path independent of those channels (detail section) | Moderate | 2026-11-30 | -| POAM-2026-231 | SI-4 / AU-5 / CA-7 / SA-11 | **The `#746` canary and gated-request metrics are biased toward healthy, the canary cannot boot on an enforcing deployment of `main`, and its single read-only probe is blind to mutating/CBF-path outages.** (1) Whenever the probe is admitted, one mechanism has three effects: under DEFER or REQUIRE_APPROVAL parking the canary's own HTTP 200 counts `permitted`, so `gateway_zero_permitted_requests` cannot fire; about five permitted probes per 5 minutes raise the sustained-refusal trigger from 5 blocked requests to at least 95; and [`run_canary_probe_once()`](../src/gateway/canary.py) reads a `payload.governance.verdict` field the gateway does not send, so `verdict in ("ALLOW", None)` passes every HTTP 200, while `run_canary_loop()` discards the result. Under hard denial (`403`/`503`, probe included) the probe is refused and zero-permitted works as designed. (2) For real traffic, `handle_defer()` and `handle_require_approval()` do not call `mark_request_refused()`, so DEFER, REQUIRE_APPROVAL and OPA MANUAL_REVIEW count `permitted` and the refusal ratio is understated. (3) [`gateway_canary.tf`](../infra/targets/gcp-gke/gateway_canary.tf) does not pass `CAGE_DEPLOYMENT_REGION`, which `#764` made mandatory under an enforcing posture, and no test checks that boot contract across workload manifests, so the canary crash-loops on every enforcing deployment; on `cage-staging` it has not completed a probe, and on `2026-11-16` silent detection was compounded across two independent alarm-path failures — zero notification channels (`POAM-2026-230`) plus compliance-bridge restarts re-arming 6h `STARTUP_GRACE_HOURS` across 9h (`15:01Z`–`00:12Z`) and silencing `_check_lula_audit_deadman()` while `lula-audit` failed every run (`POAM-2026-234`). (4) **Coverage blind spot realised on `2026-11-19` (`POAM-2026-238`):** after the canary booted on `cage-staging`, it continuously reported `HTTP 200 OK` on read-only `market_analysis` throughout `POAM-2026-238`'s live wedge while `100%` of `execute_trade` calls returned `403` `CBF_RECONCILED_BALANCE_SEQUENCE_REPLAY_DETECTED` (`seq=2187..2191`, WORM batch `000000002185-000000002191.ndjson`); closure now requires a failure-mode coverage contract specifying which governance failures must turn the canary red rather than a fixed action-class list. Defect window from `#746` (`f0ca9f4d`, `2026-11-14`), boot failure from `#764` (`3347b4b1`, `2026-11-15`); impact: staging, synthetic traffic only. Depends on `POAM-2026-230` and `POAM-2026-233` (detail section) | Moderate | 2026-12-15 | +| POAM-2026-230 | SI-4 / AU-5 / AU-12 / CA-7 / IR-4 / IR-6 / ISO 42001 A.5.3 | **Every Cloud Monitoring alert policy previously routed nowhere (`var.lula_alert_notification_channels = []`), the compliance-bridge notifier wrote only log lines, and the reference alert configuration carried two adopter-facing incident/rollout defects (Findings A & B); remediated in code (`2026-11-22`), open pending mainline merge, `cage-staging` rollout + live heartbeat verification, and `v4.1.0` release-body erratum.** Prior to remediation (`c5de2555`), the eight `google_monitoring_alert_policy` resources in [`lula_alerting.tf`](../infra/targets/gcp-gke/lula_alerting.tf) and [`metrics_alerting.tf`](../infra/targets/gcp-gke/metrics_alerting.tf) bound an unvalidated `default = []` channel list set by no committed profile, while `compliance-bridge` pinned `alert_channel = "console"`. **Defect window** opens per policy from `#704` (`600de728`, `2026-11-09`) to `#749` (`05275d02`, `2026-11-14`) and covers `prod`; **impact window** is `cage-staging` and the two torn-down Gate W clean-room projects, synthetic traffic only, **realised on `2026-11-16`** when the staging canary crash-looped and `lula-audit` failed (`24/26`) with zero notification channels (compounded by restart-extended `STARTUP_GRACE_HOURS` in `POAM-2026-234`). **Reference-architecture terminal sink amendment (`2026-11-22`, Property 3):** because CAGE is a reference architecture and not a deployed production service, GCP Cloud Pub/Sub (`topics/cage-staging-alerts` → `subscriptions/cage-staging-alerts-verify`) is the verified terminal destination by design; personal email, SMS, and commercial paging fan-out are out of scope rather than permanently unmet work. **Non-destructive 35-message Pub/Sub read-back (`2026-11-22`, Criterion 6)** after `cage-staging-alerts-pubsub` bound on `2026-11-19T16:07:46Z` (`2c2cae96`) surfaced two adopter-facing reference-configuration defects folded into this item: **Finding A** (`3` orphaned `gateway_canary_pod_health` `open` notifications from `2026-11-16`/`11-18` held open up to GCP's 7-day default after pod deletion due to missing `REDUCE_SUM`/`REDUCE_MAX` and `auto_close`) and **Finding B** (`24/35` messages — `69%` of the queue, `12` `open`/`closed` pairs across `6` rolling deploys — from `[5m]` `absent_over_time` / unaggregated `up == 0` firing during every 6–7m single-replica turnover), alongside `8` `lula_audit_failure` messages (`4` `open`/`closed` pairs, `0` at `2026-11-22T18:00Z` `seq=743`). **Remediated in code (`2026-11-22`, `AL-01`):** [`alert_routing.tf`](../infra/targets/gcp-gke/alert_routing.tf) and [`variables.tf`](../infra/targets/gcp-gke/variables.tf) rename variables to `alert_notification_channels` and `alert_owner_label`, resolve channels via `data.google_monitoring_notification_channel.bound`, enforce `lifecycle` `precondition`s across all `9` policies (including `alert_pipeline_heartbeat`), add `REDUCE_SUM`/`REDUCE_MAX` + `auto_close = "1800s"` (Finding A) and `[10m]`/`600s` `max by (job, namespace)` scrape liveness (Finding B); [`notifier.py`](../src/compliance_bridge/notifier.py) adds `PubSubNotifier`, enforces startup config validity (`NotifierConfigError`), and returns observed `bool` delivery; [`lula-validation-ir6.yaml`](../compliance/lula/lula-validation-ir6.yaml) and Terraform strings are corrected; and [`verify_alert_delivery.py`](../scripts/verify_alert_delivery.py) + [`alert-delivery-check.yml`](../.github/workflows/alert-delivery-check.yml) (`cage-alert-verifier` in [`wif.tf`](../infra/targets/gcp-gke/wif.tf)) provide independent scheduled verification. Remains **Open** pending merge, `cage-staging` rollout + live heartbeat run, and `v4.1.0` GitHub release-body edit (detail section) | Moderate | 2026-11-30 | +| POAM-2026-231 | SI-4 / AU-5 / CA-7 / SA-11 | **The `#746` canary and gated-request metrics are biased toward healthy, the canary cannot boot on an enforcing deployment of `main`, and its single read-only probe is blind to mutating/CBF-path outages.** (1) Whenever the probe is admitted, one mechanism has three effects: under DEFER or REQUIRE_APPROVAL parking the canary's own HTTP 200 counts `permitted`, so `gateway_zero_permitted_requests` cannot fire; about five permitted probes per 5 minutes raise the sustained-refusal trigger from 5 blocked requests to at least 95; and [`run_canary_probe_once()`](../src/gateway/canary.py) reads a `payload.governance.verdict` field the gateway does not send, so `verdict in ("ALLOW", None)` passes every HTTP 200, while `run_canary_loop()` discards the result. Under hard denial (`403`/`503`, probe included) the probe is refused and zero-permitted works as designed. (2) For real traffic, `handle_defer()` and `handle_require_approval()` do not call `mark_request_refused()`, so DEFER, REQUIRE_APPROVAL and OPA MANUAL_REVIEW count `permitted` and the refusal ratio is understated. (3) [`gateway_canary.tf`](../infra/targets/gcp-gke/gateway_canary.tf) does not pass `CAGE_DEPLOYMENT_REGION`, which `#764` made mandatory under an enforcing posture, and no test checks that boot contract across workload manifests, so the canary crash-loops on every enforcing deployment; on `cage-staging` it has not completed a probe, and on `2026-11-16` silent detection was compounded across two independent alarm-path failures — zero notification channels (`POAM-2026-230`) plus compliance-bridge restarts re-arming 6h `STARTUP_GRACE_HOURS` across 9h (`15:01Z`–`00:12Z`) and silencing `_check_lula_audit_deadman()` while `lula-audit` failed every run (`POAM-2026-234`). (4) **Coverage blind spot realised on `2026-11-19` (`POAM-2026-238`) and independently corroborated by Cloud Monitoring delivery logs (`2026-11-22`):** after the canary booted on `cage-staging`, it continuously reported `HTTP 200 OK` on read-only `market_analysis` throughout `POAM-2026-238`'s `16:08:53Z`–`16:09:00Z` wedge while `100%` of `execute_trade` calls returned `403` `CBF_RECONCILED_BALANCE_SEQUENCE_REPLAY_DETECTED` (`seq=2187..2191`, WORM batch `000000002185-000000002191.ndjson`) — and the `2026-11-22` Pub/Sub read-back (`POAM-2026-230`) confirmed that `cage-staging-alerts-pubsub` was bound to all eight policies at `2026-11-19T16:07:46Z`, **67 seconds before** the wedge, yet `gateway_sustained_refusal_ratio` emitted `0` notifications in `subscriptions/cage-staging-alerts-verify` across all `35` queued messages, proving on live telemetry and live alert delivery that a total mutating-path wedge occurred in front of an active, wired refusal-ratio alarm without tripping it; closure now requires a failure-mode coverage contract specifying which governance failures must turn the canary red rather than a fixed action-class list. Defect window from `#746` (`f0ca9f4d`, `2026-11-14`), boot failure from `#764` (`3347b4b1`, `2026-11-15`); impact: staging, synthetic traffic only. Depends on `POAM-2026-230` and `POAM-2026-233` (detail section) | Moderate | 2026-12-15 | | POAM-2026-232 | SC-4 / SC-24 / SI-10 / AU-10 / SA-8 | **The UNKNOWN actuation lifecycle is broken at four stages: classification, fiscal reclamation, surfacing and resubmission.** (1) Prior to `2026-11-17`, a post-dispatch broker failure settled REJECTED because [`ActuationReceipt`](../src/gateway/governance/seams/actuation.py) derived `outcome` from `accepted` when omitted (`c5de2555^:src/gateway/governance/seams/actuation.py` L253–259), cancellation left no receipt, healthcare reported UNKNOWN as BLOCKED, and partner adapters mapped by status alone; `#797` (`3dfb453d`) and `#801` (`f58592ec`) landed the required `outcome` seam (`DA-01`), post-wire/duplicate-`422` `UNKNOWN` settlement, shielded `CancelledError` receipts, and healthcare `INDETERMINATE` (partner `actuator_01`/`actuator_02` classifiers remain open), **activating Stage 2**. (2) UNKNOWN now settles `executed=True`, so `FiscalLimitGuard.confirm()` counts the amount for the remainder of the UTC calendar day (`fiscal:daily_limit:%Y-%m-%d` via [`_window_key()`](../src/cage_finance/safety/fiscal_limit_guard.py) L222–224 — **bounded to at most one UTC day / `<= 24h` per incident**, never cumulative across days); nothing reconciles fiscal spend against fills, `reclaim_expired()` covers only never-settled reservations, and nothing alarms, while CBF debits drain through reconciliation snapshots. (3) `/tools/execute` (`#789` `127eebc2`) maps `ActuationIndeterminateError` and `SymbolicGovernorViolation` to HTTP 200 `status: "ERROR"` dicts without domain-agnostic seam exception typing across callers. (4) The advisor hands a possible fill to the trading model as a plain tool error and loops back, and a re-proposal gets a fresh idempotency key: double-execution safety that depends on a model choosing not to retry is not a control. Defect windows per stage, the earliest from root commit `1902c92c` (`2026-06-01`); impact: staging, synthetic traffic only. Because the UTC daily spend reset bounds Stage 2 capacity loss to one day per incident, `POAM-2026-233` leads ahead of this item; depends on `POAM-2026-230` (detail section) | High | 2026-12-15 | | POAM-2026-233 | AU-10 / AU-3 / SI-11 / SC-24 / AC-3 / SI-4 | **Infrastructure failures are recorded and signed as policy refusals (false attestation).** Blocking when a dependency fails is correct and stays fail-closed; the defect is the record. Prior to `#803` (`f6817f2f`, `FA-1`), `evaluate_policy()` (`c5de2555^:src/gateway/core/policy.py`) returned the policy string `DENY` for every OPA failure (open breaker, latency budget, timeout, transport error, `5xx`/`408`/`429`, other non-2xx, malformed or undefined reply, any local exception), as the `PolicyClient` (`c5de2555^:src/gateway/governance/contracts.py` lines 1287-1290) contract required, so the `OPA_ERROR` branch of `OpaStage` (`c5de2555^:src/gateway/governance/governor/stages/opa.py` lines 100-114) could not fire for a conforming client and each failure became HARD `OPA_DENY` ("OPA Denied Action"). Server-input source outages (refused under the UCA breach's own code), DeferQueue and execution-ledger outages during approval redemption (`APPROVAL_NOT_REDEEMABLE`, "no unconsumed approval"), causal-telemetry outages, consensus without an inference backend and stage exceptions (`TIER_EXCEPTION`) take the same path. Every occurrence, not an occasional one, hash-chains a `GOVERNANCE_REFUSAL` through `handle_deny()`, and the `403` paths add a KMS-signed `GOVERNANCE_REFUSAL_RECEIPT`. A recorded, re-runnable search found 25 consumers that act on the refusal, among them a human approval spent by `_spend_refused()`, the advisor's two-strike denial budget, the compliance bridge's control-effectiveness score (which a false refusal raises) and DPO training pairs harvested from refusal receipts. Realized on staging inside the retained 30 days: 8 `execute_trade` refusals on 2026-10-25 caused by a local telemetry `TypeError`, and `CAUSAL_TELEMETRY_UNAVAILABLE` refusals on 2026-10-22. **Published Gate W certification negative result (`2026-11-16`, narrowed `2026-11-17` in `#805` `555b1346`):** recomputing per-control metrics across all three published Gate W WORM archives (`8956f505`, `fa772122-clean-room`, `fa772122-recovery`) confirmed `0` OPA-outage or infrastructure-failure refusals and `safety_rate = 1.0000` across all five `SUPPORTED_CONTROLS` (`A.5.2`, `A.5.3`, `A.8.4`, `A.9.2`, `SC-4`) even with all refusal, deferral, receipt, and block records excluded — published certification ratings and Lula Active ratings were **not** contaminated (vacuous census `HOLDS` rows tracked in `POAM-2026-235`); Cause 1 (OPA unavailability) remediated in `#803` (`f6817f2f`, `FA-1`), and Causes 2 (server-input source outages), 3 (`DeferQueue` redemption + `ExecutionLedger`), and 6 (stage/rollback exceptions + `CBF`/`FiscalLimitGuard` store/reconciliation unavailability + `FTRA_ERROR`/`FTRA_REGISTRY_UNAVAILABLE`) plus Consumer 10's AST-gated explicit quarantine trigger ledger ([`check_violation_quarantine_ledger.py`](../scripts/check_violation_quarantine_ledger.py)) are remediated in `#817` (`2c2cae96`, `FA-2`; `2026-11-18` intentional red-half staging drill `seq=616..632` on `d5646d90`, two `9c588192` green-half dual-DB staging drill runs — `2026-11-19` `seq=2228..2249` and `2026-11-20T00:38Z` `seq=2738..2759` — and a post-`#853` (`dcfaab47` / `d05c7b95`) re-execution on `2026-11-22T02:25Z` `seq=5753..5773` against modified `cbf_engine.py`/`barrier_tier.py` tagged in detail section), while Causes 4 (causal telemetry) and 5 (consensus configuration), residual rule-body `except` blocks, and remaining downstream consumers stay open on `POAM-2026-233` (detail section) | High | 2026-11-30 | | POAM-2026-234 | CA-7 / SI-4 / AU-5 / SA-11 | **Systematic favourable-error bias across measurement, rating, alerting, and count surfaces (plus live unfavourable-direction latch instances).** Independent measurement defects across gateway metrics, the canary probe, alert routing, compliance-bridge ratings/freshness, and Lula audit reporting all err in the same direction — reporting the system healthier, fresher, or more compliant than it is. Newly confirmed in the 2026-11-16 rating-contamination audit on top of `POAM-2026-230`, `POAM-2026-231`, and `POAM-2026-233`: (1) [`_is_control_effective_record()`](../src/compliance_bridge/metrics.py) scores `GOVERNANCE_REFUSAL`, `GOVERNANCE_REFUSAL_RECEIPT`, unpersisted `GOVERNANCE_DEFERRAL` (`persisted=False`), and fail-closed `SC-7` quarantine `INFERENCE_PROXY_BLOCK` records as control effectiveness and refreshes evidence age in [`sp800-53-component-definition.yaml`](../compliance/oscal/sp800-53-component-definition.yaml) `ca-7`/`ir-6`/`si-4` SLA monitors (published Gate W archives `8956f505` and `fa772122` verified uncontaminated at `safety_rate = 1.0000` across the 5 `SUPPORTED_CONTROLS` even with all refusals/blocks excluded, while the OSCAL census carried vacuous `HOLDS` and decayed `read_back`s tracked in `POAM-2026-235`); (2) [`_fetch_from_evidence_stream_sync()`](../src/compliance_bridge/metrics.py) sets `evidence_age_seconds = 0.0` when `total_traces == 0` or only failing `lula_audit` records exist, so [`_check_sla_once()`](../src/compliance_bridge/sla_monitor.py) silently passes dark controls (`A.9.2`, `SC-8`, `SC-7`, `AU-2`, `SI-7` on staging); (3) every compliance-bridge restart resets `_DEPLOYMENT_START_UTC` and activates `STARTUP_GRACE_HOURS` (6h), silencing [`_check_lula_audit_deadman()`](../src/compliance_bridge/sla_monitor.py) across 9 hours of staging restarts on `2026-11-16` while [`run_lula_audit.sh`](../infra/modules/lula_cron/run_lula_audit.sh) counts `startup_grace` controls (`lula-validation-a52`, `lula-validation-a92`) in `satisfied_controls`; and (4) [`get_last_passing_lula_audit_age_seconds()`](../src/compliance_bridge/metrics.py) previously reset the dead-man timer on `insufficient_traffic` runs (**remediated `2026-11-22` across `#855` `da4d82a5` and two-question separation**: [`get_last_passing_lula_audit_age_seconds()`](../src/compliance_bridge/metrics.py) / `cage_lula_audit_last_pass_timestamp_seconds` tracks strictly `26/26` statistical satisfaction — verified `0.0` at `18:00Z` on `cage-staging` — while [`get_last_healthy_lula_audit_age_seconds()`](../src/compliance_bridge/metrics.py) / `cage_lula_audit_last_healthy_run_timestamp_seconds` tracks `2 × schedule` auditor & structural liveness on `evaluated_count >= 26` and `failed_count == 0`, preventing permanent dead-man latching on canary-only clusters). **Further instances (`2026-11-17`–`2026-11-22`):** external fork pull-request check rollups display `no failing checks` while workflow runs wait in `action_required` with zero of the nine ruleset-`25966171` required checks executed (`mergeStateStatus` stayed `BLOCKED`), gateway OTLP trace export drops `100%` of spans on HTTP `401` with zero Prometheus counter or readiness signal (`POAM-2026-236`), `POST /v1/chat/completions` (along with `/governance/state-commitments` and `/v1/nemo/*`) omitted confirmed `SC-7` workload-quarantine `403` refusals from `cage_governance_refusals_total`, understating the refusal ratio (closed incidentally on `2026-11-21` in `#848` via consolidated [`_emit_quarantine_refusal()`](../src/gateway/server/quarantine_guard.py)), and **(live *unfavourable-direction* instances, `2026-11-22`)** self-referential control-evaluation feedback plus uncached cold-store timeout (`POAM-2026-201` / `POAM-2026-244`, **closed `2026-11-22`** via `#855` `da4d82a5` + `#856` `905893b5` + scheduled `job.batch/lula-audit-29922840` `seq=743`). Closes upon complete enumeration and failure-direction determination of every metric, rating, alert, and count, backed by a shared measurement inventory consumed by a bidirectional failure-direction gate (detail section) | Moderate | 2026-12-15 | @@ -1987,7 +1987,7 @@ Nothing else read the flag. The earlier `staging.tfvars` comment saying it turns 2. Require each entry's `display_name` to name an owner/purpose, and enforce the format with a resource precondition, not a `validation` block on `variable "authorized_networks"` in [`variables.tf`](../infra/targets/gcp-gke/variables.tf). A sweep of `scripts/`, `.github/`, `infra/`, `tests/` and the docs on `2026-11-03` found no producer that follows an `owner:purpose` convention. All of the following must be migrated in the same change, or they fail at plan: - **Committed profiles:** [`prod.tfvars`](../infra/targets/gcp-gke/prod.tfvars) (`line 72`), [`apac-prod.tfvars`](../infra/targets/gcp-gke/apac-prod.tfvars) (`line 95`), [`eu-prod.tfvars`](../infra/targets/gcp-gke/eu-prod.tfvars) (`line 96`), [`dev.tfvars`](../infra/targets/gcp-gke/dev.tfvars) (`line 42`), [`us-dev.tfvars`](../infra/targets/gcp-gke/us-dev.tfvars) (`line 106`), [`apac-dev.tfvars`](../infra/targets/gcp-gke/apac-dev.tfvars) (`line 99`), and [`eu-dev.tfvars`](../infra/targets/gcp-gke/eu-dev.tfvars) (`line 99`). - **Generated at run time:** the `"deployer-egress"` entry in [`staging_lifecycle.sh`](../scripts/staging_lifecycle.sh) (`line 1280`), and the assertion on it in [`test_staging_lifecycle.py`](../tests/infrastructure/test_staging_lifecycle.py) (`line 636`). - - **Terraform test fixtures:** every `display_name = "test"` in `infra/targets/gcp-gke/tests/`: [`gpu_pool.tftest.hcl`](../infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl) (`lines 43, 80, 122, 142, 167, 195`), [`governance_persistence.tftest.hcl`](../infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl) (`line 90`), [`image_digests.tftest.hcl`](../infra/targets/gcp-gke/tests/image_digests.tftest.hcl) (`line 68`), [`poam_019.tftest.hcl`](../infra/targets/gcp-gke/tests/poam_019.tftest.hcl) (`line 71`), [`retention_posture.tftest.hcl`](../infra/targets/gcp-gke/tests/retention_posture.tftest.hcl) (`line 78`), and [`w6.tftest.hcl`](../infra/targets/gcp-gke/tests/w6.tftest.hcl) (`line 68`). + - **Terraform test fixtures:** every `display_name = "test"` in `infra/targets/gcp-gke/tests/`: [`gpu_pool.tftest.hcl`](../infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl) (`lines 50, 92, 134, 154, 179, 207`), [`governance_persistence.tftest.hcl`](../infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl) (`line 97`), [`image_digests.tftest.hcl`](../infra/targets/gcp-gke/tests/image_digests.tftest.hcl) (`line 74`), [`poam_019.tftest.hcl`](../infra/targets/gcp-gke/tests/poam_019.tftest.hcl) (`line 77`), [`retention_posture.tftest.hcl`](../infra/targets/gcp-gke/tests/retention_posture.tftest.hcl) (`line 85`), and [`w6.tftest.hcl`](../infra/targets/gcp-gke/tests/w6.tftest.hcl) (`line 74`). - **Examples operators copy:** [`QUICK_START.md`](../infra/QUICK_START.md) (`lines 282, 336`), [`DEPLOYMENT_RULES.md`](operations/DEPLOYMENT_RULES.md) (`line 460`), the target [`README.md`](../infra/targets/gcp-gke/README.md) (`line 141`), the module [`README.md`](../infra/modules/gcp_gke_cluster/README.md) (`line 93`), [`staging.tfvars`](../infra/targets/gcp-gke/staging.tfvars) (`line 122`), the commented examples in [`apac-dev.tfvars`](../infra/targets/gcp-gke/apac-dev.tfvars) and [`eu-dev.tfvars`](../infra/targets/gcp-gke/eu-dev.tfvars) (`line 94` in each), and the commented [`display_name` example in `terraform.auto.tfvars.example`](../infra/targets/gcp-gke/terraform.auto.tfvars.example) (`line 86`). - **Outside the repository:** the precondition rejects unmigrated local files at plan and apply without stopping a teardown; record the change in [`BREAKING_CHANGES.md`](BREAKING_CHANGES.md). - **Not affected:** the `0.0.0.0/0` fallback block in [`gcp_gke_cluster/main.tf`](../infra/modules/gcp_gke_cluster/main.tf) (`line 173`) is built inside the module and never passes through the target variable. It belongs to `POAM-2026-174`. @@ -4902,10 +4902,13 @@ This record does not establish whether any policy opened an incident in those pr 1. **Plan-time validity.** Every channel in the bound set exists and is enabled when the plan runs. A non-empty list is not enough, because Terraform accepts a channel ID that no longer resolves: either Terraform owns the channel resources, with endpoints from the gitignored tfvars so IDs cannot dangle, or a lookup fails the plan when a channel is missing or disabled. It is enforced by a `lifecycle` `precondition` on each alert policy resource, the placement `AGENTS.md` requires (on the protected resource, not a variable validation or a standalone `terraform_data` guard), with `expect_failures` runs in the tftest for an empty set, a missing channel and a disabled channel in an enforcing posture. **1b. Start-time validity, for application alert config.** Property 1 is written for Terraform-managed Cloud Monitoring channels and does not cover the compliance-bridge notifier, which is application configuration, not a Terraform channel resource. Its form: in an enforcing posture the bridge refuses to start when `ALERT_CHANNEL` is unset, is `console`, or does not resolve to a configured destination (a missing secret or a non-HTTPS URL). A fallback to the console is a start failure, not a warning. 2. **Bindings, at plan time and at run time.** Every `google_monitoring_alert_policy` in the target, enumerated rather than hard-coded to eight so that a ninth cannot skip it, binds exactly the validated channel set, the heartbeat policy included; tftest asserts this for each planned policy. At run time the recurring check lists the live alert policies and fails if any binds a different set, which catches drift such as a console edit. The binding check asserts set equality between the heartbeat's channels and every real policy's, so the heartbeat proves delivery for the channels the real policies use. For the notifier, every application alert emitter (the call sites in the notifier subsection above) sends through the validated destination, and nothing records an alert as sent from having called the notifier. -3. **Delivery, observed at the destination.** On a schedule, the check trips the heartbeat and fails unless the notification is observed at the destination of every channel in the bound set within a stated bound. Cloud Monitoring's send or dispatch status does not count: a notification sent to a dead webhook or a bouncing address still reports success, and a check that reads it reproduces this finding one layer up. The bound set is limited to channel types whose destinations the check can read, or each channel has its own destination-side observation; an unobserved channel can fail silently, which is this finding at the channel level. The verified boundary is the bound channel's sink: any fan-out from that sink to a person is beyond what the check proves, and closure does not claim end-to-end delivery to a person. The heartbeat also goes through `send_critical_alert()` and is observed at the notifier's destination. -4. **The check's failure surfaces independently.** A failed check (heartbeat not observed, binding mismatch, or the check not running) surfaces through a path that uses none of the channels it tests, for example a scheduled CI workflow failure, so a dead channel cannot silence its own check. The same applies to the notifier's check. -5. **Citation corrections.** Each `2026-11-16` correction in the sweep below is re-verified against properties 1–4 and either rewritten to name the verified boundary or kept; the Terraform strings in remediation item 4 are corrected; and the `v4.1.0` release body carries the correction already made in `CHANGELOG.md`. -6. **Incident read-back.** Remediation item 5's result is recorded here. +3. **Delivery, observed at the destination (amended `2026-11-22` — Reference-Architecture Terminal Sink).** On a schedule, the check trips the heartbeat and fails unless the notification is observed at the destination of every channel in the bound set within a stated bound. Cloud Monitoring's send or dispatch status does not count: a notification sent to a dead webhook or a bouncing address still reports success, and a check that reads it reproduces this finding one layer up. **Reference-architecture boundary (`2026-11-22`):** because CAGE is a reference architecture demonstrating AI governance patterns rather than a deployed production service, GCP Cloud Pub/Sub (`topics/cage-staging-alerts` → `subscriptions/cage-staging-alerts-verify`) is the **terminal destination by design** for both Cloud Monitoring `AlertPolicy` resources and the `compliance-bridge` notifier (`PubSubNotifier`). Personal email, SMS, and commercial paging fan-out beyond Pub/Sub are out of scope by design rather than permanently unmet work; "observed at the destination" is satisfied directly by pulling from the Pub/Sub subscription (`subscriptions/cage-staging-alerts-verify`). Production adopters attach their incident-response fan-out behind that Pub/Sub topic or bind additional verified `NotificationChannel`s. The heartbeat also goes through `send_critical_alert()` (`send_notifier_heartbeat()` / periodic `sla_monitor` heartbeat) and is observed at the same Pub/Sub destination. +4. **The check's failure surfaces independently.** A failed check (heartbeat not observed, binding mismatch, or the check not running) surfaces through a path that uses none of the channels it tests — implemented as scheduled GitHub Actions workflow [`alert-delivery-check.yml`](../.github/workflows/alert-delivery-check.yml) authenticating via keyless OIDC WIF (`google_service_account.alert_verifier` in [`wif.tf`](../infra/targets/gcp-gke/wif.tf)) — so a dead channel cannot silence its own check. The same applies to the notifier's check. +5. **Citation corrections.** Each `2026-11-16` correction in the sweep below is re-verified against properties 1–4 and either rewritten to name the verified boundary or kept; the Terraform strings in remediation item 4 and [`lula-validation-ir6.yaml`](../compliance/lula/lula-validation-ir6.yaml) L21 & L46 are corrected; and the `v4.1.0` release body carries the correction already made in `CHANGELOG.md`. +6. **Incident read-back.** Remediation item 5's result is recorded below. +7. **Adopter-facing alert-stability invariants (folded in `2026-11-22` from queue read-back — Findings A & B).** + - **Finding A (No orphaned pod-scoped incidents):** Pod-level threshold/absence conditions (`lula_audit_pod_restart` and `gateway_canary_pod_health`) aggregate across pod series (`cross_series_reducer = "REDUCE_SUM"` on `restart_count`, `"REDUCE_MAX"` on `uptime`) and all `google_monitoring_alert_policy` resources set `alert_strategy { auto_close = "1800s" }` so ReplicaSet turnover never leaves per-pod incidents open for GCP's 7-day default. + - **Finding B (Single-replica rolling-deploy turnover tolerance):** `prometheus_metrics_scrape_liveness` aggregates `up` across replicas via `max by (job, namespace) (up{...}) == 0`, widens `absent_over_time` lookback from `[5m]` to `[10m]`, and sets `duration = "600s"` (`10m` > 6–7m single-replica GKE rolling deploy turnover) so routine rolling deploys do not page adopters. **Citation sweep (`2026-11-16`):** Searched `docs/**`, `compliance/**`, `CHANGELOG.md`, `README.md`, the Terraform comments and alert `documentation` strings, the Gate W certification record, and the GitHub release bodies published on or after `2026-11-09` (`v4.1.0`, `client-v0.3.0`, `conformance-v0.4.1`, `gate-w-8956f505`; read only) for the eight policy names, both variables, "alert policy", "page", "paging", "notify", "on-call", "alarm" and "dead-man". No document mentions a notification channel. Corrected with a dated note naming this item: @@ -4930,9 +4933,23 @@ This record does not establish whether any policy opened an incident in those pr | [`NIST_RMF_CHUNK3_SELECT_IMPLEMENT.md`](compliance/us_fed/NIST_RMF_CHUNK3_SELECT_IMPLEMENT.md), [`NIST_RMF_CHUNK4_ASSESS_AUTHORIZE.md`](compliance/us_fed/NIST_RMF_CHUNK4_ASSESS_AUTHORIZE.md), [`NIST_RMF_CHUNK5_MONITOR_ROADMAP.md`](compliance/us_fed/NIST_RMF_CHUNK5_MONITOR_ROADMAP.md) | Alerts go to Slack or PagerDuty | They go to the console | | IR-6 census row (`g7000008`) notes | Cites the notifier as the reporting path | The notifier is pinned to the console | -Found and left unchanged: the Gate W record [`gate_w_certification.json`](../compliance/gate_w_certification.json) mentions the "symmetric absent_over_time alert policies" only as the setting of its scrape read-back. Neither it nor the `8956f505` and `v4.1.0` archive notes assert that alerting or delivery was verified, and no phase of the Gate W lifecycle script reads an alert policy, so no certification qualification is needed. The `client-v0.3.0`, `conformance-v0.4.1` and `gate-w-8956f505` release bodies make no alerting claim. Also left unchanged: `lula-validation-ir6.yaml` L21 and L46 (remediation item 6); `LANGFUSE_PROJECT_ISOLATION.md` and `REGION_GUARD_AUDIT.md`, which describe the notifier's channel options and sinks rather than delivery; `AI_600_1_IMPLEMENTATION_PLAN.md`, which plans alerts; `HUMAN_OVERSIGHT_SCOPE.md` L176, a different path (reviewer notification for parked deferrals) outside this item; and the claim register, which is rendered from the census. +Found and left unchanged: the Gate W record [`gate_w_certification.json`](../compliance/gate_w_certification.json) mentions the "symmetric absent_over_time alert policies" only as the setting of its scrape read-back. Neither it nor the `8956f505` and `v4.1.0` archive notes assert that alerting or delivery was verified, and no phase of the Gate W lifecycle script reads an alert policy, so no certification qualification is needed. The `client-v0.3.0`, `conformance-v0.4.1` and `gate-w-8956f505` release bodies make no alerting claim. Also left unchanged on `2026-11-16` (now corrected in `2026-11-22` remediation): `lula-validation-ir6.yaml` L21 and L46 (remediation item 6); left unchanged as option/plan/out-of-scope docs: `LANGFUSE_PROJECT_ISOLATION.md` and `REGION_GUARD_AUDIT.md`, which describe the notifier's channel options and sinks rather than delivery; `AI_600_1_IMPLEMENTATION_PLAN.md`, which plans alerts; `HUMAN_OVERSIGHT_SCOPE.md` L176, a different path (reviewer notification for parked deferrals) outside this item; and the claim register, which is rendered from the census. -**Scope change (`2026-11-16`):** The compliance-bridge notifier, first recorded here as adjacent, is folded into this item (see the notifier subsection and property 1b). IB-24, an internal shard-review finding that is not a repository artifact, covers the notifier's fallback to the console when a configured channel lacks its secret, and the `ERROR` findings that Step 4b and Step 5 skip. Its proposed fix validates secrets only for `pagerduty`, `slack` and `webhook`, so it leaves `console` accepted in an enforcing posture and does not meet property 1b. +**Scope changes (`2026-11-16` & `2026-11-22`):** On `2026-11-16`, the compliance-bridge notifier, first recorded here as adjacent, was folded into this item (see the notifier subsection and property 1b). IB-24, an internal shard-review finding that is not a repository artifact, covered the notifier's fallback to the console when a configured channel lacks its secret, and the `ERROR` findings that Step 4b and Step 5 skip; its proposed fix validated secrets only for `pagerduty`, `slack` and `webhook`, leaving `console` accepted in an enforcing posture and failing property 1b. On `2026-11-22`, Property 3 was amended to codify GCP Cloud Pub/Sub as CAGE's terminal reference-architecture sink by design, and **Findings A and B** (orphaned per-pod series incidents and single-replica rolling-deploy `[5m]` scrape-liveness alert fatigue discovered in the 35-message Pub/Sub read-back below) were folded into this item because adopters copying CAGE's Terraform inherit both defects directly. + +**Incident & Pub/Sub queue read-back (`2026-11-22`, Criterion 6):** +- **Gate W clean-room projects (`fa772122`, `8956f505`):** Both ephemeral certification projects were destroyed at the conclusion of their respective `staging_lifecycle.sh` runs (`2026-11-12` and `2026-11-14`) and no longer exist in GCP, so historical Cloud Monitoring incident state cannot be queried on either project. +- **Live `cage-staging` binding & complete 35-message non-destructive Pub/Sub read-back (``):** `projects//notificationChannels/15662083261173829432` (`displayName: cage-staging-alerts-pubsub`, `type: pubsub`, `enabled: true` → `topics/cage-staging-alerts` → `subscriptions/cage-staging-alerts-verify`) had been staged in gitignored `terraform.auto.tfvars` on `2026-11-18` and bound across `8/8` `AlertPolicy` resources during the `2026-11-19T16:07:46Z` (`2c2cae96`) apply. Pulling all `35` queued messages non-destructively (`modifyAckDeadline=0`, `0` consumed) on `2026-11-22` accounted for every notification since `2026-11-19T16:07:46Z`: + 1. **`3` orphaned `open` messages — `Gateway Synthetic Canary Pod Restart / Eviction` (Finding A):** Retroactively emitted at `2026-11-19T16:07:46Z` when the channel first bound onto three already-open per-pod incidents (`0.of38d4i5w2a3` started `2026-11-16T17:59:09Z` on `gateway-canary-667dc8b7db-x8gvw`, `0.of3en2j2q9g4` started `2026-11-16T22:33:59Z` on `gateway-canary-57bfbd7986-w7l7r`, and `0.of5hdsgn60pd` started `2026-11-18T04:17:50Z` on `gateway-canary-77875bc8cb-k4xts`). None ever emitted a `closed` notification because pod deletion stopped per-pod `restart_count` series without `REDUCE_SUM` or `auto_close`, holding incidents open up to GCP's 7-day default. + 2. **`8` messages (`4` `open`/`closed` pairs) — `Lula Compliance Audit Failure / Dead-Man Switch`:** `0.of5jthe3dt8x` (`2026-11-18T06:04:30Z` → `2026-11-19T16:18:17Z`), `0.of7e718tw26p` (`2026-11-19T18:06:33Z` → `2026-11-22T02:29:28Z`, `56h 23m` dead-man/failure window), `0.of8tijbwfndt` (`2026-11-20T19:09:16Z` → `19:14:33Z`), and `0.ofaymevipwsd` (`2026-11-22T02:36:42Z` → `13:59:36Z`, `11h 23m` `POAM-2026-201`/`244` self-referential failure). Zero incidents fired at the `2026-11-22T18:00Z` scheduled tick (`job.batch/lula-audit-29922840`, `seq=743`). + 3. **`24` messages (`12` `open`/`closed` pairs, `69%` of queue) — `GMP Metrics Scrape & Series Arrival Down / Absent (AU-12)` (Finding B):** Fired and self-closed across `6` rolling deploys (`2c2cae96` on `11-19`, `9c588192` on `11-20`, `d05c7b95`, `da4d82a5`, `905893b5`, and `ddbbdc81` `20:35:20Z` → `20:48:54Z` on `11-22`, the last closing once GMP scraped the newly split `cage_lula_audit_last_healthy_run_timestamp_seconds` series) because `[5m]` `absent_over_time` + `300s` duration was shorter than single-replica GKE rolling turnover (`6–7m`). + 4. **Zero messages from the remaining five policies** (`lula_audit_pod_restart`, `gateway_sustained_refusal_ratio`, `gateway_zero_permitted_requests`, `gateway_canary_probe_absent`, `gateway_evidence_append_reconciliation`), including across `POAM-2026-238`'s `2026-11-19T16:08:53Z`–`16:09:00Z` trade-path wedge 67 seconds after channel binding (corroborating `POAM-2026-231` Finding 4 below). + +**Remediation status (`2026-11-22` — Remediated in code, Open pending merge, staging rollout & `v4.1.0` release-body edit):** +- **Terraform channel validity, stability & verifier IAM (`AL-01`):** [`variables.tf`](../infra/targets/gcp-gke/variables.tf) and [`alert_routing.tf`](../infra/targets/gcp-gke/alert_routing.tf) replace `lula_alert_notification_channels` and `lula_alert_owner` with target-wide `alert_notification_channels` (resolved via `data.google_monitoring_notification_channel.bound`) and `alert_owner_label`, enforce `lifecycle { precondition { condition = local.alert_channels_valid } }` across all `9` `google_monitoring_alert_policy` resources (including `alert_pipeline_heartbeat`), add `REDUCE_SUM`/`REDUCE_MAX` + `auto_close = "1800s"` (Finding A) and `max by (job, namespace) (up == 0)` + `[10m]`/`600s` on `prometheus_metrics_scrape_liveness` (Finding B), correct all `"pages the named owner"` strings in [`lula_alerting.tf`](../infra/targets/gcp-gke/lula_alerting.tf) and [`metrics_alerting.tf`](../infra/targets/gcp-gke/metrics_alerting.tf), allow `pubsub.googleapis.com` egress, grant topic-scoped `roles/pubsub.publisher` to `cage-compliance-bridge`, and provision `google_service_account.alert_verifier` in [`wif.tf`](../infra/targets/gcp-gke/wif.tf); verified by `13/13` runs in [`lula_cron.tftest.hcl`](../infra/targets/gcp-gke/tests/lula_cron.tftest.hcl) (`156/156` target tftest runs) and `14/14` runs in [`operator_identity.tftest.hcl`](../infra/modules/compliance_bridge/tests/operator_identity.tftest.hcl). +- **Notifier startup validity, `PubSubNotifier` & observed delivery:** [`notifier.py`](../src/compliance_bridge/notifier.py), [`main.py`](../src/compliance_bridge/main.py), [`audit_workflow.py`](../src/compliance_bridge/audit_workflow.py), and [`sla_monitor.py`](../src/compliance_bridge/sla_monitor.py) add `PubSubNotifier`, enforce `validate_notifier_config()` in `lifespan()` and `create_notifier()` (`NotifierConfigError`, zero console fallback), record `alerted` / `remediation_sent` strictly from `(await notifier.send_*(...)) is True`, emit periodic SLA heartbeats (`ALERT_HEARTBEAT_INTERVAL_SECONDS`), and correct [`lula-validation-ir6.yaml`](../compliance/lula/lula-validation-ir6.yaml) L21 & L46; verified by [`test_compliance_notifier_routing.py`](../tests/unit/test_compliance_notifier_routing.py). +- **Destination observation & independent CI failure path:** [`verify_alert_delivery.py`](../scripts/verify_alert_delivery.py) and scheduled workflow [`alert-delivery-check.yml`](../.github/workflows/alert-delivery-check.yml) verify runtime channel-set equality across all `>= 9` cluster policies, trip & reset `custom.googleapis.com/cage/alert_heartbeat_probe`, and observe both Cloud Monitoring and `compliance-bridge` heartbeats on `subscriptions/cage-staging-alerts-verify` while returning all operational alerts untouched (`modifyAckDeadline=0`); verified by [`test_verify_alert_delivery.py`](../tests/unit/test_verify_alert_delivery.py). +- **Remaining steps before marking Closed:** (1) squash-merge to `main`, (2) build images + `terraform apply` on `cage-staging` and record a passing live `scripts/verify_alert_delivery.py` execution + configure repository variables `CAGE_ALERT_VERIFIER_*` / `CAGE_ALERT_VERIFY_*`, and (3) maintainer edit of the `v4.1.0` GitHub release body removing the `"bound to @lahlfors"` claim (Criterion 5). ### POAM-2026-231: The `#746` Canary and Gated-Request Metrics Are Biased Toward Healthy, and the Canary Cannot Boot on an Enforcing Deployment @@ -4955,7 +4972,7 @@ Found and left unchanged: the Gate W record [`gate_w_certification.json`](../com **Finding 3: the canary cannot boot on an enforcing deployment.** `#764` (`3347b4b1`, `2026-11-15`) made `resolve_deployment_region()` raise `DeploymentRegionError` when `CAGE_DEPLOYMENT_REGION` is unset under an enforcing posture. The gateway, compliance bridge, advisor and reconciliation worker read it from the `cage-deployment` ConfigMap ([`gateway/main.tf`](../infra/modules/gateway/main.tf) L303–307, [`compliance_bridge/main.tf`](../infra/modules/compliance_bridge/main.tf) L156–160, [`governed_advisor/main.tf`](../infra/modules/governed_advisor/main.tf) L89–93, [`reconciliation_worker/main.tf`](../infra/modules/reconciliation_worker/main.tf) L199–203), whose module says to pass it to every workload ([`deployment_config/outputs.tf`](../infra/modules/deployment_config/outputs.tf) L16). [`gateway_canary.tf`](../infra/targets/gcp-gke/gateway_canary.tf) sets `CAGE_ENV` (L119) but not the region, and no test checks that boot contract across workload manifests: the canary tftest asserts that the Deployment is planned ([`lula_cron.tftest.hcl`](../infra/targets/gcp-gke/tests/lula_cron.tftest.hcl) L175), not that it can start. So the canary crash-loops on every enforcing deployment of `main` since `#764`. Neither Gate W run had a canary: `8956f505` (`2026-11-13`) and `fa772122` (`2026-11-12`) both predate `#746`. -**Finding 4: probe coverage gap — single read-only probe stays green while mutating/CBF governance paths are wedged (realised live `2026-11-19`).** Even after the canary boots and checks `payload.verdict == "ALLOW"`, [`plugin.py`](../src/cage_finance/plugin.py) probes only read-only `market_analysis`. During the live `POAM-2026-238` outage on `cage-staging` (`2026-11-19T16:08:53Z`–`16:09:00Z`, `2c2cae96`), `reconciliation-worker` restarted at `sequence = 4 < last_accepted = 585`, wedging `100%` of `execute_trade` calls into HTTP `403` `CBF_RECONCILED_BALANCE_SEQUENCE_REPLAY_DETECTED` while `gateway-canary` continuously reported `200 OK` every 60s. Because `market_analysis` skips CBF ground-truth reconciliation, sequence validation, fiscal-limit reservation, and mutating-tier STPA/OPA rules, a green canary made a broader system-health claim than it tested. The coverage specification must therefore be defined by **which failure modes must turn the canary red** (not merely by enumerating a fixed list of action classes), so future governed actions and new governance stages have a clear rule for whether the canary probe suite must be extended. +**Finding 4: probe coverage gap — single read-only probe stays green while mutating/CBF governance paths are wedged (realised live `2026-11-19`, independently corroborated by Cloud Monitoring delivery logs `2026-11-22`).** Even after the canary boots and checks `payload.verdict == "ALLOW"`, [`plugin.py`](../src/cage_finance/plugin.py) probes only read-only `market_analysis`. During the live `POAM-2026-238` outage on `cage-staging` (`2026-11-19T16:08:53Z`–`16:09:00Z`, `2c2cae96`), `reconciliation-worker` restarted at `sequence = 4 < last_accepted = 585`, wedging `100%` of `execute_trade` calls into HTTP `403` `CBF_RECONCILED_BALANCE_SEQUENCE_REPLAY_DETECTED` while `gateway-canary` continuously reported `200 OK` every 60s. **Independent delivery-log corroboration (`2026-11-22`, `POAM-2026-230`):** non-destructive read-back of all `35` messages in `subscriptions/cage-staging-alerts-verify` confirmed that `cage-staging-alerts-pubsub` was bound to all eight Cloud Monitoring policies at **`2026-11-19T16:07:46Z`** — **67 seconds before** `seq=2187..2191` wedged `execute_trade` (`16:08:53Z`–`16:09:00Z`) — yet `gateway_sustained_refusal_ratio` emitted **zero** notifications (`2` blocked `execute_trade` attempts stayed below the `5`-request volume floor while `~5` permitted `market_analysis` canary probes per 5 minutes diluted the denominator, raising the `>= 0.95` threshold to `95` blocked requests). That establishes on live telemetry and live alert delivery, not only by counter arithmetic, that a total mutating-tier wedge occurred in front of an active, wired refusal-ratio alarm without tripping it. Because `market_analysis` skips CBF ground-truth reconciliation, sequence validation, fiscal-limit reservation, and mutating-tier STPA/OPA rules, a green canary made a broader system-health claim than it tested. The coverage specification must therefore be defined by **which failure modes must turn the canary red** (not merely by enumerating a fixed list of action classes), so future governed actions and new governance stages have a clear rule for whether the canary probe suite must be extended. **Operator episode (`2026-11-16`, recorded without assigning blame):** The staging canary was scaled to `0` at about 22:39Z on a premise later corrected, and restored to `1` at about 23:20Z. The canary has not completed a probe on `cage-staging` (`POAM-2026-230`, Realised), so neither change altered what any alarm could see: zero-permitted needs canary traffic, and there was none in either state. Scaling to `0` would have disabled that alarm, not unsuppressed it, had the canary been running, and no notification channel existed in either state (`POAM-2026-230`). The scale-down decision and the trade-off analysis that followed were made without checking that the canary pod was running; its `0/1` ready status was in the command output at the 22:39Z scale-down and was missed by both the maintainer and the agent. The analysis of what the control detects ran for four exchanges before anyone established that the control ran, which is the failure this register catalogues. The rule it implies: establish that a control is deployed and running (ready replicas, last successful run, policy enabled and bound) before reasoning about what it detects. diff --git a/infra/modules/app_secrets/main.tf b/infra/modules/app_secrets/main.tf index e91577598..727d6f5d6 100644 --- a/infra/modules/app_secrets/main.tf +++ b/infra/modules/app_secrets/main.tf @@ -162,7 +162,8 @@ resource "kubernetes_secret" "compliance_alerts" { } data = { - "webhook-url" = "" + "webhook-url" = var.compliance_alert_webhook_url + "pagerduty-routing-key" = var.pagerduty_routing_key } } @@ -173,7 +174,7 @@ resource "kubernetes_secret" "compliance_alert_channel" { } data = { - "channel" = "console" + "channel" = var.compliance_alert_channel } } diff --git a/infra/modules/app_secrets/variables.tf b/infra/modules/app_secrets/variables.tf index 15ef732ae..785f2aa72 100644 --- a/infra/modules/app_secrets/variables.tf +++ b/infra/modules/app_secrets/variables.tf @@ -198,3 +198,23 @@ variable "gateway_redis_password" { default = "" sensitive = true } + +variable "compliance_alert_channel" { + description = "Configured compliance-bridge ALERT_CHANNEL stored in Secret/compliance-alert-channel (POAM-2026-230)." + type = string + default = "console" +} + +variable "compliance_alert_webhook_url" { + description = "HTTPS webhook URL for SlackNotifier or WebhookNotifier stored in Secret/compliance-alert-secrets (POAM-2026-230)." + type = string + sensitive = true + default = "" +} + +variable "pagerduty_routing_key" { + description = "PagerDuty Events API v2 routing key stored in Secret/compliance-alert-secrets (POAM-2026-230)." + type = string + sensitive = true + default = "" +} diff --git a/infra/modules/compliance_bridge/main.tf b/infra/modules/compliance_bridge/main.tf index 1077cda62..40af03f7f 100644 --- a/infra/modules/compliance_bridge/main.tf +++ b/infra/modules/compliance_bridge/main.tf @@ -83,6 +83,16 @@ resource "kubernetes_deployment" "compliance_bridge" { condition = !strcontains(var.webauthn_credentials_json, "PRIVATE KEY") error_message = "CAGE Invariant (IA-2 / POAM-2026-210): webauthn_credentials_json must contain only asymmetric public keys (never PRIVATE KEY material)." } + + precondition { + condition = !contains(["staging", "prod", "production"], lower(var.cage_env)) || ( + contains(["pubsub", "webhook", "slack", "pagerduty"], lower(trimspace(var.alert_channel))) && + (lower(trimspace(var.alert_channel)) != "pubsub" || can(regex("^projects/[a-z][a-z0-9-]{4,28}[a-z0-9]/topics/[A-Za-z][A-Za-z0-9-_.~%+]{2,254}$", trimspace(var.alert_pubsub_topic)))) && + (!contains(["webhook", "slack"], lower(trimspace(var.alert_channel))) || var.alert_webhook_configured) && + (lower(trimspace(var.alert_channel)) != "pagerduty" || var.pagerduty_routing_key_configured) + ) + error_message = "CAGE Invariant (IR-6 / AU-5 / CA-7 / POAM-2026-230): under an enforcing posture, compliance-bridge alert_channel must be 'pubsub', 'webhook', 'slack', or 'pagerduty' (never unset or 'console') with its destination configured. Set compliance_alert_channel = \"pubsub\" and alert_pubsub_topic = \"projects//topics/\" (or compliance_alert_webhook_url / pagerduty_routing_key) in gitignored infra/targets/gcp-gke/terraform.auto.tfvars (see terraform.auto.tfvars.example and AL-01 in docs/BREAKING_CHANGES.md)." + } } metadata { @@ -299,6 +309,16 @@ resource "kubernetes_deployment" "compliance_bridge" { value = var.alert_channel } + env { + name = "COMPLIANCE_ALERT_PUBSUB_TOPIC" + value = var.alert_pubsub_topic + } + + env { + name = "ALERT_HEARTBEAT_INTERVAL_SECONDS" + value = tostring(var.alert_heartbeat_interval_seconds) + } + env { name = "COMPLIANCE_ALERT_WEBHOOK_URL" value_from { @@ -310,6 +330,17 @@ resource "kubernetes_deployment" "compliance_bridge" { } } + env { + name = "PAGERDUTY_ROUTING_KEY" + value_from { + secret_key_ref { + name = "compliance-alert-secrets" + key = "pagerduty-routing-key" + optional = true + } + } + } + env { name = "OSCAL_S3_ENDPOINT" value = "https://storage.googleapis.com" diff --git a/infra/modules/compliance_bridge/tests/operator_identity.tftest.hcl b/infra/modules/compliance_bridge/tests/operator_identity.tftest.hcl index 1bc437622..7549f442e 100644 --- a/infra/modules/compliance_bridge/tests/operator_identity.tftest.hcl +++ b/infra/modules/compliance_bridge/tests/operator_identity.tftest.hcl @@ -36,6 +36,8 @@ variables { cage_env = "staging" evidence_cold_store_location = "us-central1" + alert_channel = "pubsub" + alert_pubsub_topic = "projects/hitl-test-project/topics/cage-alerts" trusted_operator_identities = ["risk-officer-1@cage.example", "risk-officer-2@cage.example"] operator_oidc_issuer = "https://idp.cage.example" operator_oidc_audience = "cage-compliance-bridge" @@ -180,3 +182,55 @@ run "enforcing_empty_cold_store_location_is_refused" { ] } +run "enforcing_console_alert_channel_is_refused" { + command = plan + + variables { + alert_channel = "console" + } + + expect_failures = [ + kubernetes_deployment.compliance_bridge, + ] +} + +run "enforcing_pubsub_without_topic_is_refused" { + command = plan + + variables { + alert_channel = "pubsub" + alert_pubsub_topic = "" + } + + expect_failures = [ + kubernetes_deployment.compliance_bridge, + ] +} + +run "enforcing_webhook_without_configured_secret_is_refused" { + command = plan + + variables { + alert_channel = "webhook" + alert_webhook_configured = false + } + + expect_failures = [ + kubernetes_deployment.compliance_bridge, + ] +} + +run "enforcing_pagerduty_without_routing_key_is_refused" { + command = plan + + variables { + alert_channel = "pagerduty" + pagerduty_routing_key_configured = false + } + + expect_failures = [ + kubernetes_deployment.compliance_bridge, + ] +} + + diff --git a/infra/modules/compliance_bridge/variables.tf b/infra/modules/compliance_bridge/variables.tf index 631ed3264..2ba9356aa 100644 --- a/infra/modules/compliance_bridge/variables.tf +++ b/infra/modules/compliance_bridge/variables.tf @@ -111,8 +111,38 @@ variable "vllm_api_key" { } variable "alert_channel" { - type = string - default = "console" + description = "Compliance-bridge ALERT_CHANNEL ('pubsub', 'webhook', 'slack', 'pagerduty'; 'console' allowed only in non-enforcing dev/test/ci postures; POAM-2026-230)." + type = string + default = "console" +} + +variable "alert_pubsub_topic" { + description = "GCP Pub/Sub topic ('projects//topics/') injected as COMPLIANCE_ALERT_PUBSUB_TOPIC when alert_channel = 'pubsub' (POAM-2026-230)." + type = string + default = "" +} + +variable "alert_webhook_configured" { + description = "True when an https:// webhook URL is populated in Secret/compliance-alert-secrets ('webhook-url') for alert_channel = 'webhook' or 'slack' (POAM-2026-230)." + type = bool + default = false +} + +variable "pagerduty_routing_key_configured" { + description = "True when a non-empty PagerDuty Events API v2 routing key is populated in Secret/compliance-alert-secrets ('pagerduty-routing-key') for alert_channel = 'pagerduty' (POAM-2026-230)." + type = bool + default = false +} + +variable "alert_heartbeat_interval_seconds" { + description = "Interval in seconds between synthetic non-paging compliance-bridge notifier heartbeats (ALERT_HEARTBEAT_INTERVAL_SECONDS; 0 disables; POAM-2026-230)." + type = number + default = 21600 + + validation { + condition = var.alert_heartbeat_interval_seconds >= 0 && floor(var.alert_heartbeat_interval_seconds) == var.alert_heartbeat_interval_seconds + error_message = "alert_heartbeat_interval_seconds must be a non-negative integer." + } } variable "oscal_s3_bucket" { diff --git a/infra/targets/gcp-gke/alert_routing.tf b/infra/targets/gcp-gke/alert_routing.tf new file mode 100644 index 000000000..a7134b425 --- /dev/null +++ b/infra/targets/gcp-gke/alert_routing.tf @@ -0,0 +1,171 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ─── Target-Wide Cloud Monitoring Alert Channel Resolution & Heartbeat (POAM-2026-230) ─── +# +# Reference Architecture Boundary: +# CAGE is a reference architecture, not a deployed production service. By design, +# the verified terminal destination for Cloud Monitoring AlertPolicies and the +# compliance-bridge notifier on GKE is a GCP Pub/Sub topic/subscription +# (var.alert_notification_channels / var.alert_pubsub_topic), rather than personal +# email, SMS, or commercial paging fan-out. Adopters deploying CAGE in production +# either attach their incident-response fan-out behind that Pub/Sub topic or bind +# additional verified NotificationChannels. +# +# Plan-Time Validity (Property 1): +# Every entry in var.alert_notification_channels is looked up via +# data.google_monitoring_notification_channel.bound, and every +# google_monitoring_alert_policy resource in this target carries a lifecycle +# precondition requiring local.alert_channels_valid (non-empty set, every channel +# resolved with a valid resource name, and enabled == true). Placing the +# precondition directly on each protected policy ensures targeted plans +# (-target=google_monitoring_alert_policy.) still fail closed (POAM-2026-180) +# while terraform destroy succeeds without channel inputs (POAM-2026-174). + +data "google_monitoring_notification_channel" "bound" { + for_each = local.enforcing_posture ? { + for idx, ch in var.alert_notification_channels : tostring(idx) => ch + } : {} + + project = var.project_id + display_name = trimspace(each.value.display_name) + type = each.value.type != null && trimspace(each.value.type) != "" ? trimspace(each.value.type) : null + labels = length(each.value.labels) > 0 ? each.value.labels : null +} + +locals { + resolved_alert_notification_channels = local.enforcing_posture ? [ + for idx in range(length(var.alert_notification_channels)) : + data.google_monitoring_notification_channel.bound[tostring(idx)].name + ] : [] + + alert_channels_valid = !local.enforcing_posture || ( + length(var.alert_notification_channels) > 0 && + length(data.google_monitoring_notification_channel.bound) == length(var.alert_notification_channels) && + alltrue([ + for idx, spec in var.alert_notification_channels : + data.google_monitoring_notification_channel.bound[tostring(idx)].enabled == true && + can( + regex( + "^projects/[^/]+/notificationChannels/[^/]+$", + data.google_monitoring_notification_channel.bound[tostring(idx)].name, + ) + ) && + ( + spec.name == null || + trimspace(spec.name) == "" || + data.google_monitoring_notification_channel.bound[tostring(idx)].name == trimspace(spec.name) + ) + ]) + ) + + effective_compliance_alert_channel = local.enforcing_posture ? trimspace(var.compliance_alert_channel) : ( + trimspace(var.compliance_alert_channel) != "" ? trimspace(var.compliance_alert_channel) : "console" + ) + + alert_channels_error_message = trimspace(<<-EOT + [POAM-2026-230] Enforcing posture refuses empty, disabled, or mismatched Cloud Monitoring notification channels. To remediate: (1) If upgrading from lula_alert_notification_channels (ignored with 'Warning: Value for undeclared variable' in .tfvars), migrate to alert_notification_channels = [{ display_name = "", type = "pubsub" }] in gitignored infra/targets/gcp-gke/terraform.auto.tfvars (see AL-01 in docs/BREAKING_CHANGES.md). (2) On a new project, create a Pub/Sub topic + Cloud Monitoring channel ('gcloud pubsub topics create cage-alerts --project=${var.project_id}' and 'gcloud beta monitoring channels create --project=${var.project_id} --display-name=cage-alerts-pubsub --type=pubsub --channel-labels=topic=projects/${var.project_id}/topics/cage-alerts') and bind it in terraform.auto.tfvars (see terraform.auto.tfvars.example). (3) If an existing channel is disabled, run 'gcloud beta monitoring channels update --enabled --project=${var.project_id}'. (4) If a bound channel was deleted out-of-band and you are running terraform destroy, pass -var='alert_notification_channels=[]' so data.google_monitoring_notification_channel.bound is skipped during teardown. + EOT + ) +} + +# ─── Synthetic Alert Pipeline Heartbeat Policy (POAM-2026-230 Property 3) ───── +# Tripped exclusively by scripts/verify_alert_delivery.py writing +# custom.googleapis.com/cage/alert_heartbeat_probe = 1 (and reset to 0 once +# observed at the destination Pub/Sub subscription). Never trip real operational +# policies for scheduled delivery tests: synthetic pages on real alarms train +# operators to ignore them. + +resource "google_monitoring_alert_policy" "alert_pipeline_heartbeat" { + count = local.enforcing_posture ? 1 : 0 + + project = var.project_id + display_name = "${var.cluster_name} - Alert Pipeline Synthetic Heartbeat (No Action Required)" + combiner = "OR" + enabled = true + severity = "WARNING" + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } + + user_labels = { + owner = trimspace(var.alert_owner_label) + component = "alert-pipeline-heartbeat" + control = "ca-7" + environment = var.environment + alert_kind = "heartbeat" + } + + documentation { + mime_type = "text/markdown" + content = <<-EOT + ## SYNTHETIC PIPELINE HEARTBEAT — NO OPERATOR ACTION REQUIRED (`POAM-2026-230`) + + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) + + Synthetic end-to-end delivery probe tripped by `scripts/verify_alert_delivery.py` + writing `custom.googleapis.com/cage/alert_heartbeat_probe > 0` and immediately + resetting to `0` once observed on the destination subscription. Requires **no + operator action**. + EOT + } + + conditions { + display_name = "Synthetic alert-pipeline heartbeat probe > 0" + + condition_threshold { + filter = "resource.type = \"global\" AND metric.type = \"custom.googleapis.com/cage/alert_heartbeat_probe\"" + comparison = "COMPARISON_GT" + threshold_value = 0 + duration = "0s" + + aggregations { + alignment_period = "60s" + per_series_aligner = "ALIGN_MAX" + cross_series_reducer = "REDUCE_MAX" + } + } + } + + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + + depends_on = [module.gke] +} + +# ─── Compliance-Bridge Pub/Sub Alert Publisher IAM (POAM-2026-230) ──────────── +# Grants least-privilege topic-scoped publisher authority exclusively to the +# dedicated compliance-bridge GSA when PubSubNotifier is the active notifier. + +resource "google_pubsub_topic_iam_member" "compliance_bridge_alert_publisher" { + count = ( + var.enable_compliance_bridge && + lower(local.effective_compliance_alert_channel) == "pubsub" && + trimspace(var.alert_pubsub_topic) != "" + ) ? 1 : 0 + + project = var.project_id + topic = trimspace(var.alert_pubsub_topic) + role = "roles/pubsub.publisher" + member = "serviceAccount:${google_service_account.compliance_bridge.email}" +} + diff --git a/infra/targets/gcp-gke/lula_alerting.tf b/infra/targets/gcp-gke/lula_alerting.tf index 3e4cbc80f..75c033c8e 100644 --- a/infra/targets/gcp-gke/lula_alerting.tf +++ b/infra/targets/gcp-gke/lula_alerting.tf @@ -14,9 +14,11 @@ # ─── In-Cluster Lula Compliance Audit Alerting (ISO/IEC 42001 A.5.3 / CA-7) ─── # Pairs with compliance-bridge `ingest_infra_event` (`cage_lula_audit_*` GMP -# metrics) and `sla_monitor.py` (`2 x schedule` = 1800s dead-man's switch) so -# every `lula_audit` failure, `< 26` manifest corpus-floor breach, dead-man -# breach, or `lula-audit` container restart pages the named owner. +# metrics) and `sla_monitor.py` (`2 x schedule` dead-man's switch) so every +# `lula_audit` failure, `< 26` manifest corpus-floor breach, dead-man breach, +# or `lula-audit` container restart routes to `var.alert_notification_channels` +# (GCP Pub/Sub terminal sink by design in the CAGE reference architecture; +# `var.alert_owner_label` is triage metadata only and routes nothing). resource "google_monitoring_alert_policy" "lula_audit_failure" { count = var.enable_compliance_bridge && local.enforcing_posture ? 1 : 0 @@ -26,10 +28,14 @@ resource "google_monitoring_alert_policy" "lula_audit_failure" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "compliance-auditor" control = "a-5-3" environment = var.environment @@ -40,7 +46,8 @@ resource "google_monitoring_alert_policy" "lula_audit_failure" { content = <<-EOT ## CAGE In-Cluster Lula Compliance Audit Alert (ISO/IEC 42001 A.5.3 / NIST CA-7) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Schedule:** `${var.lula_schedule}` (`2 x schedule` = `${local.lula_audit_max_age_seconds}s` dead-man window) @@ -53,11 +60,10 @@ resource "google_monitoring_alert_policy" "lula_audit_failure" { report separately on `cage_lula_audit_insufficient_traffic_controls` and `cage_lula_audit_insufficient_sample_controls`, advancing auditor liveness `cage_lula_audit_last_healthy_run_timestamp_seconds` without claiming - statistical satisfaction on `cage_lula_audit_last_pass_timestamp_seconds`), + statistical satisfaction on `cage_lula_audit_last_pass_timestamp_seconds`), or 2. `increase(cage_lula_audit_deadman_breaches_total[5m]) > 0` because no auditor-healthy (`>= 26` evaluated, `failed_count == 0`) - `lula_audit` run completed within `2 x schedule` (`${local.lula_audit_max_age_seconds}s`), or - 3. `kubernetes.io/container/restart_count` increases for `lula-audit` pods. + `lula_audit` run completed within `2 x schedule` (`${local.lula_audit_max_age_seconds}s`). EOT } @@ -72,6 +78,13 @@ resource "google_monitoring_alert_policy" "lula_audit_failure" { } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -83,10 +96,16 @@ resource "google_monitoring_alert_policy" "lula_audit_pod_restart" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + # POAM-2026-230 Finding A: CronJob Job pods terminate after completion, stopping + # per-pod series; REDUCE_SUM + 30m auto_close prevents 7-day orphaned incidents. + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "compliance-auditor" control = "a-5-3" environment = var.environment @@ -97,12 +116,15 @@ resource "google_monitoring_alert_policy" "lula_audit_pod_restart" { content = <<-EOT ## CAGE In-Cluster Lula Auditor Pod Restart Alert (ISO/IEC 42001 A.5.3 / NIST CA-7) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - Fires when `kubernetes.io/container/restart_count` increases for `lula-audit` pods. - Separated from `lula_audit_failure` because Cloud Monitoring restricts - `prometheus_query_language` alert policies to a single condition. + Fires when workload-aggregated `kubernetes.io/container/restart_count` delta + exceeds `0` for `lula-audit` pods (`REDUCE_SUM` across pod turnovers with + `1800s` `auto_close` so completed CronJob pods never leave 7-day orphaned + incidents). Separated from `lula_audit_failure` because Cloud Monitoring + restricts `prometheus_query_language` alert policies to a single condition. EOT } @@ -116,11 +138,19 @@ resource "google_monitoring_alert_policy" "lula_audit_pod_restart" { duration = "0s" aggregations { - alignment_period = "300s" - per_series_aligner = "ALIGN_DELTA" + alignment_period = "300s" + per_series_aligner = "ALIGN_DELTA" + cross_series_reducer = "REDUCE_SUM" } } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } diff --git a/infra/targets/gcp-gke/main.tf b/infra/targets/gcp-gke/main.tf index fdb7e23f6..0fb34ca99 100644 --- a/infra/targets/gcp-gke/main.tf +++ b/infra/targets/gcp-gke/main.tf @@ -1002,21 +1002,25 @@ module "compliance_bridge" { # EA-1: model backends admit TCP 8000 from the gateway alone # (model-backend-ingress), so the bridge has no model to call. "none" records # the remediation advisory as not performed instead of dialling a dropped URL. - cage_inference_backend = "none" - vllm_base_url = "" - vllm_api_key = "" - alert_channel = "console" - oscal_s3_bucket = module.worm_bucket.bucket_name - trusted_mesh_identities = ["${local.ksa_gateway}.${module.namespace.name}.${module.service_mesh.identity_suffix}"] - auditor_mesh_identity = "${local.ksa_lula}.${module.namespace.name}.${module.service_mesh.identity_suffix}" - oscal_s3_region = var.region - evidence_cold_store = "gcs" - evidence_cold_store_bucket = module.worm_bucket.bucket_name - cmek_key_resource_name = var.enable_cmek ? local.evidence_cmek_key_id : "" - cage_env = local.effective_cage_env - startup_grace_hours = var.startup_grace_hours - lula_audit_max_age_seconds = local.lula_audit_max_age_seconds - deployment_config_map_name = module.deployment_config.config_map_name + cage_inference_backend = "none" + vllm_base_url = "" + vllm_api_key = "" + alert_channel = local.effective_compliance_alert_channel + alert_pubsub_topic = var.alert_pubsub_topic + alert_webhook_configured = trimspace(var.compliance_alert_webhook_url) != "" + pagerduty_routing_key_configured = trimspace(var.pagerduty_routing_key) != "" + alert_heartbeat_interval_seconds = var.alert_heartbeat_interval_seconds + oscal_s3_bucket = module.worm_bucket.bucket_name + trusted_mesh_identities = ["${local.ksa_gateway}.${module.namespace.name}.${module.service_mesh.identity_suffix}"] + auditor_mesh_identity = "${local.ksa_lula}.${module.namespace.name}.${module.service_mesh.identity_suffix}" + oscal_s3_region = var.region + evidence_cold_store = "gcs" + evidence_cold_store_bucket = module.worm_bucket.bucket_name + cmek_key_resource_name = var.enable_cmek ? local.evidence_cmek_key_id : "" + cage_env = local.effective_cage_env + startup_grace_hours = var.startup_grace_hours + lula_audit_max_age_seconds = local.lula_audit_max_age_seconds + deployment_config_map_name = module.deployment_config.config_map_name # POAM-2026-220: inject the WORM bucket's immutable GCS location rather than # expanding runtime IAM with storage.buckets.get (roles/storage.legacyBucketReader). @@ -1060,7 +1064,15 @@ module "compliance_bridge" { infra_evidence_previous_chain_head_hash = var.infra_evidence_previous_chain_head_hash infra_evidence_previous_batch_attestation_digest = var.infra_evidence_previous_batch_attestation_digest - depends_on = [module.langfuse, module.vllm, module.worm_bucket, module.memorystore_governance, module.service_mesh, terraform_data.memorystore_ca_pinning_guard] + depends_on = [ + module.langfuse, + module.vllm, + module.worm_bucket, + module.memorystore_governance, + module.service_mesh, + terraform_data.memorystore_ca_pinning_guard, + google_pubsub_topic_iam_member.compliance_bridge_alert_publisher, + ] } @@ -1391,6 +1403,9 @@ module "app_secrets" { langfuse_compliance_public_key = var.langfuse_compliance_public_key langfuse_compliance_secret_key = var.langfuse_compliance_secret_key + compliance_alert_channel = local.effective_compliance_alert_channel + compliance_alert_webhook_url = var.compliance_alert_webhook_url + pagerduty_routing_key = var.pagerduty_routing_key cage_deployment_region = var.cage_deployment_region diff --git a/infra/targets/gcp-gke/metrics_alerting.tf b/infra/targets/gcp-gke/metrics_alerting.tf index 8a4c855c1..d485ccb89 100644 --- a/infra/targets/gcp-gke/metrics_alerting.tf +++ b/infra/targets/gcp-gke/metrics_alerting.tf @@ -18,33 +18,36 @@ # HTTPRoute Exact GET /metrics and AuthorizationPolicy scoped to # NetworkAuthentication/workload-probe-network and compliance-bridge-probe-network. # Checking up alone is insufficient because HTTP 200 from an empty or uninitialised -# registry yields up == 1 while zero cage_* series arrive. Both targets therefore -# combine scrape-target health (up == 0 or absent_over_time(up[5m])) with named -# startup-registered series absence: -# - gateway: cage_event_loop_lag_seconds_count (250 ms Histogram) -# - compliance-bridge: cage_lula_audit_not_satisfied_controls & -# cage_evidence_verified_batches (unlabeled Gauges) +# registry yields up == 1 while zero cage_* series arrive. +# +# POAM-2026-230 Finding B (Rollout-Noise Elimination): +# 1. Aggregate `up` across replicas via `max by (job, namespace) (up{...}) == 0` +# so a terminating or starting pod with `up == 0` never fires per-pod alerts +# while another replica serves `up == 1`. +# 2. Use a `10m` `absent_over_time(...[10m])` lookback paired with a `600s` (`10m`) +# sustain duration (exceeding the observed 6–7 minute single-replica rollout +# turnover + GMP target-discovery lag) and `alert_strategy.auto_close = "1800s"`. locals { gateway_metrics_scrape_failure_promql = join(" or ", [ - "(up{job=\"gateway-metrics\",namespace=\"${module.namespace.name}\"} == 0)", - "absent_over_time(up{job=\"gateway-metrics\",namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_event_loop_lag_seconds_count{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_gateway_gated_requests_total{namespace=\"${module.namespace.name}\",outcome=\"blocked\"}[5m])", - "absent_over_time(cage_gateway_gated_requests_total{namespace=\"${module.namespace.name}\",outcome=\"permitted\"}[5m])", - "absent_over_time(cage_gateway_canary_requests_total{namespace=\"${module.namespace.name}\",outcome=\"blocked\"}[5m])", - "absent_over_time(cage_gateway_canary_requests_total{namespace=\"${module.namespace.name}\",outcome=\"permitted\"}[5m])", - "absent_over_time(cage_gateway_evidence_records_appended_total{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_gateway_evidenced_requests_permitted_total{namespace=\"${module.namespace.name}\"}[5m])", + "(max by (job, namespace) (up{job=\"gateway-metrics\",namespace=\"${module.namespace.name}\"}) == 0)", + "absent_over_time(up{job=\"gateway-metrics\",namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_event_loop_lag_seconds_count{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_gateway_gated_requests_total{namespace=\"${module.namespace.name}\",outcome=\"blocked\"}[10m])", + "absent_over_time(cage_gateway_gated_requests_total{namespace=\"${module.namespace.name}\",outcome=\"permitted\"}[10m])", + "absent_over_time(cage_gateway_canary_requests_total{namespace=\"${module.namespace.name}\",outcome=\"blocked\"}[10m])", + "absent_over_time(cage_gateway_canary_requests_total{namespace=\"${module.namespace.name}\",outcome=\"permitted\"}[10m])", + "absent_over_time(cage_gateway_evidence_records_appended_total{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_gateway_evidenced_requests_permitted_total{namespace=\"${module.namespace.name}\"}[10m])", ]) compliance_bridge_metrics_scrape_failure_promql = join(" or ", [ - "(up{job=\"compliance-bridge-metrics\",namespace=\"${module.namespace.name}\"} == 0)", - "absent_over_time(up{job=\"compliance-bridge-metrics\",namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_lula_audit_not_satisfied_controls{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_lula_audit_insufficient_traffic_controls{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_lula_audit_insufficient_sample_controls{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_lula_audit_last_healthy_run_timestamp_seconds{namespace=\"${module.namespace.name}\"}[5m])", - "absent_over_time(cage_evidence_verified_batches{namespace=\"${module.namespace.name}\"}[5m])", + "(max by (job, namespace) (up{job=\"compliance-bridge-metrics\",namespace=\"${module.namespace.name}\"}) == 0)", + "absent_over_time(up{job=\"compliance-bridge-metrics\",namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_lula_audit_not_satisfied_controls{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_lula_audit_insufficient_traffic_controls{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_lula_audit_insufficient_sample_controls{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_lula_audit_last_healthy_run_timestamp_seconds{namespace=\"${module.namespace.name}\"}[10m])", + "absent_over_time(cage_evidence_verified_batches{namespace=\"${module.namespace.name}\"}[10m])", ]) prometheus_metrics_scrape_liveness_promql = var.enable_compliance_bridge ? "${local.gateway_metrics_scrape_failure_promql} or ${local.compliance_bridge_metrics_scrape_failure_promql}" : local.gateway_metrics_scrape_failure_promql @@ -57,7 +60,7 @@ locals { ">= ${local.gateway_refusal_ratio_threshold}", ]) # Conditioned on canary probe arrival (> 0) so a crashed, evicted, or Linkerd- - # dropped canary prober pages gateway_canary_probe_absent / gateway_canary_pod_health + # dropped canary prober triggers gateway_canary_probe_absent / gateway_canary_pod_health # (component = "gateway-canary") rather than misattributing an outage to gateway. gateway_zero_permitted_requests_promql = join(" ", [ "(sum(rate(cage_gateway_gated_requests_total{job=\"gateway-metrics\",namespace=\"${module.namespace.name}\",outcome=\"permitted\"}[5m])) == 0)", @@ -96,10 +99,14 @@ resource "google_monitoring_alert_policy" "prometheus_metrics_scrape_liveness" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "metrics-pipeline" control = "au-12" environment = var.environment @@ -110,33 +117,39 @@ resource "google_monitoring_alert_policy" "prometheus_metrics_scrape_liveness" { content = <<-EOT ## CAGE GMP Metrics Scrape & Named-Series Arrival Alert (NIST SP 800-53 AU-12 / AU-5) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Targets:** `PodMonitoring/gateway-metrics` (`:9090/metrics`)${var.enable_compliance_bridge ? " and `PodMonitoring/compliance-bridge-metrics` (`:9090/metrics`)" : ""} - Fires when GKE Managed Prometheus records `up == 0` (HTTP `403` from - Linkerd `Server` / `AuthorizationPolicy`, `probeCidrs` source-IP mismatch, - `NetworkPolicy` drop, or connection failure), `absent_over_time(up[5m])` - (missing `PodMonitoring` target or collector outage), or `absent_over_time` - on startup-registered `cage_*` series (`cage_event_loop_lag_seconds_count`, - `cage_gateway_gated_requests_total`, and `cage_gateway_canary_requests_total` - on `gateway`; `cage_lula_audit_not_satisfied_controls` and - `cage_evidence_verified_batches` on `compliance-bridge`, catching HTTP `200` - from an empty registry) for `120s`. + Fires when GKE Managed Prometheus records workload-wide `max by (job, namespace) (up) == 0` + (HTTP `403` from Linkerd `Server` / `AuthorizationPolicy`, `probeCidrs` source-IP + mismatch, `NetworkPolicy` drop, or connection failure across all replicas), + `absent_over_time(up[10m])` (missing `PodMonitoring` target or collector outage), + or `absent_over_time(...[10m])` on startup-registered `cage_*` series continuously + for `600s` (`10m`, exceeding single-replica rolling deploy turnover so normal + rollouts do not emit alert fatigue). EOT } conditions { - display_name = "GMP PodMonitoring scrape target down (up == 0) or named cage_* series absent for 5m" + display_name = "GMP PodMonitoring scrape target down (max up == 0) or named cage_* series absent for 10m" condition_prometheus_query_language { query = local.prometheus_metrics_scrape_liveness_promql - duration = "120s" + duration = "600s" evaluation_interval = "60s" disable_metric_validation = true } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -157,15 +170,15 @@ resource "google_monitoring_alert_policy" "prometheus_metrics_scrape_liveness" { # rejected before reaching downstream routes and a compromised in-mesh caller # cannot send 404s to inflate outcome="permitted". If gateway ingress is ever # widened to expose public or unauthenticated routes outside OPEN_EXACT_PATHS, -# random 400/404 scanner noise will count toward outcome="blocked" and page — -# narrow the blocked HTTP status predicate (or split client_error out of -# blocked/permitted) before opening ingress. +# random 400/404 scanner noise will count toward outcome="blocked" and trigger +# this alert — narrow the blocked HTTP status predicate (or split client_error +# out of blocked/permitted) before opening ingress. # # Outage & Canary Attribution Partition (separated because Cloud Monitoring # restricts prometheus_query_language alert policies to one condition per policy): # 1. gateway_sustained_refusal_ratio (component="gateway", 180s, >= 5 req / 5m): -# pages quickly during the initial retry burst of a total-denial event or -# an active adversarial flood, without false-paging on single-shot probes. +# fires during the initial retry burst of a total-denial event or an active +# adversarial flood, without firing on single-shot probes. # 2. gateway_zero_permitted_requests (component="gateway", 900s, gated on # var.enable_gateway_canary): fires when rate(permitted) == 0 AND # rate(cage_gateway_canary_requests_total) > 0 — proving the canary prober @@ -175,10 +188,10 @@ resource "google_monitoring_alert_policy" "prometheus_metrics_scrape_liveness" { # var.enable_gateway_canary): fires when rate(cage_gateway_canary_requests_total) == 0 # — proving synthetic probes stopped reaching WorkloadIdentityMiddleware # (dead/wedged prober, NetworkPolicy drop, or broken HTTPRoute/gateway-canary). -# 4. gateway_canary_pod_health (component="gateway-canary", native k8s_container -# restart_count > 0 OR uptime absent for 300s): immediately separates -# "Deployment/gateway-canary crashed or was evicted" from "canary pod is -# running, but mesh/network delivery to gateway:8080 broke". +# 4. gateway_canary_pod_health (component="gateway-canary", workload-aggregated +# k8s_container restart_count > 0 OR uptime absent for 300s): immediately +# separates "Deployment/gateway-canary crashed or was evicted" from "canary +# pod is running, but mesh/network delivery to gateway:8080 broke". resource "google_monitoring_alert_policy" "gateway_sustained_refusal_ratio" { count = local.enforcing_posture ? 1 : 0 @@ -188,10 +201,14 @@ resource "google_monitoring_alert_policy" "gateway_sustained_refusal_ratio" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "gateway" control = "si-4" environment = var.environment @@ -202,7 +219,8 @@ resource "google_monitoring_alert_policy" "gateway_sustained_refusal_ratio" { content = <<-EOT ## CAGE Gateway Sustained Refusal-Ratio Alert (NIST SP 800-53 SI-4 / AU-5) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Metric:** `cage_gateway_gated_requests_total{outcome="blocked"|"permitted"}` on `PodMonitoring/gateway-metrics` (`:9090/metrics`) @@ -210,7 +228,7 @@ resource "google_monitoring_alert_policy" "gateway_sustained_refusal_ratio" { gateway requests arrive within `5m` and the `blocked` share stays `>= ${local.gateway_refusal_ratio_threshold}` for `180s` (`OPEN_EXACT_PATHS` such as `/health`, `/healthz`, and JWKS are excluded so kubelet probes - never dilute the denominator).${var.enable_gateway_canary ? " Paired with `gateway_zero_permitted_requests` (`rate(permitted) == 0 and rate(canary) > 0` over `900s`) and `gateway_canary_probe_absent` (`rate(canary) == 0` over `300s`) so paging persists if callers back off while distinguishing gateway refusal from prober failure." : ""} + never dilute the denominator).${var.enable_gateway_canary ? " Paired with `gateway_zero_permitted_requests` (`rate(permitted) == 0 and rate(canary) > 0` over `900s`) and `gateway_canary_probe_absent` (`rate(canary) == 0` over `300s`) so detection persists if callers back off while distinguishing gateway refusal from prober failure." : ""} ### Triage Checklist 1. **Fail-closed dependency outage (gateway alive, `/healthz` = `200`, routes `403`/`503`):** @@ -234,6 +252,13 @@ resource "google_monitoring_alert_policy" "gateway_sustained_refusal_ratio" { } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -245,10 +270,14 @@ resource "google_monitoring_alert_policy" "gateway_zero_permitted_requests" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "gateway" control = "si-4" environment = var.environment @@ -259,7 +288,8 @@ resource "google_monitoring_alert_policy" "gateway_zero_permitted_requests" { content = <<-EOT ## CAGE Gateway Zero Permitted Gated Requests Alert (NIST SP 800-53 SI-4 / AU-5) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Metrics:** `cage_gateway_gated_requests_total{outcome="permitted"}` and `cage_gateway_canary_requests_total` on `PodMonitoring/gateway-metrics` (`:9090/metrics`) - **Synthetic Liveness Canary:** `Deployment/gateway-canary` (`cage-gateway-canary-sa`, 1 governed request / `${var.gateway_canary_interval_seconds}s`) @@ -271,7 +301,7 @@ resource "google_monitoring_alert_policy" "gateway_zero_permitted_requests" { classified as `blocked`, this alert unambiguously attributes the outage to the **gateway refusing traffic** (quarantine/evidence Redis, OPA sidecar, or KMS failure) rather than a dead or disconnected canary prober (which - pages `gateway_canary_probe_absent` / `gateway_canary_pod_health` under + triggers `gateway_canary_probe_absent` / `gateway_canary_pod_health` under `component = "gateway-canary"` instead). EOT } @@ -287,6 +317,13 @@ resource "google_monitoring_alert_policy" "gateway_zero_permitted_requests" { } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -298,10 +335,14 @@ resource "google_monitoring_alert_policy" "gateway_canary_probe_absent" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "gateway-canary" control = "si-4" environment = var.environment @@ -312,7 +353,8 @@ resource "google_monitoring_alert_policy" "gateway_canary_probe_absent" { content = <<-EOT ## CAGE Gateway Synthetic Canary Probe Absence Alert (NIST SP 800-53 SI-4 / CA-7) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Metric:** `cage_gateway_canary_requests_total` on `PodMonitoring/gateway-metrics` (`:9090/metrics`) - **Prober:** `Deployment/gateway-canary` (`cage-gateway-canary-sa`, expected every `${var.gateway_canary_interval_seconds}s`) @@ -342,6 +384,13 @@ resource "google_monitoring_alert_policy" "gateway_canary_probe_absent" { } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -353,10 +402,16 @@ resource "google_monitoring_alert_policy" "gateway_canary_pod_health" { combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + # POAM-2026-230 Finding A: ReplicaSet replacements delete old pod series; + # REDUCE_SUM/REDUCE_MAX + 30m auto_close prevents 7-day orphaned incidents. + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "gateway-canary" control = "si-4" environment = var.environment @@ -367,14 +422,15 @@ resource "google_monitoring_alert_policy" "gateway_canary_pod_health" { content = <<-EOT ## CAGE Gateway Synthetic Canary Pod Restart / Eviction Alert (NIST SP 800-53 SI-4 / CA-7) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Workload:** `Deployment/gateway-canary` (`cage-gateway-canary-sa`) Fires when `Deployment/gateway-canary` experiences a container restart - (`kubernetes.io/container/restart_count` delta `> 0`) or has no running - container reporting `kubernetes.io/container/uptime` for `300s` (pod - eviction, node-pool scheduling failure, or replica scaled to `0`). + (workload-aggregated `kubernetes.io/container/restart_count` delta `> 0`) or + has no running container reporting `kubernetes.io/container/uptime` for `300s` + (pod eviction, node-pool scheduling failure, or replica scaled to `0`). EOT } @@ -388,8 +444,9 @@ resource "google_monitoring_alert_policy" "gateway_canary_pod_health" { duration = "0s" aggregations { - alignment_period = "300s" - per_series_aligner = "ALIGN_DELTA" + alignment_period = "300s" + per_series_aligner = "ALIGN_DELTA" + cross_series_reducer = "REDUCE_SUM" } } } @@ -402,12 +459,20 @@ resource "google_monitoring_alert_policy" "gateway_canary_pod_health" { duration = "300s" aggregations { - alignment_period = "60s" - per_series_aligner = "ALIGN_MEAN" + alignment_period = "60s" + per_series_aligner = "ALIGN_MEAN" + cross_series_reducer = "REDUCE_MAX" } } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } @@ -419,10 +484,14 @@ resource "google_monitoring_alert_policy" "gateway_evidence_append_reconciliatio combiner = "OR" enabled = true severity = "CRITICAL" - notification_channels = var.lula_alert_notification_channels + notification_channels = local.resolved_alert_notification_channels + + alert_strategy { + auto_close = "1800s" + } user_labels = { - owner = trimspace(var.lula_alert_owner) + owner = trimspace(var.alert_owner_label) component = "gateway" control = "au-5" environment = var.environment @@ -433,7 +502,8 @@ resource "google_monitoring_alert_policy" "gateway_evidence_append_reconciliatio content = <<-EOT ## CAGE Gateway Evidence Append Reconciliation Alert (NIST SP 800-53 AU-5 / AU-12 / POAM-2026-217) - - **Owner:** `${trimspace(var.lula_alert_owner)}` + - **Owner Label (metadata only; routes nothing):** `${trimspace(var.alert_owner_label)}` + - **Delivery Route:** Bound `var.alert_notification_channels` (GCP Pub/Sub terminal sink in reference architecture) - **Cluster:** `${var.cluster_name}` (`${var.namespace}`) - **Ingress Metrics:** `cage_gateway_gated_requests_total{outcome="permitted"}` and `cage_gateway_evidenced_requests_permitted_total` (`WorkloadIdentityMiddleware`) - **Custody Metric:** `cage_gateway_evidence_records_appended_total` (`EvidenceStreamSink._acknowledge` after Redis `XADD`) @@ -442,8 +512,8 @@ resource "google_monitoring_alert_policy" "gateway_evidence_append_reconciliatio the Redis evidence stream over a `15m` window (`POAM-2026-217`), evaluated across a sustained `600s` (`10m`) duration (exceeding group-commit batching, `15s` `PodMonitoring` scrape skew, and `EvidenceCustodian`'s `300s` cadence - so asynchronous flush lag at window boundaries does not false-page). Fires - when for `600s` either: + so asynchronous flush lag at window boundaries does not trigger false alerts). + Fires when for `600s` either: 1. Permitted request rate is `>= 3 / 15m` while `rate(cage_gateway_evidence_records_appended_total[15m]) == 0` (total append stall), **or** 2. `(rate(appended[15m]) + rate(trace_shed[15m])) / rate(evidenced_requests_permitted[15m]) < ${local.gateway_evidence_reconciliation_ratio_floor}` @@ -453,7 +523,7 @@ resource "google_monitoring_alert_policy" "gateway_evidence_append_reconciliatio **Operator note (`EC-1`):** Under `EVIDENCE_CHAIN_BLOCKING=true` (enforcing default), a `memorystore_governance` Redis custody outage fails all governed - traffic closed (`503` — full gateway outage, paging `gateway_sustained_refusal_ratio` + traffic closed (`503` — full gateway outage, triggering `gateway_sustained_refusal_ratio` and `gateway_zero_permitted_requests`). This reconciliation policy catches the complementary failure mode (`EVIDENCE_CHAIN_BLOCKING=false` break-glass or a code-path regression) where traffic is permitted without durable Redis appends. @@ -471,7 +541,12 @@ resource "google_monitoring_alert_policy" "gateway_evidence_append_reconciliatio } } + lifecycle { + precondition { + condition = local.alert_channels_valid + error_message = local.alert_channels_error_message + } + } + depends_on = [module.gke] } - - diff --git a/infra/targets/gcp-gke/terraform.auto.tfvars.example b/infra/targets/gcp-gke/terraform.auto.tfvars.example index 01972198f..7bc920ddd 100644 --- a/infra/targets/gcp-gke/terraform.auto.tfvars.example +++ b/infra/targets/gcp-gke/terraform.auto.tfvars.example @@ -170,6 +170,22 @@ enable_compliance_bridge = false # Compliance bridge container image (must be pinned by @sha256: digest when Binary Authorization is enabled) # compliance_bridge_image = "gcr.io/your-project/compliance-bridge@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +# ═══════════════════════════════════════════════════════════════════════════════ +# Alert Routing & Compliance-Bridge Notifier (Required in Enforcing Postures) +# ═══════════════════════════════════════════════════════════════════════════════ +# Enforcing postures (staging, prod, or enforce_in_dev = true) fail closed at +# plan time unless alert_notification_channels resolves at least one existing, +# enabled Cloud Monitoring NotificationChannel AND compliance_alert_channel is +# set to an external backend (pubsub, slack, webhook, or pagerduty). +# In CAGE's reference architecture, GCP Pub/Sub is the verified terminal sink: +# +# alert_owner_label = "platform-compliance-oncall" # metadata label only; routes nothing +# alert_notification_channels = [{ display_name = "cage-staging-alerts-pubsub", type = "pubsub" }] +# compliance_alert_channel = "pubsub" +# alert_pubsub_topic = "projects/your-gcp-project-id/topics/cage-staging-alerts" +# alert_verify_pubsub_subscription = "cage-staging-alerts-verify" + + # ═══════════════════════════════════════════════════════════════════════════════ # OPA Policy Engine # ═══════════════════════════════════════════════════════════════════════════════ diff --git a/infra/targets/gcp-gke/tests/clickhouse_rbac.tftest.hcl b/infra/targets/gcp-gke/tests/clickhouse_rbac.tftest.hcl index 07604d6a8..fd8b8be2c 100644 --- a/infra/targets/gcp-gke/tests/clickhouse_rbac.tftest.hcl +++ b/infra/targets/gcp-gke/tests/clickhouse_rbac.tftest.hcl @@ -17,7 +17,14 @@ # together using the scoped `langfuse_app` principal and `langfuse` database, # never sharing ClickHouse `default` superuser credentials. -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/domain_opa_policies.tftest.hcl b/infra/targets/gcp-gke/tests/domain_opa_policies.tftest.hcl index 2261f7a14..2f4ae06c4 100644 --- a/infra/targets/gcp-gke/tests/domain_opa_policies.tftest.hcl +++ b/infra/targets/gcp-gke/tests/domain_opa_policies.tftest.hcl @@ -19,7 +19,14 @@ # verifies that stub domains without .rego policies (physical_ai) fail closed at # terraform plan via domain_opa_policies_guard and opa_policies preconditions. -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/evidence_domain.tftest.hcl b/infra/targets/gcp-gke/tests/evidence_domain.tftest.hcl index 07087ef56..4c6e4f910 100644 --- a/infra/targets/gcp-gke/tests/evidence_domain.tftest.hcl +++ b/infra/targets/gcp-gke/tests/evidence_domain.tftest.hcl @@ -25,7 +25,14 @@ # 4. prod refuses single-project custody unless external_evidence_domain_enabled = true # or evidence_project_id != project_id, while staging allows single-project mode. -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/fixtures/image_digests.tfvars b/infra/targets/gcp-gke/tests/fixtures/image_digests.tfvars index 9e7146d84..b9d1ca466 100644 --- a/infra/targets/gcp-gke/tests/fixtures/image_digests.tfvars +++ b/infra/targets/gcp-gke/tests/fixtures/image_digests.tfvars @@ -39,3 +39,19 @@ image_digests = { "governed-financial-advisor" = "registry.invalid/cage-test/governed-financial-advisor@sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" "inference-stub" = "registry.invalid/cage-test/inference-stub@sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" } + +# POAM-2026-230: Committed .tfvars profiles intentionally leave +# alert_notification_channels = [] and compliance_alert_channel = "" so real +# enforcing plans fail closed until an adopter binds verified destinations. +# Mock-provider terraform test suites plan with this fake test-only Pub/Sub sink; +# negative expect_failures runs in lula_cron.tftest.hcl override these to prove +# empty, disabled, mismatched, and console configurations are refused. +alert_notification_channels = [ + { + display_name = "cage-test-alerts-pubsub" + type = "pubsub" + } +] +compliance_alert_channel = "pubsub" +alert_pubsub_topic = "projects/cage-test-project/topics/cage-test-alerts" + diff --git a/infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl b/infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl index 4c4fc0bf7..c8094e11e 100644 --- a/infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl +++ b/infra/targets/gcp-gke/tests/governance_persistence.tftest.hcl @@ -33,6 +33,12 @@ # The key values below are test fixtures, not credentials. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl b/infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl index c2e8508b7..93c9ca08c 100644 --- a/infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl +++ b/infra/targets/gcp-gke/tests/gpu_pool.tftest.hcl @@ -15,7 +15,14 @@ # POAM-2026-132 / Probe #12: plan-time contracts for GPU pool total autoscaling, # zero initial node count, and verified regional L4 + g2-standard-8 zones. -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/hitl_operator_and_secrets.tftest.hcl b/infra/targets/gcp-gke/tests/hitl_operator_and_secrets.tftest.hcl index 3a7f23829..f6c5f3871 100644 --- a/infra/targets/gcp-gke/tests/hitl_operator_and_secrets.tftest.hcl +++ b/infra/targets/gcp-gke/tests/hitl_operator_and_secrets.tftest.hcl @@ -19,6 +19,12 @@ # per the POAM-2026-180 guard placement matrix in infra/targets/gcp-gke/main.tf. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/image_digests.tftest.hcl b/infra/targets/gcp-gke/tests/image_digests.tftest.hcl index 26a47ddd1..5581f45e0 100644 --- a/infra/targets/gcp-gke/tests/image_digests.tftest.hcl +++ b/infra/targets/gcp-gke/tests/image_digests.tftest.hcl @@ -20,6 +20,12 @@ # -var-file=tests/fixtures/image_digests.tfvars mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/lula_cron.tftest.hcl b/infra/targets/gcp-gke/tests/lula_cron.tftest.hcl index eae1adb47..bc9e25b03 100644 --- a/infra/targets/gcp-gke/tests/lula_cron.tftest.hcl +++ b/infra/targets/gcp-gke/tests/lula_cron.tftest.hcl @@ -18,6 +18,12 @@ # NetworkPolicy isolation (CA-2, CA-7, SC-7). mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { @@ -253,12 +259,26 @@ run "lula_image_latest_tag_is_refused" { expect_failures = [var.lula_image] } -run "custom_lula_alert_owner_and_channels_propagate" { +run "custom_alert_owner_label_and_channels_propagate" { command = plan variables { - lula_alert_owner = "secops-compliance-oncall" - lula_alert_notification_channels = ["projects/lula-cron-test-project/notificationChannels/12345"] + alert_owner_label = "secops-compliance-oncall" + alert_notification_channels = [ + { + display_name = "cage-staging-alerts-pubsub" + type = "pubsub" + name = "projects/lula-cron-test-project/notificationChannels/12345" + } + ] + } + + override_data { + target = data.google_monitoring_notification_channel.bound["0"] + values = { + enabled = true + name = "projects/lula-cron-test-project/notificationChannels/12345" + } } assert { @@ -266,36 +286,190 @@ run "custom_lula_alert_owner_and_channels_propagate" { google_monitoring_alert_policy.lula_audit_failure[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.lula_audit_failure[0].documentation[0].content, "secops-compliance-oncall") && contains(google_monitoring_alert_policy.lula_audit_failure[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.lula_audit_failure[0].alert_strategy[0].auto_close == "1800s" && google_monitoring_alert_policy.lula_audit_pod_restart[0].user_labels["owner"] == "secops-compliance-oncall" && contains(google_monitoring_alert_policy.lula_audit_pod_restart[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.lula_audit_pod_restart[0].alert_strategy[0].auto_close == "1800s" && + google_monitoring_alert_policy.lula_audit_pod_restart[0].conditions[0].condition_threshold[0].aggregations[0].cross_series_reducer == "REDUCE_SUM" && google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].user_labels["owner"] == "secops-compliance-oncall" && contains(google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].alert_strategy[0].auto_close == "1800s" && + google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].conditions[0].condition_prometheus_query_language[0].duration == "600s" && + strcontains(google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].conditions[0].condition_prometheus_query_language[0].query, "max by (job, namespace)") && + strcontains(google_monitoring_alert_policy.prometheus_metrics_scrape_liveness[0].conditions[0].condition_prometheus_query_language[0].query, "[10m]") && google_monitoring_alert_policy.gateway_sustained_refusal_ratio[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.gateway_sustained_refusal_ratio[0].documentation[0].content, "secops-compliance-oncall") && contains(google_monitoring_alert_policy.gateway_sustained_refusal_ratio[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.gateway_sustained_refusal_ratio[0].alert_strategy[0].auto_close == "1800s" && google_monitoring_alert_policy.gateway_zero_permitted_requests[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.gateway_zero_permitted_requests[0].documentation[0].content, "secops-compliance-oncall") && contains(google_monitoring_alert_policy.gateway_zero_permitted_requests[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.gateway_zero_permitted_requests[0].alert_strategy[0].auto_close == "1800s" && google_monitoring_alert_policy.gateway_canary_probe_absent[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.gateway_canary_probe_absent[0].documentation[0].content, "secops-compliance-oncall") && contains(google_monitoring_alert_policy.gateway_canary_probe_absent[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.gateway_canary_probe_absent[0].alert_strategy[0].auto_close == "1800s" && google_monitoring_alert_policy.gateway_canary_pod_health[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.gateway_canary_pod_health[0].documentation[0].content, "secops-compliance-oncall") && contains(google_monitoring_alert_policy.gateway_canary_pod_health[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.gateway_canary_pod_health[0].alert_strategy[0].auto_close == "1800s" && + google_monitoring_alert_policy.gateway_canary_pod_health[0].conditions[0].condition_threshold[0].aggregations[0].cross_series_reducer == "REDUCE_SUM" && + google_monitoring_alert_policy.gateway_canary_pod_health[0].conditions[1].condition_absent[0].aggregations[0].cross_series_reducer == "REDUCE_MAX" && google_monitoring_alert_policy.gateway_evidence_append_reconciliation[0].user_labels["owner"] == "secops-compliance-oncall" && strcontains(google_monitoring_alert_policy.gateway_evidence_append_reconciliation[0].documentation[0].content, "secops-compliance-oncall") && - contains(google_monitoring_alert_policy.gateway_evidence_append_reconciliation[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") + contains(google_monitoring_alert_policy.gateway_evidence_append_reconciliation[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.gateway_evidence_append_reconciliation[0].alert_strategy[0].auto_close == "1800s" && + google_monitoring_alert_policy.alert_pipeline_heartbeat[0].user_labels["owner"] == "secops-compliance-oncall" && + google_monitoring_alert_policy.alert_pipeline_heartbeat[0].user_labels["alert_kind"] == "heartbeat" && + contains(google_monitoring_alert_policy.alert_pipeline_heartbeat[0].notification_channels, "projects/lula-cron-test-project/notificationChannels/12345") && + google_monitoring_alert_policy.alert_pipeline_heartbeat[0].alert_strategy[0].auto_close == "1800s" ) - error_message = "custom lula_alert_owner and lula_alert_notification_channels must propagate into Lula, GMP scrape-liveness, gateway refusal-ratio, gateway zero-permitted, gateway canary liveness, and gateway evidence reconciliation alert policies" + error_message = "alert_owner_label, resolved alert_notification_channels, Finding A pod-series reducers/auto_close, and Finding B 10m scrape-liveness window must propagate across all 9 Cloud Monitoring alert policies" + } +} + +run "empty_alert_owner_label_is_refused" { + command = plan + + variables { + alert_owner_label = " " + } + + expect_failures = [var.alert_owner_label] +} + +run "empty_alert_notification_channels_refused_in_enforcing_posture" { + command = plan + + variables { + alert_notification_channels = [] + } + + expect_failures = [ + google_monitoring_alert_policy.alert_pipeline_heartbeat, + google_monitoring_alert_policy.lula_audit_failure, + google_monitoring_alert_policy.lula_audit_pod_restart, + google_monitoring_alert_policy.prometheus_metrics_scrape_liveness, + google_monitoring_alert_policy.gateway_sustained_refusal_ratio, + google_monitoring_alert_policy.gateway_zero_permitted_requests, + google_monitoring_alert_policy.gateway_canary_probe_absent, + google_monitoring_alert_policy.gateway_canary_pod_health, + google_monitoring_alert_policy.gateway_evidence_append_reconciliation, + ] +} + +run "disabled_notification_channel_refused_in_enforcing_posture" { + command = plan + + override_data { + target = data.google_monitoring_notification_channel.bound["0"] + values = { + enabled = false + name = "projects/cage-test-project/notificationChannels/12345" + } } + + expect_failures = [ + google_monitoring_alert_policy.alert_pipeline_heartbeat, + google_monitoring_alert_policy.lula_audit_failure, + google_monitoring_alert_policy.lula_audit_pod_restart, + google_monitoring_alert_policy.prometheus_metrics_scrape_liveness, + google_monitoring_alert_policy.gateway_sustained_refusal_ratio, + google_monitoring_alert_policy.gateway_zero_permitted_requests, + google_monitoring_alert_policy.gateway_canary_probe_absent, + google_monitoring_alert_policy.gateway_canary_pod_health, + google_monitoring_alert_policy.gateway_evidence_append_reconciliation, + ] } -run "empty_lula_alert_owner_is_refused" { +run "mismatched_notification_channel_name_refused_in_enforcing_posture" { command = plan variables { - lula_alert_owner = " " + alert_notification_channels = [ + { + display_name = "cage-test-alerts-pubsub" + type = "pubsub" + name = "projects/cage-test-project/notificationChannels/99999" + } + ] } - expect_failures = [var.lula_alert_owner] + expect_failures = [ + google_monitoring_alert_policy.alert_pipeline_heartbeat, + google_monitoring_alert_policy.lula_audit_failure, + google_monitoring_alert_policy.lula_audit_pod_restart, + google_monitoring_alert_policy.prometheus_metrics_scrape_liveness, + google_monitoring_alert_policy.gateway_sustained_refusal_ratio, + google_monitoring_alert_policy.gateway_zero_permitted_requests, + google_monitoring_alert_policy.gateway_canary_probe_absent, + google_monitoring_alert_policy.gateway_canary_pod_health, + google_monitoring_alert_policy.gateway_evidence_append_reconciliation, + ] } + +run "invalid_compliance_alert_channel_is_refused" { + command = plan + + variables { + compliance_alert_channel = "telegram" + } + + expect_failures = [var.compliance_alert_channel] +} + +run "console_compliance_alert_channel_refused_in_enforcing_posture" { + command = plan + + module { + source = "../../modules/compliance_bridge" + } + + variables { + namespace = "governance-stack" + image = "registry.invalid/cage-test/compliance-bridge@sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + service_account_name = "cage-compliance-bridge-sa" + vllm_base_url = "http://vllm-inference:8000/v1" + vllm_api_key = "not-needed" + oscal_s3_bucket = "cage-oscal-staging" + oscal_s3_region = "us-central1" + evidence_stream_redis_url = "rediss://10.10.0.5:6379" + evidence_stream_redis_db = 0 + evidence_stream_key = "cage:evidence:stream" + enable_redis_tls = true + redis_ca_pem = "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----\n" + deployment_config_map_name = "cage-deployment" + cage_env = "staging" + evidence_cold_store_location = "us-central1" + alert_channel = "console" + trusted_operator_identities = ["alice@example.org"] + operator_oidc_issuer = "https://idp.example.org" + operator_oidc_audience = "cage-compliance-bridge" + operator_jwks_uri = "https://idp.example.org/.well-known/jwks.json" + } + + expect_failures = [ + kubernetes_deployment.compliance_bridge, + ] +} + +run "dev_non_enforcing_posture_allows_empty_alert_channels_and_console_notifier" { + command = plan + + variables { + environment = "dev" + enforce_in_dev = false + alert_notification_channels = [] + compliance_alert_channel = "" + } + + assert { + condition = ( + length(google_monitoring_alert_policy.alert_pipeline_heartbeat) == 0 && + length(google_monitoring_alert_policy.lula_audit_failure) == 0 && + local.effective_compliance_alert_channel == "console" + ) + error_message = "non-enforcing dev posture must omit Cloud Monitoring alert policies and default effective_compliance_alert_channel to console" + } +} + diff --git a/infra/targets/gcp-gke/tests/memorystore_clients.tftest.hcl b/infra/targets/gcp-gke/tests/memorystore_clients.tftest.hcl index fde602d88..1a833d366 100644 --- a/infra/targets/gcp-gke/tests/memorystore_clients.tftest.hcl +++ b/infra/targets/gcp-gke/tests/memorystore_clients.tftest.hcl @@ -39,6 +39,12 @@ # The key values below are test fixtures, not credentials. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/namespace_segmentation.tftest.hcl b/infra/targets/gcp-gke/tests/namespace_segmentation.tftest.hcl index 7b57f5ed9..25b940e8a 100644 --- a/infra/targets/gcp-gke/tests/namespace_segmentation.tftest.hcl +++ b/infra/targets/gcp-gke/tests/namespace_segmentation.tftest.hcl @@ -18,6 +18,12 @@ # policy-verdict logging. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/opa_uds_sidecar.tftest.hcl b/infra/targets/gcp-gke/tests/opa_uds_sidecar.tftest.hcl index 26701d4e2..75ec8720c 100644 --- a/infra/targets/gcp-gke/tests/opa_uds_sidecar.tftest.hcl +++ b/infra/targets/gcp-gke/tests/opa_uds_sidecar.tftest.hcl @@ -23,6 +23,12 @@ # - governed_advisor carries no OPA_URL or OPA_AUTH_TOKEN env vars. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/poam_019.tftest.hcl b/infra/targets/gcp-gke/tests/poam_019.tftest.hcl index e85c56640..a3d388fa4 100644 --- a/infra/targets/gcp-gke/tests/poam_019.tftest.hcl +++ b/infra/targets/gcp-gke/tests/poam_019.tftest.hcl @@ -23,6 +23,12 @@ # The key values below are test fixtures, not credentials. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/posture_guards.tftest.hcl b/infra/targets/gcp-gke/tests/posture_guards.tftest.hcl index ba26eb8c0..9eba9a664 100644 --- a/infra/targets/gcp-gke/tests/posture_guards.tftest.hcl +++ b/infra/targets/gcp-gke/tests/posture_guards.tftest.hcl @@ -30,7 +30,14 @@ # key values and CIDRs below are test fixtures, not credentials or operator # addresses (203.0.113.0/24 is TEST-NET-3). -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/retention_posture.tftest.hcl b/infra/targets/gcp-gke/tests/retention_posture.tftest.hcl index 88281f72b..df1092526 100644 --- a/infra/targets/gcp-gke/tests/retention_posture.tftest.hcl +++ b/infra/targets/gcp-gke/tests/retention_posture.tftest.hcl @@ -30,6 +30,12 @@ # The key values below are test fixtures, not credentials. mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/staging_compliance.tftest.hcl b/infra/targets/gcp-gke/tests/staging_compliance.tftest.hcl index 23deafcf7..6057f53c0 100644 --- a/infra/targets/gcp-gke/tests/staging_compliance.tftest.hcl +++ b/infra/targets/gcp-gke/tests/staging_compliance.tftest.hcl @@ -28,7 +28,14 @@ # The key values and CIDRs below are test fixtures, not credentials or # operator addresses (203.0.113.0/24 is TEST-NET-3). -mock_provider "google" {} +mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } +} mock_provider "helm" {} mock_provider "kubernetes" {} mock_provider "random" {} diff --git a/infra/targets/gcp-gke/tests/vpc_binding.tftest.hcl b/infra/targets/gcp-gke/tests/vpc_binding.tftest.hcl index 02c23aa93..73acf45c5 100644 --- a/infra/targets/gcp-gke/tests/vpc_binding.tftest.hcl +++ b/infra/targets/gcp-gke/tests/vpc_binding.tftest.hcl @@ -25,6 +25,12 @@ # -var-file=tests/fixtures/image_digests.tfvars mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/tests/w6.tftest.hcl b/infra/targets/gcp-gke/tests/w6.tftest.hcl index 054f35b3d..1ee90cf19 100644 --- a/infra/targets/gcp-gke/tests/w6.tftest.hcl +++ b/infra/targets/gcp-gke/tests/w6.tftest.hcl @@ -20,6 +20,12 @@ # -var-file=tests/fixtures/image_digests.tfvars mock_provider "google" { + mock_data "google_monitoring_notification_channel" { + defaults = { + enabled = true + name = "projects/cage-test-project/notificationChannels/12345" + } + } mock_resource "google_container_cluster" { override_during = plan defaults = { diff --git a/infra/targets/gcp-gke/variables.tf b/infra/targets/gcp-gke/variables.tf index 39edfd240..49d19add7 100644 --- a/infra/targets/gcp-gke/variables.tf +++ b/infra/targets/gcp-gke/variables.tf @@ -785,26 +785,100 @@ variable "lula_schedule" { default = "0 */6 * * *" } -variable "lula_alert_notification_channels" { - description = "Cloud Monitoring notification channel resource names attached to the Lula compliance audit AlertPolicy (CA-7 / IR-4)." - type = list(string) - default = [] +variable "alert_notification_channels" { + description = "Cloud Monitoring NotificationChannel lookup descriptors bound to every AlertPolicy in this target (CA-7 / IR-4 / POAM-2026-230). Resolved at plan time via data.google_monitoring_notification_channel.bound; enforcing postures fail closed when empty, unresolved, or disabled. In CAGE's reference architecture, the verified terminal sink is a GCP Pub/Sub topic/subscription rather than personal email/SMS/commercial paging." + type = list(object({ + display_name = string + type = optional(string) + labels = optional(map(string), {}) + name = optional(string) + })) + default = [] + + validation { + condition = alltrue([ + for ch in var.alert_notification_channels : + trimspace(ch.display_name) != "" && + (ch.name == null || trimspace(ch.name) == "" || can(regex("^projects/[^/]+/notificationChannels/[^/]+$", trimspace(ch.name)))) + ]) + error_message = "Every entry in alert_notification_channels must carry a non-empty display_name and, if name is set, match projects//notificationChannels/." + } } -variable "lula_alert_owner" { - description = "Named on-call team or owner label responsible for triaging Lula compliance audit alerts (CA-7 / IR-4)." +variable "alert_owner_label" { + description = "Metadata-only GCP user label ('owner') and documentation tag attached to every Cloud Monitoring AlertPolicy in this target. Routes nothing — actual notification delivery requires var.alert_notification_channels (POAM-2026-230)." type = string default = "platform-compliance-oncall" validation { condition = ( - trimspace(var.lula_alert_owner) != "" && - can(regex("^[a-z0-9][a-z0-9_-]{0,62}$", trimspace(var.lula_alert_owner))) + trimspace(var.alert_owner_label) != "" && + can(regex("^[a-z0-9][a-z0-9_-]{0,62}$", trimspace(var.alert_owner_label))) ) - error_message = "lula_alert_owner must be a non-empty lowercase GCP label identifier (1-63 chars matching ^[a-z0-9][a-z0-9_-]{0,62}$)." + error_message = "alert_owner_label must be a non-empty lowercase GCP label identifier (1-63 chars matching ^[a-z0-9][a-z0-9_-]{0,62}$)." } } +variable "compliance_alert_channel" { + description = "External alert delivery backend for compliance-bridge (pubsub, slack, webhook, pagerduty). Empty defaults to 'console' only in non-enforcing dev postures; enforcing postures refuse empty, console, or mock at both plan time and pod startup (POAM-2026-230)." + type = string + default = "" + + validation { + condition = contains( + ["", "console", "pubsub", "slack", "webhook", "pagerduty"], + lower(trimspace(var.compliance_alert_channel)), + ) + error_message = "compliance_alert_channel must be empty or one of: console, pubsub, slack, webhook, pagerduty." + } +} + +variable "alert_pubsub_topic" { + description = "Fully-qualified Cloud Pub/Sub topic (projects//topics/) published to by compliance-bridge when compliance_alert_channel = 'pubsub' (reference-architecture terminal sink, POAM-2026-230)." + type = string + default = "" + + validation { + condition = ( + trimspace(var.alert_pubsub_topic) == "" || + can(regex("^projects/[a-z][a-z0-9-]{4,29}/topics/[A-Za-z][A-Za-z0-9-_.~+%]{2,254}$", trimspace(var.alert_pubsub_topic))) + ) + error_message = "alert_pubsub_topic must be empty or match projects//topics/." + } +} + +variable "compliance_alert_webhook_url" { + description = "HTTPS destination webhook URL injected into Secret/compliance-alert-secrets when compliance_alert_channel is 'slack' or 'webhook' (POAM-2026-230)." + type = string + sensitive = true + default = "" +} + +variable "pagerduty_routing_key" { + description = "PagerDuty Events v2 integration routing key injected into Secret/compliance-alert-secrets when compliance_alert_channel is 'pagerduty' (POAM-2026-230)." + type = string + sensitive = true + default = "" +} + +variable "alert_heartbeat_interval_seconds" { + description = "Interval in seconds between non-paging synthetic notifier heartbeats emitted by compliance-bridge SLA monitor (0 disables; POAM-2026-230 Property 3)." + type = number + default = 21600 + + validation { + condition = var.alert_heartbeat_interval_seconds >= 0 && floor(var.alert_heartbeat_interval_seconds) == var.alert_heartbeat_interval_seconds + error_message = "alert_heartbeat_interval_seconds must be a non-negative integer." + } +} + +variable "alert_verify_pubsub_subscription" { + description = "Optional Cloud Pub/Sub subscription resource ID or short name granted subscriber/viewer IAM to google_service_account.alert_verifier for scheduled independent alert-delivery verification (POAM-2026-230 Property 4)." + type = string + default = "" +} + + variable "trusted_operator_identities" { description = "Allowlisted human OIDC operator sub claims permitted to approve HITL deferrals on compliance-bridge (CAGE_TRUSTED_OPERATOR_IDENTITIES; POAM-2026-196)." type = list(string) @@ -1317,11 +1391,12 @@ variable "vllm_egress_allowed_fqdns" { } variable "compliance_bridge_egress_allowed_fqdns" { - description = "FQDNs allowed for compliance-bridge HTTPS (443) egress via GKE FQDNNetworkPolicy: WORM bucket writes (GCS), per-batch evidence attestation signing (Cloud KMS) and Workload Identity token exchange (§5.3)" + description = "FQDNs allowed for compliance-bridge HTTPS (443) egress via GKE FQDNNetworkPolicy: WORM bucket writes (GCS), per-batch evidence attestation signing (Cloud KMS), Pub/Sub alert notification publishing, and Workload Identity token exchange (§5.3, POAM-2026-230)" type = list(string) default = [ "storage.googleapis.com", "cloudkms.googleapis.com", + "pubsub.googleapis.com", "oauth2.googleapis.com", ] } diff --git a/infra/targets/gcp-gke/wif.tf b/infra/targets/gcp-gke/wif.tf index 4fe91d699..a04488c2c 100644 --- a/infra/targets/gcp-gke/wif.tf +++ b/infra/targets/gcp-gke/wif.tf @@ -164,3 +164,65 @@ resource "google_kms_crypto_key_iam_policy" "partner_harness_kms_signer" { crypto_key_id = "projects/${var.project_id}/locations/${var.region}/keyRings/${var.partner_harness_kms_keyring}/cryptoKeys/${var.partner_harness_kms_key}" policy_data = data.google_iam_policy.partner_harness_kms_signer[0].policy_data } + +# ─── 3. Scheduled Alert-Delivery Verifier Identity (POAM-2026-230 Property 4) ─ +# Dedicated low-privilege GSA for .github/workflows/alert-delivery-check.yml: +# - Restricted via WIF to var.github_deployer_ref (refs/heads/main), where +# scheduled workflows execute. +# - Holds zero cluster, KMS, Secret Manager, or GCS access. +# - Permitted only to read Cloud Monitoring AlertPolicy/NotificationChannel +# metadata, write the synthetic custom.googleapis.com/cage/alert_heartbeat_probe +# gauge, and pull/nack/ack synthetic heartbeats on var.alert_verify_pubsub_subscription. + +resource "google_service_account" "alert_verifier" { + account_id = "cage-alert-verifier" + display_name = "CAGE Alert Delivery Verifier" + description = "Least-privilege WIF identity for scheduled independent alert-delivery verification (POAM-2026-230)" + project = var.project_id +} + +resource "google_service_account_iam_binding" "alert_verifier_workload_identity" { + service_account_id = google_service_account.alert_verifier.name + role = "roles/iam.workloadIdentityUser" + members = [ + "principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.github_actions.name}/attribute.ref/${var.github_deployer_ref}", + ] +} + +resource "google_service_account_iam_binding" "alert_verifier_token_creator" { + service_account_id = google_service_account.alert_verifier.name + role = "roles/iam.serviceAccountTokenCreator" + members = [ + "principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.github_actions.name}/attribute.ref/${var.github_deployer_ref}", + "serviceAccount:${google_service_account.alert_verifier.email}", + ] +} + +resource "google_project_iam_member" "alert_verifier_monitoring_viewer" { + project = var.project_id + role = "roles/monitoring.viewer" + member = "serviceAccount:${google_service_account.alert_verifier.email}" +} + +resource "google_project_iam_member" "alert_verifier_metric_writer" { + project = var.project_id + role = "roles/monitoring.metricWriter" + member = "serviceAccount:${google_service_account.alert_verifier.email}" +} + +resource "google_pubsub_subscription_iam_member" "alert_verifier_subscriber" { + count = trimspace(var.alert_verify_pubsub_subscription) != "" ? 1 : 0 + project = var.project_id + subscription = trimspace(var.alert_verify_pubsub_subscription) + role = "roles/pubsub.subscriber" + member = "serviceAccount:${google_service_account.alert_verifier.email}" +} + +resource "google_pubsub_subscription_iam_member" "alert_verifier_viewer" { + count = trimspace(var.alert_verify_pubsub_subscription) != "" ? 1 : 0 + project = var.project_id + subscription = trimspace(var.alert_verify_pubsub_subscription) + role = "roles/pubsub.viewer" + member = "serviceAccount:${google_service_account.alert_verifier.email}" +} + diff --git a/scripts/verify_alert_delivery.py b/scripts/verify_alert_delivery.py new file mode 100644 index 000000000..338360230 --- /dev/null +++ b/scripts/verify_alert_delivery.py @@ -0,0 +1,772 @@ +#!/usr/bin/env python3 +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""End-to-end Cloud Monitoring & compliance-bridge alert delivery verifier (POAM-2026-230). + +Pure Python stdlib script (zero third-party imports) safe to execute in minimal +OIDC-authenticated GitHub Actions jobs without installing PyPI dependencies +(POAM-2026-115 / POAM-2026-221). + +Verifies all runtime properties of POAM-2026-230 against CAGE's reference-architecture +terminal sink (GCP Cloud Pub/Sub): + 1. Runtime Policy & Channel Validity (Property 1 / 2): + - Lists all Cloud Monitoring AlertPolicy resources for ``--cluster-name``. + - Asserts at least ``--min-policies`` (default: 9) exist, every policy has + ``enabled == True`` and non-empty ``notificationChannels``, every policy + shares the exact same channel set, and every referenced NotificationChannel + exists with ``enabled == True``. + 2. Cloud Monitoring Heartbeat Delivery at Destination (Property 3a): + - Writes ``custom.googleapis.com/cage/alert_heartbeat_probe = 1`` to trip + ``google_monitoring_alert_policy.alert_pipeline_heartbeat`` (a dedicated + ``WARNING`` policy labeled ``alert_kind=heartbeat``, never a real operational + alarm). + - Polls ``--subscription`` until the resulting incident notification arrives, + returning all real operational alert messages untouched via + ``modifyAckDeadline(ackDeadlineSeconds=0)`` so real alerts are never consumed. + - Resets ``custom.googleapis.com/cage/alert_heartbeat_probe = 0`` in a + ``finally`` block so the synthetic incident closes cleanly. + 3. Compliance-Bridge Notifier Delivery at Destination (Property 3b): + - Asserts that a fresh ``source="compliance_bridge"``, ``alert_type="heartbeat"`` + envelope emitted by the in-cluster ``compliance-bridge`` SLA monitor arrived + in ``--subscription`` within ``--max-bridge-heartbeat-age-seconds`` (keeping + the newest heartbeat unacknowledged for idempotency while garbage-collecting + superseded older heartbeats), and optionally emits an on-demand tagged + ``--emit-bridge-heartbeat-topic`` probe and observes its arrival. +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import os +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from datetime import datetime, timezone +from typing import Any + +HEARTBEAT_METRIC_TYPE = "custom.googleapis.com/cage/alert_heartbeat_probe" +MONITORING_API_BASE = "https://monitoring.googleapis.com/v3" +PUBSUB_API_BASE = "https://pubsub.googleapis.com/v1" +METADATA_TOKEN_URL = ( + "http://metadata.google.internal/computeMetadata/v1/" + "instance/service-accounts/default/token" +) + + +class AlertVerificationError(RuntimeError): + """Raised when any runtime binding or destination-delivery check fails.""" + + +def _validate_https_url(url: str) -> str: + parsed = urllib.parse.urlparse(url) + if parsed.scheme != "https" or not parsed.netloc: + raise AlertVerificationError( + f"Refusing non-HTTPS API URL (scheme={parsed.scheme!r}): {url!r}" + ) + return url + + +def _http_json( + method: str, + url: str, + token: str, + payload: dict[str, Any] | None = None, + timeout: float = 30.0, +) -> dict[str, Any]: + validated_url = _validate_https_url(url) + body_bytes = json.dumps(payload).encode("utf-8") if payload is not None else None + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/json", + } + if body_bytes is not None: + headers["Content-Type"] = "application/json; charset=utf-8" + + req = urllib.request.Request( + validated_url, + data=body_bytes, + headers=headers, + method=method, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 # HTTPS scheme and non-empty netloc validated by _validate_https_url + raw = resp.read().decode("utf-8", errors="replace").strip() + return json.loads(raw) if raw else {} + except urllib.error.HTTPError as exc: + err_body = exc.read().decode("utf-8", errors="replace")[:400] + raise AlertVerificationError( + f"HTTP {exc.code} calling {method} {validated_url}: {err_body}" + ) from exc + except urllib.error.URLError as exc: + raise AlertVerificationError( + f"Network error calling {method} {validated_url}: {exc}" + ) from exc + + +def resolve_gcp_access_token() -> str: + """Resolve an OAuth2 Bearer token from CI env, GCE metadata, or gcloud.""" + env_token = os.environ.get("GOOGLE_OAUTH_ACCESS_TOKEN", "").strip() + if env_token: + return env_token + + parsed_meta = urllib.parse.urlparse(METADATA_TOKEN_URL) + if ( + parsed_meta.scheme == "http" + and parsed_meta.netloc == "metadata.google.internal" + ): + req = urllib.request.Request( + METADATA_TOKEN_URL, + headers={"Metadata-Flavor": "Google"}, + method="GET", + ) + try: + with urllib.request.urlopen(req, timeout=2.0) as resp: # nosec B310 # Pinned metadata.google.internal HTTP scheme/host verified immediately above + data = json.loads(resp.read().decode("utf-8")) + tok = str(data.get("access_token", "")).strip() + if tok: + return tok + except Exception: + pass + + try: + proc = subprocess.run( + ["gcloud", "auth", "print-access-token"], + check=True, + capture_output=True, + text=True, + timeout=10.0, + ) + tok = proc.stdout.strip() + if tok: + return tok + except Exception as exc: + raise AlertVerificationError( + "Unable to acquire GCP OAuth2 access token from GOOGLE_OAUTH_ACCESS_TOKEN, " + f"metadata.google.internal, or `gcloud auth print-access-token`: {exc}" + ) from exc + + raise AlertVerificationError("Empty GCP OAuth2 access token.") + + +def _normalize_subscription(project: str, subscription: str) -> str: + sub = subscription.strip() + if sub.startswith("projects/"): + return sub + return f"projects/{project}/subscriptions/{sub}" + + +def _normalize_topic(project: str, topic: str) -> str: + top = topic.strip() + if top.startswith("projects/"): + return top + return f"projects/{project}/topics/{top}" + + +def verify_runtime_alert_policies( + *, + project: str, + cluster_name: str, + token: str, + min_policies: int = 9, + expected_channels: list[str] | None = None, +) -> dict[str, Any]: + """Verify all cluster AlertPolicies are enabled, bound, and share active channels.""" + policies: list[dict[str, Any]] = [] + page_token = "" + while True: + query = {"pageSize": "200"} + if page_token: + query["pageToken"] = page_token + url = ( + f"{MONITORING_API_BASE}/projects/{urllib.parse.quote(project, safe='')}" + f"/alertPolicies?{urllib.parse.urlencode(query)}" + ) + resp = _http_json("GET", url, token) + policies.extend(resp.get("alertPolicies", [])) + page_token = str(resp.get("nextPageToken", "")).strip() + if not page_token: + break + + prefix = f"{cluster_name} - " + cluster_policies = [ + p for p in policies if str(p.get("displayName", "")).startswith(prefix) + ] + if len(cluster_policies) < min_policies: + raise AlertVerificationError( + f"Expected at least {min_policies} AlertPolicies prefixed {prefix!r} in " + f"project {project!r}, found {len(cluster_policies)}: " + f"{[p.get('displayName') for p in cluster_policies]}" + ) + + channel_sets: dict[str, frozenset[str]] = {} + heartbeat_policy: dict[str, Any] | None = None + + for policy in cluster_policies: + display_name = str(policy.get("displayName", "")) + enabled_val = policy.get("enabled", False) + if isinstance(enabled_val, dict): + enabled_val = bool(enabled_val.get("value", False)) + if enabled_val is not True: + raise AlertVerificationError( + f"AlertPolicy {display_name!r} is disabled in project {project!r}." + ) + channels = frozenset( + str(ch).strip() + for ch in policy.get("notificationChannels", []) + if str(ch).strip() + ) + if not channels: + raise AlertVerificationError( + f"AlertPolicy {display_name!r} has zero notificationChannels bound!" + ) + channel_sets[display_name] = channels + labels = policy.get("userLabels") or {} + if labels.get("alert_kind") == "heartbeat": + heartbeat_policy = policy + + if heartbeat_policy is None: + raise AlertVerificationError( + f"Missing synthetic heartbeat policy (userLabels.alert_kind='heartbeat') " + f"among {len(cluster_policies)} policies for {cluster_name!r}." + ) + + distinct_sets = set(channel_sets.values()) + if len(distinct_sets) != 1: + raise AlertVerificationError( + f"Channel-set drift across AlertPolicies for {cluster_name!r}: " + f"{ {k: sorted(v) for k, v in channel_sets.items()} }" + ) + + common_channels = next(iter(distinct_sets)) + if expected_channels: + expected_set = frozenset(c.strip() for c in expected_channels if c.strip()) + if common_channels != expected_set: + raise AlertVerificationError( + f"Runtime AlertPolicy channels {sorted(common_channels)} do not match " + f"expected channels {sorted(expected_set)}." + ) + + verified_channels: list[dict[str, Any]] = [] + for channel_name in sorted(common_channels): + if not channel_name.startswith("projects/"): + raise AlertVerificationError( + f"Malformed NotificationChannel resource name: {channel_name!r}" + ) + ch_url = f"{MONITORING_API_BASE}/{channel_name}" + ch_obj = _http_json("GET", ch_url, token) + ch_enabled = ch_obj.get("enabled", True) + if isinstance(ch_enabled, dict): + ch_enabled = bool(ch_enabled.get("value", False)) + if ch_enabled is not True: + raise AlertVerificationError( + f"Bound NotificationChannel {channel_name!r} " + f"({ch_obj.get('displayName')!r}) has enabled={ch_enabled!r}!" + ) + verified_channels.append( + { + "name": ch_obj.get("name", channel_name), + "display_name": ch_obj.get("displayName", ""), + "type": ch_obj.get("type", ""), + "enabled": True, + } + ) + + return { + "policy_count": len(cluster_policies), + "heartbeat_policy_name": heartbeat_policy.get("name", ""), + "heartbeat_policy_display_name": heartbeat_policy.get("displayName", ""), + "channels": verified_channels, + } + + +def write_heartbeat_metric( + *, + project: str, + token: str, + value: int, +) -> None: + """Write an INT64 gauge point to custom.googleapis.com/cage/alert_heartbeat_probe.""" + now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + url = ( + f"{MONITORING_API_BASE}/projects/{urllib.parse.quote(project, safe='')}" + "/timeSeries" + ) + payload = { + "timeSeries": [ + { + "metric": { + "type": HEARTBEAT_METRIC_TYPE, + "labels": {"probe_source": "verify_alert_delivery"}, + }, + "resource": { + "type": "global", + "labels": {"project_id": project}, + }, + "points": [ + { + "interval": {"endTime": now_iso}, + "value": {"int64Value": str(int(value))}, + } + ], + } + ] + } + _http_json("POST", url, token, payload=payload) + + +def publish_synthetic_bridge_probe( + *, + topic_path: str, + token: str, + probe_id: str, +) -> str: + """Publish a synthetic compliance_bridge heartbeat message to Pub/Sub.""" + envelope = { + "source": "compliance-bridge", + "alert_type": "heartbeat", + "severity": "info", + "audit_id": f"heartbeat-ondemand-{probe_id}", + "probe_id": probe_id, + "timestamp": datetime.now(timezone.utc).isoformat(), + "findings_count": 1, + "findings": [ + { + "control_id": "CA-7-HEARTBEAT", + "finding_id": f"heartbeat-ondemand-{probe_id}", + "result": "PASS", + "assessment_status": "heartbeat", + "evidence_age_s": 0.0, + } + ], + } + encoded = base64.b64encode( + json.dumps(envelope, sort_keys=True).encode("utf-8") + ).decode("ascii") + url = f"{PUBSUB_API_BASE}/{topic_path}:publish" + resp = _http_json( + "POST", + url, + token, + payload={ + "messages": [ + { + "data": encoded, + "attributes": { + "source": "compliance-bridge", + "alert_type": "heartbeat", + "probe_id": probe_id, + }, + } + ] + }, + ) + msg_ids = resp.get("messageIds") + if not isinstance(msg_ids, list) or not msg_ids: + raise AlertVerificationError( + f"Pub/Sub publish on {topic_path!r} returned no messageIds: {resp!r}" + ) + return str(msg_ids[0]) + + +def _parse_iso_epoch(raw: str) -> float | None: + if not raw: + return None + try: + cleaned = raw.strip() + if cleaned.endswith("Z"): + cleaned = cleaned[:-1] + "+00:00" + return datetime.fromisoformat(cleaned).timestamp() + except ValueError: + return None + + +def _ack_messages(subscription_path: str, token: str, ack_ids: list[str]) -> None: + if not ack_ids: + return + url = f"{PUBSUB_API_BASE}/{subscription_path}:acknowledge" + _http_json("POST", url, token, payload={"ackIds": ack_ids}) + + +def _nack_messages(subscription_path: str, token: str, ack_ids: list[str]) -> None: + if not ack_ids: + return + url = f"{PUBSUB_API_BASE}/{subscription_path}:modifyAckDeadline" + _http_json( + "POST", + url, + token, + payload={"ackIds": ack_ids, "ackDeadlineSeconds": 0}, + ) + + +def inspect_subscription_batch( + *, + subscription_path: str, + token: str, + trip_started_epoch: float, + expected_ondemand_probe_id: str | None = None, +) -> dict[str, Any]: + """Pull up to 50 messages, ack only synthetic probes, and nack all real alerts.""" + pull_url = f"{PUBSUB_API_BASE}/{subscription_path}:pull" + resp = _http_json( + "POST", + pull_url, + token, + payload={"returnImmediately": True, "maxMessages": 50}, + timeout=20.0, + ) + received = resp.get("receivedMessages") or [] + if not received: + return { + "monitoring_heartbeat_observed": False, + "monitoring_incident_id": None, + "ondemand_bridge_probe_observed": False, + "freshest_bridge_heartbeat_epoch": None, + "operational_messages_preserved": 0, + } + + ack_ids: list[str] = [] + nack_ids: list[str] = [] + monitoring_heartbeat_observed = False + monitoring_incident_id: str | None = None + ondemand_bridge_probe_observed = False + periodic_bridge_heartbeats: list[tuple[float, str]] = [] + operational_preserved = 0 + + for item in received: + ack_id = str(item.get("ackId", "")).strip() + msg = item.get("message") or {} + raw_b64 = str(msg.get("data", "")).strip() + publish_epoch = _parse_iso_epoch(str(msg.get("publishTime", ""))) or 0.0 + + payload: dict[str, Any] | None = None + if raw_b64: + try: + decoded = base64.b64decode(raw_b64).decode("utf-8", errors="replace") + parsed = json.loads(decoded) + if isinstance(parsed, dict): + payload = parsed + except Exception: + payload = None + + if payload is None: + if ack_id: + nack_ids.append(ack_id) + operational_preserved += 1 + continue + + # Case 1: Cloud Monitoring AlertPolicy notification envelope + incident = payload.get("incident") + if isinstance(incident, dict): + user_labels = incident.get("policy_user_labels") or {} + policy_name = str(incident.get("policy_name", "")) + is_synthetic_hb = ( + user_labels.get("alert_kind") == "heartbeat" + or "Synthetic Heartbeat" in policy_name + ) + if is_synthetic_hb: + started_at = float(incident.get("started_at") or 0) + state = str(incident.get("state", "")).lower() + if state == "open" and ( + started_at >= trip_started_epoch - 120.0 + or publish_epoch >= trip_started_epoch - 10.0 + ): + monitoring_heartbeat_observed = True + monitoring_incident_id = str(incident.get("incident_id", "")) + # Ack all synthetic Cloud Monitoring heartbeat messages (open/close/stale) + # so synthetic delivery checks never clutter the subscription. + if ack_id: + ack_ids.append(ack_id) + else: + if ack_id: + nack_ids.append(ack_id) + operational_preserved += 1 + continue + + # Case 2: compliance-bridge notifier envelope + if ( + payload.get("source") in ("compliance-bridge", "compliance_bridge") + and payload.get("alert_type") == "heartbeat" + ): + probe_id = str(payload.get("probe_id", "")).strip() + msg_epoch = ( + _parse_iso_epoch(str(payload.get("timestamp", ""))) or publish_epoch + ) + if expected_ondemand_probe_id and probe_id == expected_ondemand_probe_id: + ondemand_bridge_probe_observed = True + if ack_id: + ack_ids.append(ack_id) + elif probe_id: + # Stale on-demand probe from an earlier run -> ack to keep queue clean. + if ack_id: + ack_ids.append(ack_id) + else: + # Periodic SLA-monitor heartbeat from compliance-bridge pod: + # keep only the newest unacked so repeated verification runs are idempotent! + if ack_id: + periodic_bridge_heartbeats.append((msg_epoch, ack_id)) + continue + + # Everything else is an operational alert -> preserve in queue! + if ack_id: + nack_ids.append(ack_id) + operational_preserved += 1 + + freshest_bridge_epoch: float | None = None + if periodic_bridge_heartbeats: + periodic_bridge_heartbeats.sort(key=lambda pair: pair[0], reverse=True) + freshest_bridge_epoch, newest_ack_id = periodic_bridge_heartbeats[0] + nack_ids.append(newest_ack_id) + for _older_epoch, older_ack_id in periodic_bridge_heartbeats[1:]: + ack_ids.append(older_ack_id) + + _ack_messages(subscription_path, token, ack_ids) + _nack_messages(subscription_path, token, nack_ids) + + return { + "monitoring_heartbeat_observed": monitoring_heartbeat_observed, + "monitoring_incident_id": monitoring_incident_id, + "ondemand_bridge_probe_observed": ondemand_bridge_probe_observed, + "freshest_bridge_heartbeat_epoch": freshest_bridge_epoch, + "operational_messages_preserved": operational_preserved, + } + + +def verify_end_to_end_delivery( + *, + project: str, + subscription: str, + token: str, + timeout_seconds: int = 240, + poll_interval_seconds: int = 10, + require_bridge_heartbeat: bool = True, + max_bridge_heartbeat_age_seconds: int = 25200, + emit_bridge_heartbeat_topic: str = "", +) -> dict[str, Any]: + """Trip Cloud Monitoring synthetic heartbeat + verify arrival on Pub/Sub.""" + subscription_path = _normalize_subscription(project, subscription) + ondemand_probe_id: str | None = None + if emit_bridge_heartbeat_topic.strip(): + ondemand_probe_id = uuid.uuid4().hex[:12] + topic_path = _normalize_topic(project, emit_bridge_heartbeat_topic) + publish_synthetic_bridge_probe( + topic_path=topic_path, + token=token, + probe_id=ondemand_probe_id, + ) + + trip_started_epoch = time.time() + last_metric_write = 0.0 + monitoring_ok = False + monitoring_incident_id: str | None = None + ondemand_ok = ondemand_probe_id is None + freshest_bridge_epoch: float | None = None + + try: + deadline = trip_started_epoch + max(timeout_seconds, 15) + while time.time() < deadline: + now = time.time() + if now - last_metric_write >= 55.0: + write_heartbeat_metric(project=project, token=token, value=1) + last_metric_write = now + + batch = inspect_subscription_batch( + subscription_path=subscription_path, + token=token, + trip_started_epoch=trip_started_epoch, + expected_ondemand_probe_id=ondemand_probe_id, + ) + if batch["monitoring_heartbeat_observed"]: + monitoring_ok = True + monitoring_incident_id = batch["monitoring_incident_id"] + if batch["ondemand_bridge_probe_observed"]: + ondemand_ok = True + if batch["freshest_bridge_heartbeat_epoch"] is not None: + if ( + freshest_bridge_epoch is None + or batch["freshest_bridge_heartbeat_epoch"] > freshest_bridge_epoch + ): + freshest_bridge_epoch = batch["freshest_bridge_heartbeat_epoch"] + + bridge_fresh_ok = not require_bridge_heartbeat or ( + freshest_bridge_epoch is not None + and (time.time() - freshest_bridge_epoch) + <= max_bridge_heartbeat_age_seconds + ) + if monitoring_ok and ondemand_ok and bridge_fresh_ok: + break + + time.sleep(max(poll_interval_seconds, 1)) + finally: + # Always reset the synthetic probe gauge to 0 so the heartbeat policy closes. + write_heartbeat_metric(project=project, token=token, value=0) + + if not monitoring_ok: + raise AlertVerificationError( + f"Timed out after {timeout_seconds}s waiting for Cloud Monitoring " + f"alert_pipeline_heartbeat notification on {subscription_path!r}." + ) + + if not ondemand_ok: + raise AlertVerificationError( + f"On-demand compliance-bridge Pub/Sub probe ({ondemand_probe_id}) was " + f"not observed on {subscription_path!r} within {timeout_seconds}s." + ) + + bridge_age_seconds: float | None = None + if freshest_bridge_epoch is not None: + bridge_age_seconds = round(max(0.0, time.time() - freshest_bridge_epoch), 2) + + if require_bridge_heartbeat: + if bridge_age_seconds is None: + raise AlertVerificationError( + f"No periodic compliance_bridge heartbeat message found on " + f"{subscription_path!r} (expected within " + f"{max_bridge_heartbeat_age_seconds}s)." + ) + if bridge_age_seconds > max_bridge_heartbeat_age_seconds: + raise AlertVerificationError( + f"Freshest compliance_bridge heartbeat on {subscription_path!r} is " + f"{bridge_age_seconds:.1f}s old, exceeding max age " + f"{max_bridge_heartbeat_age_seconds}s." + ) + + return { + "subscription": subscription_path, + "monitoring_heartbeat_delivered": True, + "monitoring_incident_id": monitoring_incident_id, + "ondemand_bridge_probe_delivered": ondemand_probe_id is not None, + "periodic_bridge_heartbeat_age_seconds": bridge_age_seconds, + } + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Verify CAGE Cloud Monitoring AlertPolicy bindings and end-to-end " + "heartbeat delivery to the terminal Pub/Sub subscription (POAM-2026-230)." + ) + ) + parser.add_argument("--project", required=True, help="GCP project ID.") + parser.add_argument( + "--cluster-name", + default="cage-staging", + help="Cluster prefix on AlertPolicy displayName (default: cage-staging).", + ) + parser.add_argument( + "--subscription", + required=True, + help="Pub/Sub subscription name or full projects/

/subscriptions/ path.", + ) + parser.add_argument( + "--min-policies", + type=int, + default=9, + help="Minimum number of cluster AlertPolicies required (default: 9).", + ) + parser.add_argument( + "--expected-channel", + action="append", + default=[], + help="Optional expected NotificationChannel resource name (repeatable).", + ) + parser.add_argument( + "--timeout-seconds", + type=int, + default=240, + help="Max seconds to wait for heartbeat incident delivery (default: 240).", + ) + parser.add_argument( + "--poll-interval-seconds", + type=int, + default=10, + help="Seconds between Pub/Sub pull checks (default: 10).", + ) + parser.add_argument( + "--skip-bridge-heartbeat", + action="store_true", + help="Skip asserting freshness of the in-cluster periodic compliance-bridge heartbeat.", + ) + parser.add_argument( + "--max-bridge-heartbeat-age-seconds", + type=int, + default=25200, + help="Max age in seconds for the periodic compliance-bridge heartbeat (default: 25200 = 7h).", + ) + parser.add_argument( + "--emit-bridge-heartbeat-topic", + default="", + help="Optional Pub/Sub topic to publish an immediate on-demand bridge probe.", + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + args = _build_parser().parse_args(argv) + try: + token = resolve_gcp_access_token() + policy_report = verify_runtime_alert_policies( + project=args.project, + cluster_name=args.cluster_name, + token=token, + min_policies=args.min_policies, + expected_channels=args.expected_channel or None, + ) + delivery_report = verify_end_to_end_delivery( + project=args.project, + subscription=args.subscription, + token=token, + timeout_seconds=args.timeout_seconds, + poll_interval_seconds=args.poll_interval_seconds, + require_bridge_heartbeat=not args.skip_bridge_heartbeat, + max_bridge_heartbeat_age_seconds=args.max_bridge_heartbeat_age_seconds, + emit_bridge_heartbeat_topic=args.emit_bridge_heartbeat_topic, + ) + except AlertVerificationError as exc: + print( + json.dumps( + { + "status": "FAIL", + "error": str(exc), + "checked_at": datetime.now(timezone.utc).isoformat(), + }, + indent=2, + ), + file=sys.stderr, + ) + return 1 + + print( + json.dumps( + { + "status": "PASS", + "checked_at": datetime.now(timezone.utc).isoformat(), + "runtime_policies": policy_report, + "delivery": delivery_report, + }, + indent=2, + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/compliance_bridge/audit_workflow.py b/src/compliance_bridge/audit_workflow.py index 0b90e3b83..c4f88c44c 100644 --- a/src/compliance_bridge/audit_workflow.py +++ b/src/compliance_bridge/audit_workflow.py @@ -391,13 +391,20 @@ async def _step4_alert_on_critical_fail( return False, [] notifier = create_notifier() - await notifier.send_critical_alert(critical_fails, audit_id) + delivered = (await notifier.send_critical_alert(critical_fails, audit_id)) is True alert_targets = [f.control_id for f in critical_fails] - logger.info( - "[audit_workflow] Critical alert sent for: %s", ", ".join(alert_targets) - ) - return True, alert_targets + if delivered: + logger.info( + "[audit_workflow] Critical alert delivered for: %s", + ", ".join(alert_targets), + ) + else: + logger.error( + "[audit_workflow] Critical alert NOT delivered externally for: %s", + ", ".join(alert_targets), + ) + return delivered, alert_targets # --------------------------------------------------------------------------- @@ -626,13 +633,15 @@ async def _step5_one_control( # Deliver notification notifier = create_notifier() - await notifier.send_remediation_followup( - control_id=control_id, - audit_id=audit_id, - model_name=model_name, - remediation_text=remediation_text, - trace_ids=trace_ids_sampled, - ) + remediation_delivered = ( + await notifier.send_remediation_followup( + control_id=control_id, + audit_id=audit_id, + model_name=model_name, + remediation_text=remediation_text, + trace_ids=trace_ids_sampled, + ) + ) is True # Log advisory to compliance Langfuse (non-fatal) # C-09: Use correct Langfuse SDK v2 API — propagate_attributes and @@ -706,7 +715,7 @@ def _log_advisory_sync() -> None: return { "control_id": control_id, - "remediation_sent": True, + "remediation_sent": remediation_delivered, "remediation_text": remediation_text, "advisor_error": None, "trace_ids_sampled": trace_ids_sampled, diff --git a/src/compliance_bridge/main.py b/src/compliance_bridge/main.py index a8d6a6b3f..aeb5e4f11 100644 --- a/src/compliance_bridge/main.py +++ b/src/compliance_bridge/main.py @@ -116,7 +116,11 @@ def _ensure_langfuse_imported() -> None: get_compliance_metrics, invalidate_compliance_metrics_cache, ) -from .notifier import create_notifier +from .notifier import ( + create_notifier, + is_external_notifier_configured, + validate_notifier_config, +) from .oscal_exporter import build_oscal_assessment_results, findings_from_metrics_dict from .sla_monitor import run_sla_monitor from .sse_events import event_bus @@ -239,9 +243,11 @@ async def lifespan(app: FastAPI): # type: ignore[no-untyped-def] "is True or CAGE_ENV is not 'dev'/'development' (POAM-2026-167 / LT-1)." ) - # POAM-018: fail closed on missing Langfuse credentials before any custody - # client, background task or connection is created. + # POAM-018 & POAM-2026-230: fail closed on missing Langfuse credentials or + # unconfigured/console alert notifier before any custody client, background + # task or connection is created. validate_langfuse_credentials() + validate_notifier_config() _custodian: EvidenceCustodian | None = None _custody_task: asyncio.Task | None = None @@ -625,6 +631,7 @@ async def health() -> dict: "langfuse_compliance_configured": langfuse_compliance_configured, "langfuse_app_configured": langfuse_app_configured, "oscal_storage_configured": oscal_storage_configured, + "alert_channel_configured": is_external_notifier_configured(), "environment": active_env, } @@ -1707,7 +1714,13 @@ async def _handle_lula_audit_post_custody( audit_id = f"lula-audit-{receipt_hash[:16]}" try: notifier = create_notifier() - await notifier.send_critical_alert(findings, audit_id) + delivered = (await notifier.send_critical_alert(findings, audit_id)) is True + if not delivered: + logger.error( + "[infra/events] Notifier did not confirm external delivery for CRITICAL " + "lula_audit event (record_hash=%s)", + receipt_hash, + ) except Exception as notify_exc: logger.error( "[infra/events] Notifier transport failed after CRITICAL lula_audit log " diff --git a/src/compliance_bridge/notifier.py b/src/compliance_bridge/notifier.py index e3bcb308b..35327a425 100644 --- a/src/compliance_bridge/notifier.py +++ b/src/compliance_bridge/notifier.py @@ -15,50 +15,88 @@ """ notifier.py — Alert channel abstraction for ISO 42001 compliance events. -Ported from src/langfuse-bridge/src/notifier.ts. +Ported from src/langfuse-bridge/src/notifier.ts and hardened for POAM-2026-230. Channel selection is driven by the ALERT_CHANNEL environment variable: - ALERT_CHANNEL=console (default) — Logs JSON payload to stdout via logging.warning(). - Zero external deps. Visible in `kubectl logs`. + ALERT_CHANNEL=pubsub — Publishes structured JSON alert events to a + Google Cloud Pub/Sub topic via the Pub/Sub REST + API using Workload Identity / ADC credentials. + Requires COMPLIANCE_ALERT_PUBSUB_TOPIC + ('projects//topics/'). + Reference-architecture terminal sink on GKE. - ALERT_CHANNEL=slack — Posts Slack Block Kit payloads to - COMPLIANCE_ALERT_WEBHOOK_URL using httpx. + ALERT_CHANNEL=slack — Posts Slack Block Kit payloads to an HTTPS + COMPLIANCE_ALERT_WEBHOOK_URL (or SLACK_WEBHOOK_URL) + using httpx. - ALERT_CHANNEL=pagerduty (Capability 2.4) — Posts PagerDuty Events API v2 incidents. + ALERT_CHANNEL=pagerduty — Posts PagerDuty Events API v2 incidents. Requires PAGERDUTY_ROUTING_KEY. - Closes POAM-008 / NIST IR-1 incident response. Severity mapping: - FAIL critical control → 'critical' (pages on-call) + FAIL critical control → 'critical' SLA breach → 'error' - Remediation advisory → 'info' + Heartbeat / advisory → 'info' - ALERT_CHANNEL=webhook (Capability 2.4) — Posts a generic JSON payload to any HTTP + ALERT_CHANNEL=webhook — Posts a generic JSON payload to any HTTPS endpoint (OpsGenie, Jira Service Mgmt, ServiceNow). Requires COMPLIANCE_ALERT_WEBHOOK_URL. + ALERT_CHANNEL=console — Logs JSON payload to stdout via logging.warning() + and returns False (not delivered externally). + Permitted ONLY in permissive postures (dev/test/ci); + refused at startup in enforcing postures (POAM-2026-230). + ALERT_CHANNEL=mock — Captures calls in-memory, no I/O. - Use in unit tests. + Permitted ONLY in non-enforcing test postures + when TESTING=1. -The SLACK_WEBHOOK_URL env var is also accepted as an alias for -COMPLIANCE_ALERT_WEBHOOK_URL (backward compat with the task spec). +Every notifier returns a boolean from ``send_critical_alert()`` and +``send_remediation_followup()`` reflecting observed destination acknowledgement +(HTTP 2xx / Pub/Sub ``messageIds``), never merely that the notifier was called. """ from __future__ import annotations +import argparse import asyncio +import base64 import json import logging import os +import re +import sys +import uuid +from collections.abc import Mapping from datetime import datetime, timezone from typing import Protocol +from urllib.parse import urlparse import httpx +from src.gateway.governance.env_posture import is_enforcing + from .types import OscalFinding logger = logging.getLogger(__name__) +_PUBSUB_TOPIC_RE = re.compile( + r"^projects/[a-z][a-z0-9-]{4,28}[a-z0-9]/topics/[A-Za-z][A-Za-z0-9\-_.~%+]{2,254}$" +) +_PUBSUB_API_BASE = "https://pubsub.googleapis.com/v1" +_PUBSUB_SCOPE = "https://www.googleapis.com/auth/pubsub" + +# PagerDuty Events API v2 endpoint — hardcoded per PD docs, not configurable +_PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue" + +SUPPORTED_ENFORCING_ALERT_CHANNELS = frozenset( + {"pubsub", "webhook", "slack", "pagerduty"} +) + + +class NotifierConfigError(RuntimeError, ValueError): + """Raised when ALERT_CHANNEL or its destination configuration is invalid.""" + + # --------------------------------------------------------------------------- # HIGH-3 FIX: Shared HTTP client to prevent resource exhaustion # @@ -94,8 +132,128 @@ async def close_notifier_http_client() -> None: logger.info("[notifier] Shared HTTP client closed") -# PagerDuty Events API v2 endpoint — hardcoded per PD docs, not configurable -_PAGERDUTY_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue" +def _validate_https_webhook_url(url: str, *, channel: str) -> str: + cleaned = url.strip() + if not cleaned: + raise NotifierConfigError( + f"[POAM-2026-230] ALERT_CHANNEL={channel} requires COMPLIANCE_ALERT_WEBHOOK_URL " + "(or SLACK_WEBHOOK_URL) to be set; console fallback is refused." + ) + parsed = urlparse(cleaned) + if parsed.scheme != "https" or not parsed.netloc: + raise NotifierConfigError( + f"[POAM-2026-230] ALERT_CHANNEL={channel} requires an https:// webhook URL; " + f"got scheme={parsed.scheme!r}." + ) + return cleaned + + +def _validate_pubsub_topic(topic: str) -> str: + cleaned = topic.strip() + if not cleaned or not _PUBSUB_TOPIC_RE.match(cleaned): + raise NotifierConfigError( + "[POAM-2026-230] ALERT_CHANNEL=pubsub requires COMPLIANCE_ALERT_PUBSUB_TOPIC " + "matching 'projects//topics/'; console fallback is refused." + ) + return cleaned + + +def validate_notifier_config(env: Mapping[str, str] | None = None) -> str: + """Validate ``ALERT_CHANNEL`` and its destination settings (POAM-2026-230 Property 1b). + + Under an enforcing posture (``staging``, ``production``, ``local``, or an + unknown ``CAGE_ENV``), ``ALERT_CHANNEL`` must name a supported external + channel (``pubsub``, ``webhook``, ``slack``, or ``pagerduty``) with valid + destination settings; unset, ``console``, and ``mock`` are refused. + + Under permissive postures (``dev``, ``test``, ``ci``), ``console`` (or unset) + logs a warning and is allowed for local development, and ``mock`` is allowed + when ``TESTING`` is set; explicitly selecting an external channel with + missing/invalid settings or an unknown channel still raises + :class:`NotifierConfigError` rather than silently degrading to stdout. + """ + source = os.environ if env is None else env + enforcing = is_enforcing(source) + raw = source.get("ALERT_CHANNEL", "") + channel = raw.strip().lower() + + if enforcing: + if not channel or channel == "console": + raise NotifierConfigError( + "[POAM-2026-230] ALERT_CHANNEL is unset or 'console' under an enforcing " + "posture. Set ALERT_CHANNEL to 'pubsub' (with COMPLIANCE_ALERT_PUBSUB_TOPIC=" + "'projects//topics/'), 'webhook'/'slack' (with https:// " + "COMPLIANCE_ALERT_WEBHOOK_URL), or 'pagerduty' (with PAGERDUTY_ROUTING_KEY) — on " + "GKE, populate compliance_alert_channel and alert_pubsub_topic in gitignored " + "infra/targets/gcp-gke/terraform.auto.tfvars (see AL-01 in docs/BREAKING_CHANGES.md)." + ) + if channel == "mock": + raise NotifierConfigError( + "[POAM-2026-230] MockNotifier is not permitted under an enforcing posture." + ) + + if not channel or channel == "console": + logger.warning( + "[POAM-2026-230] ALERT_CHANNEL=%r in permissive posture — alerts will write " + "stdout log lines only and report alerted=False.", + channel or "console", + ) + return "console" + + if channel == "mock": + if not source.get("TESTING"): + raise NotifierConfigError( + "MockNotifier is not permitted in production. " + "Set ALERT_CHANNEL to a real channel (pubsub, slack, pagerduty, webhook) " + "or set TESTING=1 to enable mock notifications in a test environment." + ) + return "mock" + + if channel == "pagerduty": + routing_key = source.get("PAGERDUTY_ROUTING_KEY", "").strip() + if not routing_key: + raise NotifierConfigError( + "[POAM-2026-230] ALERT_CHANNEL=pagerduty requires PAGERDUTY_ROUTING_KEY; " + "console fallback is refused." + ) + return "pagerduty" + + if channel in ("webhook", "slack"): + url = source.get("COMPLIANCE_ALERT_WEBHOOK_URL") or source.get( + "SLACK_WEBHOOK_URL", "" + ) + _validate_https_webhook_url(url, channel=channel) + return channel + + if channel == "pubsub": + _validate_pubsub_topic(source.get("COMPLIANCE_ALERT_PUBSUB_TOPIC", "")) + return "pubsub" + + raise NotifierConfigError( + f"[POAM-2026-230] Unknown ALERT_CHANNEL={raw!r}. Expected one of " + f"{sorted(SUPPORTED_ENFORCING_ALERT_CHANNELS)} (or 'console' in dev/test/ci)." + ) + + +def is_external_notifier_configured(env: Mapping[str, str] | None = None) -> bool: + """Return True iff ``env`` configures a valid external alert destination.""" + source = os.environ if env is None else env + raw = source.get("ALERT_CHANNEL", "").strip().lower() + if raw not in SUPPORTED_ENFORCING_ALERT_CHANNELS: + return False + try: + validate_notifier_config({**dict(source), "CAGE_ENV": "production"}) + return True + except NotifierConfigError: + return False + + +def _is_heartbeat_batch(findings: list[OscalFinding]) -> bool: + return bool(findings) and all( + (f.assessment_status or "").lower() == "heartbeat" + or f.control_id == "CA-7-HEARTBEAT" + for f in findings + ) # --------------------------------------------------------------------------- @@ -107,14 +265,25 @@ def _build_critical_alert_body( critical_fails: list[OscalFinding], audit_id: str, ) -> dict: + is_hb = _is_heartbeat_batch(critical_fails) + title = ( + "💓 CAGE Synthetic Alert Pipeline Heartbeat (No Action Required)" + if is_hb + else "🚨 ISO 42001 Critical Control FAIL" + ) + headline = ( + "💓 CAGE Synthetic Alert Pipeline Heartbeat — No Action Required" + if is_hb + else "🚨 ISO 42001 CRITICAL COMPLIANCE FAILURE — Cybernetic Governance Engine" + ) return { - "text": "🚨 ISO 42001 CRITICAL COMPLIANCE FAILURE — Cybernetic Governance Engine", + "text": headline, "blocks": [ { "type": "header", "text": { "type": "plain_text", - "text": "🚨 ISO 42001 Critical Control FAIL", + "text": title, }, }, *[ @@ -159,11 +328,9 @@ def _escape_slack_mrkdwn(text: str) -> str: channel mentions, user mentions) from untrusted LLM output. See: https://api.slack.com/reference/surfaces/formatting#escaping """ - # Escape the three HTML entities Slack requires text = text.replace("&", "&") text = text.replace("<", "<") text = text.replace(">", ">") - # Neutralise mrkdwn formatting characters that could be injected for ch in ("*", "_", "`", "~"): text = text.replace(ch, f"\\{ch}") return text @@ -177,7 +344,6 @@ def _build_remediation_followup_body( trace_ids: list[str], ) -> dict: trace_ref = ", ".join(trace_ids) if trace_ids else "none available" - # M-22: Escape LLM-generated text before embedding in Slack mrkdwn safe_remediation_text = _escape_slack_mrkdwn(remediation_text) return { "text": f"🔍 Remediation Advisory — {control_id} | Audit {audit_id}", @@ -265,7 +431,134 @@ async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: ... + ) -> bool: ... + + async def send_remediation_followup( + self, + control_id: str, + audit_id: str, + model_name: str, + remediation_text: str, + trace_ids: list[str], + ) -> bool: ... + + +# --------------------------------------------------------------------------- +# PubSubNotifier — GCP Pub/Sub REST channel (POAM-2026-230 reference sink) +# --------------------------------------------------------------------------- + + +def _fetch_pubsub_access_token_sync() -> str: + """Mint a short-lived OAuth2 bearer token via Google ADC / Workload Identity.""" + import google.auth + from google.auth.transport.requests import Request as GoogleAuthRequest + + creds, _ = google.auth.default(scopes=[_PUBSUB_SCOPE]) + if not creds.valid or not creds.token: + creds.refresh(GoogleAuthRequest()) + if not creds.token: + raise RuntimeError("Google ADC returned an empty Pub/Sub access token") + return str(creds.token) + + +class PubSubNotifier: + """Publishes structured JSON alert events to a Google Cloud Pub/Sub topic.""" + + def __init__(self, topic: str) -> None: + self._topic = _validate_pubsub_topic(topic) + + @property + def topic(self) -> str: + return self._topic + + async def _publish(self, payload: dict, *, alert_type: str, audit_id: str) -> bool: + try: + token = await asyncio.to_thread(_fetch_pubsub_access_token_sync) + encoded = base64.b64encode( + json.dumps(payload, sort_keys=True).encode("utf-8") + ).decode("ascii") + body = { + "messages": [ + { + "data": encoded, + "attributes": { + "source": "compliance-bridge", + "alert_type": alert_type, + "audit_id": audit_id, + }, + } + ] + } + client = await _get_notifier_http_client() + resp = await client.post( + f"{_PUBSUB_API_BASE}/{self._topic}:publish", + json=body, + headers={ + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + }, + ) + if not resp.is_success: + logger.error( + "[PubSubNotifier] Pub/Sub publish returned HTTP %d: %s", + resp.status_code, + resp.text[:256], + ) + return False + resp_json = resp.json() + msg_ids = ( + resp_json.get("messageIds") if isinstance(resp_json, dict) else None + ) + if not isinstance(msg_ids, list) or not any( + isinstance(m, str) and m.strip() for m in msg_ids + ): + logger.error( + "[PubSubNotifier] Pub/Sub publish returned HTTP %d without messageIds", + resp.status_code, + ) + return False + logger.info( + "[PubSubNotifier] Published %s alert (audit_id=%s, message_id=%s)", + alert_type, + audit_id, + msg_ids[0], + ) + return True + except Exception as exc: + logger.error("[PubSubNotifier] Failed to publish alert: %s", exc) + return False + + async def send_critical_alert( + self, + critical_fails: list[OscalFinding], + audit_id: str, + ) -> bool: + if not critical_fails: + return False + alert_type = ( + "heartbeat" if _is_heartbeat_batch(critical_fails) else "critical_failure" + ) + return await self._publish( + { + "source": "compliance-bridge", + "alert_type": alert_type, + "audit_id": audit_id, + "timestamp": datetime.now(tz=timezone.utc).isoformat(), + "findings": [ + { + "control_id": f.control_id, + "result": f.result, + "finding_id": f.finding_id, + "assessment_status": f.assessment_status, + "remarks": f.remarks, + "safety_rate": f.safety_rate, + } + for f in critical_fails + ], + }, + alert_type=alert_type, + audit_id=audit_id, + ) async def send_remediation_followup( self, @@ -274,26 +567,42 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: ... + ) -> bool: + return await self._publish( + { + "source": "compliance-bridge", + "alert_type": "remediation", + "audit_id": audit_id, + "control_id": control_id, + "timestamp": datetime.now(tz=timezone.utc).isoformat(), + "model_name": model_name, + "remediation_text": remediation_text, + "trace_ids": trace_ids, + "note": "LLM-generated advisory — verify before applying (ISO 42001 A.7.2)", + }, + alert_type="remediation", + audit_id=audit_id, + ) # --------------------------------------------------------------------------- -# SlackNotifier — production channel +# SlackNotifier — HTTPS Block Kit webhook channel # --------------------------------------------------------------------------- class SlackNotifier: def __init__(self, webhook_url: str) -> None: - self._webhook_url = webhook_url + self._webhook_url = _validate_https_webhook_url(webhook_url, channel="slack") async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: + ) -> bool: + if not critical_fails: + return False body = _build_critical_alert_body(critical_fails, audit_id) try: - # HIGH-3 FIX: Reuse shared client instead of creating new one per request client = await _get_notifier_http_client() resp = await client.post( self._webhook_url, @@ -305,12 +614,12 @@ async def send_critical_alert( "[SlackNotifier] 🚨 Alert sent for: %s", ", ".join(f.control_id for f in critical_fails), ) - else: - logger.error( - "[SlackNotifier] Alert webhook returned %d", resp.status_code - ) + return True + logger.error("[SlackNotifier] Alert webhook returned %d", resp.status_code) + return False except Exception as exc: logger.error("[SlackNotifier] Failed to send alert: %s", exc) + return False async def send_remediation_followup( self, @@ -319,12 +628,11 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: + ) -> bool: body = _build_remediation_followup_body( control_id, audit_id, model_name, remediation_text, trace_ids ) try: - # HIGH-3 FIX: Reuse shared client instead of creating new one per request client = await _get_notifier_http_client() resp = await client.post( self._webhook_url, @@ -336,48 +644,49 @@ async def send_remediation_followup( "[SlackNotifier] 📨 Remediation advisory posted to Slack for %s", control_id, ) - else: - logger.error( - "[SlackNotifier] Slack follow-up returned %d", resp.status_code - ) + return True + logger.error( + "[SlackNotifier] Slack follow-up returned %d", resp.status_code + ) + return False except Exception as exc: logger.error("[SlackNotifier] Failed to post Slack follow-up: %s", exc) + return False # --------------------------------------------------------------------------- -# PagerDutyNotifier — incident management channel (Capability 2.4 / POAM-008) -# -# Uses PagerDuty Events API v2 (https://developer.pagerduty.com/docs/events-api-v2). -# Requires PAGERDUTY_ROUTING_KEY (integration key from a PD service). -# -# Severity mapping: -# Critical control FAIL → 'critical' (pages on-call immediately) -# SLA breach → 'error' (high priority, may be suppressed by noise rules) -# Remediation advisory → 'info' (informational, no page) -# -# Dedup key: cage-- -# Multiple alerts for the same audit+control are automatically de-duplicated. +# PagerDutyNotifier — incident management channel (Capability 2.4 / POAM-008) # --------------------------------------------------------------------------- class PagerDutyNotifier: def __init__(self, routing_key: str) -> None: - self._routing_key = routing_key + cleaned = routing_key.strip() + if not cleaned: + raise NotifierConfigError( + "[POAM-2026-230] PagerDutyNotifier requires a non-empty routing_key." + ) + self._routing_key = cleaned async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: + ) -> bool: """Trigger one PagerDuty incident per critical failing control.""" + if not critical_fails: + return False + is_hb = _is_heartbeat_batch(critical_fails) + all_delivered = True for finding in critical_fails: dedup_key = f"cage-{audit_id}-{finding.control_id}" payload = _build_pagerduty_trigger( summary=( - f"[CAGE] ISO 42001 Critical Failure: {finding.control_id} — " - f"Audit {audit_id}" + f"[CAGE] Synthetic Alert Heartbeat (No Action Required) — {audit_id}" + if is_hb + else f"[CAGE] ISO 42001 Critical Failure: {finding.control_id} — Audit {audit_id}" ), - severity="critical", + severity="info" if is_hb else "critical", source="compliance-bridge", routing_key=self._routing_key, dedup_key=dedup_key, @@ -388,11 +697,11 @@ async def send_critical_alert( "remarks": finding.remarks or "", "safety_rate": finding.safety_rate, "audit_id": audit_id, + "alert_type": "heartbeat" if is_hb else "critical_failure", "standard": "ISO/IEC 42001:2023", }, ) try: - # HIGH-3 FIX: Reuse shared client instead of creating new one per request client = await _get_notifier_http_client() resp = await client.post( _PAGERDUTY_EVENTS_URL, @@ -401,11 +710,12 @@ async def send_critical_alert( ) if resp.is_success: logger.info( - "[PagerDutyNotifier] 🚨 Incident triggered: %s (dedup=%s)", + "[PagerDutyNotifier] 🚨 Event delivered: %s (dedup=%s)", finding.control_id, dedup_key, ) else: + all_delivered = False logger.error( "[PagerDutyNotifier] Events API returned %d for %s: %s", resp.status_code, @@ -413,11 +723,13 @@ async def send_critical_alert( resp.text, ) except Exception as exc: + all_delivered = False logger.error( "[PagerDutyNotifier] Failed to trigger incident for %s: %s", finding.control_id, exc, ) + return all_delivered async def send_remediation_followup( self, @@ -426,7 +738,7 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: + ) -> bool: """Post an informational PD event for the remediation advisory.""" dedup_key = f"cage-remediation-{audit_id}-{control_id}" payload = _build_pagerduty_trigger( @@ -439,13 +751,12 @@ async def send_remediation_followup( "control_id": control_id, "audit_id": audit_id, "model_name": model_name, - "remediation_text": remediation_text[:512], # PD detail limit + "remediation_text": remediation_text[:512], "trace_ids": trace_ids, "note": "LLM-generated — human verification required (ISO 42001 A.7.2)", }, ) try: - # HIGH-3 FIX: Reuse shared client instead of creating new one per request client = await _get_notifier_http_client() resp = await client.post( _PAGERDUTY_EVENTS_URL, @@ -457,42 +768,34 @@ async def send_remediation_followup( "[PagerDutyNotifier] 📨 Remediation advisory event posted for %s", control_id, ) - else: - logger.error( - "[PagerDutyNotifier] Events API returned %d for remediation %s: %s", - resp.status_code, - control_id, - resp.text, - ) + return True + logger.error( + "[PagerDutyNotifier] Events API returned %d for remediation %s: %s", + resp.status_code, + control_id, + resp.text, + ) + return False except Exception as exc: logger.error( "[PagerDutyNotifier] Failed to post remediation advisory for %s: %s", control_id, exc, ) + return False # --------------------------------------------------------------------------- -# WebhookNotifier — generic JSON POST channel (Capability 2.4) -# -# Sends a structured JSON payload to any HTTP endpoint that accepts POST. -# Compatible with OpsGenie, Jira Service Management, ServiceNow, and any -# custom ITSM webhook receiver. -# -# Payload shape: -# critical_failure: { source, alert_type, audit_id, timestamp, findings: [...] } -# remediation: { source, alert_type, audit_id, control_id, timestamp, -# model_name, remediation_text, trace_ids, note } +# WebhookNotifier — generic HTTPS JSON POST channel (Capability 2.4) # --------------------------------------------------------------------------- class WebhookNotifier: def __init__(self, webhook_url: str) -> None: - self._webhook_url = webhook_url + self._webhook_url = _validate_https_webhook_url(webhook_url, channel="webhook") - async def _post(self, payload: dict) -> None: + async def _post(self, payload: dict) -> bool: try: - # HIGH-3 FIX: Reuse shared client instead of creating new one per request client = await _get_notifier_http_client() resp = await client.post( self._webhook_url, @@ -506,24 +809,31 @@ async def _post(self, payload: dict) -> None: logger.info( "[WebhookNotifier] ✅ Payload posted (HTTP %d)", resp.status_code ) - else: - logger.error( - "[WebhookNotifier] Webhook returned %d: %s", - resp.status_code, - resp.text, - ) + return True + logger.error( + "[WebhookNotifier] Webhook returned %d: %s", + resp.status_code, + resp.text, + ) + return False except Exception as exc: logger.error("[WebhookNotifier] Failed to POST to webhook: %s", exc) + return False async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: - await self._post( + ) -> bool: + if not critical_fails: + return False + alert_type = ( + "heartbeat" if _is_heartbeat_batch(critical_fails) else "critical_failure" + ) + return await self._post( { "source": "compliance-bridge", - "alert_type": "critical_failure", + "alert_type": alert_type, "audit_id": audit_id, "timestamp": datetime.now(tz=timezone.utc).isoformat(), "findings": [ @@ -531,6 +841,7 @@ async def send_critical_alert( "control_id": f.control_id, "result": f.result, "finding_id": f.finding_id, + "assessment_status": f.assessment_status, "remarks": f.remarks, "safety_rate": f.safety_rate, } @@ -546,8 +857,8 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: - await self._post( + ) -> bool: + return await self._post( { "source": "compliance-bridge", "alert_type": "remediation", @@ -563,21 +874,24 @@ async def send_remediation_followup( # --------------------------------------------------------------------------- -# ConsoleNotifier — dev / CI channel (default) +# ConsoleNotifier — permissive dev/test/ci channel ONLY (returns False) # --------------------------------------------------------------------------- class ConsoleNotifier: + """Writes stdout log lines in permissive postures and returns False (not delivered).""" + async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: + ) -> bool: body = _build_critical_alert_body(critical_fails, audit_id) logger.warning( - "[ConsoleNotifier] 🚨 CRITICAL COMPLIANCE ALERT (dev mode — no Slack webhook)\n%s", + "[ConsoleNotifier] 🚨 CRITICAL COMPLIANCE ALERT (dev mode — no external sink)\n%s", json.dumps(body, indent=2), ) + return False async def send_remediation_followup( self, @@ -586,15 +900,16 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: + ) -> bool: body = _build_remediation_followup_body( control_id, audit_id, model_name, remediation_text, trace_ids ) logger.warning( - "[ConsoleNotifier] 🔍 REMEDIATION ADVISORY for %s (dev mode — no Slack webhook)\n%s", + "[ConsoleNotifier] 🔍 REMEDIATION ADVISORY for %s (dev mode — no external sink)\n%s", control_id, json.dumps(body, indent=2), ) + return False # --------------------------------------------------------------------------- @@ -605,8 +920,9 @@ async def send_remediation_followup( class MockNotifier: """Captures all calls in-memory for assertion in unit tests. No I/O.""" - def __init__(self) -> None: + def __init__(self, *, simulate_delivery_failure: bool = False) -> None: self.calls: list[dict] = [] + self.simulate_delivery_failure = simulate_delivery_failure @property def alert_count(self) -> int: @@ -617,7 +933,7 @@ async def send_critical_alert( self, critical_fails: list[OscalFinding], audit_id: str, - ) -> None: + ) -> bool: self.calls.append( { "type": "critical", @@ -625,6 +941,7 @@ async def send_critical_alert( "audit_id": audit_id, } ) + return not self.simulate_delivery_failure async def send_remediation_followup( self, @@ -633,7 +950,7 @@ async def send_remediation_followup( model_name: str, remediation_text: str, trace_ids: list[str], - ) -> None: + ) -> bool: self.calls.append( { "type": "remediation", @@ -644,101 +961,136 @@ async def send_remediation_followup( "trace_ids": trace_ids, } ) + return not self.simulate_delivery_failure # --------------------------------------------------------------------------- -# Factory — reads env vars at call time (not module load) so tests can swap +# Factory — reads env vars at call time (not module load) and fails closed # --------------------------------------------------------------------------- -def create_notifier() -> ( - ConsoleNotifier | SlackNotifier | PagerDutyNotifier | WebhookNotifier | MockNotifier +def create_notifier( + env: Mapping[str, str] | None = None, +) -> ( + PubSubNotifier + | ConsoleNotifier + | SlackNotifier + | PagerDutyNotifier + | WebhookNotifier + | MockNotifier ): + """Return the validated notifier for ``ALERT_CHANNEL`` (POAM-2026-230). + + Never falls back silently to :class:`ConsoleNotifier` when a channel is + unknown, lacks its credentials/URL/topic, uses non-HTTPS HTTP, or runs + under an enforcing posture. """ - Returns the appropriate notifier based on ALERT_CHANNEL env var. - - Precedence: - 1. ALERT_CHANNEL=pagerduty → PagerDutyNotifier (requires PAGERDUTY_ROUTING_KEY) - 2. ALERT_CHANNEL=webhook → WebhookNotifier (requires COMPLIANCE_ALERT_WEBHOOK_URL) - 3. ALERT_CHANNEL=slack → SlackNotifier (requires COMPLIANCE_ALERT_WEBHOOK_URL - or SLACK_WEBHOOK_URL) - 4. ALERT_CHANNEL=mock → MockNotifier (requires TESTING=1) - 5. ALERT_CHANNEL=console → ConsoleNotifier ← default - 6. (anything else) → ConsoleNotifier with warning - """ - channel = os.environ.get("ALERT_CHANNEL", "console").lower().strip() + source = os.environ if env is None else env + channel = validate_notifier_config(source) + + if channel == "pubsub": + return PubSubNotifier(source.get("COMPLIANCE_ALERT_PUBSUB_TOPIC", "")) if channel == "pagerduty": - routing_key = os.environ.get("PAGERDUTY_ROUTING_KEY", "") - if not routing_key: - logger.warning( - "[create_notifier] ALERT_CHANNEL=pagerduty but PAGERDUTY_ROUTING_KEY " - "is not set. Falling back to ConsoleNotifier. " - "(Set PAGERDUTY_ROUTING_KEY to enable incident management — POAM-008)" - ) - return ConsoleNotifier() - return PagerDutyNotifier(routing_key) + return PagerDutyNotifier(source.get("PAGERDUTY_ROUTING_KEY", "")) if channel == "webhook": - url = os.environ.get("COMPLIANCE_ALERT_WEBHOOK_URL") or os.environ.get( - "SLACK_WEBHOOK_URL" + url = source.get("COMPLIANCE_ALERT_WEBHOOK_URL") or source.get( + "SLACK_WEBHOOK_URL", "" ) - if not url: - logger.warning( - "[create_notifier] ALERT_CHANNEL=webhook but COMPLIANCE_ALERT_WEBHOOK_URL " - "is not set. Falling back to ConsoleNotifier." - ) - return ConsoleNotifier() return WebhookNotifier(url) if channel == "slack": - url = os.environ.get("COMPLIANCE_ALERT_WEBHOOK_URL") or os.environ.get( - "SLACK_WEBHOOK_URL" + url = source.get("COMPLIANCE_ALERT_WEBHOOK_URL") or source.get( + "SLACK_WEBHOOK_URL", "" ) - if not url: - logger.warning( - "[create_notifier] ALERT_CHANNEL=slack but COMPLIANCE_ALERT_WEBHOOK_URL " - "is not set. Falling back to ConsoleNotifier." - ) - return ConsoleNotifier() return SlackNotifier(url) if channel == "mock": - if not os.environ.get("TESTING"): - raise ValueError( - "MockNotifier is not permitted in production. " - "Set ALERT_CHANNEL to a real channel (slack, pagerduty, webhook, etc.) " - "or set TESTING=1 to enable mock notifications in a test environment." - ) return MockNotifier() - if channel != "console": - logger.warning( - "[create_notifier] Unknown ALERT_CHANNEL=%r. Falling back to ConsoleNotifier.", - channel, - ) - return ConsoleNotifier() # --------------------------------------------------------------------------- -# Module-level convenience functions (called by audit_workflow) +# Module-level convenience functions & synthetic pipeline heartbeat # --------------------------------------------------------------------------- -async def notify_critical_failure(control_id: str, finding: OscalFinding) -> None: +async def notify_critical_failure(control_id: str, finding: OscalFinding) -> bool: """Convenience wrapper: notifies a single critical control failure.""" notifier = create_notifier() - await notifier.send_critical_alert([finding], finding.finding_id) + return (await notifier.send_critical_alert([finding], finding.finding_id)) is True -async def notify_remediation(control_id: str, advice: str) -> None: +async def notify_remediation(control_id: str, advice: str) -> bool: """Convenience wrapper: sends remediation advice notification.""" notifier = create_notifier() - await notifier.send_remediation_followup( - control_id=control_id, - audit_id="", - model_name="", - remediation_text=advice, - trace_ids=[], + return ( + await notifier.send_remediation_followup( + control_id=control_id, + audit_id="", + model_name="", + remediation_text=advice, + trace_ids=[], + ) + ) is True + + +async def send_notifier_heartbeat(audit_id: str | None = None) -> tuple[bool, str]: + """Emit a synthetic non-paging heartbeat through ``send_critical_alert()`` (POAM-2026-230). + + Returns ``(delivered, audit_id)`` where ``delivered`` is ``True`` only when + the configured destination acknowledged receipt. + """ + hb_id = ( + audit_id.strip() + if audit_id and audit_id.strip() + else f"notifier-heartbeat-{uuid.uuid4().hex[:12]}" + ) + finding = OscalFinding( + control_id="CA-7-HEARTBEAT", + result="PASS", + finding_id=hb_id, + assessment_status="heartbeat", + remarks=( + "SYNTHETIC_NOTIFIER_HEARTBEAT — end-to-end compliance-bridge alert " + "pipeline verification probe; no operator action required (POAM-2026-230)." + ), + safety_rate=1.0, + ) + notifier = create_notifier() + delivered = (await notifier.send_critical_alert([finding], hb_id)) is True + return delivered, hb_id + + +def _cli_main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Compliance-bridge notifier verification CLI (POAM-2026-230)." + ) + parser.add_argument( + "--heartbeat", + action="store_true", + required=True, + help="Emit one synthetic heartbeat via create_notifier().send_critical_alert().", + ) + parser.add_argument( + "--audit-id", + default="", + help="Optional deterministic audit_id for destination correlation.", ) + args = parser.parse_args(argv) + + async def _run() -> tuple[bool, str]: + try: + return await send_notifier_heartbeat(args.audit_id or None) + finally: + await close_notifier_http_client() + + delivered, hb_id = asyncio.run(_run()) + print(json.dumps({"delivered": delivered, "audit_id": hb_id})) + return 0 if delivered else 1 + + +if __name__ == "__main__": + sys.exit(_cli_main()) diff --git a/src/compliance_bridge/sla_monitor.py b/src/compliance_bridge/sla_monitor.py index f4518b1de..12c321f0d 100644 --- a/src/compliance_bridge/sla_monitor.py +++ b/src/compliance_bridge/sla_monitor.py @@ -64,12 +64,17 @@ get_compliance_metrics, get_last_healthy_lula_audit_age_seconds, ) -from .notifier import create_notifier +from .notifier import ( + create_notifier, + is_external_notifier_configured, + send_notifier_heartbeat, +) from .types import OscalFinding, get_sla_seconds logger = logging.getLogger(__name__) _DEFAULT_POLL_INTERVAL = 300 # 5 minutes +_DEFAULT_HEARTBEAT_INTERVAL = 21600 # 6 hours (POAM-2026-230 synthetic notifier probe) _DEFAULT_LULA_AUDIT_MAX_AGE_SECONDS = ( 43200 # 2 x 6h default CronJob/lula-audit schedule ("0 */6 * * *") ) @@ -124,6 +129,13 @@ def _poll_interval() -> int: ) +def _heartbeat_interval() -> int: + raw = os.environ.get( + "ALERT_HEARTBEAT_INTERVAL_SECONDS", str(_DEFAULT_HEARTBEAT_INTERVAL) + ) + return max(0, int(raw.strip() or "0")) + + def _active_sla_seconds() -> dict[str, int]: """Return the SLA thresholds applicable to the active deployment region. @@ -222,7 +234,11 @@ async def _check_lula_audit_deadman( audit_id = f"lula-audit-deadman-{now_ts}" try: notifier = create_notifier() - await notifier.send_critical_alert([finding], audit_id) + delivered = (await notifier.send_critical_alert([finding], audit_id)) is True + if not delivered: + logger.error( + "[sla_monitor] Dead-man alert NOT delivered externally (%s)", audit_id + ) except Exception as exc: logger.error( "[sla_monitor] Failed to send lula-audit-deadman critical alert: %s", exc @@ -236,13 +252,20 @@ async def _dispatch_sla_error_alerts( findings: list[OscalFinding], audit_id: str, label: str, -) -> None: - """Dispatch a consolidated critical alert batch, logging transport failures.""" +) -> bool: + """Dispatch a consolidated critical alert batch, returning observed delivery.""" if not findings: - return + return False try: notifier = create_notifier() - await notifier.send_critical_alert(findings, audit_id) + delivered = (await notifier.send_critical_alert(findings, audit_id)) is True + if not delivered: + logger.error( + "[sla_monitor] %s critical alert NOT delivered externally (%s)", + label, + audit_id, + ) + return delivered except Exception as exc: logger.error( "[sla_monitor] Failed to send %s critical alert (%s): %s", @@ -250,6 +273,7 @@ async def _dispatch_sla_error_alerts( audit_id, exc, ) + return False async def _check_sla_once() -> list[str]: @@ -410,15 +434,46 @@ async def _fire_sla_alerts(breached: list[str]) -> None: audit_id = f"sla-monitor-{now_ts}" try: - await notifier.send_critical_alert(findings, audit_id) - logger.warning( - "[sla_monitor] 🚨 SLA breach alert sent for: %s", - ", ".join(breached), - ) + delivered = (await notifier.send_critical_alert(findings, audit_id)) is True + if delivered: + logger.warning( + "[sla_monitor] 🚨 SLA breach alert delivered for: %s", + ", ".join(breached), + ) + else: + logger.error( + "[sla_monitor] SLA breach alert NOT delivered externally for: %s", + ", ".join(breached), + ) except Exception as exc: logger.error("[sla_monitor] Failed to send SLA breach alert: %s", exc) +async def _maybe_emit_notifier_heartbeat( + last_hb_monotonic: float | None, +) -> float | None: + """Emit a synthetic non-paging notifier heartbeat when the interval elapses.""" + hb_interval = _heartbeat_interval() + if hb_interval <= 0 or not is_external_notifier_configured(): + return last_hb_monotonic + now_mono = asyncio.get_running_loop().time() + if last_hb_monotonic is not None and (now_mono - last_hb_monotonic) < hb_interval: + return last_hb_monotonic + try: + delivered, hb_id = await send_notifier_heartbeat() + if delivered: + logger.info( + "[sla_monitor] Synthetic notifier heartbeat delivered (%s)", hb_id + ) + return now_mono + logger.error( + "[sla_monitor] Synthetic notifier heartbeat NOT delivered (%s)", hb_id + ) + except Exception as exc: + logger.error("[sla_monitor] Synthetic notifier heartbeat failed: %s", exc) + return last_hb_monotonic + + async def run_sla_monitor() -> None: """ Continuous SLA monitoring loop — runs until the task is cancelled. @@ -445,10 +500,15 @@ async def run_sla_monitor() -> None: ", ".join(_active_sla_seconds().keys()), ) + last_hb_monotonic: float | None = None try: + last_hb_monotonic = await _maybe_emit_notifier_heartbeat(last_hb_monotonic) while True: await asyncio.sleep(poll_interval) try: + last_hb_monotonic = await _maybe_emit_notifier_heartbeat( + last_hb_monotonic + ) sla_keys = set(_active_sla_seconds().keys()) breached = await _check_sla_once() if "A.5.3" not in sla_keys: diff --git a/tests/infrastructure/test_clickhouse_operator.py b/tests/infrastructure/test_clickhouse_operator.py index 402fbdc09..39dc8bc4b 100644 --- a/tests/infrastructure/test_clickhouse_operator.py +++ b/tests/infrastructure/test_clickhouse_operator.py @@ -200,9 +200,13 @@ def test_compliance_bridge_wired_to_worm_bucket_and_object_creator_iam() -> None gke_main = _GKE_MAIN.read_text() cb_block = _extract_module_block("compliance_bridge", gke_main) - assert "oscal_s3_bucket = module.worm_bucket.bucket_name" in cb_block - assert 'evidence_cold_store = "gcs"' in cb_block - assert "evidence_cold_store_bucket = module.worm_bucket.bucket_name" in cb_block + assert re.search( + r"oscal_s3_bucket\s*=\s*module\.worm_bucket\.bucket_name", cb_block + ) + assert re.search(r'evidence_cold_store\s*=\s*"gcs"', cb_block) + assert re.search( + r"evidence_cold_store_bucket\s*=\s*module\.worm_bucket\.bucket_name", cb_block + ) assert "clickhouse" not in cb_block.lower() cb_module_main = _COMPLIANCE_BRIDGE_MAIN.read_text() diff --git a/tests/infrastructure/test_wif_deployer_isolation.py b/tests/infrastructure/test_wif_deployer_isolation.py index 2090dc452..1e673bcaf 100644 --- a/tests/infrastructure/test_wif_deployer_isolation.py +++ b/tests/infrastructure/test_wif_deployer_isolation.py @@ -150,3 +150,41 @@ def test_partner_harness_kms_key_defaults_empty_for_clean_projects() -> None: 'var.partner_harness_kms_keyring != "" && var.partner_harness_kms_key != ""' in wif_text ) + + +def test_alert_verifier_isolation_and_least_privilege_grants() -> None: + text = WIF_TF.read_text(encoding="utf-8") + verifier_sa = _extract_resource_block( + text, "google_service_account", "alert_verifier" + ) + assert 'account_id = "cage-alert-verifier"' in verifier_sa + + for binding_name in ( + "alert_verifier_workload_identity", + "alert_verifier_token_creator", + ): + block = _extract_resource_block( + text, "google_service_account_iam_binding", binding_name + ) + assert "attribute.ref/${var.github_deployer_ref}" in block + assert "attribute.repository/" not in block + assert "-compute@developer.gserviceaccount.com" not in block + + mon_viewer = _extract_resource_block( + text, "google_project_iam_member", "alert_verifier_monitoring_viewer" + ) + assert 'role = "roles/monitoring.viewer"' in mon_viewer + mon_writer = _extract_resource_block( + text, "google_project_iam_member", "alert_verifier_metric_writer" + ) + assert 'role = "roles/monitoring.metricWriter"' in mon_writer + + for sub_binding in ("alert_verifier_subscriber", "alert_verifier_viewer"): + block = _extract_resource_block( + text, "google_pubsub_subscription_iam_member", sub_binding + ) + assert 'trimspace(var.alert_verify_pubsub_subscription) != ""' in block + assert ( + 'member = "serviceAccount:${google_service_account.alert_verifier.email}"' + in block + ) diff --git a/tests/test_audit_workflow.py b/tests/test_audit_workflow.py index 4fb98120a..2ee579651 100644 --- a/tests/test_audit_workflow.py +++ b/tests/test_audit_workflow.py @@ -228,7 +228,7 @@ async def test_alert_sent_on_critical_fail(self): findings = [self._make_finding(critical_control, "FAIL")] mock_notifier = MagicMock() - mock_notifier.send_critical_alert = AsyncMock() + mock_notifier.send_critical_alert = AsyncMock(return_value=True) with patch( "src.compliance_bridge.audit_workflow.create_notifier", @@ -252,7 +252,7 @@ async def test_alert_sent_on_critical_error(self): findings = [self._make_finding(critical_control, "ERROR")] mock_notifier = MagicMock() - mock_notifier.send_critical_alert = AsyncMock() + mock_notifier.send_critical_alert = AsyncMock(return_value=True) with patch( "src.compliance_bridge.audit_workflow.create_notifier", @@ -264,6 +264,27 @@ async def test_alert_sent_on_critical_error(self): assert alerted is True + @pytest.mark.asyncio + async def test_alert_false_when_notifier_does_not_confirm_delivery(self): + """POAM-2026-230: alerted must be False when ConsoleNotifier or failed HTTP transport returns False.""" + from src.compliance_bridge.audit_workflow import _step4_alert_on_critical_fail + from src.compliance_bridge.notifier import ConsoleNotifier + from src.compliance_bridge.types import CRITICAL_CONTROLS + + critical_control = next(iter(CRITICAL_CONTROLS)) + findings = [self._make_finding(critical_control, "FAIL")] + + with patch( + "src.compliance_bridge.audit_workflow.create_notifier", + return_value=ConsoleNotifier(), + ): + alerted, targets = await _step4_alert_on_critical_fail( + findings, "audit-console-001" + ) + + assert alerted is False + assert critical_control in targets + @pytest.mark.asyncio async def test_no_alert_for_non_critical_fail(self): """No alert is sent for a FAIL on a non-critical control.""" @@ -273,7 +294,7 @@ async def test_no_alert_for_non_critical_fail(self): findings = [self._make_finding("NON_CRITICAL_CONTROL_XYZ", "FAIL")] mock_notifier = MagicMock() - mock_notifier.send_critical_alert = AsyncMock() + mock_notifier.send_critical_alert = AsyncMock(return_value=True) with patch( "src.compliance_bridge.audit_workflow.create_notifier", diff --git a/tests/test_ci_gate_effectiveness.py b/tests/test_ci_gate_effectiveness.py index 57f7bb905..107a4369e 100644 --- a/tests/test_ci_gate_effectiveness.py +++ b/tests/test_ci_gate_effectiveness.py @@ -73,7 +73,7 @@ GITLEAKS_TOML_PATH = REPO_ROOT / ".gitleaks.toml" STAGING_LIFECYCLE_PATH = REPO_ROOT / "scripts" / "staging_lifecycle.sh" -# Complete classification of all 21 workflows in .github/workflows/ +# Complete classification of all 22 workflows in .github/workflows/ NON_GATE_WORKFLOWS: frozenset[str] = frozenset( { "publish-client-sdk.yml", # Tag/manual release workflow building & pushing cage-client wheel/GHCR package @@ -82,6 +82,10 @@ GATE_WORKFLOWS: frozenset[str] = frozenset( { + # Scheduled independent Cloud Monitoring & notifier Pub/Sub delivery + # verification (POAM-2026-230 Property 4); planted-defect tests in + # tests/unit/test_verify_alert_delivery.py. + "alert-delivery-check.yml", "apac-mas-compliance.yml", "ci-integration.yml", "ci-partner-integration.yml", @@ -159,7 +163,7 @@ def test_workflow_inventory_is_complete_and_classified() -> None: "Register new workflows in GATE_WORKFLOWS and add adversarial gate tests." ) assert not missing, f"Classified workflow(s) missing from disk: {missing}" - assert len(on_disk) == 21, f"Expected 21 workflows, found {len(on_disk)}" + assert len(on_disk) == 22, f"Expected 22 workflows, found {len(on_disk)}" # Verify publish-client-sdk.yml is genuinely a release workflow, not a disguised test gate pub_data = yaml.safe_load( diff --git a/tests/test_compliance_bridge.py b/tests/test_compliance_bridge.py index cafd18855..42d6b4f07 100644 --- a/tests/test_compliance_bridge.py +++ b/tests/test_compliance_bridge.py @@ -378,11 +378,13 @@ class TestAuditIngestAuth: "CAGE_INTERNAL_TOKEN": "secret-token", "CAGE_ENV": "staging", "CAGE_TRUSTED_OPERATOR_IDENTITIES": "operator:auditor@example.org", - # Synthetic, non-secret values satisfying the POAM-018 lifespan pre-flight. + # Synthetic, non-secret values satisfying the POAM-018 & POAM-2026-230 lifespan pre-flights. "LANGFUSE_COMPLIANCE_PUBLIC_KEY": "synthetic-compliance-public", "LANGFUSE_COMPLIANCE_SECRET_KEY": "synthetic-compliance-secret", "LANGFUSE_PUBLIC_KEY": "synthetic-app-public", "LANGFUSE_SECRET_KEY": "synthetic-app-secret", + "ALERT_CHANNEL": "pubsub", + "COMPLIANCE_ALERT_PUBSUB_TOPIC": "projects/cage-test-01/topics/cage-alerts", } @pytest.fixture(autouse=True) diff --git a/tests/test_compliance_bridge_lifespan_posture.py b/tests/test_compliance_bridge_lifespan_posture.py index 65897e86b..73ae943b4 100644 --- a/tests/test_compliance_bridge_lifespan_posture.py +++ b/tests/test_compliance_bridge_lifespan_posture.py @@ -163,6 +163,15 @@ def _set_startup_env( monkeypatch.setenv( "CAGE_TRUSTED_OPERATOR_IDENTITIES", "operator:auditor@example.org" ) + if credentials: + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-alerts", + ) + else: + monkeypatch.delenv("ALERT_CHANNEL", raising=False) + monkeypatch.delenv("COMPLIANCE_ALERT_PUBSUB_TOPIC", raising=False) for var in LANGFUSE_CREDENTIAL_ENV_VARS: if credentials: monkeypatch.setenv(var, f"synthetic-{var.lower()}") @@ -197,6 +206,7 @@ def test_lifespan_starts_in_staging_with_credentials_and_health_reports_them( assert body["langfuse_compliance_configured"] is True assert body["langfuse_app_configured"] is True + assert body["alert_channel_configured"] is True assert body["environment"] == "staging" @@ -215,4 +225,5 @@ def test_lifespan_starts_in_dev_without_credentials_and_health_reports_absence( assert body["langfuse_compliance_configured"] is False assert body["langfuse_app_configured"] is False + assert body["alert_channel_configured"] is False assert any("[POAM-018]" in rec.getMessage() for rec in caplog.records) diff --git a/tests/test_compliance_bridge_tier2b.py b/tests/test_compliance_bridge_tier2b.py index 3c334afc5..29e710a02 100644 --- a/tests/test_compliance_bridge_tier2b.py +++ b/tests/test_compliance_bridge_tier2b.py @@ -517,12 +517,11 @@ def _capture(request: httpx.Request, **kwargs): class TestNotifierFactory: - def test_default_is_console(self): + def test_default_in_dev_is_console(self): from src.compliance_bridge.notifier import ConsoleNotifier, create_notifier - with patch.dict(os.environ, {}, clear=False): - if "ALERT_CHANNEL" in os.environ: - del os.environ["ALERT_CHANNEL"] + with patch.dict(os.environ, {"CAGE_ENV": "dev"}, clear=False): + os.environ.pop("ALERT_CHANNEL", None) n = create_notifier() assert isinstance(n, ConsoleNotifier) @@ -536,15 +535,27 @@ def test_pagerduty_with_key_returns_pagerduty(self): n = create_notifier() assert isinstance(n, PagerDutyNotifier) - def test_pagerduty_without_key_falls_back_to_console(self): - from src.compliance_bridge.notifier import ConsoleNotifier, create_notifier + def test_pagerduty_without_key_raises_fail_closed(self): + from src.compliance_bridge.notifier import NotifierConfigError, create_notifier env = {"ALERT_CHANNEL": "pagerduty"} - # Ensure routing key is absent with patch.dict(os.environ, env): os.environ.pop("PAGERDUTY_ROUTING_KEY", None) + with pytest.raises(NotifierConfigError, match="PAGERDUTY_ROUTING_KEY"): + create_notifier() + + def test_pubsub_with_topic_returns_pubsub_notifier(self): + from src.compliance_bridge.notifier import PubSubNotifier, create_notifier + + with patch.dict( + os.environ, + { + "ALERT_CHANNEL": "pubsub", + "COMPLIANCE_ALERT_PUBSUB_TOPIC": "projects/cage-test-01/topics/cage-alerts", + }, + ): n = create_notifier() - assert isinstance(n, ConsoleNotifier) + assert isinstance(n, PubSubNotifier) def test_webhook_with_url_returns_webhook(self): from src.compliance_bridge.notifier import WebhookNotifier, create_notifier @@ -573,18 +584,19 @@ def test_slack_with_url_returns_slack(self): assert isinstance(n, SlackNotifier) def test_mock_requires_testing_env(self): - from src.compliance_bridge.notifier import create_notifier - - with patch.dict(os.environ, {"ALERT_CHANNEL": "mock", "TESTING": "1"}): - from src.compliance_bridge.notifier import MockNotifier + from src.compliance_bridge.notifier import MockNotifier, create_notifier + with patch.dict( + os.environ, + {"ALERT_CHANNEL": "mock", "TESTING": "1", "CAGE_ENV": "dev"}, + ): n = create_notifier() assert isinstance(n, MockNotifier) def test_mock_without_testing_raises(self): from src.compliance_bridge.notifier import create_notifier - env = {"ALERT_CHANNEL": "mock"} + env = {"ALERT_CHANNEL": "mock", "CAGE_ENV": "dev"} with patch.dict(os.environ, env): os.environ.pop("TESTING", None) with pytest.raises(ValueError, match="MockNotifier is not permitted"): @@ -596,15 +608,15 @@ def test_mock_notifier_alert_count(self): from src.compliance_bridge.notifier import MockNotifier n = MockNotifier() - # Use asyncio.run() for Python 3.12 compatibility (get_event_loop deprecated) - asyncio.run( + delivered = asyncio.run( n.send_critical_alert([_make_finding("A.9.2", "FAIL")], "count-test") ) + assert delivered is True assert n.alert_count == 1 - def test_unknown_channel_falls_back_to_console(self): - from src.compliance_bridge.notifier import ConsoleNotifier, create_notifier + def test_unknown_channel_raises_fail_closed(self): + from src.compliance_bridge.notifier import NotifierConfigError, create_notifier with patch.dict(os.environ, {"ALERT_CHANNEL": "telegram"}): - n = create_notifier() - assert isinstance(n, ConsoleNotifier) + with pytest.raises(NotifierConfigError, match="Unknown ALERT_CHANNEL"): + create_notifier() diff --git a/tests/test_evidence_verifier.py b/tests/test_evidence_verifier.py index a297458cc..49a755006 100644 --- a/tests/test_evidence_verifier.py +++ b/tests/test_evidence_verifier.py @@ -1257,7 +1257,12 @@ def test_lifespan_enforcing_fails_closed_when_verifier_unconfigured( monkeypatch.setenv("CAGE_ENV", "staging") monkeypatch.setenv("EVIDENCE_STREAM_ENABLED", "true") - # Synthetic, non-secret values satisfying the POAM-018 lifespan pre-flight. + # Synthetic, non-secret values satisfying the POAM-018 & POAM-2026-230 lifespan pre-flights. + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-alerts", + ) for var in LANGFUSE_CREDENTIAL_ENV_VARS: monkeypatch.setenv(var, f"synthetic-{var.lower()}") monkeypatch.setattr( diff --git a/tests/test_infra_events_custody.py b/tests/test_infra_events_custody.py index 579dff7ab..163498e11 100644 --- a/tests/test_infra_events_custody.py +++ b/tests/test_infra_events_custody.py @@ -1485,7 +1485,12 @@ async def test_enforcing_posture_defaults_inline_flush_true_and_fails_closed_503 monkeypatch.setenv( "CAGE_TRUSTED_OPERATOR_IDENTITIES", "operator:auditor@example.org" ) - # Synthetic, non-secret values satisfying the POAM-018 lifespan pre-flight. + # Synthetic, non-secret values satisfying the POAM-018 & POAM-2026-230 lifespan pre-flights. + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-alerts", + ) for var in LANGFUSE_CREDENTIAL_ENV_VARS: monkeypatch.setenv(var, f"synthetic-{var.lower()}") monkeypatch.delenv(INFRA_INLINE_FLUSH_ENV, raising=False) diff --git a/tests/unit/test_ci_workflow_dependency_sync.py b/tests/unit/test_ci_workflow_dependency_sync.py index 878b05729..d26ef020d 100644 --- a/tests/unit/test_ci_workflow_dependency_sync.py +++ b/tests/unit/test_ci_workflow_dependency_sync.py @@ -54,9 +54,10 @@ "check_locked_yanks.py", "check_repo_rules.py", "partner_harness.py", - # Runs in jobs that can mint a signing identity, which therefore - # install nothing (POAM-2026-115). + # Runs in jobs that can mint a signing or GCP WIF identity, which + # therefore install nothing (POAM-2026-115 / POAM-2026-230). "review_bypass_attestation.py", + "verify_alert_delivery.py", } ) diff --git a/tests/unit/test_compliance_notifier_routing.py b/tests/unit/test_compliance_notifier_routing.py new file mode 100644 index 000000000..8b43e46c8 --- /dev/null +++ b/tests/unit/test_compliance_notifier_routing.py @@ -0,0 +1,322 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for POAM-2026-230 compliance-bridge notifier validity & observed delivery.""" + +from __future__ import annotations + +import base64 +import json +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest + +from src.compliance_bridge.notifier import ( + ConsoleNotifier, + MockNotifier, + NotifierConfigError, + PubSubNotifier, + create_notifier, + is_external_notifier_configured, + send_notifier_heartbeat, + validate_notifier_config, +) +from src.compliance_bridge.sla_monitor import _maybe_emit_notifier_heartbeat +from src.compliance_bridge.types import OscalFinding + +pytestmark = [pytest.mark.unit, pytest.mark.local] + + +def _finding(control_id: str = "CA-7", result: str = "FAIL") -> OscalFinding: + return OscalFinding( + control_id=control_id, + result=result, + finding_id=f"finding-{control_id.lower()}", + evidence_age_s=12.5, + ) + + +class TestNotifierStartupValidation: + """Property 1b: Enforcing postures fail closed on unset, console, mock, or incomplete config.""" + + @pytest.mark.parametrize("posture", ["staging", "prod", "production"]) + @pytest.mark.parametrize("bad_channel", ["", "console", "mock", "unknown-sink"]) + def test_enforcing_posture_refuses_non_external_or_unknown_channels( + self, monkeypatch: pytest.MonkeyPatch, posture: str, bad_channel: str + ) -> None: + monkeypatch.setenv("CAGE_ENV", posture) + monkeypatch.setenv("TESTING", "1") + if bad_channel: + monkeypatch.setenv("ALERT_CHANNEL", bad_channel) + else: + monkeypatch.delenv("ALERT_CHANNEL", raising=False) + + with pytest.raises(NotifierConfigError): + validate_notifier_config() + + with pytest.raises(NotifierConfigError): + create_notifier() + + def test_enforcing_pubsub_requires_well_formed_topic( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("CAGE_ENV", "staging") + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.delenv("COMPLIANCE_ALERT_PUBSUB_TOPIC", raising=False) + with pytest.raises(NotifierConfigError, match="COMPLIANCE_ALERT_PUBSUB_TOPIC"): + validate_notifier_config() + + monkeypatch.setenv("COMPLIANCE_ALERT_PUBSUB_TOPIC", "cage-staging-alerts") + with pytest.raises( + NotifierConfigError, match="projects//topics/" + ): + validate_notifier_config() + + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-staging-alerts", + ) + assert validate_notifier_config() == "pubsub" + assert is_external_notifier_configured() is True + + @pytest.mark.parametrize("channel", ["slack", "webhook"]) + def test_webhook_and_slack_require_https_url( + self, monkeypatch: pytest.MonkeyPatch, channel: str + ) -> None: + monkeypatch.setenv("CAGE_ENV", "staging") + monkeypatch.setenv("ALERT_CHANNEL", channel) + monkeypatch.setenv( + "COMPLIANCE_ALERT_WEBHOOK_URL", "http://insecure.example.org/hook" + ) + with pytest.raises(NotifierConfigError, match="https://"): + validate_notifier_config() + + monkeypatch.setenv( + "COMPLIANCE_ALERT_WEBHOOK_URL", "https://hooks.example.org/alert" + ) + assert validate_notifier_config() == channel + + def test_dev_posture_allows_console_and_reports_external_unconfigured( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("CAGE_ENV", "dev") + monkeypatch.delenv("ALERT_CHANNEL", raising=False) + assert validate_notifier_config() == "console" + assert is_external_notifier_configured() is False + notifier = create_notifier() + assert isinstance(notifier, ConsoleNotifier) + + +class TestPubSubAndObservedDelivery: + """Property 2 & Remediation #6: Observed destination ack governs boolean return.""" + + @pytest.mark.asyncio + async def test_console_notifier_always_returns_false(self) -> None: + notifier = ConsoleNotifier() + assert await notifier.send_critical_alert([_finding()], "audit-1") is False + assert ( + await notifier.send_remediation_followup( + control_id="CA-7", + audit_id="audit-1", + model_name="none", + remediation_text="fix", + trace_ids=["tr-1"], + ) + is False + ) + + @pytest.mark.asyncio + async def test_pubsub_notifier_publishes_envelope_and_verifies_message_ids( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("CAGE_ENV", "staging") + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-staging-alerts", + ) + captured: list[dict[str, Any]] = [] + + def _handler(request: httpx.Request) -> httpx.Response: + captured.append( + { + "url": str(request.url), + "auth": request.headers.get("Authorization"), + "body": json.loads(request.content.decode("utf-8")), + } + ) + return httpx.Response(200, json={"messageIds": ["9876543210"]}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(_handler)) as client: + with ( + patch( + "src.compliance_bridge.notifier._fetch_pubsub_access_token_sync", + return_value="ya29.fake-test-token", + ), + patch( + "src.compliance_bridge.notifier._get_notifier_http_client", + new=AsyncMock(return_value=client), + ), + ): + notifier = PubSubNotifier( + topic="projects/cage-test-01/topics/cage-staging-alerts" + ) + ok = await notifier.send_critical_alert( + [_finding("AU-12", "FAIL")], "a-42" + ) + hb_ok, hb_id = await send_notifier_heartbeat("hb-test-01") + + assert ok is True + assert hb_ok is True + assert hb_id == "hb-test-01" + assert len(captured) == 2 + assert ( + captured[0]["url"] + == "https://pubsub.googleapis.com/v1/projects/cage-test-01/topics/cage-staging-alerts:publish" + ) + assert captured[0]["auth"] == "Bearer ya29.fake-test-token" + assert captured[0]["body"]["messages"][0]["attributes"]["alert_type"] == ( + "critical_failure" + ) + + hb_msg = captured[1]["body"]["messages"][0] + assert hb_msg["attributes"]["source"] == "compliance-bridge" + assert hb_msg["attributes"]["alert_type"] == "heartbeat" + decoded = json.loads(base64.b64decode(hb_msg["data"]).decode("utf-8")) + assert decoded["source"] == "compliance-bridge" + assert decoded["alert_type"] == "heartbeat" + + @pytest.mark.asyncio + async def test_pubsub_notifier_returns_false_on_empty_message_ids_or_http_error( + self, + ) -> None: + notifier = PubSubNotifier( + topic="projects/cage-test-01/topics/cage-staging-alerts" + ) + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda _req: httpx.Response(200, json={"messageIds": []}) + ) + ) as empty_client: + with ( + patch( + "src.compliance_bridge.notifier._fetch_pubsub_access_token_sync", + return_value="ya29.fake-test-token", + ), + patch( + "src.compliance_bridge.notifier._get_notifier_http_client", + new=AsyncMock(return_value=empty_client), + ), + ): + assert ( + await notifier.send_critical_alert([_finding()], "a-empty") is False + ) + + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda _req: httpx.Response(403, json={"error": "permission_denied"}) + ) + ) as err_client: + with ( + patch( + "src.compliance_bridge.notifier._fetch_pubsub_access_token_sync", + return_value="ya29.fake-test-token", + ), + patch( + "src.compliance_bridge.notifier._get_notifier_http_client", + new=AsyncMock(return_value=err_client), + ), + ): + assert ( + await notifier.send_critical_alert([_finding()], "a-403") is False + ) + + @pytest.mark.asyncio + async def test_mock_notifier_simulated_failure_propagates_false(self) -> None: + failing_mock = MockNotifier(simulate_delivery_failure=True) + assert await failing_mock.send_critical_alert([_finding()], "a-fail") is False + assert failing_mock.alert_count == 1 + + @pytest.mark.asyncio + async def test_sla_heartbeat_cadence_and_retry_on_failed_delivery( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("CAGE_ENV", "staging") + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-staging-alerts", + ) + monkeypatch.setenv("ALERT_HEARTBEAT_INTERVAL_SECONDS", "3600") + + mock_loop = MagicMock() + mock_loop.time.return_value = 1000.0 + + with ( + patch( + "src.compliance_bridge.sla_monitor.asyncio.get_running_loop", + return_value=mock_loop, + ), + patch( + "src.compliance_bridge.sla_monitor.send_notifier_heartbeat", + new=AsyncMock(return_value=(False, "hb-fail")), + ), + ): + # Failed delivery must preserve None so next tick retries immediately. + assert await _maybe_emit_notifier_heartbeat(None) is None + + hb_ok_mock = AsyncMock(return_value=(True, "hb-ok")) + with ( + patch( + "src.compliance_bridge.sla_monitor.asyncio.get_running_loop", + return_value=mock_loop, + ), + patch( + "src.compliance_bridge.sla_monitor.send_notifier_heartbeat", + new=hb_ok_mock, + ), + ): + mock_loop.time.return_value = 1060.0 + updated = await _maybe_emit_notifier_heartbeat(None) + assert updated == 1060.0 + assert hb_ok_mock.await_count == 1 + + # Within 3600s interval -> suppressed. + mock_loop.time.return_value = 2000.0 + assert await _maybe_emit_notifier_heartbeat(updated) == 1060.0 + assert hb_ok_mock.await_count == 1 + + # Past 3600s interval -> next heartbeat emitted. + mock_loop.time.return_value = 4700.0 + assert await _maybe_emit_notifier_heartbeat(updated) == 4700.0 + assert hb_ok_mock.await_count == 2 + + @pytest.mark.asyncio + async def test_lifespan_fails_closed_in_staging_when_notifier_is_console( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + from src.compliance_bridge.main import app, lifespan + + monkeypatch.setenv("CAGE_ENV", "staging") + monkeypatch.setenv("ALERT_CHANNEL", "console") + + with patch( + "src.compliance_bridge.main.validate_langfuse_credentials", + return_value=MagicMock(), + ): + with pytest.raises(NotifierConfigError, match="POAM-2026-230"): + async with lifespan(app): + pass diff --git a/tests/unit/test_gateway_refusal_ratio_metrics.py b/tests/unit/test_gateway_refusal_ratio_metrics.py index d2ba663b4..bde33f99c 100644 --- a/tests/unit/test_gateway_refusal_ratio_metrics.py +++ b/tests/unit/test_gateway_refusal_ratio_metrics.py @@ -28,8 +28,9 @@ carrying in-band governance refusals (``refusal_decided``, ``policy-precheck`` ``DENY``, ``verify_content_safety`` ``BLOCKED``, ``evaluate_policy`` ``DENIED``) as ``blocked``. 4. ``infra/targets/gcp-gke/metrics_alerting.tf`` provisions - ``google_monitoring_alert_policy.gateway_sustained_refusal_ratio`` paging - ``var.lula_alert_owner`` when blocked-over-total over ``[5m]`` meets ``>= 0.95`` with a + ``google_monitoring_alert_policy.gateway_sustained_refusal_ratio`` bound to + ``var.alert_notification_channels`` (labeled ``var.alert_owner_label``) when + blocked-over-total over ``[5m]`` meets ``>= 0.95`` with a minimum volume floor (``>= 5``) sustained for ``180s``. """ diff --git a/tests/unit/test_posture_guard_integrity.py b/tests/unit/test_posture_guard_integrity.py index 0e4c7500c..2bf8bda0b 100644 --- a/tests/unit/test_posture_guard_integrity.py +++ b/tests/unit/test_posture_guard_integrity.py @@ -371,6 +371,11 @@ async def test_compliance_bridge_lifespan_invokes_kms_guard_in_all_enforcing_pos monkeypatch.setenv("CAGE_ENV", cage_env) monkeypatch.setenv("EVIDENCE_STREAM_ENABLED", "true") + monkeypatch.setenv("ALERT_CHANNEL", "pubsub") + monkeypatch.setenv( + "COMPLIANCE_ALERT_PUBSUB_TOPIC", + "projects/cage-test-01/topics/cage-alerts", + ) for var in LANGFUSE_CREDENTIAL_ENV_VARS: monkeypatch.setenv(var, f"synthetic-{var.lower()}") diff --git a/tests/unit/test_verify_alert_delivery.py b/tests/unit/test_verify_alert_delivery.py new file mode 100644 index 000000000..010b39228 --- /dev/null +++ b/tests/unit/test_verify_alert_delivery.py @@ -0,0 +1,307 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for scripts/verify_alert_delivery.py (POAM-2026-230 Properties 2-4).""" + +from __future__ import annotations + +import base64 +import json +from datetime import datetime, timezone +from typing import Any +from unittest.mock import patch + +import pytest + +from scripts import verify_alert_delivery as verifier +from scripts.verify_alert_delivery import AlertVerificationError + +pytestmark = [pytest.mark.unit, pytest.mark.local] + +CHANNEL_ID = "projects/cage-test-01/notificationChannels/12345" +SUB_PATH = "projects/cage-test-01/subscriptions/cage-staging-alerts-verify" + + +def _make_policies( + count: int = 9, include_heartbeat: bool = True +) -> list[dict[str, Any]]: + policies: list[dict[str, Any]] = [] + for idx in range(count): + is_hb = include_heartbeat and idx == count - 1 + policies.append( + { + "name": f"projects/cage-test-01/alertPolicies/{idx}", + "displayName": ( + "cage-staging - Alert Pipeline Synthetic Heartbeat (No Action Required)" + if is_hb + else f"cage-staging - Policy {idx}" + ), + "enabled": True, + "notificationChannels": [CHANNEL_ID], + "userLabels": ( + {"alert_kind": "heartbeat", "owner": "secops"} + if is_hb + else {"owner": "secops"} + ), + } + ) + return policies + + +def _b64_json(obj: dict[str, Any]) -> str: + return base64.b64encode(json.dumps(obj).encode("utf-8")).decode("ascii") + + +class TestRuntimePolicyVerification: + def test_valid_policies_and_enabled_channel_pass(self) -> None: + def _fake_http( + method: str, + url: str, + _token: str, + payload: Any = None, + timeout: float = 30.0, + ) -> dict[str, Any]: + assert method == "GET" + if "/alertPolicies" in url: + return {"alertPolicies": _make_policies(9, include_heartbeat=True)} + if url.endswith(CHANNEL_ID): + return { + "name": CHANNEL_ID, + "displayName": "cage-staging-alerts-pubsub", + "type": "pubsub", + "enabled": True, + } + raise AssertionError(f"Unexpected URL {url}") + + with patch.object(verifier, "_http_json", side_effect=_fake_http): + report = verifier.verify_runtime_alert_policies( + project="cage-test-01", + cluster_name="cage-staging", + token="tok", + min_policies=9, + expected_channels=[CHANNEL_ID], + ) + assert report["policy_count"] == 9 + assert report["channels"][0]["enabled"] is True + + def test_channel_set_drift_or_disabled_channel_fails_closed(self) -> None: + drifted = _make_policies(9) + drifted[0]["notificationChannels"] = [ + "projects/cage-test-01/notificationChannels/99999" + ] + with patch.object( + verifier, + "_http_json", + return_value={"alertPolicies": drifted}, + ): + with pytest.raises(AlertVerificationError, match="Channel-set drift"): + verifier.verify_runtime_alert_policies( + project="cage-test-01", + cluster_name="cage-staging", + token="tok", + ) + + # Disabled channel at runtime must also fail closed. + def _disabled_ch( + method: str, url: str, _tok: str, **_kw: Any + ) -> dict[str, Any]: + if "/alertPolicies" in url: + return {"alertPolicies": _make_policies(9)} + return {"name": CHANNEL_ID, "displayName": "ch", "enabled": False} + + with patch.object(verifier, "_http_json", side_effect=_disabled_ch): + with pytest.raises(AlertVerificationError, match="enabled=False"): + verifier.verify_runtime_alert_policies( + project="cage-test-01", + cluster_name="cage-staging", + token="tok", + ) + + +class TestNonDestructiveSubscriptionInspection: + def test_preserves_operational_alerts_and_keeps_newest_periodic_bridge_heartbeat( + self, + ) -> None: + now_epoch = 1_800_000_000.0 + now_iso = datetime.fromtimestamp(now_epoch, tz=timezone.utc).isoformat() + older_iso = datetime.fromtimestamp( + now_epoch - 3600.0, tz=timezone.utc + ).isoformat() + + messages = [ + # 1. Real operational Cloud Monitoring incident -> MUST BE NACKED (preserved) + { + "ackId": "ack-real-mon", + "message": { + "publishTime": now_iso, + "data": _b64_json( + { + "incident": { + "incident_id": "inc-real-1", + "policy_name": "cage-staging - Lula Compliance Audit Failure", + "policy_user_labels": {"owner": "secops"}, + "state": "open", + "started_at": int(now_epoch), + } + } + ), + }, + }, + # 2. Real operational compliance_bridge critical alert -> MUST BE NACKED (preserved) + { + "ackId": "ack-real-bridge", + "message": { + "publishTime": now_iso, + "data": _b64_json( + { + "source": "compliance_bridge", + "alert_type": "critical_findings", + "severity": "critical", + } + ), + }, + }, + # 3. Synthetic Cloud Monitoring heartbeat -> MUST BE ACKED + recorded + { + "ackId": "ack-synth-mon", + "message": { + "publishTime": now_iso, + "data": _b64_json( + { + "incident": { + "incident_id": "inc-hb-1", + "policy_name": "cage-staging - Alert Pipeline Synthetic Heartbeat", + "policy_user_labels": {"alert_kind": "heartbeat"}, + "state": "open", + "started_at": int(now_epoch), + } + } + ), + }, + }, + # 4. Newer periodic bridge heartbeat -> MUST BE NACKED so repeated runs stay idempotent + { + "ackId": "ack-bridge-hb-newest", + "message": { + "publishTime": now_iso, + "data": _b64_json( + { + "source": "compliance_bridge", + "alert_type": "heartbeat", + "timestamp": now_iso, + } + ), + }, + }, + # 5. Older superseded periodic bridge heartbeat -> MUST BE ACKED (GC) + { + "ackId": "ack-bridge-hb-older", + "message": { + "publishTime": older_iso, + "data": _b64_json( + { + "source": "compliance_bridge", + "alert_type": "heartbeat", + "timestamp": older_iso, + } + ), + }, + }, + ] + + acked: list[str] = [] + nacked: list[str] = [] + + def _fake_http( + method: str, + url: str, + _token: str, + payload: Any = None, + timeout: float = 30.0, + ) -> dict[str, Any]: + assert method == "POST" + if url.endswith(":pull"): + return {"receivedMessages": messages} + if url.endswith(":acknowledge"): + acked.extend(payload["ackIds"]) + return {} + if url.endswith(":modifyAckDeadline"): + assert payload["ackDeadlineSeconds"] == 0 + nacked.extend(payload["ackIds"]) + return {} + raise AssertionError(f"Unexpected URL {url}") + + with patch.object(verifier, "_http_json", side_effect=_fake_http): + res = verifier.inspect_subscription_batch( + subscription_path=SUB_PATH, + token="tok", + trip_started_epoch=now_epoch - 5.0, + ) + + assert res["monitoring_heartbeat_observed"] is True + assert res["monitoring_incident_id"] == "inc-hb-1" + assert res["freshest_bridge_heartbeat_epoch"] == pytest.approx(now_epoch) + assert res["operational_messages_preserved"] == 2 + assert set(acked) == {"ack-synth-mon", "ack-bridge-hb-older"} + assert set(nacked) == { + "ack-real-mon", + "ack-real-bridge", + "ack-bridge-hb-newest", + } + + def test_verify_end_to_end_resets_metric_in_finally_on_timeout(self) -> None: + writes: list[int] = [] + clock = [100.0] + + def _advance_clock() -> float: + val = clock[0] + clock[0] += 8.0 + return val + + with ( + patch.object( + verifier, + "write_heartbeat_metric", + side_effect=lambda **kw: writes.append(kw["value"]), + ), + patch.object( + verifier, + "inspect_subscription_batch", + return_value={ + "monitoring_heartbeat_observed": False, + "monitoring_incident_id": None, + "ondemand_bridge_probe_observed": False, + "freshest_bridge_heartbeat_epoch": None, + "operational_messages_preserved": 0, + }, + ), + patch.object(verifier.time, "sleep", return_value=None), + patch.object(verifier.time, "time", side_effect=_advance_clock), + ): + with pytest.raises(AlertVerificationError, match="Timed out"): + verifier.verify_end_to_end_delivery( + project="cage-test-01", + subscription="cage-staging-alerts-verify", + token="tok", + timeout_seconds=15, + poll_interval_seconds=1, + ) + + assert writes == [1, 0], "Metric must be tripped to 1 and reset to 0 in finally" + + def test_validate_https_url_rejects_non_https(self) -> None: + with pytest.raises(AlertVerificationError, match="Refusing non-HTTPS"): + verifier._validate_https_url( + "http://monitoring.googleapis.com/v3/projects/x" + )