mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the other four plans. 0.2 re-derives every figure the plan captured. All twenty reproduce exactly except the cloud/identity/SaaS/code condition count, which the plan itself flagged as approximate: measured 344 against 'about 358'. D1 records why, and the finding underneath it — no script in the tree implements that sentence, so every published value of it was hand-counted with a slightly different product set, and windowed rules contribute zero because they carry no product field at all. Phase 2.1's gate has to decide that explicitly. 0.3 captures the baselines, including 'make up-full' — the one the first depth plan recorded as never captured (its D2). 22 containers on the full profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine unrelated containers on it including a foreign Postgres on 5432, and 'make up-full' failed its first bind before the port resolver's overlay landed. D2 records the sequence and, deliberately, does not claim a defect from it: the preceding state is not replayable, so it carries a clean-host reproduction as a follow-up instead. 0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The README's 'Not a drop-in SIEM replacement' is now a decided position with its cost argument — compliance search needs raw-payload retention outside the 8 GB CORE budget and an availability promise this project has no measured evidence it can keep. Proposed, and nothing in this plan builds from it. * depth2 Lane F: claim migrations 151-158 and ADR 0022 * 3.3: failing test — a repeated vendor finding leaves no count A same-fingerprint repeat is collapsed by three independent layers and kept by none of them. The only trace is a source_event_ids append, which answers 'did more than one event produce this' and nothing else: it also grows on multi-event correlation, so its length is not a repeat count, and it stops at 200. alerts.first_seen and alerts.last_seen have existed since 001_init and fusion has never written either, so the window the repeats span is recorded nowhere. 5 of 7 fail on this tree with 'no statement touched alert_occurrences'. * 3.3: keep a repeated vendor finding as a linked occurrence A same-fingerprint repeat was collapsed by three layers and kept by none. The only residue was a `source_event_ids` append — capped at 200 and shared with multi-event correlation, so its length was never a repeat count — and `alerts.first_seen` / `last_seen` have existed since 001_init with no writer at all, so the window the repeats spanned was recorded nowhere. `alert_occurrences` (migration 151) is a rollup keyed (tenant_id, alert_id): an exact count that includes the surviving alert, the real first- and last-seen window, and a bounded most-recent window of the original payload ids. A vendor re-reporting one finding 79 times is one alert that says 79. A rollup rather than a row per occurrence because "one indicator, a thousand rows" is the shape the retro-hunt sweep already refuses. The payload window evicts oldest-first so the jsonb containment guard's coverage sits where Kafka redelivery actually happens, and `payload_ids_complete` goes false the moment anything is evicted. The measurement is published as its own labelled row and never added to correlation: 28.4 % repeat folding (1000 inputs -> 716 alerts, 284 folded) beside 33.3 % and 24.5 % correlation. The reduction is identical before and after this change and the docs say so — folding is not new, keeping what it folded is. What changed is that 284 inputs are accounted for instead of absent, which the suite asserts as a four-bucket balance summing to the denominator plus a requirement that each folded repeat resolve to the id of the alert that absorbed it. Writing the live suite found a defect in this change's own migration. The conventional `WITH CHECK (tenant_id = current_tenant_id())` makes the row unwritable by fusion, which is a Kafka consumer and binds no tenant session; measured as `aisoc_app` (NOBYPASSRLS), the identical session inserts into `alerts` and is refused here. Because the write is deliberately best-effort it would have failed in silence and the feature would have read as "this vendor never repeats" — migration 123's defect exactly. The policy now mirrors `alerts_tenant`, with the reasoning in the migration. Negative controls, both measured: reverting the WITH CHECK fails all six live cases; removing the containment guard takes five redeliveries of one message from a count of 2 to 7. Baselines unchanged: 33.3 % and 24.5 % reduction, zero cross-rule groups. * 4.6 and 9.4: record what has not been measured, and gate the absence 4.6 — outcome evidence. The three outcomes a buyer asks for first can only be measured by replaying somebody's real closed alerts through `make replay-eval`; the grader compares AiSOC's verdict with a human decision, so the input cannot be synthesised without the measurement becoming a comparison with a fixture written to be compared against. No design partner has offered a window, so false-positive reduction, time to verdict and escalation rate are recorded as *not measured* with the exact two-command reproduction beside them. `check_outcome_claims.py` is what makes that record worth anything. While the replay page says an outcome is unmeasured, no published surface may print a number for it — including `0`, which is the more damaging of the two, because a zero says AiSOC was measured against a real queue and reduced nothing, and it looks like data. The prohibition is read off the replay page rather than hardcoded, so a real measurement retires it without anyone editing the gate: a gate that had to be edited to admit a measurement would be edited to admit a fabrication. Its first run flagged a true sentence — a capability table row naming `escalation rate` in a list beside an unrelated "auto-refresh every 60s" — so the rule narrowed from same-line to same-clause, with both that case and a real claim in the identical row shape pinned in the self-test. A gate that flags correct content gets switched off within a week. 9.4 — the Teams half. Verified rather than assumed: the war room is built, and `POST /war-room` answers 501 naming each absent Microsoft Graph setting instead of falling back to the incoming webhook, because one shared channel per deployment puts the next incident's traffic in the last one's thread. That is already pinned by `services/teams-bot/tests/test_war_room.py`. It is maintainer-blocked on an Entra application registration with Channel.Create, ChannelMessage.Send and Group.ReadWrite.All, admin consent and a team id — recorded as a claim row so the honest refusal cannot quietly become a fallback. Matrix 335 -> 337 rows, 332 GATED, tallies moved in lockstep. * 5.2: run a scheduled hunt on the lake, and label what it emails Two gaps, both of the "built but nothing connects them" family. The scheduler could only run a hunt against a warehouse the tenant had connected: `resolve_provider` required `connected_types.intersection(provider.connector_types)`, and `_execute_hunt` converts the resulting `UnsupportedTranslation` into a hit count of **zero**. Zero hits is not an error state — no case opens, nothing logs above INFO, and `last_run_at` moves — so on every surface it was indistinguishable from "your hunt ran and found nothing". That was the answer on every deployment whose data lives in AiSOC's own lake, which is the default deployment, because AiSOC's own connectors put it there. This is the half the `credentials.py` fix could not reach. That one gave providers the tenant's connector credentials; this is a tenant who has connected nothing for credentials to come from. `LakeProvider` declares no connector types, because there is no connector to resolve — the lake's address is deployment configuration. The registry treats an empty `connector_types` as "needs no connected warehouse", checked after the connector-backed chain so a tenant's own SIEM always wins: it holds years of history AiSOC never ingested, and answering from the lake instead would be a narrower answer to the same question given without anybody choosing it. Scoping is through `compile_hunt`, which binds the tenant structurally and asserts the predicate survived — not `rewrite_for_tenant`, which exists to constrain untrusted operator SQL. An unreachable lake raises rather than returning zero, so the hunt retries instead of moving its clock. Conditions the lake schema cannot express are logged by name, because a hunt that ran with two of its four conditions dropped found fewer matches than was asked about. ADR-0015 requires the emailed hunt PDF to be labelled as hunting output. Before this, `rg -i "hunting output"` matched only the ADR itself: the renderer emitted the row's own title and nothing else. The label is now in the banner, the page title and the mail subject, with a sentence saying what the document does not claim — a reader who does not know the phrase learns nothing from the phrase alone. Delivery itself did not exist. `render_pdf`, `build_from_hunt`, `persist` and `send_mail` all worked; `aisoc_hunt_reports` and the report scheduler's `ReportArtefact` are different surfaces and were never connected, so a hunt report could be generated and downloaded and could not be sent. It ships off: `AISOC_HUNT_REPORT_RECIPIENTS` unset means nobody asked for this. A hunt that matched nothing mails nothing, a missing WeasyPrint stack sends the HTML rather than nothing, and a failing relay never costs the case. The protocol's `credentials` is widened to `| None` rather than suppressed at the call site: the scheduler genuinely passes None for such a provider, and a signature saying otherwise would be the type checker agreeing with a contract the code does not keep. Negative control: removing the empty-connector_types arm from `resolve_provider` fails the reproduction and the scheduler-wiring case. API suite 5042 passed, 174 skipped. Matrix 337 -> 339 rows, 334 GATED. * 9.2: record the device block, and correct a README row that overstated The mobile capability table read "Voice input — Transcription is on-device by construction", which is true of the module and reads as a working feature. `apps/mobile/src/lib/voice.ts` has no recogniser behind it and no screen importing it: the only file in this repository that mentions it is that README. The row now says so, and keeps the half that is real — the module takes a recogniser returning a *string*, so no audio type appears in its signature, a device with no offline model is refused rather than silently using the platform's cloud recogniser, and check_no_audio_egress.py fails the build on any capture API or binary body. That is a design that cannot leak audio. It is not a feature that works. 9.2 proper is blocked twice over and the second row says both halves: the voice path needs 9.1's recogniser and screen to exist at all, and then an Apple developer account and provisioning profile, or a Google Play account, to reach a handset somebody can speak to. The Android assembleDebug APK does install on a handset, so once 9.1 lands the Android half becomes a device question rather than a credentials one. The mobile.yml README-honesty guard is extended rather than left behind — the workflow's own header records that "we added a build so the honesty check is no longer needed" is how an ungated claim returns. It now pins both new rows and asserts its own vacuous-pass case, since a guard that greps four patterns in a file it never opened reports success. Negative control: restoring the previous wording fails the voice-input pattern. DEPTH2_PROGRESS gains deviations D3 (four Lane F items that did not reproduce as the plan describes them, with what is actually missing) and D4. * 3.2: link alerts into stories by typed evidence, not by string match Built on attack_chain_grouper rather than beside it. It chained alerts sharing a host, user or source-IP *string*, first match wins in a fixed order, with nothing on the result saying which of the three had done it. So a NAT egress address or a shared jump host welded two unrelated intrusions into one story; an alert carrying a session id — which fusion has written onto the alert row since migration 102, alongside the human resolved behind an assumed-role chain — got no more weight than one carrying a hostname, so the strongest evidence available went unused; and `ChainMember` carried a per-member severity that nothing aggregated, so the plan's "a member benign alone may be escalated by its story" had nowhere to happen and no reason to record. Links are now typed and carry a strength, and the strength decides what a link may do. Session and resolved human are strong; file hash and domain are specific; bare entity strings are weak. A weak link may not merge two detection rules, which is what keeps v21's narrowing from being undone one layer up where the published 24.5 % cannot see it. A strong or specific link may cross rules, and the assignment records which link did it so every cross-rule story is enumerated rather than tolerated. Story severity rises by exactly one tier, never past critical, and only when the story spans three or more kill-chain stages — one alert is an alert, two can be one action seen twice, three stages on one authenticated context is a narrative. Members carrying no tactic do not count toward the span, so three tactic-less detection alerts cannot escalate each other. The reason travels on the assignment, because an escalation whose cause is in a log line cannot be audited from the alert. Actor mode is `unknown` until Lane A's 1.4 supplies cadence. Two inferences were considered and rejected in the code: a credential session with no resolved human is unresolved rather than automated, and a service-account shaped username is a naming convention rather than evidence. Measured over three labelled multi-stage scenarios interleaved with unrelated traffic sharing the tenant's NAT egress address: recall 100 % on all three (4/4, 3/3, 2/2), purity 100 % (5/5 stories), 0 cross-rule stories of 63 on a detection-shaped cohort. The purity rule was found by that measurement rather than reasoned out in advance. The first cut refused a weak link only when it crossed detection rules, and the suite immediately measured 75 %: the scenario alerts carry no rule_id, so the cross-rule arm had nothing to compare and an antivirus quarantine joined a phishing-to-exfiltration story on a shared address. A weak link now also may not join a story anchored on strong evidence. The asymmetry is deliberate and tested — a strong link may still join a pile string matching had already assembled, or the tiers would be a rule about arrival order rather than about evidence. Negative controls, both measured: removing the strong-anchor refusal fails the purity measurement and its unit case; removing the cross-rule refusal fails the enumeration and its unit case. Reduction baselines unmoved: 33.3 % and 24.5 %. Fusion suite 1090 passed. Open and recorded rather than approximated: stories are still Redis-only, so the assignment evaporates after the Kafka envelope and no API read can show one, and the resolved-identity link waits on Lane A's 3.1. * Lane F: record the eleven items the lane did not reach, with measured state Deviation D5. The reproduction work for each was done before the lane ran out of time, so each row is measured state rather than a guess — which is worth more to whoever picks them up than a fresh grep. Three are worth reading before anyone starts: 4.5's read verbs already exist (987 lines, 5 verbs, 7 vendors); the gap is that run_auto_triage has no tool channel at all, so a vendor alert that auto-triages never pulls vendor evidence. 4.4's precedent already reaches triage by two routes but matches only on exact fingerprint; a complete Qdrant recall with provenance sits unused by the triage path. A naive re-triage writes nothing, because run_id is a uuid5 over the alert and workflow version and the ledger is ON CONFLICT DO NOTHING. 9.5's claim row is stale in the repository's favour: SCIM tokens and organisation members are both built and the row still says they are not. * 3.3: declare the occurrence suite's fixture DSN as the owner it is check_runtime_db_role.py failed two jobs on #1588 with one root cause: the live suite's ISOLATION_OCCURRENCES_ADMIN_DSN connects as 'aisoc', which the workflow provisions as a superuser, and a superuser ignores every RLS policy even under FORCE ROW LEVEL SECURITY. The split is deliberate and the gate is right to make it explicit. The code under test reads ISOLATION_OCCURRENCES_DSN, which is the DML-only runtime role with NOBYPASSRLS — that is what found migration 151's WITH CHECK defect in the first place, and a suite driven entirely as the owner could not have. The owner DSN exists only so fixtures can create scratch tenants, which the runtime role cannot. Declared with the marker and the reason the gate asks for, in the same shape agent-auth-live.yml already uses. * 9.5 prerequisite: a 'not built' claim about a console page must still be true (#1592) The claim-to-gate matrix carried, inside the caveat of a GATED row: Six console pages parity 4.5 also names — branding, SCIM tokens, retention, organisation members and grants, rule packs, delegations — are not built Three of them were built. `ScimTokensPanel` had shipped, was wired into SettingsView, and is gated by another row of the same matrix — so two rows of one document disagreed about whether a surface exists. `RBACView` had shipped and is covered by BannerHonesty.test.tsx. `UsersView` had shipped at /settings/users and was tested by nothing at all. The direction of the error is what makes it worth its own change. It reads as modesty and works as an exemption: a surface recorded as absent needs no claim row and no gate, which is exactly what that sentence was doing in a caveat. A shipped page inherited the coverage of a page that does not exist. `check_claim_gate_matrix` cannot see this. It counts rows and statuses and does not read a caveat's prose, so the row stayed GATED, accurate about its own claim, while excusing an entire surface from having one. check_unbuilt_claims.py reads every "not built" assertion scoped to console pages, resolves each named surface through a component file **and** a render site — an unrendered component is not a page, and crediting one would make the gate certify the defect it is named for — and fails on any that exist. Proven against the pre-fix tree, where it names all three. Six self-test cases in both directions, including the motivating sentence verbatim and an unrelated "not built" outside a console context that must not fire. Only one direction is checked, deliberately: claimed absent, actually present. The opposite is already covered by the gates requiring a claim row to name a job that drives the production path. UsersView.test.tsx is the gate the corrected row now names: six cases asserting on first paint as well as the error branch, since `data` is undefined in both and a suite driving only the error branch never exercises the state every page load passes through. The load-failure case asserts the absent state too — "we could not read the members" and "this organisation has no members" are different facts about an access-control surface. A member count is asserted not to render over a failed read, because `total` falls back to 0 and "0 members" beside a red error box is a number nobody measured. Writing it reproduced the mirror of a recorded trap: the first mock exposed `authApi.me` where the component calls `authApi.currentUser`, so a double less capable than the real object failed six tests with a TypeError rather than an assertion. Branding, retention, rule packs and delegations genuinely are not built and the corrected caveat says so. Matrix 340 -> 341 rows, 336 GATED. * 4.3: failing test — an unevaluable operator loads into the triage hot path The worker's parser validates two of the three value domains a rule carries. A set_severity outside the ladder is dropped; a route_to outside the queue list is dropped and warned about; an op outside the comparator set is stored verbatim. _cmp then falls through every branch and returns False, so the rule loads, sits in the tenant's rule set and matches nothing, with no diagnostic. Measured on this tree, contrasting the two domains in the same position: op: neq -> parsed, op stored as 'neq', matched [], no log line route_to: not-a-queue -> rejected, route_to=None, warning emitted neq is the case worth naming: the spelling in both engines is ne, so it is the most plausible typo in the grammar, and the rule it silently disables is an escalation. A tenant authoring "escalate anything off the jump box" sees the rule saved, sees it in the list, and gets no escalation and no reason. Four assertions, all failing here: the rule must not load, the rejection must be diagnosed, rejecting it must not disable the tenant's other rules (the blast radius contract this file already states), and an unevaluable leaf nested inside an aggregator must be caught too. * 4.3: reject an operator no evaluator implements, and gate the two grammars Fix, in two parts. The worker now publishes COMPARATOR_OPS and rejects a leaf naming anything outside it, with its own diagnostic (business_context.rule_op_rejected, carrying the operator and the rule id) rather than the generic rule_skipped — matching rule_route_rejected, which is the same kind of out-of-grammar value. The check sits in _parse_condition, not in the loader, because a leaf is reachable from arbitrary aggregator depth and a top-level-only check passes {all: [{op: neq}]} straight through. Rejecting one rule still leaves the tenant's others loaded, which is this file's existing blast-radius contract. The grammar is declared twice because the two services ship as separate images and cannot import each other, so scripts/check_business_context_grammar.py holds the declarations equal. Three arms, since a one-directional check is how this class of gate reports OK while the drift that matters walks past: 1. the two declared sets are equal, checked both ways 2. every declared operator has a branch in that engine's own evaluator 3. every implemented operator is declared, so no branch is unreachable Arm 1 compares the two published constants. Arms 2 and 3 are the only place the gate reads an evaluator's source, and they read it to check the declaration against it, never to derive the declaration from it — deriving it is how a drift check ends up asserting against its own copy of the answer. Both files are parsed with ast rather than imported, because both services name their top-level package app and importing one shadows the other. On this tree: 13 operators, agreeing, each implemented in both engines. The gate's self-test covers 7 cases — one agreeing pair and six mutations: each engine ahead of the other, an operator declared by both and implemented by neither (the case plain set-equality cannot see), an implemented-but- undeclared branch, a renamed evaluator that would otherwise read as an empty agreeing set, and a computed declaration that cannot be compared statically. * 4.3: negative control — all three reverts fail, each in its own arm Three reverts, run against the committed tree, each restored afterwards. 1. Revert the parser rejection (_parse_condition no longer refuses an operator outside COMPARATOR_OPS): 4 failed, 2 passed test_unknown_operator_is_rejected_not_stored_verbatim test_unknown_operator_is_diagnosed test_rejecting_one_rule_does_not_disable_the_others test_nested_unknown_operator_is_caught_too The two that keep passing are the ones about the published set, which the revert does not touch — so the suite distinguishes the declaration from the enforcement rather than failing wholesale. 2. Teach the worker 'neq' without an implementation. Two arms fire independently, which is the point of not relying on set equality alone: FAIL operators the worker evaluates and the console rejects: ['neq'] FAIL worker declares ['neq'] with no branch in its evaluator exit=1 3. The direction that actually harms a tenant — the console gains an operator the worker cannot run: FAIL operators the console accepts and the worker cannot evaluate: ['matches'] — a rule using one of these saves successfully and never fires FAIL console declares ['matches'] with no branch in its evaluator exit=1 Arm 3 is the one the original defect would have taken. A gate that only compared the two declarations would have caught 2 and 3 but not the case where both engines declare an operator neither implements, which is why the evaluator arms exist and why the self-test covers that case separately. * depth2 Lane E: AI provider coverage, chat-compliance minimisation, hosted agents, repository AI config and four replayed AI rules (#1585) * depth2 Lane E: claim migrations 146-150 and ADR 0021 * test(connectors): reproduce the AI provider-coverage gap in llm_usage Depth 6.3 / wave-2 7.1. `LlmUsageConnector` accepted `openai` and `anthropic` and nothing else, so Gemini in Workspace, Copilot in M365, Copilot in GitHub and Entra consent grants to AI applications had no reader at all and the AI estate's provider-audit discovery source could only ever see two vendors. Six of the seven tests fail on this tree: four drive the real HTTP path against a mock server returning vendor-shaped payloads and get a ValueError from the constructor, one asserts the org-scoping refusal and one asserts the schema's select options match the accepted providers (`PROVIDERS` does not exist yet). Endpoints, query parameters and event names come from the vendors' current public references, each fetched and 200 before being written: the Admin SDK Reports API `gemini_in_workspace_apps` application, the GitHub organization audit log, the Office 365 Management Activity API schema (RecordType 261 CopilotInteraction, 284 AIAppInteraction) and Microsoft Graph directoryAudits. * feat(connectors): four more AI provider audit feeds in llm_usage Depth 6.3 / wave-2 7.1. Closes the gap the previous commit reproduced: the connector now reads Gemini in Workspace, GitHub Copilot, Microsoft 365 Copilot and Entra consent grants alongside OpenAI and Anthropic. Each client was written against the vendor's current public reference, every one of which was fetched and returned 200 before being committed; the module docstring names them per provider. The Workspace `gemini_in_workspace_apps` applicationName and the `ai_usage_event` / `feature_utilization` event names, the 23 published `copilot.*` audit actions, RecordType 261 CopilotInteraction and 284 AIAppInteraction, and the directoryAudits consent activities are all read values, not inferred ones. Three things the tests pin beyond "it parses": - Filtering happens server-side where the vendor supports it. Asking GitHub for an organisation's whole audit stream and discarding client-side is a rate-budget problem on a busy org, not a style one. - Where it cannot, the reader discards non-AI records by RecordType and by consent activity name. `Audit.General` is the entire Microsoft 365 general audit and `directoryAudits` is every directory change; a reader that forwarded both would replace the AI feed with a second copy of the general audit. - A consent grant's scopes are lifted out of the free-text `ConsentAction.Permissions` property into a sorted `scopes` list on the envelope. A grant whose scopes stay buried scores in the AI estate as a grant with no scope at all, which is the opposite of the truth for `Mail.Read`. M365 needs a second request because the subscription endpoint returns blob references rather than content; a reader that stopped at the first response would poll successfully forever and emit nothing. Workspace OAuth token grants are deliberately not read here — `google_workspace` already polls the `token` application, and a second reader would double-count every grant. What is missing there is classification, which is the next commit. Docs and the conformance matrix regenerated, not hand-edited. * test(fusion): reproduce the recorder reading a path no connector emits Wave-2 7.1 wiring. `test_ai_asset_recorder.py` writes `finding.evidence.scopes` into a hand-built OCSF event and asserts the recorder reads `finding.evidence.scopes`. Both halves are the test's own invention: no connector in the tree produces that path and ingest does not synthesise it, so the assertion holds whether or not the production path works. What ingest really hands fusion is the connector's normalized dict as a JSON string under `ocsf["raw_data"]`, which is why `_connector_fields` exists for the endpoint path and is not used by the provider-audit path. Driven through that real shape, both new tests fail: an Entra consent grant reaches the inventory with no scopes at all, so an AI notetaker consented into every mailbox in the organisation scores identically to one granted nothing, and the console's reason list is silent about the single fact that decides whether the grant matters. The fixtures are the real output of `LlmUsageConnector.normalize()`. The two services cannot import each other — both package their application as `app` — so they are held together by a committed artefact plus a check in each direction, the way the vendored narrative and the detection ruleset already are. * fix(fusion): read provider-audit fields where the connector puts them Wave-2 7.1 wiring. `_from_provider_audit` now reads through `_connector_fields`, the same reconstruction the endpoint path already performs, instead of off the canonical OCSF map. An Entra consent grant's scope list reaches `score_risk`, so a grant holding `Mail.Read` scores as broad and says so in its reason list. Two further corrections the real shape forced: - An OAuth grant is keyed on the **application**, not the audit record. Keying on the record id would make every re-consent a new asset and reset `first_seen_at` on each, so the inventory would grow a row per event and never show that this application has been there since May. - The OCSF-native `finding.evidence.scopes` read is kept as a fallback rather than replaced, so a producer that does emit it is still read. Trading one blind spot for another is not a fix. Negative control, recorded: with the `fields.get("scopes")` read reverted to the pre-fix path and nothing else changed, both new tests fail again (`KeyError: 'scopes'`). Restored, the fusion suite is 1063 passed / 28 skipped. The `normalize` contract is unchanged across all 87 connectors: the "is this record AI activity at all" decision is a separate `is_ai_record` predicate rather than a `None` return, which keeps the base signature intact and makes the filter — the thing that stops the Microsoft 365 AI feed becoming a second copy of the general audit — callable and testable on its own. * feat(api): enterprise AI-chat compliance logs, minimised by the schema Wave-2 7.1, second half. Reads an AI provider's compliance API for the directory, projects and activity feed, and — behind a second, narrower opt-in — classifies message content without keeping any of it. Written against Anthropic's Compliance API, the one enterprise AI-chat compliance surface with a complete public reference. Every path, scope, key prefix and response field was read from pages that each returned 200 before being committed; the client's module docstring names them. The Activity Feed record and the chat record in the tests are the vendor's published examples field for field. The minimisation is in the schema, which is the point of ADR-0021. A plan sentence saying "never full conversations" that a TEXT column permits is not a control; it holds until the first caller who binds "\n".join(messages) and succeeds silently. - No table has a column able to hold a message. Asserted against the ORM, since that is what application code binds through. - The snippet is VARCHAR(280). The collector truncates; the column is the backstop for the caller that forgets. - The snippet is masked BEFORE it is cut, so a row saying "this chat contained an AWS key" does not contain the key. A verbatim window would create a new copy of the secret in a table an operator believes is safe to keep, and label it so an attacker can find it. A per-pattern sweep asserts the value is absent for every shape in the shared list. - The label vocabulary is a CHECK constraint, and a test asserts the three copies of it (constraint, ORM, classifier) agree. - The client has no method returning message text, asserted on its public surface. - Two opt-ins, stricter one default-off: collection does not imply reading message bodies. - Off by default per tenant, through the console, vault-held key. No environment variable. A vault failure is a 503, never a plaintext row. The secret-shape patterns are the AI SDK's own, vendored by scripts/sync_vendored_ai_redaction.py and held byte-identical by its --check. A prompt and a chat message containing the same AWS key must produce the same shape name on both surfaces; a second hand-written copy is how two surfaces come to disagree about the same rows. The SDK groups e-mail and card shapes with credentials because it is answering a transmission question; _SDK_LABEL maps each shape to one of the plan's four classes rather than relabelling the shared list. Luhn is applied to the shared card shape. Without it the digits-only pattern labels order ids as payment data, and a classifier that labels everything is one nobody believes. Retention, legal hold and erasure come free and are tested: every table carries a column named exactly `tenant_id`, which is how `discover_tenant_tables` finds it. Discovery rather than a declared list is deliberate — a list is the thing that goes stale. Tests use httpx.MockTransport rather than respx, because respx is not in this service's locked dependency set and a test needing a package CI does not install is a test CI cannot run. MockTransport replaces only the network leg. Negative control, recorded: adding a `transcript: Mapped[str | None] = mapped_column(Text)` to AiChatContentLabel and changing nothing else fails two tests (the forbidden-column sweep and the unbounded-TEXT sweep). Removed, the API suite is 5074 passed / 174 skipped. Migration 146 and ADR-0021 were claimed in DEPTH2_PROGRESS.md before either file was written. * docs(depth2): record 7.1 in the progress tracker * feat(ai-estate): hosted agents and repository AI config as asset kinds Wave-2 7.2. Two new kinds on `aisoc_ai_assets` (migration 147), both scored by the one existing `score_risk` and rendered with their reasons on the AI estate page. No second scorer: the plan forbids it by name and it is the drift this repository keeps finding. **Hosted agents** come from `GET /v1/agents` with the `managed-agents-2026-04-01` beta header, read against the vendor's published reference (fetched, 200). An agent configured in a provider's control plane is invisible to every other discovery path here: endpoint telemetry never sees it, and gateway telemetry sees its traffic without knowing what it was configured to do. The client is read-only — the vendor offers create, update and archive and none of them is here, because an inventory that can reconfigure a customer's agents is a different risk conversation and 7.2 is read-only by the plan's rule. **Repository AI config** is the scan of agent-instruction files, skill directories and MCP configuration through the code-platform connectors, recording the tools and servers each references. "Which repositories point an agent at this MCP server" is a question the estate could not answer. Every byte of that scan is attacker-controlled and is treated as such. These files are checked in, editable by anyone who can land a pull request, and read by an agent verbatim as instructions — the same trust class as a retrieved runbook, which this platform already scans. So: - Nothing is stored raw. Excerpts are flattened and capped at 400 characters, with zero-width and bidirectional characters stripped, because an instruction file is exactly where a payload invisible in a diff gets hidden. - The content is scanned at capture and only the matched *pattern names* are kept — never the matching text, which would put the attacker's payload in a table the console renders, labelled so a security team looks at it. - Those names reach `score_risk`, so a flagged file raises the asset's exposure and the reason names the channel. - A hosted agent's `system` prompt goes through the identical path, for the identical reason. The patterns are **generated** from the agents guard's own `_RULES` table rather than hand-picked, by scripts/sync_vendored_ai_instruction_rules.py with a --check wired into ci.yml. A hand-copied subset drifts: a pattern added to the guard after the next incident would never reach the scanner and nothing would say so. One rule is excluded with its reason recorded — `fabricated_tool_result` matches a model-output envelope rather than a repository file, and its pattern is assembled from a set, so it renders in a different order in every process and no generated file could match itself. The generator fails if an excluded name leaves the guard, so the exclusion cannot outlive the rule and become a silent gap. Two things found while building it: - `path.lstrip("./")` eats the leading dot of a dotfolder, so `.cursor/rules/x.mdc` became `cursor/rules/x.mdc` and stopped matching — silently, as a path that simply is not an AI artefact. Every convention here lives in a dotfolder, so that one call would have turned most of the scan off. Caught by the classification table, which is why it enumerates real paths rather than a couple of examples. - `DEVICELESS_KINDS` is shared between the model and `score_risk`, so the four kinds that cannot have a device are not charged for lacking one. A hosted agent has no laptop to isolate; the reason string "containment has nowhere to act" would simply be false. The tool reader matches grants, not prose: "do not use `write_file`" in a paragraph is not a grant, and counting it would make a careful instruction file score worse than a careless one. Also: a committed JWT-shaped literal in the 7.1 classifier test is now assembled from parts. The repository's secret scan was right to refuse it, and a test fixture has no business looking like a credential. * docs(depth2): record 7.2 in the progress tracker * feat(detections): four AI rules on the provider feeds 7.1 added Wave-2 7.4, partial — four of the rule pack's targets, each earned rather than declared. Executable corpus 2,530 -> 2,534, regenerated from `scripts/project_stats.py` and propagated to the README, ROADMAP, truth table, corpus stats, marketplace index and the packaged API copy by their own generators. Nothing was hand-typed. - `llm-copilot-content-exclusion-changed` (critical) — content exclusion is the control that stops a coding assistant reading the paths an organisation declared off limits. It is changed in a settings page rather than in a pull request, so nothing else reviews it. - `llm-copilot-agent-mcp-config-changed` (high) — adding an MCP server adds a party that can instruct a hosted agent. A scope change, not a settings change, and the agent runs on the provider's infrastructure so no endpoint control sees the result. - `llm-ai-app-granted-write-scope` (high) — a consent grant letting an AI application change a mailbox, drive, site or the directory. The read equivalent is an exposure; this one can act. - `llm-copilot-bulk-resource-access` (medium) — one assistant turn that read 25 or more distinct resources. An assistant with a user's grant is an exfiltration path that authenticates as that user and looks like ordinary application traffic. Every rule is replayed through the REAL connector and the REAL engine in `services/fusion/tests/test_ai_rule_pack_replay.py`. The fixtures are the committed output of `LlmUsageConnector.normalize()` on vendor-shaped records, regenerated and drift-checked from the connectors side, because the two services cannot import each other. Nothing here is synthesized from the rule it tests. That is the whole point: 1 of 12 GitHub rules fired on real connector output while all twelve passed their own fixture replay, because a fixture generated from a rule carries the rule's own clause key and the replay is tautological. Each negative twin differs in exactly ONE decisive field — a different Copilot action, `Mail.Read` where the twin is `Mail.ReadWrite`, 24 resources where the twin is 40 — and a test asserts that property on the fixtures rather than trusting it, since a negative that also moved the actor would pass for a reason unrelated to the clause. Negative control, recorded: rewriting one rule's clause to the unprefixed vendor action (`event_type: content_exclusion_changed`), which is the exact shape of the measured GitHub failure, and re-exporting, fails that rule's positive replay while the other three stay green. Restored, all ten pass. `test_builtin_rule_catalogue.py`'s hand-typed counts moved 760 -> 764 and 2609 -> 2613 with the reason recorded beside the existing history, in the style that file already keeps. * docs(depth2): record 7.4 partial and 7.3 not delivered, with evidence * chore(detections): regenerate the curated index for the four new rules `curate_detections.py --check` is a drift gate I had not run: adding four rules moves the curated selection and the coverage page, and neither is produced by any of the seven generators I did regenerate. Caught by CI, reproduced locally with the same command, and regenerated rather than hand-edited. Worth recording because it is the shape this repository keeps finding: a published artefact with its own generator and its own `--check`, sitting outside the chain everything else in the family runs through. All eight detection drift gates now pass together. * fix(ci): correct the gitleaks fingerprints the four new rules shifted `.gitleaksignore` pins a finding by `file:rule:line`, so inserting four entries into `detections/rule-ids.lock.json` moved every line below them and five fingerprints stopped matching the findings they were triaged for. The file's own header describes this rot and says the fix is to correct the line number, never to drop the entry or relax the job, so that is what this does: the set is re-derived by running CI's exact gitleaks 8.21.2 with the allow-list removed, and all fourteen are written back. Thirteen are the same pre-existing, benign findings — the heuristic fires on rule *slugs* such as `llm-api-key-created` and `slack-token-exposed`, never on a value. One is genuinely new: `llm-copilot-bulk-resource-access` trips it on the word "access". Verified under 8.21.2 rather than the 8.30.1 on this machine, because the two disagree about this tree and only the pinned one decides. Also regenerates `apps/web/public/marketplace/{index,curated}.json` through `pnpm marketplace:sync`. `curate_detections.py --check` passing is not the whole gate: the web mirror is copied by a separate step, and a curated index that is current in one place and stale in the other is the drift that check exists to catch. * 9.5: the four operator pages that were built everywhere except the console Branding, retention, rule packs and delegations each shipped a complete backend — full CRUD, ownership checks, audit emission — and had no console binding at all. `brandingApi` bound only the read half, so the product rendered a tenant's branding and offered no way to set it; the other three had no client at all. The only route to any of them was curl. Retention needed more than a binding. `RETENTION_WORKER_ENABLED` defaults to false and the worker has a dry-run mode on top, so three editable numbers and a Save button would have told an operator their data is deleted after N days when, on a default deployment, nothing deletes. The route now reports the worker's state and the panel leads with it, distinguishing off from dry-run because the operator's next action differs. The windows still matter with the worker off — compliance evidence reads them — so the panel says "stated policy" rather than implying enforcement. The honest-state rule bites hardest on the two access-control surfaces. An empty delegations table over a failed read asserts that nobody holds standing authority over a customer tenant, which is a claim about access control made from no data; a retention panel rendering 90/365/730 over a failed read is indistinguishable from the tenant's real policy. Both are pinned, and both negative controls were run: each failed exactly its own case and no other. Building the four also exposed a one-directional blind spot in `check_unbuilt_claims.py`, which shipped three commits ago. It read only the text *before* "are not built", and the caveat it was written for had since moved the names *after*, so it reported OK over a sentence that had become false. It now reads both sides, bounded at the sentence so the clause naming the pages that *are* built is not flagged, and its existence resolver is injectable so the fixtures no longer decay as pages ship. Matrix 341 → 342 rows, 336 → 337 GATED, moved in lockstep across CLAIM_TO_GATE_MATRIX.md, ROADMAP.md and the evidence pack. * 3.3: the occurrence guard anchored a pattern pytest never writes `grep -qE '^[0-9]+ passed'` cannot match, because pytest writes its summary as `===== 6 passed in 0.67s =====`. The job reddened on a run where all six live tests passed, which is the worse direction for a guard: one that fails on a healthy suite teaches people to ignore it. The count is now unanchored and `[1-9][0-9]*` rather than `[0-9]+`, so a run that collected nothing and reported `0 passed` is still a failure. Verified in all three directions against the real summary line: the new pattern matches it, the old one does not, and `0 passed` is still refused. * 4.5: give auto-triage a bounded channel to the read verbs it already had (#1593) No read verb is added here. `investigation_reads.py` is 987 lines carrying five read-only capabilities across seven vendors — Defender, CrowdStrike, SentinelOne, Okta, Entra, Workspace, AWS — each with a capability contract, an executor, an autospec'd signature test, a closed agent allowlist and a parameter allowlist. All of that worked. What did not exist was any way for auto-triage to reach it. The verbs are bound to the investigation agent in `deep_investigation.py`, which runs only on the escalation path. `run_auto_triage` was a single `safe_ainvoke` with no tool channel, and said so in its own comment. So on the path every fused alert takes, a GuardDuty or Defender alert was triaged without ever asking GuardDuty or Defender what they knew, and `unverified_tool_claims` correctly blocked auto-close if the model so much as claimed a tool result. A deterministic pre-fetch rather than a tool-calling loop, for three reasons. Latency and cost on the hot path would otherwise be unbounded: one model call becomes N plus N vendor round trips on every fused alert with no ceiling anybody declared. The alert payload is untrusted by construction — it is fenced and injection-scanned before anything reasons over it — so a channel whose arguments the model derives from that payload is a door an injected string can aim; not choosing at all is strictly stronger than the parameter allowlist alone. And the citation is true: the result is in hand before the model is asked anything, so the ledger row exists because the call happened rather than because the model said it did. It is a bounded channel, not an absence of one: triage reaches the real verbs, the set is fixed per alert shape, and the budget is declared. `called_tools` is now whatever a vendor really answered, and only that. A read that was attempted and failed is deliberately absent, because the guard's question is whether a rationale credits a tool with a result and a read that returned nothing produced no result to credit. An empty tuple when the pre-fetch is off restores the previous behaviour exactly. The reads land as `tool_call` rows at seq 2 and up, in the same transaction as the verdict. Not before the model call, even though that is when they happened: seq 0 and 1 are the model call's and the verdict's keys and the `(run_id, seq)` uniqueness is what makes a replay idempotent. The `ts` on each row carries the real ordering. Off by default behind AISOC_TRIAGE_VENDOR_EVIDENCE: this reaches the customer's vendor API on every fused alert. A failed read renders as COULD NOT CHECK with its status, never as silence. A failed EDR read is not evidence that the host is healthy, and an absent answer rendered as nothing is read by a model as a clean one. Negative controls, both measured: removing the render call fails the prompt case; counting failed reads as called tools fails the guard case. Scorecard: deterministic balanced accuracy 0.250, auto-close precision not measured — identical to the committed baseline, which is what an off-by-default context source must do. Alert reduction unmoved at 33.3 % and 24.5 %. Agents suite 2215 passed, 8 skipped. Matrix 340 -> 341 rows. * 9.5: re-export the OpenAPI spec for the retention disclosure fields `RetentionOut` gained `purge_worker_enabled` and `purge_worker_dry_run`, so the committed spec went stale and its check job reddened. Regenerated rather than hand-edited, and with the dependency set the job itself pins: the exporter noticed that the installed pydantic was 2.14.2 against the 2.14.1 in `services/api/poetry.lock` and said so, which is the recorded trap about artefacts inheriting whatever drifted into the environment that produced them. Pinned to the locked version first; the resulting diff is the two new fields and nothing else. * docs(matrix): one Summary block, recomputed from the gate A keep-both merge resolution appends a second `## Summary` rather than merging it, and on four of these branches the surviving copy had been spliced into the middle of the table. The row parser stops at the first blank line, so the splice both hid rows and left the published figure describing a shorter table than the file holds. One block at the end, with every bullet, and all three surfaces — the matrix, ROADMAP and the evidence pack — recomputed from `check_claim_gate_matrix.py` rather than edited. * ci: drop the duplicated vendored-AI-rules step the merge placed too early Keeping both sides of the ci.yml conflict left two copies of the step, and the earlier one runs before `service_requirements.py api agents` installs anything — so the guard's rule table could not be imported and the gate refused with "No module named 'structlog'". That refusal is the gate being right: it will not certify a comparison it could not make. One copy, in the position main already had it: after the install. * ci: repair the duplicated gate block that stopped ci.yml from starting A both-sides merge resolution inserted a second copy of the unbuilt-claims and outcome-claims gate blocks, and truncated one step so it carried a name with no run:. That parses as YAML, which is why a local yaml.safe_load reported the file fine, but GitHub rejects the workflow at startup: the run completed with conclusion=failure and zero jobs, so none of the thirteen required contexts ci.yml owns ever reported and the pull request sat BLOCKED with no failing check to point at. Removes the partial duplicate only. Complete copies of both gates already existed in the same job and are untouched; no gate command is lost. * fix(gates): read a headers object passed to fetch by name `check_console_auth_headers` reported the branding asset upload as a bare fetch. It is not: it calls `apiHeaders()`, deletes the JSON `Content-Type` because a multipart body needs the browser's own boundary, and passes the object by name — so the bearer token was there the whole time and the gate could not see it, because it only read the call site. The gate now resolves a `headers` name to its binding in the same file and credits it when that binding calls `apiHeaders(`. Deliberately narrow, and the self-test carries both directions: a name bound to `apiHeaders()` passes, a name bound to anything else is still a finding. Without the second case this would have become "a variable called headers counts as authentication", which is the shape that makes a security gate useless. * fix(gates): resolve the repo root through git, not from __file__ `check_gate_contract` holds every wired gate to two properties, and this one failed the first: a root taken as `parents[1]` of `__file__` is whatever directory happens to sit above the script, so a gate run from a scratch copy of `scripts/` reads that tree and reports on it as though it were the repository. Use `gate_toolkit.repo_root()`, which asks git and honours `AISOC_REPO_ROOT`, matching every other gate in the directory. Behaviour in a normal checkout is unchanged: self-test still passes 7 cases with 6 detected, and the check still finds the same 13 operators. * docs(matrix): one summary stanza and one copy of each row after the merge The add/add resolution on this lane kept both sides of three things that cannot take it, and all three were already in the branch before this merge: * two claim rows appeared twice — the per-tenant entitlement row and the operator-pages honest-state row — each as a stale variant beside the version 9.5 left behind. Both stale copies still said the four operator pages were not built, which this lane is what makes false. * the `## Summary` stanza carried a second `Total`/`GATED` pair, which the matrix's own prose warns about three lines further down. * `ROADMAP.md` and `evidence-pack.md` each carried the figure paragraph twice. Deduped to one of each and recomputed the figure from the table rather than typing it: 359 rows, 354 GATED, 5 PARTIAL, 0 NO GATE. * test(console): cover the four operator panels' write paths The coverage gate failed at 56.66% lines against a 57% floor, and the four panels this lane adds were the cause: they sat at 48% because every case drove a read and none drove a write. Raising them to 93.5% puts the repo at 58.14% lines / 56.32% statements, both clear of the floor. The threshold was not touched. These are not filler. Two properties recur across the twenty-two new cases and both are things an operator page gets wrong quietly: * **A refused value must not reach the server.** Each panel validates in the browser so the operator learns which field is wrong before a round trip rather than after a 422 naming the request body. A validation that still calls the API is not a validation, and the only way to tell the difference is to assert the mock was never called — so each refusal case does. * **A failed mutation must leave the row where it was.** `RulePacksPanel` already says this in a comment — a pack shown as deleted while it still applies to a customer tenant is the dangerous direction — and a revoked- looking delegation that was not revoked is the same shape: standing authority over another tenant that nobody is now watching. Both are now asserted against a rejecting client. Also pinned: retention's two distinct confirmations, because 'saved' over a disabled purge worker means a stated policy and not deletion; branding's 409 as an answer rather than a failure; the sanitised-SVG wording, since what is stored is the stripped copy; cleared fields sent as null rather than ''; and every successful write re-reading from the server instead of patching its own copy. One assertion was written against what I assumed the no-org branch did and corrected against what it does: the fields stay and the banner explains they will save once an organisation exists. * docs(matrix): one Total/GATED pair in the summary stanza The two merges above resolved the stanza by keeping both sides, which appends a second `- Total:`/`- GATED:` pair rather than merging them. The ratchet does not catch it — `check_summary_block` reads the first match per field and both copies agree — so it passes while the rendered block states the same two figures twice. Deduped; the figures themselves are unchanged and still the ones the gate parsed.
736 lines
29 KiB
Python
736 lines
29 KiB
Python
#!/usr/bin/env python3
|
|
"""Every console call to an AiSOC API carries a credential.
|
|
|
|
Why this exists
|
|
---------------
|
|
The console reached 61 API call sites across 21 files through bare
|
|
``fetch(url)`` and through single-argument SWR fetchers that take no options
|
|
at all, so the request went out with no ``Authorization`` header. Those calls
|
|
worked, which is the whole problem: the API resolved a credential-free request
|
|
to a demo administrator whenever it ran in a development-class environment,
|
|
and that is how the quick start and the documented single-host deployment ran.
|
|
Closing the anonymous path turns every one of them into a 401, so the console
|
|
had to move onto the credentialed client in the same change.
|
|
|
|
Nothing would have caught the drift. ``check_ledger_replay_contract`` holds
|
|
one client object against one router and says nothing about headers;
|
|
``check_route_auth`` and ``check_route_authz`` look at the server. The console
|
|
side had no gate at all, and a header is exactly the kind of thing a new
|
|
component omits by copying the component beside it.
|
|
|
|
What counts as a credential
|
|
---------------------------
|
|
An ``Authorization`` header, and nothing else. Two near-misses deserve
|
|
naming because both were present in the tree and neither authenticates:
|
|
|
|
``X-Tenant-Id``
|
|
A caller-supplied tenant claim. Five call sites in ``api.ts`` sent it and
|
|
no token, which reads like an identity and is not one.
|
|
|
|
``credentials: 'include'``
|
|
Sends cookies. The API verifies a bearer token; the SSO cookie it sets is
|
|
read by nothing. A cookie-only call is anonymous to this backend.
|
|
|
|
Scope
|
|
-----
|
|
Browser code under ``apps/web/src``. Server components are in scope and
|
|
allowlisted individually rather than exempted as a class: a server render has
|
|
no session to borrow, so a call made there is either genuinely public or a
|
|
call that cannot succeed, and both deserve a written reason.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import pathlib
|
|
import re
|
|
import sys
|
|
import tempfile
|
|
from dataclasses import dataclass
|
|
|
|
# `scripts/` is on sys.path when this file is run as a program, but not when a
|
|
# test loads it by path with importlib. gate_toolkit sits beside it either way.
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
|
|
|
from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
|
|
|
|
#: Where the console lives, relative to the repository root.
|
|
CONSOLE_ROOT = "apps/web/src"
|
|
|
|
#: Path fragments that mark a URL as an AiSOC API call. `/api/v1` covers the
|
|
#: core API and every service the Next rewrites proxy; `/v1/inbox` is the
|
|
#: ingest webhook, which authenticates by token in the path.
|
|
API_MARKERS = ("/api/v1/", "/v1/inbox/")
|
|
|
|
#: Suffixes whose calls are not shipped to a browser.
|
|
EXEMPT_SUFFIXES = (".test.ts", ".test.tsx", ".spec.ts", ".spec.tsx", ".stories.tsx")
|
|
|
|
#: What counts as a credential at a call site, matched case-insensitively.
|
|
#:
|
|
#: Either the header spelled out, or a call to the one helper that attaches
|
|
#: it. Recognising the helper matters: hiding the header behind a local
|
|
#: `const headers = {...}` a few lines up is how the preferences call ended up
|
|
#: with a token and no tenant header, and the fix for that shape is to route
|
|
#: it through the helper rather than to make the gate chase variables. So the
|
|
#: rule a reviewer can state is "show the credential, or call the thing whose
|
|
#: job is attaching it, on the same expression as the fetch".
|
|
CREDENTIAL_MARKERS = ("authorization", "apiheaders(")
|
|
|
|
#: Fetchers that attach a credential themselves, so a bare reference to one as
|
|
#: an SWR fetcher is fine. Keep in step with `apps/web/src/lib/api.ts`.
|
|
AUTHED_FETCHERS = frozenset({"authedFetcher", "apiRequest", "apiFetch", "request"})
|
|
|
|
#: Single-argument fetchers that cannot attach a credential, by construction:
|
|
#: SWR calls them as `f(key)` and they take no options. A bare reference to
|
|
#: one against an API key is a finding even though no `fetch(` is in sight.
|
|
#: Both named here were retired; the names stay so that re-introducing the
|
|
#: shape is a failure rather than a silent regression.
|
|
UNAUTHED_FETCHERS = frozenset({"jsonFetcher", "safeFetcher"})
|
|
|
|
|
|
#: Calls that legitimately carry no credential, keyed by (path, url fragment)
|
|
#: with the reason. This may only shrink: `--check` reports an entry whose
|
|
#: call has gone, so a fixed site cannot leave its excuse behind.
|
|
ALLOWED_UNCREDENTIALED: dict[tuple[str, str], str] = {
|
|
(
|
|
"lib/replay.ts",
|
|
"/api/v1/r/",
|
|
): (
|
|
"The public replay permalink. Unauthenticated by design: /r/<slug> is "
|
|
"the surface a reader opens from a blog post, and the redaction pass in "
|
|
"services/api/app/services/replay_redaction.py is what makes it safe to serve."
|
|
),
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Finding:
|
|
"""One console call that reaches an API without a credential."""
|
|
|
|
rel_path: str
|
|
line: int
|
|
url: str
|
|
kind: str
|
|
detail: str
|
|
|
|
def render(self) -> str:
|
|
return f"{self.rel_path}:{self.line} [{self.kind}] {self.url}\n {self.detail}"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Report:
|
|
findings: list[Finding]
|
|
files_scanned: int
|
|
calls_scanned: int
|
|
stale_allowlist: list[str]
|
|
|
|
|
|
def _sources(root: pathlib.Path) -> list[pathlib.Path]:
|
|
console = root / CONSOLE_ROOT
|
|
if not console.is_dir():
|
|
return []
|
|
return sorted(p for p in console.rglob("*.ts*") if p.suffix in (".ts", ".tsx") and not p.name.endswith(EXEMPT_SUFFIXES))
|
|
|
|
|
|
def _call_arguments(text: str, open_paren: int) -> tuple[str, int] | None:
|
|
"""The text between the parentheses of a call, and the index after it.
|
|
|
|
Written by hand rather than with a regex because the first argument is
|
|
usually a template literal, and `${...}` puts braces and quotes inside a
|
|
string that a naive matcher would treat as structure. Tracks quote state
|
|
and template-substitution depth so `fetch(`${A}/api/v1/x`, { ... })` is
|
|
read as two arguments rather than five.
|
|
"""
|
|
if open_paren >= len(text) or text[open_paren] != "(":
|
|
return None
|
|
depth = 0
|
|
index = open_paren
|
|
quote: str | None = None
|
|
# One entry per `${` we are inside, so a nested template closes correctly.
|
|
substitutions: list[int] = []
|
|
while index < len(text):
|
|
char = text[index]
|
|
if quote is not None:
|
|
if char == "\\":
|
|
index += 2
|
|
continue
|
|
if quote == "`" and char == "$" and text[index : index + 2] == "${":
|
|
substitutions.append(depth)
|
|
quote = None
|
|
depth += 1
|
|
index += 2
|
|
continue
|
|
if char == quote:
|
|
quote = None
|
|
index += 1
|
|
continue
|
|
if char in "'\"`":
|
|
quote = char
|
|
index += 1
|
|
continue
|
|
if char in "([{":
|
|
depth += 1
|
|
elif char in ")]}":
|
|
depth -= 1
|
|
if substitutions and depth == substitutions[-1]:
|
|
substitutions.pop()
|
|
quote = "`"
|
|
index += 1
|
|
continue
|
|
if depth == 0:
|
|
return text[open_paren + 1 : index], index + 1
|
|
index += 1
|
|
return None
|
|
|
|
|
|
def _split_top_level(argument_text: str) -> list[str]:
|
|
"""Split a call's arguments on commas that are not nested or quoted."""
|
|
parts: list[str] = []
|
|
depth = 0
|
|
quote: str | None = None
|
|
substitutions: list[int] = []
|
|
start = 0
|
|
index = 0
|
|
while index < len(argument_text):
|
|
char = argument_text[index]
|
|
if quote is not None:
|
|
if char == "\\":
|
|
index += 2
|
|
continue
|
|
if quote == "`" and argument_text[index : index + 2] == "${":
|
|
substitutions.append(depth)
|
|
quote = None
|
|
depth += 1
|
|
index += 2
|
|
continue
|
|
if char == quote:
|
|
quote = None
|
|
index += 1
|
|
continue
|
|
if char in "'\"`":
|
|
quote = char
|
|
elif char in "([{":
|
|
depth += 1
|
|
elif char in ")]}":
|
|
depth -= 1
|
|
if substitutions and depth == substitutions[-1]:
|
|
substitutions.pop()
|
|
quote = "`"
|
|
elif char == "," and depth == 0:
|
|
parts.append(argument_text[start:index])
|
|
start = index + 1
|
|
index += 1
|
|
parts.append(argument_text[start:])
|
|
return [part.strip() for part in parts]
|
|
|
|
|
|
def _api_path_in(text: str) -> str | None:
|
|
"""The API path a URL expression names, if it names one."""
|
|
for marker in API_MARKERS:
|
|
if marker in text:
|
|
# Report from the marker so the finding reads as a route rather
|
|
# than as whatever base-URL expression happens to precede it.
|
|
tail = text[text.index(marker) :]
|
|
for terminator in ("`", "'", '"', "?"):
|
|
if terminator in tail:
|
|
tail = tail[: tail.index(terminator)]
|
|
return tail.strip()
|
|
return None
|
|
|
|
|
|
def _line_of(text: str, index: int) -> int:
|
|
return text.count("\n", 0, index) + 1
|
|
|
|
|
|
def _skip_generic(text: str, index: int) -> int:
|
|
"""Past a `<...>` type argument list, if one starts at `index`.
|
|
|
|
`useSWR<Role[]>('/api/v1/rbac/roles', fetcher)` is a call, and a matcher
|
|
that only skips whitespace between the name and `(` does not see it. Both
|
|
SWR sites in the settings console carried a generic, so the rule that was
|
|
meant to catch an unauthenticated fetcher matched nothing at all.
|
|
|
|
Only a balanced `<...>` immediately followed by `(` counts, so a genuine
|
|
comparison such as `a < b && c > (d)` is left alone.
|
|
"""
|
|
if index >= len(text) or text[index] != "<":
|
|
return index
|
|
depth = 0
|
|
cursor = index
|
|
while cursor < len(text):
|
|
char = text[cursor]
|
|
if char == "<":
|
|
depth += 1
|
|
elif char == ">":
|
|
depth -= 1
|
|
if depth == 0:
|
|
after = cursor + 1
|
|
while after < len(text) and text[after] in " \t\n":
|
|
after += 1
|
|
return after if after < len(text) and text[after] == "(" else index
|
|
elif char in ";{}\n" and depth:
|
|
return index
|
|
cursor += 1
|
|
return index
|
|
|
|
|
|
def _find_call_sites(source: str, callee: str) -> list[tuple[int, str, list[str]]]:
|
|
"""Every `callee(...)` in `source`, as (offset, raw arguments, split)."""
|
|
sites: list[tuple[int, str, list[str]]] = []
|
|
needle = callee
|
|
cursor = 0
|
|
while True:
|
|
found = source.find(needle, cursor)
|
|
if found < 0:
|
|
return sites
|
|
cursor = found + len(needle)
|
|
# Reject `myFetch(` and `.fetch(` style matches: only a call whose
|
|
# name starts at a word boundary is this callee.
|
|
before = source[found - 1] if found else " "
|
|
if before.isalnum() or before in "_$.":
|
|
continue
|
|
after = found + len(needle)
|
|
while after < len(source) and source[after] in " \t\n":
|
|
after += 1
|
|
after = _skip_generic(source, after)
|
|
parsed = _call_arguments(source, after)
|
|
if parsed is None:
|
|
continue
|
|
raw, _ = parsed
|
|
sites.append((found, raw, _split_top_level(raw)))
|
|
|
|
|
|
def _carries_credential(options_text: str) -> bool:
|
|
lowered = options_text.lower()
|
|
return any(marker in lowered for marker in CREDENTIAL_MARKERS)
|
|
|
|
|
|
#: `headers` given as a name rather than an object literal: either the
|
|
#: shorthand `{ ..., headers, ... }` or `headers: someName`.
|
|
_HEADERS_BY_NAME = re.compile(r"\bheaders\s*(?::\s*(?P<named>[A-Za-z_$][\w$]*))?(?=\s*[,}]|$)")
|
|
|
|
|
|
def _credential_through_a_variable(options_text: str, source: str) -> bool:
|
|
"""Whether the options hand `fetch` a headers object built by `apiHeaders()`.
|
|
|
|
A multipart upload cannot use the JSON `Content-Type` `apiHeaders()`
|
|
sets by default, so it builds the object, deletes that one key and
|
|
passes it by name. That is a credentialed call, and reading only the
|
|
call site cannot tell it from an uncredentialed one — the branding
|
|
asset upload was reported as a bare fetch while carrying the bearer
|
|
token the whole time.
|
|
|
|
Deliberately narrow. The name has to be bound to `apiHeaders(` in this
|
|
file: a `headers` built any other way is still a finding, which is what
|
|
stops this from becoming "a variable called headers counts as auth".
|
|
"""
|
|
for match in _HEADERS_BY_NAME.finditer(options_text):
|
|
name = match.group("named") or "headers"
|
|
definition = _definition_of(source, name)
|
|
if definition and _carries_credential(definition):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _definition_of(source: str, name: str) -> str | None:
|
|
"""The text of a `const name = ...` or `function name(...)` in this file.
|
|
|
|
SWR takes a fetcher by name, so judging the call means reading what the
|
|
name is bound to. Three bindings occur in this console and they answer
|
|
differently: an alias of an imported fetcher, an inline arrow that calls
|
|
`fetch(url)` on the SWR key, and a name imported from another module.
|
|
Only the first two can be decided here.
|
|
"""
|
|
for opener in (f"const {name} = ", f"let {name} = ", f"function {name}("):
|
|
found = source.find(opener)
|
|
if found < 0:
|
|
continue
|
|
start = found + len(opener)
|
|
depth = 0
|
|
cursor = start
|
|
while cursor < len(source):
|
|
char = source[cursor]
|
|
if char in "([{":
|
|
depth += 1
|
|
elif char in ")]}":
|
|
depth -= 1
|
|
if depth < 0:
|
|
break
|
|
elif char == ";" and depth == 0:
|
|
break
|
|
elif char == "\n" and depth == 0 and _statement_ends_at(source, start, cursor):
|
|
break
|
|
cursor += 1
|
|
return source[start:cursor]
|
|
return None
|
|
|
|
|
|
#: Tokens that mean a statement continues on the next line, so a newline at
|
|
#: brace depth zero is not the end of the definition. Both fetchers on the
|
|
#: honeytokens and purple-team pages are written as
|
|
#: `const fetcher = (url: string) =>\n fetch(url).then(...)`, and stopping at
|
|
#: the first newline read the definition as the bare signature `(url: string)
|
|
#: =>`. That has no `fetch(` in it, so the gate concluded "imported from
|
|
#: elsewhere, judged where defined" and skipped nine real findings while
|
|
#: printing a clean line for them.
|
|
_CONTINUES = ("=>", "=", "&&", "||", "?", ":", ",", "+", "(", "[", "{", ".", "await", "return")
|
|
|
|
|
|
def _statement_ends_at(source: str, start: int, cursor: int) -> bool:
|
|
text = source[start:cursor].rstrip()
|
|
if not text:
|
|
return False
|
|
return not any(text.endswith(token) for token in _CONTINUES)
|
|
|
|
|
|
def _fetcher_is_credentialed(source: str, fetcher: str) -> bool | None:
|
|
"""Whether a named SWR fetcher attaches a credential. None means unknown."""
|
|
if fetcher in AUTHED_FETCHERS:
|
|
return True
|
|
if fetcher in UNAUTHED_FETCHERS:
|
|
return False
|
|
definition = _definition_of(source, fetcher)
|
|
if definition is None:
|
|
# Imported from another module; judged where it is defined.
|
|
return None
|
|
stripped = definition.strip().rstrip(";")
|
|
if stripped in AUTHED_FETCHERS:
|
|
return True
|
|
if stripped in UNAUTHED_FETCHERS:
|
|
return False
|
|
if _carries_credential(definition):
|
|
return True
|
|
if "fetch(" in definition:
|
|
# An inline fetcher that calls fetch() on the SWR key with no header.
|
|
# The fetch() scanner cannot see this one: its URL is the parameter,
|
|
# so there is no API path at the call site to match on.
|
|
return False
|
|
return None
|
|
|
|
|
|
def _allowlist_reason(rel_path: str, url: str) -> str | None:
|
|
for (path, fragment), reason in ALLOWED_UNCREDENTIALED.items():
|
|
if path == rel_path and fragment in url:
|
|
return reason
|
|
return None
|
|
|
|
|
|
def inspect(root: pathlib.Path) -> Report:
|
|
findings: list[Finding] = []
|
|
calls = 0
|
|
files = _sources(root)
|
|
used_allowlist: set[tuple[str, str]] = set()
|
|
|
|
for path in files:
|
|
rel = path.relative_to(root / CONSOLE_ROOT).as_posix()
|
|
source = path.read_text(encoding="utf-8", errors="replace")
|
|
|
|
for offset, _raw, parts in _find_call_sites(source, "fetch"):
|
|
url = _api_path_in(parts[0] if parts else "")
|
|
if url is None:
|
|
continue
|
|
calls += 1
|
|
options = ",".join(parts[1:])
|
|
if _carries_credential(options) or _credential_through_a_variable(options, source):
|
|
continue
|
|
reason = _allowlist_reason(rel, url)
|
|
if reason is not None:
|
|
for key in ALLOWED_UNCREDENTIALED:
|
|
if key[0] == rel and key[1] in url:
|
|
used_allowlist.add(key)
|
|
continue
|
|
findings.append(
|
|
Finding(
|
|
rel,
|
|
_line_of(source, offset),
|
|
url,
|
|
"bare-fetch",
|
|
"fetch() with no Authorization header. Use apiRequest() from @/lib/api.",
|
|
)
|
|
)
|
|
|
|
for offset, _raw, parts in _find_call_sites(source, "useSWR"):
|
|
if len(parts) < 2:
|
|
continue
|
|
url = _api_path_in(parts[0])
|
|
if url is None:
|
|
# The key may be a local binding rather than a literal.
|
|
# `const dashKey = `/api/v1/compliance/${f}`;` followed by
|
|
# `useSWR(dashKey, fetcher)` is an API call with a fetcher
|
|
# that sends no credential, and reading only the call site
|
|
# sees a bare identifier with no path in it. That is how
|
|
# `FrameworkView.tsx` kept an uncredentialed compliance call
|
|
# through the sweep that was meant to find exactly this.
|
|
swr_key = parts[0].strip()
|
|
if swr_key.isidentifier():
|
|
binding = _definition_of(source, swr_key)
|
|
if binding is not None:
|
|
url = _api_path_in(binding)
|
|
if url is None:
|
|
continue
|
|
calls += 1
|
|
fetcher = parts[1].strip()
|
|
if "=>" in fetcher or fetcher.startswith("function"):
|
|
# An inline arrow is judged on what it does, not its name.
|
|
if _carries_credential(fetcher) or "fetch(" not in fetcher:
|
|
continue
|
|
elif fetcher.isidentifier():
|
|
credentialed = _fetcher_is_credentialed(source, fetcher)
|
|
if credentialed is not False:
|
|
continue
|
|
else:
|
|
continue
|
|
reason = _allowlist_reason(rel, url)
|
|
if reason is not None:
|
|
continue
|
|
findings.append(
|
|
Finding(
|
|
rel,
|
|
_line_of(source, offset),
|
|
url,
|
|
"swr-fetcher",
|
|
f"useSWR keyed on an API path with `{fetcher}`, which sends no credential. Use authedFetcher from @/lib/api.",
|
|
)
|
|
)
|
|
|
|
stale = [f"{path} :: {fragment}" for (path, fragment) in ALLOWED_UNCREDENTIALED if (path, fragment) not in used_allowlist]
|
|
return Report(findings, len(files), calls, stale)
|
|
|
|
|
|
def _verdict(report: Report) -> int:
|
|
if report.files_scanned == 0:
|
|
print(
|
|
f"check_console_auth_headers: no console sources under {CONSOLE_ROOT} — refusing to report a tree with nothing in it as clean",
|
|
file=sys.stderr,
|
|
)
|
|
return 2
|
|
if report.calls_scanned == 0:
|
|
print(
|
|
"check_console_auth_headers: scanned "
|
|
f"{report.files_scanned} file(s) and found no API call at all. "
|
|
"Either the console stopped calling the API or the matcher broke; "
|
|
"both need a human.",
|
|
file=sys.stderr,
|
|
)
|
|
return 2
|
|
|
|
if report.stale_allowlist:
|
|
print("check_console_auth_headers: allowlist entries whose call is gone:", file=sys.stderr)
|
|
for entry in report.stale_allowlist:
|
|
print(f" {entry}", file=sys.stderr)
|
|
print("Remove them; the allowlist may only shrink.", file=sys.stderr)
|
|
return 1
|
|
|
|
if report.findings:
|
|
print(
|
|
f"check_console_auth_headers: {len(report.findings)} console call(s) reach an API with no credential:",
|
|
file=sys.stderr,
|
|
)
|
|
for finding in report.findings:
|
|
print(f" {finding.render()}", file=sys.stderr)
|
|
return 1
|
|
|
|
print(
|
|
f"check_console_auth_headers: OK — {report.calls_scanned} API call(s) across "
|
|
f"{report.files_scanned} console file(s) all carry a credential "
|
|
f"({len(ALLOWED_UNCREDENTIALED)} allowlisted as public)."
|
|
)
|
|
return 0
|
|
|
|
|
|
# ── Self-test ───────────────────────────────────────────────────────────────
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Case:
|
|
"""One self-test case: source, and the finding kind that must account for it.
|
|
|
|
`expect` names the kind rather than asking "did anything fire", so a bare
|
|
fetch cannot pass on the strength of the SWR rule catching the same line.
|
|
`expect=None` means the case must produce nothing.
|
|
"""
|
|
|
|
description: str
|
|
source: str
|
|
expect: str | None
|
|
suffix: str = ".tsx"
|
|
name: str = "View"
|
|
|
|
|
|
def self_test_cases() -> tuple[Case, ...]:
|
|
return (
|
|
Case(
|
|
"a bare fetch to an API path, the shape that shipped",
|
|
"export async function go() {\n await fetch('/api/v1/rbac/roles/abc', { method: 'DELETE' });\n}\n",
|
|
"bare-fetch",
|
|
),
|
|
Case(
|
|
"a template-literal URL behind a base variable",
|
|
"const API = process.env.NEXT_PUBLIC_HONEYTOKENS_URL ?? '';\n"
|
|
"export async function go() {\n"
|
|
" await fetch(`${API}/api/v1/honeytokens/x/revoke`, { method: 'PATCH' });\n}\n",
|
|
"bare-fetch",
|
|
),
|
|
Case(
|
|
"X-Tenant-Id alone, which reads like an identity and is not one",
|
|
"export async function go() {\n"
|
|
" await fetch('/api/v1/cases/1/investigations/2/report.pdf', {\n"
|
|
" headers: { 'X-Tenant-Id': t },\n });\n}\n",
|
|
"bare-fetch",
|
|
),
|
|
Case(
|
|
"credentials: 'include', which sends cookies the API never reads",
|
|
"export async function go() {\n await fetch('/api/v1/compliance/soc2/export', { credentials: 'include' });\n}\n",
|
|
"bare-fetch",
|
|
),
|
|
# The two halves of reading `headers` as a name. A multipart upload
|
|
# has to build the object and drop the JSON Content-Type, so it
|
|
# cannot write `apiHeaders()` at the call site — and the exemption
|
|
# is only safe because the name has to be bound to `apiHeaders(`.
|
|
Case(
|
|
"headers passed by name, bound to apiHeaders() — credentialed",
|
|
"import { apiHeaders } from '@/lib/api';\n"
|
|
"export async function go(file: File) {\n"
|
|
" const headers = apiHeaders();\n"
|
|
" delete headers['Content-Type'];\n"
|
|
" await fetch('/api/v1/branding/assets/logo', { method: 'POST', headers, body: f });\n}\n",
|
|
None,
|
|
),
|
|
Case(
|
|
"headers passed by name, bound to anything else — still a finding",
|
|
"export async function go(file: File) {\n"
|
|
" const headers = { 'X-Tenant-Id': t };\n"
|
|
" await fetch('/api/v1/branding/assets/logo', { method: 'POST', headers, body: f });\n}\n",
|
|
"bare-fetch",
|
|
),
|
|
Case(
|
|
"a local alias of an unauthenticated fetcher used by SWR",
|
|
"import { jsonFetcher } from '@/lib/failure';\n"
|
|
"const fetcher = jsonFetcher;\n"
|
|
"export function V() {\n"
|
|
" const { data } = useSWR('/api/v1/rbac/roles', fetcher);\n"
|
|
" return <b>{data}</b>;\n}\n",
|
|
"swr-fetcher",
|
|
name="Aliased",
|
|
),
|
|
Case(
|
|
"the same alias behind a generic, which hid both real SWR sites",
|
|
"import { jsonFetcher } from '@/lib/failure';\n"
|
|
"const fetcher = jsonFetcher;\n"
|
|
"export function V() {\n"
|
|
" const { data } = useSWR<Role[]>('/api/v1/rbac/roles', fetcher, { x: 1 });\n"
|
|
" return <b>{data}</b>;\n}\n",
|
|
"swr-fetcher",
|
|
name="Generic",
|
|
),
|
|
Case(
|
|
"an inline fetcher whose URL is the SWR key, invisible to fetch() scanning",
|
|
"const fetcher = async (url: string) => {\n"
|
|
" const r = await fetch(url);\n return r.json();\n};\n"
|
|
"export function V() {\n"
|
|
" const { data } = useSWR<Row[]>('/api/v1/sla/config', fetcher);\n"
|
|
" return <b>{data}</b>;\n}\n",
|
|
"swr-fetcher",
|
|
name="Inline",
|
|
),
|
|
# ── and the directions it must not fire in ──────────────────────────
|
|
Case(
|
|
"a credentialed fetch",
|
|
"export async function go() {\n"
|
|
" await fetch('/api/v1/playbooks/1/run', {\n"
|
|
" method: 'POST',\n headers: { Authorization: `Bearer ${t}` },\n });\n}\n",
|
|
None,
|
|
),
|
|
Case(
|
|
"the authenticated client, which attaches the header itself",
|
|
"import { apiRequest, authedFetcher } from '@/lib/api';\n"
|
|
"export function V() {\n"
|
|
" const { data } = useSWR('/api/v1/rbac/roles', authedFetcher);\n"
|
|
" void apiRequest('/api/v1/playbooks', { method: 'POST' });\n"
|
|
" return <b>{data}</b>;\n}\n",
|
|
None,
|
|
),
|
|
Case(
|
|
"a multi-line arrow fetcher, truncated at the newline by a first pass",
|
|
"const fetcher = (url: string) =>\n"
|
|
" fetch(url).then((r) => {\n"
|
|
" if (!r.ok) throw new Error(`HTTP ${r.status}`)\n"
|
|
" return r.json()\n"
|
|
" })\n"
|
|
"export function V() {\n"
|
|
" const { data } = useSWR<Row[]>(t ? `${API}/api/v1/purple-team/coverage?x=1` : null, fetcher)\n"
|
|
" return <b>{data}</b>;\n}\n",
|
|
"swr-fetcher",
|
|
name="MultiLine",
|
|
),
|
|
Case(
|
|
"the header helper, which is the credentialed path",
|
|
"import { apiHeaders } from '@/lib/api';\n"
|
|
"export async function go() {\n"
|
|
" await fetch('/api/v1/auth/me/preferences', {\n"
|
|
" method: 'PATCH',\n headers: apiHeaders(),\n });\n}\n",
|
|
None,
|
|
),
|
|
Case(
|
|
"a fetch to something that is not an AiSOC API",
|
|
"export async function go() {\n await fetch('https://cdn.example.com/logo.svg');\n}\n",
|
|
None,
|
|
),
|
|
Case(
|
|
"a template literal whose substitution contains braces and a quote",
|
|
"export async function go() {\n"
|
|
" await fetch(`/api/v1/x/${encodeURIComponent(o['k'])}`, {\n"
|
|
" headers: { Authorization: `Bearer ${t}` },\n });\n}\n",
|
|
None,
|
|
),
|
|
)
|
|
|
|
|
|
def _case_results(tmp: pathlib.Path) -> list[tuple[str, bool]]:
|
|
results: list[tuple[str, bool]] = []
|
|
for index, case in enumerate(self_test_cases()):
|
|
tree = tmp / f"case{index}"
|
|
console = tree / CONSOLE_ROOT
|
|
console.mkdir(parents=True)
|
|
(console / f"{case.name}{case.suffix}").write_text(case.source, encoding="utf-8")
|
|
report = inspect(tree)
|
|
kinds = {finding.kind for finding in report.findings}
|
|
if case.expect is None:
|
|
passed = not report.findings
|
|
detail = f"expected nothing, got {sorted(kinds)}" if not passed else ""
|
|
else:
|
|
passed = case.expect in kinds
|
|
detail = f"expected {case.expect}, got {sorted(kinds)}" if not passed else ""
|
|
results.append((f"{case.description}{f' — {detail}' if detail else ''}", passed))
|
|
return results
|
|
|
|
|
|
def _corpus_result(root: pathlib.Path) -> tuple[str, bool]:
|
|
"""A console whose calls all vanished must fail, not pass."""
|
|
report = inspect(root)
|
|
return (
|
|
f"counts what it scanned ({report.calls_scanned} API calls in {report.files_scanned} files)",
|
|
report.calls_scanned > 0 and report.files_scanned > 0,
|
|
)
|
|
|
|
|
|
def self_test() -> int:
|
|
with tempfile.TemporaryDirectory(prefix="aisoc-console-auth-") as tmp:
|
|
extra = _case_results(pathlib.Path(tmp))
|
|
extra.append(_corpus_result(repo_root()))
|
|
return self_test_main(pathlib.Path(__file__).name, ["--check"], extra)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--check", action="store_true", help="render a verdict (default)")
|
|
parser.add_argument(SELF_TEST_FLAG, action="store_true", dest="self_test")
|
|
args = parser.parse_args()
|
|
if args.self_test:
|
|
return self_test()
|
|
return _verdict(inspect(repo_root()))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|