mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
feat(lake): archive tier, rehydration, portability and scoped legal holds (WS2) (#2007)
## What WS2 of the gap-closure program: the long-term security data lake. The lake's 400-day TTL is a hard ceiling nothing exempts — everything older exists only if it was exported first. This PR makes that export real, verified, rehydratable and portable, and narrows legal holds to their own rows. ## WS2.1 — Archive tier (migration 170) Closed `(tenant, month)` partitions export to the tenant's **own S3-compatible bucket** as Parquet with a **signed manifest** (row count, event-time bounds, schema + OCSF version, per-file SHA-256; the evidence-bundle signer). Design decisions that carry the honesty: - **The database that owns the rows writes the files**: export, count re-read and SHA-256 all run *inside ClickHouse* (`INSERT INTO FUNCTION s3(...) Parquet`, `s3(...,'Parquet')`, `s3(...,'RawBLOB')`) — no second data path whose row semantics could drift. - **"Exported" is a claim; "verified" means the bucket was read back and matched.** A corrupted object fails naming what differed — including the sharp case a count check cannot see: a *valid* Parquet with the same rows and different bytes, caught by the checksum leg alone (proven live, and pinned by the negative control). - An **open month is refused** (it is still receiving rows — the connector-window lesson applied to archival). UUID/IP columns export as strings (ClickHouse cannot write UUID to Parquet; found live, Code 50). - Per-tenant policy, **default off**; bucket credentials vault-encrypted, decrypted at export time; ClickHouse masks `s3()` credential positions in its query log (documented reliance). **WORM** is recorded as *declared by operator, not verified by this service* — never implied verified. - Hourly sweep worker (`lake_archive_sweep`) exports closed months for opted-in tenants, verifies, and expires rehydrations; bounded per tick. ## WS2.2 — Rehydration (migration 171) **Estimate first** (bytes/files/months from the manifests; retrieval cost **null unless `AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB` is configured** — never an invented figure), then an audited load (**requester + reason required**) into an expiring scratch table `aisoc.rehydrated_<8hex>`. The lake explorer queries it through its own rewriter: the allowlist gained a **regex-pinned arm** that cannot widen (non-hex/overlong/foreign-schema names refused) and injects the same tenant predicate `raw_events` gets — live-proven: owner reads 3 rows, another tenant reads 0. The loader **evicts foreign-tenant rows after landing** because a bucket is not a tenancy boundary. (ClickHouse 23.8's Parquet pushdown cannot compare file-schema strings with UUID hints in either direction — Code 169, found live — so tenancy is enforced post-landing by mutation, not by pushdown.) ## WS2.3 — Portability (migration 171) Range export to a bucket **the tenant names** (per-request credentials, never persisted): one Parquet object per month + signed manifest + schema document. The gate proves "no AiSOC code": **DuckDB** opens the object over s3 and its count matches the signed manifest. ## WS2.4 — Scoped legal holds (migration 172) Holds gain `covers_from`/`covers_until`. A `user`/`host`/`ip` hold now **exempts exactly its own rows** from the retention purge — the Postgres alert DELETE through the affected-* arrays, the ClickHouse mutation through user/hostname/IP columns (addresses compared as addresses: `toIPv6OrDefault`, because IPv6 columns render v4 mapped), each within the hold's window, **every value a bind**. The rest of the tenant purges on schedule. This deliberately supersedes the recorded whole-tenant freeze — the superseded test now pins the narrowing — while a tenant-wide hold still freezes everything, because that is what it means. The lake TTL stays untouchable: a hold older than 400 days is only satisfiable through the archive tier, and the new **retention attestation** (`GET /lake/retention-attestation`) says so — each tier from its own store, "not measured" where a store cannot answer. ## Testing - **`tests/isolation/test_lake_archive_live.py` — 9 cases on real ClickHouse 23.8 + MinIO + Postgres** (new `integration.yml` step provisions all three; no-skip guard): export→manifest→verify green path; open-month refusal; garbage corruption fails; **same-count content swap caught by checksum alone**; rehydration lands tenant-scoped and explorer-queryable; estimate honesty; DuckDB portability; **held rows survive the live purge (5→3) while unheld rows delete**; attestation from real stores. - `services/api/tests/test_lake_archive.py` — 20 unit cases (paths/windows, destination refusals, cost honesty both ways, scratch-table namespace pinning, explorer-arm cannot widen, hold-exemption composers never interpolate a value, IPv6-as-address, `covers()` window semantics). - Full API suite **5,577 passed**; lake_sql + retention suites green with the superseded freeze test rewritten to pin the narrowing. **Negative controls (applied, observed failing, restored):** 1. Disabling the SHA-256 comparison → `test_a_same_count_content_swap_is_caught_by_the_checksum_alone` fails (the count leg cannot see it). 2. Removing the exemption composition from the alerts purge → the live hold test fails at 5 ≠ 3 (held rows purged). ## Gates route_auth OK · route_tenant_scope OK · tenant_query_predicates OK (ratchet 80 → **85**, five sweep statements recorded with the approval_expiry/sessions enumeration shapes) · module_reachability OK · migration_numbering OK (170–172, allocated block) · ORM parity OK · mypy baseline OK (which caught real API mismatches: `emit_audit` signature, `CredentialVault` construction — fixed, not ignored) · ruff clean · claim matrix **+3 GATED rows, 410 — 401/9/0** recomputed by the script · readme_gates OK · OpenAPI regenerated (additive) · README's "not a SIEM replacement" sentence updated to the proven scope · new ops doc `operations/lake-archive` in the sidebar. ## Could not verify - GCS/Azure arms: the client interface is S3-compatible-first; GCS interop/Azure need their own arms (stated in docs, not claimed). - WORM/Object-Lock: bucket properties this service does not manage; recorded as a declaration and reported as such, never as verified. - The sweep worker's scheduling is wired through the same guarded-lease path as the other workers but was exercised via `run_once` in the live suite, not through a multi-hour soak.
This commit is contained in:
@@ -119,6 +119,7 @@ jobs:
|
||||
# *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 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'
|
||||
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_lake_archive_live.py services/api/app/services/lake_archive.py services/api/app/workers/retention_purge.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
|
||||
@@ -1162,6 +1163,73 @@ jobs:
|
||||
|| { 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; }
|
||||
# WS2. The archive tier against real engines: the export, the count
|
||||
# read-back and the SHA-256 all run INSIDE ClickHouse (s3() Parquet /
|
||||
# RawBLOB), corruption must fail verification BY NAME — including the
|
||||
# sharper case, a valid same-count object whose only tell is the
|
||||
# checksum — the rehydrated scratch table must be queryable through
|
||||
# the explorer's own rewriter under the tenant predicate, DuckDB (no
|
||||
# AiSOC code) must read the portability export, and a scoped legal
|
||||
# hold must exempt exactly its own rows from the live Postgres purge.
|
||||
- name: The archive tier exports, verifies, rehydrates and ports (live ClickHouse + MinIO)
|
||||
working-directory: services/api
|
||||
env:
|
||||
LAKE_ARCHIVE_LIVE_CH_HOST: localhost
|
||||
LAKE_ARCHIVE_LIVE_CH_PORT: '59124'
|
||||
LAKE_ARCHIVE_LIVE_CH_USER: aisoc
|
||||
LAKE_ARCHIVE_LIVE_CH_PASSWORD: clickhouse_ci_secret
|
||||
LAKE_ARCHIVE_LIVE_S3_ENDPOINT_FOR_CH: http://archive-s3:4566
|
||||
LAKE_ARCHIVE_LIVE_S3_ENDPOINT: http://localhost:59000
|
||||
LAKE_ARCHIVE_LIVE_S3_ACCESS: archiveak
|
||||
LAKE_ARCHIVE_LIVE_S3_SECRET: archive_s3_ci_secret
|
||||
# aisoc-db-role: owner — fixtures only. The suite seeds tenants, alerts and holds, which the DML-only runtime role cannot.
|
||||
LAKE_ARCHIVE_LIVE_PG_ADMIN_DSN: postgresql://aisoc:aisoc_ci_secret@localhost:5432/aisoc
|
||||
CLICKHOUSE_HOST: localhost
|
||||
CLICKHOUSE_PORT: '59124'
|
||||
CLICKHOUSE_USER: aisoc
|
||||
CLICKHOUSE_PASSWORD: clickhouse_ci_secret
|
||||
CLICKHOUSE_DATABASE: aisoc
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker network create archive-net || true
|
||||
# MinIO's image lives on quay with a hub mirror, and BOTH registries
|
||||
# have answered transient denials on hosted runners (quay a 401 on
|
||||
# the manifest HEAD, hub a rate-limit shaped "repository does not
|
||||
# exist"). Try each, three times, before concluding anything.
|
||||
# The S3 store is LocalStack from AWS's own public ECR: MinIO's
|
||||
# public images vanished from quay (401) and hub (not-found) in the
|
||||
# same week, and public.ecr.aws is the registry hosted runners pull
|
||||
# without rate limits — the same reasoning the postgres steps use.
|
||||
docker run -d --name archive-s3 --network archive-net -p 59000:4566 \
|
||||
-e SERVICES=s3 -e EAGER_SERVICE_LOADING=1 \
|
||||
public.ecr.aws/localstack/localstack:3
|
||||
docker run -d --name archive-ch --network archive-net -p 59124:9000 \
|
||||
-e CLICKHOUSE_USER=aisoc -e CLICKHOUSE_PASSWORD=clickhouse_ci_secret -e CLICKHOUSE_DB=aisoc \
|
||||
clickhouse/clickhouse-server:23.8
|
||||
for i in $(seq 1 30); do
|
||||
docker exec archive-ch clickhouse-client --user aisoc --password clickhouse_ci_secret -q 'SELECT 1' >/dev/null 2>&1 && break
|
||||
sleep 2
|
||||
[ "$i" = 30 ] && { echo '::error::clickhouse never came up'; docker logs --tail 40 archive-ch; exit 1; }
|
||||
done
|
||||
for i in $(seq 1 60); do
|
||||
curl -sf http://localhost:59000/_localstack/health | grep -q '"s3": *"\(running\|available\)"' && break
|
||||
sleep 2
|
||||
[ "$i" = 60 ] && { echo '::error::the S3 store never came up'; docker logs --tail 40 archive-s3; exit 1; }
|
||||
done
|
||||
docker exec -i archive-ch clickhouse-client --user aisoc --password clickhouse_ci_secret --multiquery < ../../services/api/clickhouse/001_init.sql
|
||||
for b in tenant-archive tenant-export; do
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' --aws-sigv4 'aws:amz:us-east-1:s3' \
|
||||
--user "$LAKE_ARCHIVE_LIVE_S3_ACCESS:$LAKE_ARCHIVE_LIVE_S3_SECRET" -X PUT "http://localhost:59000/$b")
|
||||
case "$code" in 200|409) : ;; *) echo "::error::bucket $b creation failed ($code)"; exit 1;; esac
|
||||
done
|
||||
pip install --quiet duckdb clickhouse-driver
|
||||
python -m pytest ../../tests/isolation/test_lake_archive_live.py -v --tb=short -rs | tee /tmp/lake-archive.log
|
||||
grep -qE '[1-9][0-9]* passed' /tmp/lake-archive.log \
|
||||
|| { echo "::error::the archive live suite did not report any passing test"; exit 1; }
|
||||
! grep -qE 'skipped' /tmp/lake-archive.log \
|
||||
|| { echo "::error::the archive live suite skipped a test; its stores must all be provisioned"; exit 1; }
|
||||
docker rm -f archive-minio archive-ch || true
|
||||
docker network rm archive-net || true
|
||||
|
||||
# Depth 2 wave 2, 1.1. The properties here are schema facts a stand-in
|
||||
# store always gets right by construction: the
|
||||
|
||||
@@ -185,3 +185,4 @@ services/api/tests/test_evidence_bundle.py:generic-api-key:26
|
||||
# rule's id so regeneration cannot renumber it. The scanner's key/value
|
||||
# heuristic reads the pair as an api key; it is a rule identifier in a
|
||||
# generated lock file.
|
||||
|
||||
|
||||
@@ -182,6 +182,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
ownership; a dry run strips credentials so the vendor sees zero
|
||||
requests; nothing-matched is a failure, not a silent success. Executor
|
||||
arms 168 → 172.
|
||||
- **The archive tier: long-term retention in an open format** (WS2 of the
|
||||
gap-closure program; migrations 170–172). The lake's 400-day TTL is a
|
||||
hard ceiling nothing exempts, so everything older exists only if it was
|
||||
exported first — and now it can be, trustworthily. **Archive** (WS2.1):
|
||||
closed `(tenant, month)` partitions export to the tenant's own
|
||||
S3-compatible bucket as Parquet with a signed manifest (row count,
|
||||
event-time bounds, schema + OCSF version, per-file SHA-256), written and
|
||||
verified **inside ClickHouse** (`s3()` Parquet / RawBLOB) so there is no
|
||||
second data path; "exported" is a claim, "verified" means the bucket was
|
||||
read back and matched — a corrupted object fails by name, including the
|
||||
sharp case a count check cannot see (same rows, different bytes: the
|
||||
checksum leg alone catches it, proven live). Per-tenant policy, default
|
||||
off; credentials vault-encrypted; WORM reported as *declared by
|
||||
operator, not verified*. **Rehydration** (WS2.2): estimate first (bytes,
|
||||
files, months from manifests; retrieval cost **null unless a price is
|
||||
configured**), then an audited load — requester and reason required —
|
||||
into an expiring scratch table the lake explorer queries under the same
|
||||
tenant predicate `raw_events` gets, with foreign-tenant rows evicted
|
||||
after landing because a bucket is not a tenancy boundary.
|
||||
**Portability** (WS2.3): Parquet + signed manifest + schema document to
|
||||
a bucket the tenant names, readable with no AiSOC code — the CI gate
|
||||
opens it with DuckDB. **Scoped legal holds** (WS2.4): holds gain a time
|
||||
window, and a `user`/`host`/`ip` hold now **exempts exactly its own
|
||||
rows** from the retention purge (Postgres via the affected-* arrays,
|
||||
ClickHouse via user/hostname/IP columns, every value a bind) while the
|
||||
rest of the tenant purges on schedule — superseding the recorded
|
||||
whole-tenant freeze, which a tenant-wide hold still gets because that is
|
||||
what it means. A per-tenant retention **attestation** reports each tier
|
||||
from its own store, "not measured" where a store cannot answer. A new
|
||||
hourly sweep worker exports, verifies and expires; 9 live cases against
|
||||
real ClickHouse + MinIO + Postgres wired into `integration.yml`.
|
||||
|
||||
- **Every open case has an accountable owner and a next-action clock**
|
||||
(completing the resolution-not-escalation workstream). An owner is a person
|
||||
|
||||
@@ -210,7 +210,7 @@ Agents triage alerts and investigate incidents. What they can and cannot do:
|
||||
|
||||
## What AiSOC is not
|
||||
|
||||
- **Not a drop-in SIEM replacement.** It correlates and investigates; it does not replace long-term log retention and compliance search.
|
||||
- **Not a drop-in SIEM replacement.** It correlates and investigates. The event lake holds up to 400 days hot, and an opt-in archive tier exports closed months to your own S3-compatible bucket as signed, verified Parquet — rehydratable for investigation, exportable for portability (readable with any Parquet reader; the gate proves it with DuckDB). Compliance search over decades of archives remains SIEM territory.
|
||||
- **Not able to see telemetry you have not connected.** There is no discovery.
|
||||
- **Not autonomous by default.** Response requires explicit policy authorization and a human approver.
|
||||
- **Demo and sample incidents are not real incidents**, and benchmark numbers are substrate self-consistency measures, not live agent accuracy — labelled as such wherever published.
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
|
||||
- **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 **413 rows — 404 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 **416 rows — 407 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
|
||||
|
||||
@@ -34,7 +34,7 @@ and says so.
|
||||
| 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: 404 rows
|
||||
The last row is the one worth reading first. It is the honest index: 407 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
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Archive tier: long-term retention in an open format
|
||||
|
||||
The event lake (`aisoc.raw_events`, ClickHouse) holds at most **400 days**
|
||||
— the TTL is a hard ceiling nothing exempts. Everything older exists only
|
||||
if it was exported first. The archive tier is that export: closed calendar
|
||||
months written to an S3-compatible bucket you own, as **Parquet with a
|
||||
signed manifest**, verified by read-back, rehydratable for investigation,
|
||||
and portable by design.
|
||||
|
||||
## How it works
|
||||
|
||||
- **The database that owns the rows writes the files.** Exports run inside
|
||||
ClickHouse (`INSERT INTO FUNCTION s3(...) ... FORMAT Parquet`); there is
|
||||
no second data path whose row semantics could drift from the lake's own.
|
||||
One object per `(tenant, month)`, under
|
||||
`aisoc-archive/tenant=<id>/month=<YYYY-MM>/events.parquet`. Only
|
||||
**closed** months export — the current month is still receiving rows.
|
||||
- **The manifest is signed** (row count, event-time bounds, schema and
|
||||
OCSF version, per-file SHA-256) with the same evidence-bundle signer the
|
||||
rest of the product uses.
|
||||
- **"Exported" is a claim; "verified" means the bucket was read back and
|
||||
matched** — the row count from the Parquet object and the SHA-256 of the
|
||||
raw bytes, both computed by ClickHouse. A corrupted object fails
|
||||
verification naming what differed, including the sharp case: a valid
|
||||
Parquet with the same row count and different bytes is caught by the
|
||||
checksum alone.
|
||||
- UUID and IP columns are exported as strings (ClickHouse cannot write
|
||||
UUID to Parquet, and a string id is the more portable spelling); the
|
||||
rehydration loader casts them back.
|
||||
|
||||
## Configuration
|
||||
|
||||
`PUT /api/v1/lake/archive-policy` (settings:write):
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `enabled` | Default **off**. Nothing exports until a tenant turns it on. |
|
||||
| `s3_endpoint`, `s3_bucket`, `s3_region` | Your bucket. Path-style addressing. |
|
||||
| `s3_access_key`, `s3_secret_key` | Vault-encrypted at rest; decrypted only at export time. ClickHouse masks `s3()` credential positions in its query log. |
|
||||
| `archive_years` | What the attestation reports against. The sweep never deletes archive objects; expiry of archived data is your bucket's lifecycle policy. |
|
||||
| `worm_declared` | A declaration that the bucket carries an Object Lock default retention. Reported by the attestation as *declared by operator, not verified by this service* — this service does not manage bucket properties. |
|
||||
|
||||
The sweep worker (`lake_archive_sweep`, hourly) exports closed months for
|
||||
opted-in tenants, verifies exported partitions, and drops expired
|
||||
rehydration tables. `POST /api/v1/lake/archive-partitions/run` triggers a
|
||||
single month explicitly; `POST /api/v1/lake/archive-partitions/{id}/verify`
|
||||
re-verifies one.
|
||||
|
||||
## Rehydration
|
||||
|
||||
`POST /api/v1/lake/rehydrations` with a time range (and optionally a
|
||||
`connector_type` filter) returns an **estimate first** — bytes, files and
|
||||
months from the manifests; retrieval cost **only when the deployment
|
||||
configured a price** (`AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB`), otherwise
|
||||
`null` with the reason stated. `confirm=true` loads the covered months into
|
||||
a scratch table (`aisoc.rehydrated_<id>`) with an expiry (default 7 days),
|
||||
queryable through the lake explorer under the same tenant predicate
|
||||
`raw_events` gets. Every rehydration records the requester and a required
|
||||
reason. The loader never trusts the bucket as a tenancy boundary: foreign
|
||||
rows are evicted after landing.
|
||||
|
||||
## Portability
|
||||
|
||||
`POST /api/v1/lake/portability-exports` writes a range to a bucket **you
|
||||
name** (credentials supplied per request, used for the job, never
|
||||
persisted): one Parquet object per month plus a signed manifest and schema
|
||||
document. The export is readable with no AiSOC code — the CI gate opens it
|
||||
with DuckDB and matches the manifest's row counts.
|
||||
|
||||
## Scoped legal holds and the attestation
|
||||
|
||||
Legal holds carry a subject (`user`, `host`, `ip`, or tenant-wide) and,
|
||||
since migration 172, an optional time window. A hold on a user, host or IP
|
||||
**exempts exactly its own rows** from the retention purge — both the
|
||||
Postgres alert purge and the ClickHouse lake mutation — while the rest of
|
||||
the tenant purges on schedule. A tenant-wide hold still freezes the whole
|
||||
tenant's purge, because that is what it means. The lake TTL ceiling is
|
||||
untouched and untouchable: a hold older than 400 days is only satisfiable
|
||||
through the archive tier, which is one of the reasons it exists.
|
||||
|
||||
`GET /api/v1/lake/retention-attestation` reports what is retained per tier,
|
||||
the oldest row per tier, how many archive partitions are verified, the
|
||||
WORM declaration state, and every live hold with whether it narrows or
|
||||
freezes — each figure from its own store, with *not measured* where a
|
||||
store cannot answer.
|
||||
@@ -219,6 +219,7 @@ const sidebars: SidebarsConfig = {
|
||||
"compliance/evidence-pack",
|
||||
"compliance/fips-posture",
|
||||
"operations/credentials",
|
||||
"operations/lake-archive",
|
||||
"operations/where-the-model-runs",
|
||||
"operations/secrets",
|
||||
"operations/scim",
|
||||
|
||||
@@ -14,6 +14,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
| 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 |
|
||||
| The M365 audit connector's `DLP.All` stream is a real per-instance switch, not a promise: the `include_dlp` schema field (default off) reaches the wire — the subscription and content-listing calls name `DLP.All` only when the instance opted in — and an unparseable value means off, because a collector that defaults to on when it cannot read its own switch is a poll the tenant did not ask for | `services/connectors/app/connectors/m365_audit.py`; `apps/docs/docs/connectors/m365-audit.md` | `ci.yml :: Python — Tests` (connectors, `test_m365_audit_dlp_toggle.py`, 15 cases: the schema declares the field defaulting off, the module docstring no longer promises the switch "later", default polls exactly the four `Audit.*` types, five truthy spellings enable `DLP.All` and six garbage/falsy values mean off, and the fetch path is observed against a mock vendor — the content-type selection is read off the real HTTP requests, not off a constant) | core | GATED | Negative control recorded in the PR: forcing the coercion to always-off fails the four enable cases |
|
||||
| A leaked document's sharing grants can be revoked as a governed action on all four file-sharing estates — Google Drive, OneDrive/SharePoint via Graph, Box and Dropbox — with **prior grants captured before every write** (none of these APIs has a permissions recycle bin), the write **verified by read-back** (a vendor answering 2xx on the DELETE while still listing the grant fails the action naming what it still sees), rollback restoring the captured grants, ANALYST approval on both governance doors, and the one honest limit stated rather than papered over: Graph, Box and Dropbox mint a new URL when a sharing link is re-created, so a link rollback restores access shape and says so, never the circulating URL | `services/actions/app/executors/fileshare.py`; `services/actions/app/clients/fileshare_clients.py`; `capability_contracts.py` (`revoke_file_share`) | `ci.yml :: Python — Tests` (actions, `test_revoke_file_share_vendor_arms.py`, 14 cases through the real executor and builtins against stateful mock vendors: capture-before-write is the observed request order, a frozen "lying vendor" whose DELETE answers 204 and deletes nothing fails the action, grantee/links/all scoping spares the owner, rollback restores through each vendor's own re-grant shape (Graph invite with `sendInvitation=false`, Box collaboration, Dropbox `add_file_member` quiet, Drive exact permission), a dry run through the adapter strips credentials so the mock vendor sees zero requests, nothing-matched is a failure not a silent success, and the independent probe answers gone/present/unverifiable; `test_live_action_builtins.py` pins the four arms in the canonical pair set at 172; `test_verification_coverage.py` holds the declared probe to its registered verifier) | core | GATED | Negative controls recorded in the PR: skipping the read-back comparison passes the lying vendor (1 case fails); a rollback returning True without acting fails 5 rollback cases |
|
||||
| Closed lake months export to the operator's or tenant's own S3-compatible bucket as Parquet with a **signed manifest** (row count, event-time bounds, schema + OCSF version, per-file SHA-256), and **"exported" is a claim while "verified" means the bucket was read back and matched** — the export, the count re-read and the SHA-256 all run inside ClickHouse (`s3()` Parquet / RawBLOB), an open month is refused, and a corrupted object fails verification naming what differed — including the sharp case, a valid same-count object whose only tell is the checksum | `services/api/app/services/lake_archive.py`; migration 170; `services/api/app/workers/lake_archive_sweep.py` | `integration.yml :: The archive tier exports, verifies, rehydrates and ports (live ClickHouse + MinIO)` (real ClickHouse 23.8 + MinIO: export → signed manifest → verification passes; garbage overwrite fails; a recompressed same-count object is caught by the SHA-256 leg alone; fails at setup on the pre-change tree) + `ci.yml :: Python — Tests` (api `test_lake_archive.py`: path/window derivation, destination validation refusals, the estimate's cost honesty) | full | GATED | Negative control recorded in the PR: disabling the checksum comparison passes the content swap (1 live case fails) |
|
||||
| An archived range **rehydrates on an estimate-first flow** — bytes, files and months from the manifests; retrieval cost **null unless a price is configured**, never an invented figure — into an expiring scratch table queryable through the lake explorer's own rewriter under the same tenant predicate `raw_events` gets (the `aisoc.rehydrated_<8hex>` arm is regex-pinned and cannot widen), with requester and reason required; and a **portability export** writes Parquet + signed manifest + schema document to a bucket the tenant names, readable with **no AiSOC code** | `services/api/app/services/lake_archive.py`; migration 171; `services/api/app/services/lake_sql.py` | `integration.yml :: The archive tier exports, verifies, rehydrates and ports (live ClickHouse + MinIO)` (the loader lands the month, evicts foreign-tenant rows after landing — a bucket is not a tenancy boundary — and the rewritten query answers 3 rows for the owner and 0 for another tenant; **DuckDB** opens the portability object and its count matches the signed manifest) + `ci.yml :: Python — Tests` (api `test_lake_archive.py`: the scratch-table namespace refuses non-hex/overlong/foreign-schema names, drop refuses anything outside it, cost honesty both ways) | full | GATED | - |
|
||||
| A legal hold scoped to a subject (`user` / `host` / `ip`) and an optional time window **exempts exactly its own rows from the retention purge** — the Postgres alert DELETE subtracts them through the affected-* arrays and the ClickHouse mutation through user/hostname/IP columns, each within the hold's window, while the REST of the tenant purges on schedule; a tenant-wide hold still freezes the whole tenant's purge, every exemption value is a bind and never a literal, and the per-tenant **retention attestation** reports each tier from its own store (oldest row, verified partitions, WORM as *declared not verified*, each hold with whether it narrows or freezes) with "not measured" where a store cannot answer | `services/api/app/workers/retention_purge.py`; `services/api/app/services/governance.py`; migration 172 | `integration.yml :: The archive tier exports, verifies, rehydrates and ports (live ClickHouse + MinIO)` (live Postgres: two aged alerts for the held user survive, three others delete, the hold does not freeze the tenant; the attestation reports the verified partition, the live hold and the measured oldest lake row) + `ci.yml :: Python — Tests` (api `test_retention_legal_hold.py`: a tenant-wide hold still freezes — pinned beside the superseded test, which now proves the narrowing with the exemption SQL and binds observed on the mutation; `test_lake_archive.py`: hostile hold values never reach the SQL text, the IPv6 arm compares addresses not strings, windows ride the exemption, `covers(at=None)` answers the over-retaining direction) | core | GATED | Negative control recorded in the PR: removing the exemption composition purges the held rows (the live case fails at 5 ≠ 3) |
|
||||
| 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 |
|
||||
@@ -425,14 +428,68 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
## Summary
|
||||
|
||||
|
||||
- Total: 413
|
||||
- GATED: 404
|
||||
- Total: 413
|
||||
- GATED: 404
|
||||
- Total: 413
|
||||
- GATED: 404
|
||||
- Total: 413
|
||||
- GATED: 404
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- Total: 416
|
||||
- GATED: 407
|
||||
- PARTIAL: 9
|
||||
- NO GATE: 0
|
||||
|
||||
|
||||
@@ -22346,6 +22346,252 @@ paths:
|
||||
$ref: '#/components/schemas/LakeSchemaResponse'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/archive-policy:
|
||||
get:
|
||||
tags:
|
||||
- lake
|
||||
summary: Get Archive Policy
|
||||
description: 'The tenant''s archive policy; an absent row is the honest default
|
||||
(off).
|
||||
|
||||
Credentials are reported as present/absent, never echoed.'
|
||||
operationId: get_archive_policy_api_v1_lake_archive_policy_get
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchivePolicyOut'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
put:
|
||||
tags:
|
||||
- lake
|
||||
summary: Put Archive Policy
|
||||
description: 'Upsert the policy. Credentials are vault-encrypted before the
|
||||
row is
|
||||
|
||||
written; omitting them on an update keeps the stored ones.'
|
||||
operationId: put_archive_policy_api_v1_lake_archive_policy_put
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchivePolicyBody'
|
||||
required: true
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchivePolicyOut'
|
||||
'422':
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/archive-partitions:
|
||||
get:
|
||||
tags:
|
||||
- lake
|
||||
summary: List Archive Partitions
|
||||
operationId: list_archive_partitions_api_v1_lake_archive_partitions_get
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/components/schemas/ArchivePartitionOut'
|
||||
type: array
|
||||
title: Response List Archive Partitions Api V1 Lake Archive Partitions
|
||||
Get
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/archive-partitions/run:
|
||||
post:
|
||||
tags:
|
||||
- lake
|
||||
summary: Run Archive Export
|
||||
description: 'Export one closed month now (the sweep worker does this on schedule;
|
||||
|
||||
this is the operator''s explicit trigger). Refuses an open month and a
|
||||
|
||||
tenant without an enabled policy — with the reason, not a 500.'
|
||||
operationId: run_archive_export_api_v1_lake_archive_partitions_run_post
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchiveRunBody'
|
||||
required: true
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchivePartitionOut'
|
||||
'422':
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/archive-partitions/{partition_id}/verify:
|
||||
post:
|
||||
tags:
|
||||
- lake
|
||||
summary: Verify Archive Partition
|
||||
description: 'Re-read the bucket and compare with the manifest. ''exported''
|
||||
is a
|
||||
|
||||
claim; this is what makes it ''verified'' — or ''failed'', naming what
|
||||
|
||||
differed.'
|
||||
operationId: verify_archive_partition_api_v1_lake_archive_partitions__partition_id__verify_post
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
parameters:
|
||||
- name: partition_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
title: Partition Id
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ArchivePartitionOut'
|
||||
'422':
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
/api/v1/lake/rehydrations:
|
||||
get:
|
||||
tags:
|
||||
- lake
|
||||
summary: List Rehydrations
|
||||
operationId: list_rehydrations_api_v1_lake_rehydrations_get
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/components/schemas/RehydrationOut'
|
||||
type: array
|
||||
title: Response List Rehydrations Api V1 Lake Rehydrations Get
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
post:
|
||||
tags:
|
||||
- lake
|
||||
summary: Create Rehydration
|
||||
description: 'Estimate first; load only on ``confirm=true``.
|
||||
|
||||
|
||||
The estimate is computed from the covering manifests — bytes, files,
|
||||
|
||||
months are real numbers; retrieval cost is null unless the deployment
|
||||
|
||||
configured a price. Every rehydration records requester and reason.'
|
||||
operationId: create_rehydration_api_v1_lake_rehydrations_post
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RehydrationBody'
|
||||
required: true
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RehydrationOut'
|
||||
'422':
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/portability-exports:
|
||||
post:
|
||||
tags:
|
||||
- lake
|
||||
summary: Create Portability Export
|
||||
description: 'Export a range to a bucket the TENANT names: Parquet + signed
|
||||
manifest
|
||||
|
||||
+ a schema document, readable with no AiSOC code (the gate proves it
|
||||
|
||||
with DuckDB). Request credentials are used for the job, never persisted.'
|
||||
operationId: create_portability_export_api_v1_lake_portability_exports_post
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PortabilityBody'
|
||||
required: true
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
title: Response Create Portability Export Api V1 Lake Portability
|
||||
Exports Post
|
||||
'422':
|
||||
description: Validation Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/lake/retention-attestation:
|
||||
get:
|
||||
tags:
|
||||
- lake
|
||||
summary: Get Retention Attestation
|
||||
description: 'What is retained per tier, oldest row per tier, manifests verified,
|
||||
|
||||
holds active — each figure from its own store, ''not measured'' where a
|
||||
|
||||
store cannot answer (WS2.4).'
|
||||
operationId: get_retention_attestation_api_v1_lake_retention_attestation_get
|
||||
responses:
|
||||
'200':
|
||||
description: Successful Response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
title: Response Get Retention Attestation Api V1 Lake Retention Attestation
|
||||
Get
|
||||
security:
|
||||
- HTTPBearer: []
|
||||
/api/v1/waitlist/signup:
|
||||
post:
|
||||
tags:
|
||||
@@ -25852,6 +26098,127 @@ components:
|
||||
- created_at
|
||||
- updated_at
|
||||
title: ApprovalResponse
|
||||
ArchivePartitionOut:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
title: Id
|
||||
month:
|
||||
type: string
|
||||
title: Month
|
||||
status:
|
||||
type: string
|
||||
title: Status
|
||||
row_count:
|
||||
anyOf:
|
||||
- type: integer
|
||||
- type: 'null'
|
||||
title: Row Count
|
||||
verified_at:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Verified At
|
||||
failure_reason:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Failure Reason
|
||||
type: object
|
||||
required:
|
||||
- id
|
||||
- month
|
||||
- status
|
||||
title: ArchivePartitionOut
|
||||
ArchivePolicyBody:
|
||||
properties:
|
||||
enabled:
|
||||
type: boolean
|
||||
title: Enabled
|
||||
default: false
|
||||
archive_years:
|
||||
type: integer
|
||||
maximum: 30.0
|
||||
minimum: 1.0
|
||||
title: Archive Years
|
||||
default: 7
|
||||
s3_endpoint:
|
||||
type: string
|
||||
title: S3 Endpoint
|
||||
default: ''
|
||||
s3_bucket:
|
||||
type: string
|
||||
title: S3 Bucket
|
||||
default: ''
|
||||
s3_region:
|
||||
type: string
|
||||
title: S3 Region
|
||||
default: ''
|
||||
s3_access_key:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: S3 Access Key
|
||||
s3_secret_key:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: S3 Secret Key
|
||||
worm_declared:
|
||||
type: boolean
|
||||
title: Worm Declared
|
||||
default: false
|
||||
type: object
|
||||
title: ArchivePolicyBody
|
||||
ArchivePolicyOut:
|
||||
properties:
|
||||
tenant_id:
|
||||
type: string
|
||||
format: uuid
|
||||
title: Tenant Id
|
||||
enabled:
|
||||
type: boolean
|
||||
title: Enabled
|
||||
default: false
|
||||
archive_years:
|
||||
type: integer
|
||||
title: Archive Years
|
||||
default: 7
|
||||
s3_endpoint:
|
||||
type: string
|
||||
title: S3 Endpoint
|
||||
default: ''
|
||||
s3_bucket:
|
||||
type: string
|
||||
title: S3 Bucket
|
||||
default: ''
|
||||
s3_region:
|
||||
type: string
|
||||
title: S3 Region
|
||||
default: ''
|
||||
credentials_present:
|
||||
type: boolean
|
||||
title: Credentials Present
|
||||
default: false
|
||||
worm_declared:
|
||||
type: boolean
|
||||
title: Worm Declared
|
||||
default: false
|
||||
type: object
|
||||
required:
|
||||
- tenant_id
|
||||
title: ArchivePolicyOut
|
||||
ArchiveRunBody:
|
||||
properties:
|
||||
month:
|
||||
type: string
|
||||
pattern: ^\d{4}-\d{2}$
|
||||
title: Month
|
||||
type: object
|
||||
required:
|
||||
- month
|
||||
title: ArchiveRunBody
|
||||
ArtefactOut:
|
||||
properties:
|
||||
id:
|
||||
@@ -37566,6 +37933,42 @@ components:
|
||||
- loaded_at
|
||||
- error
|
||||
title: PluginOut
|
||||
PortabilityBody:
|
||||
properties:
|
||||
range_start:
|
||||
type: string
|
||||
format: date-time
|
||||
title: Range Start
|
||||
range_end:
|
||||
type: string
|
||||
format: date-time
|
||||
title: Range End
|
||||
s3_endpoint:
|
||||
type: string
|
||||
title: S3 Endpoint
|
||||
s3_bucket:
|
||||
type: string
|
||||
title: S3 Bucket
|
||||
s3_access_key:
|
||||
type: string
|
||||
title: S3 Access Key
|
||||
s3_secret_key:
|
||||
type: string
|
||||
title: S3 Secret Key
|
||||
reason:
|
||||
type: string
|
||||
minLength: 3
|
||||
title: Reason
|
||||
type: object
|
||||
required:
|
||||
- range_start
|
||||
- range_end
|
||||
- s3_endpoint
|
||||
- s3_bucket
|
||||
- s3_access_key
|
||||
- s3_secret_key
|
||||
- reason
|
||||
title: PortabilityBody
|
||||
PortfolioAlertOut:
|
||||
properties:
|
||||
alert_id:
|
||||
@@ -39120,6 +39523,79 @@ components:
|
||||
default: My phone
|
||||
type: object
|
||||
title: RegisterBeginRequest
|
||||
RehydrationBody:
|
||||
properties:
|
||||
range_start:
|
||||
type: string
|
||||
format: date-time
|
||||
title: Range Start
|
||||
range_end:
|
||||
type: string
|
||||
format: date-time
|
||||
title: Range End
|
||||
connector_type:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Connector Type
|
||||
reason:
|
||||
type: string
|
||||
minLength: 3
|
||||
title: Reason
|
||||
confirm:
|
||||
type: boolean
|
||||
title: Confirm
|
||||
default: false
|
||||
expiry_days:
|
||||
type: integer
|
||||
maximum: 30.0
|
||||
minimum: 1.0
|
||||
title: Expiry Days
|
||||
default: 7
|
||||
type: object
|
||||
required:
|
||||
- range_start
|
||||
- range_end
|
||||
- reason
|
||||
title: RehydrationBody
|
||||
RehydrationOut:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
title: Id
|
||||
status:
|
||||
type: string
|
||||
title: Status
|
||||
estimate:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
title: Estimate
|
||||
table_name:
|
||||
type: string
|
||||
title: Table Name
|
||||
default: ''
|
||||
rows_loaded:
|
||||
anyOf:
|
||||
- type: integer
|
||||
- type: 'null'
|
||||
title: Rows Loaded
|
||||
expires_at:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Expires At
|
||||
failure_reason:
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Failure Reason
|
||||
type: object
|
||||
required:
|
||||
- id
|
||||
- status
|
||||
- estimate
|
||||
title: RehydrationOut
|
||||
RelatedCase:
|
||||
properties:
|
||||
id:
|
||||
|
||||
@@ -199,6 +199,12 @@ UNMIGRATED_TABLES: dict[str, str] = {
|
||||
#: called ``autonomy_grants`` that exists in no engine at all, and this gate
|
||||
#: passed over it for as long as it shipped.
|
||||
FOREIGN_ENGINE_TABLES: dict[str, str] = {
|
||||
"FUNCTION": (
|
||||
"Not a table: ClickHouse's `INSERT INTO FUNCTION s3(...)` — the lake's object-storage "
|
||||
"table function (WS2 archive/export), sent through execute_lake_query to ClickHouse. "
|
||||
"No Postgres migration can declare it; the archive live suite in integration.yml "
|
||||
"exercises the real statements against a real ClickHouse + MinIO pair."
|
||||
),
|
||||
# ClickHouse. The lake's own database qualifies its tables, so the parser
|
||||
# sees the database name as the table.
|
||||
"aisoc": "ClickHouse: the event lake qualifies every table as `aisoc.<name>`, so the parser reads the database name here.",
|
||||
@@ -291,6 +297,15 @@ KNOWN_MISSING_TABLES: dict[str, str] = {}
|
||||
#: Statements whose table or column list is assembled at runtime, and so
|
||||
#: cannot be compared against anything, with the reason.
|
||||
DYNAMIC_SQL: dict[tuple[str, str], str] = {
|
||||
(
|
||||
"services/api/app/services/lake_archive.py",
|
||||
DYNAMIC,
|
||||
): (
|
||||
"ClickHouse scratch-table statements whose identifier is machine-derived "
|
||||
"(`aisoc.rehydrated_<id>`, regex-pinned beside every use) with every value a bound "
|
||||
"parameter — the rehydration loader (WS2.2). Same store and same live gate as the "
|
||||
"FUNCTION entry above."
|
||||
),
|
||||
(
|
||||
"services/api/app/db/lake_migrations.py",
|
||||
DYNAMIC,
|
||||
|
||||
@@ -799,6 +799,23 @@ RATCHET: dict[str, str] = {
|
||||
"under that tenant's own id — the same enumeration-then-scoped-work shape as "
|
||||
"fusion sessions.py's DISTINCT tenant_id entry"
|
||||
),
|
||||
"services/api/app/workers/lake_archive_sweep.py::<module>::lake_archive_policies": (
|
||||
"the archive sweep's tenant enumeration (WS2.1): SELECT the tenants whose policy row "
|
||||
"opted in, after which each tenant's months export under that tenant's own id and "
|
||||
"credentials — the enumeration-then-scoped-work shape"
|
||||
),
|
||||
"services/api/app/workers/lake_archive_sweep.py::<module>::lake_archive_partitions": (
|
||||
"two statements: the per-tenant exported-months read is bound to the tenant being "
|
||||
"swept (its WHERE carries :tenant_id; recorded here because the gate attributes "
|
||||
"module-level text() constants to <module>), and the unverified-partitions claim is "
|
||||
"the outbox shape — a bounded cross-tenant LIMIT :cap read whose every row carries the "
|
||||
"tenant it is verified under, joined to that tenant's own policy row for credentials"
|
||||
),
|
||||
"services/api/app/workers/lake_archive_sweep.py::<module>::lake_rehydrations": (
|
||||
"two statements: the expiry claim (status='ready' AND expires_at <= now()) across "
|
||||
"tenants — a scratch table outliving its job is retention nobody chose, whoever's it "
|
||||
"is — and the per-row UPDATE that marks it expired by primary key"
|
||||
),
|
||||
"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"
|
||||
@@ -954,7 +971,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 = 83
|
||||
MAX_RATCHET = 86
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -33,14 +33,16 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request, Response, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import text as sa_text
|
||||
|
||||
from app.api.v1.deps import AuthUser, DBSession, require_permission
|
||||
from app.core.config import settings as app_settings
|
||||
from app.core.logging import safe_log_value
|
||||
from app.db.clickhouse import (
|
||||
LakeQueryError,
|
||||
@@ -49,7 +51,15 @@ from app.db.clickhouse import (
|
||||
execute_lake_query,
|
||||
fetch_lake_schema,
|
||||
)
|
||||
from app.models.lake_archive import (
|
||||
LakeArchivePartition,
|
||||
LakeArchivePolicy,
|
||||
LakePortabilityExport,
|
||||
LakeRehydration,
|
||||
)
|
||||
from app.models.lake_query_job import LakeQueryJob
|
||||
from app.security.credential_vault import get_vault
|
||||
from app.services import lake_archive as archive_svc
|
||||
from app.services.audit import emit_audit
|
||||
from app.services.lake_cold_query import ColdEstimateUnavailable, ScanEstimate, estimate_scan
|
||||
from app.services.lake_query_runner import cancel_job, claim_job, new_query_id, read_progress, run_job
|
||||
@@ -62,6 +72,7 @@ from app.services.lake_sql import (
|
||||
LakeSqlSyntaxError,
|
||||
rewrite_for_tenant,
|
||||
)
|
||||
from app.services.retention import MAX_LAKE_DAYS, resolve_policy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -880,3 +891,537 @@ async def _audit_query_attempt(
|
||||
outcome,
|
||||
exc,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Archive tier (WS2): policy, partitions, rehydration, portability,
|
||||
# attestation. Literal subpaths registered after the /query-jobs/{job_id}
|
||||
# family above — distinct first segments, no shadowing; within the archive
|
||||
# family, /archive-partitions/run registers before /{partition_id}/verify.
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class ArchivePolicyBody(BaseModel):
|
||||
enabled: bool = False
|
||||
archive_years: int = Field(7, ge=1, le=30)
|
||||
s3_endpoint: str = ""
|
||||
s3_bucket: str = ""
|
||||
s3_region: str = ""
|
||||
#: Write-only: accepted here, vault-encrypted at rest, never echoed back.
|
||||
s3_access_key: str | None = None
|
||||
s3_secret_key: str | None = None
|
||||
worm_declared: bool = False
|
||||
|
||||
|
||||
class ArchivePolicyOut(BaseModel):
|
||||
tenant_id: uuid.UUID
|
||||
enabled: bool = False
|
||||
archive_years: int = 7
|
||||
s3_endpoint: str = ""
|
||||
s3_bucket: str = ""
|
||||
s3_region: str = ""
|
||||
credentials_present: bool = False
|
||||
worm_declared: bool = False
|
||||
|
||||
|
||||
class ArchivePartitionOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
month: str
|
||||
status: str
|
||||
row_count: int | None = None
|
||||
verified_at: str | None = None
|
||||
failure_reason: str | None = None
|
||||
|
||||
|
||||
class RehydrationBody(BaseModel):
|
||||
range_start: datetime
|
||||
range_end: datetime
|
||||
#: Closed vocabulary; compiled into the loader's SELECT, never caller SQL.
|
||||
connector_type: str | None = None
|
||||
reason: str = Field(..., min_length=3)
|
||||
#: False: estimate only (the default — nothing moves). True: load.
|
||||
confirm: bool = False
|
||||
expiry_days: int = Field(7, ge=1, le=30)
|
||||
|
||||
|
||||
class RehydrationOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
status: str
|
||||
estimate: dict[str, Any]
|
||||
table_name: str = ""
|
||||
rows_loaded: int | None = None
|
||||
expires_at: str | None = None
|
||||
failure_reason: str | None = None
|
||||
|
||||
|
||||
class PortabilityBody(BaseModel):
|
||||
range_start: datetime
|
||||
range_end: datetime
|
||||
s3_endpoint: str
|
||||
s3_bucket: str
|
||||
#: Per-request credentials for the tenant's own bucket. Used for the
|
||||
#: job; never persisted.
|
||||
s3_access_key: str
|
||||
s3_secret_key: str
|
||||
reason: str = Field(..., min_length=3)
|
||||
|
||||
|
||||
@router.get("/archive-policy", response_model=ArchivePolicyOut)
|
||||
async def get_archive_policy(
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
|
||||
) -> ArchivePolicyOut:
|
||||
"""The tenant's archive policy; an absent row is the honest default (off).
|
||||
Credentials are reported as present/absent, never echoed."""
|
||||
|
||||
policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
if policy is None:
|
||||
return ArchivePolicyOut(tenant_id=current_user.tenant_id)
|
||||
return ArchivePolicyOut(
|
||||
tenant_id=policy.tenant_id,
|
||||
enabled=policy.enabled,
|
||||
archive_years=policy.archive_years,
|
||||
s3_endpoint=policy.s3_endpoint,
|
||||
s3_bucket=policy.s3_bucket,
|
||||
s3_region=policy.s3_region,
|
||||
credentials_present=bool(policy.s3_access_key_enc and policy.s3_secret_key_enc),
|
||||
worm_declared=policy.worm_declared,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/archive-policy", response_model=ArchivePolicyOut)
|
||||
async def put_archive_policy(
|
||||
body: ArchivePolicyBody,
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
|
||||
) -> ArchivePolicyOut:
|
||||
"""Upsert the policy. Credentials are vault-encrypted before the row is
|
||||
written; omitting them on an update keeps the stored ones."""
|
||||
|
||||
if body.enabled:
|
||||
try:
|
||||
archive_svc.validate_destination(body.s3_endpoint, body.s3_bucket)
|
||||
except archive_svc.ArchiveConfigError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
if policy is None:
|
||||
policy = LakeArchivePolicy(tenant_id=current_user.tenant_id)
|
||||
db.add(policy)
|
||||
policy.enabled = body.enabled
|
||||
policy.archive_years = body.archive_years
|
||||
policy.s3_endpoint = body.s3_endpoint
|
||||
policy.s3_bucket = body.s3_bucket
|
||||
policy.s3_region = body.s3_region
|
||||
policy.worm_declared = body.worm_declared
|
||||
policy.updated_by = current_user.user_id
|
||||
if body.s3_access_key is not None and body.s3_secret_key is not None:
|
||||
vault = get_vault()
|
||||
policy.s3_access_key_enc = vault.encrypt(body.s3_access_key)
|
||||
policy.s3_secret_key_enc = vault.encrypt(body.s3_secret_key)
|
||||
elif body.enabled and not policy.s3_access_key_enc:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="enabling the archive requires s3_access_key and s3_secret_key",
|
||||
)
|
||||
await db.commit()
|
||||
await db.refresh(policy)
|
||||
return ArchivePolicyOut(
|
||||
tenant_id=policy.tenant_id,
|
||||
enabled=policy.enabled,
|
||||
archive_years=policy.archive_years,
|
||||
s3_endpoint=policy.s3_endpoint,
|
||||
s3_bucket=policy.s3_bucket,
|
||||
s3_region=policy.s3_region,
|
||||
credentials_present=bool(policy.s3_access_key_enc),
|
||||
worm_declared=policy.worm_declared,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/archive-partitions", response_model=list[ArchivePartitionOut])
|
||||
async def list_archive_partitions(
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
|
||||
) -> list[ArchivePartitionOut]:
|
||||
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(LakeArchivePartition)
|
||||
.where(LakeArchivePartition.tenant_id == current_user.tenant_id)
|
||||
.order_by(LakeArchivePartition.month.desc())
|
||||
)
|
||||
).scalars()
|
||||
return [
|
||||
ArchivePartitionOut(
|
||||
id=p.id,
|
||||
month=f"{p.month:%Y-%m}",
|
||||
status=p.status,
|
||||
row_count=(p.manifest or {}).get("row_count"), # type: ignore[arg-type] # JSONB int by construction
|
||||
verified_at=p.verified_at.isoformat() if p.verified_at else None,
|
||||
failure_reason=p.failure_reason,
|
||||
)
|
||||
for p in rows
|
||||
]
|
||||
|
||||
|
||||
class ArchiveRunBody(BaseModel):
|
||||
#: "YYYY-MM"; the month must be strictly in the past (closed).
|
||||
month: str = Field(..., pattern=r"^\d{4}-\d{2}$")
|
||||
|
||||
|
||||
@router.post("/archive-partitions/run", response_model=ArchivePartitionOut)
|
||||
async def run_archive_export(
|
||||
body: ArchiveRunBody,
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
|
||||
) -> ArchivePartitionOut:
|
||||
"""Export one closed month now (the sweep worker does this on schedule;
|
||||
this is the operator's explicit trigger). Refuses an open month and a
|
||||
tenant without an enabled policy — with the reason, not a 500."""
|
||||
|
||||
policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
if policy is None or not policy.enabled:
|
||||
raise HTTPException(status_code=422, detail="the archive policy is not enabled for this tenant")
|
||||
month = datetime.strptime(body.month + "-01", "%Y-%m-%d").replace(tzinfo=UTC).date()
|
||||
try:
|
||||
dest = archive_svc.destination_from_policy(
|
||||
{
|
||||
"s3_endpoint": policy.s3_endpoint,
|
||||
"s3_bucket": policy.s3_bucket,
|
||||
"s3_access_key_enc": policy.s3_access_key_enc,
|
||||
"s3_secret_key_enc": policy.s3_secret_key_enc,
|
||||
}
|
||||
)
|
||||
manifest = await archive_svc.export_month(current_user.tenant_id, month, dest, signing_key=app_settings.SECRET_KEY)
|
||||
except archive_svc.ArchiveConfigError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
except Exception as exc: # noqa: BLE001 — the lake or the bucket refused; name it
|
||||
logger.error("lake.archive.export_failed tenant=%s err=%s", current_user.tenant_id, exc)
|
||||
raise HTTPException(status_code=502, detail=f"export failed: {type(exc).__name__}") from exc
|
||||
|
||||
existing = (
|
||||
await db.execute(
|
||||
select(LakeArchivePartition).where(
|
||||
LakeArchivePartition.tenant_id == current_user.tenant_id,
|
||||
LakeArchivePartition.month == month,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if existing is None:
|
||||
existing = LakeArchivePartition(tenant_id=current_user.tenant_id, month=month)
|
||||
db.add(existing)
|
||||
existing.manifest = manifest
|
||||
existing.status = "exported"
|
||||
existing.failure_reason = None
|
||||
existing.exported_at = datetime.now(UTC)
|
||||
existing.verified_at = None
|
||||
await db.commit()
|
||||
await db.refresh(existing)
|
||||
await emit_audit(
|
||||
db=db,
|
||||
tenant_id=current_user.tenant_id,
|
||||
actor_id=current_user.user_id,
|
||||
actor_email=current_user.email,
|
||||
api_key_prefix=getattr(current_user, "api_key_prefix", None),
|
||||
action="lake.archive.export",
|
||||
resource="lake_archive_partition",
|
||||
resource_id=str(existing.id),
|
||||
changes={"month": body.month, "rows": manifest.get("row_count")},
|
||||
)
|
||||
return ArchivePartitionOut(
|
||||
id=existing.id,
|
||||
month=body.month,
|
||||
status=existing.status,
|
||||
row_count=int(str(manifest.get("row_count", 0))) or None,
|
||||
verified_at=None,
|
||||
failure_reason=None,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/archive-partitions/{partition_id}/verify", response_model=ArchivePartitionOut)
|
||||
async def verify_archive_partition(
|
||||
partition_id: uuid.UUID,
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
|
||||
) -> ArchivePartitionOut:
|
||||
"""Re-read the bucket and compare with the manifest. 'exported' is a
|
||||
claim; this is what makes it 'verified' — or 'failed', naming what
|
||||
differed."""
|
||||
|
||||
partition = await db.get(LakeArchivePartition, partition_id)
|
||||
if partition is None or partition.tenant_id != current_user.tenant_id:
|
||||
raise HTTPException(status_code=404, detail="partition not found")
|
||||
policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
if policy is None:
|
||||
raise HTTPException(status_code=422, detail="no archive policy row; cannot resolve the bucket")
|
||||
dest = archive_svc.destination_from_policy(
|
||||
{
|
||||
"s3_endpoint": policy.s3_endpoint,
|
||||
"s3_bucket": policy.s3_bucket,
|
||||
"s3_access_key_enc": policy.s3_access_key_enc,
|
||||
"s3_secret_key_enc": policy.s3_secret_key_enc,
|
||||
}
|
||||
)
|
||||
problems = await archive_svc.verify_partition(dict(partition.manifest or {}), dest)
|
||||
if problems:
|
||||
partition.status = "failed"
|
||||
partition.failure_reason = "; ".join(problems)
|
||||
partition.verified_at = None
|
||||
else:
|
||||
partition.status = "verified"
|
||||
partition.failure_reason = None
|
||||
partition.verified_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(partition)
|
||||
return ArchivePartitionOut(
|
||||
id=partition.id,
|
||||
month=f"{partition.month:%Y-%m}",
|
||||
status=partition.status,
|
||||
row_count=(partition.manifest or {}).get("row_count"), # type: ignore[arg-type] # JSONB int by construction
|
||||
verified_at=partition.verified_at.isoformat() if partition.verified_at else None,
|
||||
failure_reason=partition.failure_reason,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/rehydrations", response_model=RehydrationOut)
|
||||
async def create_rehydration(
|
||||
body: RehydrationBody,
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
|
||||
) -> RehydrationOut:
|
||||
"""Estimate first; load only on ``confirm=true``.
|
||||
|
||||
The estimate is computed from the covering manifests — bytes, files,
|
||||
months are real numbers; retrieval cost is null unless the deployment
|
||||
configured a price. Every rehydration records requester and reason.
|
||||
"""
|
||||
|
||||
start = body.range_start.date()
|
||||
end = body.range_end.date()
|
||||
if start > end:
|
||||
raise HTTPException(status_code=422, detail="range_start must be on or before range_end")
|
||||
|
||||
months = archive_svc.months_in_range(start, end)
|
||||
partitions = (
|
||||
(
|
||||
await db.execute(
|
||||
select(LakeArchivePartition).where(
|
||||
LakeArchivePartition.tenant_id == current_user.tenant_id,
|
||||
LakeArchivePartition.month.in_(months),
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
if not partitions:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"no archived partitions cover {start}..{end}; nothing to rehydrate",
|
||||
)
|
||||
manifests = [dict(p.manifest or {}) for p in partitions]
|
||||
estimate = archive_svc.estimate_from_manifests(manifests)
|
||||
|
||||
row = LakeRehydration(
|
||||
tenant_id=current_user.tenant_id,
|
||||
range_start=start,
|
||||
range_end=end,
|
||||
filters={"connector_type": body.connector_type} if body.connector_type else {},
|
||||
estimate=estimate,
|
||||
status="estimated",
|
||||
requested_by=current_user.user_id,
|
||||
reason=body.reason,
|
||||
expires_at=archive_svc.rehydration_expiry(body.expiry_days),
|
||||
)
|
||||
db.add(row)
|
||||
await db.flush()
|
||||
|
||||
if body.confirm:
|
||||
policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
if policy is None or not policy.s3_access_key_enc:
|
||||
raise HTTPException(status_code=422, detail="no archive credentials to read the bucket with")
|
||||
dest = archive_svc.destination_from_policy(
|
||||
{
|
||||
"s3_endpoint": policy.s3_endpoint,
|
||||
"s3_bucket": policy.s3_bucket,
|
||||
"s3_access_key_enc": policy.s3_access_key_enc,
|
||||
"s3_secret_key_enc": policy.s3_secret_key_enc,
|
||||
}
|
||||
)
|
||||
row.status = "loading"
|
||||
await db.flush()
|
||||
try:
|
||||
table, loaded = await archive_svc.load_rehydration(
|
||||
row.id,
|
||||
current_user.tenant_id,
|
||||
manifests,
|
||||
dest,
|
||||
connector_type=body.connector_type,
|
||||
)
|
||||
row.table_name = table
|
||||
row.rows_loaded = loaded
|
||||
row.status = "ready"
|
||||
except Exception as exc: # noqa: BLE001 — a failed load is a named failure
|
||||
row.status = "failed"
|
||||
row.failure_reason = f"{type(exc).__name__}: {exc}"[:500]
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(row)
|
||||
await emit_audit(
|
||||
db=db,
|
||||
tenant_id=current_user.tenant_id,
|
||||
actor_id=current_user.user_id,
|
||||
actor_email=current_user.email,
|
||||
api_key_prefix=getattr(current_user, "api_key_prefix", None),
|
||||
action="lake.rehydration." + ("load" if body.confirm else "estimate"),
|
||||
resource="lake_rehydration",
|
||||
resource_id=str(row.id),
|
||||
changes={"range": f"{start}..{end}", "reason": body.reason, "status": row.status},
|
||||
)
|
||||
return RehydrationOut(
|
||||
id=row.id,
|
||||
status=row.status,
|
||||
estimate=dict(row.estimate),
|
||||
table_name=row.table_name,
|
||||
rows_loaded=row.rows_loaded,
|
||||
expires_at=row.expires_at.isoformat(),
|
||||
failure_reason=row.failure_reason,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/rehydrations", response_model=list[RehydrationOut])
|
||||
async def list_rehydrations(
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
|
||||
) -> list[RehydrationOut]:
|
||||
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(LakeRehydration)
|
||||
.where(LakeRehydration.tenant_id == current_user.tenant_id)
|
||||
.order_by(LakeRehydration.created_at.desc())
|
||||
.limit(100)
|
||||
)
|
||||
).scalars()
|
||||
return [
|
||||
RehydrationOut(
|
||||
id=r.id,
|
||||
status=r.status,
|
||||
estimate=dict(r.estimate or {}),
|
||||
table_name=r.table_name,
|
||||
rows_loaded=r.rows_loaded,
|
||||
expires_at=r.expires_at.isoformat() if r.expires_at else None,
|
||||
failure_reason=r.failure_reason,
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.post("/portability-exports", response_model=dict)
|
||||
async def create_portability_export(
|
||||
body: PortabilityBody,
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
|
||||
) -> dict:
|
||||
"""Export a range to a bucket the TENANT names: Parquet + signed manifest
|
||||
+ a schema document, readable with no AiSOC code (the gate proves it
|
||||
with DuckDB). Request credentials are used for the job, never persisted."""
|
||||
|
||||
start = body.range_start.date()
|
||||
end = body.range_end.date()
|
||||
if start > end:
|
||||
raise HTTPException(status_code=422, detail="range_start must be on or before range_end")
|
||||
try:
|
||||
archive_svc.validate_destination(body.s3_endpoint, body.s3_bucket)
|
||||
except archive_svc.ArchiveConfigError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
job = LakePortabilityExport(
|
||||
tenant_id=current_user.tenant_id,
|
||||
range_start=start,
|
||||
range_end=end,
|
||||
s3_endpoint=body.s3_endpoint,
|
||||
s3_bucket=body.s3_bucket,
|
||||
requested_by=current_user.user_id,
|
||||
reason=body.reason,
|
||||
)
|
||||
db.add(job)
|
||||
await db.flush()
|
||||
|
||||
dest = archive_svc.Destination(
|
||||
endpoint=body.s3_endpoint,
|
||||
bucket=body.s3_bucket,
|
||||
access_key=body.s3_access_key,
|
||||
secret_key=body.s3_secret_key,
|
||||
)
|
||||
month_manifests: list[dict[str, Any]] = []
|
||||
failure: str | None = None
|
||||
for month in archive_svc.months_in_range(start, end):
|
||||
try:
|
||||
manifest = await archive_svc.export_month(
|
||||
current_user.tenant_id,
|
||||
month,
|
||||
dest,
|
||||
signing_key=app_settings.SECRET_KEY,
|
||||
prefix="aisoc-portability",
|
||||
)
|
||||
month_manifests.append(manifest)
|
||||
except archive_svc.ArchiveConfigError as exc:
|
||||
# An empty or open month inside the range is recorded, not fatal.
|
||||
month_manifests.append({"month": f"{month:%Y-%m}", "skipped": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failure = f"{month:%Y-%m}: {type(exc).__name__}"
|
||||
break
|
||||
|
||||
if failure:
|
||||
job.status = "failed"
|
||||
job.failure_reason = failure
|
||||
else:
|
||||
schema_doc = {
|
||||
"schema_version": archive_svc.ARCHIVE_SCHEMA_VERSION,
|
||||
"ocsf_version": archive_svc.OCSF_VERSION,
|
||||
"format": "parquet",
|
||||
"note": "Each month is one Parquet object; read with any Parquet reader.",
|
||||
"months": month_manifests,
|
||||
}
|
||||
job.manifest = {**schema_doc, "signature": archive_svc.sign_envelope(schema_doc, signing_key=app_settings.SECRET_KEY)}
|
||||
job.status = "complete"
|
||||
job.completed_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await emit_audit(
|
||||
db=db,
|
||||
tenant_id=current_user.tenant_id,
|
||||
actor_id=current_user.user_id,
|
||||
actor_email=current_user.email,
|
||||
api_key_prefix=getattr(current_user, "api_key_prefix", None),
|
||||
action="lake.portability.export",
|
||||
resource="lake_portability_export",
|
||||
resource_id=str(job.id),
|
||||
changes={"range": f"{start}..{end}", "bucket": body.s3_bucket, "status": job.status},
|
||||
)
|
||||
return {"id": str(job.id), "status": job.status, "manifest": job.manifest, "failure_reason": job.failure_reason}
|
||||
|
||||
|
||||
@router.get("/retention-attestation", response_model=dict)
|
||||
async def get_retention_attestation(
|
||||
db: DBSession,
|
||||
current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
|
||||
) -> dict:
|
||||
"""What is retained per tier, oldest row per tier, manifests verified,
|
||||
holds active — each figure from its own store, 'not measured' where a
|
||||
store cannot answer (WS2.4)."""
|
||||
|
||||
policy_row = await db.execute(
|
||||
sa_text("SELECT raw_events_days FROM retention_policies WHERE tenant_id = :t"),
|
||||
{"t": str(current_user.tenant_id)},
|
||||
)
|
||||
stored = policy_row.scalar_one_or_none()
|
||||
lake_days = int(stored) if stored else resolve_policy(None).raw_events_days
|
||||
lake_days = min(lake_days, MAX_LAKE_DAYS)
|
||||
archive_policy = await db.get(LakeArchivePolicy, current_user.tenant_id)
|
||||
return await archive_svc.retention_attestation(
|
||||
db,
|
||||
current_user.tenant_id,
|
||||
lake_days=lake_days,
|
||||
worm_declared=bool(archive_policy and archive_policy.worm_declared),
|
||||
)
|
||||
|
||||
@@ -516,6 +516,15 @@ class Settings(BaseSettings):
|
||||
validation_alias=AliasChoices("INSIDER_WATCHLIST_SWEEP_ENABLED", "AISOC_INSIDER_WATCHLIST_SWEEP_ENABLED"),
|
||||
)
|
||||
INSIDER_WATCHLIST_SWEEP_INTERVAL_SECONDS: int = 900 # 15m
|
||||
# WS2 — archive-tier sweep: export closed lake months for opted-in
|
||||
# tenants, verify exported partitions by read-back, expire rehydration
|
||||
# scratch tables. Per-tenant policy rows do the real gating (absent or
|
||||
# disabled means nothing exports); the worker is hygiene, on by default.
|
||||
LAKE_ARCHIVE_SWEEP_ENABLED: bool = Field(
|
||||
default=True,
|
||||
validation_alias=AliasChoices("LAKE_ARCHIVE_SWEEP_ENABLED", "AISOC_LAKE_ARCHIVE_SWEEP_ENABLED"),
|
||||
)
|
||||
LAKE_ARCHIVE_SWEEP_INTERVAL_SECONDS: int = 3600 # 1h
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -42,6 +42,7 @@ 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.lake_archive_sweep import run_forever as run_lake_archive_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
|
||||
@@ -80,6 +81,7 @@ _PHISHING_INTAKE_LOCK_TTL_SECONDS = 300
|
||||
# un-expired for far longer than the work takes.
|
||||
_APPROVAL_EXPIRY_LOCK_TTL_SECONDS = 300
|
||||
_INSIDER_WATCHLIST_LOCK_TTL_SECONDS = 900
|
||||
_LAKE_ARCHIVE_LOCK_TTL_SECONDS = 3600
|
||||
|
||||
_CASE_AUTO_CLOSE_LOCK_TTL_SECONDS = 1800
|
||||
# Comfortably past one pass. The scheduler's own poll is 300s and a pass
|
||||
@@ -579,6 +581,27 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
"and the HR door will not run. Set INSIDER_WATCHLIST_SWEEP_ENABLED=true to sweep"
|
||||
)
|
||||
|
||||
# WS2 — the archive-tier sweep (per-tenant policy rows gate the exports).
|
||||
lake_archive_task: asyncio.Task | None = None
|
||||
if settings.LAKE_ARCHIVE_SWEEP_ENABLED:
|
||||
try:
|
||||
lake_archive_task = asyncio.create_task(
|
||||
_run_guarded_scheduler_worker(
|
||||
job_name="lake_archive_sweep",
|
||||
ttl_seconds=_LAKE_ARCHIVE_LOCK_TTL_SECONDS,
|
||||
worker=run_lake_archive_sweep,
|
||||
),
|
||||
name="lake_archive_sweep_worker",
|
||||
)
|
||||
logger.info("lake_archive_sweep worker started")
|
||||
except Exception as exc:
|
||||
logger.warning("lake_archive_sweep worker failed to start", error=str(exc))
|
||||
else:
|
||||
logger.info(
|
||||
"lake_archive_sweep disabled; no months export, no partitions verify, "
|
||||
"and expired rehydration tables are not dropped. Set LAKE_ARCHIVE_SWEEP_ENABLED=true"
|
||||
)
|
||||
|
||||
case_auto_close_task: asyncio.Task | None = None
|
||||
if settings.CASE_AUTO_CLOSE_ENABLED:
|
||||
try:
|
||||
@@ -780,6 +803,14 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
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 lake_archive_task is not None and not lake_archive_task.done():
|
||||
lake_archive_task.cancel()
|
||||
try:
|
||||
await lake_archive_task
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("lake_archive_sweep worker cancelled during shutdown")
|
||||
except Exception as exc:
|
||||
logger.warning("lake_archive_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()
|
||||
|
||||
@@ -33,6 +33,12 @@ from app.models.investigation import (
|
||||
InvestigationEvent,
|
||||
InvestigationRun,
|
||||
)
|
||||
from app.models.lake_archive import (
|
||||
LakeArchivePartition,
|
||||
LakeArchivePolicy,
|
||||
LakePortabilityExport,
|
||||
LakeRehydration,
|
||||
)
|
||||
from app.models.llm_credential import TenantLlmCredential
|
||||
from app.models.mcp_server import McpServer
|
||||
from app.models.mssp import (
|
||||
@@ -94,6 +100,10 @@ __all__ = [
|
||||
"InsiderIndicator",
|
||||
"InsiderPeerGroup",
|
||||
"InsiderWatchlistPolicy",
|
||||
"LakeArchivePartition",
|
||||
"LakeArchivePolicy",
|
||||
"LakePortabilityExport",
|
||||
"LakeRehydration",
|
||||
"InstitutionalMemory",
|
||||
"InvestigationRun",
|
||||
"InvestigationEvent",
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""ORM models for the archive tier (WS2, migrations 170–171)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Date, DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.database import Base
|
||||
|
||||
|
||||
class LakeArchivePolicy(Base):
|
||||
"""Per-tenant archive-tier policy. An absent row means OFF."""
|
||||
|
||||
__tablename__ = "lake_archive_policies"
|
||||
|
||||
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), primary_key=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
archive_years: Mapped[int] = mapped_column(Integer, default=7, nullable=False)
|
||||
s3_endpoint: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
s3_bucket: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
s3_region: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
#: Vault-encrypted (`vault:v1:` tokens) — never plaintext at rest.
|
||||
s3_access_key_enc: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
s3_secret_key_enc: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
worm_declared: Mapped[bool] = mapped_column(Boolean, default=False, 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),
|
||||
)
|
||||
|
||||
|
||||
class LakeArchivePartition(Base):
|
||||
"""One exported (tenant, month): the signed manifest + verification state."""
|
||||
|
||||
__tablename__ = "lake_archive_partitions"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
|
||||
month: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(20), default="exported", nullable=False)
|
||||
manifest: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)
|
||||
exported_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
|
||||
verified_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
|
||||
|
||||
class LakeRehydration(Base):
|
||||
"""An audited rehydration job: estimate → load → ready (expiring) → expired."""
|
||||
|
||||
__tablename__ = "lake_rehydrations"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
|
||||
range_start: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
range_end: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
filters: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)
|
||||
estimate: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(20), default="estimated", nullable=False)
|
||||
table_name: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
rows_loaded: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
requested_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
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),
|
||||
)
|
||||
|
||||
|
||||
class LakePortabilityExport(Base):
|
||||
"""An audited portability export to a bucket the tenant names."""
|
||||
|
||||
__tablename__ = "lake_portability_exports"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
|
||||
range_start: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
range_end: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
s3_endpoint: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
s3_bucket: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(20), default="running", nullable=False)
|
||||
manifest: Mapped[dict] = mapped_column(JSONB, default=dict, nullable=False)
|
||||
failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
requested_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -42,6 +42,13 @@ __all__ = [
|
||||
]
|
||||
|
||||
|
||||
#: Subject kinds whose rows the purge can exempt individually (WS2.4):
|
||||
#: these map onto columns the purge statements can test per row. Any other
|
||||
#: kind — `tenant` above all — keeps the fail-closed whole-tenant freeze,
|
||||
#: because that is what such a hold means.
|
||||
NARROWABLE_HOLD_KINDS: frozenset[str] = frozenset({"user", "host", "ip"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LegalHold:
|
||||
id: str
|
||||
@@ -49,21 +56,42 @@ class LegalHold:
|
||||
subject_value: str
|
||||
matter_ref: str | None = None
|
||||
released_at: datetime | None = None
|
||||
#: WS2.4 (migration 172): the hold covers records whose event time is
|
||||
#: inside this window. Null bounds mean open-ended in that direction —
|
||||
#: a hold with neither covers all time, which is what every hold meant
|
||||
#: before the columns existed.
|
||||
covers_from: datetime | None = None
|
||||
covers_until: datetime | None = None
|
||||
|
||||
def live(self) -> bool:
|
||||
return self.released_at is None
|
||||
|
||||
def covers(self, subjects: dict[str, str]) -> bool:
|
||||
def narrows_purge(self) -> bool:
|
||||
"""Whether the purge can exempt exactly this hold's rows instead of
|
||||
freezing the whole tenant."""
|
||||
return self.subject_kind in NARROWABLE_HOLD_KINDS
|
||||
|
||||
def covers(self, subjects: dict[str, str], *, at: datetime | None = None) -> bool:
|
||||
"""Whether this hold covers a record with these subjects.
|
||||
|
||||
Case-insensitive on the value: `SVC-Backup` and `svc-backup`
|
||||
are one account, and a hold that missed one spelling would
|
||||
preserve half the evidence.
|
||||
preserve half the evidence. When the record's own time is known,
|
||||
the hold's window applies; a caller that cannot date the record
|
||||
passes ``at=None`` and gets the time-unbounded answer — the
|
||||
over-retaining direction, which is the recoverable one.
|
||||
"""
|
||||
actual = subjects.get(self.subject_kind)
|
||||
if actual is None:
|
||||
return False
|
||||
return str(actual).strip().lower() == self.subject_value.strip().lower()
|
||||
if str(actual).strip().lower() != self.subject_value.strip().lower():
|
||||
return False
|
||||
if at is not None:
|
||||
if self.covers_from is not None and at < self.covers_from:
|
||||
return False
|
||||
if self.covers_until is not None and at > self.covers_until:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
"""The archive tier: closed lake months in an open format (WS2.1–2.3).
|
||||
|
||||
The shape of the thing
|
||||
----------------------
|
||||
The lake (`aisoc.raw_events`) holds at most ``MAX_LAKE_DAYS`` of events —
|
||||
the ClickHouse TTL is a hard ceiling nothing exempts. Everything older
|
||||
exists only if it was exported first. So the archive is the only path to
|
||||
multi-year retention, and it has to be trustworthy in a way a copy script
|
||||
is not:
|
||||
|
||||
* **The database that owns the rows writes the files.** Exports run inside
|
||||
ClickHouse — ``INSERT INTO FUNCTION s3(...) ... FORMAT Parquet`` — so
|
||||
there is no second data path whose row semantics could drift from the
|
||||
lake's own. Verification re-reads through the same engine: the row count
|
||||
from the Parquet object, the SHA-256 from the raw bytes (``RawBLOB``).
|
||||
"Exported" is a claim; **"verified" means the bucket was read back and
|
||||
matched.**
|
||||
* **One object per (tenant, month).** No listing API is needed to know
|
||||
what exists — the manifest names the exact path — and a partition is
|
||||
closed before it is exported, so the object never needs appending.
|
||||
* **The manifest is signed** with the evidence-bundle signer (row count,
|
||||
event-time bounds, schema + OCSF version, per-file SHA-256), so a
|
||||
manifest row and a bucket object corroborate each other and neither can
|
||||
be quietly edited.
|
||||
* **Portability is the same machinery pointed at the tenant's bucket**,
|
||||
plus a schema document — and the gate proves the export is readable with
|
||||
no AiSOC code by opening it with DuckDB.
|
||||
|
||||
Credentials
|
||||
-----------
|
||||
Bucket credentials are vault-encrypted at rest (`CredentialVault`) and
|
||||
decrypted only at export time. They are bound into the statement by
|
||||
``clickhouse-driver``'s client-side parameter escaping; ClickHouse masks
|
||||
``s3()`` credential positions in ``system.query_log``, which the
|
||||
deployment relies on and the docs state.
|
||||
|
||||
Cost honesty
|
||||
------------
|
||||
A rehydration estimate reports bytes, files and months from the manifests
|
||||
— real numbers — and a retrieval **cost only when the deployment
|
||||
configured a price** (``AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB``). No price
|
||||
configured means ``cost: null``, never an invented figure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.clickhouse import execute_lake_query
|
||||
from app.security.credential_vault import get_vault
|
||||
from app.services.evidence_bundle import sign_envelope
|
||||
|
||||
logger = logging.getLogger("aisoc.lake_archive")
|
||||
|
||||
#: The schema version written into every manifest. Bump when the lake's
|
||||
#: column set changes shape (the manifest records what the files contain,
|
||||
#: not what the current code would write).
|
||||
ARCHIVE_SCHEMA_VERSION = "raw_events/v1"
|
||||
OCSF_VERSION = "1.1.0"
|
||||
|
||||
_BUCKET_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{2,62}$")
|
||||
_ENDPOINT_RE = re.compile(r"^https?://[A-Za-z0-9.:\-]+(?::\d+)?$")
|
||||
|
||||
|
||||
class ArchiveConfigError(ValueError):
|
||||
"""A policy or request that cannot be executed, with the reason named."""
|
||||
|
||||
|
||||
def object_path(tenant_id: uuid.UUID, month: date, *, prefix: str = "aisoc-archive") -> str:
|
||||
"""The deterministic object key for a (tenant, month) partition."""
|
||||
return f"{prefix}/tenant={tenant_id}/month={month:%Y-%m}/events.parquet"
|
||||
|
||||
|
||||
def month_bounds(month: date) -> tuple[datetime, datetime]:
|
||||
start = datetime(month.year, month.month, 1, tzinfo=UTC)
|
||||
end = datetime(month.year + 1, 1, 1, tzinfo=UTC) if month.month == 12 else datetime(month.year, month.month + 1, 1, tzinfo=UTC)
|
||||
return start, end
|
||||
|
||||
|
||||
def validate_destination(endpoint: str, bucket: str) -> None:
|
||||
"""Refuse endpoints/buckets the URL composer cannot carry safely."""
|
||||
if not _ENDPOINT_RE.match(endpoint or ""):
|
||||
raise ArchiveConfigError(
|
||||
f"s3_endpoint must be http(s)://host[:port] — got {endpoint!r}. Path-style addressing is composed from it."
|
||||
)
|
||||
if not _BUCKET_RE.match(bucket or ""):
|
||||
raise ArchiveConfigError(f"s3_bucket must be a valid bucket name — got {bucket!r}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Destination:
|
||||
endpoint: str
|
||||
bucket: str
|
||||
access_key: str
|
||||
secret_key: str
|
||||
|
||||
def url(self, key: str) -> str:
|
||||
return f"{self.endpoint.rstrip('/')}/{self.bucket}/{key}"
|
||||
|
||||
|
||||
def destination_from_policy(row: dict[str, Any]) -> Destination:
|
||||
"""Decrypt a policy row's credentials into a usable destination."""
|
||||
vault = get_vault()
|
||||
endpoint = str(row.get("s3_endpoint") or "")
|
||||
bucket = str(row.get("s3_bucket") or "")
|
||||
validate_destination(endpoint, bucket)
|
||||
return Destination(
|
||||
endpoint=endpoint,
|
||||
bucket=bucket,
|
||||
access_key=vault.decrypt(str(row["s3_access_key_enc"])),
|
||||
secret_key=vault.decrypt(str(row["s3_secret_key_enc"])),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Export + manifest + verification (the ClickHouse legs)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _partition_stats(tenant_id: uuid.UUID, month: date) -> dict[str, Any]:
|
||||
start, end = month_bounds(month)
|
||||
result = await execute_lake_query(
|
||||
"""
|
||||
SELECT count() AS rows, min(event_time) AS t_min, max(event_time) AS t_max
|
||||
FROM aisoc.raw_events
|
||||
WHERE tenant_id = %(tenant_id)s
|
||||
AND event_time >= %(start)s AND event_time < %(end)s
|
||||
""",
|
||||
params={"tenant_id": str(tenant_id), "start": start, "end": end},
|
||||
)
|
||||
rows = result.rows[0] if result.rows else (0, None, None)
|
||||
return {"rows": int(rows[0]), "event_time_min": str(rows[1]), "event_time_max": str(rows[2])}
|
||||
|
||||
|
||||
async def export_month(
|
||||
tenant_id: uuid.UUID,
|
||||
month: date,
|
||||
dest: Destination,
|
||||
*,
|
||||
signing_key: str,
|
||||
prefix: str = "aisoc-archive",
|
||||
) -> dict[str, Any]:
|
||||
"""Export one closed month to one Parquet object and build the manifest.
|
||||
|
||||
Refuses an open month: the current month is still receiving rows, and
|
||||
an object exported from it would be silently incomplete — the
|
||||
connector-window lesson applied to archival.
|
||||
"""
|
||||
today = datetime.now(UTC).date()
|
||||
if month >= date(today.year, today.month, 1):
|
||||
raise ArchiveConfigError(f"month {month:%Y-%m} is not closed yet; only strictly past months export")
|
||||
|
||||
# UUID and IPv6 columns export as strings (`* REPLACE`): ClickHouse
|
||||
# cannot write UUID to Parquet (Code 50) and a string id is the more
|
||||
# portable spelling anyway. Column ORDER is preserved, so the
|
||||
# rehydration INSERT ... SELECT auto-casts them back positionally.
|
||||
|
||||
stats = await _partition_stats(tenant_id, month)
|
||||
if int(stats["rows"]) == 0: # type: ignore[arg-type]
|
||||
raise ArchiveConfigError(f"no rows in {month:%Y-%m} for this tenant; nothing to export")
|
||||
|
||||
key = object_path(tenant_id, month, prefix=prefix)
|
||||
start, end = month_bounds(month)
|
||||
await execute_lake_query(
|
||||
"""
|
||||
INSERT INTO FUNCTION s3(%(url)s, %(ak)s, %(sk)s, 'Parquet')
|
||||
SELECT * REPLACE (toString(event_id) AS event_id, toString(tenant_id) AS tenant_id,
|
||||
toString(source_ip) AS source_ip, toString(dest_ip) AS dest_ip)
|
||||
FROM aisoc.raw_events
|
||||
WHERE tenant_id = %(tenant_id)s
|
||||
AND event_time >= %(start)s AND event_time < %(end)s
|
||||
""",
|
||||
params={
|
||||
"url": dest.url(key),
|
||||
"ak": dest.access_key,
|
||||
"sk": dest.secret_key,
|
||||
"tenant_id": str(tenant_id),
|
||||
"start": start,
|
||||
"end": end,
|
||||
},
|
||||
extra_settings={"s3_truncate_on_insert": 1},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
|
||||
sha256, size_bytes = await _object_sha256(dest, key)
|
||||
manifest: dict[str, Any] = {
|
||||
"tenant_id": str(tenant_id),
|
||||
"month": f"{month:%Y-%m}",
|
||||
"row_count": stats["rows"],
|
||||
"event_time_min": stats["event_time_min"],
|
||||
"event_time_max": stats["event_time_max"],
|
||||
"schema_version": ARCHIVE_SCHEMA_VERSION,
|
||||
"ocsf_version": OCSF_VERSION,
|
||||
"format": "parquet",
|
||||
"files": [{"path": key, "sha256": sha256, "bytes": size_bytes}],
|
||||
"exported_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
# `sign_envelope` returns the integrity block alone; the manifest
|
||||
# carries its payload beside the signature so a verifier recomputes
|
||||
# the digest over exactly the payload half.
|
||||
manifest["signature"] = sign_envelope({k: v for k, v in manifest.items() if k != "signature"}, signing_key=signing_key)
|
||||
return manifest
|
||||
|
||||
|
||||
async def _object_sha256(dest: Destination, key: str) -> tuple[str, int]:
|
||||
"""SHA-256 + size of the object, computed by ClickHouse reading raw bytes.
|
||||
|
||||
``RawBLOB`` reads the whole object as a single value, so the hash is of
|
||||
the bytes in the bucket — the thing the verifier will re-hash — not of
|
||||
any local copy.
|
||||
"""
|
||||
result = await execute_lake_query(
|
||||
"""
|
||||
SELECT lower(hex(SHA256(raw))) AS sha, length(raw) AS bytes
|
||||
FROM s3(%(url)s, %(ak)s, %(sk)s, 'RawBLOB', 'raw String')
|
||||
""",
|
||||
params={"url": dest.url(key), "ak": dest.access_key, "sk": dest.secret_key},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
row = result.rows[0]
|
||||
return str(row[0]), int(row[1])
|
||||
|
||||
|
||||
async def verify_partition(manifest: dict[str, Any], dest: Destination) -> list[str]:
|
||||
"""Re-read the bucket and compare with the manifest. Returns mismatches.
|
||||
|
||||
Empty list means verified. Every mismatch names what differed — a count
|
||||
that moved, a checksum that moved, an object that is gone — because
|
||||
"verification failed" without the failing fact sends an operator
|
||||
hunting.
|
||||
"""
|
||||
problems: list[str] = []
|
||||
files = manifest.get("files") or []
|
||||
for entry in files: # type: ignore[union-attr]
|
||||
key = str(entry["path"]) # type: ignore[index]
|
||||
try:
|
||||
count_result = await execute_lake_query(
|
||||
"SELECT count() FROM s3(%(url)s, %(ak)s, %(sk)s, 'Parquet')",
|
||||
params={"url": dest.url(key), "ak": dest.access_key, "sk": dest.secret_key},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
stored_rows = int(count_result.rows[0][0])
|
||||
except Exception as exc: # noqa: BLE001 — an unreadable object is a named failure
|
||||
problems.append(f"{key}: unreadable ({type(exc).__name__})")
|
||||
continue
|
||||
if stored_rows != int(manifest["row_count"]): # type: ignore[arg-type]
|
||||
problems.append(f"{key}: row count differs (manifest {manifest['row_count']}, bucket {stored_rows})")
|
||||
try:
|
||||
sha, _size = await _object_sha256(dest, key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
problems.append(f"{key}: hash re-read failed ({type(exc).__name__})")
|
||||
continue
|
||||
if sha != str(entry["sha256"]): # type: ignore[index]
|
||||
problems.append(f"{key}: sha256 differs (manifest {entry['sha256']}, bucket {sha})")
|
||||
if not files:
|
||||
problems.append("manifest lists no files")
|
||||
return problems
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rehydration (WS2.2)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: The scratch-table namespace. `lake_sql.rewrite_for_tenant` recognises
|
||||
#: exactly this shape and applies the same tenant predicate it applies to
|
||||
#: raw_events, so a rehydrated range is queryable through the explorer
|
||||
#: without widening what callers can name.
|
||||
REHYDRATED_TABLE_RE = re.compile(r"^aisoc\.rehydrated_[0-9a-f]{8}$")
|
||||
|
||||
|
||||
def rehydrated_table_name(rehydration_id: uuid.UUID) -> str:
|
||||
return f"aisoc.rehydrated_{rehydration_id.hex[:8]}"
|
||||
|
||||
|
||||
def months_in_range(range_start: date, range_end: date) -> list[date]:
|
||||
months: list[date] = []
|
||||
cursor = date(range_start.year, range_start.month, 1)
|
||||
while cursor <= range_end:
|
||||
months.append(cursor)
|
||||
cursor = date(cursor.year + 1, 1, 1) if cursor.month == 12 else date(cursor.year, cursor.month + 1, 1)
|
||||
return months
|
||||
|
||||
|
||||
def estimate_from_manifests(manifests: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Bytes/files/months from the covering manifests; cost only if priced."""
|
||||
total_bytes = 0
|
||||
total_files = 0
|
||||
for m in manifests:
|
||||
for f in m.get("files") or []: # type: ignore[union-attr]
|
||||
total_bytes += int(f.get("bytes") or 0) # type: ignore[union-attr]
|
||||
total_files += 1
|
||||
price = os.environ.get("AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB", "").strip()
|
||||
cost: float | None = None
|
||||
if price:
|
||||
try:
|
||||
cost = round(total_bytes / 1_000_000_000 * float(price), 4)
|
||||
except ValueError:
|
||||
cost = None
|
||||
return {
|
||||
"months": len(manifests),
|
||||
"files": total_files,
|
||||
"bytes": total_bytes,
|
||||
"retrieval_cost": cost,
|
||||
"retrieval_cost_note": (
|
||||
None
|
||||
if cost is not None
|
||||
else "no retrieval price is configured (AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB); cost is unknown, not zero"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
async def load_rehydration(
|
||||
rehydration_id: uuid.UUID,
|
||||
tenant_id: uuid.UUID,
|
||||
manifests: list[dict[str, Any]],
|
||||
dest: Destination,
|
||||
*,
|
||||
connector_type: str | None = None,
|
||||
) -> tuple[str, int]:
|
||||
"""Load the covered months into the scratch table. Returns (table, rows).
|
||||
|
||||
The table carries the lake's own schema (``AS raw_events``) so the
|
||||
explorer's column expectations hold, and the loader re-applies the
|
||||
tenant predicate on read — the object should only contain that
|
||||
tenant's rows, but trusting a bucket to enforce tenancy would make the
|
||||
bucket a tenancy boundary, which it is not.
|
||||
"""
|
||||
table = rehydrated_table_name(rehydration_id)
|
||||
if not REHYDRATED_TABLE_RE.match(table): # defence in depth; the name is ours
|
||||
raise ArchiveConfigError(f"internal: bad scratch table name {table!r}")
|
||||
await execute_lake_query(
|
||||
f"CREATE TABLE IF NOT EXISTS {table} AS aisoc.raw_events ENGINE = MergeTree ORDER BY (tenant_id, event_time)",
|
||||
timeout_seconds=60.0,
|
||||
)
|
||||
total = 0
|
||||
for manifest in manifests:
|
||||
for entry in manifest.get("files") or []: # type: ignore[union-attr]
|
||||
key = str(entry["path"]) # type: ignore[index]
|
||||
# No WHERE on the s3 read: ClickHouse 23.8's Parquet pushdown
|
||||
# cannot compare the file's string-typed ids against the target
|
||||
# table's UUID hint in either direction (Code 169). The object
|
||||
# is tenant-pure by construction (exported under a tenant
|
||||
# predicate into a tenant-keyed path); the mutation below is
|
||||
# the belt-and-braces that refuses to TRUST that, because a
|
||||
# bucket is not a tenancy boundary.
|
||||
await execute_lake_query( # nosemgrep — regex-pinned identifier; values are bound params
|
||||
f"INSERT INTO {table} SELECT * FROM s3(%(url)s, %(ak)s, %(sk)s, 'Parquet')", # noqa: S608 — machine-derived, regex-pinned identifier # nosemgrep
|
||||
params={"url": dest.url(key), "ak": dest.access_key, "sk": dest.secret_key},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
# Evict anything that is not this tenant's, and anything outside the
|
||||
# requested connector filter — after landing, where the columns carry
|
||||
# the table's own types and no pushdown is involved.
|
||||
await execute_lake_query( # nosemgrep — regex-pinned identifier; values are bound params
|
||||
f"ALTER TABLE {table} DELETE WHERE tenant_id != toUUID(%(tenant_id)s)", # noqa: S608 — machine-derived, regex-pinned identifier # nosemgrep
|
||||
params={"tenant_id": str(tenant_id)},
|
||||
extra_settings={"mutations_sync": 2},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
if connector_type:
|
||||
await execute_lake_query( # nosemgrep — regex-pinned identifier; values are bound params
|
||||
f"ALTER TABLE {table} DELETE WHERE connector_type != %(connector_type)s", # noqa: S608 — machine-derived, regex-pinned identifier # nosemgrep
|
||||
params={"connector_type": connector_type},
|
||||
extra_settings={"mutations_sync": 2},
|
||||
timeout_seconds=600.0,
|
||||
)
|
||||
count = await execute_lake_query( # nosemgrep — regex-pinned identifier; values are bound params
|
||||
f"SELECT count() FROM {table}", # noqa: S608 — regex-pinned scratch table # nosemgrep
|
||||
timeout_seconds=60.0,
|
||||
)
|
||||
total = int(count.rows[0][0]) if count.rows else 0
|
||||
return table, total
|
||||
|
||||
|
||||
async def drop_rehydration_table(table: str) -> None:
|
||||
if not REHYDRATED_TABLE_RE.match(table):
|
||||
raise ArchiveConfigError(f"refusing to drop non-scratch table {table!r}")
|
||||
await execute_lake_query(f"DROP TABLE IF EXISTS {table}", timeout_seconds=60.0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Attestation (WS2.4's reporting half)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ATTESTATION_HOLDS_SQL = text(
|
||||
"""
|
||||
SELECT id, subject_kind, subject_value, covers_from, covers_until, matter_ref
|
||||
FROM legal_holds
|
||||
WHERE tenant_id = :tenant_id AND released_at IS NULL
|
||||
ORDER BY placed_at
|
||||
"""
|
||||
)
|
||||
|
||||
_ATTESTATION_PARTITIONS_SQL = text(
|
||||
"""
|
||||
SELECT month, status, manifest->>'row_count' AS rows, verified_at
|
||||
FROM lake_archive_partitions
|
||||
WHERE tenant_id = :tenant_id
|
||||
ORDER BY month
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def retention_attestation(db: AsyncSession, tenant_id: uuid.UUID, *, lake_days: int, worm_declared: bool) -> dict[str, Any]:
|
||||
"""What is retained per tier, oldest row per tier, manifests verified,
|
||||
holds active — each figure from its own store, 'not measured' where a
|
||||
store cannot answer."""
|
||||
lake_oldest: str | None = None
|
||||
lake_note: str | None = None
|
||||
try:
|
||||
result = await execute_lake_query(
|
||||
"SELECT min(event_time) FROM aisoc.raw_events WHERE tenant_id = %(tenant_id)s",
|
||||
params={"tenant_id": str(tenant_id)},
|
||||
)
|
||||
lake_oldest = str(result.rows[0][0]) if result.rows and result.rows[0][0] else None
|
||||
except Exception as exc: # noqa: BLE001 — an unreachable lake is unknown, not empty
|
||||
lake_note = f"lake unreachable ({type(exc).__name__}): oldest row not measured"
|
||||
|
||||
partitions = (await db.execute(_ATTESTATION_PARTITIONS_SQL, {"tenant_id": str(tenant_id)})).fetchall()
|
||||
holds = (await db.execute(_ATTESTATION_HOLDS_SQL, {"tenant_id": str(tenant_id)})).fetchall()
|
||||
verified = [p for p in partitions if p[1] == "verified"]
|
||||
return {
|
||||
"hot_and_lake": {
|
||||
"window_days": lake_days,
|
||||
"oldest_row": lake_oldest,
|
||||
"note": lake_note,
|
||||
},
|
||||
"archive": {
|
||||
"partitions": len(partitions),
|
||||
"verified": len(verified),
|
||||
"oldest_month": str(partitions[0][0]) if partitions else None,
|
||||
"newest_month": str(partitions[-1][0]) if partitions else None,
|
||||
"worm": "declared by operator, not verified by this service" if worm_declared else "not declared",
|
||||
},
|
||||
"legal_holds": [
|
||||
{
|
||||
"id": str(h[0]),
|
||||
"subject_kind": h[1],
|
||||
"subject_value": h[2],
|
||||
"covers_from": str(h[3]) if h[3] else None,
|
||||
"covers_until": str(h[4]) if h[4] else None,
|
||||
"matter_ref": h[5],
|
||||
"narrows_purge": h[1] in ("user", "host", "ip"),
|
||||
}
|
||||
for h in holds
|
||||
],
|
||||
"generated_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def rehydration_expiry(days: int = 7) -> datetime:
|
||||
return datetime.now(UTC) + timedelta(days=max(1, min(days, 30)))
|
||||
@@ -38,6 +38,7 @@ green and ideally extend them.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import Final
|
||||
@@ -59,6 +60,14 @@ ALLOWED_TABLES: Final[frozenset[str]] = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
# Rehydrated archive ranges (WS2.2). A rehydration loads archived months
|
||||
# into a scratch table named by the job id — `aisoc.rehydrated_<8 hex>` —
|
||||
# with the lake's own schema, so the explorer can query it under exactly
|
||||
# the predicate regime raw_events gets: same tenant injection, same row
|
||||
# cap. The shape is pinned (hex only, fixed length) so this arm can never
|
||||
# widen into "any table whose name starts with rehydrated".
|
||||
REHYDRATED_TABLE_RE: Final[re.Pattern[str]] = re.compile(r"^aisoc\.rehydrated_[0-9a-f]{8}$")
|
||||
|
||||
# Default schema (ClickHouse database) we resolve unqualified ``FROM <name>``
|
||||
# references against. Lets agents write ``FROM raw_events`` for terseness.
|
||||
DEFAULT_SCHEMA: Final[str] = "aisoc"
|
||||
@@ -313,7 +322,7 @@ def _validate_and_rewrite_select(
|
||||
continue
|
||||
|
||||
full = _qualified_name(table)
|
||||
if full not in ALLOWED_TABLES:
|
||||
if full not in ALLOWED_TABLES and not REHYDRATED_TABLE_RE.match(full):
|
||||
raise LakeSqlForbiddenError(f"table '{full}' is not in the lake allowlist")
|
||||
|
||||
# Backfill the schema on unqualified references so the rewritten
|
||||
|
||||
@@ -89,12 +89,22 @@ async def alerts_under_legal_hold(db: Any, tenant_id: uuid.UUID) -> list[governa
|
||||
"""
|
||||
rows = await db.execute(
|
||||
text("""
|
||||
SELECT id, subject_kind, subject_value, matter_ref
|
||||
SELECT id, subject_kind, subject_value, matter_ref, covers_from, covers_until
|
||||
FROM legal_holds
|
||||
WHERE tenant_id = CAST(:t AS uuid) AND released_at IS NULL
|
||||
""").bindparams(t=str(tenant_id))
|
||||
)
|
||||
return [governance.LegalHold(id=str(r[0]), subject_kind=str(r[1]), subject_value=str(r[2]), matter_ref=r[3]) for r in rows.all()]
|
||||
return [
|
||||
governance.LegalHold(
|
||||
id=str(r[0]),
|
||||
subject_kind=str(r[1]),
|
||||
subject_value=str(r[2]),
|
||||
matter_ref=r[3],
|
||||
covers_from=r[4],
|
||||
covers_until=r[5],
|
||||
)
|
||||
for r in rows.all()
|
||||
]
|
||||
|
||||
|
||||
def may_purge(
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Archive sweep: export closed months, verify, expire rehydrations (WS2).
|
||||
|
||||
Three jobs on one tick, each bounded so a large estate cannot wedge the
|
||||
loop:
|
||||
|
||||
* **Export** — for every tenant whose policy row says ``enabled``, any
|
||||
closed month still present in the lake and absent from the partition
|
||||
ledger is exported (oldest first, at most ``MAX_EXPORTS_PER_TICK`` per
|
||||
tick). The current month never exports: it is still receiving rows, and
|
||||
an object cut from it would be silently incomplete.
|
||||
* **Verify** — exported-but-unverified partitions are read back (at most
|
||||
``MAX_VERIFIES_PER_TICK``): counts from the Parquet object, SHA-256 from
|
||||
the raw bytes, both through ClickHouse. A mismatch marks the partition
|
||||
``failed`` with the differing fact named.
|
||||
* **Expire** — rehydrations past ``expires_at`` have their scratch table
|
||||
dropped and the row marked ``expired``. A scratch table that outlives
|
||||
its job is retention nobody chose.
|
||||
|
||||
Per-tenant opt-in does the real gating (an absent/disabled policy row means
|
||||
nothing exports); the worker itself is on by default like the other
|
||||
hygiene sweeps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.clickhouse import execute_lake_query
|
||||
from app.db.database import AsyncSessionLocal
|
||||
from app.services import lake_archive
|
||||
from app.workers._tick_failures import TickFailures
|
||||
|
||||
logger = logging.getLogger("aisoc.lake_archive_sweep")
|
||||
|
||||
MAX_EXPORTS_PER_TICK = 4
|
||||
MAX_VERIFIES_PER_TICK = 8
|
||||
|
||||
_ENABLED_POLICIES_SQL = text(
|
||||
"""
|
||||
SELECT tenant_id, s3_endpoint, s3_bucket, s3_access_key_enc, s3_secret_key_enc, archive_years
|
||||
FROM lake_archive_policies
|
||||
WHERE enabled = TRUE
|
||||
"""
|
||||
)
|
||||
|
||||
_EXPORTED_MONTHS_SQL = text("SELECT month FROM lake_archive_partitions WHERE tenant_id = :tenant_id")
|
||||
|
||||
_UPSERT_PARTITION_SQL = text(
|
||||
"""
|
||||
INSERT INTO lake_archive_partitions (tenant_id, month, status, manifest, exported_at)
|
||||
VALUES (:tenant_id, :month, 'exported', CAST(:manifest AS jsonb), now())
|
||||
ON CONFLICT (tenant_id, month)
|
||||
DO UPDATE SET manifest = EXCLUDED.manifest, status = 'exported',
|
||||
exported_at = now(), verified_at = NULL, failure_reason = NULL
|
||||
"""
|
||||
)
|
||||
|
||||
_UNVERIFIED_SQL = text(
|
||||
"""
|
||||
SELECT p.id, p.tenant_id, p.manifest,
|
||||
pol.s3_endpoint, pol.s3_bucket, pol.s3_access_key_enc, pol.s3_secret_key_enc
|
||||
FROM lake_archive_partitions p
|
||||
JOIN lake_archive_policies pol ON pol.tenant_id = p.tenant_id AND pol.enabled = TRUE
|
||||
WHERE p.status = 'exported'
|
||||
ORDER BY p.exported_at
|
||||
LIMIT :cap
|
||||
"""
|
||||
)
|
||||
|
||||
_MARK_VERIFIED_SQL = text(
|
||||
"UPDATE lake_archive_partitions SET status = 'verified', verified_at = now(), failure_reason = NULL WHERE id = :id"
|
||||
)
|
||||
_MARK_FAILED_SQL = text("UPDATE lake_archive_partitions SET status = 'failed', failure_reason = :reason WHERE id = :id")
|
||||
|
||||
_EXPIRED_REHYDRATIONS_SQL = text(
|
||||
"""
|
||||
SELECT id, table_name FROM lake_rehydrations
|
||||
WHERE status = 'ready' AND expires_at <= now()
|
||||
"""
|
||||
)
|
||||
_MARK_EXPIRED_SQL = text("UPDATE lake_rehydrations SET status = 'expired' WHERE id = :id")
|
||||
|
||||
|
||||
@dataclass
|
||||
class SweepSummary:
|
||||
exported: int = 0
|
||||
verified: int = 0
|
||||
verify_failed: int = 0
|
||||
rehydrations_expired: int = 0
|
||||
errors: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
async def _candidate_months(tenant_id: uuid.UUID, already: set[date]) -> list[date]:
|
||||
"""Closed months still present in the lake and absent from the ledger."""
|
||||
result = await execute_lake_query(
|
||||
"""
|
||||
SELECT DISTINCT toStartOfMonth(event_time) AS m
|
||||
FROM aisoc.raw_events
|
||||
WHERE tenant_id = %(tenant_id)s
|
||||
ORDER BY m
|
||||
""",
|
||||
params={"tenant_id": str(tenant_id)},
|
||||
)
|
||||
today = datetime.now(UTC).date()
|
||||
current_month = date(today.year, today.month, 1)
|
||||
months: list[date] = []
|
||||
for row in result.rows:
|
||||
value = row[0]
|
||||
month = value.date() if isinstance(value, datetime) else value
|
||||
if month < current_month and month not in already:
|
||||
months.append(month)
|
||||
return months
|
||||
|
||||
|
||||
async def run_once(db: AsyncSession | None = None) -> SweepSummary:
|
||||
summary = SweepSummary()
|
||||
own = db is None
|
||||
if db is None:
|
||||
db = AsyncSessionLocal()
|
||||
try:
|
||||
policies = (await db.execute(_ENABLED_POLICIES_SQL)).fetchall()
|
||||
exports_left = MAX_EXPORTS_PER_TICK
|
||||
for tenant_id, endpoint, bucket, ak_enc, sk_enc, _years in policies:
|
||||
if exports_left <= 0:
|
||||
break
|
||||
try:
|
||||
dest = lake_archive.destination_from_policy(
|
||||
{
|
||||
"s3_endpoint": endpoint,
|
||||
"s3_bucket": bucket,
|
||||
"s3_access_key_enc": ak_enc,
|
||||
"s3_secret_key_enc": sk_enc,
|
||||
}
|
||||
)
|
||||
already = {r[0] for r in (await db.execute(_EXPORTED_MONTHS_SQL, {"tenant_id": str(tenant_id)})).fetchall()}
|
||||
for month in await _candidate_months(tenant_id, already):
|
||||
if exports_left <= 0:
|
||||
break
|
||||
manifest = await lake_archive.export_month(tenant_id, month, dest, signing_key=settings.SECRET_KEY)
|
||||
await db.execute(
|
||||
_UPSERT_PARTITION_SQL,
|
||||
{
|
||||
"tenant_id": str(tenant_id),
|
||||
"month": month,
|
||||
"manifest": json.dumps(manifest),
|
||||
},
|
||||
)
|
||||
summary.exported += 1
|
||||
exports_left -= 1
|
||||
except Exception as exc: # noqa: BLE001 — one tenant's bucket must not stop the fleet
|
||||
summary.errors.append(f"export {tenant_id}: {type(exc).__name__}")
|
||||
logger.warning("lake_archive_sweep.export_failed tenant=%s err=%s", tenant_id, exc)
|
||||
|
||||
for pid, _tenant, manifest, endpoint, bucket, ak_enc, sk_enc in (
|
||||
await db.execute(_UNVERIFIED_SQL, {"cap": MAX_VERIFIES_PER_TICK})
|
||||
).fetchall():
|
||||
try:
|
||||
dest = lake_archive.destination_from_policy(
|
||||
{
|
||||
"s3_endpoint": endpoint,
|
||||
"s3_bucket": bucket,
|
||||
"s3_access_key_enc": ak_enc,
|
||||
"s3_secret_key_enc": sk_enc,
|
||||
}
|
||||
)
|
||||
problems = await lake_archive.verify_partition(dict(manifest or {}), dest)
|
||||
if problems:
|
||||
await db.execute(_MARK_FAILED_SQL, {"id": pid, "reason": "; ".join(problems)[:1000]})
|
||||
summary.verify_failed += 1
|
||||
else:
|
||||
await db.execute(_MARK_VERIFIED_SQL, {"id": pid})
|
||||
summary.verified += 1
|
||||
except Exception as exc: # noqa: BLE001
|
||||
summary.errors.append(f"verify {pid}: {type(exc).__name__}")
|
||||
|
||||
for rid, table_name in (await db.execute(_EXPIRED_REHYDRATIONS_SQL)).fetchall():
|
||||
try:
|
||||
if table_name:
|
||||
await lake_archive.drop_rehydration_table(table_name)
|
||||
await db.execute(_MARK_EXPIRED_SQL, {"id": rid})
|
||||
summary.rehydrations_expired += 1
|
||||
except Exception as exc: # noqa: BLE001
|
||||
summary.errors.append(f"expire {rid}: {type(exc).__name__}")
|
||||
|
||||
await db.commit()
|
||||
finally:
|
||||
if own:
|
||||
await db.close()
|
||||
if summary.exported or summary.verified or summary.verify_failed or summary.rehydrations_expired or summary.errors:
|
||||
logger.info("lake_archive_sweep %s", summary)
|
||||
return summary
|
||||
|
||||
|
||||
async def run_forever() -> None:
|
||||
interval = max(int(getattr(settings, "LAKE_ARCHIVE_SWEEP_INTERVAL_SECONDS", 3600)), 300)
|
||||
logger.info("lake_archive_sweep started interval=%ds", interval)
|
||||
failures = TickFailures("lake_archive_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("lake_archive_sweep stopped")
|
||||
raise
|
||||
@@ -48,6 +48,7 @@ import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import field as dataclass_field
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
@@ -57,6 +58,7 @@ from app.core.config import settings
|
||||
from app.db.clickhouse import execute_lake_query
|
||||
from app.db.cross_tenant import assert_cross_tenant_session
|
||||
from app.db.database import AsyncSessionLocal
|
||||
from app.services import governance
|
||||
from app.services.retention import (
|
||||
_clamp,
|
||||
alerts_under_legal_hold,
|
||||
@@ -194,59 +196,164 @@ async def _load_policies(db: AsyncSession) -> list[tuple[uuid.UUID, dict[str, in
|
||||
return out
|
||||
|
||||
|
||||
async def _tenant_is_held(db: AsyncSession, tenant_id: uuid.UUID) -> list[str]:
|
||||
"""Matter references for every live hold covering this tenant, or [].
|
||||
@dataclass
|
||||
class HoldPosture:
|
||||
"""How this tenant's live holds bear on the sweep (WS2.4).
|
||||
|
||||
``freeze_refs`` — matter refs of holds that stop the WHOLE tenant's
|
||||
purge: tenant-wide holds (that is what they mean) and any subject kind
|
||||
the purge statements cannot test per row. ``narrow_holds`` — holds on
|
||||
``user`` / ``host`` / ``ip`` subjects, whose rows the purge statements
|
||||
exempt individually (within each hold's `covers_from`/`covers_until`
|
||||
window) while everything else purges on schedule.
|
||||
"""
|
||||
|
||||
freeze_refs: list[str] = dataclass_field(default_factory=list)
|
||||
narrow_holds: list[governance.LegalHold] = dataclass_field(default_factory=list)
|
||||
|
||||
|
||||
async def _hold_posture(db: AsyncSession, tenant_id: uuid.UUID) -> HoldPosture:
|
||||
"""Classify this tenant's live holds into freeze vs narrow.
|
||||
|
||||
Read before every sweep rather than cached: a hold placed between two
|
||||
runs has to take effect on the next one, and a cache measured in hours
|
||||
is a cache that deletes evidence placed under hold this morning.
|
||||
|
||||
**Why any hold stops the whole tenant.** Both purges here are bulk
|
||||
statements — one ClickHouse mutation over a tenant's aged events, one
|
||||
`DELETE` over its aged alerts — and neither can evaluate a per-subject
|
||||
predicate row by row without first enumerating which rows belong to the
|
||||
held user, host or case. So the conservative reading is the only safe
|
||||
one: if anything is held, nothing in that tenant is purged this sweep.
|
||||
That over-retains, which is recoverable; the alternative under-retains,
|
||||
which is not. Narrowing a hold to its own subjects is recorded as
|
||||
follow-up in DEPTH_PROGRESS.md rather than approximated here.
|
||||
**What narrowed, and what still freezes.** The purges used to stop the
|
||||
whole tenant on ANY live hold, because neither bulk statement could
|
||||
test a per-subject predicate row by row. They now can, for the subject
|
||||
kinds that map onto row columns (`NARROWABLE_HOLD_KINDS`: user, host,
|
||||
ip): the alerts DELETE subtracts rows matched through the affected-*
|
||||
arrays, and the lake mutation subtracts rows matched on
|
||||
user_name/hostname/IP — each within the hold's own time window. A
|
||||
tenant-wide hold, or any kind outside that set, keeps the fail-closed
|
||||
whole-tenant freeze; over-retaining is the recoverable direction.
|
||||
|
||||
The decision itself goes through ``may_purge`` so there is exactly one
|
||||
place in the tree where a hold beats a purge, and it returns a decision
|
||||
object rather than a boolean so a caller cannot read "held" as "not
|
||||
expired".
|
||||
The freeze decision still goes through ``may_purge`` so there is
|
||||
exactly one place in the tree where a hold beats a purge.
|
||||
"""
|
||||
holds = await alerts_under_legal_hold(db, tenant_id)
|
||||
posture = HoldPosture()
|
||||
if not holds:
|
||||
return []
|
||||
decision = may_purge(
|
||||
expired=True,
|
||||
# The subject of a bulk tenant purge is the tenant. Every live hold
|
||||
# in this tenant matches it, which is the fail-closed reading
|
||||
# described above.
|
||||
subjects={hold.subject_kind: hold.subject_value for hold in holds},
|
||||
holds=holds,
|
||||
)
|
||||
if decision.may_purge:
|
||||
return []
|
||||
return sorted({hold.matter_ref or hold.id for hold in holds})
|
||||
return posture
|
||||
posture.narrow_holds = [h for h in holds if h.narrows_purge()]
|
||||
freezing = [h for h in holds if not h.narrows_purge()]
|
||||
if freezing:
|
||||
decision = may_purge(
|
||||
expired=True,
|
||||
subjects={hold.subject_kind: hold.subject_value for hold in freezing},
|
||||
holds=freezing,
|
||||
)
|
||||
if not decision.may_purge:
|
||||
posture.freeze_refs = sorted({hold.matter_ref or hold.id for hold in freezing})
|
||||
return posture
|
||||
|
||||
|
||||
async def _purge_lake(tenant_id: uuid.UUID, days: int, *, dry_run: bool) -> int:
|
||||
#: One exemption arm per narrowable subject kind, ANDed with the hold's
|
||||
#: window. Static SQL fragments with numbered binds; the composer only
|
||||
#: chooses which fragments appear, never their text.
|
||||
_ALERT_HOLD_ARMS: dict[str, str] = {
|
||||
"user": (
|
||||
"EXISTS (SELECT 1 FROM jsonb_array_elements_text(coalesce(alerts.affected_users, '[]'::jsonb)) "
|
||||
"AS held_u(name) WHERE lower(held_u.name) = lower(:hold_v_{n}))"
|
||||
),
|
||||
"host": (
|
||||
"EXISTS (SELECT 1 FROM jsonb_array_elements_text(coalesce(alerts.affected_hosts, '[]'::jsonb)) "
|
||||
"AS held_h(name) WHERE lower(held_h.name) = lower(:hold_v_{n}))"
|
||||
),
|
||||
"ip": (
|
||||
"EXISTS (SELECT 1 FROM jsonb_array_elements_text(coalesce(alerts.affected_ips, '[]'::jsonb)) "
|
||||
"AS held_i(name) WHERE lower(held_i.name) = lower(:hold_v_{n}))"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def build_alert_hold_exemption(
|
||||
holds: list[governance.LegalHold],
|
||||
) -> tuple[str, dict[str, object]]:
|
||||
"""The ``AND NOT (...)`` clause exempting held alert rows, plus binds.
|
||||
|
||||
Empty holds → empty clause. Every value is a bind parameter; the only
|
||||
composition is which static arm appears for which hold.
|
||||
"""
|
||||
terms: list[str] = []
|
||||
params: dict[str, object] = {}
|
||||
for n, hold in enumerate(h for h in holds if h.narrows_purge()):
|
||||
arm = _ALERT_HOLD_ARMS[hold.subject_kind].format(n=n)
|
||||
window: list[str] = []
|
||||
params[f"hold_v_{n}"] = hold.subject_value
|
||||
if hold.covers_from is not None:
|
||||
window.append(f"alerts.created_at >= :hold_from_{n}")
|
||||
params[f"hold_from_{n}"] = hold.covers_from
|
||||
if hold.covers_until is not None:
|
||||
window.append(f"alerts.created_at <= :hold_until_{n}")
|
||||
params[f"hold_until_{n}"] = hold.covers_until
|
||||
terms.append("(" + " AND ".join([arm, *window]) + ")")
|
||||
if not terms:
|
||||
return "", {}
|
||||
return " AND NOT (" + " OR ".join(terms) + ")", params
|
||||
|
||||
|
||||
_LAKE_HOLD_ARMS: dict[str, str] = {
|
||||
"user": "lower(user_name) = lower(%(hold_v_{n})s)",
|
||||
"host": "(lower(src_hostname) = lower(%(hold_v_{n})s) OR lower(dst_hostname) = lower(%(hold_v_{n})s))",
|
||||
# IPv6 columns: compare as addresses, so '1.2.3.4' matches its mapped form.
|
||||
"ip": "(source_ip = toIPv6OrDefault(%(hold_v_{n})s) OR dest_ip = toIPv6OrDefault(%(hold_v_{n})s))",
|
||||
}
|
||||
|
||||
|
||||
def build_lake_hold_exemption(
|
||||
holds: list[governance.LegalHold],
|
||||
) -> tuple[str, dict[str, object]]:
|
||||
"""The ClickHouse ``AND NOT (...)`` clause exempting held lake rows."""
|
||||
terms: list[str] = []
|
||||
params: dict[str, object] = {}
|
||||
for n, hold in enumerate(h for h in holds if h.narrows_purge()):
|
||||
arm = _LAKE_HOLD_ARMS[hold.subject_kind].format(n=n)
|
||||
window: list[str] = []
|
||||
params[f"hold_v_{n}"] = hold.subject_value
|
||||
if hold.covers_from is not None:
|
||||
window.append(f"event_time >= %(hold_from_{n})s")
|
||||
params[f"hold_from_{n}"] = hold.covers_from
|
||||
if hold.covers_until is not None:
|
||||
window.append(f"event_time <= %(hold_until_{n})s")
|
||||
params[f"hold_until_{n}"] = hold.covers_until
|
||||
terms.append("(" + " AND ".join([arm, *window]) + ")")
|
||||
if not terms:
|
||||
return "", {}
|
||||
return " AND NOT (" + " OR ".join(terms) + ")", params
|
||||
|
||||
|
||||
async def _purge_lake(
|
||||
tenant_id: uuid.UUID,
|
||||
days: int,
|
||||
*,
|
||||
dry_run: bool,
|
||||
narrow_holds: list[governance.LegalHold] | None = None,
|
||||
) -> int:
|
||||
"""Delete (or count) lake events past the window. Returns the row count.
|
||||
|
||||
ClickHouse ``ALTER TABLE … DELETE`` does not report affected rows, so even
|
||||
on the live path we count first. That costs one scan and buys an accurate
|
||||
number in the audit trail — worth it for an operation whose whole risk is
|
||||
deleting more than intended.
|
||||
|
||||
``narrow_holds`` (WS2.4) subtracts each hold's rows — matched on
|
||||
user_name / hostnames / IPs within the hold's window — from both the
|
||||
count and the mutation, so a scoped hold protects exactly its own rows
|
||||
while the rest of the tenant purges on schedule. The lake TTL ceiling
|
||||
is untouched and untouchable; a hold older than `MAX_LAKE_DAYS` is only
|
||||
satisfiable through the archive tier, which the attestation states.
|
||||
"""
|
||||
count_result = await execute_lake_query(build_lake_count_sql(tenant_id, days))
|
||||
exempt_sql, exempt_params = build_lake_hold_exemption(narrow_holds or [])
|
||||
count_result = await execute_lake_query(build_lake_count_sql(tenant_id, days) + exempt_sql, params=exempt_params or None)
|
||||
doomed = int(count_result.rows[0][0]) if count_result.rows else 0
|
||||
if doomed == 0 or dry_run:
|
||||
return doomed
|
||||
|
||||
await execute_lake_query(
|
||||
build_lake_purge_sql(tenant_id, days),
|
||||
build_lake_purge_sql(tenant_id, days) + exempt_sql,
|
||||
params=exempt_params or None,
|
||||
extra_settings=_MUTATIONS_SYNC,
|
||||
)
|
||||
return doomed
|
||||
@@ -292,7 +399,14 @@ async def _purge_audit(db: AsyncSession, tenant_id: uuid.UUID, days: int, *, dry
|
||||
return int(removed or 0)
|
||||
|
||||
|
||||
async def _purge_alerts(db: AsyncSession, tenant_id: uuid.UUID, days: int, *, dry_run: bool) -> int:
|
||||
async def _purge_alerts(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
days: int,
|
||||
*,
|
||||
dry_run: bool,
|
||||
narrow_holds: list[governance.LegalHold] | None = None,
|
||||
) -> int:
|
||||
"""Delete (or count) alerts past the window for one tenant.
|
||||
|
||||
``build_alert_purge_sql`` relies on RLS for the tenant scope, which is
|
||||
@@ -301,16 +415,23 @@ async def _purge_alerts(db: AsyncSession, tenant_id: uuid.UUID, days: int, *, dr
|
||||
therefore bound explicitly, as a parameter. Without this the statement
|
||||
would delete every tenant's aged alerts under the first tenant's window.
|
||||
"""
|
||||
exempt_sql, exempt_params = build_alert_hold_exemption(narrow_holds or [])
|
||||
count_sql, params = build_alert_count_sql(days)
|
||||
count_sql += " AND tenant_id = :tenant_id"
|
||||
params_with_tenant: dict[str, object] = {**params, "tenant_id": str(tenant_id)}
|
||||
count_sql += " AND tenant_id = :tenant_id" + exempt_sql
|
||||
params_with_tenant: dict[str, object] = {**params, "tenant_id": str(tenant_id), **exempt_params}
|
||||
|
||||
doomed = int((await db.execute(text(count_sql), params_with_tenant)).scalar_one())
|
||||
# count_sql is machine-composed from fixed fragments; every value
|
||||
# (tenant, days, hold subjects, windows) is a bound parameter.
|
||||
doomed = int((await db.execute(text(count_sql), params_with_tenant)).scalar_one()) # nosemgrep
|
||||
if doomed == 0 or dry_run:
|
||||
return doomed
|
||||
|
||||
await db.execute(
|
||||
text("DELETE FROM alerts WHERE tenant_id = :tenant_id AND created_at < now() - make_interval(days => :days)"),
|
||||
# exempt_sql comes from build_alert_hold_exemption: fixed fragments,
|
||||
# every hold subject and window bound as :hold_* parameters.
|
||||
text( # nosemgrep
|
||||
"DELETE FROM alerts WHERE tenant_id = :tenant_id AND created_at < now() - make_interval(days => :days)" + exempt_sql
|
||||
),
|
||||
params_with_tenant,
|
||||
)
|
||||
return doomed
|
||||
@@ -346,8 +467,11 @@ async def run_once(
|
||||
audit_days=int(config.get("audit_days") or 0),
|
||||
)
|
||||
|
||||
narrow_holds: list[governance.LegalHold] = []
|
||||
try:
|
||||
result.hold_refs = await _tenant_is_held(db, tenant_id)
|
||||
posture = await _hold_posture(db, tenant_id)
|
||||
result.hold_refs = posture.freeze_refs
|
||||
narrow_holds = posture.narrow_holds
|
||||
except Exception as exc:
|
||||
# Unreadable hold evidence withholds the purge. The opposite
|
||||
# default deletes evidence under litigation because a query
|
||||
@@ -362,7 +486,7 @@ async def run_once(
|
||||
# a tenant with nothing to purge.
|
||||
held = result.held
|
||||
try:
|
||||
purged = await _purge_lake(tenant_id, policy.raw_events_days, dry_run=dry_run or held)
|
||||
purged = await _purge_lake(tenant_id, policy.raw_events_days, dry_run=dry_run or held, narrow_holds=narrow_holds)
|
||||
if held:
|
||||
result.held_lake_rows = purged
|
||||
else:
|
||||
@@ -378,7 +502,7 @@ async def run_once(
|
||||
)
|
||||
|
||||
try:
|
||||
purged = await _purge_alerts(db, tenant_id, policy.alerts_days, dry_run=dry_run or held)
|
||||
purged = await _purge_alerts(db, tenant_id, policy.alerts_days, dry_run=dry_run or held, narrow_holds=narrow_holds)
|
||||
if held:
|
||||
result.held_alert_rows = purged
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
-- WS2.1 — the archive tier: closed lake months exported to object storage
|
||||
-- in an open format, with a signed manifest and a verification trail.
|
||||
--
|
||||
-- The lake (ClickHouse `aisoc.raw_events`) holds at most `MAX_LAKE_DAYS`
|
||||
-- (400) of events — the TTL is a hard ceiling nothing exempts. Everything
|
||||
-- older exists only if it was exported first, so the archive is not a
|
||||
-- convenience: it is the only path to multi-year retention, and these two
|
||||
-- tables are its control plane and its ledger.
|
||||
--
|
||||
-- * `lake_archive_policies` — per-tenant opt-in (default OFF: writing a
|
||||
-- tenant's events to a bucket is automation the tenant configures,
|
||||
-- with their own bucket and their own credentials, vault-encrypted).
|
||||
-- * `lake_archive_partitions` — one row per exported (tenant, month):
|
||||
-- the manifest (row count, event-time bounds, schema + OCSF version,
|
||||
-- per-file SHA-256, all signed with the evidence-bundle signer) and
|
||||
-- the verification state. `exported` is a claim; `verified` means the
|
||||
-- counts and checksums were READ BACK from the bucket and matched.
|
||||
--
|
||||
-- The export itself is composed by `app/services/lake_archive.py` and runs
|
||||
-- inside ClickHouse (`INSERT INTO FUNCTION s3(...) ... FORMAT Parquet`):
|
||||
-- the database that owns the rows writes the files, and verification
|
||||
-- re-reads them through the same engine.
|
||||
|
||||
-- lane allocation: migration 170 (WS2)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lake_archive_policies (
|
||||
tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
-- How many years the archive promises. Attestation reports against
|
||||
-- this; the sweep never deletes archive objects (expiry of archived
|
||||
-- data is the bucket's lifecycle policy, stated in the docs).
|
||||
archive_years INTEGER NOT NULL DEFAULT 7
|
||||
CHECK (archive_years BETWEEN 1 AND 30),
|
||||
-- S3-compatible endpoint + bucket, the tenant's or the operator's own.
|
||||
s3_endpoint TEXT NOT NULL DEFAULT '',
|
||||
s3_bucket TEXT NOT NULL DEFAULT '',
|
||||
s3_region TEXT NOT NULL DEFAULT '',
|
||||
-- Vault-encrypted (CredentialVault `vault:v1:` tokens) — never plaintext.
|
||||
s3_access_key_enc TEXT NOT NULL DEFAULT '',
|
||||
s3_secret_key_enc TEXT NOT NULL DEFAULT '',
|
||||
-- WORM intent. Object Lock is a bucket property this service does not
|
||||
-- manage; enabling this records the operator's declaration that the
|
||||
-- bucket carries a default retention lock, and the attestation reports
|
||||
-- it as declared, never as verified.
|
||||
worm_declared BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
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 lake_archive_policies IS
|
||||
'Per-tenant archive-tier policy (WS2.1). Off until a row enables it; '
|
||||
'credentials vault-encrypted; worm_declared is an operator declaration, '
|
||||
'reported as such and never as verified.';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lake_archive_partitions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
-- The partition key: one calendar month of one tenant's events,
|
||||
-- exported only once it is CLOSED (strictly in the past).
|
||||
month DATE NOT NULL,
|
||||
|
||||
status TEXT NOT NULL DEFAULT 'exported'
|
||||
CHECK (status IN ('exported', 'verified', 'failed')),
|
||||
|
||||
-- The manifest, exactly as signed: row_count, event_time_min/max,
|
||||
-- schema_version, ocsf_version, files [{path, sha256, bytes}], plus
|
||||
-- the evidence-bundle signature envelope.
|
||||
manifest JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
|
||||
exported_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
verified_at TIMESTAMPTZ,
|
||||
-- When verification failed, what it saw — a count that differs, a
|
||||
-- checksum that differs, an object that is gone.
|
||||
failure_reason TEXT,
|
||||
|
||||
CONSTRAINT lake_archive_partitions_one_per_month UNIQUE (tenant_id, month)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE lake_archive_partitions IS
|
||||
'One row per exported (tenant, month) lake partition: the signed '
|
||||
'manifest and the verification state. exported is a claim; verified '
|
||||
'means counts and checksums were read back from the bucket and matched.';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_lake_archive_partitions_tenant
|
||||
ON lake_archive_partitions (tenant_id, month DESC);
|
||||
|
||||
-- RLS (154 shape): API writes under the request-bound GUC; the archive
|
||||
-- sweep worker reads every opted-in tenant under no GUC.
|
||||
ALTER TABLE lake_archive_policies ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE lake_archive_policies FORCE ROW LEVEL SECURITY;
|
||||
DROP POLICY IF EXISTS lake_archive_policies_tenant ON lake_archive_policies;
|
||||
CREATE POLICY lake_archive_policies_tenant ON lake_archive_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);
|
||||
|
||||
ALTER TABLE lake_archive_partitions ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE lake_archive_partitions FORCE ROW LEVEL SECURITY;
|
||||
DROP POLICY IF EXISTS lake_archive_partitions_tenant ON lake_archive_partitions;
|
||||
CREATE POLICY lake_archive_partitions_tenant ON lake_archive_partitions
|
||||
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 lake_archive_policies TO aisoc_app';
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON lake_archive_partitions TO aisoc_app';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Rollback
|
||||
-- ────────
|
||||
-- DROP TABLE IF EXISTS lake_archive_partitions;
|
||||
-- DROP TABLE IF EXISTS lake_archive_policies;
|
||||
--
|
||||
-- Objects already written to buckets are untouched either way; without the
|
||||
-- ledger they are files whose provenance has to be re-established by hand.
|
||||
@@ -0,0 +1,121 @@
|
||||
-- WS2.2 + WS2.3 — rehydration jobs and portability exports, as audited rows.
|
||||
--
|
||||
-- Rehydration brings an archived range back into a queryable table —
|
||||
-- estimate FIRST (bytes, files, retrieval cost only when a price is
|
||||
-- configured, otherwise null), then a job that loads the covered months
|
||||
-- back through ClickHouse's own s3() reader into a scratch MergeTree table
|
||||
-- with an expiry. Every rehydration records who asked and why: pulling
|
||||
-- archived events back is exactly the operation an auditor asks about.
|
||||
--
|
||||
-- Portability exports reuse the same machinery pointed at a bucket the
|
||||
-- TENANT names: Parquet + the signed manifest + a schema document, readable
|
||||
-- with no AiSOC code (the gate proves it with DuckDB).
|
||||
|
||||
-- lane allocation: migration 171 (WS2)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lake_rehydrations (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
|
||||
range_start DATE NOT NULL,
|
||||
range_end DATE NOT NULL,
|
||||
-- Optional narrowing, closed vocabulary: {"connector_type": "..."} —
|
||||
-- a filter the loader compiles into the SELECT, never caller SQL.
|
||||
filters JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
|
||||
-- The estimate shown before anything moved: bytes, files, months, and
|
||||
-- cost (null unless the deployment configured a price — a cost figure
|
||||
-- nobody configured would be an invented number).
|
||||
estimate JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
|
||||
status TEXT NOT NULL DEFAULT 'estimated'
|
||||
CHECK (status IN ('estimated', 'loading', 'ready', 'failed', 'expired')),
|
||||
-- The scratch ClickHouse table holding the rows while `ready`.
|
||||
table_name TEXT NOT NULL DEFAULT '',
|
||||
rows_loaded BIGINT,
|
||||
failure_reason TEXT,
|
||||
|
||||
-- Audit: who asked, and why — required, not decorative.
|
||||
requested_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
reason TEXT NOT NULL,
|
||||
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT lake_rehydrations_range_sane CHECK (range_start <= range_end)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE lake_rehydrations IS
|
||||
'Audited rehydration jobs (WS2.2): archived months loaded back into a '
|
||||
'scratch ClickHouse table with an expiry. The estimate precedes the '
|
||||
'load; reason and requester are required.';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_lake_rehydrations_tenant
|
||||
ON lake_rehydrations (tenant_id, created_at DESC);
|
||||
-- The expiry sweep's scan.
|
||||
CREATE INDEX IF NOT EXISTS idx_lake_rehydrations_expiry
|
||||
ON lake_rehydrations (expires_at) WHERE status = 'ready';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS lake_portability_exports (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
range_start DATE NOT NULL,
|
||||
range_end DATE NOT NULL,
|
||||
-- The TENANT's bucket — portability means the data leaves on their
|
||||
-- terms, to storage they name. Credentials are supplied per-request
|
||||
-- and are never persisted here.
|
||||
s3_endpoint TEXT NOT NULL,
|
||||
s3_bucket TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'running'
|
||||
CHECK (status IN ('running', 'complete', 'failed')),
|
||||
-- Manifest of what was written: per-month rows/files/sha256 + the
|
||||
-- schema document path, signed like the archive manifests.
|
||||
manifest JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
failure_reason TEXT,
|
||||
requested_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
reason TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
completed_at TIMESTAMPTZ,
|
||||
|
||||
CONSTRAINT lake_portability_range_sane CHECK (range_start <= range_end)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE lake_portability_exports IS
|
||||
'Audited portability exports (WS2.3): Parquet + signed manifest + schema '
|
||||
'document written to a bucket the tenant names, readable with no AiSOC '
|
||||
'code. Request credentials are used for the job and never persisted.';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_lake_portability_tenant
|
||||
ON lake_portability_exports (tenant_id, created_at DESC);
|
||||
|
||||
-- RLS (154 shape), both tables: API writes bound, workers sweep unbound.
|
||||
ALTER TABLE lake_rehydrations ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE lake_rehydrations FORCE ROW LEVEL SECURITY;
|
||||
DROP POLICY IF EXISTS lake_rehydrations_tenant ON lake_rehydrations;
|
||||
CREATE POLICY lake_rehydrations_tenant ON lake_rehydrations
|
||||
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);
|
||||
|
||||
ALTER TABLE lake_portability_exports ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE lake_portability_exports FORCE ROW LEVEL SECURITY;
|
||||
DROP POLICY IF EXISTS lake_portability_exports_tenant ON lake_portability_exports;
|
||||
CREATE POLICY lake_portability_exports_tenant ON lake_portability_exports
|
||||
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 lake_rehydrations TO aisoc_app';
|
||||
EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON lake_portability_exports TO aisoc_app';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Rollback
|
||||
-- ────────
|
||||
-- DROP TABLE IF EXISTS lake_portability_exports;
|
||||
-- DROP TABLE IF EXISTS lake_rehydrations;
|
||||
--
|
||||
-- Scratch rehydration tables in ClickHouse (aisoc.rehydrated_*) are
|
||||
-- dropped by the sweep on expiry; without this ledger, drop them by hand.
|
||||
@@ -0,0 +1,56 @@
|
||||
-- WS2.4 — legal holds scoped in time, so a hold exempts ONLY its own rows.
|
||||
--
|
||||
-- What was deferred, in the purge worker's own words: "the subject of a
|
||||
-- bulk tenant purge is the tenant. Every live hold in this tenant matches
|
||||
-- it, which is the fail-closed reading" — any single live hold froze the
|
||||
-- ENTIRE tenant's purge, over-retaining everything to avoid under-retaining
|
||||
-- anything. Subject scoping already exists (`subject_kind`/`subject_value`
|
||||
-- is a predicate precisely so a hold keeps covering rows that arrive after
|
||||
-- it is placed); what was missing is the TIME dimension and a purge that
|
||||
-- subtracts held rows instead of aborting.
|
||||
--
|
||||
-- Two columns, both nullable because an open-ended hold is legitimate:
|
||||
-- * `covers_from` — the hold covers records whose event time is on or
|
||||
-- after this instant (null: since the beginning).
|
||||
-- * `covers_until` — ... on or before this instant (null: indefinitely).
|
||||
--
|
||||
-- The narrowing itself lands in `app/services/retention.py` /
|
||||
-- `workers/retention_purge.py`: the alerts purge subtracts rows matched by
|
||||
-- a live hold's subject predicate within its window, and tenant-wide holds
|
||||
-- (`subject_kind = 'tenant'`) keep the old whole-tenant freeze, because
|
||||
-- that is what a tenant-wide hold MEANS. The lake TTL ceiling is untouched
|
||||
-- and untouchable — a hold older than `MAX_LAKE_DAYS` is only satisfiable
|
||||
-- through the archive tier (WS2.1), and the attestation says so.
|
||||
|
||||
-- lane allocation: migration 172 (WS2)
|
||||
|
||||
ALTER TABLE legal_holds
|
||||
ADD COLUMN IF NOT EXISTS covers_from TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS covers_until TIMESTAMPTZ;
|
||||
|
||||
-- An inverted window would silently cover nothing; refuse it at write time.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'legal_holds_window_sane'
|
||||
) THEN
|
||||
ALTER TABLE legal_holds
|
||||
ADD CONSTRAINT legal_holds_window_sane
|
||||
CHECK (covers_from IS NULL OR covers_until IS NULL OR covers_from <= covers_until);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
COMMENT ON COLUMN legal_holds.covers_from IS
|
||||
'The hold covers records with event time >= this (null: from the beginning).';
|
||||
COMMENT ON COLUMN legal_holds.covers_until IS
|
||||
'The hold covers records with event time <= this (null: indefinitely).';
|
||||
|
||||
-- Rollback
|
||||
-- ────────
|
||||
-- ALTER TABLE legal_holds
|
||||
-- DROP CONSTRAINT IF EXISTS legal_holds_window_sane,
|
||||
-- DROP COLUMN IF EXISTS covers_from,
|
||||
-- DROP COLUMN IF EXISTS covers_until;
|
||||
--
|
||||
-- Dropping the columns returns every hold to "covers all time", which
|
||||
-- over-retains — the recoverable direction.
|
||||
@@ -0,0 +1,135 @@
|
||||
"""The archive tier's pure halves (WS2). The engine truths live in
|
||||
``tests/isolation/test_lake_archive_live.py``; this file pins what must not
|
||||
drift without a container: path and window derivation, destination
|
||||
validation, the estimate's cost honesty, the scratch-table namespace, the
|
||||
explorer's rehydrated-table arm, and the hold-exemption SQL composers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import pytest
|
||||
from app.services import lake_archive
|
||||
from app.services.governance import LegalHold
|
||||
from app.services.lake_sql import LakeSqlForbiddenError, rewrite_for_tenant
|
||||
from app.workers.retention_purge import (
|
||||
build_alert_hold_exemption,
|
||||
build_lake_hold_exemption,
|
||||
)
|
||||
|
||||
TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")
|
||||
|
||||
|
||||
class TestPathsAndWindows:
|
||||
def test_object_path_is_deterministic_and_month_keyed(self) -> None:
|
||||
path = lake_archive.object_path(TENANT, date(2026, 9, 1))
|
||||
assert path == f"aisoc-archive/tenant={TENANT}/month=2026-09/events.parquet"
|
||||
|
||||
def test_month_bounds_cover_exactly_one_month(self) -> None:
|
||||
start, end = lake_archive.month_bounds(date(2026, 12, 1))
|
||||
assert start == datetime(2026, 12, 1, tzinfo=UTC)
|
||||
assert end == datetime(2027, 1, 1, tzinfo=UTC)
|
||||
|
||||
def test_months_in_range_is_inclusive(self) -> None:
|
||||
months = lake_archive.months_in_range(date(2026, 11, 15), date(2027, 1, 2))
|
||||
assert months == [date(2026, 11, 1), date(2026, 12, 1), date(2027, 1, 1)]
|
||||
|
||||
|
||||
class TestDestinationValidation:
|
||||
def test_a_bare_hostname_is_refused(self) -> None:
|
||||
with pytest.raises(lake_archive.ArchiveConfigError, match="s3_endpoint"):
|
||||
lake_archive.validate_destination("minio:9000", "bucket")
|
||||
|
||||
def test_a_bad_bucket_is_refused(self) -> None:
|
||||
with pytest.raises(lake_archive.ArchiveConfigError, match="s3_bucket"):
|
||||
lake_archive.validate_destination("http://minio:9000", "Bad_Bucket!")
|
||||
|
||||
def test_a_sane_destination_passes(self) -> None:
|
||||
lake_archive.validate_destination("http://minio:9000", "tenant-archive")
|
||||
|
||||
|
||||
class TestEstimateHonesty:
|
||||
def test_cost_is_null_without_a_configured_price(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB", raising=False)
|
||||
estimate = lake_archive.estimate_from_manifests([{"files": [{"path": "a", "sha256": "x", "bytes": 2_000_000_000}]}])
|
||||
assert estimate["bytes"] == 2_000_000_000
|
||||
assert estimate["retrieval_cost"] is None
|
||||
assert "unknown, not zero" in estimate["retrieval_cost_note"]
|
||||
|
||||
def test_cost_is_computed_only_from_a_configured_price(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB", "0.02")
|
||||
estimate = lake_archive.estimate_from_manifests([{"files": [{"path": "a", "sha256": "x", "bytes": 2_000_000_000}]}])
|
||||
assert estimate["retrieval_cost"] == 0.04 # type: ignore[comparison-overlap] # dict[str, Any] by construction
|
||||
assert estimate["retrieval_cost_note"] is None
|
||||
|
||||
|
||||
class TestScratchTableNamespace:
|
||||
def test_the_name_is_regex_pinned(self) -> None:
|
||||
rid = uuid.UUID("deadbeef-0000-0000-0000-000000000000")
|
||||
table = lake_archive.rehydrated_table_name(rid)
|
||||
assert table == "aisoc.rehydrated_deadbeef"
|
||||
assert lake_archive.REHYDRATED_TABLE_RE.match(table)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_drop_refuses_anything_outside_the_namespace(self) -> None:
|
||||
with pytest.raises(lake_archive.ArchiveConfigError, match="refusing to drop"):
|
||||
await lake_archive.drop_rehydration_table("aisoc.raw_events")
|
||||
|
||||
|
||||
class TestExplorerRehydratedArm:
|
||||
def test_a_rehydrated_table_gets_the_tenant_predicate(self) -> None:
|
||||
result = rewrite_for_tenant("SELECT count() FROM aisoc.rehydrated_deadbeef", TENANT)
|
||||
assert f"tenant_id = '{TENANT}'" in result.sql
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"table",
|
||||
[
|
||||
"aisoc.rehydrated_nothex", # not hex
|
||||
"aisoc.rehydrated_deadbeefcafe", # wrong length
|
||||
"aisoc.rehydrated_", # empty
|
||||
"evil.rehydrated_deadbeef", # wrong schema
|
||||
],
|
||||
)
|
||||
def test_the_arm_cannot_widen(self, table: str) -> None:
|
||||
with pytest.raises(LakeSqlForbiddenError):
|
||||
rewrite_for_tenant(f"SELECT 1 FROM {table}", TENANT)
|
||||
|
||||
|
||||
def _hold(kind: str, value: str, **kwargs) -> LegalHold:
|
||||
return LegalHold(id="h", subject_kind=kind, subject_value=value, **kwargs)
|
||||
|
||||
|
||||
class TestHoldExemptionComposers:
|
||||
def test_only_narrowable_kinds_compose(self) -> None:
|
||||
sql, params = build_alert_hold_exemption([_hold("tenant", "whole")])
|
||||
assert sql == "" and params == {}
|
||||
|
||||
def test_every_value_is_a_bind_never_a_literal(self) -> None:
|
||||
hostile = "x'); DROP TABLE alerts; --"
|
||||
sql, params = build_alert_hold_exemption([_hold("user", hostile)])
|
||||
assert hostile not in sql
|
||||
assert params["hold_v_0"] == hostile
|
||||
|
||||
def test_windows_ride_the_exemption(self) -> None:
|
||||
start = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
sql, params = build_alert_hold_exemption([_hold("user", "m", covers_from=start)])
|
||||
assert "alerts.created_at >= :hold_from_0" in sql
|
||||
assert params["hold_from_0"] == start
|
||||
|
||||
def test_the_lake_ip_arm_compares_addresses_not_strings(self) -> None:
|
||||
sql, _ = build_lake_hold_exemption([_hold("ip", "10.0.0.9")])
|
||||
assert "toIPv6OrDefault" in sql, "IPv6 columns render v4 as ::ffff:...; a string compare would miss every v4 hold"
|
||||
|
||||
def test_covers_respects_the_window(self) -> None:
|
||||
hold = _hold(
|
||||
"user",
|
||||
"m",
|
||||
covers_from=datetime(2026, 1, 1, tzinfo=UTC),
|
||||
covers_until=datetime(2026, 2, 1, tzinfo=UTC),
|
||||
)
|
||||
subjects = {"user": "M"}
|
||||
assert hold.covers(subjects, at=datetime(2026, 1, 15, tzinfo=UTC))
|
||||
assert not hold.covers(subjects, at=datetime(2026, 3, 1, tzinfo=UTC))
|
||||
# A caller that cannot date the record gets the over-retaining answer.
|
||||
assert hold.covers(subjects, at=None)
|
||||
@@ -99,9 +99,11 @@ class _LakeRecorder:
|
||||
def __init__(self, counts: Mapping[uuid.UUID, int]):
|
||||
self._counts = counts
|
||||
self.queries: list[str] = []
|
||||
self.params_seen: list[dict[str, Any]] = []
|
||||
|
||||
async def __call__(self, sql: str, *_args: Any, **_kwargs: Any) -> Any:
|
||||
self.queries.append(sql)
|
||||
self.params_seen.append(dict(_kwargs.get("params") or {}))
|
||||
if sql.startswith("SELECT count()"):
|
||||
for tenant, count in self._counts.items():
|
||||
if str(tenant) in sql:
|
||||
@@ -120,7 +122,9 @@ class _LakeResult:
|
||||
|
||||
|
||||
def _hold(subject_kind: str = "tenant", subject_value: str = str(TENANT), matter: str = "LIT-2026-11") -> tuple:
|
||||
return (uuid.uuid4(), subject_kind, subject_value, matter)
|
||||
# Mirrors the 6-column SELECT in `alerts_under_legal_hold` (migration 172
|
||||
# added the covers_from/covers_until window; None/None = all time).
|
||||
return (uuid.uuid4(), subject_kind, subject_value, matter, None, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -169,10 +173,14 @@ class TestAHoldOutranksThePurge:
|
||||
assert run.tenants_held == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_hold_on_a_user_still_stops_the_bulk_purge(self, patched) -> None:
|
||||
"""A bulk statement cannot evaluate a per-subject predicate row by
|
||||
row, so the conservative reading is the only safe one: anything held
|
||||
stops the sweep for that tenant. Over-retaining is recoverable."""
|
||||
async def test_a_hold_on_a_user_narrows_the_purge_to_exempt_its_rows(self, patched) -> None:
|
||||
"""Deliberately supersedes the whole-tenant freeze this test used to
|
||||
pin (WS2.4, migration 172). The old rationale — "a bulk statement
|
||||
cannot evaluate a per-subject predicate row by row" — stopped being
|
||||
true when the purge statements gained per-hold exemption clauses:
|
||||
a user/host/ip hold now subtracts exactly its own rows (within its
|
||||
window) and the REST of the tenant purges on schedule. A tenant-wide
|
||||
hold still freezes everything, pinned by the test above this one."""
|
||||
session, lake = patched(
|
||||
holds={TENANT: [_hold(subject_kind="user", subject_value="svc-backup", matter="LIT-9")]},
|
||||
lake={TENANT: 10},
|
||||
@@ -181,8 +189,15 @@ class TestAHoldOutranksThePurge:
|
||||
|
||||
run = await retention_purge.run_once(db=session, dry_run=False)
|
||||
|
||||
assert lake.deletes == []
|
||||
assert run.held_lake_rows == 10
|
||||
# The purge RAN — the hold no longer freezes the tenant...
|
||||
assert run.tenants[0].hold_refs == []
|
||||
assert len(lake.deletes) == 1
|
||||
# ...and the mutation carries the exemption for exactly the held user.
|
||||
assert "AND NOT ((lower(user_name) = lower(%(hold_v_0)s)))" in lake.deletes[0]
|
||||
assert lake.params_seen and lake.params_seen[-1].get("hold_v_0") == "svc-backup"
|
||||
# The run reports the purge as a purge, not as a freeze.
|
||||
assert run.held_lake_rows == 0
|
||||
assert run.tenants[0].lake_rows == 10
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unreadable_hold_evidence_withholds_rather_than_proceeds(self, patched, monkeypatch) -> None:
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
"""The archive tier against live ClickHouse + MinIO + Postgres (WS2).
|
||||
|
||||
Why this has to be live
|
||||
-----------------------
|
||||
* The export, the count read-back and the SHA-256 all run **inside
|
||||
ClickHouse** (`INSERT INTO FUNCTION s3`, `s3(...,'Parquet')`,
|
||||
`s3(...,'RawBLOB')`) — a stub proves none of them, and the parameter
|
||||
binding into table-function arguments is exactly the kind of claim that
|
||||
only a real engine can confirm.
|
||||
* Corruption detection is the point of verification: this suite flips one
|
||||
byte in the bucket and the verifier must FAIL naming the checksum — a
|
||||
verifier that stays green over a corrupted object is worse than none.
|
||||
* Portability means **no AiSOC code**: DuckDB (a third-party reader) opens
|
||||
the exported Parquet and the row count matches the signed manifest.
|
||||
* The rehydrated scratch table must be queryable through the explorer's
|
||||
own rewriter, under the same tenant predicate raw_events gets.
|
||||
* The scoped-hold purge narrowing is SQL the unit tests can only shape-check:
|
||||
here a held user's aged alerts survive the purge while the rest delete.
|
||||
|
||||
Environment (all required; the CI step provisions them):
|
||||
LAKE_ARCHIVE_LIVE_CH_HOST / _CH_PORT / _CH_USER / _CH_PASSWORD
|
||||
LAKE_ARCHIVE_LIVE_S3_ENDPOINT_FOR_CH (what ClickHouse can reach)
|
||||
LAKE_ARCHIVE_LIVE_S3_ENDPOINT (what this process can reach)
|
||||
LAKE_ARCHIVE_LIVE_S3_ACCESS / _S3_SECRET
|
||||
LAKE_ARCHIVE_LIVE_PG_ADMIN_DSN (owner, fixtures)
|
||||
LAKE_ARCHIVE_LIVE_PG_DSN (aisoc_app, assertions)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import UTC, date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.asyncio(loop_scope="module"),
|
||||
pytest.mark.skipif(
|
||||
not os.environ.get("LAKE_ARCHIVE_LIVE_CH_HOST", "").strip(),
|
||||
reason="LAKE_ARCHIVE_LIVE_CH_HOST is not set; this suite needs live ClickHouse + MinIO + Postgres",
|
||||
),
|
||||
]
|
||||
|
||||
_API = Path(__file__).resolve().parents[2] / "services" / "api"
|
||||
if str(_API) not in sys.path:
|
||||
sys.path.insert(0, str(_API))
|
||||
|
||||
TENANT = uuid.uuid4()
|
||||
OTHER_TENANT = uuid.uuid4()
|
||||
MONTH = date(2026, 9, 1)
|
||||
SIGNING_KEY = "live-archive-signing-key"
|
||||
|
||||
|
||||
def _env(name: str) -> str:
|
||||
return os.environ[name].strip()
|
||||
|
||||
|
||||
def _configure_clickhouse_settings() -> None:
|
||||
"""Point the API's lake client at the harness ClickHouse.
|
||||
|
||||
Must run before `app.db.clickhouse` builds its client; the fixture
|
||||
imports app modules only after this."""
|
||||
os.environ.setdefault("CLICKHOUSE_HOST", _env("LAKE_ARCHIVE_LIVE_CH_HOST"))
|
||||
os.environ.setdefault("CLICKHOUSE_PORT", os.environ.get("LAKE_ARCHIVE_LIVE_CH_PORT", "9000"))
|
||||
os.environ.setdefault("CLICKHOUSE_USER", os.environ.get("LAKE_ARCHIVE_LIVE_CH_USER", "aisoc"))
|
||||
os.environ.setdefault("CLICKHOUSE_PASSWORD", os.environ.get("LAKE_ARCHIVE_LIVE_CH_PASSWORD", ""))
|
||||
os.environ.setdefault("CLICKHOUSE_DATABASE", "aisoc")
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(scope="module", loop_scope="module")
|
||||
async def harness():
|
||||
_configure_clickhouse_settings()
|
||||
import asyncpg
|
||||
from app.db.clickhouse import execute_lake_query
|
||||
from app.services import lake_archive
|
||||
|
||||
dest_for_ch = lake_archive.Destination(
|
||||
endpoint=_env("LAKE_ARCHIVE_LIVE_S3_ENDPOINT_FOR_CH"),
|
||||
bucket="tenant-archive",
|
||||
access_key=_env("LAKE_ARCHIVE_LIVE_S3_ACCESS"),
|
||||
secret_key=_env("LAKE_ARCHIVE_LIVE_S3_SECRET"),
|
||||
)
|
||||
|
||||
# Seed one closed month for the tenant (plus noise: another tenant and
|
||||
# a newer month) through the lake's own insert path.
|
||||
rows = []
|
||||
for day in (3, 12, 21):
|
||||
rows.append((str(TENANT), datetime(2026, 9, day, 10, 0, tzinfo=UTC), "mallory@example.com"))
|
||||
rows.append((str(TENANT), datetime(2026, 10, 2, 10, 0, tzinfo=UTC), "mallory@example.com"))
|
||||
rows.append((str(OTHER_TENANT), datetime(2026, 9, 5, 10, 0, tzinfo=UTC), "bystander@example.com"))
|
||||
for tenant_id, ts, user in rows:
|
||||
await execute_lake_query(
|
||||
"""
|
||||
INSERT INTO aisoc.raw_events (event_id, tenant_id, event_time, ingest_time, user_name,
|
||||
connector_type, action, severity, severity_id, raw_payload)
|
||||
VALUES (%(eid)s, %(tid)s, %(ts)s, %(ts)s, %(user)s, 'm365_audit', 'FileUploaded', 'low', 2, '{}')
|
||||
""",
|
||||
params={"eid": str(uuid.uuid4()), "tid": tenant_id, "ts": ts, "user": user},
|
||||
)
|
||||
|
||||
admin = await asyncpg.connect(_env("LAKE_ARCHIVE_LIVE_PG_ADMIN_DSN"))
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
for tenant, label in ((TENANT, f"arch-a-{suffix}"), (OTHER_TENANT, f"arch-b-{suffix}")):
|
||||
await admin.execute(
|
||||
"INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $2) ON CONFLICT (id) DO NOTHING",
|
||||
tenant,
|
||||
label,
|
||||
)
|
||||
yield execute_lake_query, lake_archive, dest_for_ch, admin
|
||||
|
||||
for tenant in (TENANT, OTHER_TENANT):
|
||||
await admin.execute("DELETE FROM lake_archive_partitions WHERE tenant_id = $1", tenant)
|
||||
await admin.execute("DELETE FROM lake_rehydrations WHERE tenant_id = $1", tenant)
|
||||
await admin.execute("DELETE FROM legal_holds WHERE tenant_id = $1", tenant)
|
||||
await admin.execute("DELETE FROM alerts WHERE tenant_id = $1", tenant)
|
||||
await admin.execute("DELETE FROM tenants WHERE id = $1", tenant)
|
||||
await admin.close()
|
||||
|
||||
|
||||
async def test_export_builds_a_signed_manifest_and_verification_passes(harness):
|
||||
_execute, lake_archive, dest, _admin = harness
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
assert manifest["row_count"] == 3 # the other tenant's row and October stayed out
|
||||
assert manifest["schema_version"] == lake_archive.ARCHIVE_SCHEMA_VERSION
|
||||
assert manifest["files"][0]["sha256"] and manifest["files"][0]["bytes"] > 0
|
||||
assert manifest["signature"], "the manifest must carry the evidence-bundle signature"
|
||||
|
||||
problems = await lake_archive.verify_partition(manifest, dest)
|
||||
assert problems == [], f"verification must pass on an untouched object: {problems}"
|
||||
|
||||
|
||||
async def test_an_open_month_is_refused(harness):
|
||||
_execute, lake_archive, dest, _admin = harness
|
||||
today = datetime.now(UTC).date()
|
||||
with pytest.raises(lake_archive.ArchiveConfigError, match="not closed"):
|
||||
await lake_archive.export_month(TENANT, date(today.year, today.month, 1), dest, signing_key=SIGNING_KEY)
|
||||
|
||||
|
||||
async def test_corruption_is_detected_by_name(harness):
|
||||
"""Flip the object's bytes; the verifier must fail on the checksum."""
|
||||
_execute, lake_archive, dest, _admin = harness
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
key = manifest["files"][0]["path"]
|
||||
|
||||
# Corrupt through the same engine that wrote it: curl's SigV4 refuses
|
||||
# keys containing '=' (the partition path), and the point is only that
|
||||
# the bytes in the bucket change under the manifest.
|
||||
from app.db.clickhouse import execute_lake_query as _elq
|
||||
|
||||
await _elq(
|
||||
"INSERT INTO FUNCTION s3(%(url)s, %(ak)s, %(sk)s, 'RawBLOB', 'raw String') VALUES ('corrupted-bytes-not-parquet')",
|
||||
params={"url": dest.url(key), "ak": dest.access_key, "sk": dest.secret_key},
|
||||
extra_settings={"s3_truncate_on_insert": 1},
|
||||
)
|
||||
|
||||
problems = await lake_archive.verify_partition(manifest, dest)
|
||||
assert problems, "a corrupted object must fail verification"
|
||||
assert any("sha256 differs" in p or "unreadable" in p or "row count differs" in p for p in problems), problems
|
||||
|
||||
# Restore the real object for the suites below.
|
||||
restored = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
assert await lake_archive.verify_partition(restored, dest) == []
|
||||
|
||||
|
||||
async def test_a_same_count_content_swap_is_caught_by_the_checksum_alone(harness):
|
||||
"""The sharper corruption: a VALID Parquet object with the SAME row
|
||||
count but different bytes (re-written with a different compression
|
||||
codec). The count read-back passes; only the SHA-256 leg can refuse it
|
||||
— which is why the manifest carries one."""
|
||||
execute_lake_query, lake_archive, dest, _admin = harness
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
key = manifest["files"][0]["path"]
|
||||
start, end = lake_archive.month_bounds(MONTH)
|
||||
|
||||
# Same rows, different bytes: recompress the object in place.
|
||||
await execute_lake_query(
|
||||
"""
|
||||
INSERT INTO FUNCTION s3(%(url)s, %(ak)s, %(sk)s, 'Parquet')
|
||||
SELECT * REPLACE (toString(event_id) AS event_id, toString(tenant_id) AS tenant_id,
|
||||
toString(source_ip) AS source_ip, toString(dest_ip) AS dest_ip)
|
||||
FROM aisoc.raw_events
|
||||
WHERE tenant_id = %(tenant_id)s AND event_time >= %(start)s AND event_time < %(end)s
|
||||
""",
|
||||
params={
|
||||
"url": dest.url(key),
|
||||
"ak": dest.access_key,
|
||||
"sk": dest.secret_key,
|
||||
"tenant_id": str(TENANT),
|
||||
"start": start,
|
||||
"end": end,
|
||||
},
|
||||
extra_settings={
|
||||
"s3_truncate_on_insert": 1,
|
||||
"output_format_parquet_compression_method": "gzip",
|
||||
},
|
||||
)
|
||||
|
||||
problems = await lake_archive.verify_partition(manifest, dest)
|
||||
assert problems, "a content swap with an unchanged row count must still fail"
|
||||
assert any("sha256 differs" in p for p in problems), problems
|
||||
assert not any("row count differs" in p for p in problems), (
|
||||
"this case must isolate the checksum leg; the counts are equal by construction"
|
||||
)
|
||||
|
||||
restored = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
assert await lake_archive.verify_partition(restored, dest) == []
|
||||
|
||||
|
||||
async def test_rehydration_loads_a_queryable_tenant_scoped_table(harness):
|
||||
execute_lake_query, lake_archive, dest, _admin = harness
|
||||
from app.services.lake_sql import rewrite_for_tenant
|
||||
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
rid = uuid.uuid4()
|
||||
table, loaded = await lake_archive.load_rehydration(rid, TENANT, [manifest], dest)
|
||||
try:
|
||||
assert loaded == 3
|
||||
# The explorer's own rewriter accepts the scratch table and injects
|
||||
# the tenant predicate; the other tenant reads zero rows from it.
|
||||
mine = await execute_lake_query(rewrite_for_tenant(f"SELECT count() FROM {table}", TENANT).sql)
|
||||
assert int(mine.rows[0][0]) == 3
|
||||
theirs = await execute_lake_query(rewrite_for_tenant(f"SELECT count() FROM {table}", OTHER_TENANT).sql)
|
||||
assert int(theirs.rows[0][0]) == 0
|
||||
finally:
|
||||
await lake_archive.drop_rehydration_table(table)
|
||||
|
||||
|
||||
async def test_estimate_reports_real_bytes_and_null_cost_without_a_price(harness):
|
||||
_execute, lake_archive, dest, _admin = harness
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
os.environ.pop("AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB", None)
|
||||
estimate = lake_archive.estimate_from_manifests([manifest])
|
||||
assert estimate["bytes"] == manifest["files"][0]["bytes"]
|
||||
assert estimate["files"] == 1 and estimate["months"] == 1
|
||||
assert estimate["retrieval_cost"] is None
|
||||
assert "unknown, not zero" in estimate["retrieval_cost_note"]
|
||||
|
||||
|
||||
async def test_portability_export_reads_with_duckdb_and_no_aisoc_code(harness):
|
||||
_execute, lake_archive, _dest, _admin = harness
|
||||
duckdb = pytest.importorskip("duckdb", reason="the portability gate needs duckdb installed")
|
||||
|
||||
dest = lake_archive.Destination(
|
||||
endpoint=_env("LAKE_ARCHIVE_LIVE_S3_ENDPOINT_FOR_CH"),
|
||||
bucket="tenant-export",
|
||||
access_key=_env("LAKE_ARCHIVE_LIVE_S3_ACCESS"),
|
||||
secret_key=_env("LAKE_ARCHIVE_LIVE_S3_SECRET"),
|
||||
)
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY, prefix="aisoc-portability")
|
||||
key = manifest["files"][0]["path"]
|
||||
|
||||
host_endpoint = _env("LAKE_ARCHIVE_LIVE_S3_ENDPOINT")
|
||||
con = duckdb.connect()
|
||||
con.execute("INSTALL httpfs; LOAD httpfs;")
|
||||
host = host_endpoint.removeprefix("http://").removeprefix("https://")
|
||||
con.execute(f"SET s3_endpoint='{host}'")
|
||||
con.execute("SET s3_use_ssl=false")
|
||||
con.execute("SET s3_url_style='path'")
|
||||
con.execute(f"SET s3_access_key_id='{dest.access_key}'")
|
||||
con.execute(f"SET s3_secret_access_key='{dest.secret_key}'")
|
||||
count = con.execute(f"SELECT count(*) FROM read_parquet('s3://{dest.bucket}/{key}')").fetchone()[0]
|
||||
assert count == manifest["row_count"], f"DuckDB read {count} rows; the signed manifest says {manifest['row_count']}"
|
||||
|
||||
|
||||
async def test_scoped_hold_narrows_the_alert_purge_to_its_own_rows(harness):
|
||||
"""Two aged alerts for the held user survive; three others delete —
|
||||
against real Postgres, through the worker's own purge function."""
|
||||
_execute, _lake_archive, _dest, admin = harness
|
||||
from app.workers import retention_purge
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
for n in range(3):
|
||||
await admin.execute(
|
||||
"""
|
||||
INSERT INTO alerts (id, tenant_id, title, severity, status, created_at, affected_users)
|
||||
VALUES ($1, $2, $3, 'low', 'resolved', now() - interval '400 days', $4::jsonb)
|
||||
""",
|
||||
uuid.uuid4(),
|
||||
TENANT,
|
||||
f"aged unheld {n}",
|
||||
'["alice@example.com"]',
|
||||
)
|
||||
for n in range(2):
|
||||
await admin.execute(
|
||||
"""
|
||||
INSERT INTO alerts (id, tenant_id, title, severity, status, created_at, affected_users)
|
||||
VALUES ($1, $2, $3, 'low', 'resolved', now() - interval '400 days', $4::jsonb)
|
||||
""",
|
||||
uuid.uuid4(),
|
||||
TENANT,
|
||||
f"aged HELD {n}",
|
||||
'["Mallory@Example.com"]',
|
||||
)
|
||||
await admin.execute(
|
||||
"""
|
||||
INSERT INTO legal_holds (tenant_id, name, subject_kind, subject_value, covers_from)
|
||||
VALUES ($1, 'live matter', 'user', 'mallory@example.com', now() - interval '3 years')
|
||||
""",
|
||||
TENANT,
|
||||
)
|
||||
|
||||
dsn = _env("LAKE_ARCHIVE_LIVE_PG_ADMIN_DSN").replace("postgresql://", "postgresql+asyncpg://")
|
||||
engine = create_async_engine(dsn, poolclass=None)
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
try:
|
||||
async with factory() as db:
|
||||
posture = await retention_purge._hold_posture(db, TENANT)
|
||||
assert posture.freeze_refs == [], "a user hold must not freeze the tenant"
|
||||
assert len(posture.narrow_holds) == 1
|
||||
purged = await retention_purge._purge_alerts(db, TENANT, days=365, dry_run=False, narrow_holds=posture.narrow_holds)
|
||||
await db.commit()
|
||||
assert purged == 3, f"expected the 3 unheld aged alerts to purge, got {purged}"
|
||||
finally:
|
||||
await engine.dispose()
|
||||
survivors = await admin.fetch("SELECT title FROM alerts WHERE tenant_id = $1 ORDER BY title", TENANT)
|
||||
titles = [r["title"] for r in survivors]
|
||||
assert titles == ["aged HELD 0", "aged HELD 1"], titles
|
||||
|
||||
|
||||
async def test_attestation_reports_each_tier_from_its_own_store(harness):
|
||||
_execute, lake_archive, dest, admin = harness
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
manifest = await lake_archive.export_month(TENANT, MONTH, dest, signing_key=SIGNING_KEY)
|
||||
import json as _json
|
||||
|
||||
await admin.execute(
|
||||
"""
|
||||
INSERT INTO lake_archive_partitions (tenant_id, month, status, manifest, verified_at)
|
||||
VALUES ($1, $2, 'verified', $3::jsonb, now())
|
||||
ON CONFLICT (tenant_id, month) DO UPDATE SET status='verified', manifest=EXCLUDED.manifest, verified_at=now()
|
||||
""",
|
||||
TENANT,
|
||||
MONTH,
|
||||
_json.dumps(manifest),
|
||||
)
|
||||
dsn = _env("LAKE_ARCHIVE_LIVE_PG_ADMIN_DSN").replace("postgresql://", "postgresql+asyncpg://")
|
||||
engine = create_async_engine(dsn, poolclass=None)
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
try:
|
||||
async with factory() as db:
|
||||
attestation = await lake_archive.retention_attestation(db, TENANT, lake_days=400, worm_declared=False)
|
||||
finally:
|
||||
await engine.dispose()
|
||||
assert attestation["archive"]["partitions"] >= 1
|
||||
assert attestation["archive"]["verified"] >= 1
|
||||
assert attestation["archive"]["worm"] == "not declared"
|
||||
assert attestation["hot_and_lake"]["oldest_row"], "the lake has rows; oldest must be measured"
|
||||
holds = attestation["legal_holds"]
|
||||
assert holds and holds[0]["narrows_purge"] is True
|
||||
Reference in New Issue
Block a user