feat(api): the insider watchlist expires, elevates and reviews for real (WS4.4) (#2005)

## What

WS4.4 of the gap-closure program: departing-employee / insider-risk
monitoring. `user_risk_profiles.is_watchlisted` has existed since
migration 014 and the console PATCH wrote it — **and nothing consumed
it**. No alert was elevated, no row ever expired, nothing reviewed the
identity's activity. A watchlist nothing reads is a checkbox.

## The three halves (migration 168)

**Expiry — never indefinite.** Watchlisting requires a reason and a
future `watchlist_expires_at` (422 names the missing one; the console's
one-click path falls back to the tenant's `default_expiry_days`). A
sweep worker (`insider_watchlist_sweep`, on by default like
`approval_expiry` — hygiene of a deadline we recorded, not automation
toward anyone's estate) flips expired rows and rebuilds. Legacy
watchlisted rows are backfilled with a 90-day horizon.

**Elevation through the existing business-context path — no parallel
mechanism.** Watchlisted identities become *managed* rules: a tag rule
(`insider-watchlist`) and a severity floor (`info`/`low` → `medium`),
written to a machine-owned `managed_yaml` column **beside** the
analyst's verbatim `yaml_text` on the same row. Same engine, same
auto-triage application point (`BusinessContextApplier` now selects and
parses both documents independently, so a syntax error in the analyst's
draft never withdraws elevation and a managed-rule bug never disables
the tenant's suppressions). The console save path owns `yaml_text` only;
the watchlist upsert owns `managed_yaml` only. The floor is guarded by a
`severity in [info, low]` clause because `set_severity` is a fixed
assignment — without the guard it would **downgrade** `high`/`critical`,
proven by the negative control. Read-only exposure: `GET
/business-context/managed-rules`.

**Review.** The transition onto the list opens a departure-review case:
exfil-shaped lake activity (reviewable pattern list, counted per
concrete event type so the analyst sees what matched) plus the
identity's alerts in the window. An unreachable lake reads **"unknown,
not zero"**; a ref-less profile names both gaps.

**Two doors.** Manual (console). HR: per-tenant opt-in
(`insider_watchlist_policies.hr_sync_enabled`, **default off**; `PUT
/insider-threat/watchlist-policy` requires `settings:write` — switching
on an automated door is tenant configuration, unlike watchlisting one
subject). The sweep watches `workforce_members` (the HR store the
connectors service already syncs) for `terminated`/last-day members and
lists them with the HR fact as the reason and last-day-plus-grace as the
expiry — idempotently, never overwriting or shortening a manual row.

## Two grammar implementations, held together

The agents service re-implements the business-context grammar (separate
image, no shared import). A golden fixture
(`services/api/tests/fixtures/managed_rules_golden.yaml`) is pinned by
the API generator test and parsed by the agents suite with *its* loader
— either side drifting goes red. Writing this found a real
incompatibility immediately: the first generated ids
(`managed:insider-watchlist:0:tag`) violated the loader's kebab-case
slug rule.

## Testing

- `services/api/tests/test_insider_watchlist.py` — **21 cases**
(generation parses with the console's own loader; the real engine floors
low, tags, and **never downgrades** `medium`/`high`/`critical`;
adversarial YAML-shaped reasons stay data; validation messages; lookback
honesty; HR idempotence).
- `services/agents/tests/test_business_context_managed_rules.py` — **8
cases** (golden fixture through the agents loader + evaluator;
two-document isolation both ways).
- `tests/isolation/test_insider_watchlist_live.py` — **6 cases on live
Postgres** (new `integration.yml` step, migration trigger paths
updated): expiry exclusion is the rebuild SELECT's own WHERE clause; the
two upserts own one column each and never clobber the other;
`watchlist_source` is a DB CHECK; policy RLS judged under the
NOBYPASSRLS `aisoc_app` role including the unbound arm the sweep worker
depends on; the HR door end to end (workforce row → watchlist row +
managed rule + review case saying "unknown, not zero" for the absent
lake), idempotent on the second sweep. Fails at setup on the pre-change
tree.

**Negative controls (applied, observed failing, restored):**
1. Removing `AND watchlist_expires_at > :now` from the rebuild SELECT →
`test_rebuild_excludes_expired_and_refless_rows` fails live.
2. Removing the `severity in [info, low]` guard →
`test_never_downgrades[high]` and `[critical]` fail (the floor becomes a
downgrade).

## Gates

route_auth OK · route_tenant_scope OK · tenant_query_predicates OK ·
module_reachability OK (worker + service reachable from lifespan) ·
migration_numbering OK (168, allocated block) · ORM-migration parity OK
· mypy baseline OK · ruff clean · claim matrix **408 rows — 399 GATED /
9 PARTIAL / 0 NO GATE** (new GATED row; tallies recomputed by the
script) · readme_gates OK · OpenAPI regenerated (additive).

## Could not verify

The lake half of the lookback ran against the mocked
`execute_lake_query` and the live suite's *absent* lake (the honest
could-not-check path); it has not been exercised against a live
ClickHouse with matching `raw_events` rows — the SQL follows
`identity_usage_collector.py`'s proven shape (pyformat binds, same
columns).
This commit is contained in:
Beenu Arora
2026-11-22 11:51:29 -08:00
committed by GitHub
parent 7d0c5f4187
commit 035bb516b4
21 changed files with 2207 additions and 28 deletions
+25 -1
View File
@@ -118,7 +118,7 @@ jobs:
# rail legs) were inert: their live tests only ran when something
# *else* in the surviving list changed. This is the union of all
# three lists; the next lane extends it rather than re-assigning.
migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/fusion/tests/test_asset_context_live.py services/fusion/app/services/asset_context.py services/api/tests/test_alert_rail_business_context_live.py services/api/app/services/alert_rail.py services/agents/tests/test_business_context_tenant_rules_live.py services/agents/app/workers/business_context.py services/api/tests/test_alert_queue_priority_live.py services/api/app/services/alert_queue.py tests/isolation/test_alert_occurrences_live.py tests/isolation/test_alert_recurrence_after_closure_live.py services/fusion/app/services/alert_sink.py services/fusion/app/services/alert_status.py services/fusion/tests/test_alert_reduction_real.py tests/isolation/test_root_cause_findings_live.py tests/isolation/test_case_root_cause_live.py services/api/app/services/case_root_cause.py tests/isolation/test_case_resolution_live.py services/api/app/services/case_resolution.py .github/workflows/integration.yml services/api/tests/test_identity_privilege_live.py services/api/app/services/identity_privilege.py services/api/app/services/identity_privilege_store.py services/api/app/services/alert_priority.py services/api/tests/test_access_review_live.py services/api/app/services/access_review.py services/api/app/services/access_review_store.py services/api/tests/test_identity_resolution_live.py services/api/app/services/identity_resolution.py services/api/app/services/identity_resolution_store.py services/api/app/services/change_timeline.py services/connectors/app/vuln_promotion_sql.py services/connectors/app/scheduler.py services/connectors/tests/test_vuln_promotion_live.py services/api/app/api/v1/endpoints/triage_questions.py services/agents/app/context/triage_questions_store.py services/agents/app/hunt/source_report_store.py services/agents/app/api/router.py services/agents/tests/integration/ services/api/app/api/v1/endpoints/alerts.py services/api/tests/test_copilot_alert_filters_live.py services/api/tests/test_alert_list_search_filter.py services/api/app/api/v1/endpoints/cases.py services/api/tests/test_related_cases_live.py services/api/app/services/related_cases.py services/api/app/api/v1/endpoints/insights.py services/api/tests/test_insights_live.py'
migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/fusion/tests/test_asset_context_live.py services/fusion/app/services/asset_context.py services/api/tests/test_alert_rail_business_context_live.py services/api/app/services/alert_rail.py services/agents/tests/test_business_context_tenant_rules_live.py services/agents/app/workers/business_context.py services/api/tests/test_alert_queue_priority_live.py services/api/app/services/alert_queue.py tests/isolation/test_alert_occurrences_live.py tests/isolation/test_alert_recurrence_after_closure_live.py services/fusion/app/services/alert_sink.py services/fusion/app/services/alert_status.py services/fusion/tests/test_alert_reduction_real.py tests/isolation/test_root_cause_findings_live.py tests/isolation/test_case_root_cause_live.py services/api/app/services/case_root_cause.py tests/isolation/test_case_resolution_live.py services/api/app/services/case_resolution.py tests/isolation/test_insider_watchlist_live.py services/api/app/services/insider_watchlist.py .github/workflows/integration.yml services/api/tests/test_identity_privilege_live.py services/api/app/services/identity_privilege.py services/api/app/services/identity_privilege_store.py services/api/app/services/alert_priority.py services/api/tests/test_access_review_live.py services/api/app/services/access_review.py services/api/app/services/access_review_store.py services/api/tests/test_identity_resolution_live.py services/api/app/services/identity_resolution.py services/api/app/services/identity_resolution_store.py services/api/app/services/change_timeline.py services/connectors/app/vuln_promotion_sql.py services/connectors/app/scheduler.py services/connectors/tests/test_vuln_promotion_live.py services/api/app/api/v1/endpoints/triage_questions.py services/agents/app/context/triage_questions_store.py services/agents/app/hunt/source_report_store.py services/agents/app/api/router.py services/agents/tests/integration/ services/api/app/api/v1/endpoints/alerts.py services/api/tests/test_copilot_alert_filters_live.py services/api/tests/test_alert_list_search_filter.py services/api/app/api/v1/endpoints/cases.py services/api/tests/test_related_cases_live.py services/api/app/services/related_cases.py services/api/app/api/v1/endpoints/insights.py services/api/tests/test_insights_live.py'
# backup_crypt.py was missing from the old filter, and it is where
# every byte of the AES-256-GCM implementation lives — so a change
# to the encryption itself did not run the gate that proves the
@@ -1139,6 +1139,30 @@ jobs:
|| { echo "::error::the case resolution live suite did not report any passing test"; exit 1; }
! grep -qE 'skipped' /tmp/case-resolution.log \
|| { echo "::error::the case resolution live suite skipped a test; its DSNs must both be set"; exit 1; }
# WS4.4. The insider watchlist's Postgres truths: expiry exclusion is
# the rebuild SELECT's own WHERE clause (a stub always gets it right by
# construction); the console save and the watchlist upsert own one
# column each of the same row and must not clobber the other; the
# watchlist_source vocabulary is a DB CHECK; the policy table's RLS —
# including the unbound arm the sweep worker depends on — is judged
# under the DML-only NOBYPASSRLS role; and the HR door runs end to end
# (workforce row -> watchlist row + managed rule + review case that
# says "unknown, not zero" for the absent lake), idempotently.
- name: The insider watchlist expires, elevates and reviews for real (live Postgres)
working-directory: services/api
env:
MSSP_ISOLATION_REQUIRED: '1'
ISOLATION_INSIDER_WATCHLIST_DSN: postgresql://aisoc_app:aisoc_app_ci_secret@localhost:5432/aisoc
# aisoc-db-role: owner — fixtures only. The suite creates scratch tenants, profiles and workforce rows, which the DML-only runtime role cannot. The assertions read through ISOLATION_INSIDER_WATCHLIST_DSN above, the NOBYPASSRLS runtime role, so RLS is judged under the policy it really runs under.
ISOLATION_INSIDER_WATCHLIST_ADMIN_DSN: postgresql://aisoc:aisoc_ci_secret@localhost:5432/aisoc
run: |
set -euo pipefail
python -m pytest ../../tests/isolation/test_insider_watchlist_live.py -v --tb=short -rs | tee /tmp/insider-watchlist.log
grep -qE '[1-9][0-9]* passed' /tmp/insider-watchlist.log \
|| { echo "::error::the insider watchlist live suite did not report any passing test"; exit 1; }
! grep -qE 'skipped' /tmp/insider-watchlist.log \
|| { echo "::error::the insider watchlist live suite skipped a test; its DSNs must both be set"; exit 1; }
# Depth 2 wave 2, 1.1. The properties here are schema facts a stand-in
# store always gets right by construction: the
# `valid_from <= t < valid_until` select that makes an alert read the
+24
View File
@@ -29,6 +29,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
corrupts one enforcement mapping and watches two fail.
### Added
- **The insider watchlist is a control, not a checkbox** (WS4.4 of the
gap-closure program). `user_risk_profiles.is_watchlisted` existed since
migration 014 and the console wrote it — and nothing consumed it: no
elevation, no expiry, no review. Now (migration 168): a watchlist row is
**never indefinite** (reason + future expiry required; a sweep worker
flips expired rows); a watchlisted identity's alerts are tagged
`insider-watchlist` and floored `info`/`low` → `medium` **through the
existing business-context path** — a machine-owned `managed_yaml`
document beside the analyst's verbatim `yaml_text` on the same row, same
engine, same auto-triage application point, parsed independently so a
syntax error in either document never withdraws the other's rules, and
guarded so the floor can never downgrade `high`/`critical`; the
transition onto the list opens a **departure-review case** counting
exfil-shaped lake activity per event type (an unreachable lake reads
"unknown, not zero", never 0) beside the identity's recent alerts; and
the **HR door** — per-tenant opt-in, default off — watches
`workforce_members` for terminated/last-day members and lists them with
the HR fact as the reason and last-day-plus-grace as the expiry,
idempotently, never shortening a manual row. The two grammar
implementations (console loader, agents worker) are held together by a
golden fixture both suites parse. Proven by 21 API cases, 8 agents
cases and a live-Postgres suite (expiry exclusion is the SQL's own
WHERE; the two upserts own one column each; RLS under the NOBYPASSRLS
role; the HR door end to end).
- **Every open case has an accountable owner and a next-action clock**
(WS7.4, completing WS7 of the gap-closure program). An owner is a person
+1 -1
View File
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
The claim-to-gate matrix stands at **408 rows — 399 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
The claim-to-gate matrix stands at **409 rows — 400 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
+1 -1
View File
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
The last row is the one worth reading first. It is the honest index: 399 rows
The last row is the one worth reading first. It is the honest index: 400 rows
`GATED`, 9 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
+3 -2
View File
@@ -9,6 +9,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Claim | Source | Gate (workflow :: job) | Profile | Status | Closes in |
|---|---|---|---|---|---|
| A DLP alert normalizes into one finding whatever vendor raised it — policy, rule, data classes, file name/hash/size, channel, destination and its class, the enforcement the DLP product itself applied (`blocked` / `warned` / `allowed` / `audited`), user and device — with per-source profiles mapping only vendor-documented fields: an absent fact stays empty, a destination class is derived only from explicit vendor facts, an unstated enforcement stays null, and a source without a profile yields no finding rather than a best-effort parse | `services/api/app/services/dlp_finding.py`; `GET /alerts/{id}/dlp-finding` | `ci.yml :: Python — Tests` (api, `test_dlp_finding.py`, 15 cases over the vendors' own published shapes — Netskope's DLP alert export sample, the O365 Management Activity DLP schema with its 1–5 EnforcementMode ladder, Graph `alerts_v2` evidence objects — including absent-stays-empty, the managed_app-only destination-class rule, and the honest `finding: null` route answer) | core | GATED | Negative control recorded in the PR: corrupting one enforcement mapping fails two cases |
| The insider watchlist is a control, not a checkbox: a watchlist row is never indefinite (reason + future expiry required, expired rows stop elevating), a watchlisted identity's alerts are tagged and floored `info`/`low` → `medium` **through the existing business-context path** (a machine-owned `managed_yaml` document beside the analyst's verbatim `yaml_text`, same engine, same triage-worker application point, never a downgrade of `high`/`critical`), the transition onto the list opens a departure-review case whose lake half reports *could not check* rather than zero when unreachable, and the HR door (`workforce_members` status/last-day, per-tenant opt-in, default off) lists departing members idempotently without ever shortening a manual row | `services/api/app/services/insider_watchlist.py`; migration 168; `services/api/app/workers/insider_watchlist_sweep.py` | `ci.yml :: Python — Tests` (api `test_insider_watchlist.py` 21 cases: the generated document parses with the console's own loader and evaluated by the real engine floors low and never touches high/critical, adversarial reasons stay data, validation names each unmet requirement, the lookback renders per-event-type counts and an unreachable lake as unknown-not-zero, the HR door never overwrites an existing row; agents `test_business_context_managed_rules.py` 8 cases: the **agents service's independent grammar implementation** parses the same golden fixture bytes and applies the same floor, and a parse error in either document never withdraws the other's rules) + `integration.yml :: The insider watchlist expires, elevates and reviews for real (live Postgres)` (expiry exclusion is the rebuild SELECT's own WHERE; the console save and the watchlist upsert own one column each and must not clobber the other; `watchlist_source` is a DB CHECK; policy RLS judged under the NOBYPASSRLS role including the unbound sweep arm; the HR door end to end — workforce row → watchlist row + managed rule + review case — idempotent on the second sweep; fails at setup on the pre-change tree) | core | GATED | Negative controls recorded in the PR: removing the expiry exclusion fails the live rebuild test; removing the severity guard makes the floor a downgrade and fails two never-downgrade cases |
| Every open case has an accountable owner — a person or an agent run — and a next-action clock: launching an investigation claims an unowned case for the run and never steals one a person holds, and `GET /cases/attention` surfaces open cases that are unowned or overdue with `owner_kind` named and `overdue_seconds` null until due (never a confident zero) | `services/api/app/api/v1/endpoints/cases.py` (`get_cases_attention`, `_claim_case_for_run`); migration 167 | `ci.yml :: Python — Tests` (api, `test_case_ownership_attention.py`: the feed names the owner kind per row and keeps not-yet-due as null; the claim SQL carries both no-person and no-agent predicates — the negative control removes them and the test fails; the query is tenant-scoped; the PATCH surface carries both fields) | core | GATED | - |
| The investigator carries named strategies for the reference-service surfaces — AI-agent misuse, data handling against business context, BEC payment fraud, SaaS OAuth abuse, cloud exposure — each declaring the pivots the depth gate grades it on | `services/agents/app/investigator/strategies.py` | `ci.yml :: Python — Tests` (agents, `test_deep_investigation.py::TestStrategySelection` — each of the five has its own selection row, technique-match outranking keywords, and disabling any one fails its row) + `ci.yml :: python-lint` (`check_investigation_depth.py`: 15 strategies, every expected pivot resolves to a real tool in both directions) | core | GATED | Negative control recorded in the PR: renaming one strategy id fails exactly its selection row |
| A case reaches `resolved` only through the tenant's resolution contract — containment verified-or-waived-with-reason, eradication and recovery recorded, root cause determined or undetermined (a hypothesis does not satisfy), affected entities derived from the case's own rows, customer notified channel-and-time — enforced by **one shared checker** at every writer: the PATCH gate (422 naming each gap), the war-room resolve decision (refusal note, no status write), and the inbound ITSM mirror (vendor resolve demoted to `contained` with the gaps in the system note, because a webhook cannot be 422'd); off by default per tenant | `services/api/app/services/case_resolution.py`; migration 166 | `ci.yml :: Python — Tests` (api, `test_case_resolution_contract.py`, 16 cases: the pure gap computation names every unmet requirement, a hypothesis is refused in so many words, toggled-off requirements do not gap, facts validation enforces verified-requires-reference / waived-requires-reason / notification-channel-and-time-together, and all three writers are driven through their real functions with the checker monkeypatched both ways) + `integration.yml :: Resolving a case is earned, and the contract's rows are tenant-scoped (live Postgres)` (the opt-in default is the real absent-row state, one-per-tenant policy and one-per-case facts are unique-constraint behaviour, the derived entity count is JSONB arithmetic over the real schema, RLS under the NOBYPASSRLS role; fails at setup on the pre-change tree) | core | GATED | Negative control recorded in the PR: forcing the checker to answer no-gaps fails two cases |
@@ -419,8 +420,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
- Total: 408
- GATED: 399
- Total: 409
- GATED: 400
- PARTIAL: 9
- NO GATE: 0
+294 -1
View File
@@ -15776,6 +15776,18 @@ paths:
tags:
- insider-threat
summary: Update Watchlist
description: 'Watchlist (or clear) a profile — the switch that now does something.
Watchlisting requires a reason and an expiry (422 names the one that is
missing; an omitted expiry falls back to the tenant''s policy default so
the console''s one-click path still works). The transition onto the list
rebuilds the tenant''s managed business-context rules and opens the
departure-review lookback case; clearing withdraws the managed rules.'
operationId: update_watchlist_api_v1_insider_threat_profiles__profile_id__watchlist_patch
security:
- HTTPBearer: []
@@ -15799,13 +15811,61 @@ paths:
content:
application/json:
schema:
$ref: '#/components/schemas/RiskProfileOut'
$ref: '#/components/schemas/WatchlistResult'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
/api/v1/insider-threat/watchlist-policy:
get:
tags:
- insider-threat
summary: Get Watchlist Policy
description: The tenant's policy; an absent row is the honest default (all off).
operationId: get_watchlist_policy_api_v1_insider_threat_watchlist_policy_get
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/WatchlistPolicyOut'
security:
- HTTPBearer: []
put:
tags:
- insider-threat
summary: Put Watchlist Policy
description: 'Upsert the policy. `settings:write`, not `cases:write`: switching
on
an automated door that watches the HR store is tenant configuration,
unlike watchlisting one subject, which is investigative work.'
operationId: put_watchlist_policy_api_v1_insider_threat_watchlist_policy_put
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/WatchlistPolicyBody'
required: true
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/WatchlistPolicyOut'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- HTTPBearer: []
/api/v1/insider-threat/indicators:
get:
tags:
@@ -16942,6 +17002,21 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
/api/v1/business-context/managed-rules:
get:
tags:
- business-context
summary: Get Managed Rules
operationId: get_managed_rules_api_v1_business_context_managed_rules_get
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/ManagedRulesOut'
security:
- HTTPBearer: []
/api/v1/business-context/rules:
get:
tags:
@@ -34596,6 +34671,32 @@ components:
required:
- sha256
title: LookupRequest
ManagedRulesOut:
properties:
managed_yaml:
type: string
title: Managed Yaml
note:
type: string
title: Note
default: Managed by the insider watchlist; regenerated on every watchlist
change. Edit the watchlist, not this document.
type: object
required:
- managed_yaml
title: ManagedRulesOut
description: 'The machine-owned half of the rule set, read-only (WS4.4).
`managed_yaml` is regenerated whole by the insider watchlist and applied
by the triage worker beside the authored rules. It is exposed so an
analyst can *see* why an alert was elevated — and deliberately has no
write route: the console save path owns `yaml_text` only, and the two
documents never clobber each other.'
MarketplaceItemSummary:
properties:
id:
@@ -39483,6 +39584,16 @@ components:
- type: string
- type: 'null'
title: Watchlist Reason
watchlist_expires_at:
anyOf:
- type: string
format: date-time
- type: 'null'
title: Watchlist Expires At
watchlist_source:
type: string
title: Watchlist Source
default: manual
last_evaluated_at:
type: string
title: Last Evaluated At
@@ -45038,6 +45149,182 @@ components:
- last_synced_at
- last_error
title: WarRoomModel
WatchlistPolicyBody:
properties:
hr_sync_enabled:
type: boolean
title: Hr Sync Enabled
default: false
default_expiry_days:
type: integer
maximum: 365.0
minimum: 1.0
title: Default Expiry Days
default: 30
hr_grace_days:
type: integer
maximum: 90.0
minimum: 1.0
title: Hr Grace Days
default: 14
lookback_days:
type: integer
maximum: 90.0
minimum: 1.0
title: Lookback Days
default: 30
type: object
title: WatchlistPolicyBody
WatchlistPolicyOut:
properties:
hr_sync_enabled:
type: boolean
title: Hr Sync Enabled
default: false
default_expiry_days:
type: integer
maximum: 365.0
minimum: 1.0
title: Default Expiry Days
default: 30
hr_grace_days:
type: integer
maximum: 90.0
minimum: 1.0
title: Hr Grace Days
default: 14
lookback_days:
type: integer
maximum: 90.0
minimum: 1.0
title: Lookback Days
default: 30
tenant_id:
type: string
format: uuid
title: Tenant Id
updated_at:
anyOf:
- type: string
format: date-time
- type: 'null'
title: Updated At
type: object
required:
- tenant_id
title: WatchlistPolicyOut
WatchlistResult:
properties:
id:
type: string
format: uuid
title: Id
tenant_id:
type: string
format: uuid
title: Tenant Id
user_id:
anyOf:
- type: string
format: uuid
- type: 'null'
title: User Id
external_user_ref:
anyOf:
- type: string
- type: 'null'
title: External User Ref
risk_score:
type: number
title: Risk Score
risk_tier:
type: string
title: Risk Tier
failed_auth_24h:
type: integer
title: Failed Auth 24H
off_hours_events_7d:
type: integer
title: Off Hours Events 7D
data_staging_score:
type: number
title: Data Staging Score
peer_anomaly_score:
type: number
title: Peer Anomaly Score
privilege_delta:
type: integer
title: Privilege Delta
is_watchlisted:
type: boolean
title: Is Watchlisted
watchlist_reason:
anyOf:
- type: string
- type: 'null'
title: Watchlist Reason
watchlist_expires_at:
anyOf:
- type: string
format: date-time
- type: 'null'
title: Watchlist Expires At
watchlist_source:
type: string
title: Watchlist Source
default: manual
last_evaluated_at:
type: string
title: Last Evaluated At
updated_at:
type: string
title: Updated At
elevation_active:
type: boolean
title: Elevation Active
default: false
elevation_gap:
anyOf:
- type: string
- type: 'null'
title: Elevation Gap
lookback_case_id:
anyOf:
- type: string
format: uuid
- type: 'null'
title: Lookback Case Id
type: object
required:
- id
- tenant_id
- user_id
- external_user_ref
- risk_score
- risk_tier
- failed_auth_24h
- off_hours_events_7d
- data_staging_score
- peer_anomaly_score
- privilege_delta
- is_watchlisted
- watchlist_reason
- last_evaluated_at
- updated_at
title: WatchlistResult
description: 'The PATCH response: the profile plus what watchlisting actually
did.
`elevation_active` says whether a managed business-context rule now
matches this identity; when it cannot (`external_user_ref` is empty),
`elevation_gap` names the missing piece rather than implying elevation
silently. `lookback_case_id` is the departure-review case the
transition opened, when it opened one.'
WatchlistUpdate:
properties:
is_watchlisted:
@@ -45048,6 +45335,12 @@ components:
- type: string
- type: 'null'
title: Watchlist Reason
watchlist_expires_at:
anyOf:
- type: string
format: date-time
- type: 'null'
title: Watchlist Expires At
type: object
required:
- is_watchlisted
+13 -1
View File
@@ -782,6 +782,18 @@ RATCHET: dict[str, str] = {
"approval_expiry.run_once, and it was the clearest instance of the defect this rule "
"closes: it was credited by `RETURNING id, tenant_id`, a clause that constrains nothing"
),
"services/api/app/services/insider_watchlist.py::<module>::user_risk_profiles": (
"the watchlist-expiry sweep (WS4.4): flips every tenant's expired rows in one statement, "
"bounded by `watchlist_expires_at <= :now` — the same shape and the same reason as "
"approval_expiry's UPDATE two entries above. Its RETURNING tenant_id drives the per-tenant "
"managed-rule rebuild and constrains nothing"
),
"services/api/app/services/insider_watchlist.py::<module>::insider_watchlist_policies": (
"the HR-door sweep's tenant enumeration (WS4.4): SELECT the tenants whose policy row "
"opted in (`hr_sync_enabled = TRUE`), after which each tenant's workforce rows are read "
"under that tenant's own id — the same enumeration-then-scoped-work shape as "
"fusion sessions.py's DISTINCT tenant_id entry"
),
"services/fusion/app/services/sessions.py::<module>::sessions": (
"SELECT DISTINCT tenant_id of sessions due for expiry — the enumeration that drives the "
"sweep, which then closes each tenant's sessions under its own id"
@@ -937,7 +949,7 @@ RATCHET: dict[str, str] = {
# *stricter*: the statement that had to be fixed rather than recorded,
# `fetch_enabled_connectors` called from a request handler, is absent from the
# list because the route now uses a sibling that filters in SQL.
MAX_RATCHET = 80
MAX_RATCHET = 82
# ---------------------------------------------------------------------------
+41 -11
View File
@@ -345,6 +345,33 @@ def apply_rules(alert: dict[str, Any], rules: list[BusinessContextRule]) -> Busi
_TENANT_CACHE_TTL_SECONDS = 30.0
def _rules_from_row(yaml_text: str, managed_yaml: str, *, tenant_id: str = "?") -> list[BusinessContextRule]:
"""Parse a rule-set row's two documents and return their union.
``yaml_text`` is the analyst's verbatim artifact; ``managed_yaml`` is the
machine-owned half (insider-watchlist elevation, migration 168). They are
parsed **independently** so a syntax error in one never takes the other
down: the analyst breaking their draft must not withdraw watchlist
elevation, and a managed-rule bug must not disable the tenant's
suppressions. Authored rules come first; the engine orders by ``priority``
anyway, so concatenation order only breaks ties.
"""
rules: list[BusinessContextRule] = []
for label, doc in (("authored", yaml_text), ("managed", managed_yaml)):
if not doc:
continue
try:
rules.extend(load_rules_from_yaml(doc))
except Exception as exc: # noqa: BLE001 — a bad document applies none of ITS rules
logger.warning(
"business_context.tenant_parse_failed",
tenant_id=tenant_id,
document=label,
error=str(exc),
)
return rules
class BusinessContextApplier:
"""Applies business-context rules from Postgres, and from a YAML file.
@@ -393,9 +420,16 @@ class BusinessContextApplier:
conn = await asyncpg.connect(dsn, timeout=5.0)
try:
# `managed_yaml` arrived with migration 168 (insider-watchlist
# elevation). COALESCE over a missing column would be nicer but
# Postgres has no such form; a deployment running new code
# against the old schema raises here and lands in the fail-soft
# arm below — authored rules degrade too, briefly, which the
# upgrade path (`make upgrade` migrates before starting) makes
# a non-event.
row = await conn.fetchrow(
"""
SELECT yaml_text, enabled
SELECT yaml_text, managed_yaml, enabled
FROM aisoc_business_context_rule_sets
WHERE tenant_id = $1
""",
@@ -414,16 +448,12 @@ class BusinessContextApplier:
return cached[1] if cached else []
rules: list[BusinessContextRule] = []
if row is not None and row["enabled"] and row["yaml_text"]:
try:
rules = load_rules_from_yaml(row["yaml_text"])
except Exception as exc: # noqa: BLE001 — a bad rule set applies none
logger.warning(
"business_context.tenant_parse_failed",
tenant_id=tenant_id,
error=str(exc),
)
rules = []
if row is not None and row["enabled"]:
rules = _rules_from_row(
row["yaml_text"] or "",
row["managed_yaml"] or "",
tenant_id=tenant_id,
)
self._tenant_rules[tenant_id] = (now, rules)
return rules
@@ -0,0 +1,93 @@
"""The managed rule document applies on the live triage path (WS4.4).
Two implementations of one grammar
----------------------------------
The insider watchlist generates managed rules in ``services/api``
(`app/services/insider_watchlist.py`); the worker that applies them on the
auto-triage hot path is **this service's** independent re-implementation of
the business-context grammar (separate image, no shared import). Two parsers
of one language drift silently unless something holds them together — so the
API side pins its generator to a golden fixture
(`services/api/tests/fixtures/managed_rules_golden.yaml`) and this suite
parses *the same bytes* with the agents loader and evaluates them with the
agents engine. If either side changes shape, one of the two suites goes red.
The second half covers the row-level split: ``yaml_text`` (authored) and
``managed_yaml`` (machine-owned) are parsed independently, so a syntax error
in the analyst's draft never withdraws watchlist elevation and a managed-rule
bug never disables the tenant's suppressions.
"""
from __future__ import annotations
from pathlib import Path
from app.workers.business_context import (
_rules_from_row,
apply_rules,
load_rules_from_yaml,
)
GOLDEN = Path(__file__).resolve().parents[2] / "api" / "tests" / "fixtures" / "managed_rules_golden.yaml"
AUTHORED = """
rules:
- id: suppress-backup-noise
description: nightly backup account
when:
field: username
op: eq
value: svc_backup
then:
suppress: true
"""
BROKEN = "rules:\n - id: [this is not a slug\n"
def _alert(username: str, severity: str = "low") -> dict:
return {"username": username, "severity": severity, "hostname": "fin-ws-07"}
class TestGoldenFixtureParsesHere:
def test_the_agents_loader_accepts_the_generated_document(self) -> None:
rules = load_rules_from_yaml(GOLDEN.read_text())
assert len(rules) == 4
assert all(r.id.startswith("managed-insider-watchlist-") for r in rules)
def test_the_floor_raises_low_and_tags(self) -> None:
rules = load_rules_from_yaml(GOLDEN.read_text())
result = apply_rules(_alert("mallory@example.com", "low"), rules)
assert result.alert["severity"] == "medium"
assert "insider-watchlist" in result.alert.get("tags", [])
def test_the_floor_never_downgrades_high(self) -> None:
rules = load_rules_from_yaml(GOLDEN.read_text())
result = apply_rules(_alert("mallory@example.com", "high"), rules)
assert result.alert["severity"] == "high"
def test_other_identities_are_untouched(self) -> None:
rules = load_rules_from_yaml(GOLDEN.read_text())
result = apply_rules(_alert("alice@example.com", "low"), rules)
assert result.alert["severity"] == "low"
assert not result.matched_rule_ids
class TestTwoDocumentSplit:
def test_both_documents_apply(self) -> None:
rules = _rules_from_row(AUTHORED, GOLDEN.read_text())
ids = {r.id for r in rules}
assert "suppress-backup-noise" in ids
assert any(i.startswith("managed-insider-watchlist-") for i in ids)
def test_a_broken_authored_draft_does_not_withdraw_elevation(self) -> None:
rules = _rules_from_row(BROKEN, GOLDEN.read_text())
assert rules, "managed rules must survive an authored parse error"
assert all(r.id.startswith("managed-insider-watchlist-") for r in rules)
def test_a_broken_managed_document_does_not_disable_suppressions(self) -> None:
rules = _rules_from_row(AUTHORED, BROKEN)
assert [r.id for r in rules] == ["suppress-backup-noise"]
def test_empty_documents_are_no_rules(self) -> None:
assert _rules_from_row("", "") == []
@@ -447,6 +447,40 @@ async def _fetch_sample_alerts(
# ---------------------------------------------------------------------------
class ManagedRulesOut(BaseModel):
"""The machine-owned half of the rule set, read-only (WS4.4).
`managed_yaml` is regenerated whole by the insider watchlist and applied
by the triage worker beside the authored rules. It is exposed so an
analyst can *see* why an alert was elevated — and deliberately has no
write route: the console save path owns `yaml_text` only, and the two
documents never clobber each other.
"""
managed_yaml: str
note: str = "Managed by the insider watchlist; regenerated on every watchlist change. Edit the watchlist, not this document."
@router.get("/managed-rules", response_model=ManagedRulesOut)
async def get_managed_rules(
user: AuthUser,
db: DBSession,
) -> ManagedRulesOut:
await user.require_permission_db("settings:read", db)
row = (
await db.execute(
text(
"""
SELECT managed_yaml FROM aisoc_business_context_rule_sets
WHERE tenant_id = :tenant_id
"""
),
{"tenant_id": str(user.tenant_id)},
)
).first()
return ManagedRulesOut(managed_yaml=(row[0] if row else "") or "")
@router.get("/rules", response_model=RulesEnvelope)
async def get_rules(
user: AuthUser,
@@ -18,7 +18,7 @@ not tenant configuration.
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
@@ -29,7 +29,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.deps import CurrentUser, require_permission
from app.api.v1.endpoints.auth import get_current_user
from app.db.database import get_db
from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile
from app.models.insider_threat import (
InsiderIndicator,
InsiderPeerGroup,
InsiderWatchlistPolicy,
UserRiskProfile,
)
from app.services import insider_watchlist
router = APIRouter(prefix="/insider-threat", tags=["insider-threat"])
@@ -53,6 +59,8 @@ class RiskProfileOut(BaseModel):
privilege_delta: int
is_watchlisted: bool
watchlist_reason: str | None
watchlist_expires_at: datetime | None = None
watchlist_source: str = "manual"
last_evaluated_at: str
updated_at: str
@@ -62,6 +70,38 @@ class RiskProfileOut(BaseModel):
class WatchlistUpdate(BaseModel):
is_watchlisted: bool
watchlist_reason: str | None = None
#: Required when watchlisting — a watchlist row is never indefinite.
#: Omitted, the tenant's `default_expiry_days` (or 30) is applied.
watchlist_expires_at: datetime | None = None
class WatchlistResult(RiskProfileOut):
"""The PATCH response: the profile plus what watchlisting actually did.
`elevation_active` says whether a managed business-context rule now
matches this identity; when it cannot (`external_user_ref` is empty),
`elevation_gap` names the missing piece rather than implying elevation
silently. `lookback_case_id` is the departure-review case the
transition opened, when it opened one.
"""
elevation_active: bool = False
elevation_gap: str | None = None
lookback_case_id: uuid.UUID | None = None
class WatchlistPolicyBody(BaseModel):
hr_sync_enabled: bool = False
default_expiry_days: int = Field(30, ge=1, le=365)
hr_grace_days: int = Field(14, ge=1, le=90)
lookback_days: int = Field(30, ge=1, le=90)
class WatchlistPolicyOut(WatchlistPolicyBody):
tenant_id: uuid.UUID
updated_at: datetime | None = None
model_config = ConfigDict(from_attributes=True)
class IndicatorOut(BaseModel):
@@ -139,24 +179,96 @@ async def get_profile(
return profile
@router.patch("/profiles/{profile_id}/watchlist", response_model=RiskProfileOut)
@router.patch("/profiles/{profile_id}/watchlist", response_model=WatchlistResult)
async def update_watchlist(
profile_id: uuid.UUID,
body: WatchlistUpdate,
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[CurrentUser, Depends(require_permission("cases:write"))],
) -> UserRiskProfile:
) -> WatchlistResult:
"""Watchlist (or clear) a profile — the switch that now does something.
Watchlisting requires a reason and an expiry (422 names the one that is
missing; an omitted expiry falls back to the tenant's policy default so
the console's one-click path still works). The transition onto the list
rebuilds the tenant's managed business-context rules and opens the
departure-review lookback case; clearing withdraws the managed rules.
"""
profile = await db.get(UserRiskProfile, profile_id)
if not profile or profile.tenant_id != current_user.tenant_id:
raise HTTPException(status_code=404, detail="Profile not found")
profile.is_watchlisted = body.is_watchlisted # type: ignore[assignment]
profile.watchlist_reason = body.watchlist_reason # type: ignore[assignment]
policy = await db.get(InsiderWatchlistPolicy, current_user.tenant_id)
lookback_days = int(policy.lookback_days) if policy else 30
default_days = int(policy.default_expiry_days) if policy else 30
outcome: insider_watchlist.WatchlistOutcome | None = None
if body.is_watchlisted:
profile.watchlisted_at = datetime.now(UTC) # type: ignore[assignment]
profile.watchlisted_by = current_user.user_id # type: ignore[assignment]
expires_at = body.watchlist_expires_at or (datetime.now(UTC) + timedelta(days=default_days))
try:
outcome = await insider_watchlist.apply_watchlist(
db,
profile,
reason=(body.watchlist_reason or "").strip(),
expires_at=expires_at,
source="manual",
actor_id=current_user.user_id,
lookback_days=lookback_days,
)
except insider_watchlist.WatchlistValidationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
else:
profile.watchlist_reason = body.watchlist_reason # type: ignore[assignment]
await insider_watchlist.clear_watchlist(db, profile)
await db.commit()
await db.refresh(profile)
return profile
result = WatchlistResult.model_validate(profile)
if outcome is not None:
result.elevation_active = outcome.elevation_active
result.elevation_gap = outcome.elevation_gap
result.lookback_case_id = outcome.lookback_case_id
return result
# ---------------------------------------------------------------------------
# Watchlist policy (the HR door's switch — tenant configuration)
# ---------------------------------------------------------------------------
@router.get("/watchlist-policy", response_model=WatchlistPolicyOut)
async def get_watchlist_policy(
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[CurrentUser, Depends(get_current_user)],
) -> WatchlistPolicyOut:
"""The tenant's policy; an absent row is the honest default (all off)."""
policy = await db.get(InsiderWatchlistPolicy, current_user.tenant_id)
if policy is None:
return WatchlistPolicyOut(tenant_id=current_user.tenant_id)
return WatchlistPolicyOut.model_validate(policy)
@router.put("/watchlist-policy", response_model=WatchlistPolicyOut)
async def put_watchlist_policy(
body: WatchlistPolicyBody,
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
) -> WatchlistPolicyOut:
"""Upsert the policy. `settings:write`, not `cases:write`: switching on
an automated door that watches the HR store is tenant configuration,
unlike watchlisting one subject, which is investigative work."""
policy = await db.get(InsiderWatchlistPolicy, current_user.tenant_id)
if policy is None:
policy = InsiderWatchlistPolicy(tenant_id=current_user.tenant_id)
db.add(policy)
policy.hr_sync_enabled = body.hr_sync_enabled
policy.default_expiry_days = body.default_expiry_days
policy.hr_grace_days = body.hr_grace_days
policy.lookback_days = body.lookback_days
policy.updated_by = current_user.user_id
await db.commit()
await db.refresh(policy)
return WatchlistPolicyOut.model_validate(policy)
# ---------------------------------------------------------------------------
+10
View File
@@ -507,6 +507,16 @@ class Settings(BaseSettings):
)
APPROVAL_EXPIRY_INTERVAL_SECONDS: int = 300 # 5m
# WS4.4 — insider-watchlist sweep: expiry hygiene (all tenants) + the
# HR door (only tenants whose policy row opted in). On by default for
# the same reason approval expiry is: a recorded deadline that nothing
# enforces is a promise the product breaks silently.
INSIDER_WATCHLIST_SWEEP_ENABLED: bool = Field(
default=True,
validation_alias=AliasChoices("INSIDER_WATCHLIST_SWEEP_ENABLED", "AISOC_INSIDER_WATCHLIST_SWEEP_ENABLED"),
)
INSIDER_WATCHLIST_SWEEP_INTERVAL_SECONDS: int = 900 # 15m
# Resolved->closed auto-close sweep. A human moves a case to `resolved`;
# the system closes it after it has stayed resolved for this many days.
#
+34
View File
@@ -41,6 +41,7 @@ from app.workers.approval_expiry import run_forever as run_approval_expiry
from app.workers.autonomy_drift import run_forever as run_autonomy_drift
from app.workers.case_auto_close import run_forever as run_case_auto_close
from app.workers.hunt_scheduler import run_forever as run_hunt_scheduler
from app.workers.insider_watchlist_sweep import run_forever as run_insider_watchlist_sweep
from app.workers.oauth_refresh import run_forever as run_oauth_refresh
from app.workers.outbound_webhook_delivery import run_forever as run_outbound_webhook_delivery
from app.workers.phishing_report_intake import run_forever as run_phishing_report_intake
@@ -78,6 +79,7 @@ _PHISHING_INTAKE_LOCK_TTL_SECONDS = 300
# held for half an hour after a crashed replica would leave approvals
# un-expired for far longer than the work takes.
_APPROVAL_EXPIRY_LOCK_TTL_SECONDS = 300
_INSIDER_WATCHLIST_LOCK_TTL_SECONDS = 900
_CASE_AUTO_CLOSE_LOCK_TTL_SECONDS = 1800
# Comfortably past one pass. The scheduler's own poll is 300s and a pass
@@ -554,6 +556,29 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"Set APPROVAL_EXPIRY_ENABLED=true to sweep them"
)
# WS4.4 — insider-watchlist sweep. Expiry hygiene for every tenant
# (a watchlist row promised to end; silence would break that promise),
# plus the HR door for tenants whose policy row opted in.
insider_watchlist_task: asyncio.Task | None = None
if settings.INSIDER_WATCHLIST_SWEEP_ENABLED:
try:
insider_watchlist_task = asyncio.create_task(
_run_guarded_scheduler_worker(
job_name="insider_watchlist_sweep",
ttl_seconds=_INSIDER_WATCHLIST_LOCK_TTL_SECONDS,
worker=run_insider_watchlist_sweep,
),
name="insider_watchlist_sweep_worker",
)
logger.info("insider_watchlist_sweep worker started")
except Exception as exc:
logger.warning("insider_watchlist_sweep worker failed to start", error=str(exc))
else:
logger.info(
"insider_watchlist_sweep disabled; expired watchlist rows will keep elevating "
"and the HR door will not run. Set INSIDER_WATCHLIST_SWEEP_ENABLED=true to sweep"
)
case_auto_close_task: asyncio.Task | None = None
if settings.CASE_AUTO_CLOSE_ENABLED:
try:
@@ -747,6 +772,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("autonomy_drift worker shutdown error", error=type(exc).__name__)
if insider_watchlist_task is not None and not insider_watchlist_task.done():
insider_watchlist_task.cancel()
try:
await insider_watchlist_task
except asyncio.CancelledError:
logger.debug("insider_watchlist_sweep worker cancelled during shutdown")
except Exception as exc:
logger.warning("insider_watchlist_sweep worker shutdown error", error=type(exc).__name__)
if retention_purge_task is not None and not retention_purge_task.done():
retention_purge_task.cancel()
try:
+7 -1
View File
@@ -21,7 +21,12 @@ from app.models.detection_rule import DetectionRule
from app.models.easm import ExternalAsset, ExternalAssetDrift
from app.models.identity_graph import AlertIdentityLink, IdentityEdge, IdentityNode
from app.models.inbox import TenantInboxToken
from app.models.insider_threat import InsiderIndicator, InsiderPeerGroup, UserRiskProfile
from app.models.insider_threat import (
InsiderIndicator,
InsiderPeerGroup,
InsiderWatchlistPolicy,
UserRiskProfile,
)
from app.models.institutional_memory import InstitutionalMemory
from app.models.investigation import (
InvestigationArtifact,
@@ -88,6 +93,7 @@ __all__ = [
"IdentityNode",
"InsiderIndicator",
"InsiderPeerGroup",
"InsiderWatchlistPolicy",
"InstitutionalMemory",
"InvestigationRun",
"InvestigationEvent",
+28
View File
@@ -32,6 +32,10 @@ class UserRiskProfile(Base):
watchlist_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
watchlisted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
watchlisted_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
# WS4.4 (migration 168): a watchlist row is never indefinite, and it
# records which door listed it ('manual' | 'hr_sync').
watchlist_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
watchlist_source: Mapped[str] = mapped_column(String(20), default="manual")
# timestamps
last_evaluated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
@@ -72,3 +76,27 @@ class InsiderPeerGroup(Base):
description: Mapped[str | None] = mapped_column(Text, nullable=True)
criteria: Mapped[dict] = mapped_column(JSONB, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
class InsiderWatchlistPolicy(Base):
"""Per-tenant insider-watchlist policy (WS4.4, migration 168).
One row per tenant; an absent row means every automation is off. The
HR door (`hr_sync_enabled`) watches `workforce_members` for departing
members and auto-watchlists them — automation a tenant opts into.
"""
__tablename__ = "insider_watchlist_policies"
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), primary_key=True)
hr_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
default_expiry_days: Mapped[int] = mapped_column(Integer, default=30, nullable=False)
hr_grace_days: Mapped[int] = mapped_column(Integer, default=14, nullable=False)
lookback_days: Mapped[int] = mapped_column(Integer, default=30, nullable=False)
updated_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(UTC),
onupdate=lambda: datetime.now(UTC),
)
@@ -0,0 +1,592 @@
"""Departing-employee / insider watchlist: expiry, elevation, lookback.
What existed and what was missing
---------------------------------
`user_risk_profiles` has carried `is_watchlisted` / `watchlist_reason` /
`watchlisted_at` / `watchlisted_by` since migration 014, and the console
PATCH wrote them — and that was the whole feature. Nothing consumed the
flag: no alert was elevated, nothing expired, and no review of the user's
recent activity happened. A watchlist nothing reads is a checkbox, not a
control.
The three halves this module adds (WS4.4):
* **Expiry.** A watchlist row is never indefinite: watchlisting requires
`expires_at` in the future, and an expired row stops elevating — first
because the managed-rule rebuild excludes it, and belt-and-braces because
the sweep worker flips `is_watchlisted` off and rebuilds. Migration 168
backfills the handful of legacy rows with a 90-day horizon rather than
letting "no expiry" keep meaning "forever".
* **Elevation through the existing business-context path.** The brief is
explicit: do not invent a parallel elevation mechanism. Watchlisted
identities become *managed* business-context rules — a tag rule and a
severity-floor rule per identity — written to the machine-owned
``managed_yaml`` column beside the analyst's verbatim ``yaml_text``
(same row, same engine, same application point in the auto-triage
worker). The floor can only raise `info`/`low` to `medium`; a `high` or
`critical` alert is never touched, because `set_severity` is a fixed
assignment and a blanket rule would *downgrade* the alerts that matter
most. The two-column split exists because ``yaml_text`` is the analyst's
artifact (kept verbatim for round-tripping); a console save must never
clobber machine rules and a watchlist change must never clobber analyst
comments.
* **Lookback.** Watchlisting an identity (either door) opens a review
case over the trailing window: exfil-shaped activity from the lake
(uploads, shares, forwards, downloads, exports — matched by reviewable
patterns, counted per event type so the analyst sees exactly what
matched) plus the identity's recent alerts from Postgres. An
unreachable lake is reported as *could not check*, never as zero.
Two doors onto the list
-----------------------
Manual (console PATCH, reason + expiry required) and HR-driven: when a
tenant opts in (``insider_watchlist_policies.hr_sync_enabled``, default
off), the sweep watches ``workforce_members`` — the HR store the
connectors service already syncs — for members whose status is
``terminated`` or whose ``end_date`` falls inside the horizon, and
watchlists the matching identity with the HR fact as the reason and
``end_date + grace`` as the expiry. The HR door never shortens or
overwrites a manual row.
"""
from __future__ import annotations
import logging
import uuid
from dataclasses import dataclass, field
from datetime import UTC, date, datetime, timedelta
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.clickhouse import execute_lake_query
from app.models.case import Case
from app.models.insider_threat import InsiderIndicator, UserRiskProfile
from app.services import case_status
logger = logging.getLogger("aisoc.insider_watchlist")
#: The severity floor only ever raises these. `set_severity` is a fixed
#: assignment, so a rule without this guard would downgrade `high` and
#: `critical` alerts — the opposite of elevation.
FLOOR_FROM = ("info", "low")
FLOOR_TO = "medium"
#: Exfil-shaped event types, matched case-insensitively as substrings of
#: `raw_events.action`. Deliberately a reviewable module-level constant:
#: the set is a heuristic, and a heuristic hidden inside SQL is one nobody
#: audits. Counts are grouped per concrete event type so the analyst sees
#: what actually matched, not only that "something" did.
EXFIL_EVENT_PATTERNS: tuple[str, ...] = (
"%upload%",
"%download%",
"%share%",
"%anonymouslink%",
"%forward%",
"%export%",
"%masscopy%",
)
#: Hard bounds for the lookback window and result size.
MAX_LOOKBACK_DAYS = 90
_LOOKBACK_ROW_LIMIT = 200
# ---------------------------------------------------------------------------
# Managed-rule generation (pure)
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class WatchEntry:
"""One active watchlisted identity, as the rule generator sees it."""
ref: str
reason: str
expires_at: datetime
def _yaml_quote(value: str) -> str:
"""Single-quote a scalar for YAML (the grammar's values are strings).
YAML single-quoted style has exactly one escape: a quote doubles.
Newlines cannot appear in a single-quoted flow scalar, so they are
flattened to spaces — a watchlist reason is display text, not markup.
"""
flat = " ".join(str(value).split())
return "'" + flat.replace("'", "''") + "'"
def managed_rules_yaml(entries: list[WatchEntry]) -> str:
"""Render the managed rule document for the active watchlist.
Two rules per identity, ids prefixed ``managed-insider-watchlist-`` so
they are recognisable in the console's diff view and in the applier's
matched-rule list:
* a tag rule (every alert for the identity carries
``insider-watchlist``, which the triage prompt and routing can read),
* a severity floor (`info`/`low` → `medium`) that never touches
`medium` and above.
"""
if not entries:
return ""
lines: list[str] = [
"# Managed by the insider watchlist — do not edit by hand.",
"# Regenerated whenever the watchlist changes; expired rows are excluded.",
"rules:",
]
for n, entry in enumerate(sorted(entries, key=lambda e: e.ref)):
ref = _yaml_quote(entry.ref)
desc = _yaml_quote(f"Insider watchlist: {entry.reason} (expires {entry.expires_at.date().isoformat()})")
lines += [
f" - id: managed-insider-watchlist-{n}-tag",
f" description: {desc}",
" priority: 10",
" when:",
" field: username",
" op: eq",
f" value: {ref}",
" then:",
" tag: insider-watchlist",
f" - id: managed-insider-watchlist-{n}-floor",
f" description: {desc}",
" priority: 11",
" when:",
" all:",
" - field: username",
" op: eq",
f" value: {ref}",
" - field: severity",
" op: in",
f" value: [{', '.join(FLOOR_FROM)}]",
" then:",
f" set_severity: {FLOOR_TO}",
]
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------------------
# Rebuild: watchlist rows -> managed_yaml upsert
# ---------------------------------------------------------------------------
_ACTIVE_WATCHLIST_SQL = text(
"""
SELECT external_user_ref, watchlist_reason, watchlist_expires_at
FROM user_risk_profiles
WHERE tenant_id = :tenant_id
AND is_watchlisted = TRUE
AND watchlist_expires_at IS NOT NULL
AND watchlist_expires_at > :now
AND external_user_ref IS NOT NULL
AND external_user_ref != ''
ORDER BY external_user_ref
"""
)
_UPSERT_MANAGED_YAML_SQL = text(
"""
INSERT INTO aisoc_business_context_rule_sets (tenant_id, yaml_text, managed_yaml, updated_at)
VALUES (:tenant_id, '', :managed_yaml, :now)
ON CONFLICT (tenant_id)
DO UPDATE SET managed_yaml = EXCLUDED.managed_yaml, updated_at = EXCLUDED.updated_at
"""
)
async def rebuild_managed_rules(db: AsyncSession, tenant_id: uuid.UUID) -> int:
"""Regenerate the tenant's managed rules from the active watchlist.
Returns the number of identities covered. Expired, cleared and
ref-less rows are excluded *here*, which is what makes expiry
effective even before the sweep flips the flag: the applier re-reads
the row on a short TTL, so a rebuild is the moment elevation stops.
"""
now = datetime.now(UTC)
rows = (await db.execute(_ACTIVE_WATCHLIST_SQL, {"tenant_id": str(tenant_id), "now": now})).fetchall()
entries = [WatchEntry(ref=r[0], reason=r[1] or "watchlisted", expires_at=r[2]) for r in rows]
await db.execute(
_UPSERT_MANAGED_YAML_SQL,
{"tenant_id": str(tenant_id), "managed_yaml": managed_rules_yaml(entries), "now": now},
)
return len(entries)
# ---------------------------------------------------------------------------
# The two doors
# ---------------------------------------------------------------------------
class WatchlistValidationError(ValueError):
"""Raised with a message naming exactly which requirement is unmet."""
def validate_watchlist_request(*, reason: str | None, expires_at: datetime | None, now: datetime | None = None) -> None:
"""Watchlisting requires a reason and a future expiry — never indefinite."""
now = now or datetime.now(UTC)
if not (reason or "").strip():
raise WatchlistValidationError("watchlisting requires a reason")
if expires_at is None:
raise WatchlistValidationError("watchlisting requires expires_at — a watchlist row is never indefinite")
if expires_at.tzinfo is None:
raise WatchlistValidationError("expires_at must be timezone-aware")
if expires_at <= now:
raise WatchlistValidationError("expires_at must be in the future")
@dataclass
class WatchlistOutcome:
profile_id: uuid.UUID
elevation_active: bool
#: Populated when elevation could NOT be set up, naming why — an
#: identity with no `external_user_ref` has nothing for the username
#: rule to match, and saying so beats silently not elevating.
elevation_gap: str | None = None
lookback_case_id: uuid.UUID | None = None
async def apply_watchlist(
db: AsyncSession,
profile: UserRiskProfile,
*,
reason: str,
expires_at: datetime,
source: str,
actor_id: uuid.UUID | None,
lookback_days: int = 30,
) -> WatchlistOutcome:
"""Watchlist a profile: set the row, rebuild managed rules, run lookback.
The lookback runs on the transition onto the list (not on refresh), so
re-saving a watchlist does not open a duplicate review case.
"""
validate_watchlist_request(reason=reason, expires_at=expires_at)
was_watchlisted = bool(profile.is_watchlisted)
now = datetime.now(UTC)
profile.is_watchlisted = True
profile.watchlist_reason = reason
profile.watchlist_expires_at = expires_at
profile.watchlist_source = source
profile.watchlisted_at = now
if actor_id is not None:
profile.watchlisted_by = actor_id
await db.flush()
tenant_id = profile.tenant_id
await rebuild_managed_rules(db, tenant_id)
ref = (profile.external_user_ref or "").strip()
gap = (
None
if ref
else (
"no external_user_ref on the profile — the managed username rule has "
"nothing to match, so alerts for this identity are not elevated"
)
)
case_id: uuid.UUID | None = None
if not was_watchlisted:
case_id = await run_lookback(
db,
tenant_id=tenant_id,
profile=profile,
reason=reason,
lookback_days=lookback_days,
)
return WatchlistOutcome(
profile_id=profile.id,
elevation_active=bool(ref),
elevation_gap=gap,
lookback_case_id=case_id,
)
async def clear_watchlist(db: AsyncSession, profile: UserRiskProfile) -> None:
"""Take a profile off the list and withdraw its managed rules."""
profile.is_watchlisted = False
profile.watchlist_expires_at = None
await db.flush()
await rebuild_managed_rules(db, profile.tenant_id)
# ---------------------------------------------------------------------------
# Lookback: the review case
# ---------------------------------------------------------------------------
_LOOKBACK_LAKE_SQL = """
SELECT action, connector_type, count() AS events,
min(event_time) AS first_seen, max(event_time) AS last_seen
FROM aisoc.raw_events
WHERE tenant_id = %(tenant_id)s
AND event_time >= %(window_start)s
AND lower(user_name) = %(ref)s
AND multiSearchAnyCaseInsensitive(action, %(patterns)s)
GROUP BY action, connector_type
ORDER BY events DESC
LIMIT %(limit)s
"""
_LOOKBACK_ALERTS_SQL = text(
"""
SELECT count(*) FROM alerts
WHERE tenant_id = :tenant_id
AND created_at >= :window_start
AND EXISTS (
SELECT 1 FROM jsonb_array_elements_text(coalesce(affected_users, '[]'::jsonb)) AS u(name)
WHERE lower(u.name) = :ref
)
"""
)
async def run_lookback(
db: AsyncSession,
*,
tenant_id: uuid.UUID,
profile: UserRiskProfile,
reason: str,
lookback_days: int,
) -> uuid.UUID | None:
"""Open the departing-employee review case from real rows.
Two sources, each reported honestly:
* the lake — exfil-shaped event counts per concrete event type; an
unreachable lake is recorded as ``could_not_check`` with the error
class named, never as zero;
* the alerts table — how many alerts already name this identity in
the window.
The case is opened even when both sources are quiet: the point of the
watchlist is that a human reviews the departure, and "nothing matched
in the window we could see" is a reviewable statement.
"""
days = max(1, min(int(lookback_days), MAX_LOOKBACK_DAYS))
window_start = datetime.now(UTC) - timedelta(days=days)
ref = (profile.external_user_ref or "").strip().lower()
lake_rows: list[tuple] = []
could_not_check: list[str] = []
if not ref:
could_not_check.append("lake: no external_user_ref to match on")
could_not_check.append("alerts: no external_user_ref to match on")
else:
try:
result = await execute_lake_query(
_LOOKBACK_LAKE_SQL,
params={
"tenant_id": str(tenant_id),
"window_start": window_start,
"ref": ref,
"patterns": [p.strip("%") for p in EXFIL_EVENT_PATTERNS],
"limit": _LOOKBACK_ROW_LIMIT,
},
)
lake_rows = [tuple(r) for r in result.rows]
except Exception as exc: # noqa: BLE001 — an unreachable lake is not an empty one
logger.warning(
"insider_watchlist.lookback_lake_unavailable tenant=%s error=%s",
tenant_id,
type(exc).__name__,
)
could_not_check.append(f"lake: could not be queried ({type(exc).__name__}) — activity is unknown, not zero")
alert_count: int | None = None
if ref:
try:
alert_count = (
await db.execute(
_LOOKBACK_ALERTS_SQL,
{"tenant_id": str(tenant_id), "window_start": window_start, "ref": ref},
)
).scalar_one()
except Exception as exc: # noqa: BLE001 — a failed count is unknown, not zero
logger.warning(
"insider_watchlist.lookback_alerts_failed tenant=%s error=%s",
tenant_id,
type(exc).__name__,
)
could_not_check.append(f"alerts: count failed ({type(exc).__name__})")
display = profile.external_user_ref or str(profile.id)
summary_lines = [
f"Departing-employee review for {display!r} — {reason}.",
f"Lookback window: last {days} day(s).",
"",
]
if lake_rows:
summary_lines.append("Exfil-shaped activity in the lake (per event type):")
for event_type, connector_type, events, first_seen, last_seen in lake_rows[:25]:
summary_lines.append(f"- {event_type} via {connector_type}: {events} event(s), {first_seen} → {last_seen}")
elif ref and not any(c.startswith("lake:") for c in could_not_check):
summary_lines.append(
"Exfil-shaped activity in the lake: none matched the reviewed patterns "
f"({', '.join(p.strip('%') for p in EXFIL_EVENT_PATTERNS)}) in the window."
)
summary_lines.append(
f"Alerts naming this identity in the window: {alert_count}"
if alert_count is not None
else "Alerts naming this identity in the window: not measured"
)
for item in could_not_check:
summary_lines.append(f"Could not check — {item}")
case = Case(
id=uuid.uuid4(),
tenant_id=tenant_id,
case_number=f"INSIDER-{uuid.uuid4().hex[:8].upper()}",
title=f"Departing-employee review: {display}",
description="\n".join(summary_lines),
case_type="insider_review",
priority="medium",
severity="medium",
status=case_status.NEW,
tags=["insider-watchlist", f"profile:{profile.id}"],
)
db.add(case)
await db.flush()
db.add(
InsiderIndicator(
tenant_id=tenant_id,
profile_id=profile.id,
indicator_type="departure_lookback",
severity="medium",
description=f"Lookback over {days} day(s) at watchlisting; see case {case.case_number}.",
evidence={
"window_days": days,
"lake_event_types": [{"event_type": r[0], "connector_type": r[1], "events": int(r[2])} for r in lake_rows],
"alerts_in_window": alert_count,
"could_not_check": could_not_check,
"patterns": list(EXFIL_EVENT_PATTERNS),
"case_id": str(case.id),
},
)
)
await db.flush()
return case.id
# ---------------------------------------------------------------------------
# Sweep: expiry + the HR door
# ---------------------------------------------------------------------------
_EXPIRE_SQL = text(
"""
UPDATE user_risk_profiles
SET is_watchlisted = FALSE
WHERE is_watchlisted = TRUE
AND watchlist_expires_at IS NOT NULL
AND watchlist_expires_at <= :now
RETURNING tenant_id
"""
)
_HR_TENANTS_SQL = text(
"""
SELECT tenant_id, hr_grace_days, default_expiry_days, lookback_days
FROM insider_watchlist_policies
WHERE hr_sync_enabled = TRUE
"""
)
_HR_DEPARTING_SQL = text(
"""
SELECT external_id, email, display_name, status, end_date
FROM workforce_members
WHERE tenant_id = :tenant_id
AND (
status = 'terminated'
OR (end_date IS NOT NULL AND end_date <= :horizon)
)
AND email IS NOT NULL AND email != ''
"""
)
_PROFILE_BY_REF_SQL = text(
"""
SELECT id FROM user_risk_profiles
WHERE tenant_id = :tenant_id AND lower(external_user_ref) = :ref
LIMIT 1
"""
)
#: How far ahead of a known last day the HR door starts watching.
HR_HORIZON_DAYS = 30
@dataclass
class SweepSummary:
expired: int = 0
hr_watchlisted: int = 0
tenants_rebuilt: int = 0
hr_tenants: int = 0
errors: list[str] = field(default_factory=list)
async def sweep_expired(db: AsyncSession) -> SweepSummary:
"""Flip expired rows off the list and rebuild each affected tenant."""
summary = SweepSummary()
now = datetime.now(UTC)
rows = (await db.execute(_EXPIRE_SQL, {"now": now})).fetchall()
summary.expired = len(rows)
for tenant_id in {r[0] for r in rows}:
await rebuild_managed_rules(db, tenant_id)
summary.tenants_rebuilt += 1
return summary
async def sweep_hr(db: AsyncSession) -> SweepSummary:
"""The HR door: watchlist departing workforce members, per opted-in tenant.
Idempotent: an identity already on the list (either source) is left
exactly as it is — in particular the HR door never shortens a manual
expiry. The reason names the HR fact; the expiry is the member's last
day plus the tenant's grace, or now plus grace when HR has a
termination status with no date.
"""
summary = SweepSummary()
tenants = (await db.execute(_HR_TENANTS_SQL)).fetchall()
summary.hr_tenants = len(tenants)
now = datetime.now(UTC)
for tenant_id, grace_days, _default_days, lookback_days in tenants:
horizon: date = (now + timedelta(days=HR_HORIZON_DAYS)).date()
try:
members = (await db.execute(_HR_DEPARTING_SQL, {"tenant_id": str(tenant_id), "horizon": horizon})).fetchall()
except Exception as exc: # noqa: BLE001 — a tenant without the HR table synced
summary.errors.append(f"{tenant_id}: workforce query failed ({type(exc).__name__})")
continue
for _external_id, email, display_name, status, end_date in members:
ref = email.strip().lower()
existing_id = (await db.execute(_PROFILE_BY_REF_SQL, {"tenant_id": str(tenant_id), "ref": ref})).scalar_one_or_none()
profile: UserRiskProfile | None = None
if existing_id is not None:
profile = await db.get(UserRiskProfile, existing_id)
if profile is not None and profile.is_watchlisted:
continue # already listed — never overwrite, never shorten
if profile is None:
profile = UserRiskProfile(
tenant_id=tenant_id,
external_user_ref=email.strip(),
)
db.add(profile)
await db.flush()
last_day = end_date or now.date()
expires = datetime(last_day.year, last_day.month, last_day.day, tzinfo=UTC) + timedelta(days=max(int(grace_days), 1))
if expires <= now:
expires = now + timedelta(days=max(int(grace_days), 1))
reason = f"HR: {display_name or email} status {status!r}, last day {end_date.isoformat() if end_date else 'unknown'}"
await apply_watchlist(
db,
profile,
reason=reason,
expires_at=expires,
source="hr_sync",
actor_id=None,
lookback_days=int(lookback_days),
)
summary.hr_watchlisted += 1
return summary
@@ -0,0 +1,73 @@
"""Insider-watchlist sweep: expiry hygiene plus the HR door (WS4.4).
Two jobs on one tick, deliberately asymmetric about defaults:
* **Expiry** runs for every tenant unconditionally, like
``approval_expiry``. It only touches our own rows — flipping
``is_watchlisted`` off where ``watchlist_expires_at`` has passed and
regenerating that tenant's managed rules — and the alternative is a
watchlist entry that promised to end and then silently didn't. Hygiene
of a deadline we recorded is not automation a tenant opts into.
* **The HR door** runs only for tenants whose
``insider_watchlist_policies.hr_sync_enabled`` row says so (default
off): it reads ``workforce_members`` — the HR store the connectors
service already syncs — and watchlists departing members with the HR
fact as the reason and last-day-plus-grace as the expiry. Watching the
HR store and acting on it *is* automation, so it is per-tenant opt-in.
Both halves are idempotent: an expired row flips once, and the HR door
never touches an identity already on the list (in particular it never
shortens a manual expiry).
"""
from __future__ import annotations
import asyncio
import logging
from app.core.config import settings
from app.db.database import AsyncSessionLocal
from app.services.insider_watchlist import sweep_expired, sweep_hr
from app.workers._tick_failures import TickFailures
logger = logging.getLogger("aisoc.insider_watchlist_sweep")
async def run_once() -> dict[str, int | list[str]]:
"""One tick. Returns the summary so tests and logs see the same truth."""
async with AsyncSessionLocal() as db:
expired = await sweep_expired(db)
hr = await sweep_hr(db)
await db.commit()
summary: dict[str, int | list[str]] = {
"expired": expired.expired,
"tenants_rebuilt": expired.tenants_rebuilt,
"hr_tenants": hr.hr_tenants,
"hr_watchlisted": hr.hr_watchlisted,
"errors": hr.errors,
}
if expired.expired or hr.hr_watchlisted or hr.errors:
logger.info("insider_watchlist_sweep %s", summary)
return summary
async def run_forever() -> None:
"""Tick until cancelled. Owned by the API ``lifespan``, like the others."""
interval = max(int(getattr(settings, "INSIDER_WATCHLIST_SWEEP_INTERVAL_SECONDS", 900)), 60)
logger.info("insider_watchlist_sweep started interval=%ds", interval)
failures = TickFailures("insider_watchlist_sweep", logger)
try:
while True:
try:
await run_once()
except asyncio.CancelledError:
raise
except Exception as exc: # pragma: no cover - defensive
failures.record_failure(exc)
else:
failures.record_success()
await asyncio.sleep(interval)
except asyncio.CancelledError:
logger.info("insider_watchlist_sweep stopped")
raise
@@ -0,0 +1,134 @@
-- WS4.4 — the insider watchlist becomes a control instead of a checkbox.
--
-- `user_risk_profiles.is_watchlisted` has existed since migration 014 and the
-- console wrote it — and that was the whole feature. Nothing consumed the
-- flag (no elevation, no expiry, no review), so watchlisting a departing
-- employee changed nothing anywhere. Three schema changes make the halves
-- real; the behaviour lives in `app/services/insider_watchlist.py`.
--
-- 1. Expiry on the watchlist row. A watchlist is never indefinite: the
-- service refuses a new row without a future `watchlist_expires_at`, and
-- the sweep worker flips expired rows off. Legacy watchlisted rows (if
-- any) are backfilled with a 90-day horizon rather than letting the
-- absence of a column keep meaning "forever".
--
-- 2. A machine-owned rule document beside the analyst's. Elevation reuses
-- the existing business-context path (same engine, same application point
-- in the auto-triage worker) — but `yaml_text` is the analyst's verbatim
-- artifact, kept unparsed so their comments and ordering round-trip. A
-- console save must never clobber machine rules and a watchlist change
-- must never clobber analyst comments, so the managed rules get their own
-- column. The applier parses both and concatenates.
--
-- 3. A per-tenant policy row for the HR door, default OFF: watching the HR
-- store (`workforce_members`, migration 131) and auto-watchlisting
-- departing members is automation a tenant opts into.
-- lane allocation: migration 168 (orchestrator lane)
-- ── 1. expiry + source on the profile row ──────────────────────────────────
ALTER TABLE user_risk_profiles
ADD COLUMN IF NOT EXISTS watchlist_expires_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS watchlist_source VARCHAR(20) NOT NULL DEFAULT 'manual';
-- Two doors only. A CHECK rather than an enum type: the vocabulary is tiny
-- and a bad value should be a write error naming the column.
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = 'user_risk_profiles_watchlist_source_check'
) THEN
ALTER TABLE user_risk_profiles
ADD CONSTRAINT user_risk_profiles_watchlist_source_check
CHECK (watchlist_source IN ('manual', 'hr_sync'));
END IF;
END $$;
-- Backfill: any row watchlisted before this migration had no expiry at all.
-- 90 days from now, not from `watchlisted_at` — a row listed eight months
-- ago would otherwise expire retroactively the moment the sweep first runs,
-- silently dropping elevation nobody decided to drop.
UPDATE user_risk_profiles
SET watchlist_expires_at = NOW() + INTERVAL '90 days'
WHERE is_watchlisted = TRUE AND watchlist_expires_at IS NULL;
COMMENT ON COLUMN user_risk_profiles.watchlist_expires_at IS
'When this watchlist row stops elevating. Required on every new row — '
'a watchlist is never indefinite. The sweep worker flips expired rows.';
COMMENT ON COLUMN user_risk_profiles.watchlist_source IS
'Which door listed this identity: ''manual'' (console, reason required) '
'or ''hr_sync'' (the HR store said they are leaving).';
-- The sweep's scan: watchlisted rows and their deadlines.
CREATE INDEX IF NOT EXISTS idx_user_risk_profiles_watchlist_expiry
ON user_risk_profiles (watchlist_expires_at)
WHERE is_watchlisted;
-- ── 2. the machine-owned half of the rule set ──────────────────────────────
ALTER TABLE aisoc_business_context_rule_sets
ADD COLUMN IF NOT EXISTS managed_yaml TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN aisoc_business_context_rule_sets.managed_yaml IS
'Machine-managed rules (insider watchlist elevation), regenerated whole '
'on every watchlist change. Never hand-edited; never touched by the '
'console save path, which owns yaml_text. The triage applier parses '
'both documents and applies the union.';
-- ── 3. the HR door, per tenant, default off ────────────────────────────────
CREATE TABLE IF NOT EXISTS insider_watchlist_policies (
tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
-- Watching the HR store and auto-watchlisting is automation the tenant
-- opts into; a fresh row (and an absent row) means OFF.
hr_sync_enabled BOOLEAN NOT NULL DEFAULT FALSE,
-- Days of elevation a manual watchlist gets when the console does not
-- pick a date explicitly.
default_expiry_days INTEGER NOT NULL DEFAULT 30
CHECK (default_expiry_days BETWEEN 1 AND 365),
-- Elevation continues this many days past a departing member's last day.
hr_grace_days INTEGER NOT NULL DEFAULT 14
CHECK (hr_grace_days BETWEEN 1 AND 90),
-- How far back the departure review looks.
lookback_days INTEGER NOT NULL DEFAULT 30
CHECK (lookback_days BETWEEN 1 AND 90),
updated_by UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
COMMENT ON TABLE insider_watchlist_policies IS
'Per-tenant insider-watchlist policy. hr_sync_enabled gates the HR door '
'(workforce_members -> auto-watchlist); everything is off until a row '
'says otherwise.';
-- RLS, mirroring triage_questions (154): the API writes under a bound
-- tenant GUC; the sweep worker reads every opted-in tenant under no GUC,
-- so the unbound arm is load-bearing in both expressions.
ALTER TABLE insider_watchlist_policies ENABLE ROW LEVEL SECURITY;
ALTER TABLE insider_watchlist_policies FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS insider_watchlist_policies_tenant ON insider_watchlist_policies;
CREATE POLICY insider_watchlist_policies_tenant ON insider_watchlist_policies
USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)
WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON insider_watchlist_policies TO aisoc_app';
END IF;
END $$;
-- Rollback
-- ────────
-- ALTER TABLE user_risk_profiles
-- DROP CONSTRAINT IF EXISTS user_risk_profiles_watchlist_source_check,
-- DROP COLUMN IF EXISTS watchlist_expires_at,
-- DROP COLUMN IF EXISTS watchlist_source;
-- ALTER TABLE aisoc_business_context_rule_sets DROP COLUMN IF EXISTS managed_yaml;
-- DROP TABLE IF EXISTS insider_watchlist_policies;
--
-- Dropping managed_yaml withdraws every managed elevation at once; the
-- authored yaml_text is untouched either way.
+47
View File
@@ -0,0 +1,47 @@
# Managed by the insider watchlist — do not edit by hand.
# Regenerated whenever the watchlist changes; expired rows are excluded.
rules:
- id: managed-insider-watchlist-0-tag
description: 'Insider watchlist: resignation accepted (expires 2030-01-15)'
priority: 10
when:
field: username
op: eq
value: 'mallory@example.com'
then:
tag: insider-watchlist
- id: managed-insider-watchlist-0-floor
description: 'Insider watchlist: resignation accepted (expires 2030-01-15)'
priority: 11
when:
all:
- field: username
op: eq
value: 'mallory@example.com'
- field: severity
op: in
value: [info, low]
then:
set_severity: medium
- id: managed-insider-watchlist-1-tag
description: 'Insider watchlist: HR: status ''terminated'' last day 2030-01-01 (expires 2030-01-15)'
priority: 10
when:
field: username
op: eq
value: 'o''brien@example.com'
then:
tag: insider-watchlist
- id: managed-insider-watchlist-1-floor
description: 'Insider watchlist: HR: status ''terminated'' last day 2030-01-01 (expires 2030-01-15)'
priority: 11
when:
all:
- field: username
op: eq
value: 'o''brien@example.com'
- field: severity
op: in
value: [info, low]
then:
set_severity: medium
@@ -0,0 +1,341 @@
"""The insider watchlist is a control, not a checkbox (WS4.4).
What was wrong
--------------
``user_risk_profiles.is_watchlisted`` existed since migration 014 and the
console PATCH wrote it — and nothing consumed it. No alert was elevated, no
row ever expired, and nothing reviewed the identity's recent activity. The
docstring family: a feature whose whole implementation was its storage.
What this asserts
-----------------
* **Elevation goes through the existing business-context path.** The managed
document `managed_rules_yaml` generates parses with the same loader the
console uses, and evaluated by the real engine it tags the identity's
alerts and raises `info`/`low` to `medium` — and **never touches** `high`
or `critical`, because `set_severity` is a fixed assignment and a blanket
rule would downgrade exactly the alerts that matter.
* Adversarial reasons (quotes, newlines, YAML syntax) stay data.
* Watchlisting requires a reason and a future expiry — never indefinite.
* The lookback reports an unreachable lake as *could not check*, never as
zero, and opens the review case either way.
* The HR door is idempotent and never overwrites an existing row.
* The generated document is pinned to a golden fixture that the agents-side
test parses with *its* independent loader, so the two implementations of
the grammar cannot drift apart silently.
The Postgres truths (expiry exclusion inside the SQL, RLS, the upsert that
preserves the analyst's yaml_text) live in
``tests/isolation/test_insider_watchlist_live.py``.
"""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.services import insider_watchlist as svc
from app.services.business_context.engine import BusinessContextEngine
from app.services.business_context.models import load_rules_from_yaml
TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
GOLDEN = Path(__file__).parent / "fixtures" / "managed_rules_golden.yaml"
_FUTURE = datetime(2030, 1, 15, tzinfo=UTC)
def _entries() -> list[svc.WatchEntry]:
return [
svc.WatchEntry(ref="mallory@example.com", reason="resignation accepted", expires_at=_FUTURE),
svc.WatchEntry(ref="o'brien@example.com", reason="HR: status 'terminated'\nlast day 2030-01-01", expires_at=_FUTURE),
]
def _evaluate(yaml_doc: str, alert: dict[str, Any]) -> Any:
engine = BusinessContextEngine()
engine.replace(TENANT, load_rules_from_yaml(yaml_doc))
return engine.evaluate(TENANT, alert)
class TestManagedRuleGeneration:
def test_parses_with_the_consoles_own_loader(self) -> None:
rules = load_rules_from_yaml(svc.managed_rules_yaml(_entries()))
assert len(rules) == 4 # tag + floor per identity
assert all(r.id.startswith("managed-insider-watchlist-") for r in rules)
def test_tags_and_floors_a_low_severity_alert(self) -> None:
doc = svc.managed_rules_yaml(_entries())
result = _evaluate(doc, {"username": "mallory@example.com", "severity": "low"})
assert result.after.get("severity") == "medium"
assert "insider-watchlist" in (result.after.get("tags") or [])
@pytest.mark.parametrize("severity", ["high", "critical", "medium"])
def test_never_downgrades(self, severity: str) -> None:
"""`set_severity` is a fixed assignment; the guard is the `in` clause."""
doc = svc.managed_rules_yaml(_entries())
result = _evaluate(doc, {"username": "mallory@example.com", "severity": severity})
assert result.after.get("severity") == severity
def test_other_identities_are_untouched(self) -> None:
doc = svc.managed_rules_yaml(_entries())
result = _evaluate(doc, {"username": "alice@example.com", "severity": "low"})
assert result.after.get("severity") == "low"
assert not result.matched_rule_ids
def test_adversarial_reason_stays_data(self) -> None:
"""A reason containing YAML syntax must not become structure."""
hostile = svc.WatchEntry(
ref="eve@example.com",
reason="x'\nrules:\n - id: injected\n then: {suppress: true}",
expires_at=_FUTURE,
)
rules = load_rules_from_yaml(svc.managed_rules_yaml([hostile]))
assert len(rules) == 2
assert not any(r.id == "injected" for r in rules)
def test_no_entries_means_an_empty_document(self) -> None:
assert svc.managed_rules_yaml([]) == ""
def test_matches_the_golden_fixture_the_agents_side_parses(self) -> None:
"""The agents service re-implements the grammar (separate image, no
shared import). The golden fixture is the bridge: this test pins the
generator to it, and the agents suite parses the same bytes with its
own loader. Regenerate deliberately when generation changes:
python -c "import sys; sys.path.insert(0, 'services/api');
from app.services.insider_watchlist import *;
print(managed_rules_yaml([...]), end='')" > .../managed_rules_golden.yaml
"""
assert GOLDEN.read_text() == svc.managed_rules_yaml(_entries())
class TestValidation:
def test_reason_is_required(self) -> None:
with pytest.raises(svc.WatchlistValidationError, match="reason"):
svc.validate_watchlist_request(reason=" ", expires_at=_FUTURE)
def test_expiry_is_required(self) -> None:
with pytest.raises(svc.WatchlistValidationError, match="never indefinite"):
svc.validate_watchlist_request(reason="leaving", expires_at=None)
def test_expiry_must_be_future(self) -> None:
past = datetime.now(UTC) - timedelta(days=1)
with pytest.raises(svc.WatchlistValidationError, match="future"):
svc.validate_watchlist_request(reason="leaving", expires_at=past)
def test_expiry_must_be_aware(self) -> None:
with pytest.raises(svc.WatchlistValidationError, match="timezone-aware"):
svc.validate_watchlist_request(
reason="leaving",
expires_at=datetime(2030, 1, 1), # noqa: DTZ001 — the point
)
def _profile(ref: str | None = "mallory@example.com", watchlisted: bool = False) -> MagicMock:
profile = MagicMock()
profile.id = uuid.uuid4()
profile.tenant_id = TENANT
profile.external_user_ref = ref
profile.is_watchlisted = watchlisted
return profile
def _session_for_lookback(alert_count: int | None = 3) -> MagicMock:
"""A session whose execute() answers the alerts count and records adds."""
db = MagicMock()
db.added = []
db.add = lambda obj: db.added.append(obj)
db.flush = AsyncMock()
async def _execute(stmt: Any, params: dict | None = None) -> MagicMock:
result = MagicMock()
text = str(getattr(stmt, "text", stmt))
if "count(*) FROM alerts" in text:
if alert_count is None:
raise RuntimeError("alerts table unavailable")
result.scalar_one.return_value = alert_count
else: # the watchlist select / managed-yaml upsert
result.fetchall.return_value = []
return result
db.execute = AsyncMock(side_effect=_execute)
return db
class TestLookback:
@pytest.mark.asyncio
async def test_unreachable_lake_is_could_not_check_never_zero(self, monkeypatch: pytest.MonkeyPatch) -> None:
async def _boom(sql: str, **kwargs: Any) -> Any:
raise ConnectionError("lake down")
monkeypatch.setattr(svc, "execute_lake_query", _boom)
db = _session_for_lookback(alert_count=3)
profile = _profile()
case_id = await svc.run_lookback(db, tenant_id=TENANT, profile=profile, reason="leaving", lookback_days=30)
assert case_id is not None
case = next(o for o in db.added if getattr(o, "case_type", "") == "insider_review")
assert "unknown, not zero" in case.description
assert "Could not check" in case.description
indicator = next(o for o in db.added if getattr(o, "indicator_type", "") == "departure_lookback")
assert any("lake" in item for item in indicator.evidence["could_not_check"])
assert indicator.evidence["alerts_in_window"] == 3
@pytest.mark.asyncio
async def test_lake_counts_are_rendered_per_event_type(self, monkeypatch: pytest.MonkeyPatch) -> None:
async def _rows(sql: str, **kwargs: Any) -> Any:
result = MagicMock()
result.rows = [("FileUploaded", "m365_audit", 41, "2030-01-01", "2030-01-10")]
return result
monkeypatch.setattr(svc, "execute_lake_query", _rows)
db = _session_for_lookback(alert_count=0)
case_id = await svc.run_lookback(db, tenant_id=TENANT, profile=_profile(), reason="leaving", lookback_days=30)
assert case_id is not None
case = next(o for o in db.added if getattr(o, "case_type", "") == "insider_review")
assert "FileUploaded via m365_audit: 41 event(s)" in case.description
@pytest.mark.asyncio
async def test_a_refless_profile_reports_both_gaps(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(svc, "execute_lake_query", AsyncMock())
db = _session_for_lookback()
await svc.run_lookback(db, tenant_id=TENANT, profile=_profile(ref=None), reason="leaving", lookback_days=30)
indicator = next(o for o in db.added if getattr(o, "indicator_type", "") == "departure_lookback")
gaps = indicator.evidence["could_not_check"]
assert any(g.startswith("lake:") for g in gaps)
assert any(g.startswith("alerts:") for g in gaps)
svc.execute_lake_query.assert_not_called() # type: ignore[attr-defined, union-attr] # the monkeypatched AsyncMock
class TestApplyWatchlist:
@pytest.mark.asyncio
async def test_the_transition_rebuilds_and_runs_lookback(self, monkeypatch: pytest.MonkeyPatch) -> None:
rebuild = AsyncMock(return_value=1)
lookback = AsyncMock(return_value=uuid.uuid4())
monkeypatch.setattr(svc, "rebuild_managed_rules", rebuild)
monkeypatch.setattr(svc, "run_lookback", lookback)
db = MagicMock()
db.flush = AsyncMock()
profile = _profile(watchlisted=False)
outcome = await svc.apply_watchlist(
db,
profile,
reason="resignation",
expires_at=_FUTURE,
source="manual",
actor_id=uuid.uuid4(),
lookback_days=30,
)
rebuild.assert_awaited_once()
lookback.assert_awaited_once()
assert outcome.elevation_active is True
assert outcome.elevation_gap is None
assert profile.watchlist_source == "manual"
assert profile.watchlist_expires_at == _FUTURE
@pytest.mark.asyncio
async def test_a_refresh_does_not_open_a_second_case(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(svc, "rebuild_managed_rules", AsyncMock(return_value=1))
lookback = AsyncMock()
monkeypatch.setattr(svc, "run_lookback", lookback)
db = MagicMock()
db.flush = AsyncMock()
outcome = await svc.apply_watchlist(
db,
_profile(watchlisted=True),
reason="extended",
expires_at=_FUTURE,
source="manual",
actor_id=None,
lookback_days=30,
)
lookback.assert_not_awaited()
assert outcome.lookback_case_id is None
@pytest.mark.asyncio
async def test_a_refless_identity_names_the_elevation_gap(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(svc, "rebuild_managed_rules", AsyncMock(return_value=0))
monkeypatch.setattr(svc, "run_lookback", AsyncMock(return_value=None))
db = MagicMock()
db.flush = AsyncMock()
outcome = await svc.apply_watchlist(
db,
_profile(ref=""),
reason="leaving",
expires_at=_FUTURE,
source="manual",
actor_id=None,
lookback_days=30,
)
assert outcome.elevation_active is False
assert "external_user_ref" in (outcome.elevation_gap or "")
class TestHrDoor:
@pytest.mark.asyncio
async def test_an_already_listed_identity_is_never_touched(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""The HR door must not overwrite — in particular never shorten — a
manual watchlist row."""
apply_mock = AsyncMock()
monkeypatch.setattr(svc, "apply_watchlist", apply_mock)
existing_id = uuid.uuid4()
listed_profile = _profile(watchlisted=True)
db = MagicMock()
db.flush = AsyncMock()
db.get = AsyncMock(return_value=listed_profile)
async def _execute(stmt: Any, params: dict | None = None) -> MagicMock:
result = MagicMock()
text = str(getattr(stmt, "text", stmt))
if "FROM insider_watchlist_policies" in text:
result.fetchall.return_value = [(TENANT, 14, 30, 30)]
elif "FROM workforce_members" in text:
result.fetchall.return_value = [("w-1", "mallory@example.com", "Mallory", "terminated", None)]
elif "FROM user_risk_profiles" in text:
result.scalar_one_or_none.return_value = existing_id
return result
db.execute = AsyncMock(side_effect=_execute)
summary = await svc.sweep_hr(db)
assert summary.hr_tenants == 1
assert summary.hr_watchlisted == 0
apply_mock.assert_not_awaited()
@pytest.mark.asyncio
async def test_a_departing_member_is_listed_with_the_hr_fact(self, monkeypatch: pytest.MonkeyPatch) -> None:
apply_mock = AsyncMock()
monkeypatch.setattr(svc, "apply_watchlist", apply_mock)
db = MagicMock()
db.flush = AsyncMock()
db.get = AsyncMock(return_value=None)
async def _execute(stmt: Any, params: dict | None = None) -> MagicMock:
result = MagicMock()
text = str(getattr(stmt, "text", stmt))
if "FROM insider_watchlist_policies" in text:
result.fetchall.return_value = [(TENANT, 14, 30, 45)]
elif "FROM workforce_members" in text:
result.fetchall.return_value = [
("w-2", "Leaver@Example.com", "Lea Ver", "terminated", datetime(2030, 1, 1, tzinfo=UTC).date())
]
elif "FROM user_risk_profiles" in text:
result.scalar_one_or_none.return_value = None
return result
db.execute = AsyncMock(side_effect=_execute)
summary = await svc.sweep_hr(db)
assert summary.hr_watchlisted == 1
assert apply_mock.await_args is not None
kwargs = apply_mock.await_args.kwargs
assert kwargs["source"] == "hr_sync"
assert "terminated" in kwargs["reason"]
assert "2030-01-01" in kwargs["reason"]
assert kwargs["lookback_days"] == 45
# expiry = last day + grace(14), never in the past
assert kwargs["expires_at"] == datetime(2030, 1, 1, tzinfo=UTC) + timedelta(days=14)
@@ -0,0 +1,291 @@
"""The insider watchlist's Postgres truths, against real Postgres (WS4.4).
Why this has to be live
-----------------------
* Expiry exclusion lives **inside the SQL** — `rebuild_managed_rules`'s
SELECT refuses expired and ref-less rows in its WHERE clause, which a
stubbed session always gets right by construction.
* The two-document contract is upsert behaviour: the console save updates
`yaml_text` and must leave `managed_yaml` alone; the watchlist upsert
updates `managed_yaml` and must leave `yaml_text` alone. Both are
`ON CONFLICT` arms only a real unique constraint exercises.
* The `watchlist_source` vocabulary is a CHECK constraint.
* RLS on `insider_watchlist_policies` is judged under the DML-only
`aisoc_app` role, which a superuser silently bypasses — including the
unbound arm the sweep worker depends on.
Against the pre-change tree every test fails at setup: `managed_yaml`,
`watchlist_expires_at` and `insider_watchlist_policies` do not exist.
"""
from __future__ import annotations
import os
import sys
import uuid
from datetime import UTC, datetime, timedelta
from pathlib import Path
import pytest
import pytest_asyncio
pytestmark = [
pytest.mark.asyncio(loop_scope="module"),
pytest.mark.skipif(
not os.environ.get("ISOLATION_INSIDER_WATCHLIST_DSN", "").strip(),
reason="ISOLATION_INSIDER_WATCHLIST_DSN is not set; this suite needs a live Postgres",
),
]
_API = Path(__file__).resolve().parents[2] / "services" / "api"
if str(_API) not in sys.path:
sys.path.insert(0, str(_API))
TENANT_A = uuid.uuid4()
TENANT_B = uuid.uuid4()
def _dsn(name: str) -> str:
return os.environ[name].strip()
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def pools():
import asyncpg
admin = await asyncpg.connect(_dsn("ISOLATION_INSIDER_WATCHLIST_ADMIN_DSN"))
app = await asyncpg.connect(_dsn("ISOLATION_INSIDER_WATCHLIST_DSN"))
suffix = uuid.uuid4().hex[:8]
for tenant, label in ((TENANT_A, f"iw-live-a-{suffix}"), (TENANT_B, f"iw-live-b-{suffix}")):
await admin.execute(
"INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $2) ON CONFLICT (id) DO NOTHING",
tenant,
label,
)
yield admin, app
for tenant in (TENANT_A, TENANT_B):
await admin.execute("DELETE FROM insider_watchlist_policies WHERE tenant_id = $1", tenant)
await admin.execute("DELETE FROM workforce_members WHERE tenant_id = $1", tenant)
await admin.execute("DELETE FROM aisoc_business_context_rule_sets WHERE tenant_id = $1", tenant)
await admin.execute("DELETE FROM insider_indicators WHERE tenant_id = $1", tenant)
await admin.execute("DELETE FROM user_risk_profiles WHERE tenant_id = $1", tenant)
await admin.execute("DELETE FROM aisoc_cases WHERE tenant_id = $1 AND case_type = 'insider_review'", tenant)
await admin.execute("DELETE FROM tenants WHERE id = $1", tenant)
await admin.close()
await app.close()
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def session_factory():
"""A real AsyncSession over the app DSN, so the suite drives the service's
own functions (and therefore its own SQL) rather than re-typing it."""
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
dsn = _dsn("ISOLATION_INSIDER_WATCHLIST_DSN").replace("postgresql://", "postgresql+asyncpg://")
engine = create_async_engine(dsn, poolclass=None)
factory = async_sessionmaker(engine, expire_on_commit=False)
yield factory
await engine.dispose()
async def _bind(conn, tenant: uuid.UUID) -> None:
await conn.execute("SELECT set_config('app.current_tenant_id', $1, false)", str(tenant))
async def _add_profile(
admin,
tenant: uuid.UUID,
ref: str | None,
*,
watchlisted: bool = True,
expires_in_days: int = 30,
) -> uuid.UUID:
pid = uuid.uuid4()
await admin.execute(
"""
INSERT INTO user_risk_profiles
(id, tenant_id, external_user_ref, is_watchlisted, watchlist_reason,
watchlist_expires_at, watchlist_source)
VALUES ($1, $2, $3, $4, 'live fixture', $5, 'manual')
""",
pid,
tenant,
ref,
watchlisted,
datetime.now(UTC) + timedelta(days=expires_in_days),
)
return pid
async def test_rebuild_excludes_expired_and_refless_rows(pools, session_factory):
"""The exclusion is the SQL's WHERE clause — the live half of expiry."""
from app.services.insider_watchlist import rebuild_managed_rules
admin, _ = pools
await _add_profile(admin, TENANT_A, "active@example.com", expires_in_days=30)
await _add_profile(admin, TENANT_A, "expired@example.com", expires_in_days=-1)
await _add_profile(admin, TENANT_A, None) # ref-less: nothing to match
await _add_profile(admin, TENANT_A, "cleared@example.com", watchlisted=False)
async with session_factory() as db:
covered = await rebuild_managed_rules(db, TENANT_A)
await db.commit()
assert covered == 1
doc = await admin.fetchval("SELECT managed_yaml FROM aisoc_business_context_rule_sets WHERE tenant_id = $1", TENANT_A)
assert "active@example.com" in doc
assert "expired@example.com" not in doc
assert "cleared@example.com" not in doc
async def test_the_two_documents_never_clobber_each_other(pools, session_factory):
"""Console saves own yaml_text; the watchlist owns managed_yaml."""
from app.services.insider_watchlist import rebuild_managed_rules
admin, _ = pools
# Console-style save first (the endpoint's own upsert shape).
await admin.execute(
"""
INSERT INTO aisoc_business_context_rule_sets (tenant_id, yaml_text, enabled, updated_at)
VALUES ($1, 'rules: [] # analyst draft', TRUE, now())
ON CONFLICT (tenant_id) DO UPDATE SET
yaml_text = EXCLUDED.yaml_text, enabled = EXCLUDED.enabled, updated_at = EXCLUDED.updated_at
""",
TENANT_A,
)
async with session_factory() as db:
await rebuild_managed_rules(db, TENANT_A)
await db.commit()
row = await admin.fetchrow(
"SELECT yaml_text, managed_yaml FROM aisoc_business_context_rule_sets WHERE tenant_id = $1",
TENANT_A,
)
assert row["yaml_text"] == "rules: [] # analyst draft", "the watchlist upsert must not touch yaml_text"
managed_before = row["managed_yaml"]
assert "active@example.com" in managed_before
# A second console save must leave the managed document alone.
await admin.execute(
"""
INSERT INTO aisoc_business_context_rule_sets (tenant_id, yaml_text, enabled, updated_at)
VALUES ($1, 'rules: [] # edited draft', TRUE, now())
ON CONFLICT (tenant_id) DO UPDATE SET
yaml_text = EXCLUDED.yaml_text, enabled = EXCLUDED.enabled, updated_at = EXCLUDED.updated_at
""",
TENANT_A,
)
after = await admin.fetchval("SELECT managed_yaml FROM aisoc_business_context_rule_sets WHERE tenant_id = $1", TENANT_A)
assert after == managed_before, "the console save must not touch managed_yaml"
async def test_sweep_flips_expired_rows_and_rebuilds(pools, session_factory):
from app.services.insider_watchlist import sweep_expired
admin, _ = pools
pid = await _add_profile(admin, TENANT_B, "leaver@example.com", expires_in_days=-2)
async with session_factory() as db:
summary = await sweep_expired(db)
await db.commit()
assert summary.expired >= 1
flag = await admin.fetchval("SELECT is_watchlisted FROM user_risk_profiles WHERE id = $1", pid)
assert flag is False
doc = await admin.fetchval("SELECT managed_yaml FROM aisoc_business_context_rule_sets WHERE tenant_id = $1", TENANT_B)
assert doc == "" or "leaver@example.com" not in doc
async def test_watchlist_source_vocabulary_is_a_check_constraint(pools):
import asyncpg
admin, _ = pools
with pytest.raises(asyncpg.exceptions.CheckViolationError):
await admin.execute(
"""
INSERT INTO user_risk_profiles (id, tenant_id, watchlist_source)
VALUES ($1, $2, 'carrier-pigeon')
""",
uuid.uuid4(),
TENANT_A,
)
async def test_policy_rls_under_the_app_role(pools):
"""A bound session sees its own tenant only; the unbound arm (the sweep
worker's shape) sees every row — both judged under aisoc_app."""
admin, app = pools
for tenant in (TENANT_A, TENANT_B):
await admin.execute(
"""
INSERT INTO insider_watchlist_policies (tenant_id, hr_sync_enabled)
VALUES ($1, TRUE)
ON CONFLICT (tenant_id) DO UPDATE SET hr_sync_enabled = TRUE
""",
tenant,
)
role = await app.fetchval("SELECT current_user")
bypass = await app.fetchval("SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user")
assert bypass is False, f"role {role!r} bypasses RLS; this test would prove nothing"
await _bind(app, TENANT_A)
rows = await app.fetch("SELECT tenant_id FROM insider_watchlist_policies")
assert {r["tenant_id"] for r in rows} == {TENANT_A}
await app.execute("SELECT set_config('app.current_tenant_id', '', false)")
rows = await app.fetch("SELECT tenant_id FROM insider_watchlist_policies")
assert {TENANT_A, TENANT_B} <= {r["tenant_id"] for r in rows}
async def test_hr_door_lists_a_departing_member_end_to_end(pools, session_factory):
"""workforce_members row + opted-in policy -> watchlist row + managed rule
+ review case, driven through the service's own sweep."""
from app.services.insider_watchlist import sweep_hr
admin, _ = pools
await admin.execute(
"""
INSERT INTO workforce_members (tenant_id, connector_type, external_id, email, display_name, status, end_date)
VALUES ($1, 'workday', 'hr-1', 'departing@example.com', 'Dep Arting', 'terminated', CURRENT_DATE)
ON CONFLICT DO NOTHING
""",
TENANT_B,
)
async with session_factory() as db:
summary = await sweep_hr(db)
await db.commit()
assert summary.hr_watchlisted >= 1, f"sweep summary: {summary}"
row = await admin.fetchrow(
"""
SELECT is_watchlisted, watchlist_source, watchlist_expires_at
FROM user_risk_profiles
WHERE tenant_id = $1 AND lower(external_user_ref) = 'departing@example.com'
""",
TENANT_B,
)
assert row is not None and row["is_watchlisted"] is True
assert row["watchlist_source"] == "hr_sync"
assert row["watchlist_expires_at"] > datetime.now(UTC)
doc = await admin.fetchval("SELECT managed_yaml FROM aisoc_business_context_rule_sets WHERE tenant_id = $1", TENANT_B)
assert "departing@example.com" in doc
case = await admin.fetchrow(
"""
SELECT title, description FROM aisoc_cases
WHERE tenant_id = $1 AND case_type = 'insider_review'
ORDER BY created_at DESC LIMIT 1
""",
TENANT_B,
)
assert case is not None
assert "departing@example.com" in case["title"]
# The lake is absent in this harness: the case must say so, never zero.
assert "unknown, not zero" in case["description"] or "Could not check" in case["description"]
# Idempotence: a second sweep lists nobody twice.
async with session_factory() as db:
second = await sweep_hr(db)
await db.commit()
assert second.hr_watchlisted == 0