mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
f4cea19023c331c052d1585e45ec76cc4f7fcab7
529
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
13d6a2638c |
feat(phishing): vendor intake door, recipient scoping, BEC signals, reporter feedback and the org-level block (WS3)
Vendor alerts join the same campaigns user reports join, through the same record_report, mapped from published fields only. Scoping answers clicked/replied/credential-submitted per recipient with no-requires- connected-telemetry honesty, and revocation scales with established credential risk only. BEC signals are sourced evidence (domain-age refused with its reason). Feedback is policy-gated, fixed-template, webhook-delivered. The org block is Mimecast's real Blocked Senders policy behind governed block_sender_org/unblock_sender_org with readback probes and policy-id rollback. Migration 177; ratchet 80->81. |
||
|
|
8a5f68a0e1 |
feat(ai-security): session sequences, runaway sessions, refused assets, MCP drift, shadow AI and prompt classes (WS5) (#2009)
## What
WS5 of the gap-closure program: AI security at runtime. Six items; every
detection goes through the real loader + engine, every store truth
through live Postgres, and the SDK's standing privacy claim stays
exactly true.
## WS5.1 — Session-scoped sequences
`wd-ai-session-untrusted-then-secret-then-egress`: inside ONE session,
an injection/guardrail finding → a prompt the SDK's local scanner
flagged as secret-bearing → an egress-capable tool call = one HIGH
finding, grouped by `session_id`, ordered, 1h window. **The negative
fixture the brief names is pinned**: the same three events across two
sessions do NOT fire — the session is the claim. `TestTemplateCoupling`
reads the committed ai ingest templates and fails **by name** on any
rule field they stop mapping — the drift gate against the recorded
aspirational-rule defect.
## WS5.2 — Runaway sessions
`wd-ai-session-tool-call-flood` (per-session rate; two calm sessions do
not sum) and `wd-ai-identical-prompt-repetition` — **`redaction.py`
hashes every prompt "precisely so detection can ask: the same prompt
fifty times?" and nothing consumed the hash until now**. Grouped by the
hash itself; the rule's name states the cross-session scoping out loud.
Duration/token-burn deliberately stays with the existing spend-anomaly
baselines (a second rule would be a second answer to the same question).
## WS5.3 — Refused assets: the defect fix and the doorbell
**The defect, exactly as Phase 0 recorded it**: the recorder's upsert
set `risk_score = EXCLUDED.risk_score` unconditionally while `_score()`
treats `sanctioned` as always-None by design — so re-observing a REFUSED
asset silently downgraded `ai_inventory`'s +30 "Reviewed and refused,
and still running" to "Not declared". The scorer-parity suite only
exercised `sanctioned=None`, which is why the failing test had to be
**live**: the overwrite was the SQL's behaviour. The fix is the upsert's
own CASE — a judged asset's score is owned by the sanction route
(refused AND approved alike; a judgement is a judgement), an unjudged
one keeps the recorder's fresher score. Proven both ways on real
Postgres.
And the alert half: a refused asset observed again now **raises a HIGH
triage alert citing the sanction decision** — `drain_refused()` on the
recorder, one notice per flush, raised through the ordinary fusion path
(`_fuse_and_persist`), with fusion's own dedup bounding a chatty agent.
Containment stays a governed playbook step; this is the doorbell.
## WS5.4 — MCP manifest drift and tool poisoning
The SDK gains `mcp_manifest(server, tools)`: tool **names + description
SHA-256s + annotations, hashed in the customer's process** — description
text never ships; at most one ≤80-char snippet travels, and only for a
description that already tripped an instruction pattern (the pattern
list mirrors the concerns of the platform guard
`services/agents/app/mcp/untrusted.py`, which stays the canonical
defence). The recorder versions manifests per (tenant, server) —
migration 176, same-content touches, changed-content versions — and
drift becomes a triage alert naming what moved: `description_drift`,
`new_state_changing_tool` (a read-only server growing `delete_repo` is
the poisoning shape), `instruction_shaped_description` (HIGH — that one
is the answer, not the question).
## WS5.5 — Shadow AI from network telemetry
A shipped catalog (`ai_app_catalog.json`) whose **every row is a
vendor's own documented product domain, with per-row provenance** and a
stated limitation up top. SWG/DNS events (zscaler, netskope,
cisco_umbrella, cloudflare_zt) matching it become AI-estate sightings
from a `network` source whose attributes state `cannot_see_prompts:
true` outright. A refused catalog app re-observed now composes with
WS5.3's alert automatically. **Refused with a recorded reason**: the
upload-volume-to-unsanctioned-apps detection — no SWG connector
currently maps a bytes field into the engine's namespace, so the rule
would have been aspirational; it lands when a connector carries bytes.
## WS5.6 — Sensitive classes in prompts
`classes.py`: opt-in (`classify_prompt_classes=False` by default), local
regex, **counts only** ({"personal": 2} — no text, no offsets). Off by
default means the field is **absent**, not an empty dict — and the test
pins that the standing claim holds: with the opt-in on, `prompt` still
never leaves the process.
## Testing
- Fusion suite **1,266 passed** (8 new session-rule cases incl. both
negative fixtures; 2 consumer refused-alert cases; template-coupling
pin).
- SDK suite **27 passed** (hashes-never-text, bounded snippet
only-when-tripped, counts-only, absent-unless-opted-in).
- **5 live-Postgres cases** (new `integration.yml` step): judged-score
survival both ways + unjudged refresh + refused-notice once-per-flush +
manifest versioning/touch/drift with findings named.
**Negative controls (applied, observed failing, restored):**
1. Reverting the upsert CASE to the pre-fix overwrite → the
judgement-survival live cases fail.
2. Disabling the manifest hash comparison → the live drift case fails.
## Gates
check_windowed_translation OK · migration_numbering OK (176, allocated)
· mypy baseline OK · ruff clean · claim matrix **+3 GATED rows**
(tallies recomputed) · readme_gates OK · ai-runtime template extended
(`mcp_tools`, `prompt_class_counts`) with the coupling pin covering
both.
## Could not verify
- The windowed rules against the Go normalizer end-to-end (ingest →
fusion over Kafka): the coupling pin holds the field names to the
committed templates, and the engine legs run in-process; the full-spine
replay is the integration suite's existing surface.
- The SDK against a live MCP server: `mcp_manifest` is driven by the
host application; the event shape and hashing are pinned by the SDK
suite.
|
||
|
|
73036c9b57 |
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. |
||
|
|
4c9b24a5d1 |
feat(hunt): bounded campaigns, hypothesis selection and lead verification (WS6) (#2010)
## What WS6 of the gap-closure program: agentic hunting campaigns. WS6.3 (governed intake) shipped earlier in PR #1116; this PR is 6.1, 6.2 and 6.4, plus 6.3's approval gate carried into campaign selection. ## WS6.1 — Bounded campaigns (`app/hunt/campaign.py`) A campaign is a **sequence of distinct closed-schema plans**. The single-hunt agent is untouched — one plan, one correction, the model never writes query text (`check_hunt_agent_boundary` unchanged and green). The campaign adds the loop under rules that keep a loop honest: - **Summaries, never rows**: the next step's prompt carries row counts and top values passed through the egress pseudonymizer (`app/privacy`) — the test asserts the raw hostname is ABSENT from the second prompt while counts survive. - **Budgets gate BEFORE each step** (steps / rows / model calls / wall clock): an exhausted budget prevents the step — the test proves step two never executes. - **Not a retry loop**: every step must state the NEW question it answers; a repeated question stops the campaign, an identical plan under new words stops it, and two refused plans in a row trip the one-correction rule (a flag-reset bug here was caught by the test's first run — the budget absorbed the loop — and fixed with a streak counter). - **Outcomes kept apart**: ranked leads; **no-finding with a coverage statement** naming sources, fields searched and max lookback; could-not-check. Every step, refusal and stop lands in the Investigation Ledger with the budget state. ## WS6.2 — The hypothesis scheduler (`app/hunt/hypothesis_scheduler.py`, migration 179) Three deterministic schedulers existed; none SELECTED hypotheses or dispatched the LLM hunt agent. This is the selection layer: per tenant, **opt-in (default OFF)**, cadenced (`hunt_campaign_policies`), budgeted (per-tenant `CampaignBudgets` overrides), capped per tick, and **every selection is recorded in the ledger WITH its reason before the campaign starts**. Selection sources this revision: **approved hunt requests** not yet campaigned (`campaigned_at` marks one-request-one-campaign). **Recorded follow-ups, named rather than silently absent**: the coverage-gap ranker, KEV-exposure matches, and new-intel sources plug into the same `select_for_tenant` seam. ## WS6.3 remainder — approval precedes execution `_APPROVED_UNCAMPAIGNED_SQL` selects only `approved_at IS NOT NULL`; the test proves an unapproved request is never selected and the campaign runner is never awaited. ## WS6.4 — Lead verification and the real proposal id - **Leads → the investigation agent**: each top lead (capped at 3 — the investigator is the expensive half) becomes a `HUNT LEAD`-labelled state run through `run_deep_investigation` under its own run; verdicts ride back on the lead dicts. - **The long-declared, never-assigned `proposal_id` is finally real**: a productive campaign posts to the new `POST /agent-tools/hunt-plan/propose-detection` (same `rules:write`-governed surface class as the operator path), which writes the same DRAFT scaffold the saved-hunt path writes (`source: hunt-campaign`) — the reviewer reads the campaign's questions and plans, and **nothing auto-promotes**. ## Testing - `test_hunt_campaign.py` — **9 cases** through the real plan validator (summary hand-off with scrubbing asserted at the prompt; budget prevention; both repeat-stops; one-correction; coverage statement; could-not-check; count-preserving scrub). - `test_hypothesis_scheduler.py` — **5 cases** (approved-runs-once with reason recorded BEFORE launch; unapproved-never-selected; per-tick cap 2-of-5; verify-then-propose ordering; investigator cap + labelling). - Full targeted agents suites green; the 41 collection errors in the local venv are pre-existing (identical on the clean tree — this venv lacks `mcp`; CI's agents env carries it). ## Gates check_hunt_agent_boundary OK · migration_numbering OK (179, allocated) · mypy baseline OK · ruff clean · claim matrix **+2 GATED rows** (tallies recomputed) · readme_gates OK · OpenAPI regenerated (additive — the propose-detection route). ## Could not verify - A live LLM driving a campaign end-to-end (no funded key in this environment): every step runs through the real validator and the scripted-invoke seam is the same one the single-hunt suite uses. - The scheduler against live Postgres: its SQL mirrors shapes proven live elsewhere (policy enumeration, marked-once updates); the fake honours the approval gate the way the WHERE clause does, and the live migration applies in CI's chain. |
||
|
|
41351bde74 |
fix(web): every actionable destination the marketing site ships now exists (#2012)
## QA pass finding: the marketing site shipped links and contacts whose
destinations no longer exist
A comprehensive QA pass fetched every external destination the web app
publishes and verified each against the authority that owns it. Four
classes were dead in ways a reader hits immediately:
| Destination | Where it shipped | Evidence it is dead |
|---|---|---|
| `discord.gg/aisoc` | footer nav + footer social icons (every marketing
page and the 404 page) | Discord's own invite API answers `{"message":
"Unknown Invite", "code": 10006}` — the invite *page* serves HTTP 200,
which is exactly why a status-code fetch never caught it |
| `twitter.com/tryaisoc` | footer social icons | `x.com/tryaisoc`
answers **404** — the account does not exist |
| 17 `mailto:` links (`hello@`, `press@`, `privacy@`, `security@`,
`legal@` at the dead domain) across about, blog (×2), contact (×2),
customers (×2), press, pricing, privacy, sovereign (×4), terms (×2),
waitlist (error copy ×2) | `dig MX` returns **no MX record** for the
domain — every enquiry bounced, including the privacy page's
deletion-request route and a "security disclosures" inbox that
contradicted SECURITY.md's actual channel (GitHub private vulnerability
reporting; SECURITY.md itself records the prior dead-address incident in
#637) |
| `…/cases/INC-RT-001?tab=ledger` deep links ("Open the demo") | landing
Hero primary CTA + why-open-source page | the host now **301s every path
to the repository front page**, so the button's "pre-seeded
investigation with the ledger visible" promise landed on a README. The
hero also claimed the host "is the always-on demo" — there is no hosted
demo |
Also corrected alongside (same concern): the mesh marketing page
defaulted its hub to a host that is **NXDOMAIN** (every unconfigured
deployment paid a doomed fetch per view and rendered placeholders — now
no `MESH_HUB_URL` means no fetch, same honest placeholders), the mesh
architecture doc and `services/mesh` docstring claimed a community hub
"runs at" that host, and the badge route's docstring example told README
authors to embed a shields endpoint URL that the 301 breaks.
### Replacements, each verified live (HTTP 200 / API-confirmed) before
landing
- GitHub Discussions — the channel SUPPORT.md names (footer, all contact
surfaces)
- the published quickstart (`make demo` seeds the investigation the demo
buttons promised)
- SECURITY.md's private vulnerability reporting (security-contact
claims)
- the footer's X entry is deleted rather than redirected: no live
destination serves that intent (house rule: delete the link and rewrite,
never point at a 404)
### Failing-test-first
`tests/test_dead_destination_links.py` fails on the pre-fix tree
(collection of every dead destination above, with the evidence recorded
per needle), passes post-fix, and carries its own anti-vacuity guard (a
scan that inspects under 200 web sources fails rather than passing
empty).
**Negative control (recorded):** reverting `Footer.tsx` alone →
`test_web_sources_ship_no_dead_destinations` FAILS naming
`discord.gg/aisoc` and `twitter.com/tryaisoc`; restored → 3/3 pass.
The hosted-hostname gate's allow-list is ratcheted to match (15 entries
dropped, 4 lowered, 1 added for the new test's own needle strings) — its
self-test and full scan pass, so a re-add of any of these is a
deliberate decision against recorded evidence, not an accident.
### Battery (all on the rebased tree)
- repo gate suite: **2,057 passed** (1 pre-existing env-only failure on
this host: the docker-backed live-initdb test bind-mounts from a path
outside the VM's share — the same commit **passes in 5.86 s** from a
mount-visible worktree; verified, not assumed)
- web: `tsc --noEmit` clean, ESLint clean on every touched file, full
vitest suite green (incl. the updated `Hero.test.tsx`, which pinned the
dead CTA and now pins the live one)
- `check_hosted_hostname.py` (+ `--self-test`),
`check_changelog_frozen.py`, `check_competitor_names.py`,
`check_attribution.py --all`: all rc 0
- api suite on CI-parity Python 3.11: **5,572 passed** (unchanged by
this diff; run as part of the QA pass)
### Could not verify
- Whether a Discord server exists under a *different* invite (only the
shipped invite was testable; if one exists, re-adding the row with a
working invite is one line — the footer comment says exactly that).
- The OG-image change renders identically except the footer line; not
re-screenshotted (text-only change in satori markup).
|
||
|
|
71d10b0764 |
chore: internal planning labels live in PR titles only — behaviour text everywhere else, plus the program index (#2015)
## What
WS workstream ids (`WS4.1`, `WS7.2`, …) and brief-internal rule numbers
("rule 14") had leaked into surfaces a reader actually ships or
publishes — and nothing in the tree defined them, because they come from
an uncommitted program brief. A reader of the published OpenAPI spec,
the changelog or a module docstring hit an opaque label.
Every citation is replaced by the behaviour it referred to, and a
neutral program index now exists at
**`docs/roadmap/capability-program.md`**: a WS1–WS8 table in neutral
language ("benchmarked against a reference managed agentic-security
service"), each row linked to its merged PRs (Phase 0
[#1997](https://github.com/beenuar/AiSOC/pull/1997); WS1.1
[#1998](https://github.com/beenuar/AiSOC/pull/1998); WS7.1–7.4
[#1999](https://github.com/beenuar/AiSOC/pull/1999)–[#2002](https://github.com/beenuar/AiSOC/pull/2002);
WS4.1/4.2/4.4
[#2003](https://github.com/beenuar/AiSOC/pull/2003)–[#2005](https://github.com/beenuar/AiSOC/pull/2005)),
with in-flight workstreams marked as such.
Comments/docstrings/prose only — zero behaviour change. No test file or
symbol is renamed.
## Labels removed, per surface
| Surface | Labeled lines rewritten |
|---|---|
| `docs/openapi.yaml` (regenerated, not hand-edited) | 3 (WS4.1, WS7.4,
WS4.4) |
| `.github/workflows/integration.yml` step comments | 3 |
| `CHANGELOG.md` — Unreleased section only | 10 |
| Code, tests, scripts, migrations (`--` comments),
`docs/architecture/SYSTEM_DESIGN.md` | 85 WS lines + 4 "rule 14" lines |
"rule 14" **does exist on main** (4 sites: `case_resolution.py`,
`models/case_resolution.py`, migration 166's `--` comment,
`test_case_resolution_contract.py`) and each is rewritten as the
behaviour it names ("new enforcement is opt-in"). Rule references that
*are* defined in-tree were deliberately left: `docs/cve-patch-policy.md
rule 5`, `event_warehouse/registry.py`'s self-numbered selection rules,
and the detection title "GCP Firewall Rule 0.0.0.0/0".
Two WS namespaces turned out to be live: the gap-closure program's, and
an **older integrations program** (connectors' "WS8: bidirectional
ticketing", `base.py`'s "WS4" push capabilities, oauth/wizard "WS5").
Both are scrubbed to behaviour text; the index covers the current
program only and says so.
## Spec is regenerated, not hand-edited
The three spec hits were traced to their source docstrings (`alerts.py`
DLP-finding route, `cases.py` attention-feed route,
`business_context.py` `ManagedRulesOut` model), the docstrings
rewritten, and the spec regenerated via `scripts/export_openapi.py`. The
resulting spec diff is **exactly those three description strings** —
nothing else moved — and `scripts/export_openapi.py --check` passes
(exit 0, "docs/openapi.yaml is up to date").
The vendored twin
`services/api/app/_vendor/action_contracts/capability_contracts.py` was
regenerated through `scripts/sync_vendored_action_contracts.py` from the
actions-side edit, byte-identical.
## Gates and tests (all run pipelessly, exit codes echoed)
| Check | Result |
|---|---|
| `scripts/export_openapi.py --check` | exit 0 |
| `scripts/check_competitor_names.py` | exit 0 (15,612 files scanned;
the new index passes) |
| `scripts/check_claim_gate_matrix.py` | exit 0 (410 rows — untouched,
no tally change) |
| `scripts/readme_gates.py` | exit 0 |
| `scripts/check_mypy_baseline.py` | exit 0 ("no tree got worse") |
| `ruff format --check` + `ruff check` on all 50 touched `.py` files |
exit 0 / exit 0 |
| API test subset (14 files covering every touched api module) | 303
passed |
| Actions subset (`test_sync_detection_rule_vendor_arms`,
`test_live_action_builtins`) | 21 passed |
| Connectors subset (`test_m365_audit_dlp_toggle`,
`test_push_capabilities`) | 38 passed |
| Agents subset (`test_business_context_managed_rules`,
`test_deep_investigation`) | 47 passed, 3 pre-existing skips |
## Deliberately left in place
- **Migration `035_case_external_refs.sql:106`** — `COMMENT ON TABLE …
IS 'WS8: …'` is *executed DDL* in an applied migration, not a code
comment; rewriting it would change what a fresh install runs versus an
upgraded one. Left as the one WS string in the tree outside the index; a
future migration can retitle the table comment if wanted.
- `WIN-WS42` in two agents tests — a fixture hostname, not a label.
- A base64 integrity hash in `services/realtime/package-lock.json` that
coincidentally contains `Ws41`.
## For the close-out sweep
- **Labels arriving with in-flight PRs get a follow-up sweep at program
close-out.** Open PRs #2006–#2012 and #2014 (other lanes) will merge
more labeled text; their branches were deliberately not touched.
- `apps/web` carries "VelvetEdge spec rule 2/3/7/10" comments citing the
UI program's spec, which is also not committed anywhere — same defect
class, different program namespace, outside this PR's surfaces. Recorded
here for the close-out sweep.
## Convention (stated in the index's footer as well)
Workstream ids and rule numbers live in **PR titles only** — never in
code, specs, workflows or the changelog. Those surfaces describe the
behaviour; `docs/roadmap/capability-program.md` is the one place ids are
defined.
Co-authored-by: Beenu Arora <beenu@cyble.com>
|
||
|
|
035bb516b4 |
feat(api): the insider watchlist expires, elevates and reviews for real (WS4.4) (#2005)
## What WS4.4 of the gap-closure program: departing-employee / insider-risk monitoring. `user_risk_profiles.is_watchlisted` has existed since migration 014 and the console PATCH wrote it — **and nothing consumed it**. No alert was elevated, no row ever expired, nothing reviewed the identity's activity. A watchlist nothing reads is a checkbox. ## The three halves (migration 168) **Expiry — never indefinite.** Watchlisting requires a reason and a future `watchlist_expires_at` (422 names the missing one; the console's one-click path falls back to the tenant's `default_expiry_days`). A sweep worker (`insider_watchlist_sweep`, on by default like `approval_expiry` — hygiene of a deadline we recorded, not automation toward anyone's estate) flips expired rows and rebuilds. Legacy watchlisted rows are backfilled with a 90-day horizon. **Elevation through the existing business-context path — no parallel mechanism.** Watchlisted identities become *managed* rules: a tag rule (`insider-watchlist`) and a severity floor (`info`/`low` → `medium`), written to a machine-owned `managed_yaml` column **beside** the analyst's verbatim `yaml_text` on the same row. Same engine, same auto-triage application point (`BusinessContextApplier` now selects and parses both documents independently, so a syntax error in the analyst's draft never withdraws elevation and a managed-rule bug never disables the tenant's suppressions). The console save path owns `yaml_text` only; the watchlist upsert owns `managed_yaml` only. The floor is guarded by a `severity in [info, low]` clause because `set_severity` is a fixed assignment — without the guard it would **downgrade** `high`/`critical`, proven by the negative control. Read-only exposure: `GET /business-context/managed-rules`. **Review.** The transition onto the list opens a departure-review case: exfil-shaped lake activity (reviewable pattern list, counted per concrete event type so the analyst sees what matched) plus the identity's alerts in the window. An unreachable lake reads **"unknown, not zero"**; a ref-less profile names both gaps. **Two doors.** Manual (console). HR: per-tenant opt-in (`insider_watchlist_policies.hr_sync_enabled`, **default off**; `PUT /insider-threat/watchlist-policy` requires `settings:write` — switching on an automated door is tenant configuration, unlike watchlisting one subject). The sweep watches `workforce_members` (the HR store the connectors service already syncs) for `terminated`/last-day members and lists them with the HR fact as the reason and last-day-plus-grace as the expiry — idempotently, never overwriting or shortening a manual row. ## Two grammar implementations, held together The agents service re-implements the business-context grammar (separate image, no shared import). A golden fixture (`services/api/tests/fixtures/managed_rules_golden.yaml`) is pinned by the API generator test and parsed by the agents suite with *its* loader — either side drifting goes red. Writing this found a real incompatibility immediately: the first generated ids (`managed:insider-watchlist:0:tag`) violated the loader's kebab-case slug rule. ## Testing - `services/api/tests/test_insider_watchlist.py` — **21 cases** (generation parses with the console's own loader; the real engine floors low, tags, and **never downgrades** `medium`/`high`/`critical`; adversarial YAML-shaped reasons stay data; validation messages; lookback honesty; HR idempotence). - `services/agents/tests/test_business_context_managed_rules.py` — **8 cases** (golden fixture through the agents loader + evaluator; two-document isolation both ways). - `tests/isolation/test_insider_watchlist_live.py` — **6 cases on live Postgres** (new `integration.yml` step, migration trigger paths updated): expiry exclusion is the rebuild SELECT's own WHERE clause; the two upserts own one column each and never clobber the other; `watchlist_source` is a DB CHECK; policy RLS judged under the NOBYPASSRLS `aisoc_app` role including the unbound arm the sweep worker depends on; the HR door end to end (workforce row → watchlist row + managed rule + review case saying "unknown, not zero" for the absent lake), idempotent on the second sweep. Fails at setup on the pre-change tree. **Negative controls (applied, observed failing, restored):** 1. Removing `AND watchlist_expires_at > :now` from the rebuild SELECT → `test_rebuild_excludes_expired_and_refless_rows` fails live. 2. Removing the `severity in [info, low]` guard → `test_never_downgrades[high]` and `[critical]` fail (the floor becomes a downgrade). ## Gates route_auth OK · route_tenant_scope OK · tenant_query_predicates OK · module_reachability OK (worker + service reachable from lifespan) · migration_numbering OK (168, allocated block) · ORM-migration parity OK · mypy baseline OK · ruff clean · claim matrix **408 rows — 399 GATED / 9 PARTIAL / 0 NO GATE** (new GATED row; tallies recomputed by the script) · readme_gates OK · OpenAPI regenerated (additive). ## Could not verify The lake half of the lookback ran against the mocked `execute_lake_query` and the live suite's *absent* lake (the honest could-not-check path); it has not been exercised against a live ClickHouse with matching `raw_events` rows — the SQL follows `identity_usage_collector.py`'s proven shape (pyformat binds, same columns). |
||
|
|
3f8e74521c |
chore: gap-closure program Phase 0 — competitor gate + verified gap baseline (#1997)
## Phase 0 — gap-closure program baseline and guardrails
Per the program brief: one pull request, **no product code**. Three
deliverables: (1) the benchmark added to the competitor gate, (2) every
§4 gap re-verified against the current tree by reading code, (3)
proposed claim-matrix rows per workstream for review before any code
exists.
### 1. Competitor gate
`scripts/competitor_names.toml` gains the reference managed
agentic-security service (brand pair + domain banned; the plain English
word stays usable — a scheduler-prose good fixture pins "daylight
saving"). `scripts/competitor_fixtures.json` carries the known-bad and
known-good samples. `check_competitor_names.py --self-test` and the full
gate run green locally (13 known-bad / 15 known-good / 3+3 comparison
fixtures).
### 2. Gap re-verification (HEAD `71360e1eb`, v23.6.1 — the brief's own
baseline commit)
Every §4 claim re-verified by reading code, not docstrings. Headline
deltas against the brief:
- **WS6-3 (hunt-request intake) is ALREADY CLOSED** — shipped in PR
#1116 (`614e64bee`, 2026-10-04): `POST /api/v1/agents/hunt` with the
untrusted-input fence + the console Hunt form, plus a second intake via
threat-report drafting with explicit approval. WS6.4's remaining scope
is analyst approval gating *campaign launch*.
- **Partially closed** (exists/missing named in the tables): WS3-3
(reply-to mismatch + display-name impersonation ship in `headers.py`;
baseline/lookalike/domain-age legs don't), WS4-4 (scheduled HR→workforce
sync and `departing_soon` prompt facts exist;
watchlist/sensitivity/lookback automation doesn't), WS5-2
(token-burn-vs-baseline and volume-z detections ship; per-session
rate/repetition/duration don't), WS6-2 (three deterministic schedulers
exist; hypothesis *selection* doesn't), WS6-4 (saved/retro-hunt hits
open cases; no investigator verification of leads), WS8-5 (weekly
per-tenant executive digest exists and is scheduled; means lack
denominators, nothing delivers it, no service-review framing).
- **Everything else: STILL OPEN** exactly as the brief states (31 of 39
claims), including both deliberate in-code deferrals (`block_sender`'s
per-mailbox contract note; `m365_audit`'s DLP.All docstring) — closing
them is landing an invited path.
- **One adjacent live defect found** (fix lands inside WS5.3,
failing-test-first): re-observing a sanction-refused AI asset silently
*downgrades* its risk score — the recorder's flush overwrites the
sanction-aware score with a sanction-blind one, erasing +30 "refused and
still running" and rewriting the reason to the false "Not declared".
Execution notes the verification surfaced (recorded here so the
workstreams reuse rather than rebuild): the AiSOC-native rule-health
machinery (`rule_tuning.py` FP-rate-with-denominator, last-fired
staleness) is exactly WS1.3's shape and only lacks a SIEM-rule target;
one vendor-client "read rules back" surface unblocks WS1.2 + WS1.3 +
WS1.1's probe together; 2,005 quarantined SPL imports are a ready corpus
for WS1.5 round-trip tests; Box/Dropbox connectors already ingest
sharing events (detection half of WS4-5); the windowed engine already
runs session-keyed ordered sequences, so WS5.1 is rule-content work; the
SDK already hashes prompts for the repeated-identical-call question and
nothing consumes the hash; `root_cause_findings` (table) is an unrelated
fusion dedup concept sharing WS7.1's name — the new record needs its own
name; a backend `shifts.py` once existed and was deliberately deleted
(test-pinned), so WS8.1 must supersede that pin knowingly; the
escalations ack clock stops only via war-room actions; the unfed
outbound-webhook queue is the shared missing link between WS8.3 and
WS8.4.
<details><summary><b>Verification table — WS1 + WS2</b></summary>
I'm checking that the adapter maps the simulated run to SIMULATED, which
it does, so the governance layer treats it as not executed. The
user-facing result still reads as SIMULATED even though the Splunk
tenant has credentials, which is the gap I flagged earlier. Now I'm
turning to the SPL corpus.
Now I'm checking whether the SPL import directory at that path is
actually there, and counting what's in it.
All 13 claims verified against HEAD
`71360e1eb3f509452c5db7c6e2fd1370e0676fab` (branch
`chore/gap-closure-phase0`). Every claim checks out as described — **all
13 are STILL OPEN** (two of them, WS2-1 and WS2-7, are factual premises
that are accurate rather than gaps). No `git log -S` archaeology was
needed since nothing turned out to be closed.
| Claim | Verdict | Evidence | Note |
|---|---|---|---|
| WS1-1 | STILL OPEN |
`services/actions/app/live_actions/builtins.py:524-531`;
`services/actions/app/executors/siem.py:371` (only `_elastic_client`),
`:130-133` (None without `elastic_url`), `:393-409` (simulation),
`:411-414` (rollback "would disable rule" → True);
`services/actions/app/clients/splunk_client.py:228` (sole occurrence =
definition, 0 callers);
`services/actions/app/live_actions/capability_contracts.py:589`
(`has_verification_probe=False`) | All four sub-claims true; adapter
does surface the gap honestly as `LiveActionStatus.SIMULATED`
(builtins.py:143-155), so governance sees it as not-executed |
| WS1-2 | STILL OPEN | `splunk_client.py` methods (lines 64-347):
search/notables/lookup/correlation-write only;
`elastic_client.py:153-253`: create/enable/disable, no list;
`sentinel_client.py`/`qradar_client.py`: incidents/offenses only; no
migration table (164 migrations scanned) | The only
`list_saved_searches` (`services/agents/app/api/hunt_search.py:277`) is
AiSOC's own saved hunt searches; connectors *dispatch* a saved search
(`connectors/splunk.py:211`), never enumerate them |
| WS1-3 | STILL OPEN |
`services/api/app/services/rule_tuning.py:275-318` and
`detection_tuner.py:78` (`fp_rate = len(fps)/len(decided)`) operate on
AiSOC-native `DetectionRule` only | The exact scoring machinery claimed
missing (FP rate w/ denominator, last-fired staleness, hits,
disable/suppress lanes) exists — pointed at AiSOC rules, blocked for
SIEM rules by the WS1-2 inventory absence |
| WS1-4 | STILL OPEN |
`services/api/app/services/fleet_health.py:136-229` judges `last_sync`
(poll time) vs cadence; `events_ingested` carried at `:151` but never
judged | Fleet health answers "is the pipe polling", not "is the source
speaking" — a connector polling cleanly with zero events reads HEALTHY;
nothing checks last-event-time per SIEM data source |
| WS1-5 | STILL OPEN | `packages/aisoc-migrate/` contains only
`inbound.py` + `tests/test_inbound.py`; inbound docstring (lines 2-10)
confirms direction | Federated translators
(`services/connectors/app/federated/translators/{spl,kql,esql,aql}.py`)
translate hunt *queries* outbound, not rule objects — query-level
building blocks exist, rule packaging doesn't |
| WS1-6 | STILL OPEN |
`services/api/app/models/detection_proposal.py:4-6` ("once promoted it
materialises a row in `detection_rules`"); zero `sync_detection_rule`
refs in `detection_proposals.py`/`rule_tuning.py` endpoints (rg exit 1);
`rule_tuning.py:612-626` mutates AiSOC rule rows | Governed
propose→eval→promote loop exists and ends at AiSOC's own rules table; no
path reaches a customer SIEM rule |
| WS2-1 | STILL OPEN (claim accurate) |
`services/api/clickhouse/001_init.sql:130` (`TTL … + INTERVAL 400 DAY`);
`services/api/app/services/retention.py:36` (`MAX_LAKE_DAYS = 400`);
`scripts/check_retention_window.py:79,124,205-214`;
`tiering/002_tiering.sql:21-22,31` ("held equal by
scripts/check_retention_window.py", DELETE at 400) | Gate enforces TTL ≥
`MAX_LAKE_DAYS` ≥ 400-day floor; both currently equal 400, and the
tiering DDL comment states the "held equal" coupling verbatim |
| WS2-2 | STILL OPEN | Zero `parquet` hits in production code (only gate
keyword fixtures `scripts/check_attribution.py:84`,
`check_keyword_matching.py:165`); `002_tiering.sql:25-31` | Cold tier =
ClickHouse-native parts on an S3 *volume* in the platform's storage
policy, then hard DELETE at day 400 — not open-format, not
customer-owned |
| WS2-3 | STILL OPEN | `rg -i rehydrat` → only incidental hits
(redactor, MITRE loader); after the `002_tiering.sql:31` DELETE, data is
unrecoverable | `lake_cold_query.py` queries the cold tier
*pre-deletion*; there is no archive to rehydrate from |
| WS2-4 | STILL OPEN | Zero `duckdb` hits anywhere;
`tenant_export|export_job` search empty in `services/api/app` | Nearest
thing is `audit_export.py` (compliance CSV/HTML of the audit log) — not
lake events, no manifest |
| WS2-5 | STILL OPEN |
`services/api/app/workers/retention_purge.py:204-213` ("**Why any hold
stops the whole tenant** … if anything is held, nothing in that tenant
is purged this sweep"), `:222-229` (all holds passed as subjects),
`:365,381,395` (`dry_run=dry_run or held` gates lake, alerts, audit) |
Deliberate and self-documented: bulk mutations can't evaluate
per-subject predicates without enumeration; narrowing is "recorded as
follow-up in DEPTH_PROGRESS.md" — a designed conservatism, not an
oversight |
| WS2-6 | STILL OPEN | `rg -i "object.?lock|worm|immutab"` empty in
`retention.py`/`governance.py`; all repo "attestation" hits are WebAuthn
(`tests/isolation/soft_webauthn.py`) or SBOM (`ROADMAP.md:27`) |
Adjacent but distinct: audit-log hash chain + `audit_retention_truncate`
checkpoint (`retention_purge.py:34-43`) is tamper-*evidence*, not
write-once storage; `held_*` counts are run logs, not a per-tenant
attestation artifact |
| WS2-7 | STILL OPEN (claim accurate) | `README.md:213` — "**Not a
drop-in SIEM replacement.** It correlates and investigates; it does not
replace long-term log retention and compliance search." | Verbatim as
claimed |
**Surprising adjacent findings:**
1. **One missing read method blocks three gaps at once.** The
`sync_detection_rule` contract's own `verification_gap` text
(`capability_contracts.py:590-597`) complains the clients expose "no
read of the saved definition" — the identical absence that makes WS1-2
(inventory) and WS1-3 (health attribution) impossible. Adding
list/get-rule methods to the four vendor clients unlocks the inventory,
outcome attribution, *and* the verification probe in one move.
2. **The outbound-translation corpus already exists in-tree:**
`detections/splunk-imports/_quarantine/` holds 2,006 files (the 2,005
quarantined SPL rules inbound.py's docstring names, plus an index) — a
ready-made round-trip test corpus for WS1-5's missing `outbound.py`.
3. **A live incident is memorialized in `siem.py:50-60`:** the dry-run
credential-strip list once disagreed with the client factories'
read-sets, and "a connector-configured tenant previewing an action
reached the real Splunk." It's fixed and pinned by
`tests/test_dry_run_credential_strip.py`, which re-derives the read-set
from source — anyone closing WS1-1 by adding a real Splunk path must
extend that factory knowing the strip test will enforce the new keys.
4. **Fleet health carries the signal it doesn't use:** `events_ingested`
is already written per connector (`connector_repo.py:328`) and carried
in every `ConnectorHealth` (`fleet_health.py:151`) but never judged — so
a last-event-time-style silence check (WS1-4) has half its plumbing in
place, though a true per-SIEM-source check still needs source-level
granularity the connector row doesn't have.
5. **WS2-5 is a documented deferral, not a bug:** the whole-tenant hold
scope was a reasoned fail-closed choice ("over-retains, which is
recoverable; the alternative under-retains, which is not") with the
narrowing explicitly parked in `DEPTH_PROGRESS.md` — a closure PR should
engage that rationale (per-subject enumeration before the bulk mutation)
rather than just flipping the predicate.
I've confirmed the 2,006 files under `_quarantine`, which lines up with
the docstring's claim of 2,005 quarantined SPL rules plus an index.
Everything checks out, so I'm assembling the final table now. All 13
claims are still open; two of them are accurate premises rather than
gaps, and several others carry adjacent examples I need to keep
separate.
I'm now writing up the final report: a compact table of the claims, plus
a section on the surprises.
Verification complete. HEAD is
`71360e1eb3f509452c5db7c6e2fd1370e0676fab` on
`chore/gap-closure-phase0`, and all 13 claims are STILL OPEN — the full
table with file:line evidence is above. The most useful nuances for
whoever executes the closure: the scoring/proposal machinery the WS1
claims want already exists for AiSOC-native rules and just has no
SIEM-facing counterpart, a single vendor-client rule-read surface would
unblock WS1-2, WS1-3 and the verification probe together, and the WS2-5
whole-tenant hold is a reasoned, in-code-documented deferral whose fix
should address the per-subject enumeration problem its docstring raises.
</details>
<details><summary><b>Verification table — WS3 + WS4</b></summary>
Verification complete — all ten claims checked against code at
`71360e1eb3f509452c5db7c6e2fd1370e0676fab` (branch
`chore/gap-closure-phase0`, the v23.6.1 release commit). All searches
were run with `rg` inside `/tmp/aisoc-gap0`; one caution on my own
process: three searches accidentally engaged rg's `-r` replace flag via
a `-rni` flag cluster, mangling displayed match text — each affected
search was re-run cleanly before citing.
**Verdict: 7 STILL OPEN, 2 PARTIALLY CLOSED, 1 STILL
OPEN-as-claimed-verbatim.** No claim is ALREADY CLOSED. Paths below are
relative to `/tmp/aisoc-gap0`.
| Claim | Verdict | Evidence (file:line) | Note |
|---|---|---|---|
| WS3-1 | **STILL OPEN** |
`services/api/app/services/phishing/intake.py:54` (`INTAKE_SOURCES =
{manual, m365_graph, google_workspace, email_inbox}`, enforced :143);
`services/api/app/workers/phishing_report_intake.py:79-84`
(`MAILBOX_CONNECTORS` = m365_audit/azure_entra/google_workspace only) |
Proofpoint/Mimecast/Abnormal/Sublime/azure_defender have only
`fetch_alerts→normalize→ingest`; even the
`microsoft-defender-email.yaml` template maps to OCSF Security Finding
2001, never intake. |
| WS3-2 | **STILL OPEN** |
`services/api/migrations/111_phishing_campaigns.sql:136-161` —
recipients table columns are recipient, message id, `purge_state` CHECK
(`not_attempted/simulated/pending_approval/purged/not_found/failed/restored`),
restore handles | It's explicitly a *purge ledger*; no
delivered/clicked/credential-submitted/replied/forwarded columns.
`could_not_check` exists only for IOC providers
(`analysis.py:200,235,258`), not recipients. |
| WS3-3 | **PARTIALLY CLOSED** | Exists: `reply_to_redirect`
`services/api/app/services/phishing/headers.py:284-293`,
`display_name_impersonation` :303. Missing:
`services/fusion/app/services/first_seen.py:80-91` (`TRACKED_ATTRIBUTES`
has no sender→recipient), :12-17,62 (domain age deliberately refused);
zero hits for lookalike/VIP-list | Reply-to mismatch is real and
offline-safe; first-seen pairs, lookalike-vs-tenant-domains/VIP, and
domain age are absent — domain age is a *recorded refusal* (observation
age ≠ registration age), not an oversight. |
| WS3-4 | **STILL OPEN** | `reported_by` stored (`intake.py:124`,
`endpoints/phishing.py:506-531`, worker:180-197); only "notify the
reporter" mention is a prose step string in
`services/api/app/services/tenant_provision/templates.py:190` |
Starter-playbook steps are strings "a runbook UI can render", not
executable; no feedback/notify machinery reads `reported_by`. |
| WS3-5 | **STILL OPEN** (consciously recorded) |
`services/actions/app/live_actions/capability_contracts.py:793-808` —
contract note: "Per-mailbox, not tenant-wide — neither vendor exposes
its organisation-level block list through the API this platform speaks";
`builtins.py:1066-1074` (M365 inbox rule), :1115-1123 (Gmail filter) |
Full 66-verb vocabulary has no gateway/org blocklist verb under any name
(checked tenantAllowBlock/blocklist/blocked_senders). |
| WS4-1 | **STILL OPEN** | No DLP model in `services/api/app/models/`
(listed); `services/connectors/app/connectors/netskope.py:100-120`
flattens policy/app/action into a description string; only structured
DLP field anywhere is
`services/ingest/internal/normalizer/templates/agentmetry.yaml:77`
(`dlp.rule_id`) | The per-source template *mechanism* exists in the
ingest normalizer, but no DLP finding shape (data classes, hash/size,
channel, destination, enforcement, device) rides it. |
| WS4-2 | **STILL OPEN** (verbatim as claimed) |
`services/connectors/app/connectors/m365_audit.py:20-22` ("re-enabled
per-instance **later** via connector_config once the analyst opt-in path
lands"), :43-49 hard-coded `_DEFAULT_CONTENT_TYPES`, :187 and :233
iterate the constant | No `self.config`/`connector_config` read exists
anywhere in the connector body — `connector_config` appears only in the
docstring. |
| WS4-3 | **STILL OPEN** |
`services/agents/app/investigator/strategies.py:107-367` — ten ids
(endpoint-suspicious-process … generic-triage); "dlp" appears once, as a
keyword on `data-exfiltration` (:309) | Zero matches for
business-justification/data-handling/insider/departing; a DLP alert
routes to the generic exfil strategy by keyword. |
| WS4-4 | **PARTIALLY CLOSED** | Exists: scheduled HR sync
`services/connectors/app/scheduler.py:700-708` (built so "a termination
that happened on Friday" no longer waits on manual upload);
`departing_soon`/`departed` prompt facts, `DEPARTING_WITHIN_DAYS=30`
(`services/agents/app/context/identity.py:216,262-264`); manual
watchlist (`models/insider_threat.py:30-34`, PATCH
`endpoints/insider_threat.py:142-156`). Missing: only `is_watchlisted`
writer is the human PATCH; no expiry column; fusion has zero
workforce/risk_profile references; no HR-triggered hunt
(`retro_hunt_consumer.py` is threat-intel-only) | HR plumbing (BambooHR,
Rippling → `workforce_members`) and the watchlist model both exist; the
automation chain (auto time-boxed watchlist → sensitivity → lookback
hunt) does not. |
| WS4-5 | **STILL OPEN** | Full capability sweep of
`services/actions/app/live_actions/*.py`: 66 verbs, none
sharing-related; `vendor_breadth.py` vendors are EDR/identity/network;
`remove_workspace_member` is AI-workspace membership
(`capability_contracts.py:1305-1313`); no share/collab member in
`models/action.py` | No Drive/OneDrive/SharePoint/Box/Dropbox vendor arm
exists at all in live_actions. |
**Adjacent findings worth knowing:**
- **Box and Dropbox connectors already exist read-side**
(`services/connectors/app/connectors/box.py:1-8` ingests admin logs
*including file shares and collaborator changes*; `dropbox.py:1-6` the
team event log ditto) — so WS4-5 is the classic exists-unwired
half-pair: the detection surface for sharing abuse is live with no
matching response verb.
- **Two of the gaps are self-documented in shipped code**: the
`block_sender` contract note names the org-level limitation and its
reason (WS3-5), and the m365_audit docstring names the DLP opt-in as
pending (WS4-2). These were known deferrals, not oversights — closing
them means landing the invited path, not discovering it.
- **An insider-threat module already exists** (`user_risk_profiles` with
`data_staging_score`, peer groups, indicators, watchlist) — WS4-4 work
should extend it, not re-specify it; same for the workforce pipeline
(migration 131 tables, `fetch_workforce` capability on the connector
base).
- **Domain-age detection rules exist in the corpus but are deliberately
unreachable** — `first_seen.py` records why (a first-seen store must not
impersonate registry age), and a negative fixture
(`detections/fixtures/negative/net-dns-newly-registered-domain.json`)
pins it. Any WS3-3 domain-age work must come from a registry source, or
that recorded refusal gets violated.
- The phishing recipients table already feeds `scaled_impact` via
`recipient_count` (`campaigns.py:31`), so adding per-recipient
interaction columns would land on a table that approval-impact grading
already reads — a schema change there touches action governance, not
just reporting.
I've gathered all the evidence, so I'm now writing up the final verdict
table, starting with the phishing workstream. The intake allowlist and
the worker's mailbox connector list are the key points, and the vendor
connectors are still being checked.
Now I'm checking the vendor connectors, which only fetch, normalize and
ingest alerts, with the Defender email template mapping to an ordinary
alert finding and no intake references anywhere. Next is the campaign
recipients ledger, which tracks purge states and restore handles but
nothing about delivery, clicks or replies. The header checks for
reply-to redirects and display-name impersonation exist, but there's
still no sender-to-recipient first-seen baseline or lookalike-domain
list to compare against.
I'm now going through the remaining items in the verdict table: the
reporter notification gap, where the reporter is captured but nothing
sends feedback, and the sender-blocking item, which only works per
mailbox with no tenant-wide gateway verb. Next up is the DLP/insider
workstream.
Now I'm checking the DLP workstream, and there's no DLP model or
migration table in the API models, so that one is still open. Netskope's
normalizer flattens policy and action details into a plain description
string, and the only structured DLP field mapping is for the AI gateway,
so the per-source template mechanism has no DLP finding shape to work
with.
I'm checking the DLP connector's default content types, which are
hard-coded to skip DLP by default with no config read anywhere in the
body. Then I'm looking at the ten strategy IDs for DLP and insider-risk
coverage, where there's no business-justification or data-handling
strategy, and "dlp" only routes to data-exfiltration. The keyword search
for insider, departing, and related terms came back empty.
Now I'm checking the insider-risk piece, where HR sync and
departing-soon facts exist and a manual watchlist can be set through an
endpoint, but nothing automatically adds anyone to the watchlist yet.
Now I'm checking whether anything can time-box or expire a watchlist
entry, and nothing in the model has an expiry column. I also see that
fusion never reads workforce or risk-profile data, so detection
sensitivity stays unchanged. Last, the retro-hunt and hunt-scheduler
paths only cover threat-intel IOCs and have no HR trigger.
Next I'm looking at the surprises adjacent to the verdict table,
starting with the Box and Dropbox connectors, which already read
file-sharing events on the detection side but have no matching response
verb to act on them.
Now I'm looking at the surprises near the verdict table, starting with
the insider-risk side, where the HR pipeline already runs on a schedule,
so the missing piece is acting on it rather than collecting the data.
The domain-age rules exist but are deliberately unreachable, and the
existing insider_threat module should be extended rather than rebuilt.
I'm noting that the rg `-r` replace flag mangled some search output when
I bundled it into flag clusters, so I re-ran those searches cleanly and
the cited evidence comes from the clean runs. I'm also planning to state
in the table that paths are relative to /tmp/aisoc-gap0.
</details>
<details><summary><b>Verification table — WS5 + WS6</b></summary>
# Gap verification — WS5 + WS6 @
|
||
|
|
0553d9aebf |
fix(pipeline): sink-rejection durability, dead Zscaler feed, realtime consumer teardown (#1996)
## Data-pipeline integrity wave A full review of the data pipelines and integrations: 96-hour soak-log harvest from a live stack, live reproduction of each finding, vendor-contract verification, and an end-to-end ingest → fusion → alert → AI-triage pass. Three product defects found and fixed. ### 1. Threat-intel: a sink that refuses documents had them marked as stored (permanent per-sink gap) `async_bulk(raise_on_error=False)` reports per-item rejections by **returning** them, so a disk flood-stage 429 (`cluster_block_exception`) came back through the no-exception path, the pipeline recorded per-sink dedup keys for documents OpenSearch had **refused**, and every later poll read them as duplicates. Reproduced live: the KEV corpus in Qdrant and Neo4j, **zero documents in `threatintel-iocs`, permanently** — the index `match_ioc_values` (actor attribution) reads. The warning log said only "4 bulk errors", hiding the one string an operator needed. Fix: `bulk_index_iocs` returns a `BulkIndexOutcome` naming rejected ids + vendor reasons (now logged); the pipeline withholds exactly the refused documents from its dedup record so they re-offer next poll (idempotent upserts — re-requests, never duplicates). This completes the #1278 backfill for the rejected-not-unreachable failure mode. Tests: `test_pipeline_sink_rejection.py` (4) — re-offer of exactly the refused docs, wholesale-block backfill after the block clears, dedup positive control, outcome extraction with reasons. Suite cannot pass pre-fix. ### 2. Zscaler connector: polling a route the vendor does not serve (never returned an event anywhere) `fetch_alerts` POSTed `startTime/endTime/pageSize` to `/api/v1/webApplicationRules` — in Zscaler's published API that's Cloud App Control **policy CRUD** (routes are `GET|POST /webApplicationRules/{rule_type}`; the POST *creates a rule*), so the request matched no route. Independently, `_obfuscate_api_key` skipped the published algorithm's first loop and the `+2` offset — **authentication could never have succeeded either**. ZIA has no pull API for web logs (NSS push only). Fix: rewritten against the one pull feed ZIA documents — the **admin audit log report** (`POST /auditlogEntryReport` → poll `statusId` to `COMPLETE` → download CSV): event-time cursor + one-interval overlap (#1970/#1971), continuation across the vendor's 1,000-record report cap (announced when the bound binds), stable digest ids for id-less rows, admin-timezone timestamps parsed to UTC where unambiguous (unparseable keeps the row), **no invented severity** (audit entries publish none — the Sophos rule). Paging debt ceiling falls **48 → 47**; checkpoint-adopter registry records zscaler. Docs regenerated from the schema. Tests: `test_zscaler.py` (12) — obfuscation against an independently-written reference, CSV preamble/timezone/id parsing, full report flow, 401-reauth-once, ERRORED with vendor reason, page continuation, nothing touches `webApplicationRules`, schema honesty. ### 3. Realtime: crashed Kafka consumers leaked (16 instances over the soak) The supervisor reattached after kafkajs crashes (offset-manager `TypeError`, fetch timeouts) but never disconnected the crashed instance — each crash leaked a consumer's sockets and timers for the process lifetime. Starters now return the consumer handle; the supervisor tears it down best-effort before replacing it (and tolerates the disabled-by-config starter). Type-check + 41 realtime tests green. ### Live E2E evidence (current images) - ingest accept → fusion alert row: **1.6 s**; auto-triage verdict `true_positive` @0.8 on the local model (1,235/126 tokens, 31 s CPU), below the 0.85 default-deny threshold → escalated, ledger-persisted. - Console read path: login → alert envelope (narrative, 5 entities, status `triaged`). Dead-letters: 0/24 h. - Enrichment auth: garbage bearer → **401**; authenticated → 200 honest-empty (no provider keys). One deployment finding, no code change: a QA stack ran a **mixed-version fleet** (enrichment/ueba on v21.0.0 `:latest` pulled pre-GHSA-qf6m, rest v23.5.0) — on the stale image the enrichment auth of GHSA-qf6m is absent. Current images verified correct; the stack was refreshed to v23.6.1. `make upgrade` (which pulls) prevents this; a bare `up` after a partial pull does not. |
||
|
|
2bf19641fa |
docs: restore backticks around the huntress subdomain placeholder (#1963)
## What Restores the multi-token MDX placeholder escape in `scripts/generate_connector_docs.py` (with the docstring that records why it exists) and regenerates `apps/docs/docs/connectors/huntress.md` — two files, ten lines. ## Why [#1961](https://github.com/beenuar/AiSOC/pull/1961) regressed `_mdx_safe` to the single-token placeholder pattern and deleted the comment warning against exactly that: `<your subdomain>` parses in MDX as an unclosed JSX tag (`your` with a boolean `subdomain` attribute), and this precise Huntress help text once broke the docs deploy for six days. The regenerated page shipped without backticks, and **Deploy Docs to GitHub Pages failed on the merge commit** ([run 44238855720](https://github.com/beenuar/AiSOC/actions/runs/44238855720), `end-tag-mismatch`, line 22). The Docusaurus build only runs on push to `main`, so #1961's 129 green checks never exercised it; the connector-docs gate *did* catch the first draft of this fix when it patched the page without the generator — the page is generated, so the fix has to be at the source. ## Verification - `python3 scripts/generate_connector_docs.py --check`: OK — 97 connectors documented; the restored generator reproduces the fixed `huntress.md` byte-for-byte (0 pages rewritten after the manual fix). - `pnpm --filter @aisoc/docs build` passes on this tree; the identical tree without the fix is the failing CI run above. - `ruff format --check` / `ruff check` green on the changed script. - A sweep of every docs file #1961 touched (fence- and inline-code-aware) found no other unbackticked angle-bracket placeholder. Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
6887191e76 |
docs(visuals): refresh README screenshots + walkthrough on a live v23.5.0 stack (#1961)
## What Every README/console image and the deployment walkthrough, re-captured against a **real v23.5.0 deployment** — images pulled from `ghcr.io`, demo mode off, nothing seeded, driven through the console's own flows. The user asked for full product visibility with a great demo and *nothing faked*; this is that, and refusing to fake it surfaced two real defects (fixed below). ### Visuals - **17 console tiles** re-shot at v23.5.0 (footer reads `v23.5.0`), plus two new ones for this release's headline features: the **entity-risk queue** with the hosts each entity was *seen on*, and the **related-cases** panel resolving a genuinely shared alert. - **`attack-graph.png` is now a genuine full-profile capture** with Neo4j live (users/hosts/IPs/network-paths over real ingested telemetry), replacing the back-level v10.0.0 still — the honesty caveat in the guide is simply gone. - **`demo.mp4` (2 m 1 s) and `hero.gif` re-cut.** Opening card → real cold `make up` (asciinema, idle capped, password `sed`-filtered) → sign-in → sample load through the real ingest path → alert queue → **real local-model triage verdict** in the rail → entity-risk queue → KEV feed → cost dashboard → `make smoke` 10/10. All five alerts were triaged by the bundled `llama3.2:3b` through the gateway (~1,245 prompt tokens, ~25 s each on CPU), **not** the deterministic fallback the old recording showed. - Both provenance READMEs and the **technical guide** rewritten to match (KEV 1,754→1,782, catalogue 2,614→3,045, playbooks 63→64, graph caption, the `?status=open` paragraph), guide → v1.5, **PDF re-rendered** (papers digest gate green). - Screenshots palette-quantized (near-lossless on flat dark UI) and the PDF reduced from 6.5 MB → 3.1 MB, so the refresh adds **~5 MB to a clone, not ~15 MB**. ### Two real defects found while capturing (fixed here, tree-derived tests) 1. **The v23.5.0 "sixteenth secret" never reached the service that enforces it.** The actor-attribution token the release notes describe was neither generated by `ensure_env` nor delivered by compose to `threatintel` (enforcer) or `agents` (caller), so a fresh `make up` answered **503 for every `/api/v1/actors/*` call** with all secrets "correctly" generated. Now generated and wired to both ends; pinned by `tests/test_threatintel_token_wiring.py`, which discovers the readers from source and asserts compose delivers to each. 2. **`GET /cases?status=open` matched zero rows.** `open` is a write-path alias the read path string-matched literally, so the console's *add to existing case* picker always showed an empty list and the related-cases path was unreachable. The alias now expands to `case_status.OPEN_STATUSES`; pinned by `services/api/tests/test_cases_open_alias.py`. ## Provenance / honesty Captured on 2026-11-18 from a v23.5.0 stack carrying the two fixes above. Demo mode off, no hosted provider ever configured, the two cases created through the console's escalate flow and their relationship resolved from a real shared alert. Every claim in the screenshot captions was checked against the pixels. No secrets or machine paths in the tree (swept). ## Verification - `tests/test_threatintel_token_wiring.py` (3) + `services/api/tests/test_cases_open_alias.py` (2) pass; `test_cases_tenant_isolation.py` still green. - `render_white_paper.py --check`, `readme_gates.py`, `check_competitor_names.py`, `check_attribution.py --all` all green locally. - Live end-to-end: fresh `make up` → wizard sample load → 5/5 alerts triaged by the local model → `make smoke` 10/10; `make up-full` → Neo4j populated (1,782 IOCs + users/hosts/IPs) → graph renders. --------- Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
c123ad6312 |
fix(docs): escape the raw placeholder that broke every docs deploy since Nov 12 (#1960)
## What One character class, six days of silent breakage: the Huntress setup table's `api_secret` cell says the secret is "Generated with the API key at <your subdomain>.huntress.io" — and MDX parses a bare angle-bracket placeholder in prose as an unclosed JSX tag (`Expected a closing tag for \`<your>\``), which fails the whole Docusaurus build. **Deploy Docs to GitHub Pages has failed on every push to main since the connector landed** — last green deploy 2026-11-12 (`468abb5b9`), 15 consecutive failures since — so the live portal is frozen on pre-v23.4.0 content. The v23.4.0 and v23.5.0 docs, including the three new connector pages (ESET PROTECT, WithSecure Elements, Vectra AI Platform), never published. Per-PR CI never caught it because the Docusaurus build only runs in the deploy workflow, on push to main. ## Fix Backtick-wrap the hostname so it is a code span, which MDX does not parse. One line. ## Verification Ran the deploy job's own command locally from this tree: `pnpm build` in `apps/docs` compiles both bundles and generates static files (`[SUCCESS] Generated static files`). The build walks every doc, so this also confirms huntress.md was the tree's only prose-context raw tag — a strip-fences-and-code-spans scan over `apps/docs` agreed (every other candidate sits inside a fence or a multi-line code span, in files older than the breakage window). |
||
|
|
6a0ba4cff0 |
chore(security): time-boxed ignore for picomatch GHSA-fc5q-39xc-vjpf — no patch exists
ReDoS via repeated extglobs, vulnerable range <= 4.0.7 with first_patched null: there is no version to float to. Every consumer in this lockfile is build/test/lint tooling whose glob patterns are repo-authored; none ships in a runtime image. 89-day expiry forces the re-check. |
||
|
|
e6685422a5 |
fix(llm): align gateway authentication and tenant BYOK routing
Preserve CORE/Ollama defaults while resolving provider-native gateway credentials and reloading changed configuration during upgrades. Bind each tenant endpoint to its credential source across runtime consumers, probes and status, with explicit provider model guidance. Combine the related AI configuration fixes on the current upstream base. Keep demo seeding and investigation-ledger repairs outside this change. Retain real gateway, PostgreSQL, provider-HTTP and Settings browser coverage. Signed-off-by: Albert Hsieh <knowlet@pm.me> |
||
|
|
6d6300c0dc |
fix(fusion): preserve Wazuh event identity and repeat occurrences
Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com> |
||
|
|
1cdf516b70 |
fix(agents,ueba): context bundle reaches UEBA baselines — port, auth, vocabulary, wire shape (#1935)
Fixes #1929. ## What was broken Verified on current `main`, exactly as reported: `ContextBundleBuilder._fetch_baselines` could not return a baseline on **any** deployment, and the failure was a per-entity `debug` log nobody sees. Four independent defects — fixing any one alone still returns nothing: 1. **Wrong port.** Default `http://ueba:8086`; UEBA listens on **8004** (compose publishes `8007:8004`). 2. **No service auth.** Bare `httpx` client against a router that fails closed (`require_service_auth` + tenant assertion). 3. **Vocabulary mismatch.** The bundle queried `entity_type=host`/`email`; UEBA stores hosts as `device` and has no `email` kind. 4. **Wire-shape mismatch + truncation.** The reader used `baseline_features`/`window_days`/`deviation_score` — fields `BaselineOut` has never had — and fetched the newest 50 rows to filter client-side, so entities outside that page were unreachable. ## The fix - Default URL `http://ueba:8004`; compose sets `AISOC_UEBA_URL` on `agents` explicitly (Helm deployments set the same variable; the chart carries no agents-specific env block to wire it into). - Calls present `AISOC_UEBA_SERVICE_TOKEN` (then `AISOC_SERVICE_TOKEN`) + `X-AiSOC-Tenant-ID` — the client-side mirror of UEBA's `resolve_token()`, same pattern as `tools/enrichment.service_headers`. Per the report: the caller must present *UEBA's* token, not its own `AISOC_AGENTS_SERVICE_TOKEN`. - `host`→`device`; `email` is **not queried** rather than queried-and-never-matched. - Wire mapping reads `feature_stats` (`{feature: {mean,std,count}}` → `{feature: mean}`) and derives the window from `window_start`/`window_end`. `deviation_score` is read from the entity's newest `/anomalies` row (24h default window) with an honest `not computed` note when that lookup fails — a baseline describes the norm and carries no deviation, so inventing one from it was never an option. - UEBA `GET /baselines` gains a server-side `entity_id` filter (additive; the bundle still client-matches for compatibility with older UEBA versions that ignore the parameter), and `BaselineOut` exposes `peer_group_id` (the ORM column existed all along). - A permanently broken UEBA source logs **one warning per process** ("check AISOC_UEBA_URL and the service token"); later failures stay at `debug`. On a core-profile deployment (no UEBA service) that one warning is the honest state. ## Verification - 11 new agents tests (`test_ueba_baseline_fetch.py`): token preference order, tenant header, vocabulary map, wire mapping incl. sparse rows, compose↔code default parity, and end-to-end against a mock transport that behaves like the real router (fails closed without the credential, filters `entity_id` server-side). The e2e asserts the request went to **port 8004** with `entity_type=device`, `entity_id`, `limit=1` and both headers. - 4 new UEBA route tests (`test_baselines_entity_filter.py`): predicate present/absent, `peer_group_id` carried and defaulted. **Negative control: all 4 fail against the pre-fix `routes.py`** (no such parameter). The agents suite cannot pass against the pre-fix `bundle.py` (the helpers it pins don't exist; behaviorally, the mock UEBA 401s the credential-less client the old code was). - Full UEBA suite: 131 passed. Agents context suites (`test_context_bundle`, `test_bundle_incident_context`): 35 passed. Ruff clean, changelog gate green. Thanks @relains — the reproduction table in the report (connection-refused → 401 → 403 → wrong-type-zero-rows) made this a straight walk. Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
c68dbabd51 |
fix(cases): comments accept the console's payload, failed writes roll back, resolution persists (#1933)
Fixes #1932. ## What was broken Reported in #1932 against v23.4.0 and verified on current `main`: 1. **Every comment post 422'd, and the UI claimed it saved.** `casesApi.addComment` sent `{"comment": ...}`; `AddCommentRequest` declares only `body`. The workspace had already inserted the comment optimistically, and the `catch` showed *"Saved locally (writes disabled in demo)"* on **every** deployment — so on a real install the analyst's note silently vanished on reload. 2. **The Resolution panel had no save path at all.** A `defaultValue`-only textarea; no client call, no `UpdateCaseRequest` field, no `resolution` in the response — although `aisoc_cases.resolution` has existed since migration 046 and the console's `Case` type already declares it. ## The fix - `AddCommentRequest.body` accepts both wire names via `AliasChoices("body", "comment")` — `body` canonical, `comment` kept so deployed consoles work against a new API. `min_length=1` still enforced through the alias. - The console now sends `body`, which works against old and new API versions alike. - `CaseWorkspace` comment/task failure handling: on a non-demo deployment the optimistic entry is rolled back, the composer text is restored, and a real error toast names the failure. The demo path (`canUseDemoData()`) keeps its honest "saved locally" copy. - Resolution end to end: `PATCH /api/v1/cases/{id}` accepts `resolution` (empty string = deliberate clear), `CaseResponse`/`_row_to_case` return it, and the panel is a controlled textarea with a Save button (dirty-tracking, saving state). - `docs/openapi.yaml` regenerated — additive only (two nullable string properties), no breaking change. ## Verification - 9 new contract tests in `services/api/tests/test_case_comment_resolution_contract.py` (alias both names, alias does not relax validation, PATCH persists/clears/omits resolution, response mapping incl. explicit-column-list rows). - **Negative control:** with the original `cases.py` restored, 5 of 9 fail (alias + all resolution tests); with the fix, 9/9 pass. - Adjacent suites green locally: `test_cases_tenant_isolation`, `test_cases_authorization`, `test_case_summary`, `test_case_postmortem`, `test_case_reopen` — 80 passed, 8 skipped. - `scripts/export_openapi.py --check` passes; `check_changelog_frozen` passes; ruff clean. Thanks @relains for the precise report — the `AliasChoices` workaround you run is exactly what shipped, plus the client-side half and the rollback contract. Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
d2c0c78887 |
fix(security): fail closed on demo-tenant seeding and threat-intel actor gate (SEC-2/SEC-15/NC-7)
Same fix as #1899, landed for the fra-hq-soc-01 deployment so the running containers can actually carry it: the product images bake app code at build time (no bind mounts), so until this lands on master the live threatintel service stays open despite #1899. Tests: 11 passed (api env-gate), 7 passed (threatintel auth). |
||
|
|
f4a40b1f95 |
feat(fusion): /metrics/prometheus — same figures, exposition format (#1893)
## Summary Closes the remaining half of #1881: the `aisoc-fusion` scrape job had read the JSON `/metrics` since the job was written and **never recorded a sample**, because JSON is not exposition format. Deleting the job (the declined #1876's approach) would have silenced the failure and lost the signal; this gives Prometheus something it can parse. ## Mechanism `GET /metrics/prometheus` reads the **same sources** as the JSON endpoint — `get_metrics()` consumer counters, `consumer_lag()`, `pending_notifications()` (per-tenant labels), `lake.metrics()` + `archive_degraded` — so the two cannot drift, and renders text format. Collectors are sync and two sources are async, so the route awaits everything first and registers a one-shot snapshot collector on a **fresh registry per scrape**; that is also what keeps the honest-absence rule intact across the format change: a source answering `None` has no sample that scrape (never a zero), and an outage cannot linger as a stale gauge from an earlier scrape. Cumulative counts render as counters, spool/backlog levels as gauges. Unauthenticated like the JSON route (a scaler scrapes); JSON `/metrics` keeps its callers unchanged. ## Verification - Tests drive the real route over ASGI and parse the output with `prometheus_client`'s own text parser (4/4): figures present with the right types and labels; `None` lag/journal absent not zero; no worker → empty-but-valid scrape; degraded archive reports 1. - `promtool check config --syntax-only` on the retargeted scrape config: SUCCESS. - Route-duplicates gate: OK (23 fusion routes, no pair twice). Fusion already depends on `prometheus-client ^0.19`. With this and #1887, every job in the bundled Prometheus points at an endpoint that answers in a parseable format with working credentials. --------- Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
71eeba4076 |
fix(telemetry): stop ueba/honeytokens/purple-team tracing from targeting their own containers (#1848) (#1851)
## Summary Fixes **#1848**: `ueba`, `honeytokens` and `purple-team` built their OTLP span exporter inline in `main.py` against `settings.otel_endpoint`, whose default `http://localhost:4317` is — inside a container — the service itself. Tracing from these three could never reach the collector (`otel-collector:4317`, behind the compose `monitoring` profile), and because UEBA emits spans continuously, its batch processor retried the refused connection every few seconds — hundreds of export-failure log lines over a few hours on a stand without the profile. ## Changes - The three services share a guarded `app/core/telemetry.py` — the `api`/`agents` pattern, held byte-identical by a new `scripts/sync_vendored_telemetry.py --check` wired into CI beside its fifteen `sync_vendored_*` siblings ("three copies that can drift silently are worse than one copy plus a gate"). - **Quiet by default**: `OTEL_EXPORTER` defaults to `none` for these three — deliberately diverging from `api`/`agents` (default `otlp`), because they emit spans continuously and a missing collector must cost one startup log line, not a retry loop. The line names the variable that turns tracing on. - `OTEL_EXPORTER=otlp` targets `OTEL_EXPORTER_OTLP_ENDPOINT` (default `http://otel-collector:4317` — the compose service, never localhost), matching the OpenTelemetry convention `api`/`agents` already use. `console` and unknown values behave as in the canonical module (stdout / disabled-with-a-named-reason). - `docker-compose.yml` passes both knobs through on all three services, with the comment pointing at the `monitoring` profile. - The dead `otel_endpoint` config field is removed from all three configs, with a test pinning that it stays gone — it was the defect, not a knob. (Behavioural note: a deployment that set `OTEL_ENDPOINT`/`UEBA_OTEL_ENDPOINT` should now set `OTEL_EXPORTER=otlp` + `OTEL_EXPORTER_OTLP_ENDPOINT`.) ## Tests - `tests/test_telemetry_guard.py` in each service: disabled by default (no retry loop), default endpoint is the compose collector and never localhost, operator endpoint honoured, unknown exporter disables rather than guesses, and the localhost config field cannot come back. - Full suites: ueba **127 passed**, honeytokens **101 passed / 6 skipped**, purple-team **119 passed**. `sync_vendored_telemetry.py --check` OK, mypy baseline OK, ruff clean, `docker compose config` parses. ## Credit Reported by **@43n51c** (#1848) with the measured repro (~920 export-failure lines over 4h) and the fix sketch this follows. |
||
|
|
3a853d16b0 |
fix(enrichment): authenticate /enrich callers and key the limiter on the credential (GHSA-qf6m-hgwv-65f9) (#1844)
## Summary Fixes **GHSA-qf6m-hgwv-65f9** (medium): the Go enrichment service's `POST /enrich` and `/enrich/bulk` authenticated nobody, and two console Next rewrites (`/api/v1/enrichment/lookup`, `/api/v1/enrichment/bulk`) made them same-origin reachable from any browser that could reach the console. An unauthenticated client could run enrichment lookups, receive threat-intel results, and spend the deployment's provider quota (VirusTotal, AbuseIPDB, GreyNoise, …) — and because the rate limiter was keyed on the request body's `tenant_id`, rotating that string minted a fresh token bucket per request, so the limiter limited nothing. ## Changes **Service-side (the boundary fix):** - New `services/enrichment/internal/tenantauth` — a behaviour-identical Go port of the contract the Python services vendor in `app/security/tenant_scope.py`: - console HS256 access tokens (alg pinned to HS256, `type == "access"`, expiry with 30s skew, `tenant_id` claim required; placeholder secrets from `INSECURE_SECRET_KEY_DEFAULTS` count as unset), - or the service token (`AISOC_ENRICHMENT_SERVICE_TOKEN`, then `AISOC_SERVICE_TOKEN`; constant-time compare) with the acting tenant declared on `X-AiSOC-Tenant-ID` — an absent tenant is an empty scope, never every scope, - fail-closed 503 when neither is configured, with the same three-condition dev bypass as the Python module (`AISOC_DEV_MODE` + `AISOC_DEV_AUTH_BYPASS` + loopback-only `AISOC_PUBLISHED_BIND_ADDRS`). - `/enrich` and `/enrich/bulk` sit behind the middleware (`/health` stays open for the compose healthcheck). The rate limiter and cache are keyed on the **authenticated** tenant; a body naming any other tenant — or an arbitrary bucket-minting string like `"probe-a"` — is refused (403 on the single route, a named per-item error in bulk). **Console-side (closing the public door):** - The two rewrites are removed. Nothing in the console calls them — `threatIntelApi.lookup` reads the tenant's own threat-intel store — and `ENRICHMENT_URL` leaves `resolve-runtime-routes.mjs`'s operator-intent list so setting it is not treated as something the resolver can satisfy. **Callers (the paths that must keep working):** - Fusion's fuse-time `AlertEnricher`, the investigator's `enrich_ioc`, the playbook `enrich` step, and the context bundle's threat-intel fetch now present the service token and declare the run's/alert's own tenant on the platform header. - Compose wires `SECRET_KEY`, `AISOC_DEV_MODE` and `AISOC_PUBLISHED_BIND_ADDRS` into the enrichment service (it already had `AISOC_SERVICE_TOKEN`), and the dev overlay grants it the same deliberate bypass as the Python services. ## Tests - `internal/tenantauth/tenantauth_test.go`: fail-closed with nothing configured; all three dev-bypass conditions individually; valid console token resolves tenant+role; expired / refresh-type / no-tenant / wrong-signature / alg-none tokens refused; placeholder secret counts as unset; service token without header 403, non-UUID header 400, declared tenant resolves delegated; per-service override wins; `Covers` is intersection-only. - `internal/handler/handler_auth_test.go` + updated `handler_ratelimit_test.go`: handlers refuse with no principal; body cannot name another tenant; bulk items scoped individually with a named per-item refusal; **rotating the body tenant does not mint buckets** (the advisory's limiter PoC, inverted); per-tenant budgets still per-tenant; nil limiter still grants. - Python callers: fusion `test_alert_enricher.py` asserts the service call carries the token and the alert's tenant header; agents `test_playbook_enrich_target.py` asserts the same for the playbook step. - Full suites: enrichment `go test ./...` ok, `go vet` + `gofmt` clean; fusion **1229 passed**; agents **2599 passed, 219 subtests**; ruff clean. ## Disclosure Reported by **@naroSEC** via a repository security advisory with a reproduction against the `full` profile. The advisory will be published with credit once this lands in a release. |
||
|
|
4d8790e214 |
chore(release): v23.2.0 (#1840)
Cuts **v23.2.0** — the community-capability release. Everything in it merged to `main` since the v23.1.0 tag; this PR is the release surfaces plus two honesty fixes found while cutting it. ## Release content (already on main) - **Sophos Central connector** (#1834, @officialasishkumar), **console connector editing** (#1836 carrying #1833, same contributor, closes #1832), **Shodan/URLScan/IPInfo enrichers** (#1835 carrying #1831, @43n51c). - Paging-to-the-end-of-the-window fixes for Cortex XDR/XSIAM (#1815), Trend Vision One (#1816 carrying #1814) and the Wazuh indexer (#1825, reported in #1820 by @pitimon). - Copilot grounding (#1828 carrying #1819, @knowlet), session renewal (#1818), tab deep links (#1817), `METRICS_TOKEN` passthrough (#1823, closes #1822), `error_count` semantics (#1824, closes #1821), Agentmetry context (#1826, @blitzcrieg1), changelog-freeze gate (#1827), node-forge floor (#1829), session-check hardening (#1830). ## What this PR changes - **CHANGELOG**: `[Unreleased]` promoted to `[23.2.0] - 2026-11-11`; five entries added for merged work that had none (enrichers, copilot grounding, Agentmetry, node-forge, session-check script). - **Freeze-gate fix**: `check_changelog_frozen.py` failed its own release PR by design — the promoted section's tag cannot exist until after the merge. The newest section, only when it equals `VERSION` and only until its tag exists, now reports an explicit `PENDING` state; every other untagged section stays fatal, and the moment the tag exists the section is compared like any other. Four new tests pin each bound; self-test extended to ten cases. - **Honest plugin floor**: the Sophos manifest claimed `min_aisoc_version: "23.1.0"`, an artifact that does not contain the connector — corrected to `23.2.0`, marketplace mirrors re-synced. - **Surfaces**: `VERSION` 23.2.0, web `package.json`, chart `7.21.0` / `appVersion v23.2.0`, README badge, `RELEASES.md` TL;DR + What's new (11 defects fixed here, 50 across the last three releases, dependency advisories excluded), `docs/openapi.yaml` re-exported (version string only), `llms.txt`/`llms-full.txt` regenerated, scoreboard row re-graded live at `d1bbafa8` (0.97). After merge: tag `v23.2.0` on the merge commit; `release.yml` publishes the GitHub release from the `[23.2.0]` section and pushes images. Neither `stable` channel moves (v22 generation; a minor may not cross a major without the dispatch). |
||
|
|
8dd5a48ef1 |
fix(scripts): validate the fixture token shape in the session live check (CodeQL #1129) (#1830)
Addresses the one open code-scanning alert, [#1129](https://github.com/beenuar/AiSOC/security/code-scanning/1129) (`js/file-access-to-http`, warning/medium) on `scripts/check_session_refresh_live.mjs:50`. **What the alert sees:** fixture-file data (the expired access token) flowing into an outbound request. **What it cannot see:** that flow is the harness's negative control — the token is signed by the isolated API precisely so the live 401 can be asserted — and the destination is already pinned to loopback by an assertion on `fixture.base_url` before any request is made (file data cannot choose a non-loopback URL). **The change:** the token is now validated as a structurally well-formed JWT (three base64url segments) before any request — a genuine harness improvement (a malformed fixture fails at the door with a named reason instead of as a confusing 401-assertion three calls later), and the strongest shape constraint available for a value that must flow. **Disposition if the alert persists:** this repo has measured that inline guards and `codeql[...]` markers frequently do not satisfy this tracker (documented in `tests/isolation/test_sso_live.py` and `services/agents/app/hunt/from_report.py`). If #1129 is still open after this merges, it gets dismissed as a false positive with this reasoning on the alert — the documented disposition — rather than contorting the harness. |
||
|
|
20438b20a2 |
fix(changelog): freeze released sections to their tags; gate the drift that shipped four times (#1827)
**The defect class:** a fix PR writes its entry under an empty `[Unreleased]`, a release promotes the section, and when the PR merges after the tag, git's three-way merge anchors the entry by context — inside the released section. Main then claims a fix the tagged artifact does not contain. Four measured instances: Datadog into `[23.0.0]` (hand-corrected in #1805), Cortex and Trend into `[23.1.0]` (corrected here), and — found by running the new gate — a post-tag credit line in `[22.1.0]`. **The gate:** `scripts/check_changelog_frozen.py` compares the newest five released sections byte-for-byte against the `CHANGELOG.md` committed at each section's own tag. Mismatch prints a unified diff; an unresolvable tag is an explicit failure, not a skip; zero comparisons refuses as vacuous. `--self-test` injects drift in every direction; nine unit tests cover the parser and auditor. **Run against the pre-fix tree it exits 1 naming `[23.1.0]` and showing both drifted entries** — the gate found real drift before it ever went green, including the `[22.1.0]` instance nobody knew about. **Wiring:** unconditional workflow (no `paths:` filter — the drift lands via merges whose own diffs touch only `[Unreleased]`, so a filter would never fire), self-test before gate, and the context added to `.github/required-checks.json`. Per the documented order, branch protection gains the context **after** this merges (manifest first; a manifest briefly ahead of protection reds nothing). **The corrections, by doctrine rather than convenience:** - Cortex/Trend entries move to `[Unreleased]`, where the next release will truthfully carry them. - `[22.2.0]` and `[22.1.0]` are spliced verbatim from their tags; the `[22.1.0]` post-tag credit line relocates to `.github/CREDITS.md` (@rudycelekli keeps the credit on the surface built to stay current — released sections are frozen). - `[Unreleased]` gains this wave's reconciled entries: #1817 (tab deep links), #1823 (agents METRICS_TOKEN), #1824 (error_count reset), #1825 (Wazuh search_after), each crediting its reporter/author. - CREDITS rows: @pitimon (three high-signal reports) and @knowlet's row extended (#1817, #1818). **Local verification:** gate self-test 6/6; gate OK on the corrected tree (5 of 5 sections verified); 9/9 unit tests; ruff format clean; attribution, competitor-name and required-check-substance gates all pass locally. Merges **after** #1823/#1824/#1825 so its `[Unreleased]` entries describe merged reality. |
||
|
|
aec39e71fe |
fix(connectors): follow search_after to the end of the Wazuh window (closes #1820) (#1825)
Closes #1820. @pitimon asked the right question — deliberate exclusion or not yet reached? — and the honest answer is **neither defensible**: the gate listed wazuh among the unclassified debt ('requests a capped page and never follows a continuation'), and the docstring's deliberate-cap rationale ('drop the polling interval, not chase a single huge batch') is the exact argument this repo has rejected elsewhere, because the cut is silent and the abutting windows mean the overflow is never re-requested by anything. **The fix**: `_search` — the one executor both fetch paths share — now follows `search_after` (OpenSearch's documented continuation for sorted queries) to the end of the window, appending a `_doc` tiebreaker so equal timestamps cannot skip or repeat rows across pages. Properties, matching the paging doctrine: the opening page keeps the existing never-raise contract exactly (request error / non-200 / bad JSON → `[]` + the existing wazuh.* warnings); a failed later page **keeps what was read** (`connector.paging.next_page_*`); a full page whose last hit carries no sort values stops rather than looping on an uncontinuable read; and the 25-page bound announces itself (`page_cap_reached`) with the data-loss consequence stated. Both alert and vulnerability-findings reads page identically through the one loop. Docstrings now say what is true; the old rationale is kept as history rather than deleted. **Gate**: `MAX_UNCLASSIFIED` falls 49 → 48 and the audit now counts wazuh among the followers (43 follow, 1 reviewed, 48 unclassified — verified locally). **Tests**: 9 new transport-level cases (multi-page read with `search_after` echo verification, tiebreaker presence, short-page end, failed/transport-error later pages keeping partials, opening failure still `[]`, sortless full page stopping safely, page-cap bound, and the vulnerability path paging) plus the existing wazuh connector suite and gate tests — 46 pass locally; ruff format clean. Changelog entry lands in the consolidated changelog-integrity PR for this wave. (Branch created via the API — git-protocol pushes currently 403 on this machine while REST works.) |
||
|
|
703bbfb063 |
fix(auth): renew browser sessions before signing users out (#1818)
## Summary The browser stores a refresh token but never calls POST /api/v1/auth/refresh. The first protected 401 deletes both tokens, so the default 30-minute access expiry discards a usable seven-day refresh credential. ## Type of change - [x] Bug fix - [x] Documentation update ## Related issues None filed. ## Changes - Share refresh and one-time replay across JSON, streams, downloads and authenticated fetch callers. - Preserve method, body, headers, tenant and cancellation. Keep recoverable credentials on transient failures. - Prevent pending requests from restoring a logged-out session or replaying under a different login. - Align responder guards with shared JWT validity and refresh availability. - Restore the missing Explain proxy rewrite exposed by the route gate. - Add regression tests, real HTTP/API/PostgreSQL checks and CHANGELOG. Token lifetimes, backend security checks and dependencies are unchanged. ## Testing - [x] Unit tests added and updated - [x] Local integration tests passed - [ ] Rendered-browser manual test | Check | Local result | | --- | --- | | Web suite | 1,194 passed across 122 files | | TypeScript and production build | Passed | | ESLint | 0 errors, 95 warnings identical to base | | Live API/PostgreSQL session suite | 10 passed, 0 skipped | | Production client, real HTTP | 4 passed; base client fails; restored fix passes | | Ruff check/format and mypy baseline | Passed | | Console route/wire/auth-header gates | Passed | | Attribution, naming and whitespace gates | Passed | HTTP verification uses real API authentication and PostgreSQL, simulated browser storage/navigation, and disabled unrelated lifespan workers. It is not rendered-browser, complete-stack or operator-deployment validation. Remote CI has not run. Full root cause, design and verification details: docs/research/session-refresh.md. ## Screenshots Not applicable: session transport behavior only. ## Checklist - [x] Style, self-review and regression coverage complete - [x] Documentation and CHANGELOG updated - [x] No new lint warnings - [x] Diff checked for credentials - [x] DCO signed off ## Eval harness - [x] Not applicable: no substrate, playbook packs, detections, prompts or eval inputs changed Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com> |
||
|
|
8a06f2eb51 |
fix(connectors): follow the Trend Vision One nextLink to the end of the window (carries #1814) (#1816)
Carries #1814 by @officialasishkumar, which went conflicting after #1815 merged — the sibling collision both of this author's PR pairs hit today: both move the paging gate's falling debt ceiling and add adjacent gate tests, and fork branches cannot be rebased from this repository. Relative to #1814 as submitted: ceiling lands at **49** (his branch said 52→51, written before the Cortex pair took 50), the CHANGELOG entry's arithmetic is corrected to match, and both PRs' gate tests are kept. The connector change itself is byte-identical. **Verified locally:** claims re-checked against main before the carry (both Trend feeds read `top: 100` single-page with no `nextLink` handling); `check_connector_paging.py` OK at ceiling 49; 38 tests pass (his 179-line Trend suite + the Cortex suite + gate tests); `ruff format --check` clean. Also extends the author's CREDITS row to five collection-integrity fixes (Slack, Datadog, Duo, Cortex pair, Trend). Authorship preserved (commit author + co-author trailer). Co-authored-by: Asish Kumar <officialasishkumar@gmail.com> |
||
|
|
d81e119652 |
fix(connectors): follow the Cortex XDR and XSIAM incident offsets to the end of the window (#1815)
## Summary
`CortexXDRConnector.fetch_alerts` and
`CortexXSIAMConnector.fetch_alerts` both asked `POST
/public_api/v1/incidents/get_incidents` for `search_from: 0, search_to:
100` and stopped there. The endpoint pages by offset and returns at most
100 incidents per request. The poll window is clock-derived and
consecutive windows abut exactly, so a window holding more than 100
incidents lost the rest permanently. Both connectors now read the window
to the end through a new shared `read_offset_pages` in `_paging.py`.
## Type of change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change
## Related issues
None filed. `cortex_xdr` and `cortex_xsiam` are two of the connectors
`scripts/check_connector_paging.py` names as unclassified ("requests a
capped page and never follows a continuation").
## Changes
- **The vendor contract.** A `get_incidents` request returns the
incidents from `search_from` up to `search_to`. There is no link or
token to the next page. Palo Alto's own integration code is the
reference: `get_incidents` in
[`CoreIRApiModule`](https://github.com/demisto/content/blob/master/Packs/ApiModules/Scripts/CoreIRApiModule/CoreIRApiModule.py),
shared by its Cortex XDR and Cortex XSIAM integrations.
- It reads page *n* as `search_from = n * limit`, `search_to =
search_from + limit`.
- The [integration
definition](https://github.com/demisto/content/blob/master/Packs/CortexXDR/Integrations/CortexXDRIR/CortexXDRIR.yml)
documents the page size as "The default and maximum is 100".
- `services/connectors/app/connectors/_paging.py`: new
`read_offset_pages`, the offset counterpart of `read_linked_pages`.
- It continues from the caller's own 200 response for offset 0, so each
connector keeps how a refused opening request is reported.
- It asks for the next `page_size` rows until a page comes back short. A
short page is the end because an offset-paged list fills every page but
its last, and there is no continuation to read instead.
- It holds the same properties as the other readers: a failed later page
keeps what was read (`connector.paging.next_page_*`), and the 25-page
bound is announced when it binds (`connector.paging.page_cap_reached`).
- `services/connectors/app/connectors/cortex_xdr.py` and
`cortex_xsiam.py`:
- Both read through the new helper, with
`items_field="reply.incidents"`.
- Every page repeats the same `creation_time >= since` filter.
- Each Cortex XDR page is signed for itself, because the advanced-auth
hash covers a fresh nonce and timestamp.
- **Sort order.** Both now ask for `creation_time` ascending instead of
descending. Offset paging over a newest-first list breaks when an
incident is created mid-read: it lands at offset 0 and shifts every row
beneath the pages still to be read. Oldest-first, it joins the end of
the list.
- **Unchanged:** a refused opening request. Cortex XDR still raises, so
the scheduler records a failed poll. Cortex XSIAM still logs
`cortex_xsiam.fetch_failed` and returns nothing. Both are pinned by
tests.
- **Small behaviour change:** an unparseable opening body on Cortex XDR
is now logged as `connector.paging.first_page_unparseable` and returns
no rows, instead of raising `ValueError` out of `fetch_alerts`. This
matches the other readers.
- `scripts/check_connector_paging.py`: `read_offset_pages` joins
`_PAGING_HELPERS`, and `MAX_UNCLASSIFIED` falls from 52 to 50.
`test_paging_gate.py` pins both connectors in the paging set.
- `CHANGELOG.md`: entry under Unreleased → Fixed.
I'm sending a Trend Vision One paging fix as a separate PR. Both lower
`MAX_UNCLASSIFIED` and add a changelog entry at the same spot, so
whichever merges second needs a one-line rebase. Merged after the Trend
PR, this one goes from 51 to 49.
## Testing
- [x] Unit tests added / updated
- [ ] Integration tests pass locally
- [x] Manually tested (describe steps below)
<details>
<summary>Manual test steps</summary>
1. `services/connectors/tests/connectors/test_cortex_incident_paging.py`
drives the real `fetch_alerts` of both connectors through an
`httpx.MockTransport`. The mock serves `get_incidents` the way the
endpoint does: the rows from `search_from` to `search_to`. It covers,
for each connector:
- 250 incidents arriving in full, requested as `(0, 100)`, `(100, 200)`,
`(200, 300)`;
- every page keeping the window filter and asking for `creation_time
asc`;
- a short page ending the read;
- a window of exactly 200 ending on the empty third page without
announcing the cap;
- a 429 on page three keeping pages one and two;
- a timeout on page two keeping page one;
- a window past the cap being bounded at `DEFAULT_MAX_PAGES` and
announced once.
Then per connector: Cortex XDR signing every page with a fresh nonce on
the tenant host, Cortex XDR still raising on a refused opening request,
and Cortex XSIAM still logging it and returning nothing.
2. The new test file run against the pre-fix connectors from `main`: `13
failed, 4 passed`. The four that pass are the single short-page cases
and the two opening-refusal cases, which the old code also got right.
3. `pytest tests/connectors` in `services/connectors`, on the locked
dependency set from `scripts/service_requirements.py connectors
--locked` under Python 3.11, passes. The full `pytest tests/`: 1518
passed, 3 failed in `test_ticket_sync_loop.py`. Those 3 fail identically
on an untouched `main` checkout, because they resolve a hostname and the
machine I tested on has no DNS.
4. `python3 scripts/check_connector_paging.py` → `41 follow a
continuation, 1 reviewed, 50 unclassified` / `OK`, plus `--self-test`
OK. `python3 scripts/check_module_reachability.py` OK.
5. `ruff format --check .`, `ruff check services/ scripts/ tests/
tools/` (ruff 0.16.10), `python scripts/check_mypy_baseline.py` (no tree
got worse), `python3 scripts/check_attribution.py --all` and `python3
scripts/check_competitor_names.py`.
No live Cortex tenant was used. The contract comes from Palo Alto's own
integration code and its integration definition.
</details>
## Screenshots (if UI changes)
Not applicable.
## Checklist
- [x] My code follows the style guidelines of this project (`ruff`,
`eslint`, `gofmt`)
- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally
- [x] I have updated documentation as needed (README, CHANGELOG,
CONTRIBUTING)
- [x] My changes do not introduce new linter warnings
- [x] I have checked for sensitive data / credentials in my diff
## Eval harness (required for substrate / playbook / detection changes)
> **Required if this PR touches:** `services/agents/`,
`services/api/app/orchestrator/`,
> `playbooks/packs/`, `detections/`, `services/agents/tests/eval_data/`,
> `scripts/generate_eval_incidents.py`, `scripts/run_evals.py`, or any
prompt /
> RAG corpus / response template under those trees.
>
> Run `python3 scripts/run_evals.py --json --out /tmp/report.json`
before and
> after your change and paste both summary blocks below. Any axis that
> regresses must be called out explicitly. Playbook-touching PRs must
include
> the `playbook_completion_rate` block — orphan playbooks / templates
fail CI.
<details>
<summary><strong>Before</strong> (paste
<code>scripts/run_evals.py</code> output on base branch)</summary>
```text
Not applicable.
```
</details>
<details>
<summary><strong>After</strong> (paste <code>scripts/run_evals.py</code>
output on this branch)</summary>
```text
Not applicable.
```
</details>
- [x] Not applicable — this PR does not touch substrate, playbooks,
detections, or eval inputs
- [ ] No axis regressed
- [ ] An axis regressed; rationale and follow-up are described in the
Summary above
Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
|
||
|
|
6cb8030738 |
feat(detections): flag AI agents reading credential files, and fix the two catalogue claims that were false (#1804)
## Summary Adds the first community detection rule: an AI agent's file tool reading a credential file (`~/.ssh/id_rsa`, `~/.aws/credentials`, …) — T1552.001, which prompt-level secret scanning cannot see, because the prompt is clean and the disclosure happens on the way out (into the model context, a tool argument, or a second call). Writing it surfaced three catalogue/portability bugs, all fixed here: the `quarantine_reason` fallback asserted `enabled: false` about a rule file the builder never opened; the marketplace, corpus-stats, truth-table, llms and curation generators wrote the platform's line endings and `str(Path)` separators, so their `--check` compared text that had already translated the difference away; and `hello-hunt.md` instructed contributors to do the one thing `detection_truth_table.py --check` rejects. Regenerated: the marketplace index (three copies), the corpus stats, the detection truth table, and the llms.txt pair. The published rule counts follow: 7408 on disk, 4442 not loaded. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Documentation update - [ ] Refactor / tech debt - [ ] CI / infra change ## Related issues Nothing closed by this PR; no tracking issue existed for these bugs. - Relates to #357 (detection rule contributions wanted / community rules) — this is the first rule under `detections/community/application/`. - Relates to #978 and #898, which introduced and later widened the `quarantine_reason` / executable-split surface corrected here. ## Changes **New rule + fixtures** - `detections/community/application/ai-agent-credential-file-read.yaml` — `community-toufiqtoufiqbo-ai-agent-credential-file-read`, high, `application`, T1552.001. Matches the `ai_runtime` fields the `aisoc-ai-sdk` actually emits (`tool_name`, `resource` — both string literals in `aisoc_ai/client.py`), excludes public-key reads (`*.pub`, `authorized_keys`), and does not fire on model calls. It ships `enabled: false` with a `quarantine_reason`, because the truth-table gate refuses an enabled rule the engine never loads and nothing walks `detections/community/` into the compiled rule set. - `detections/fixtures/{positive,negative}/ai-agent-credential-file-read.json`. **Truthful `quarantine_reason`** - `scripts/build_marketplace.py` — new `_why_not_executable()`. The old fallback told every non-quarantined, non-executable row that it was "disabled in the rule file (`enabled: false`)" — a claim about a file the builder never opened, reached precisely when it had not looked. The reason now names the real cause per tier, and the rule's own `quarantine_reason` still wins when the file carries one. - `apps/docs/docs/detections/hello-hunt.md` — the tutorial said "`enabled: true` controls whether the rule runs in production. Community rules ship as `true` by default." Both halves are false: nothing loads a community rule, and `detection_truth_table.py --check` fails one that claims to be enabled. It now says what the gate enforces — `enabled: false` plus a `quarantine_reason` naming what promotion would take. - `tests/test_marketplace_executable_split.py` — `test_a_reason_that_names_the_rule_file_is_true_of_it` walks every reference-only entry whose reason quotes `enabled: false` (99 today), reads the rule file it cites, and fails if the flag disagrees. It also fails if it ever ends up checking nothing. **LF / POSIX artefacts, byte-level `--check`** - `scripts/build_marketplace.py`, `scripts/curate_detections.py`, `scripts/generate_corpus_stats.py`, `scripts/detection_truth_table.py`, `scripts/generate_llms_txt.py` — explicit `newline="\n"` on every artefact write; manifest `path` fields via `.as_posix()`. - The `--check` modes now compare **bytes** and reject `b"\r"`. In text mode the read translated CRLF away, so a CRLF file and an LF template agreed with each other and the drift was invisible. - `scripts/curate_detections.py` — the curated selection's `path` field used `str(Path)`. On Windows that is 601 backslashed paths, so `pnpm marketplace:curate --check` could never pass there and regenerating rewrote every entry. Now `.as_posix()`, and the check passes on Windows and Linux alike. **Regenerated** - `marketplace/index.json`, `apps/web/public/marketplace/index.json`, `services/api/app/data/marketplace/index.json` — byte-identical, LF, POSIX paths, 7582 items. - `apps/web/src/data/corpus-stats.json` — 2966 executable, 7408 on disk, 4442 quarantined. - `docs/detections/truth-table.md` — 7408 on disk, community 2, `enabled: false` 229. - `apps/docs/static/llms.txt`, `apps/docs/static/llms-full.txt` — the gate that first caught the stale on-disk count. - `README.md`, `apps/docs/docs/concepts/detections.md` — the published on-disk count (7407 → 7408), the tier line (`community=1` → `community=2`) and the not-loaded figure (4441 → 4442). `marketplace/curated.json` and `apps/docs/docs/detections/coverage.md` are deliberately unchanged: the curated selection is byte-identical once paths are POSIX, so there is nothing to regenerate, and touching them would rewrite all 601 entries for no content change. ## Testing - [x] Unit tests added / updated - [ ] Integration tests pass locally — see the two environment-only failures below - [x] Manually tested (describe steps below) <details> <summary>Manual test steps</summary> All commands run in the pushed tree, with `AISOC_REPO_ROOT` set (this machine has no `git` binary) and `PYTHONUTF8=1`. 1. Rule validator — all 7408 rules, including the new one, and its fixtures: ```text Validated 7408 rules — 7408 passed, 0 failed, 0 fixture warnings Tiers: community=2, imported=6113, native=1293 Executable (loaded by the engine): 2966; not loaded: 4442 ``` 2. Engine replay of the rule through the engine's own `_sigma_fallback`, five cases — the fourth is a Windows path, which `pathlib` would have normalised away before the `.as_posix()` fix: ```text PASS positive (private key): matched=1 expected=1 PASS negative (benign pdf): matched=0 expected=0 PASS public key exclusion: matched=0 expected=0 PASS windows credential path: matched=1 expected=1 PASS model call is not a file read: matched=0 expected=0 ``` 3. Artefact gates, all four, on Windows: ```text OK: detection truth table current — 2966 executable / 7408 on disk marketplace index is up to date in 3 locations (7582 items). check_marketplace_index_parity: OK — 3 identical copies, 7582 items all carrying a digest corpus-stats OK — 2966 executable across 7 categories, 7408 indexed on disk (4442 quarantined), 85 plugins, 64 playbook packs OK: llms.txt and llms-full.txt match their sources (2 files). curation up to date (601 curated, 122 techniques). ``` 4. `python -m pytest tests/test_marketplace_executable_split.py -q` → `10 passed` (was 9; the new test is the truthfulness one). 5. `ruff format --check .` clean over the whole tree (2979 files) and `ruff check services/ scripts/ tests/ tools/` clean — the two commands CI runs. 6. Byte-level check of all touched paths: all LF, no `\r` anywhere, including the three 11 MB index copies. 7. Regeneration is a no-op: every `--check` above passes immediately after the committed artefacts, on a Windows checkout — the platform the bugs were invisible on. **Two pre-existing local failures, not caused by this PR:** `tests/test_attribution_gate.py` and `tests/test_detection_attribution_gate.py` fail on this machine because they shell out to `git` and `bash`, neither of which exists here. They are untouched by this diff. </details> ## Screenshots (if UI changes) None — no UI change. (`corpus-stats.json` moves the counts the landing page reads; the numbers change, not the rendering.) ## Checklist - [x] My code follows the style guidelines of this project (`ruff`, `eslint`, `gofmt`) - [x] I have performed a self-review of my own code - [x] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally — all except the two `git`/`bash`-dependent gates noted above - [x] I have updated documentation as needed (README, CHANGELOG, CONTRIBUTING) - [x] My changes do not introduce new linter warnings - [x] I have checked for sensitive data / credentials in my diff ## Eval harness (required for substrate / playbook / detection changes) `python3 scripts/run_evals.py --json` on `3ec5fb1` (before) and on this branch (after), same machine, same synthetic dataset (200 deterministic cases). Both runs `all_passed: true`. The new rule is catalogue-only — it lives under `detections/community/`, which no engine path loads — so no eval input changes and the suites are identical, as expected. No axis regressed. <details> <summary><strong>Before</strong> (<code>scripts/run_evals.py</code> on <code>3ec5fb1</code>)</summary> ```text suite metric value target passed mitre_accuracy accuracy 0.97 >=0.8 true alert_reduction reduction_ratio 0.753 >=0.7 true investigation_completeness mean_keyword_coverage 0.9425 >=0.85 true response_quality mean_rubric_score 1.0 >=0.8 true hunt_corpus positive_scenario_catch_rate 1.0 >=1.0 true adversary_eval graceful_degradation_catch 0.475 >=0.4 true confidence_calibration investigation_brier_score 0.0646 <=0.18 true memory_recall memory_recall_accuracy 1.0 >=1.0 true override_accuracy override_accuracy 1.0 >=1.0 true playbook_completion_rate completion_rate 0.735 >=0.5 true detection_fp_rate worst_per_rule_fp_rate 0.0031 <=0.05 true all_passed: true ``` </details> <details> <summary><strong>After</strong> (<code>scripts/run_evals.py</code> on this branch)</summary> ```text suite metric value target passed mitre_accuracy accuracy 0.97 >=0.8 true alert_reduction reduction_ratio 0.753 >=0.7 true investigation_completeness mean_keyword_coverage 0.9425 >=0.85 true response_quality mean_rubric_score 1.0 >=0.8 true hunt_corpus positive_scenario_catch_rate 1.0 >=1.0 true adversary_eval graceful_degradation_catch 0.475 >=0.4 true confidence_calibration investigation_brier_score 0.0646 <=0.18 true memory_recall memory_recall_accuracy 1.0 >=1.0 true override_accuracy override_accuracy 1.0 >=1.0 true playbook_completion_rate completion_rate 0.735 >=0.5 true detection_fp_rate worst_per_rule_fp_rate 0.0031 <=0.05 true all_passed: true ``` </details> - [ ] Not applicable — this PR does not touch substrate, playbooks, detections, or eval inputs - [x] No axis regressed - [ ] An axis regressed; rationale and follow-up are described in the Summary above Signed-off-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com> Co-authored-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com> |
||
|
|
2abbad9274 |
fix(connectors): follow the Duo authentication log offset to the end of the window (carries #1802) (#1805)
Carries #1802 by @officialasishkumar, which went conflicting after #1801 merged — both PRs move the paging gate's debt ceiling and add adjacent gate tests, and fork branches cannot be rebased from this repository. **What changed relative to #1802 as submitted:** - `MAX_UNCLASSIFIED` lands at **52** (his branch said 54→53, written before the Datadog fix took 53; the falling-ceiling arithmetic, not the work, is what conflicted) — and the CHANGELOG sentence is corrected to match. - Both gate tests kept (`datadog_cloud_siem` from #1801, `duo_security` from this). - **CHANGELOG placement fix that the conflict surfaced:** #1801's entry had merge-drifted *inside* the `[23.0.0]` section — but that fix merged after the v23.0.0 tag, so the notes claimed a fix the tagged tree doesn't contain. Both the Datadog and Duo entries now sit under `[Unreleased]`, where the next release will truthfully carry them. **Verified locally:** `check_connector_paging.py` OK at ceiling 52 (duo_security now classified); all 21 tests pass (his 16-case Duo paging suite + the gate tests); `ruff format --check` clean. The connector work itself is excellent — documented maximum page size, the two-element `next_offset` joined per Duo's own contract, per-page request signing, partial reads kept on a failed later page, and the cap announced with its data-loss consequence stated. Authorship is preserved (commit author + co-author trailer), so the contribution credit stays with @officialasishkumar. --------- Co-authored-by: Asish Kumar <officialasishkumar@gmail.com> |
||
|
|
005163ab00 |
fix(connectors): follow the Datadog Cloud SIEM signal cursor to the end of the window (#1801)
## Summary
`DatadogCloudSIEMConnector.fetch_alerts` asked `GET
/api/v2/security_monitoring/signals` for `page[limit]=100`, sorted
`-timestamp`, and read only the first response. Datadog's cursor,
`meta.page.after`, was ignored. The poll window is clock-derived and
consecutive windows abut exactly, so a window holding more than 100
signals lost its oldest ones permanently, and those are the start of
whatever caused the burst. The connector now reads the window to the end
through the shared `read_token_pages`.
## Type of change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change
## Related issues
None filed. `datadog_cloud_siem` is one of the connectors
`scripts/check_connector_paging.py` names as unclassified ("requests a
capped page and never follows a continuation").
## Changes
- **The vendor contract.** The [API
reference](https://docs.datadoghq.com/api/latest/security-monitoring/#get-a-quick-list-of-security-signals)
describes `meta.page.after` as "The cursor used to get the next results,
if any. To make the next request, use the same parameters with the
addition of the `page[cursor]`." Datadog's published OpenAPI document
declares the same thing as this operation's `x-pagination`:
`cursorParam: page[cursor]`, `cursorPath: meta.page.after`,
`resultsPath: data`. `page[limit]` defaults to 10 and its maximum is
1000.
- `services/connectors/app/connectors/datadog_cloud_siem.py`:
`fetch_alerts` reads through `read_token_pages` with
`items_field="data"` and `token_field="meta.page.after"`. Every request
repeats the same `filter[from]`, `sort` and `page[limit]` and the same
credentials; only `page[cursor]` is added. A failed later page keeps
what was read, and the 25-page bound is logged when it binds. Both come
from the shared helper.
- `services/connectors/app/connectors/_paging.py`: `read_token_pages`
gains `empty_page_ends: bool = False`. The helper deliberately follows a
token beside an empty page, because Cloud Logging and GitLab require
that, and every existing caller keeps that rule. Datadog's own generated
clients end this read on an empty page as well as on an absent cursor
(Python `ApiClient` pagination; Go
`ListSecurityMonitoringSignalsWithPagination`; TypeScript
`listSecurityMonitoringSignalsWithPagination`). So a Datadog cursor
beside an empty page is not a promise of more rows. Datadog passes
`empty_page_ends=True` so a quiet window doesn't spend the page cap and
log a false `page_cap_reached`.
- **Behaviour change in the logs.** A refused opening request is now
logged as the helper's `connector.paging.token_page_failed`, with the
same status and body fields, instead of
`datadog_cloud_siem.fetch_failed`. It still returns no rows, as before
and as the Slack change did. Nothing in the tree referenced the old
event name.
- `scripts/check_connector_paging.py`: `MAX_UNCLASSIFIED` falls from 54
to 53. `test_paging_gate.py` pins `datadog_cloud_siem` in the paging
set.
- `CHANGELOG.md`: entry under Unreleased → Fixed.
If the Duo authentication-log paging PR lands first, this branch needs a
one-line rebase. Both lower `MAX_UNCLASSIFIED` from 54 to 53, so
whichever merges second should go to 52, and both add a changelog entry
at the same spot.
## Testing
- [x] Unit tests added / updated
- [ ] Integration tests pass locally
- [x] Manually tested (describe steps below)
<details>
<summary>Manual test steps</summary>
1.
`services/connectors/tests/connectors/test_datadog_cloud_siem_paging.py`
drives the real `fetch_alerts` through an `httpx.MockTransport`. It
covers:
- every page of a 250-signal window arriving, with a base64-shaped
cursor containing `+`, `/` and `=` sent back intact
- every request keeping the window, the order, the page size, the site
host and both keys
- a short page with a cursor not ending the read
- five end-of-collection shapes (empty, null and absent `after`, no
`page`, no `meta`)
- an empty page beside a cursor ending the read without announcing the
cap
- a 429 on page two keeping page one
- a refused opening request returning nothing
- an endless cursor being bounded at `DEFAULT_MAX_PAGES` and announced
2. The new test file run against the pre-fix connector from `main`: `7
failed, 5 passed`. The five that pass are the single-page
end-of-collection cases, which the old code also got right.
3. `pytest tests/connectors` in `services/connectors`, on the locked
dependency set CI installs: 453 passed. The full `pytest tests/`: 1483
passed and 3 failed in `test_ticket_sync_loop.py`. Those 3 fail
identically on an untouched `main` checkout, because they resolve a
hostname and the machine I tested on has no DNS.
4. `python3 scripts/check_connector_paging.py` → `38 follow a
continuation, 1 reviewed, 53 unclassified` / `OK`, plus `--self-test`
OK.
5. `ruff format --check .`, `ruff check services/ scripts/ tests/
tools/`, `python scripts/check_mypy_baseline.py` (no tree got worse) and
`python3 scripts/check_attribution.py --all`, all at the versions in
`ci.yml`.
No live Datadog tenant was used. The contract is the API reference, the
OpenAPI document and Datadog's own clients.
</details>
## Screenshots (if UI changes)
Not applicable.
## Checklist
- [x] My code follows the style guidelines of this project (`ruff`,
`eslint`, `gofmt`)
- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally
- [x] I have updated documentation as needed (README, CHANGELOG,
CONTRIBUTING)
- [x] My changes do not introduce new linter warnings
- [x] I have checked for sensitive data / credentials in my diff
## Eval harness (required for substrate / playbook / detection changes)
> **Required if this PR touches:** `services/agents/`,
`services/api/app/orchestrator/`,
> `playbooks/packs/`, `detections/`, `services/agents/tests/eval_data/`,
> `scripts/generate_eval_incidents.py`, `scripts/run_evals.py`, or any
prompt /
> RAG corpus / response template under those trees.
<details>
<summary><strong>Before</strong> (paste
<code>scripts/run_evals.py</code> output on base branch)</summary>
```text
Not applicable.
```
</details>
<details>
<summary><strong>After</strong> (paste <code>scripts/run_evals.py</code>
output on this branch)</summary>
```text
Not applicable.
```
</details>
- [x] Not applicable — this PR does not touch substrate, playbooks,
detections, or eval inputs
- [ ] No axis regressed
- [ ] An axis regressed; rationale and follow-up are described in the
Summary above
Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
|
||
|
|
7794078eb4 |
chore(deps): fold the Nov-9 GitHub Actions wave (pnpm/action-setup 6.1.1 everywhere, cosign 4.1.3, docker/login 4.8.0, kind 1.15.2, codeql group) (#1791)
Folds the five open GitHub-Actions Dependabot PRs into one family PR per the repo convention (cf. #1419, #1467, #1468): - #1780 — sigstore/cosign-installer 4.1.2 → 4.1.3 (3 workflows) - #1779 — pnpm/action-setup → 6.1.1 (13 workflows). Review note: 19 of 21 call sites were **already on v6.0.9 and green**; only `aisoc-action.yml` and `aisoc-cli.yml` still carried v4, so the scary-looking 4→6 major is in practice a unification at the version the fleet already runs. No workflow passes a `version:` input — all resolve pnpm from the root `packageManager` field (`pnpm@8.15.1`), which v6 supports. - #1777 — docker/login-action 4.7.0 → 4.8.0 (4 workflows) - #1774 — helm/kind-action 1.15.1 → 1.15.2 - #1772 — codeql-action group (init/autobuild/analyze) bump All bumps are SHA-pinned with the version comment preserved, matching the repo's pin style. The five folded PRs will be closed as superseded once this merges. |
||
|
|
d0297c177a |
fix(ci): survive the ubuntu-26.04 runner rotation; close CodeQL #1127 (#1762)
Two more reds surfaced on `main` right after #1761 merged, both from the same environment event and neither from that merge's diff. **Zero open CodeQL alerts.** Alert #1127, `py/import-and-import-from` (note) in `services/agents/tests/test_closure_authorization.py` — the file has imported `Path` at module level since it landed (Oct 27) and one test kept a function-local `import pathlib`; today's analysis surfaced it. One import style per module, as this repository already prescribes: the local import is gone and the test uses the module-level `Path`. The touched test passes; the file's two pre-existing local-environment failures are unchanged and green in CI. **Backup → destroy → restore.** The `ubuntu-latest` rotation from 24.04 to 26.04 moved the runner's apt `postgresql-client` to 18. `pg_dump` 18 writes `SET transaction_timeout` into its plain-format preamble, the job's pinned Postgres **16** server does not recognise that parameter, and the `--single-transaction` replay aborted wholesale — while `psql` exited 0 and `restore.sh` logged "restore complete" over a database holding nothing. Only the job's probe-row count caught it. Two fixes, one per defect: the job now shims `pg_dump`/`psql`/`pg_restore` to the server container's own binaries (client and server are the same version by construction, whichever image the runner rotates to next; both scripts stream over stdin/stdout, and the shim forwards `PGPASSWORD` for the seed and verify steps), and `restore.sh` replays with `ON_ERROR_STOP=on` so a failed replay is a failed restore rather than a success banner. Same family as the Helm 4 half of #1761: the runner image is not a pinned dependency, and every tool silently taken from it is a version pin that rotates on GitHub's schedule. Touching `scripts/restore.sh` and `integration.yml` makes the backup area run the full seed → backup → destroy → restore cycle on this PR, so the fix is exercised here, not asserted. |
||
|
|
f7d211ca85 |
fix(gates): paths-aware image-lag counting; catch AI session trailers (#1761)
Two gates redded `main` on 2026-11-08; both failures were real signal pointing at gate defects, and both are fixed here with defect-shaped tests. **Image availability.** `publish-images.yml` publishes only when a push touches its `on.push.paths` filter, so the docs-only credits commit moved `main` without moving any `:latest`, and the daily currency check — which counts raw commits behind — called sixteen tags stale for holding exactly what a build of the head would produce. The lag now counts commits touching the workflow's own paths filter, read from the workflow itself so the gate and the trigger cannot drift, and the publish window runs from the newest image-affecting commit rather than the head — closing the masking hole where a busy docs day kept a failed publish inside a forever-young window. A docs-only lag is tolerated out loud as a NOTE, never silently. Verified against the live registry on the exact state that failed this morning: 16 findings become NOTEs, exit 0. Also: a Helm values block shipping an empty repository on purpose (the template `required`s a value at render time) no longer emits a nameless `:vX.Y.Z` into the third-party list. Self-test grew 62 → 76 assertions, including a real commit-graph fixture proving the root-anchored glob semantics match the workflow's. **Attribution.** The squash merge of #1760 landed two attribution lines on `main`. The push-leg caught the tool co-author trailer; a vendor session trailer carrying a claude.ai session URL was caught by nothing — the bare-URL pattern is anchored to line start and no pattern covered session trailer keys, so the PR-side scan was green and the violation surfaced only where history is immutable. Two patterns close it: vendor-named session/conversation/transcript/thread trailer keys, and an AI session or share link anywhere in a line. Model alias mapping keys, provider config keys, and app URLs carrying a session query parameter are pinned as known-good so the gate cannot grow over-broad. The commit-msg hook reads the same pattern file and now strips these lines client-side — it stripped the first draft of this PR's own first commit message, which had quoted the offending line verbatim. The co-author half of #1760's squash message existed nowhere a pre-merge scan could see: GitHub appended it at merge time from a branch commit's *authorship*, under `squash_merge_commit_message=COMMIT_MESSAGES`. That repository default moves to `PR_BODY` with this change (the hook's load-bearing comment records it), and the push-to-main leg stays the backstop for merge-time behaviour no pre-merge scan can reach. The violating squash message on `04a46d14` is immutable history: its red Attribution run stays red on that commit, correctly. This branch's own range is clean, so the push scan on the next merge goes green. |
||
|
|
cf226d002b |
fix(connectors): read GitLab vulnerabilities from a route GitLab serves, and stop filing a 404 as a plan limit (#1759)
* fix(connectors): read GitLab vulnerabilities from a route GitLab serves, and stop filing a 404 as a plan limit Closes #1754. `GitLabConnector.fetch_alerts` polled `GET /groups/{id}/security/vulnerability_findings`. There is no such endpoint. Probed against gitlab.com it answers `404 {"error":"404 Not Found"}` — Grape's route-not-found body, byte-identical to the answer for a path invented on the spot — while `/groups/{id}/audit_events` answers `403 {"message":…}` and the documented `/projects/{id}/vulnerability_findings` answers `401 {"message":…}`. An existing route refuses you by `message`; a route never served says `error`. So the stream had never returned a row on any deployment. The reason nobody noticed is the second half of this change: its 404 shared a branch with 403, so a URL we got wrong was logged at `info` as the tenant's tier. Group.vulnerabilities, over GraphQL ----------------------------------- The documented REST route is project-scoped and this connector is configured with a group. Reaching it means enumerating the group's projects and polling each: `gitlab-org` reports `x-total: 3810` with subgroups, so one poll becomes thousands of requests every five minutes, and bounding that number silently stops scanning the rest of the group — the unread-window defect the paging work exists to prevent, rebuilt. The endpoint also takes no time filter, carries no `created_at` to window on client-side, defaults `scope` to `dismissed`, and GitLab says of it: "This API is in the process of being deprecated and considered unstable… Use the GraphQL API instead." `Group.vulnerabilities` has none of those problems. Group-scoped, so there is nothing to enumerate and no bound to get wrong; `sort: detected_desc` with `detectedAt` on every node, so a clock-derived window is readable; and a real Relay cursor. Every field was checked against the live schema by introspection and the whole query was executed against `gitlab.com/api/graphql`, which answered 200 with a live `endCursor`. `cloudflare_zt` made the same move for the same reason in #1686. 404 is not 403 -------------- On the REST half, a 403 on audit events stays an `info` line — the token does not own the group, or the plan does not include them. A 404 is now a warning naming the group and the instance URL, because that route exists and so a 404 is about the group, not the tier. GraphQL answers 200 for everything, so the same distinction is drawn on the body: an `errors` array is our defect and warns; a null `group` is a path nobody can see and warns; only a null `vulnerabilities` is the plan, and only that is `info`. `scripts/check_connector_404_conflation.py` makes it durable. No connector may accept a 404 in the same branch as a 401 or 403 unless the pairing is declared with the vendor's own response list for that endpoint. One pairing is declared — GitHub publishes `404 - Resource not found` for `/orgs/{org}/code-scanning/alerts` — nothing else in the tree conflates them, and the ceiling is zero. Against the pre-fix tree the gate exits 1 naming all three GitLab sites. Evidence -------- * 14 new tests drive the real `fetch_alerts` through a transport, and all 14 fail on `main`. The first prints the dead URL the connector still asked for. * The old suite mocked that route and answered it 200, which is how a path GitLab has never served looked healthy for the connector's whole life. The replacement deliberately does not register it, so respx fails a regression that re-adds the call. * Measured against the live endpoint rather than assumed: an authorization-filtered page comes back `nodes: []` beside `hasNextPage: true`, so an empty page must not end the read. * Negative controls, each observed: removing the window stop reads 9 pages where 1 is correct; discarding a partial read on a later-page rejection fails the test that keeps it. * `check_connector_paging` is unchanged at 54 — the connector still pages both streams, through a different helper for the second one. * No live GitLab Ultimate tenant was available, so no real vulnerability has been observed through this path. The contract is the published schema plus a query executed against GitLab's own endpoint. The docs page is touched because it is gated: the schema's help text moved, so `generate_connector_docs.py --check` fails without regenerating the field reference. The prose corrected alongside it said the REST endpoint "is reliable on Ultimate and is what the connector pulls", and that GraphQL was "not used". * fix(api): regenerate the bundled connector catalog after the GitLab schema moved `services/api/app/data/connector_catalog_fallback.json` is generated from every connector's `schema()`, and the GitLab description and token help text changed in the commit before this one. `generate_connector_catalog_fallback.py --check` caught the drift in CI, which is the gate doing its job. The diff is exactly those two strings. This is the second artefact downstream of `schema()` in this branch — the other is the docs field reference — and both are generated, so neither was edited by hand. --------- Co-authored-by: Beenu Arora <beenu@cyble.com> |
||
|
|
4446d29643 |
ci: gate the single source of truth for the version (#1737)
* ci: gate the single source of truth for the version The root VERSION file is authoritative and several surfaces restate it instead of deriving from it. A restated number is correct until the next release and then silently is not, because 'agrees with a constant' is not a property anyone checks. settings.VERSION is the sharpest case: it is the version= handed to the FastAPI application, so it is also the version in the published OpenAPI document and the one the root route serves -- and it reads 0.1.0 on a tree several majors past that. This is the gate only. The surfaces are corrected by a separate change, so it is RED against main today by design -- five findings -- and graded against that change's actual head it exits 0. Hold until that lands. * fix(ci): type the version-gate's literal tuples as the three-element tuples they are mypy's unmanaged tree reported six findings and the baseline records zero, so Python - Lint & Type-check was red. Five are one bug: SurfaceReport.literals and js_literals' accumulator were annotated list[tuple[int, str]] while both have carried (line, literal, is_fallback) since the fallback case was split out, so the grade() unpack of three values was unprovable. The sixth is node.lineno on the ast.AST that ast.walk yields; the walk now skips anything that is not one of the two narrowed assignment statements with an explicit else, which is clearer than filtering afterwards and is what makes the line number provable. Annotations only - no behaviour changes. Re-verified after the change: self-test exit 0, --list reports 5 of 5 surfaces deriving, and reverting APP_VERSION to the 0.1.0 literal still exits 1 naming both numbers. check_mypy_baseline now reports no tree got worse. |
||
|
|
311408d0bb |
fix(tests): make the borrowed service package a package, and share one migration comparison (#1753)
* fix(tests): make the borrowed service package a package, and share one migration comparison
Two things, one of which is a regression `b24d8122` caused.
The live tenant-isolation suite
-------------------------------
Every test in `tests/isolation/test_backtest_lake_live.py` that reaches the
warehouse — twelve of fifteen — has been erroring at fixture setup on `main`
since that merge, with:
ModuleNotFoundError: No module named 'app.core.version';
'app.core' is not a package
The cause is not the cross-service `app` collision itself; it is the
machinery built to avoid it. The fixture registered `app`, `app.core`,
`app.db` and `app.services` as bare `types.ModuleType` objects. A module has
no `__path__`, so it is not a package and the import system cannot resolve
*any* submodule through it, however plainly the file is on disk. A
hand-written list of file paths was therefore the only way a module became
reachable — a wall, not an optimisation. Adding
`from app.core.version import resolve_version` to `app/core/config.py` hit
it, and the next module under `app/core/` would have hit it too.
So the fix is at the level the error names. `tests/isolation/service_packages.py`
borrows a service's `app` tree as a real package whose `__path__` is the real
directory, and the import system resolves submodules from disk the way it
does in production. Nothing is added to `sys.path`, so no other service's
modules become findable; on exit the whole `app` namespace is restored by
snapshot rather than by a list of names the caller recorded, which it has to
be now that the import system registers submodules nobody enumerated. There
is no allowlist to keep current because there is no allowlist.
`test_retro_hunt_live.py` had the same construction and now uses the same
helper. It keeps one exception — `app.services.retro_hunt`'s `__init__.py`
re-exports from four siblings, two of which reach SQLAlchemy, which this job
does not install — and that package is registered without executing its
`__init__.py` while still resolving its children.
`tests/isolation/test_service_packages.py` pins the property: four modules
nobody enumerates resolve, the namespace comes back unchanged including when
the block raises, and the namespace-only exception still resolves children.
Reverting the `__path__` reproduces the original error on all of them.
Why it merged ungraded
----------------------
`isolation-live.yml` named three `services/api` files. The backtest suite
loads eleven, and `app/core/config.py` is one of the eight it did not name,
so the job never ran on that pull request. The filter now names the three
directories that contain the whole measured closure, and the pull-request
list is a YAML anchor of the push list so the two cannot drift apart.
One migration comparison, not two
---------------------------------
`scripts/pending_migrations.py` and `services/api/app/services/schema_skew.py`
compared the same two sets with two copies of the arithmetic, and the copies
had already drifted: the service skipped a directory named `*.sql` and the
script counted it. The script now loads the service's `migrations_on_disk`
and `evaluate_skew` by path — the pure half is standard-library-only by
construction, and `_read_applied` defers its SQLAlchemy import so it stays
that way.
What stays different is the verdict on one case, deliberately. A migration
applied in the database and absent from the tree means the deployment runs
older code than its schema. The service calls that skewed, because it is
asked whether the schema matches the build. The script exits 0, because it
is asked whether to run `make upgrade`, and upgrading applies migrations
forward and cannot fix a rollback. That is one named branch in
`exit_code_for`, and `tests/test_upgrade_path.py` drives both callers over
seven verdicts and fails if any second case disagrees, if the script grows
its own copy again, or if the shared module gains a module-scope
third-party import.
* docs(changelog): record the isolation-suite fix and the shared migration comparison
* fix(tests): keep the raise out of the combined with, so the flow stays readable
CodeQL does not model `pytest.raises` as swallowing the exception, so a
`with pytest.raises(...), service_app_tree(...)` whose body raises makes
everything after it unreachable to the analysis and the snapshot above it
unused — two open alerts on a test that is correct. The raise moves into a
nested function, which costs nothing and leaves one honest control flow for
both a reader and the analyser.
|
||
|
|
a264aeb0fa |
fix(connectors): follow the Slack audit log cursor to the end of the window
Carries the work of #1752 onto a repo-owned branch so the paging gate's ceiling can be resolved against the Link-header change that landed in #1751. The code is unchanged from the original commit; the only edits are the two lines the two branches both touch. `SlackAuditConnector.fetch_alerts` sent `limit=200` and ignored `response_metadata.next_cursor`. Slack documents that cursor as the way to reach the rest of a collection, that an "empty, null, or non-existent" value is the only end-of-collection signal, and that the audit log's default ordering is "descending (most to least recent)". The poll window is clock-derived and this connector keeps no checkpoint, so an entry past the 200th was requested once, not returned, and never asked for again — and being the oldest of the window, it was the beginning of whatever burst overflowed the page. `read_token_pages` already had the right loop; `token_field` now accepts a dotted path so a vendor that nests its token can use it. Resolved against #1751: * MAX_UNCLASSIFIED 55 -> 54. The original commit wrote 58 -> 57 against a base where the Link-header work had not landed. Applied on top of 55 that would raise a ceiling the gate's own docstring says may only fall, which is why git refused the merge rather than taking either side. * The CHANGELOG entry is kept verbatim apart from the same two numbers. Both #1751 and #1752 were opened against a base that predates the merge of #1750, and a fork branch cannot be rebased by a maintainer from here, so the carry-over is the only route that keeps the author's commit in the history. Co-authored-by: Asish Kumar <officialasishkumar@gmail.com> |
||
|
|
bc6be6e111 |
fix(connectors): follow the Link header on Okta, GitHub and GitLab windows (#1751)
All three vendors answer a capped collection request with the first page and a `Link: <url>; rel="next"` header, and all three connectors read the first response and stopped. A poll window opens where the last one closed, so a row left unread is never requested again. Okta kept the first 50 rows per event type, oldest-first; the GitHub and GitLab streams stopped at 100. Add `read_link_header_pages` to `_paging.py` beside the two existing readers, with the same properties: a partial read is kept, the page cap is announced when it binds. Two rules are specific to this shape: - An empty page ends the read even when it carries a next link. Okta documents that a System Log request with no `until` has "an infinite number of pages" whose next link is "always present", and says to continue "until no events are returned". - A next link may not leave the origin of the opening request. The egress guard validates the URLs a tenant configures, not the ones a server answers with, and `domain` and `gitlab_url` are tenant-controlled, so a server at a permitted address could otherwise point the loop at a metadata address with the vendor credential attached. GitHub code scanning and GitLab vulnerability findings have no server-side time filter, so `stop_when` ends those reads at the first page that passes the start of the window instead of walking back to the oldest open finding. Okta moves to its documented 1,000-row maximum to spend fewer requests from the System Log rate limit. GitLab audit events move to keyset pagination because offset pagination on that endpoint is deprecated. The paging gate credits the new helper and MAX_UNCLASSIFIED falls from 58 to 55. Signed-off-by: Asish Kumar <officialasishkumar@gmail.com> |
||
|
|
2d034fcc71 |
fix(api): bound re-roling in both directions, and give the service principal one permission model (#1750)
* fix(api): bound re-roling in both directions, and give the service principal one permission model GHSA-qcgm-c945-q96h: authorize_role_change checked only the role being conferred, and the last-administrator guard counted only the wildcard roles that no API caller can hold -- so one tenant_admin could demote every peer and then itself, leaving a tenant nobody can administer. Reproduced at 200 twice against real Postgres. The guard's count also bound uuid columns as text, so it answered 500 rather than 409 the moment it fired. GHSA-ghpm-vc6j-hp5r: SERVICE_PRINCIPAL_PERMISSIONS and ROLE_PERMISSIONS[api_service] declared one principal twice and disagreed, and has_permission_db read neither the resolved set nor elevation nor conditions. A deprovisioned user reached GET /api/v1/mcp-servers on their old static role at 200 while every require_permission route answered 403. * docs(security): point the advisory references at the surviving report The finding was submitted twice, 28 seconds apart, with byte-identical descriptions. GHSA-hrc5-w9r3-2g8r is the first-filed one and the one whose reporter credit is already accepted, so it is kept and GHSA-qcgm-c945-q96h is closed as the duplicate. Every code comment, test and document that named the duplicate now names the live advisory. * fix(gate): narrow the assignment node before reading its value mypy's attr-defined: the conditional pulled .targets and .value off a bare ast.stmt. Same check, narrowed per node type. |
||
|
|
40c0b4388f |
fix(connectors): follow the Slack audit log cursor to the end of the window
`SlackAuditConnector.fetch_alerts` sent `limit=200` and read the first response. Slack documents `response_metadata.next_cursor` as the way to reach more results, and returns entries most-recent-first. A poll window opens where the last one closed, so a window holding more than 200 entries lost its oldest ones for good, and those are the start of whatever caused the burst. Read through the shared `read_token_pages`, which already keeps a partial read and announces its page cap. Slack nests its cursor, so `token_field` now accepts a dotted path; the Google callers pass top-level names and are unaffected. Slack states that a page can be shorter than `limit` while more results remain, and that an empty, null or absent cursor ends the collection. Both are pinned by test, because a client testing the page length would stop early. A refused opening request is now reported by the helper's `connector.paging.token_page_failed` rather than `slack_audit.fetch_failed`, with the same status and body fields, and still returns no rows. The paging gate's changelog entry named this connector as unconfirmed against a vendor document. That document exists, so MAX_UNCLASSIFIED falls from 58 to 57. Signed-off-by: Asish Kumar <officialasishkumar@gmail.com> |
||
|
|
4ccf214982 |
Merge the VAID live-path mint and startup preflight by @solara-associates (#1746)
Carries the contributor commits verbatim so authorship and the review stay legible apart. Review changes follow as their own commit. |
||
|
|
010a3981bf |
feat(web): wire the i18n catalogue into the console, and fail the gate when nothing reads it (#1747)
* feat(web): wire the i18n catalogue into the console and gate its readers The console was English-only not because i18n was unbuilt but because nothing imported it: `apps/web/src/lib/i18n/` shipped a translator, a direction helper, Intl formatting and two catalogues with zero importers, while the parity gate stayed green comparing the locales with each other. - `LocaleProvider` mounts in the root layout, shaped like `ThemeProvider`. Direction is written to `<html dir>` by a pre-paint bootstrap script and by the provider, so the right-to-left locale lays out right-to-left. - A language switcher in Settings, beside Theme and Density, persisting to this device and to the user profile. No automatic browser negotiation. - `check_i18n_keys.py` fails when a base key is rendered by no component. Per key, not per import. Fatal rather than ratcheted, with a named exemption list holding one entry. - Four keys naming copy the console does not have were deleted. - The switcher states its own scope, measured from the catalogue. The untranslated ceiling is unchanged at 6. Closes #1729 * fix(scripts): stop two mypy findings in the i18n reader gate Both are variable shadowing inside one function rather than a behaviour change: the unknown-call-site report reused `path`, already bound as a `Path` by the file walk above it, and the self-test reused `unknown`, already bound as a `list[str]` by the parity cases. mypy reads the first binding's type, so the second assignment is an error and the tuple unpack that follows reads as unpacking a string. Caught by `check_mypy_baseline`, which records 0 findings for a new file and so fails on any. * fix(scripts): the mock-data gate cannot read a translation catalogue Wiring the catalogue gave it its first component reader, which is what brought it into this gate's scope — and it reported `en` as a module-scope dataset of named entities with no demo gate. That is a structural false positive rather than a violation. A UI catalogue's keys *are* the column names a SOC renders, so `severity:`, `status:` and `firstSeen:` sit in it by definition and `_asserts_state()` is always true of it; and any two-word Title Case label satisfies `PROPER_NOUN`. The catalogue is therefore permanently one ordinary label away from redding this gate for a reason unrelated to fabricated data, which is how a gate gets switched off rather than fixed. Narrowed at the source instead of recorded in `KNOWN_UNGATED`, because nothing here is unfixed debt: every value is UI copy rendered as a label, and `check_i18n_keys.py` now proves per key that it is. The self-test runs one source down two paths — quiet under `lib/i18n/messages`, still caught from anywhere else — since a narrowing proven only in the direction that silences it is indistinguishable from deleting the rule. |
||
|
|
d90c2c47ed |
docs(compose): keep honeytokens opt-in, and state the real reason (#1745)
The compose comment said the honeytokens image 'isn't published to GHCR yet'. That is false: both ghcr.io/beenuar/aisoc-honeytokens:v22.2.0 and :latest resolve as multi-arch manifests, so the stated reason for the profile had stopped being true. The placement itself is still correct and is kept, now with the reason that holds: honeytokens is a leaf service that nothing else in the stack calls, no code path seeds a token automatically, the console renders an explicit unavailable state when it is absent, and the Helm chart defaults it off -- so a CORE deployment that never visits the page gains a service it cannot use. It is enabled with a single profile flag. Two claim sites that render the profile counts in word form were never watched by the counts check; both are now registered, taking it from 31 sites to 33. |
||
|
|
b8487a9b25 |
ci(reproducible-builds): derive the install floor from each service's lock (#1744)
The twice / twice-all / twice-lockonly legs asserted a hardcoded floor of 20 installed packages. services/escalations installs 3 runtime packages from its own lock, so the leg failed on a build that was completely correct, and the number carried no relationship to any service it graded. The floor is now derived per service from its committed poetry.lock: packages whose group and PEP 508 markers hold for the image's own marker environment, with PEP 621 optional-dependencies and Poetry extras excluded because 'poetry export --only main' does not install them. scripts/check_install_completeness.py names the missing distributions when an install is short, rather than printing a count comparison. |
||
|
|
8ef86a6c95 |
feat(agents,actions): mint a VAID badge on the real agent path, startup preflight (beenuar/AiSOC#1739 follow-up)
Closes the gap PR #1742 left open: the VAID plugin verified a shape but minted nothing on a real path. deep_investigation.py's issue_identity call for the investigation agent is the one real caller in this service, and is now the mint site, gated by the same AISOC_VAID_PLUGIN_ENABLED flag; the existing with_granted_tools() call on an MCP grant re-mints through the same duck-typed path, with no branch of its own needed. Both services gained a startup preflight (vaid_plugin.preflight_or_raise, vaid_verifier.preflight_or_raise) that refuses to come up when the plugin is enabled but nothing can mint/verify or no revocation list is configured, called unguarded from each service's startup hook so a misconfiguration fails the process rather than refusing the first real request live. The allowlist entry for services/agents/app/security/vaid_plugin.py in scripts/check_module_reachability.py is removed, as the entry itself asked for: the module now has a real production caller. Off by default, unchanged: with the flag unset, deep_investigation.py's mint call is still exactly issue_identity(...), same type, same arguments, and every preflight is a no-op. services/agents: pytest -q -> 2567 passed, 20 skipped (was 2558 passed, 20 skipped on the base commit with vaid-mint installed). services/actions: pytest -q -> 2116 passed, 10 skipped (was 2111 passed, 10 skipped). check_module_reachability --check: OK, 1128/1156 reachable, 28 allowlisted (was 1127/1156, 29 allowlisted). Signed-off-by: Solara Associates <info@solara.associates> |
||
|
|
ff669398e3 |
feat(agents,actions): optional VAID badge plugin for agent identity, off by default (#1739, #1741) (#1742)
Carries #1741 by Allan Smeyatsky, with review fixes. Off by default and unwired; this does not make VAID the project's agent identity format. Co-authored-by: Allan Smeyatsky <asmeyatsky@hotmail.com> |
||
|
|
125d00b8fe |
fix(honeytokens): deliver a tripped honeytoken, and never lose one to an outage (GHSA-9q6p-m345-h3hj) (#1736)
* fix(honeytokens): deliver a tripped honeytoken, and never lose one to an outage
GHSA-9q6p-m345-h3hj.
F57: send_alert posted to HONEYTOKEN_ALERT_WEBHOOK_URL, which has no
default, and returned False after an info log when it was unset. No
receiver route exists in the API, so a tripped honeytoken produced
nothing. A trip is now pushed into the ingest spine by default, the way
a connector pushes a vendor finding, and becomes an alert through the
path every other signal takes. The normalizer profile ships with it:
without one the push is filed as category 4 and never promoted.
F58: delivery was attempted inline, once, so a trip during a receiver
restart was lost. It is now journalled before the trip is acknowledged
and drained by an awaited path, with permanent and transient really
distinguished -- a 404 is terminal with the reason on the row, a 503 is
retried under a capped backoff, and an exhausted row stops rather than
churning.
Reported by Jake Davis.
* ci(honeytokens): grade the outbox durability suite against live Postgres
A live suite that runs in no workflow is decoration. The migrations job
already applies this service's alembic chain to a real database, so the
suite runs there, as the DML-only aisoc_app role the service connects
as, with a skip treated as a failure.
* fix(honeytokens): address CI findings on the outbox change
Three real findings, none of them suppressed:
* the live suite asserted on drain_once's global return, so it got its
answer from rows an earlier test had left behind -- it passed locally
and failed in CI with 'assert 2 == 1'. Every assertion is now pinned to
the row the test itself created, and the suite passes repeatedly
against a dirty table.
* CodeQL py/ineffectual-statement on a bare 'await task' at shutdown.
Replaced with a bounded asyncio.wait_for, which is also better: a drain
wedged on an unresponsive receiver must not hold the pod open for its
whole grace period.
* semgrep's credential heuristic keys on the substring 'token', so five
log events reading 'honeytoken alert for trigger ...' were counted as
credential disclosure. No secret was ever logged. The events are
reworded rather than the ceiling raised, with the reason recorded
beside them.
Also annotated three test lists mypy could not infer.
* fix(honeytokens): regenerate the connector union and bank the semgrep shrink
The new `honeytoken` normalizer profile is an input to
scripts/generate_connector_types.py, so the committed TypeScript union
drifted from what generation produces.
The semgrep ceiling comes down 113 -> 112 rather than staying put: the
five credential-heuristic false positives were reworded away and the
dead alerting module was deleted, and a shrink that is not banked drifts
back up for free.
* fix(honeytokens): declare the honeytoken profile internal, not a connector
check_connector_profiles requires every normalizer profile to name a
connector an operator can configure. A tripped honeytoken is pushed by
services/honeytokens rather than polled, so there is no such connector —
it belongs in INTERNAL_PROFILES beside aisoc_sample, the set that exists
precisely so self-generated telemetry gets a profile without appearing in
the catalog or inflating the published connector count. It meets that
set's honesty requirement by naming AiSOC as its vendor, and the count
gate confirms the figure is unchanged at 91.
Also drops a deleted file's path from an allowlist comment, which
check_comment_paths correctly refused.
* fix(honeytokens): make the outbox migration legible to the parity gate
check_orm_migration_parity reads these files statically. Two things
hid the table from it, and both are the same class of defect as a
constants module defeating a SQL scanner elsewhere in this tree:
* the table was named through a module variable, so the gate reported
honeytoken_alert_outbox as created by no migration at all while the
ORM mapped it;
* with that fixed, the inline sa.CheckConstraint was read as a column
named "status IN ('pending', 'delivered', 'dead')". The constraint is
now its own ALTER TABLE, which is also where the index and the RLS
policy already sit.
Verified against a real database rather than by reading: the chain
upgrades, downgrades and upgrades again on a clean database, and the
constraint rejects an out-of-vocabulary status.
|
||
|
|
4711bdcaaa |
fix(agents,actions): make the VAID badge check total, bound and pinned (#1741)
Review follow-ups on the optional VAID badge plugin. The plugin stays off
by default and unwired; what changes is that its refusals are now stated
rather than incidental, that a badge has to be the caller's own, and that
the dependency cannot move under a deployment.
Three defects, each found by executing the path rather than reading it,
and each with a negative control that goes red when the fix is reverted.
A malformed badge raised instead of refusing. vaid-mint 0.11.0's
`assemble_lineage` opens with a bare `leaf["vaid_id"]`, so
`verify_badge_for_dispatch({}, "isolate_host")` raised `KeyError` — past
`dispatch()`, which caught only `BadgeDenied`, and out of a route whose
own docstring promises it "never returns 5xx for executor failures"
because "the agent loop relies on a uniform success-shape". The action
never ran either way, so the refusal held; the structured refusal, the
audit line naming why, and the route contract did not. Both services now
gate on vaid-mint's own `parse_vaid_document` rather than on a
hand-written member list that would drift from it, and `dispatch()` keeps
a broad `except` as the backstop, because the thing that made this
reachable was a verifier promise about a third-party library and the next
release of that library is not bound by it.
A genuine badge was not checked to be *this* caller's badge.
`verify_vaid_standing` answers "authentic and still standing", which a
correctly-signed badge issued for another agent, or under another
tenant's authority, passes. Measured: a `triage` identity carrying a real
`respond` badge was accepted in-process, and a badge minted for tenant A
cleared a dispatch belonging to tenant B. Neither escalates privilege —
scope is still decided by `AgentIdentity.require`, and the actions
service's kill switch, contract, approval matrix and blast-radius tier
all still run — but proof of *under whose authority* an action ran is the
one thing #1739 asked for, and a credential valid under anyone's
authority does not provide it. The agents side now binds `agent_class` to
the identity it accompanies; the dispatch side binds the badge's tenant
to the request's, refusing a tenant-bound badge on a tenant-less dispatch
rather than reading a missing field as permission.
A mistyped TTL crashed minting. `_ttl_hours` called
`logger.warning("event", value=raw)` — structlog's call shape — against
this service's stdlib logger, which answers `TypeError`. The branch that
exists to tolerate a bad `AISOC_VAID_TTL_HOURS` was the branch that took
`issue_vaid_identity` down. Surfaced by mypy's `call-arg`; reachable only
by setting that variable to something unparseable.
`vaid-mint` is now pinned exactly rather than `>=0.11.0,<1.0.0`, held
equal across both services by `scripts/check_dependency_pins.py`, and
present in both lockfiles — regenerated with the repository's pinned
poetry so a second resolver's answer is not what lands. A signature
verifier that decides whether a containment action runs belongs in the
same category as `cryptography` and `sqlglot`: on a 0.x library any minor
may change behaviour, and `update-types: semver-major` cannot hold a 0.x
dependency at all. Registering it surfaced a false positive in that gate,
which read a bare `version = "0.11.0"` — poetry's legal shorthand for
`==` — as an unparseable bound and reported a correct tree as "outside
the declared range 0.11.0"; a gate that fails a correct tree is the kind
that gets switched off, so it now reads the shorthand, tested both ways.
`services/agents/app/security/vaid_plugin.py` is allowlisted in
`check_module_reachability` with the gap stated: nothing mints a
`VaidBackedIdentity` on a real agent path yet, and wiring the hook alone
would be worse than leaving it, since with no minting call site an
operator who set the flag would refuse every tool call. The
actions-service half is reachable from `dispatch()` and is not
allowlisted. The entry names the change that removes it.
Also: the ruff format and lint gates, which the branch did not pass as
submitted, and two comments pointing at a report file that does not exist
in this repository.
Also records the plugin under [Unreleased] in CHANGELOG.md.
|
||
|
|
3178841b81 |
fix(fusion): reopen a closed alert when its detection fires again (GHSA-qp9f-459j-w89c) (#1735)
* fix(fusion): reopen a closed alert when its detection fires again GHSA-qp9f-459j-w89c. The alert sink deduplicated on (tenant_id, dedup_hash) with no status predicate, so a closed alert absorbed every later firing of the same detection and no open alert was created. An attacker who tripped a detection, waited for it to be closed and repeated the activity was invisible to the queue. Reopen rather than insert a second row: uq_alerts_tenant_dedup is UNIQUE per (tenant_id, dedup_hash), and a time-bucketed fingerprint would split two firings that straddle a bucket boundary while the alert is open, breaking deduplication to fix recurrence. The reopen is counted, timestamped and reasoned (migration 160), and its status = ANY(terminal) predicate is also the control that leaves an open alert alone. Reported by Jake Davis. * fix(scripts): narrow the alert-status extractor so mypy can prove it mypy read `node.value` off the common `ast.stmt` because the isinstance narrowing happened inside a conditional expression rather than on the node itself. Handling Assign and AnnAssign as separate branches makes the narrowing real, and surfaces a case the one-liner hid: an AnnAssign with no value is a bare declaration, which must be refused rather than rendered as an empty vocabulary. |