Commit Graph
500 Commits
Author SHA1 Message Date
beenuar f4cea19023 fix(docs): the vendor-door row cites the intake worker by its full path 2026-11-22 14:13:14 -08:00
beenuar 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.
2026-11-22 11:37:35 -08:00
Beenu Arora 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.
2026-11-23 11:13:06 -08:00
Beenu Arora 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.
2026-11-23 02:39:38 -08:00
Beenu Arora 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.
2026-11-22 22:00:09 -08:00
Beenu Aroraandbeenuar 5216d06169 feat(actions): governed undo route — executor rollbacks reachable in production (#2016)
## The gap

Nothing in production called an executor's `rollback()`.
`services/actions` had no undo route and no worker invoked one, so
`SplunkSyncDetectionRuleExecutor.rollback`,
`ElasticSyncDetectionRuleExecutor.rollback` and every other executor's
reversal was reachable only from tests — while the capability contracts
advertise `reverse_capability` on every platform-reversible verb and the
executors capture `rollback_data` on every destructive one. A reversal
the product cannot dispatch is a promise the docs make and the product
breaks.

## What this adds

**`POST /actions/{action_id}/rollback` on the actions service**
(service-token-guarded beside approve/reject/reconcile; logic in
`app/services/undo.py`):

- **The record decides what is reversed.** The verb, the target and the
vendor come from the stored action record (`rollback_data.vendor`, with
execution output as fallback) — the caller chooses none of them. A
record that captured nothing (simulation-mode forward run) or names no
vendor is refused with the reason (422).
- **State guard = one conditional UPDATE.**
`action_store.claim_rollback()` moves `completed → rolling_back` (new
`ActionStatus.ROLLING_BACK`, added to the store's intent-locked set)
exactly as `claim_for_execution` claims a forward run — Postgres
row-lock plus predicate re-evaluation elects one executor across
replicas and retries. An action that never executed, was already rolled
back, is mid-reversal, or has an unestablished outcome is refused 409
naming which. The claim lands under its own `rollback` key so the
forward dispatch provenance survives the undo.
- **The reversal is governed like a forward dispatch.** The undo is
graded against the **reverse** capability's own contract through the
same `evaluate_contract` every forward door calls (tenant tier,
confidence with `None` as the lowest band, asset criticality, response
schedule). A reversal graded `analyst`/`mandatory_human` does not run
until a distinct approver is bound — permission-checked and
separation-of-duties-compared against the undo's requester via the same
`authorize_approver` the approve door uses; `prohibited` never runs. The
invoking principal needs the forward verb's own execution-tier
permission (`authorize_action`).
- **Credentials arrive per call, never from the record.** The body's
`auth_config` carries connector-schema fields translated at the boundary
by the same `resolve_params` forward dispatch uses. Verbs whose legacy
reversal cannot accept per-call credentials (every one-argument
`rollback(result)` today) are refused up front (422) rather than queued
for an approval that could only simulate — only the credential-capable
arms are dispatchable, which is currently the two `sync_detection_rule`
arms, and the route generalises as arms widen.
- **The executor's boolean is reported honestly.** Only a confirmed
reversal settles the record to `rolled_back`, stamping `rolled_back_at`,
`rolled_back_by` (the approver when one decided, else the principal) and
full provenance (requester, approver, separation-of-duties state,
vendor, grading requirement and reason). A `False` — vendor refusal,
missing reversal state — is a **failed undo**: the record returns to
`completed` (the effect is in force, the undo retryable) with the error
recorded. Never a success.

**`POST /api/v1/actions/{action_id}/undo` on the API**
(session-authenticated, `require_permission("actions:execute")` — the
same permission as the forward playbook-step door; logic in
`app/services/action_undo.py`):

- **The request cannot carry credentials.** The body model refuses
unknown fields (`extra="forbid"`), so there is no key to put a token or
a destination in; it carries only `confidence`. Credentials are resolved
server-side at dispatch time: the tenant's enabled connector for the
vendor the record executed against (honouring per-instance capability
downscoping, via the playbook hop's own `_pick_connector`), decrypted
through the vault, merged with the connector's operational config —
mirroring `playbook_step_dispatch` exactly.
- **A queued undo follows the forward approval flow.**
`pending_approval` from the grading creates an `AgentApproval` row
(`kind: action_undo`, requester stamped from authenticated context) in
the same approvals inbox forward actions use; the response carries the
`approval_id`. Deciding it re-drives the reversal through
`_dispatch_decision`'s new undo branch with the deciding identity bound
as approver and the stamped requester kept separate — the requester
cannot approve their own undo, and credentials are resolved freshly at
decide time so nothing secret ever waits in a queue. A denial executes
nothing.
- **Every outcome is audited**: `emit_audit(action="actions:undo",
resource="action", resource_id=<action id>)` with the status, the
reversal verdict, the vendor, the verb, the target, and the approval id
when one was queued.

`docs/openapi.yaml` regenerated — purely additive (+85 lines, 0
deletions). No migration: the record fields ride the existing JSONB
record column, and the approvals table already exists.

## Failing-test-first

`services/actions/tests/test_action_undo_route.py` was written first
against the absent route (TestClient over the real router, in-memory
store, **real `SplunkSyncDetectionRule` adapter against the mock Splunk
management API from `test_sync_detection_rule_vendor_arms.py`**):

- before implementation: **12 failed, 1 passed** (the cross-tenant 404
passes vacuously while the route is absent);
- after: **13 passed**, including the headline — forward
`sync_detection_rule` executed through the real Splunk arm (prior
definition captured), undone through the route with an approver bound,
and the mock vendor shows the prior SPL **and schedule** restored; the
seeded records carry no credentials, so the restore happening at all
proves the credentials came from the request's `auth_config` (the
stored-integration path) and were translated `base_url/token →
splunk_url/splunk_token` at the boundary.

`services/api/tests/test_action_undo.py` likewise failed on collection
before the endpoint existed, then **10 passed**: vault-not-request
credential sourcing, credential-bearing bodies refused by validation,
pending-approval row creation, decide-path re-drive with the deciding
identity, denial executing nothing, vendor refusals and upstream state
refusals surfacing with their reasons, and the audit row.

Approval grading proven in both shapes, the way the forward tests do it:
the analyst-tier reversal (`sync_detection_rule`, whose reverse is
itself, declared `analyst`) queues with the vendor untouched and runs
only once a distinct, permitted approver is bound —
requester-as-approver and an under-permissioned approver both 403 before
the vendor; the auto-allowed shape (`block_sender`, whose reverse
`unblock_sender` is low-impact/`automatic`) runs with no approver at
tier L3 with confidence above the floor, via a capturing adapter
monkeypatched into the live registry exactly as the forward suites stub
`EXECUTOR_REGISTRY`.

## Negative controls (run on the committed tree, then restored)

**Credential resolution severed** (`params = resolve_params(vendor_id,
…)` replaced with `params = {}` in
`services/actions/app/services/undo.py`):

```
FAILED tests/test_action_undo_route.py::TestApprovalGoverned::test_a_bound_approver_releases_the_reversal
E       AssertionError: assert 'undo_failed' == 'rolled_back'
```

The break produced an honest *failed undo*, not a fake success — the
designed failure direction. Restored via `git checkout --`; the named
test passes again.

**Grading severed** (the graded requirement forced to `automatic` before
it is consulted):

```
FAILED tests/test_action_undo_route.py::TestApprovalGoverned::test_an_analyst_tier_reversal_waits_for_an_approver
E       AssertionError: assert 'rolled_back' == 'pending_approval'
```

With governance cut out, the undo ran unapproved and the test caught it.
Restored; all 13 pass.

## Gates (run pipelessly, exit codes echoed)

| gate | exit |
| --- | --- |
| `scripts/check_route_auth.py` | 0 |
| `scripts/check_route_tenant_scope.py` | 0 |
| `scripts/check_tenant_query_predicates.py` | 0 |
| `scripts/check_module_reachability.py` | 0 |
| `scripts/check_action_contract.py` | 0 |
| `scripts/check_mypy_baseline.py` (21 trees + unmanaged: "no tree got
worse") | 0 |
| `ruff format --check` / `ruff check` (services/actions, services/api)
| 0 / 0 |
| `scripts/export_openapi.py --check` | 0 |

Full suites at the final tree: `services/actions` **2145 passed, 10
skipped**; `services/api` **5603 passed, 272 skipped, 1 xfailed**.

## Scope notes

- The two `sync_detection_rule` arms are the only reversals that can
take per-call credentials today; every other executor's
`rollback(result)` is one-argument and is refused up front with the
reason rather than dispatched into a simulation that would read as an
undo. Widening an arm to `rollback(result, params)` makes it
dispatchable with no route change.
- A worker dying between the rollback claim and the settle leaves the
record visibly `rolling_back` — the same stranding semantics as a
forward `running` claim, and deliberately a visible state rather than an
invisible one.

---------

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-22 19:26:09 -08:00
Beenu Arora 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).
2026-11-22 18:57:11 -08:00
Beenu AroraandBeenu Arora 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>
2026-11-22 18:32:40 -08:00
Beenu Arora 922b0c641e feat(actions): revoke_file_share across Drive, Graph, Box and Dropbox (WS4.5) (#2006)
## What

WS4.5 of the gap-closure program. A leaked document's blast radius is
its sharing grants, and the product had no verb for them — no executor
touched Google Drive, OneDrive/SharePoint, Box or Dropbox permissions at
all. This adds **`revoke_file_share`**: one capability, four vendor
arms, under the full action-governance contract.

## Design

- **One executor, four arms** (`executors/fileshare.py`), vendor
selected by which credentials appear — the registry answers "who can
revoke a file share?" with four concrete vendors (`google_workspace`,
`m365`, `box`, `dropbox`).
- **New clients** (`clients/fileshare_clients.py`), each method shape
taken from the vendor's published reference (cited per class): Drive v3
permissions (`supportsAllDrives` on every call;
`sendNotificationEmail=false` on restores), Graph driveItem permissions
(restore via `invite` with `sendInvitation=false` / `createLink`), Box
collaborations + the file's `shared_link` field, Dropbox `sharing/*`
RPCs (`quiet: true` on restores). The Google client reuses the existing
Workspace JWT mint with a Drive-scoped token (domain-wide delegation
authorizes per scope list, so it must be a separate grant — one-line
seam in the existing client, subclass owns its scopes).
- **Scoping**: `revoke=grantee` (requires `grantee_email`) / `links` /
`all` — ownership always survives, per-vendor owner-role tables.
- **The contract's three properties**, per vendor:
1. **Capture before write** — none of these APIs has a permissions
recycle bin; the pre-write listing is the only record of what to
restore, and it travels in `rollback_data`.
2. **Read-back verification** — the grant list is re-read after the
revocation and the action **fails naming what it still sees** if a
revoked grant is still present. A 2xx on the DELETE is the vendor
accepting the request, not the estate changing.
3. **Real rollback** — restores through each vendor's own re-grant
shape; returns `False` on refusal. The one honest limit is stated, not
papered over: **Graph, Box and Dropbox mint a new URL when a sharing
link is re-created** (vendor fact, recorded in the clients), so a link
rollback restores access shape and the result says so; Drive's `anyone`
grant is an ordinary permission and restores exactly.
- **Governance**: ANALYST approval on both doors
(`APPROVAL_REQUIRED_ACTIONS` + the capability contract —
`test_approval_doors_agree` holds them level), blast radius MEDIUM,
declared verification probe with a registered independent verifier
(`_probe_revoke_file_share`), `dry_run` strips credentials so the vendor
sees zero requests, nothing-matched is a **failure**, never a silent
success.

## Testing

`test_revoke_file_share_vendor_arms.py` — **14 cases** through the real
executor, clients and builtins against stateful mock vendors:
capture-before-write is the observed request order; a frozen "lying
vendor" (204 on DELETE, grant still listed) fails the action; scoping
spares the owner; rollback restores per vendor (Graph invite without
mail, Box collaboration, Dropbox quiet add, Drive exact permission; link
restores logged as new-URL); missing `drive_id` on the Graph arm is
refused; the probe answers gone/present/unverifiable.

**Negative controls (applied, observed failing, restored):**
1. Skipping the read-back comparison on the Drive arm →
`test_a_lying_vendor_fails_the_action` fails (the 204 is believed).
2. `rollback` returning `True` without acting (the exact WS1.1 defect
shape) → 5 rollback cases fail.

## Ratchets & gates

Full actions suite **2,116 passed** · connectors suite 2,025 passed
(Capability enum gained the mirror member) · builtin count pin 168 →
**172** + 4 canonical pairs · `docs/audit/executor-arms.json`
regenerated via `check_executor_arm_count.py --write` (172 arms / 67
verbs / 40 vendors) · `check_action_contract` OK (180 contracts
coherent) · vendored contracts synced
(`sync_vendored_action_contracts.py`) · `check_module_reachability` OK ·
mypy baseline OK · ruff clean · claim matrix +1 GATED row, tallies
recomputed by the script.

## Could not verify

No live tenant for any of the four vendors — the arms are proven against
mock vendors through the real clients' request construction (the same
standard WS1.1's `sync_detection_rule` arms set). Request/response
shapes follow each vendor's published reference, cited in the client
docstrings.
2026-11-22 17:34:39 -08:00
Beenu Arora a42feeb57b feat(connectors): the M365 audit DLP.All stream is a real per-instance switch (WS4.2) (#2004)
## What

WS4.2 of the gap-closure program. The `m365_audit` module docstring
promised *"DLP can be re-enabled per-instance later via
`connector_config` once the analyst opt-in path lands"* while
`_DEFAULT_CONTENT_TYPES` was hard-coded and the constructor accepted no
such setting — the aspirational-comment family. A tenant who wanted
Purview DLP events through the audit trail had no switch to flip.

## The change

- `schema()` declares **`include_dlp`** (boolean, default **off**) with
help text naming the volume cost and the stricter `ActivityFeed.ReadDlp`
permission that sensitive-data details require.
- The constructor accepts it; coercion follows the house `_truthy` rule
(the `wiz` connector's): a boolean from the wizard and a string from a
hand-written instance row mean the same thing, and **an unparseable
value means off** — a collector that defaults to on when it cannot read
its own switch is a poll the tenant did not ask for.
- `content_types()` replaces direct `_DEFAULT_CONTENT_TYPES` iteration
in both the subscription-start and content-listing loops; a transport
seam lets tests drive the real fetch path.
- Docs page corrected: it claimed *"the connector subscribes to all five
content types"*, which was false before this change and would have been
misleading after; it now states the four-by-default / opt-in-fifth truth
and what `ActivityFeed.ReadDlp` does and does not gate.
- Docstring rewritten to state what is true (the 'later' promise is
gone, and a test pins that).

## Testing (failing test first)

- `test_m365_audit_dlp_toggle.py` — **15 cases, all red on the
pre-change tree** (schema field absent, constructor rejects the kwarg,
fetch path unobservable): schema declares the field defaulting off; the
docstring no longer says 'later'; default polls exactly the four
`Audit.*` types; five truthy spellings enable `DLP.All`; six
garbage/falsy values mean off; and the fetch path is observed **at the
wire** — the mock Management API records the real HTTP requests and the
content-type selection is read off them, not off a constant.
- **Negative control**: forcing the coercion to always-`False` fails the
four enable cases (`4 failed, 11 passed`); restored, `15 passed`.
- Full connectors suite: **2040 passed, 3 skipped**. `ruff` clean,
`check_mypy_baseline` OK, `check_claim_gate_matrix` 408 rows / 399
GATED, `readme_gates` OK.

## Artifacts regenerated (not hand-edited)

`scripts/connector_conformance.py`,
`scripts/generate_connector_catalog_fallback.py`,
`scripts/generate_connector_docs.py`, `pnpm marketplace:sync` (the
`coverage.md` timestamp diff is the normal regeneration artifact).
`plugins/m365-audit/plugin.yaml` mirrors the schema field.

## Claim matrix

One new GATED row (the switch reaches the wire), tallies recomputed by
the script: 408 rows — 399 GATED / 9 PARTIAL / 0 NO GATE.
2026-11-22 14:29:19 -08:00
Beenu Arora 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).
2026-11-22 11:51:29 -08:00
Beenu Arora 7d0c5f4187 feat(api): the normalized DLP finding — one vocabulary over three vendors (WS4.1) (#2003)
## WS4.1 — the normalized DLP finding: one vocabulary over three vendors

Sixth product item of the gap-closure program; WS4 begins (WS4.3's
data-handling strategy already shipped inside WS7.3).

### The gap

Three sources already deliver DLP alerts — Netskope's DLP feed, Purview
DLP/insider-risk alerts riding Defender's `alerts_v2` (Phase 0 verified
they arrive today, unfiltered, with `service_source` preserved), and the
M365 audit trail's `DlpRuleMatch` events — but each arrived as its
vendor shaped it, readable only through `raw_event`. Nothing existed
that a triage prompt, the data-handling strategy, or a console panel
could read in one vocabulary.

### The change

`app/services/dlp_finding.py`, mirroring the phishing-intake precedent
(frozen dataclass, per-source adapters, the two binding rules): **a
field that was not in the payload is empty, never invented**, and **the
vendor's own shape is the input**.

- **Netskope profile** — mapped from the vendor's own published
DLP-alert sample: `dlp_profile`/`dlp_rule`/`dlp_rule_severity`,
`object`/`file_size`/`local_sha256`, `app`/`appcategory`, `ext_labels[]`
as data classes, and the enforcement vocabulary (`block→blocked`,
`useralert→warned`, `alert→audited`, `allow→allowed`).
`destination_class` derives **only** from the explicit `managed_app`
fact — no fact, no claim.
- **M365 audit profile** — the O365 Management Activity DLP schema:
`PolicyDetails[].Rules[]` (policy, rule, severity, `Actions`),
`SensitiveInformationTypeName` collection across rules plus
`EndpointMetaData.SensitiveInformation`, the three metadata complex
types for file/destination/device, and the schema's own
`EnforcementMode` ladder (1=audit, 2–3=warn, 4=block, 5=allow).
- **Defender profile** — `alerts_v2` with Purview `serviceSource`s:
file/user/device evidence objects by `@odata.type`; the alert names the
policy but **not** the per-event outcome, so `enforcement` stays `None`
— a null, not a guess.
- **Dispatcher** keyed on connector type: a source without a profile
yields no finding rather than a best-effort parse.
- **Route**: `GET /alerts/{id}/dlp-finding` (`alerts:read`, tenant
predicate), answering `finding: null` honestly for non-DLP alerts.

### Evidence

- `test_dlp_finding.py` — **15 cases** over the vendors' own published
shapes (each fixture cites its source in-file): field mapping with
bystander selectivity, absent-stays-empty, the managed_app-only
destination-class rule, the EnforcementMode ladder, evidence-object
extraction, dispatcher keying, and the route's honest null.
Failing-first (collection error pre-module).
- **Negative control**: corrupting the Netskope `block→blocked` mapping
fails two cases; restored, 15/15.
- Full api suite: **5,572 passed**. Gates: route auth, route
tenant-scope, tenant predicates, module reachability, mypy baseline,
ruff, claim matrix (408 rows / 399 GATED — one lesson en route: a claim
cell containing raw `|` characters splits the markdown row, which the
matrix parser caught), tallies recounted, OpenAPI regenerated
(additive).

### Scope notes

- Consumption by the data-handling strategy's prompt context and the
console panel ride later WS4 items; this PR is the vocabulary and its
truth rules.
- WS4.2 (the real `DLP.All` per-instance switch, copying wiz.py's opt-in
boolean pattern) is next.
2026-11-22 10:00:45 -08:00
Beenu Arora a38c8ada41 feat(api): every open case has an owner and a next-action clock (WS7.4) (#2002)
## WS7.4 — every open case has an owner and a next-action clock
(completes WS7)

Fifth product item of the gap-closure program; the last WS7 item.

### The gap

A case could sit open with nobody — person or agent — responsible for it
and no time by which anything was due. Nothing surfaced that state: the
operations dashboard counted cases but never asked "who owns this and
when is its next action due", so an unowned, overdue case looked exactly
like a well-tended one.

### The change

- **Migration 167**: `aisoc_cases` gains `next_action_due_at` and
`owner_agent_run_id`, plus a partial index over the open caseload for
the attention query. An owner is a person (`assigned_to_id`, which
always existed) **or** an agent run.
- **Launch claims unowned cases**: `POST /cases/{id}/investigate` sets
the run as owner — claim-if-unowned only, with both no-person and
no-agent predicates in the UPDATE, so an agent never steals a case a
person holds and a second run never displaces the first. Ownership is
bookkeeping; the launch never blocks on it.
- **`GET /cases/attention`** (registered before `/{case_id}` for the
Starlette route-order reason): open cases that are unowned or overdue,
each row naming `owner_kind` (person / agent_run / none) and carrying
`overdue_seconds` as **null until due** — "not due yet" and "due exactly
now" are different facts, and a confident zero would blur them. This is
the operations dashboard's feed and what WS8.1's shift handoff will
consume.
- **PATCH surface**: `next_action_due_at` and `owner_agent_run_id`
settable and clearable, via `model_fields_set` so absence and
explicit-null stay distinct.

### Evidence

- `test_case_ownership_attention.py` — failing-first (4 red → 4 green):
owner-kind per row, null-until-due, tenant-scoped query, the claim SQL's
no-steal predicates, the PATCH fields.
- **Negative control**: removing the two claim predicates fails
`test_claim_sql_only_touches_unowned_cases`; restored, green.
- Full api suite: **5,557 passed**. Gates: migration numbering (167),
ORM parity, tenant predicates, route auth, route tenant-scope, module
reachability, mypy baseline, ruff, claim matrix (407 rows / 398 GATED),
tallies recounted, OpenAPI regenerated (additive).

### Scope notes

- Console rendering of the attention feed rides the WS8.1 PR (the shift
handoff consumes the same endpoint, so the UI lands once, against both).
- WS7 is complete: root-cause record (#1999), resolution contract
(#2000), five strategies (#2001), ownership + attention (this PR).
2026-11-22 07:59:10 -08:00
Beenu Arora 9939a8c10f feat(agents): five investigator strategies for the reference-service surfaces (WS7.3) (#2001)
## WS7.3 — five investigator strategies for the reference-service
surfaces

Fourth product item of the gap-closure program. Pure strategy-content
work: the registry, the depth gate and the selection machinery already
existed — Phase 0's verification said so — and these are the five
surfaces the brief names.

### The strategies

- **`ai-agent-misuse`** — the confused-deputy chase: the agent session's
timeline, the grants and tokens its identity holds, the identity
provider's view of that credential, egress matched against the suspect
tool calls, SIEM search over session id and tool names. Keyword-selected
(`prompt injection`, `mcp`, `agent session`, …) because AI misuse has no
honest ATT&CK anchor — an empty technique tuple rather than a stretched
mapping.
- **`data-handling`** — business-context triage of DLP hits (shared
shape with WS4.3): the user's **own** history for this data class and
destination, role/department and HR-relevant changes, prior dispositions
as precedent, the cloud audit trail of the repository, and the rule the
rationale states outright: *blocked means attempted, not leaked*.
- **`bec-payment-fraud`** — BEC rarely drops a payload, so the mailbox
is the crime scene: rules and delegations, session-vs-owner on the
accounts in the thread, OAuth read-grants, counterpart addresses and
lookalike domains through the SIEM.
- **`saas-oauth-abuse`** — the grant that survives the password reset:
application, scopes, consent times, every consenting account, and what
the app actually did with the access (T1528).
- **`cloud-exposure`** — who changed it, from where, with which
credential; what reached the resource while it was open; whether the
change is one of a series (T1530, T1190).

### Evidence

- Each strategy has its own selection row in `TestStrategySelection`
(failing-first: 5 red before the registry change, all green after);
technique match still outranks keywords; the new keywords are verified
non-colliding by the full 14-row selection matrix.
- `check_investigation_depth.py`: **15 strategies, 11 lake tools + 6
customer tools**, every expected pivot resolving to a real tool in both
directions, loop wired into the production path.
- **Negative control**: renaming `bec-payment-fraud`'s id fails exactly
its selection row; restored, all green.
- Full agents suite: **2,622 passed, 219 subtests**. Ruff, mypy
baseline, claim matrix (406 rows / 397 GATED), figure tallies recounted.

### Scope note

WS7.4 (case ownership + next-action due times) follows as its own PR,
completing WS7.
2026-11-22 06:33:33 -08:00
Beenu Arora ad84ff7354 feat(api): a case reaches resolved only through the resolution contract (WS7.2) (#2000)
## WS7.2 — a case reaches `resolved` only through the resolution
contract

Third product item of the gap-closure program. Consumes WS7.1's
root-cause record (#1999).

### The gap

`resolved` was a free transition. The PATCH gate checked only the status
ladder, and the survey found **three writers that never checked
anything**: the war-room chat "resolve" decision wrote
`status='resolved'` directly, an inbound Jira/ServiceNow webhook could
jump any open case straight to `resolved`/`closed`, and the hourly sweep
then auto-closed whatever arrived. Nothing required containment to have
been verified, eradication/recovery to be recorded, a root cause to
exist, or the customer to have been told.

### The change

**One shared checker** — `case_resolution.resolution_gaps`, the way
`case_status` is the one vocabulary — consulted by every writer:

- **PATCH** `… → resolved` refuses with a 422 listing every unmet
requirement, written for the analyst who reads it in the console toast.
- **War-room resolve** becomes a refusal note carrying the gaps; no
status write.
- **Inbound ITSM**: a vendor-side resolve/close that fails the contract
lands as `contained` with the gaps in the system note — a webhook cannot
be 422'd, but it must not be the door that skips the contract.

**The contract** (each requirement toggleable): containment verified by
a named probe/action reference *or* waived with a reason; eradication
and recovery recorded; root cause **determined or undetermined** — a
`hypothesis` is refused in those words, which is WS7.1's statuses doing
their job; at least one affected entity **derived from the case's own
rows** (observable graph + linked alerts' affected-* arrays), never
self-attested; customer notified with channel and time together.

**Off by default per tenant** (migration 166: `case_resolution_policies`
+ `case_resolution_facts`, RLS on both; no policy row = no enforcement —
rule 14). Policy writes take `settings:write` (an analyst records facts;
an admin decides whether resolve is gated); the write-surface ratchet
gains a two-tier accounting for exactly this distinction. The policy
routes register **before** `/{case_id}` because Starlette matches in
registration order — a literal segment placed after it is swallowed as a
case id.

**Surfaces**: `GET/PUT /cases/{id}/resolution` (facts, with
verified-requires-reference / waived-requires-reason /
notification-channel-and-time enforced at write), `GET
/cases/{id}/resolution/gaps` (the console's Resolve pre-flight — the
same checker the gate runs, so the answer cannot drift from the
refusal), `GET /cases/{id}/resolution-summary` (customer-facing markdown
from persisted rows only; hypotheses stay labelled; absent facts say
"not recorded"), and the evidence bundle's new optional `resolution`
section (schema 1.0 → 1.1, present only when rows exist).

### Evidence

- `test_case_resolution_contract.py` — **16 cases**: the pure gap
computation names every requirement; a hypothesis does not satisfy;
toggles work; facts validation enforces its conditionals; all three
writers driven through their real functions with the checker answering
both ways.
- `tests/isolation/test_case_resolution_live.py` — live Postgres through
the DML-only role: the opt-in default is the real absent-row state;
one-per-tenant policy and one-per-case facts are unique-constraint
behaviour; the derived entity count is JSONB arithmetic over the real
schema; RLS hides both tables across tenants. Verified twice locally
against a chain-migrated Postgres (164 migrations incl. 166); wired into
`integration.yml` with the skip-guard.
- **Negative control**: forcing the checker to answer no-gaps fails
`test_everything_missing_names_every_requirement` and
`test_a_hypothesis_does_not_satisfy_root_cause`; restored, 16/16.
- Full api suite: **5,553 passed**. Gates: migration numbering (166),
ORM parity, tenant predicates, route auth, route tenant-scope, module
reachability, mypy baseline, ruff, claim matrix (405 rows / 396 GATED),
figure tallies recounted, OpenAPI regenerated (additive). Semgrep over
the touched files: the single finding is the pre-existing baseline
f-string in `_apply_status_to_case`, not this diff — net new findings:
0.
- Two ITSM test fakes taught the honest no-policy state (`fetchone() ->
None`) — a bare MagicMock read as a truthy policy row made of mocks.

### Scope notes

- WS7.3 (new investigator strategies) and WS7.4 (case ownership + due
times) follow as their own PRs.
- The auto-close sweep needs no change: it only moves `resolved →
closed`, and entry into `resolved` is now governed at every door.
2026-11-22 05:01:03 -08:00
Beenu Arora 82280188f0 feat(api): the case root-cause record — evidence-backed, or honestly not (WS7.1) (#1999)
## WS7.1 — the case root-cause record: evidence-backed, or honestly not

Second product item of the gap-closure program (order per the brief:
Phase 0 → WS1.1 → WS7). One item, one PR; WS7.2 (the resolution
contract) follows separately and consumes this record.

### The gap

The only root-cause artifact anywhere was `root_cause_hypothesis` — a
free string on the forensic agent's run state, rendered as-is into the
report and the console. Nothing distinguished "we walked the chain back
to the 09:02 delivery, here is the ledger entry" from "the model wrote a
plausible sentence", and the post-mortem had **no root-cause section at
all**.

### The change

- **Migration 165**: `case_root_cause_records` (one per case by `UNIQUE
(tenant_id, case_id)`) + `case_root_cause_citations`, RLS on both in the
migration-154 shape. Deliberately **not** named `root_cause_findings` —
migration 152 already uses that for fusion's unrelated cross-vendor
grouping.
- **The contract, service-enforced**
(`app/services/case_root_cause.py`):
  - `determined` requires **at least one cited event**;
- every citation names an Investigation Ledger entry by **`(run_id,
seq)`** — the ledger's own stable address (`investigation_events` is
`UNIQUE (run_id, seq)`; the row UUID is minted at write time and is
nobody's reference) — and must **resolve**: naming a pair the ledger
does not hold is refused with the shortfall counted;
  - `undetermined` must name the missing telemetry;
  - `hypothesis` is stored as the unverified lead it is.
- **Routes**: `GET`/`PUT /cases/{id}/root-cause`
(`cases:read`/`cases:write`), explicit tenant predicates on every
statement (the cases-family convention), refusals as 422s written for
the analyst who sees them in the console toast. The write route is
registered in the authorization-surface ratchet.
- **Post-mortem**: a new root-cause section that **labels a hypothesis
as a hypothesis**, names missing telemetry for `undetermined`, and
renders an honest "no root-cause record" absence — never synthesized
from the agent's prose.

### Evidence

- `services/api/tests/test_case_root_cause.py` — 11 cases through the
real endpoint handlers (validation rules, ledger-resolution refusal
naming the shortfall, 404/422 shapes, all four post-mortem states).
- `tests/isolation/test_case_root_cause_live.py` — live Postgres through
the DML-only `aisoc_app` role: the one-per-case upsert **replaces rather
than duplicates**, citations resolve against real `investigation_events`
rows, the status vocabulary is a DB CHECK, and RLS hides one tenant's
record and citations from the other. Fails at setup on the pre-change
tree (no tables). Wired into `integration.yml` with the established
skip-guard pattern and added to the migration-paths trigger list.
- **Negative control**: disabling the determined-requires-citation rule
fails `test_determined_requires_at_least_one_citation` and
`test_contract_violations_are_422_with_the_rule_named`; restored, 11/11.
- Full api suite: **5,535 passed, 272 skipped**. Gates: migration
numbering (165 claimed clean), ORM parity, tenant predicates, route
auth, route tenant-scope, mypy baseline, ruff, claim matrix (404 rows /
395 GATED), readme figure tallies recounted, OpenAPI regenerated
(additive: +152 lines).

### Claim row added

"A case's root cause is an evidence-backed record: determined requires
at least one cited event, every citation resolves to a ledger entry,
undetermined names the missing telemetry, and the post-mortem labels a
hypothesis as a hypothesis" → GATED on the api unit job + the new
live-Postgres integration step.

### Scope notes

- The forensic agent's `root_cause_hypothesis` prose is deliberately
untouched — it enters the record only when promoted, as `hypothesis`.
- Auto-populating the record from the investigator's walk-back (story
links → graph → lake) and consuming it in the resolution contract are
WS7.2's scope, where the three status writers that bypass the PATCH gate
(war-room resolve, inbound ITSM webhooks, the auto-close sweep) get one
shared checker.
2026-11-22 03:38:50 -08:00
Beenu Arora fe8fd3b541 fix(actions): sync_detection_rule reaches its vendor, verifies by read-back, and rolls back (WS1.1) (#1998)
## WS1.1 — `sync_detection_rule` reaches its vendor, verifies by
read-back, rolls back for real

First product item of the gap-closure program, after Phase 0 (#1997).
One item, one PR.

### The defect

`SplunkSyncDetectionRule` described creating a Splunk saved search and
delegated to `SyncDetectionRuleExecutor`, which **only ever built an
Elastic client from `elastic_url`** — with Splunk credentials the call
fell straight to the simulation branch, and
`SplunkClient.create_or_update_correlation_search` sat in the tree with
**no caller at all**. `rollback` logged `"would disable rule"` and
returned `True` without acting. The contract honestly declared
`has_verification_probe=False` with a `verification_gap`, because no
client exposed a read of the stored definition.

### The change

- **One executor per vendor arm.** `SplunkSyncDetectionRuleExecutor`
drives the Splunk client; `ElasticSyncDetectionRuleExecutor` keeps the
Elastic behaviour (`SyncDetectionRuleExecutor` stays as a subclass alias
so existing imports keep the arm they always had). A new
`ElasticSyncDetectionRule` builtin registers the Elastic arm, which
previously had no adapter of its own.
- **Prior state captured before every write** into `rollback_data`
(content only, never credentials), so the reverse restores a known state
rather than guessing.
- **Read-back verification**: the stored definition is compared against
the normalized intended content, and a mismatch **fails the action
naming the differing fields**. Existence alone would be the wrong check
— the contract's own words: this verb's failure mode is a rule that
saved with *different* content.
- **Real rollback**: restores the captured prior version, deletes a rule
the action created, and returns `False` when the vendor refuses. The
adapter gained a rollback bridge that threads caller-supplied
credentials and passes the captured state through the live result's
`details`.
- **Clients gained their read half**: `SplunkClient.get_saved_search` /
`delete_saved_search`, `ElasticClient.get_detection_rule` /
`delete_detection_rule`, plus a `transport` seam on both so the arms are
testable against a mock vendor.
- **Contract declares the probe** (`has_verification_probe=True`, gap
text removed) and `_probe_sync_detection_rule` is registered in the
post-action verifier as an **independent** read-back —
`test_verification_coverage.py` requires every declared probe to have a
registered verifier.
- **Latent client bug fixed on the way**: the Splunk session login
passed `verify=` to `client.post()`, which httpx does not accept (the
`AsyncClient` already carries it). The transport threading exposed it to
the type checker.

### Evidence

- New `services/actions/tests/test_sync_detection_rule_vendor_arms.py` —
**11 cases** through the real builtins against mock Splunk and Kibana
servers: the arm reaches the right vendor and issues a read-back;
tampered storage fails the action; prior definition captured and
restored; a created rule is deleted on rollback; a vendor refusal
returns `False` rather than `True`; `dry_run` touches no vendor; the
contract declares the probe.
- **Negative control:** reverting the Splunk adapter to the borrowed
Elastic executor makes
`test_the_splunk_arm_reaches_splunk_and_reads_back` fail with **zero
Splunk requests** observed by the mock vendor. Restored, 11/11 pass.
- Full actions suite: **2,100 passed, 12 skipped** (ratchets updated:
builtin count 167 → 168, canonical pair set gains `("elastic",
"sync_detection_rule")`).
- Gates run locally: `check_mypy_baseline.py` OK (no tree got worse) ·
`ruff check services/ scripts/` clean · `ruff format --check .` 3,077
files formatted · `check_claim_gate_matrix.py` OK (403 rows, 394 GATED,
9 PARTIAL, 0 NO GATE) · `check_action_contract.py` OK ·
`check_module_reachability.py` OK · `check_competitor_names.py` OK ·
`check_attribution.py` OK.

### Claim row added

"A SIEM rule sync reaches the vendor it names, captures the prior
definition before every write, verifies the write by content read-back,
and rolls back to the captured state" → GATED on `ci.yml :: Python —
Tests` (actions).

### Not verified locally

No live Splunk ES or Kibana tenant exists here, so the wire behaviour is
asserted against each vendor's documented REST shapes through a mock
transport — the same posture the repo's other vendor-client tests take.
What is proven live is the executor contract: arm selection, prior
capture, read-back comparison, and rollback outcomes.
2026-11-22 01:21:13 -08:00
Beenu Arora 71360e1eb3 release: v23.6.1 (#1994)
## v23.6.1 — the tenant-isolation patch

Release mechanics only; the fixes are already on `main`.

### What it carries
- **GHSA-mpxh-f6q6-6w8g** (medium, reported by @benchmeister):
cross-tenant read on the agents service's investigation run routes —
fixed in #1993, with a negative-control suite (9/11 fail on the pre-fix
tree). The advisory publishes naming **23.6.1** as patched once this tag
exists.
- **Vendor-evidence boundary note** (#1991, fixed in #1992): live vendor
records no longer described to the model as stale knowledge-base
documents.

### Mechanics
`VERSION` 23.6.1 · CHANGELOG `[23.6.1]` frozen · `RELEASES.md` TL;DR +
What's-new · README badge · chart **7.25.1** / `appVersion` v23.6.1
(appVersion-only move) · `apps/web/package.json` · scoreboard refreshed
(0.97, pinned `a52a55a6`) · llms/openapi regenerated · changelog-frozen,
single-version, readme-gates, scoreboard, competitor gates green
locally.

**No breaking changes.** Neither `stable` channel moves. Tag goes on the
merge commit; release.yml publishes; registry verified after.
2026-11-21 18:40:30 -08:00
Beenu Aroraandbeenuar ee76d4b943 release: v23.6.0 (#1989)
## v23.6.0 — the console-capability minor, community end to end

Two analyst-facing features from @knowlet and four defect fixes from
@alexmateescu's continuing review, every one landed with authorship
preserved. This PR is release mechanics only.

### Features
- **Per-device minimum severity for Web Push**
([#1979](https://github.com/beenuar/AiSOC/pull/1979), carry of #1978):
each device sets its fused-alert risk floor; approvals and on-call
hand-offs bypass by design; legacy subscriptions unchanged;
omitted-vs-empty topics handled correctly on renewal.
- **Operations posture drilldown**
([#1988](https://github.com/beenuar/AiSOC/pull/1988)): every posture
counter and severity/status segment opens the matching alert grid with
URL-stable filters; two bounded opt-in API filters on the authenticated
tenant scope.

### Fixes (11 distinct defects)
- Triage consumer commits **per-partition watermarks** instead of the
Kafka fetch position; quiet topics commit on a timer
([#1984](https://github.com/beenuar/AiSOC/pull/1984)).
- Alerts **page-size reaches the server** (`pageSize` vs `page_size`),
tiles open the list they count, connector tile counts the inventory
([#1985](https://github.com/beenuar/AiSOC/pull/1985)).
- Identity-privilege resolver **honours never-raises** (`event_time`,
not a nonexistent field)
([#1986](https://github.com/beenuar/AiSOC/pull/1986)).
- Drift sentinel compares a **stable-core baseline** (migration 164);
drift now means a baseline field disappeared
([#1987](https://github.com/beenuar/AiSOC/pull/1987)).
- SOC Insights on real console tokens with bounded aggregates and
closed-vs-resolved honesty
([#1977](https://github.com/beenuar/AiSOC/pull/1977)).

### Mechanics
`VERSION` 23.6.0 · CHANGELOG `[23.6.0]` cut **including five entries
backfilled** for the carries and #1988, which shipped without them ·
RELEASES.md TL;DR + What's-new (11 defects here, 15 across three
releases) · README badge · chart `7.25.0`/`v23.6.0` ·
`apps/web/package.json` · scoreboard refreshed (0.97, pinned `833df002`)
· llms/openapi regenerated · changelog-frozen, single-version,
readme-gates, papers, competitor gates green locally.

**No breaking changes.** Neither `stable` channel moves. Tag goes on the
merge commit; release.yml publishes; registry verified after.

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-20 17:35:24 +11:00
Albert Hsieh 833df00209 Feat/operations alert posture drilldown (#1988)
## Summary

Make the SOC operations Alert posture counters and severity/status
breakdowns open the matching alert grid. Keep the URL and visible
filters consistent across chip removal, reload, and browser history, and
prevent a default saved view from replacing an explicit drilldown.

## 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

Contribution guidance:
[#353](https://github.com/beenuar/AiSOC/issues/353). This PR does not
close that onboarding issue; there is no linked feature request.

## Changes

- Link Total, New (24h), Critical open, and severity/disposition
segments and legends to the corresponding alert-grid filters. Preserve
the actual labels of statuses such as Escalated.
- Add opt-in `unresolved_only` and `created_within_hours` API filters.
They use the same unresolved predicate and `created_at` column as the
statistics endpoint. Tenant scope continues to come from the
authenticated principal.
- Share URL validation between server entry and client navigation.
Synchronize changed/cleared filters with the URL, preserve unrelated
query values and fragments, and read live query parameters when history
restores cached page props.
- Give explicit drilldowns, including Total and a cleared grid,
precedence over automatic saved-view defaults. Manual preset selection
remains available. Improve empty-state guidance and visible, unclipped
keyboard focus.
- Map the alerts client's `pageSize`, `startTime`, and `endTime` to
`page_size`, `event_since`, and `event_until`; test the actual outgoing
query names, including the responder queue's `pageSize: 100` call.
- Fix the dashboard test's Link mock to forward accessibility attributes
and the API test's assumption that SQLAlchemy expanding binds must be
tuples. Add regression coverage, five browser journeys, usage
documentation, generated OpenAPI changes, and a CHANGELOG `[Unreleased]`
entry.

Against `beenuar/main` this branch is 2 commits ahead and 0 behind,
based on `143c70616848432793e9e96e7669bcfb336b4d06` (v23.5.3). Head is
`a3f3a238334b0db302a7c31209b15291aad77220`. Both contribution commits
carry DCO sign-offs (`Signed-off-by: Albert Hsieh
<knowlet@users.noreply.github.com>`).

## Testing

- [x] Unit tests added / updated
- [ ] Integration tests pass locally
- [x] Manually tested (describe steps below)

The integration checkbox is left unchecked in this revision because the
author-reported real-PostgreSQL and full local API suite figures were
not re-run here (no Postgres on the review box). Full-stack startup and
pipeline jobs did complete successfully on the fork CI for this head, as
listed below. The browser journeys use synthetic intercepted API
responses.

### CI on fork head `a3f3a238` (knowlet/AiSOC)

Re-checked at 2026-11-19 15:53 UTC. All check runs for this SHA were
completed: 132 latest-per-name successes, 14 skipped, 2 cancelled, 1
neutral (`cubic · AI code reviewer`), 0 failed, 0 still running.
Combined status is success (CommitCheck). The two cancelled jobs are
`aisoc-sandbox · offline smoke (macos-latest)` and `Published on-ramp ·
registry install (macos-latest)`; their ubuntu-latest counterparts
succeeded. There is no pull request on `beenuar/AiSOC`; these checks ran
on draft [knowlet/AiSOC#13](https://github.com/knowlet/AiSOC/pull/13)
(base `knowlet/main` at `420c707f`, which is behind this branch's
merge-base).

Cited jobs from the fork PR body, all now completed success:

- [Web — Vitest smoke tests + coverage
gate](https://github.com/knowlet/AiSOC/actions/runs/44545907004/job/135637087486)
- [Web —
Build](https://github.com/knowlet/AiSOC/actions/runs/44545907004/job/135637087314)
/ [Web — Lint &
Type-check](https://github.com/knowlet/AiSOC/actions/runs/44545907004/job/135636267404)
- [Buyer
journey](https://github.com/knowlet/AiSOC/actions/runs/44545907378/job/135636269274)
- [Python —
Tests](https://github.com/knowlet/AiSOC/actions/runs/44545907004/job/135638459108)
(completed 2026-11-19 15:44:29 UTC)
- [docker compose up — full
stack](https://github.com/knowlet/AiSOC/actions/runs/44545907792/job/135636271961)
- [One real event through the real
pipeline](https://github.com/knowlet/AiSOC/actions/runs/44545907387/job/135636268721)

Internal stage counts inside those logs (for example 20/1 buyer-journey
totals or 10/10 smoke stages) were not re-read in this pass. Local web
vitest on this head was 130 files, 1,303 tests passed, which matches the
figure previously quoted from the web unit-test job.

### Local checks re-run on this head

Node 24, pnpm 8.15.1, `apps/web`; Python 3.12 and ruff 0.17.5 for the
API files:

- `pnpm run lint`: exit 0, 0 errors, 95 warnings. No warnings in new or
edited UI files. The two warnings in `apps/web/src/lib/api.ts` are on
unchanged lines 384 and 7782.
- `pnpm run type-check`: exit 0.
- `pnpm exec vitest run`: 130 files, 1,303 tests passed, including the
previously failing dashboard link test and all tests in
`AlertsDrilldown.test.tsx`, `api.alerts-list.test.ts`, and
`SavedViewsBar.test.tsx`.
- `ruff check` and `ruff format --check` on the two changed Python
files: pass.
- `pytest tests/test_alerts_tenant_isolation.py`: 19 passed.
- `python3 scripts/check_attribution.py --commits upstream/main..HEAD`,
`--diff-base upstream/main`, and `--text-file` on this body: OK.
- `python3 scripts/export_openapi.py --check`: `docs/openapi.yaml is up
to date`.
- Full `services/api` pytest and the author-reported 14 live
HTTP/PostgreSQL checks: not run.

<details>
<summary>Manual test steps</summary>

`next dev -p 3140` with browser-side mocks: `GET /api/v1/alerts/stats`
returned a fixed review fixture (total 128, new_last_24h 22,
critical_open 3, plus the severity/status maps below), `GET
/api/v1/alerts` returned one row chosen from the query string, and every
other `/api/*` request was answered 503 except branding/auth stubs. No
backend was running. "Failed to load saved views" on the alerts page is
from that 503, not from this change.

1. `/dashboards/operations` rendered the fixture counts. Accessible
names and hrefs matched Total, New (24h), Critical open, and the
severity/status bar+legend pairs. Focusing a Critical bar segment
produced a 2px solid outline with 2px offset, and the parent overflow
was `visible`.
2. Clicking Total, New (24h), Critical open, By severity Critical, and
By disposition False positive opened the Alerts tab with the expected
query and list request (`page_size`, `created_within_hours`,
`unresolved_only`, or `status` as appropriate).
3. Removing the 24h chip immediately dropped `created_within_hours` from
the URL (leaving `view=alerts`), issued
`/api/v1/alerts?page=1&sort=priority&page_size=25`, and kept the Alerts
tab. A reload stayed on `/alerts?view=alerts` with the chip still gone.
4. `/alerts?view=alerts&status=escalated&tag=one&tag=two#queue` showed
the Escalated label and chip. Removing the status chip left
`/alerts?view=alerts&tag=one&tag=two#queue`.
5. After removing `unresolved_only` from a critical-open URL, navigating
to SOC Operations and pressing Back returned
`/alerts?view=alerts&severity=critical` with the unresolved chip still
gone.
6.
`/alerts?view=alerts&created_within_hours=-50&status=new%26tenant_id%3Dother`
still opened the Alerts tab, but the list request was
`/api/v1/alerts?page=1&sort=priority&page_size=25`.
7. `/alerts` with no drill-down query kept the Entities tab selected.

Not checked: a live `make up` stack, or a conflicting default saved view
in the browser (that path is covered by component and CI journey tests,
but the review harness 503'd the saved-views API).

</details>

## Screenshots (if UI changes)

<img width="1600" height="1000" alt="image"
src="https://github.com/user-attachments/assets/17e4816d-5133-4ef1-a9c5-98afae6f5832"
/>
<img width="648" height="381" alt="image"
src="https://github.com/user-attachments/assets/5069a5fe-e3dc-4dbc-93d2-1c28264badb1"
/>


## 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 (web vitest 1,303/1,303
and the 19 tenant-isolation tests; the full local API suite was not
re-run)
- [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)

This PR changes console navigation and alert-list filtering. It does not
touch any substrate, orchestrator, playbook, detection, prompt, RAG or
eval-input path covered by the template, so before/after eval runs are
not applicable.

- [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: Albert Hsieh <knowlet@users.noreply.github.com>
2026-11-20 16:14:03 +11:00
Beenu AroraandAlexandru Mateescu e2a386dd95 fix(console): page size reaches the server, tiles link to their queue, connector count matches the page (carry of #1981 by @alexmateescu) (#1985)
Carry of #1981 by @alexmateescu, authorship preserved on the commit
(fork branches cannot be maintainer-rebased, and this one needed in-tree
fixes no rerun could produce: a stale committed OpenAPI spec, a
live-test kwargs pin, and a CodeQL finding on the new code).

## What ships (unchanged from #1981)
- **Page size reaches the server**: the console sent `pageSize`, a name
FastAPI discards as undeclared, pinning every queue page to the server
default of 25; `alertListParams()` now maps it to `page_size`.
- **Dashboard tiles link to their queue**: Active/Critical tiles
deep-link with the new `unresolved_only` server filter (same
`alert_status.unresolved_filter` the tiles count with), so a clicked
number opens the list that produced it.
- **Connector count matches the page**, with
`ConnectedSourceCount.test.tsx` extended.

## What the carry adds
- `docs/openapi.yaml` regenerated — `unresolved_only` changes the
published API surface and `check-openapi` compares the committed spec
(`export_openapi.py --check` passes).
- `test_alert_list_search_filter.py`: `unresolved_only: False` added to
the explicit kwargs — the file calls the handler as a plain function, so
an omitted parameter receives the truthy `Query(...)` object and
silently applies the filter (the failure the fork PR's Migrations job
showed; the file's own docstring warns of exactly this).
- `api.ts`: the pass-through loop iterates a compile-time-enumerated key
set instead of `Object.entries` over the caller's object, so no written
property name derives from runtime input — resolves the new
high-severity `js/remote-property-injection` CodeQL alert from the fork
PR.
- Import order and an Optional-consumer guard in the timer committer
(ruff + the mypy `union-attr` baseline gate); the file stays
byte-identical to #1984's so the two carries cannot conflict on it.

Verified locally: web type-check clean; 196 lib/dashboard + 150 alerts
vitest tests pass; ruff format + check clean; OpenAPI check passes.

Merge order: after #1984.

Closes #1981.

Co-authored-by: Alexandru Mateescu <alexmateescu@users.noreply.github.com>
2026-11-20 11:11:24 +11:00
Beenu Aroraandbeenuar 143c706168 release: v23.5.3 (#1975)
## v23.5.3 — connector data completeness, community end to end

Both defects were reported with failing tests by @pavancharak **against
the shipped v23.5.2 tag**
([#1970](https://github.com/beenuar/AiSOC/issues/1970),
[#1971](https://github.com/beenuar/AiSOC/issues/1971)); both fixed by
first-time contributor @Varshith-Kali in
[#1973](https://github.com/beenuar/AiSOC/pull/1973). Fixing `main` fixes
no tag — deployments pulling v23.5.2 keep silently losing rows on these
paths until a release carries the fix, which is the bar for this patch.

### What the tag gets
1. **Checkpoint cursors compare instants, not text** — `…10:00:00.500Z`
no longer drops against a `…10:00:00Z` cursor (`.` sorts before `Z`),
offset-written cursors no longer drop later rows, the staged cursor
names the newest instant with id tie-breaks, and an unparseable time
keeps its row rather than losing it.
2. **Huntress / Cisco Secure Endpoint / Sophos Central stop losing
scheduler-skipped intervals** — each persists an event-time cursor
(Huntress on `sent_at`, preserving raise-once), overlaps one poll
interval so a single skipped run is covered before any cursor exists,
and skips are logged (`connector.scheduler.poll_skipped`). Overlap
re-reads drop against the cursor: a re-request, never a duplicate or a
loss.

**Verified, not asserted:** 449 connector tests pass on the fix; the new
instant-ordering suite fails 5/8 against the pre-fix tree.

### Mechanics
`VERSION` 23.5.3 · CHANGELOG `[23.5.3]` cut (entries landed in #1974) ·
RELEASES.md TL;DR + What's-new · README badge · chart `7.24.3`/`v23.5.3`
· `apps/web/package.json` · scoreboard refreshed (0.97, pinned to
`420c707f`) · llms/openapi regenerated · changelog-frozen,
single-version, readme-gates, papers, competitor gates green locally.

**No breaking changes.** One observable note: the three converted
connectors emit batches oldest-first by event time rather than page
order. Tag goes on the merge commit; release.yml publishes; registry
verified after.

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-19 22:41:06 +11:00
Beenu Aroraandbeenuar 7fcfa5d77f release: v23.5.2 (#1968)
## v23.5.2 — undo the silent revert the previous two tags shipped

A stale-base push serialized an old tree over `main`: the
[#1933](https://github.com/beenuar/AiSOC/pull/1933) merge (an unrelated
cases fix) quietly rolled back
[#1904](https://github.com/beenuar/AiSOC/pull/1904)'s security work. So
**v23.5.0 and v23.5.1 shipped a fail-open threat-actor attribution
enforcer** (unset token → warn once, allow every caller) while both
releases' notes described 503 — and **managed provisioning again
published the known-password demo admin** into every promoted tenant.

### Fixed (both already merged; this PR is release mechanics only)
1. **Demo identity out of provisioning, structurally**
([#1966](https://github.com/beenuar/AiSOC/pull/1966), @knowlet): starter
content only, never a login; `_ensure_user` refuses non-canonical
tenants before any DB read; **migration 163** retires already-published
demo admins (deactivated, sessions revoked, sentinel hash, role
demoted); live weakening-detector pins both layers.
2. **Fail-closed enforcer restored**
([#1967](https://github.com/beenuar/AiSOC/pull/1967)): unset token → 503
unless `AISOC_THREATINTEL_ALLOW_UNAUTHENTICATED=1`; reverted tests and
the deleted compose token gate restored (now two detectors for one
contract); Dependabot #1928's realtime OTel bump re-applied.

Window audited for the revert signature: exactly two bad merges (#1933,
#1961), both remediated; the push tooling now refuses stale worktrees.

### Mechanics
`VERSION` 23.5.2 · CHANGELOG `[23.5.2]` cut **including the #1966 entry
it shipped without** · RELEASES.md TL;DR + What's-new · README badge ·
chart `7.24.2`/`v23.5.2` · `apps/web/package.json` · scoreboard row
refreshed against a fresh live run (0.97, sha pinned to the pre-release
tip) · llms/openapi regenerated · changelog-frozen, single-version,
readme-gates, papers, competitor gates green locally.

**No breaking changes.** One behavioural note: migration 163 retires
`demo@example.com` admin rows in managed tenants (canonical demo tenant
untouched). Tag `v23.5.2` on the merge commit; release.yml publishes;
registry verified after.

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-18 15:54:14 -08:00
Beenu Aroraandbeenuar 5f64fb73d9 release: v23.5.1 (#1962)
## v23.5.1 — make v23.5.0's release note true

v23.5.0's notes described the **"sixteenth secret"** — the threat-actor
attribution service token — as generated and wired to both ends. On the
tag it was **neither**: `ensure_env` never minted
`AISOC_THREATINTEL_SERVICE_TOKEN`, and compose delivered it only to the
API, not to the `threatintel` container that *enforces* the fail-closed
gate nor the `agents` container that *sends* it. So a fresh `make up`
answered **503 for every `/api/v1/actors/*` call** with every secret
apparently in place — a dead feature inside the shipped artifact, and a
published claim that wasn't true. This patch fixes that, which is the
bar the standing rule sets for a release.

### Fixed (3 defects, all found by exercising the shipped tag)
1. **Threat-actor attribution token generated and wired** — `ensure_env`
mints it (generated-secret count 15 → 16, reflected in `.env.example`
and the documented count) and compose forwards it to the enforcer and
the caller. Pinned by `tests/test_threatintel_token_wiring.py`, which
discovers the readers from source so the generator and the wiring can't
drift apart again.
2. **`GET /cases?status=open` matches the open caseload again** — it
string-matched the write-path alias literally and returned zero rows,
leaving the console's "add to existing case" picker permanently empty.
Now expands through `case_status.OPEN_STATUSES`. Pinned by
`services/api/tests/test_cases_open_alias.py`.
3. **Documentation portal builds again** — a generated connector page
shipped `<your subdomain>.huntress.io`, which MDX parses as an unclosed
tag, failing every GitHub Pages deploy for six days while per-PR CI
stayed green. Generator now escapes it; pinned by
`tests/test_connector_docs_mdx_safe.py`.

The code for all three already merged
([#1961](https://github.com/beenuar/AiSOC/pull/1961),
[#1960](https://github.com/beenuar/AiSOC/pull/1960)); this PR is the
release mechanics only.

### Release mechanics
`VERSION` 23.5.1 (single-source gate green) · CHANGELOG `[23.5.1]`
section dated 2026-11-18 · RELEASES.md What's-new + TL;DR with the
3-defect count · README badge · chart `7.24.1`/`v23.5.1`
(appVersion-only; stable channels hold) · `llms.txt`/`openapi.yaml`
regenerated from VERSION · changelog-frozen, readme-gates, papers
--check, competitor gates green locally.

**No breaking changes.** Tag `v23.5.1` goes on the merge commit;
release.yml publishes images; registry verified after.

---------

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-17 23:55:46 -08:00
Beenu Aroraandbeenuar 164b668eb7 release: v23.5.0 (#1958)
## v23.5.0 — the community-wave release

Cut per the standing close-out after the board reached zero: every open
PR and issue dispositioned, GHSA-grv9-vcqp-f37v fixed and **published**,
main green on everything graded.

### In the box
- **Three new EDR connectors** (ESET PROTECT, WithSecure Elements,
Vectra AI) and **certificate authentication** for Entra ID / M365 audit.
- **Credential isolation for the LLM gateway** (#1954): the platform's
provider key can no longer be lured to a tenant-selected endpoint by a
broken vault token.
- **Four governed security carries** from an external review: MFA verify
throttled, actions require a principal by default (**the one breaking
change** — env opt-out documented), threat-actor API fails closed with
the sixteenth generated secret wired to both ends, demo identities
refused outside dev.
- **Entity hosts** (#1950) and **related cases** (#1952), both to their
reporters' designs; **Wazuh event identity** (#1951) so repeat
occurrences count.
- Prometheus finally scrapes everything it points at; Kafka consumers
survive broker outages; analyst FP verdicts are durable suppression
while AI verdicts are not.

### Release mechanics in this PR
`VERSION` 23.5.0 (single-source gate green) · CHANGELOG section cut
dated 2026-11-18, **plus four entries restored that the week's
merge-conflict cascades had silently dropped** (audited every merge
since v23.4.0 for lost additions) · RELEASES.md TL;DR with the counted
formula (**30 defects here, 34 across three**) · README badge · chart
`7.24.0`/`v23.5.0` (appVersion move; stable channels hold on v22 by
design) · technical guide v1.4 re-rendered with the papers digest gate
green · `llms.txt`/`openapi.yaml` regenerated from VERSION.

Tag `v23.5.0` goes on the merge commit; release.yml publishes images and
the GitHub release; registry verified after.

---------

Co-authored-by: beenuar <beenuar@users.noreply.github.com>
2026-11-17 16:04:53 -08:00
Albert Hsieh 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>
2026-11-17 09:58:55 +08:00
Albert Hsieh 63767164f5 feat(cases): expose related cases with shared evidence
Match exact typed observables as well as shared alert IDs within the authenticated tenant. Expose bounded, ranked evidence in the case workspace with explicit loading, empty, error, retry, and truncation states.

Verify the route against migrated PostgreSQL under the runtime role, cover the console transport and navigation, and document the response contract.

Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com>
2026-11-17 11:21:02 +08:00
Beenu Aroraandbeenuar 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>
2026-11-16 10:24:47 -08:00
Beenu Arora 520b94b7b1 Merge pull request #1905 from beenuar/carry/ms-cert-auth
feat(connectors): certificate auth for Entra ID and M365 audit (carries #1897)
2026-11-15 22:31:49 -08:00
AJ 5d4f68ed7c feat(connectors): certificate auth for Entra ID and M365 audit
Optional certificate_pem / certificate_thumbprint / private_key_password
fields; token request sends an RS256 client_assertion (x5t, x5t#S256) via
shared ms_cert_auth helper. client_secret is now optional; exactly one
method is required, certificate wins if both. Secret auth unchanged.
2026-11-15 18:26:51 +00:00
Asish Kumar 38380bf9db feat(connectors): add a WithSecure Elements connector
Adds `withsecure_elements`, an EDR connector for WithSecure Elements
Broad Context Detections (BCDs), read through the Elements API. Part of
the connector wishlist in #356.

Authentication is the documented OAuth2 client credentials flow: the
API client's ID and secret are exchanged with HTTP Basic at
POST /as/token.oauth2 for a token scoped to connect.api.read only. The
host is fixed at api.connect.withsecure.com, so the vaulted secret can
only ever reach WithSecure, and every request carries the User-Agent the
API requires. The token is cached until a minute before expires_in; a
cached token refused with 401 is exchanged once more, while a token
issued for that same request and refused fails the poll rather than
looping. An optional organization ID (validated as a UUID, refused with
422 otherwise) lets a partner account read a customer organization.

The poll reads GET /incidents/v1/incidents by createdTimestampStart /
createdTimestampEnd, oldest first, 50 a page, and follows nextAnchor
through the shared read_token_pages. A BCD is updated whenever a
detection joins it, so windowing on creation raises each BCD once. The
window opens at the persisted createdTimestamp cursor, the same
event-time watermark eset_protect and wazuh use, so a poll cut short by
the page bound or a run of failed polls is caught up. A refused or
unreachable opening request raises; a later page failing keeps what was
read. BCDs WithSecure closed itself as merged, autoFalsePositive or
autoAcceptedBehavior are dropped. `archived` is deliberately not
filtered on, since WithSecure does not document when a BCD is archived.

Each BCD is enriched from its newest 100 detections
(GET /incidents/v1/detections) and the devices they name
(GET /devices/v1/devices): process, command line, hash (labelled SHA-1
or SHA-256 only when it has that shape), user, host, addresses, OS, and
every MITRE ATT&CK technique and tactic. The host columns always
describe the device the alert is filed on. The detections and device
records ride on the BCD so a replay normalizes the same; each detection
is stored without its open-ended activityContext, which keeps the event
bounded, since an event ingest refuses would be re-read on every poll.
Lookups go to the most severe BCDs and each BCD's own host first, and
are bounded (50 BCDs, 50 devices) so a whole poll stays well under
WithSecure's documented 300 requests a minute for EDR endpoints. A 429,
or a credential refused part-way through, stops the lookups; a failed
lookup costs the context, never the BCD.

WithSecure's five severity levels each keep their own tier, critical
included; a BCD without one falls back to riskLevel, whose top level
severe maps to critical. Anything undocumented carries no severity.

ocsf_classes.go files withsecure_elements at 2001 Security Finding.
Adds the plugin manifest, a docs page with setup, rate limit and
troubleshooting notes, a CHANGELOG entry, the checkpoint-contract entry,
and the regenerated connector count, types, docs, sidebar, catalog
fallback, conformance matrix, marketplace index, llms.txt and corpus
stats.

Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
2026-11-15 17:20:03 +05:30
Beenu Arora a291ac8e67 Merge pull request #1885 from officialasishkumar/feature/eset-protect-connector
feat(connectors): add an ESET PROTECT connector
2026-11-14 07:44:00 -08:00
Asish Kumar a01e332dfe feat(connectors): add an ESET PROTECT connector
Adds `eset_protect`, an EDR connector for ESET PROTECT detections read
through the ESET Connect API. Part of #356.

Auth and where requests go
- An OAuth2 password grant for a dedicated API user (the ESET Connect
  model; the user needs the Integrations toggle and must have signed in
  once). Only the password is vaulted.
- The region is a select of ESET's five (eu, de, us, ca, jpn), not a URL,
  so the credential and the bearer token only ever reach that region's
  *.eset.systems hosts. An unknown region is refused at construction.
- The token is cached until a minute before `expires_in`. A token reused
  from an earlier request and refused with 401 is exchanged once more; a
  token issued for the request and refused fails instead of looping.

Reading the window
- GET /v1/detections with startTime/endTime (second precision, endTime
  exclusive) and pageSize=1000, following nextPageToken through the shared
  read_token_pages until it is empty. The exact window is applied to
  occurTime, closed at the moment the read began.
- A refused or unreachable opening request raises, so a failed poll is not
  read as a quiet estate; a later page failing, including a refused token
  re-exchange, keeps the pages already read.
- ESET answers a query it cannot finish in 30 s with 202 and a
  response-id header. The identical request is re-sent with that header
  every 5 s, within ESET's own 120 s limit.

The host behind a detection
- A detection names its device only by UUID. Distinct, well-formed UUIDs
  are looked up through GET /v1/devices:batchGet, 50 per request and 500
  per poll, for the hostname, public address and operating system. The
  record rides on the detection under `device`, so a replay normalizes to
  the same host. A failed batch costs hosts, never detections; a 429 or a
  batch still pending after 120 s stops the lookups for the poll.

Normalization
- Title, circumstances, category, object name/type/URL, SHA-1/SHA-256,
  process path, user, device id and the actions ESET took. Network
  detections are oriented by the recorded direction, so an inbound peer is
  the source; without a direction the host fills src_ip and the peer is
  kept as remote_ip.
- Severity: diagnostic and informational -> info, low/medium/high -> their
  own tier. ESET's ladder stops at high, so nothing is raised as critical,
  and an unspecified level carries no tier.
- ocsf_classes.go files eset_protect at 2001 Security Finding.

Also: the plugin manifest and marketplace sync, a hand-written docs page
(credential, regions, what is read, the offline-device caveat, slow
answers, severity, troubleshooting), the CHANGELOG entry, and the
regenerated connector count, ConnectorType union, catalog fallback,
conformance matrix, llms.txt and corpus stats.

Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
2026-11-14 17:52:26 +05:30
beenuar 6a8cbdb85d docs(api): regenerate openapi.yaml for the disposition filter and search wiring (#1877) 2026-11-14 01:12:18 -08:00
Asish Kumar cc85af3c42 feat(connectors): add a Vectra AI Platform connector (#1859)
## Summary

Adds `vectra_ai`, a connector for Vectra AI Platform detections
(network, identity and cloud) through the v3.4 detection events API,
with OAuth2 client credentials. Each detection becomes one alert,
carrying its host or account and its ATT&CK techniques. Vectra no longer
scores individual detections, so the connector emits no severity tier
rather than inventing one; the ingest profile files it at 2001 Security
Finding, which promotes regardless of severity. Read-only.

## Type of change

- [ ] 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)
- [ ] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change

## Related issues

Closes #1858
Part of #356

## Changes

- `services/connectors/app/connectors/vectra_ai.py`: the connector.
- **Auth.** `POST {portal}/oauth2/token` with HTTP Basic client
credentials. The bearer token is cached until a minute before
`expires_in`. If Vectra refuses a cached token early, the credential is
exchanged once more; a freshly issued token that is refused fails the
poll instead of looping.
- **HTTPS only.** A bare host is read as `https://<host>`, and an
`http://` portal is refused before any request is sent. Only
`client_secret` is vaulted.
- **Reading the window.** `GET /api/v3.4/events/detections` opens at the
window's start through `event_timestamp_gte` (500 a page) and follows
`next_checkpoint` via `from` while `remaining_count > 0`. Only an
integer checkpoint beside a positive count continues the read.
- **Where requests go.** Every request is built from the configured
portal, never from a host named in a response.
- **Failures.** A refused or unreachable opening request raises
`VectraAIError`, so a failure isn't read as a quiet network. A later
page failing keeps the pages already read, and the 25-page bound is
logged (`connector.paging.page_cap_reached`) when it binds.
- **One alert per detection.** The stream emits a detection again on
every update, so `external_id` is the `detection_id`. A poll keeps the
newest event of each detection (the one with the highest event `id`, in
whatever order a page arrives).
- **Window edges and triage.** An event stamped after the read began is
left to the next window. A detection a Vectra triage rule has marked
(`triaged: true`) is not raised.
- **Entity columns.** A host detection fills `hostname` and an account
detection fills `actor`, never both.
- **No severity.** No tier is derived from `threat`, `certainty` or the
undocumented integer `severity`; all three stay in `raw_event`, the same
as an unscored ExtraHop detection.
- `services/connectors/tests/connectors/test_vectra_ai.py`: 54 cases
that drive the real connector through `httpx.MockTransport`.
- `services/ingest/internal/normalizer/ocsf_classes.go`: `vectra_ai` →
2001 Security Finding, next to `extrahop`, with the reason.
- `plugins/vectra-ai/plugin.yaml` (`min_aisoc_version: 23.5.0`, the
first release that can contain it), plus the marketplace sync output.
- `apps/docs/docs/connectors/vectra-ai.md`: credential, the HTTPS rule,
what is read, one alert per detection, why there is no severity, and
troubleshooting.
- Regenerated: the connector count, `ConnectorType` union, connector
docs and sidebar, catalog fallback, conformance matrix, `llms.txt` and
corpus stats. Updated by hand: the connector figure in `AGENTS.md` and
`CLAIM_TO_GATE_MATRIX.md`.
- `CHANGELOG.md`: entry under Unreleased, Added.

### Vendor contract

The endpoint, query parameters (`event_timestamp_gte`, `limit`, `from`)
and response envelope (`events`, `next_checkpoint`, `remaining_count`)
were cross-checked against two published Vectra integrations: Elastic's
`vectra_rux` package and the Cortex XSOAR `VectraRUXEventsDetections`
integration. Both read this same stream. The token exchange matches
Vectra's RUX API guide and XSOAR's client. The test fixture uses the
field names from Elastic's sample events.

On severity: Vectra's own analyst guidance says that on this platform
"individual detections are no longer scored", and the detection event's
integer `severity` field isn't documented anywhere I could find. That is
why the connector carries no tier rather than mapping from a number
whose meaning isn't published.

## Testing

- [x] Unit tests added / updated
- [ ] Integration tests pass locally
- [x] Manually tested (describe steps below)

<details>
<summary>Manual test steps</summary>

1. `pytest tests/connectors/test_vectra_ai.py` in `services/connectors`
(Python 3.11): 54 passed. Two checks that the tests fail without the
code they cover: dropping the event-id comparison fails
`test_the_newest_event_wins_however_the_page_is_ordered`, and the
severity tests pin that no tier is emitted.
2. Full `services/connectors` suite: 1749 passed, 3 skipped, 3 failed.
The 3 failures are in `tests/test_ticket_sync_loop.py` (an `SSRFError`
in the Jira loop) and fail identically on `main` on the same machine.
3. `go test ./internal/normalizer/...`, `gofmt -l` and `go vet` in
`services/ingest`: clean.
4. `ruff check` and `ruff format` on the new files: clean.
5. Every `python scripts/*.py` gate invoked from
`.github/workflows/*.yml`, run on this branch and on `main`. The set of
failures is identical (11 that need the full API or console toolchain),
so none is introduced here. Among them, these pass on the branch:
`generate_connector_count --check`, `generate_connector_types --check`,
`generate_connector_docs --check`, `generate_connector_catalog_fallback
--check`, `connector_conformance --check` (95/95), `build_marketplace
--check`, `generate_llms_txt --check`, `generate_corpus_stats --check`,
`check_connector_paging`, `check_connector_404_conflation`,
`check_connector_profiles`, `check_ocsf_class_coverage --check`,
`check_default_egress`, `check_changelog_frozen`, `check_attribution
--all` and `check_competitor_names`.

</details>

## Screenshots (if UI changes)

N/A. The console form is generated from `schema()`.

## 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)

- [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>
2026-11-13 07:19:29 -08:00
Beenu Arora b64ff1510c chore(release): v23.4.0 (#1854)
Cuts **v23.4.0** — the follow-through release, hours after v23.3.0,
because the queue refilled with shippable community work. Everything in
it merged to `main` since the v23.3.0 tag; this PR is the release
surfaces only.

## Release content (already on main)

- **GHSA-xh3r-vqgc-cv78** (low, reported by **abdochtouki**): empty
password accepted at tenant user creation and verified at login forever
after. Fixed in [#1853](https://github.com/beenuar/AiSOC/pull/1853):
NIST 8-char floor + bcrypt 72-byte ceiling at creation, empty string
refused at login (locks out residue rows). Publishes against this
release.
- **Huntress connector**
([#1850](https://github.com/beenuar/AiSOC/pull/1850), carrying
[#1847](https://github.com/beenuar/AiSOC/pull/1847) commit-intact,
@officialasishkumar; closes #1845). Its `min_aisoc_version: 23.4.0` —
set at carry time as "the first release that will contain it" — is
confirmed correct by this cut.
- **Incident-context Neo4j session fix**
([#1846](https://github.com/beenuar/AiSOC/pull/1846), @43n51c):
per-dimension sessions; four of five dimensions were silently dropping
with `BufferError` on real escalations.
- **OTLP telemetry guard**
([#1851](https://github.com/beenuar/AiSOC/pull/1851), closes #1848,
reported by @43n51c): ueba/honeytokens/purple-team tracing no longer
targets the service's own container; quiet by default, new
`sync_vendored_telemetry.py` gate.

## What this PR changes

- `CHANGELOG`: `[Unreleased]` promoted to `[23.4.0] - 2026-11-13`
(freeze gate PENDING until the tag exists, as designed).
- `VERSION` → 23.4.0 and the derived surfaces: README badge,
`llms.txt`/`llms-full.txt`, `apps/web/package.json`,
`docs/openapi.yaml`.
- Helm chart **7.23.0** — `appVersion`-only move carrying v23.4.0.
- Scoreboard substrate row refreshed (date/version/sha);
`check_scoreboard.py` re-measures in CI.
- `RELEASES.md`: new TL;DR, v23.3.0 demoted to "Previously:", "What's
new" rewritten. **2 defects fixed in this release, 15 across it and the
two before** (2 here, 2 in v23.3.0, 11 in v23.2.0).

## Channels

Neither `stable` channel moves: both sit on the v22 generation, and a
v23 minor may not carry a channel across a major without the deliberate
dispatch.
2026-11-12 19:33:13 -08:00
Beenu Arora 76296e749a fix(api): refuse empty and sub-floor passwords at creation, and the empty string at login (GHSA-xh3r-vqgc-cv78) (#1853)
## Summary

Fixes **GHSA-xh3r-vqgc-cv78** (low): `POST /api/v1/tenants/me/users`
declared its password as a bare `str`, so an explicit `""` passed
validation, was bcrypt-hashed like any password, and `POST
/api/v1/auth/login` accepted the empty string for that account from then
on — `verify_password("", bcrypt(""))` is simply true. Requires an
authenticated `users:write` holder to create the account that way (not
an unauthenticated takeover), as the reporter's unusually careful
scoping already established.

## Changes

- `CreateUserRequest.password` now carries `Field(min_length=8,
max_length=72)` — the floor is NIST SP 800-63B's eight characters; the
ceiling is bcrypt's 72-byte truncation boundary, refused rather than
silently cut (a password the user typed and the password that verifies
must not differ).
- `LoginRequest.password` refuses the empty string at the boundary. This
half is load-bearing, not belt-and-braces: an account row created with
an empty password *before* the creation floor landed still carries
`bcrypt("")`, which the empty login verifies against — the boundary
refusal locks the residue out rather than leaving it quietly serviceable
forever. No legitimate credential is affected (real passwords are
non-empty; the SCIM `!scim-provisioned-no-password` and invite
`!invite-pending` sentinels are non-empty and already fail
verification). An admin recovers a residue account by setting a real
password.
- `docs/openapi.yaml` regenerated (the constraints are now part of the
published contract).

## Tests

`services/api/tests/test_password_floor.py`: empty refused, sub-floor
refused, >72 refused, ordinary password passes, and the login boundary
test that first *proves* `verify_password("", bcrypt(""))` is true —
documenting why the login floor exists — then asserts the empty login is
refused. Auth/tenant test subset: **764 passed, 35 skipped**. Ruff
clean.

## Disclosure

Reported by **abdochtouki** via a repository security advisory with a
live PoC, a verified list of what the bug is *not*, and the fix sketch
this follows. The advisory will be published with credit once this lands
in a release.
2026-11-12 18:03:55 -08:00
Asish Kumar f085df9e70 feat(connectors): add a Huntress connector
Huntress Managed EDR is widely run by MSPs and mid-market SOCs and the
catalogue had no way to ingest it. `huntress` reads its incident
reports, the findings a Huntress SOC analyst has confirmed and
delivered, through GET /v1/incident_reports with HTTP Basic auth. The
vendor contract is the Huntress API reference and the OpenAPI document
behind it (api.huntress.io/v1/swagger_doc.json).

Reading the window: the list endpoint has no time filter. The connector
reads it by updated_at, newest first, at the documented 500-report
maximum through read_token_pages, following pagination.next_page_token
until a page's oldest report was last updated before the window
opened. The following request is built with the token rather than
taken from next_page_url, and the host is fixed, so the credential only
ever goes to api.huntress.io. A refused or unreachable opening request
raises HuntressError so the scheduler records a failed poll; a later
page failing keeps the pages already read.

Raising each report once: the window is applied to sent_at, closed at
the moment the read began. Closing, commenting on or remediating a
report updates it, so windowing on updated_at would raise the same
incident again on every update. A report sent mid-read is left to the
next poll, whose window opens where this one closed, and a report never
delivered is not raised. A report moved to the top of the list by an
update mid-read is de-duplicated by id.

The host behind a report: a report names its host only by agent_id.
Each distinct agent is looked up once through GET /v1/agents/{id} for
hostname, internal and external address and OS, and the record is
carried on the report under `agent` so a replay normalizes to the same
host. The lookups share the account's 60 requests a minute with the
list read, so a poll makes at most 20 and stops on a 429, logging
either bound. A failed lookup costs the host, never the report. Only a
positive integer agent id is put into a request path.

Severity keeps Huntress's low, high and critical; critical is never
collapsed into high, and any other value carries no severity. Both the
API key and the secret key are vaulted.

Also:
- ocsf_classes.go files `huntress` at 2001 Security Finding.
- plugins/huntress/plugin.yaml, and the marketplace sync output.
- apps/docs/docs/connectors/huntress.md: credential, what is read, the
  host lookup and its budget, the severity table and troubleshooting.
- Regenerated connector count, ConnectorType union, catalog fallback,
  conformance matrix, llms.txt and corpus stats; the connector figure
  in AGENTS.md and CLAIM_TO_GATE_MATRIX.md by hand.
- CHANGELOG entry under Unreleased, Added.

Tests: 49 cases in tests/connectors/test_huntress.py drive the real
connector through an httpx.MockTransport.

Closes #1845
Part of #356

Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
2026-11-12 22:27:45 +05:30
Beenu Arora 468abb5b90 chore(release): v23.3.0 (#1849)
Cuts **v23.3.0** — the same-day security-response release. Everything in
it merged to `main` since the v23.2.0 tag; this PR is the release
surfaces plus one manifest correction.

## Release content (already on main)

- **GHSA-qfvv-rf5p-6h69** (high, reported by **1ceS1amese**): fusion
`POST /process` trusted the body's `tenant_id`, letting any tenant's
session — `viewer` included — inject alerts into another tenant's live
dedup/correlation/RBA state. Fixed in
[#1843](https://github.com/beenuar/AiSOC/pull/1843): credential-scoped
tenant + `alerts:write` role gate (mirrored from the API's role table,
pinned by a drift test), with the same contract on `/ml/feedback`,
`/confidence/score`, `/ml/retrain`, and `/dlq/replay` refusing console
sessions in favour of the API's audited door.
- **GHSA-qf6m-hgwv-65f9** (medium, reported by **naroSEC**): the
enrichment service's `/enrich` routes authenticated nobody, two console
rewrites exposed them same-origin, and the limiter's bucket key was a
body field anyone could rotate. Fixed in
[#1844](https://github.com/beenuar/AiSOC/pull/1844):
`internal/tenantauth` (Go port of the vendored `tenant_scope` contract),
limiter/cache keyed on the authenticated tenant, dead rewrites removed,
all four real callers authenticating with the service token + the run's
own tenant.
- **Cisco Secure Endpoint connector**
([#1842](https://github.com/beenuar/AiSOC/pull/1842),
@officialasishkumar, #356): `GET /v1/events` at the documented 500-event
maximum through `read_offset_pages`, region as a closed three-cloud
select, unrated operational events kept out of the alert queue, Cisco's
four severities mapped one-to-one.

Both advisories will be published naming `23.3.0` as the patched version
once the tag exists.

## What this PR changes

- `CHANGELOG`: `[Unreleased]` promoted to `[23.3.0] - 2026-11-12`
(frozen-gate PENDING until the tag exists, as designed).
- `VERSION` → 23.3.0 and the derived surfaces: README badge, `llms.txt`
/ `llms-full.txt`, `apps/web/package.json`, `docs/openapi.yaml`
info.version.
- **Helm chart `7.22.0`** — no chart content change; the bump carries
`appVersion: v23.3.0`, because republishing an existing chart version
naming a different application is the v13.0.0 defect the chart gate
refuses.
- **`min_aisoc_version` correction**: the Cisco connector's manifest
(authored pre-release) claimed `23.2.0`, an artifact in which the
connector does not exist. Corrected to `23.3.0` in
`plugins/cisco-secure-endpoint/plugin.yaml` and the three marketplace
index copies — same correction the v23.2.0 release PR made for Sophos.
- `RELEASES.md`: new TL;DR, previous demoted to "Previously:", "What's
new" rewritten. **2 defects fixed in this release, 22 across it and the
two before** (2 here, 11 in v23.2.0, 9 in v23.1.0).
- Scoreboard substrate row refreshed (date/version/sha) —
`check_scoreboard.py` re-measures `mitre_accuracy` fresh in CI and fails
on drift, so the row is verified, not asserted.

## Channels

Neither `stable` channel moves: both sit on the v22 generation, and a
v23 minor may not carry a channel across a major without the deliberate
dispatch.
2026-11-12 13:00:19 -08:00
Asish Kumar 4fc6cbd0a8 feat(connectors): add a Cisco Secure Endpoint connector (#1842)
## Summary

Adds a **Cisco Secure Endpoint** connector (`cisco_secure_endpoint`,
category `edr`). Cisco Secure Endpoint (formerly AMP for Endpoints) is
one of the most widely deployed endpoint protection platforms, and the
catalogue doesn't have it yet. The connector reads its detections
through the v1 events API (`GET /v1/events`), the feed Cisco's own SIEM
integrations read. The operator picks one of Cisco's three regions and
enters an API client ID and key.

The window is read to the end. The API key only ever goes to a Cisco
host. Operational events that Cisco leaves unrated (policy updates,
scans, installs) are not promoted into the alert queue. Cisco's four
severities are kept as published, and `Critical` stays `critical`.

## Type of change

- [ ] 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)
- [ ] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change

## Related issues

Part of #356 (connector wishlist). It doesn't close the issue, because
the wishlist stays open by design.

## Changes

- **Where the vendor contract comes from.**
- Cisco's [Secure Endpoint API
documentation](https://developer.cisco.com/docs/secure-endpoint/) and
its API FAQ: regional hosts, HTTP Basic auth, and "a maximum of 500
results will be returned" with paginated links.
- Event shapes and the severity vocabulary were cross-checked against
the payloads in Elastic's `cisco_secure_endpoint` integration, which
reads the same route the same way. The ladder there is `Low | Medium |
High | Critical`, and policy updates, scans and file fetches carry no
severity.
- `services/connectors/app/connectors/cisco_secure_endpoint.py` (new):
- **Auth and region.** HTTP Basic with the API client ID and API key.
`region` is a select over Cisco's three clouds: `nam` →
`api.amp.cisco.com`, `eu` → `api.eu.amp.cisco.com` and `apjc` →
`api.apjc.amp.cisco.com`. It is not a URL. An unknown region raises
`ValueError` in the constructor, so the router answers 422 with the
reason, and the credential can only reach one of Cisco's hosts.
  - **Reading the window to the end.**
- The connector reads from `start_date` (ISO 8601) at `limit=500`, the
documented maximum, through `read_offset_pages`.
- Each following request is built from the configured region with the
next `offset`, which is the only thing `metadata.links.next` changes.
Building it here means a host named in a response body is never sent the
credential.
- A refused opening request raises, so the scheduler records a failed
poll rather than a quiet one. The messages for 401 (wrong key, or the
wrong region for this credential) and 429 (rate limit) tell the operator
what to do.
- If a later page fails, the pages already read are kept. The 25-page
bound is logged when it is reached.
- **Newest-first duplicates.** The list is newest first, so an event
recorded mid-read pushes one row across a page boundary and it comes
back twice. Rows are de-duplicated by `id` before the batch leaves the
connector.
- **Only rated events.** The stream also carries operational records
with no severity: policy updates, scans and installs. This connector is
filed at OCSF 2001, which fusion promotes unconditionally, so those
records would land in the alert queue. They are skipped, and the number
skipped is logged as `cisco_secure_endpoint.unrated_events_skipped`.
- **Normalization.** The canonical envelope carries the vendor record
under `raw_event`.
- The title is the event type plus the most specific name the event has:
the detection name, the IOC short description, or the threat hunting
incident title.
- `computer.hostname`, `computer.user` and the first internal address
become host, actor and source IP. `network_info.remote_ip` becomes the
destination IP.
- File name, path, SHA-256 and disposition are kept, along with ATT&CK
technique ids from the event and from a threat hunting incident.
- Cisco sends the event `id` as an integer wider than 53 bits, so it is
carried as text.
- **Severity.** `Low | Medium | High | Critical` map to their own tiers,
and `Critical` is never collapsed into `high`. Any other value carries
no severity.
- `services/ingest/internal/normalizer/ocsf_classes.go`:
`cisco_secure_endpoint` is filed at 2001 Security Finding, with the
reason in a comment, so `check_ocsf_class_coverage.py --check` stays
green without adding to the generic-mapping count.
- `plugins/cisco-secure-endpoint/plugin.yaml`, plus the `pnpm
marketplace:sync` output.
- `apps/docs/docs/connectors/cisco-secure-endpoint.md`, generated by
`generate_connector_docs.py`. The human-notes section covers:
  - getting the credential
  - the console-to-region table
  - what is read and what is skipped
  - the severity table
  - a troubleshooting table keyed on the connector's own error messages
- Regenerated derived artefacts:
  - connector counts (`generate_connector_count.py`)
- the `ConnectorType` union. Most of its diff is column realignment,
because the new id is the longest.
  - the catalog fallback
  - the conformance matrix
  - `llms.txt`
  - corpus stats
- I updated the connector figure in `AGENTS.md` and the count row in
`docs/audit/CLAIM_TO_GATE_MATRIX.md` by hand.
- `CHANGELOG.md`: entry under Unreleased → Added.

## 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_cisco_secure_endpoint.py`
has 47 tests. They drive the real connector through an
`httpx.MockTransport` that serves the three regional hosts, and cover:
   - registration, the schema and the region options
   - an unknown region being refused before any request
   - each region reading its own host over https
   - the Basic auth header
- the response's `next` link (pointed at a foreign host in the fixture)
never being requested
   - every page arriving by offset until a short one
   - a row shifted across a page boundary being returned once
   - a failed later page keeping the earlier pages
   - the page cap being announced
   - the ISO 8601 `start_date`
   - unrated events being skipped and counted
   - 401 and 429 refusals raising with guidance
   - the `test_connection` outcomes
- normalization of threat, Cloud IOC, network and threat-hunting events
   - the four-tier severity ladder
2. Negative controls:
   - With the unrated-event filter removed, 2 tests fail.
   - With the `id` de-duplication removed, 1 test fails.
3. `pytest tests/` in `services/connectors`, with coverage, on the
committed lock and Python 3.11: 1644 passed and 3 failed. The 3 failures
are in `test_ticket_sync_loop.py` and fail the same way on an untouched
`main`, because the test machine has no DNS for the hostname they
resolve. Total coverage is 75.9% against the floor of 66%. The new
module is at 97%.
4. `go test ./internal/normalizer/` in `services/ingest` passes on Go
1.26.0, and `gofmt -l` reports nothing.
5. These all report OK:
- `check_connector_paging.py`, `check_connector_profiles.py`,
`check_ocsf_class_coverage.py --check` and
`check_connector_404_conflation.py`
- `connector_conformance.py --check` and the `--check` mode of every
connector generator (count, types, docs, catalog fallback)
- `build_marketplace.py --check`, `curate_detections.py --check`,
`generate_llms_txt.py --check` and `generate_corpus_stats.py --check`
- `check_changelog_frozen.py`, `check_repo_self_links.py`,
`check_competitor_names.py`, `check_claim_gate_matrix.py`,
`check_toolchain_versions.py`, and `check_attribution.py --all` and
`--commits origin/main..HEAD`
6. Lint and types: `ruff check services/ scripts/ tests/ tools/` and
`ruff format --check` on the touched files, with ruff 0.16, are clean.
`check_mypy_baseline.py` with mypy 2.3 reports that no tree got worse.

No live Secure Endpoint organisation was used. The contract comes from
Cisco's published API documentation and the payloads of an existing
integration against the same route.

</details>

## Screenshots (if UI changes)

Not applicable. The connector appears in the existing catalog grid and
wizard through the registry, and the region select is rendered by the
existing select field.

## 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)

- [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>
2026-11-12 06:45:43 -08:00
Beenu Arora 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).
2026-11-11 16:34:12 -08:00
Beenu AroraandAsish Kumar e4c1458675 feat(connectors): edit a saved connector from the console (carries #1833, closes #1832) (#1836)
Carries #1833 by @officialasishkumar, which reviewed **sound** on every
security axis — the RFC 7396-at-depth-one merge under a row lock, stored
secret leaves kept as vault tokens with only newly-typed values
encrypted (pinned by
`test_merged_secrets_keep_their_tokens_and_only_new_values_are_encrypted`),
and the retirement of the documented delete-and-re-add footgun that
loses the id, checkpoint, counters and push token.

**Why the carry:** the required check *Verify docs/openapi.yaml is up to
date* fails deterministically on #1833 — the request-model change alters
the published spec and the committed `docs/openapi.yaml` wasn't
regenerated — and fork branches can't be pushed to from this repository.
This branch is #1833 byte-identical plus the regenerated spec (23
insertions, verified with `export_openapi.py --check`). The other ten
failures on #1833 were the runner-fleet DNS outage, not the diff.

**Verified locally:** ruff lint + format clean · mypy baseline OK ·
merge-semantics tests 10 passed / 3 skipped (DB-backed skips per the
probe convention) · spec check green.

Closes #1832. Authorship preserved via co-author trailer.

Co-authored-by: Asish Kumar <officialasishkumar@gmail.com>
2026-11-11 11:33:03 -08:00
Asish Kumar 1da3b22332 feat(connectors): add a Sophos Central connector (#1834)
## Summary

Adds a **Sophos Central** connector (`sophos_central`, category `edr`),
one of the most widely deployed endpoint and server protection platforms
and absent from the catalogue. It reads Sophos Central alerts through
the SIEM Integration API (`GET /siem/v1/alerts`), the same feed Sophos's
own SIEM integration reads. The operator enters a client ID and secret
and nothing else: the tenant and its data region are discovered from the
credential, and partner or organization credentials work by naming one
tenant. The window is read to the end, the vendor's 24-hour lookback
limit is respected, and Sophos's three severities are kept as published.

## Type of change

- [ ] 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)
- [ ] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change

## Related issues

Part of #356 (connector wishlist). This doesn't close it, because the
wishlist stays open by design.

## Changes

- **The vendor contract.** It comes from Sophos's developer portal:
[getting started
(tenant)](https://developer.sophos.com/getting-started-tenant), [getting
started (partner)](https://developer.sophos.com/getting-started) and the
[alerts route
reference](https://developer.sophos.com/reference/siem-v1/alerts/get-alerts/).
Sophos's own `Sophos-Central-SIEM-Integration` client resolves tenants
and pages the same way.
- `services/connectors/app/connectors/sophos_central.py` (new):
- **Auth.** OAuth2 client credentials at
`https://id.sophos.com/api/v2/oauth2/token` with `scope=token`. The
token is cached with a minute of headroom and renewed once on a 401.
- **Tenant discovery.** `GET https://api.central.sophos.com/whoami/v1`
tells the connector what kind of credential it has.
- A credential with `idType: tenant` reads the `apiHosts.dataRegion`
that whoami names. If a configured `tenant_id` names a different tenant,
the connector refuses and says why.
- A partner or organization credential has no data region of its own, so
`tenant_id` is required. The connector looks the tenant up through
`/{idType}/v1/tenants/{id}` with `X-Partner-ID` or `X-Organization-ID`
and reads its `apiHost`.
- `tenant_id` is validated as a UUID in the constructor, because it is
interpolated into a request path. A bad value becomes a 422 with the
reason.
- **The bearer token stays with Sophos.** The data region host comes
from a response, so the egress guard, which vets configured values,
never sees it. The host must be `https` under `sophos.com`, and it is
rebuilt from the scheme, host and port that were checked before the
token is sent there.
- **Reading the window to the end.** Pages are read at `limit=1000` (the
documented maximum; the minimum is 200) through `read_token_pages` with
`more_field="has_more"`. Following pages send `cursor` without
`from_date`, as Sophos's client does. A refused opening request raises,
so the scheduler records a failed poll rather than a quiet one. A later
page failing keeps the pages already read, and the 25-page bound is
announced when it binds.
- **The 24-hour ceiling.** `from_date` "must be within last 24 hours".
The scheduler's outage backfill asks for up to exactly 24 hours, which
the API would refuse outright. A longer window is shortened to just
under the limit and logged as `sophos_central.window_shortened`.
- **Normalization.** The canonical envelope carries the vendor record
under `raw_event`. `description` becomes the title, `location` the
hostname, `source` the actor (`n/a` is no user), `data.source_info.ip`
the source IP and `data.ips_threat.remote_ip` the destination IP.
`threat`, `type`, the endpoint id and the endpoint type are kept.
- **Severity.** Sophos publishes `LOW | MEDIUM | HIGH` and nothing
above. These map straight through, so nothing is ever `critical`. Any
other value carries no severity rather than a guess.
- `services/connectors/app/connectors/_paging.py`: `read_token_pages`
gains an opt-in `more_field`. Sophos returns `next_cursor` on its last
page too, so ending on the token alone would re-request the final page
up to the page cap. When `more_field` is set, the read ends as soon as
that flag is not `True`. Existing callers are unchanged.
- `services/ingest/internal/normalizer/ocsf_classes.go`:
`sophos_central` is filed at 2001 Security Finding, so its alerts
promote, and `check_ocsf_class_coverage.py --check` stays at 42 generic
connectors.
- `plugins/sophos-central/plugin.yaml` plus `pnpm marketplace:sync`
output.
- `apps/docs/docs/connectors/sophos-central.md`, generated by
`generate_connector_docs.py`. The human-notes section covers:
  - getting the credential
  - partner and organization tenants
  - what is read and the 24-hour limit
  - the severity table
  - a troubleshooting table keyed on the connector's own error messages
- Regenerated derived artefacts:
  - connector counts (`generate_connector_count.py`)
  - the `ConnectorType` union
  - the catalog fallback
  - the conformance matrix
  - `llms.txt`
  - corpus stats
- The connector figures in `AGENTS.md` and the count row in
`docs/audit/CLAIM_TO_GATE_MATRIX.md` were updated by hand.
- `CHANGELOG.md`: entry under Unreleased → Added.

## 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_sophos_central.py` (54
tests) drives the real connector through an `httpx.MockTransport` that
serves Sophos ID, the global API and a data region. It covers:
   - registration and schema
   - the token request's form body
   - whoami-to-data-region routing with `X-Tenant-ID`
   - partner and organization lookups with their scope headers
   - the missing and mismatched tenant messages
- refusal of non-Sophos, plain-http and look-alike data region hosts,
and the host being rebuilt from its checked parts
   - all pages arriving, with `cursor` replacing `from_date`
   - `has_more: false` ending the read beside a cursor
   - a failed later page keeping earlier pages
   - the page cap being announced
   - the 24-hour clamp being logged
   - a refused opening request raising
   - a lapsed token being renewed once
   - the normalized envelope and the three-tier severity ladder

   Direct tests of `more_field` on the shared reader are included.
2. Negative control: with the `more_field` check removed from
`read_token_pages`, 11 of the tests fail.
3. `pytest tests/` in `services/connectors`: 1596 passed and 3 failed in
`test_ticket_sync_loop.py`. Those 3 fail identically on an untouched
`main` checkout, because the machine I tested on has no DNS for the
hostname they resolve.
4. These all report OK:
- `check_connector_paging.py`, `check_connector_profiles.py`,
`check_ocsf_class_coverage.py --check` and
`check_connector_404_conflation.py`
- `connector_conformance.py --check` and the `--check` mode of every
connector generator (count, types, docs, catalog fallback)
- `build_marketplace.py --check`, `curate_detections.py --check`,
`generate_llms_txt.py --check` and `generate_corpus_stats.py --check`
- `check_changelog_frozen.py`, `check_repo_self_links.py`,
`check_competitor_names.py` and `check_attribution.py --all`
5. `ruff check` and `ruff format --check .` with ruff 0.16.10, and
`check_mypy_baseline.py` with mypy alone on Python 3.11: no tree got
worse.

I didn't run the Go change locally. It is one entry in the class table,
and `TestEveryDeclaredConnectorHasAnOCSFDecision` in CI checks it, along
with the Python mirror `check_ocsf_class_coverage.py`, which passes. No
live Sophos Central tenant was used. The contract is the vendor's
published reference and its own SIEM client.

</details>

## Screenshots (if UI changes)

Not applicable. The connector appears in the existing catalog grid and
wizard through the registry.

## 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)

- [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>
2026-11-11 10:35:29 -08:00
Beenu Aroraandknowlet a2cf25be56 fix(copilot): ground chat in caller-scoped security data (carries #1819) (#1828)
Carries #1819 by @knowlet — the capability is exactly right and reviewed
well; the carry exists because two required checks failed on content a
fork branch can't be amended from here.

**What the PR does (as reviewed):** copilot's chat transports bind three
read-only tools (alerts, one record by UUID, Fusion entity risk) that
forward the **caller's own** authorization and tenant to the core API —
the API remains the authority, no LLM argument or page context can
choose a URL, credential or tenant; `kind` is enum-bound and `record_id`
round-trips `uuid.UUID` with a response-echo check; entity paths are
percent-encoded with `safe=''`; redirects disabled, reads bounded,
failures answer as explicit unavailability. The text cache is disabled
when tools are bound (a cached prose answer must not impersonate a live
read), a truncated tool loop no longer publishes the last raw lookup as
a conclusion, and the Fusion risk endpoints return **503 instead of a
fabricated empty queue** — the exact honest-failure doctrine this repo
enforces. Big test surface: read boundaries (223 lines), live reads, API
filter tests, provenance.

**Corrections relative to #1819 as submitted (the two failing required
checks, reproduced locally before fixing):**
1. *No competitor product named*: seven vendor-name mentions in
prose/docstrings/test strings reworded neutrally (the gate's own
suggested phrasing); test semantics unchanged — the renamed source value
appears only at its insert site.
2. *Python — Lint & Type-check*: the import-boundary test's finder now
subclasses `importlib.abc.MetaPathFinder` and carries the ABC's own
`find_spec` signature — the two `arg-type` findings (and the `override`
finding the first fix shape would have left) against the mypy baseline.

**Verified locally:** competitor gate 0 · ruff lint + format clean over
services/agents + services/api · `check_mypy_baseline` OK (no tree got
worse) · 62 passed / 1 skipped across the five agents suites
(import-boundary, read-boundaries, fallback-honesty, agent-identity,
vaid). The DB-backed live suites get their grade in CI.

Authorship preserved via co-author trailer; the contribution credit
stays with @knowlet.

---------

Co-authored-by: knowlet <knowlet@users.noreply.github.com>
2026-11-11 06:08:13 -08:00
Ioannis Loutsis 97ea663d39 fix(ingest): preserve Agentmetry investigation context (#1826)
## Summary

The Agentmetry inbox template drops optional source context needed to
investigate a finding. Preserve selected account provenance,
supporting-event references, recorder coverage and MCP schema
observations under `finding.evidence.agentmetry`, keeping reported
account claims separate from `actor.user` and excluding full account
email and opaque account/user IDs.

Existing field paths, the activity/finding split, the severity ladder
and the OCSF 1.1.0 declaration remain unchanged.

## Type of change

- [x] Bug fix
- [x] Documentation update

## Related discussion

https://github.com/beenuar/AiSOC/discussions/1577

## Changes

- Extend `agentmetry.yaml` with selected optional context mappings
rather than copying the raw payload.
- Add `agentmetry_context_test.go` regressions for supporting-event
references, host-wide correlation, reported account provenance,
partial/unknown claims, zero/false/empty coverage values and MCP schema
states.
- Document field destinations, privacy boundaries and investigation
limits; extend the existing claim-matrix row with the mapping coverage.

## Testing and scope

The committed regressions use the inbox JSON decoder, embedded template
and normalized JSON serialization. They cover field selection and
routing, without claiming that a supporting event arrived or that a
reported account identifies the person who made a call. Source-event
references must be scoped by tenant and host; host-wide findings can
reference multiple sessions.

The required upstream CI checks must complete before merge. These
mapping regressions do not establish current-release full-stack
compatibility, finding persistence, retrieval, UI pivots or source-trail
verification. The existing dated manual-run caveat is retained.

## Checklist

- [x] Unit regression tests added
- [x] Documentation updated
- [x] Self-review completed
- [x] Sensitive data and credentials checked in the diff

## Eval harness

- [x] Not applicable: this PR does not touch substrate, playbooks,
detections or eval inputs.

Signed-off-by: Ioannis L. <44038245+blitzcrieg1@users.noreply.github.com>
2026-11-11 06:08:03 -08:00
Albert Hsieh 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>
2026-11-11 03:15:33 -08:00
Albert Hsieh adeeeeef7d fix(web): keep tab deep links in sync with navigation (#1817)
## Summary

Fix Settings deep links such as /settings?tab=deployment opening
Profile, plus related Case and Responder navigation defects.

## Root causes and changes

- Settings ignored the query string via useState('profile'). All 15
sections now read the URL.
- CaseWorkspace read the tab only at mount. Tab clicks, query changes,
investigation transitions and browser history now stay synchronized.
- Responder redirected every legacy shortcut to Triage. New shortcuts
use canonical routes; existing Cases and On-call links redirect
correctly.

A shared useUrlTab hook validates tabs, preserves other query parameters
and fragments, supports Reload/Back/Forward, and avoids duplicate
history entries. Settings adds Suspense and active controls expose
aria-current.

## Testing

Verified on 7b5788db69:
- Lint: passed, 0 errors / 95 existing warnings; no new warnings.
- TypeScript: passed.
- Production and Storybook builds: passed.
- Vitest: 121 files / 1,199 tests passed; coverage gate passed.
- E2E: 13 passed / 1 pre-existing skipped. All 6 new browser tests and 5
new HTTP tests passed without retries.
- CodeQL: passed, no new alerts in changed code.
- Ruff lint/format and mypy baseline: passed.

Negative controls reproduced the original failures on the unchanged
base. HTTP assertions use the existing HTML parser; both initial CodeQL
test-regex findings are resolved.

Validation logs and CI links: https://github.com/knowlet/AiSOC/pull/5

## Checklist

- [x] Bug fix with regression tests and research notes
- [x] No new lint warnings, dependencies or workflow changes
- [x] DCO sign-off included
- [x] Contribution guidance in #353 followed; this does not close #353
- [x] Eval harness not applicable (frontend navigation only)

---------

Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com>
2026-11-11 00:29:53 -08:00
Beenu Arora 0d547c10b3 chore(release): v23.1.0 (#1813)
## Summary

Promotes `[Unreleased]` to **v23.1.0** (2026-11-10) and moves every
release surface together.

v23.0.0 shipped two first-run regressions, both since fixed on `main`
(#1808, #1809); anyone on the v23.0.0 tag or its frozen images hits
both. With an Added section present (#1804, the first community
detection rule), semver says MINOR.

## What this PR changes

- **CHANGELOG.md** — `[Unreleased]` → `[23.1.0] - 2026-11-10` (fresh
empty `[Unreleased]` left behind). Four merged PRs had shipped without
changelog entries; accurate ones are added from their diffs and PR
bodies: #1804 (Added: community rule; Fixed: marketplace
`quarantine_reason` fallback, byte-level artefact `--check`;
Documentation: hello-hunt `enabled` guidance), #1806 (investigator
enrichment), #1807 (federated Splunk self-hosted index), #1800 (Wazuh
permission docs). The initdb entry now also records that CI executes the
docker-backed regression test rather than skipping it — verified in the
merge commit's `Python — Tests` job log
(`test_live_initdb_installed_database_is_current PASSED`).
- **VERSION** → 23.1.0; **apps/web/package.json** → 23.1.0; **README**
version badge → 23.1.0.
- **Chart** → `version: 7.20.0`, `appVersion: "v23.1.0"` (7.19.0 is
published naming v23.0.0; an appVersion change is chart content, so the
chart version moves).
- **RELEASES.md** — new TL;DR paragraph; v23.0.0 demoted to
**Previously:**; `## What's new` opening updated. Defect count per the
established convention: **9 in this release, 48 across it and the two
before** (9 here, 30 in v23.0.0, 9 in v22.2.0; the hello-hunt
replay-grading bullet is a documentation-claim correction, mentioned but
not counted).
- **Regenerated:** `llms.txt` / `llms-full.txt`, benchmark scoreboard
row (re-measured: `mitre_accuracy` 0.97, stamped 23.1.0),
`docs/openapi.yaml` (diff is exactly `info.version`).

## Gates run locally (all pass)

`readme_gates.py`, `check_single_version_source.py` (5/5 surfaces),
`check_chart_version.py` (7.20.0 collides with nothing published),
`check_attribution.py --all`, `check_competitor_names.py`,
`generate_llms_txt.py --check`, `check_scoreboard.py --check`,
`export_openapi.py --check`.

## After merge

Tag `v23.1.0` on the merge commit; `release.yml` publishes the GitHub
Release from the CHANGELOG section, the 16 images, and chart 7.20.0. The
`stable` channels are expected to hold (they sit on the v22 generation;
the guard refuses a cross-major move without a deliberate dispatch) — to
be verified at the registry and reported.
2026-11-10 11:59:12 -08:00
ToufiqtoufiqboandToufiqtoufiqbo 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>
2026-11-10 08:00:15 -08:00
Beenu Arora 3ec5fb1975 chore(release): v23.0.0 (#1798)
Promotes `[Unreleased]` → `[23.0.0]` (2026-11-10) and moves every
release surface together.

**Why a major:** [#1732](https://github.com/beenuar/AiSOC/pull/1732)
removed `DeploymentConfig.update_channel` / `auto_update` and
`DeploymentConfigUpdate.telemetry_enabled` from the published spec
(fields nothing implements; `telemetry_enabled` becomes read-only
`Literal[False]`) — a published-spec break under the repo's own
openapi-breaking policy, sitting in `[Unreleased]` under `### BREAKING`.

**CHANGELOG mechanics:** the accumulated section had lane-duplicated
headings (three `Fixed`, two `Added`/`Security`); they are merged into
one canonical set with entry text preserved byte-for-byte (bullet count
51 → 56, the +5 being this wave's new entries), and `### BREAKING` is
hoisted to the top so a release-body cut at the 125k cap can never drop
it.

**Surfaces:** `VERSION` 23.0.0 · `apps/web/package.json` · chart
`appVersion: v23.0.0` (chart `version` stays at the staged, unpublished
7.18.0 — 7.17.0 is what v22.2.0 published) · README badge · RELEASES.md
TL;DR (new paragraph; v22.2.0 demoted to *Previously*) + What's-new
rewrite · `llms.txt`/`llms-full.txt` regenerated · scoreboard row
refreshed (substrate 0.97, stamped 23.0.0) · CREDITS row for @knowlet.

**TL;DR defect count:** 30 in this release (21 Fixed + 9 Security, by
the established counting rule), 55 across the last three; six
documentation-claim corrections exist and are explicitly not counted.

**Local verification:** `readme_gates` OK ·
`check_single_version_source` 5/5 OK · `check_chart_version` OK ·
`check_scoreboard --check` OK (row re-measured, not relabelled) ·
`generate_llms_txt --check` OK · attribution + competitor scans OK.

**Sequencing:** #1797 (Settings connector links, @knowlet) is in CI now
and its CHANGELOG entry is included here — this PR merges after it so
the tagged tree contains everything the notes claim. Tag `v23.0.0` goes
on main after this merges; the two advisories fixed by #1750 get their
`patched` field set to 23.0.0 once the release exists. Neither `stable`
channel moves (application major; deliberate dispatch required).
2026-11-10 03:08:55 -08:00