mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-12-03 10:57:40 +08:00
f4cea19023c331c052d1585e45ec76cc4f7fcab7
493
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
8a5f68a0e1 |
feat(ai-security): session sequences, runaway sessions, refused assets, MCP drift, shadow AI and prompt classes (WS5) (#2009)
## What
WS5 of the gap-closure program: AI security at runtime. Six items; every
detection goes through the real loader + engine, every store truth
through live Postgres, and the SDK's standing privacy claim stays
exactly true.
## WS5.1 — Session-scoped sequences
`wd-ai-session-untrusted-then-secret-then-egress`: inside ONE session,
an injection/guardrail finding → a prompt the SDK's local scanner
flagged as secret-bearing → an egress-capable tool call = one HIGH
finding, grouped by `session_id`, ordered, 1h window. **The negative
fixture the brief names is pinned**: the same three events across two
sessions do NOT fire — the session is the claim. `TestTemplateCoupling`
reads the committed ai ingest templates and fails **by name** on any
rule field they stop mapping — the drift gate against the recorded
aspirational-rule defect.
## WS5.2 — Runaway sessions
`wd-ai-session-tool-call-flood` (per-session rate; two calm sessions do
not sum) and `wd-ai-identical-prompt-repetition` — **`redaction.py`
hashes every prompt "precisely so detection can ask: the same prompt
fifty times?" and nothing consumed the hash until now**. Grouped by the
hash itself; the rule's name states the cross-session scoping out loud.
Duration/token-burn deliberately stays with the existing spend-anomaly
baselines (a second rule would be a second answer to the same question).
## WS5.3 — Refused assets: the defect fix and the doorbell
**The defect, exactly as Phase 0 recorded it**: the recorder's upsert
set `risk_score = EXCLUDED.risk_score` unconditionally while `_score()`
treats `sanctioned` as always-None by design — so re-observing a REFUSED
asset silently downgraded `ai_inventory`'s +30 "Reviewed and refused,
and still running" to "Not declared". The scorer-parity suite only
exercised `sanctioned=None`, which is why the failing test had to be
**live**: the overwrite was the SQL's behaviour. The fix is the upsert's
own CASE — a judged asset's score is owned by the sanction route
(refused AND approved alike; a judgement is a judgement), an unjudged
one keeps the recorder's fresher score. Proven both ways on real
Postgres.
And the alert half: a refused asset observed again now **raises a HIGH
triage alert citing the sanction decision** — `drain_refused()` on the
recorder, one notice per flush, raised through the ordinary fusion path
(`_fuse_and_persist`), with fusion's own dedup bounding a chatty agent.
Containment stays a governed playbook step; this is the doorbell.
## WS5.4 — MCP manifest drift and tool poisoning
The SDK gains `mcp_manifest(server, tools)`: tool **names + description
SHA-256s + annotations, hashed in the customer's process** — description
text never ships; at most one ≤80-char snippet travels, and only for a
description that already tripped an instruction pattern (the pattern
list mirrors the concerns of the platform guard
`services/agents/app/mcp/untrusted.py`, which stays the canonical
defence). The recorder versions manifests per (tenant, server) —
migration 176, same-content touches, changed-content versions — and
drift becomes a triage alert naming what moved: `description_drift`,
`new_state_changing_tool` (a read-only server growing `delete_repo` is
the poisoning shape), `instruction_shaped_description` (HIGH — that one
is the answer, not the question).
## WS5.5 — Shadow AI from network telemetry
A shipped catalog (`ai_app_catalog.json`) whose **every row is a
vendor's own documented product domain, with per-row provenance** and a
stated limitation up top. SWG/DNS events (zscaler, netskope,
cisco_umbrella, cloudflare_zt) matching it become AI-estate sightings
from a `network` source whose attributes state `cannot_see_prompts:
true` outright. A refused catalog app re-observed now composes with
WS5.3's alert automatically. **Refused with a recorded reason**: the
upload-volume-to-unsanctioned-apps detection — no SWG connector
currently maps a bytes field into the engine's namespace, so the rule
would have been aspirational; it lands when a connector carries bytes.
## WS5.6 — Sensitive classes in prompts
`classes.py`: opt-in (`classify_prompt_classes=False` by default), local
regex, **counts only** ({"personal": 2} — no text, no offsets). Off by
default means the field is **absent**, not an empty dict — and the test
pins that the standing claim holds: with the opt-in on, `prompt` still
never leaves the process.
## Testing
- Fusion suite **1,266 passed** (8 new session-rule cases incl. both
negative fixtures; 2 consumer refused-alert cases; template-coupling
pin).
- SDK suite **27 passed** (hashes-never-text, bounded snippet
only-when-tripped, counts-only, absent-unless-opted-in).
- **5 live-Postgres cases** (new `integration.yml` step): judged-score
survival both ways + unjudged refresh + refused-notice once-per-flush +
manifest versioning/touch/drift with findings named.
**Negative controls (applied, observed failing, restored):**
1. Reverting the upsert CASE to the pre-fix overwrite → the
judgement-survival live cases fail.
2. Disabling the manifest hash comparison → the live drift case fails.
## Gates
check_windowed_translation OK · migration_numbering OK (176, allocated)
· mypy baseline OK · ruff clean · claim matrix **+3 GATED rows**
(tallies recomputed) · readme_gates OK · ai-runtime template extended
(`mcp_tools`, `prompt_class_counts`) with the coupling pin covering
both.
## Could not verify
- The windowed rules against the Go normalizer end-to-end (ingest →
fusion over Kafka): the coupling pin holds the field names to the
committed templates, and the engine legs run in-process; the full-spine
replay is the integration suite's existing surface.
- The SDK against a live MCP server: `mcp_manifest` is driven by the
host application; the event shape and hashing are pinned by the SDK
suite.
|
||
|
|
73036c9b57 |
feat(lake): archive tier, rehydration, portability and scoped legal holds (WS2) (#2007)
## What WS2 of the gap-closure program: the long-term security data lake. The lake's 400-day TTL is a hard ceiling nothing exempts — everything older exists only if it was exported first. This PR makes that export real, verified, rehydratable and portable, and narrows legal holds to their own rows. ## WS2.1 — Archive tier (migration 170) Closed `(tenant, month)` partitions export to the tenant's **own S3-compatible bucket** as Parquet with a **signed manifest** (row count, event-time bounds, schema + OCSF version, per-file SHA-256; the evidence-bundle signer). Design decisions that carry the honesty: - **The database that owns the rows writes the files**: export, count re-read and SHA-256 all run *inside ClickHouse* (`INSERT INTO FUNCTION s3(...) Parquet`, `s3(...,'Parquet')`, `s3(...,'RawBLOB')`) — no second data path whose row semantics could drift. - **"Exported" is a claim; "verified" means the bucket was read back and matched.** A corrupted object fails naming what differed — including the sharp case a count check cannot see: a *valid* Parquet with the same rows and different bytes, caught by the checksum leg alone (proven live, and pinned by the negative control). - An **open month is refused** (it is still receiving rows — the connector-window lesson applied to archival). UUID/IP columns export as strings (ClickHouse cannot write UUID to Parquet; found live, Code 50). - Per-tenant policy, **default off**; bucket credentials vault-encrypted, decrypted at export time; ClickHouse masks `s3()` credential positions in its query log (documented reliance). **WORM** is recorded as *declared by operator, not verified by this service* — never implied verified. - Hourly sweep worker (`lake_archive_sweep`) exports closed months for opted-in tenants, verifies, and expires rehydrations; bounded per tick. ## WS2.2 — Rehydration (migration 171) **Estimate first** (bytes/files/months from the manifests; retrieval cost **null unless `AISOC_ARCHIVE_RETRIEVAL_PRICE_PER_GB` is configured** — never an invented figure), then an audited load (**requester + reason required**) into an expiring scratch table `aisoc.rehydrated_<8hex>`. The lake explorer queries it through its own rewriter: the allowlist gained a **regex-pinned arm** that cannot widen (non-hex/overlong/foreign-schema names refused) and injects the same tenant predicate `raw_events` gets — live-proven: owner reads 3 rows, another tenant reads 0. The loader **evicts foreign-tenant rows after landing** because a bucket is not a tenancy boundary. (ClickHouse 23.8's Parquet pushdown cannot compare file-schema strings with UUID hints in either direction — Code 169, found live — so tenancy is enforced post-landing by mutation, not by pushdown.) ## WS2.3 — Portability (migration 171) Range export to a bucket **the tenant names** (per-request credentials, never persisted): one Parquet object per month + signed manifest + schema document. The gate proves "no AiSOC code": **DuckDB** opens the object over s3 and its count matches the signed manifest. ## WS2.4 — Scoped legal holds (migration 172) Holds gain `covers_from`/`covers_until`. A `user`/`host`/`ip` hold now **exempts exactly its own rows** from the retention purge — the Postgres alert DELETE through the affected-* arrays, the ClickHouse mutation through user/hostname/IP columns (addresses compared as addresses: `toIPv6OrDefault`, because IPv6 columns render v4 mapped), each within the hold's window, **every value a bind**. The rest of the tenant purges on schedule. This deliberately supersedes the recorded whole-tenant freeze — the superseded test now pins the narrowing — while a tenant-wide hold still freezes everything, because that is what it means. The lake TTL stays untouchable: a hold older than 400 days is only satisfiable through the archive tier, and the new **retention attestation** (`GET /lake/retention-attestation`) says so — each tier from its own store, "not measured" where a store cannot answer. ## Testing - **`tests/isolation/test_lake_archive_live.py` — 9 cases on real ClickHouse 23.8 + MinIO + Postgres** (new `integration.yml` step provisions all three; no-skip guard): export→manifest→verify green path; open-month refusal; garbage corruption fails; **same-count content swap caught by checksum alone**; rehydration lands tenant-scoped and explorer-queryable; estimate honesty; DuckDB portability; **held rows survive the live purge (5→3) while unheld rows delete**; attestation from real stores. - `services/api/tests/test_lake_archive.py` — 20 unit cases (paths/windows, destination refusals, cost honesty both ways, scratch-table namespace pinning, explorer-arm cannot widen, hold-exemption composers never interpolate a value, IPv6-as-address, `covers()` window semantics). - Full API suite **5,577 passed**; lake_sql + retention suites green with the superseded freeze test rewritten to pin the narrowing. **Negative controls (applied, observed failing, restored):** 1. Disabling the SHA-256 comparison → `test_a_same_count_content_swap_is_caught_by_the_checksum_alone` fails (the count leg cannot see it). 2. Removing the exemption composition from the alerts purge → the live hold test fails at 5 ≠ 3 (held rows purged). ## Gates route_auth OK · route_tenant_scope OK · tenant_query_predicates OK (ratchet 80 → **85**, five sweep statements recorded with the approval_expiry/sessions enumeration shapes) · module_reachability OK · migration_numbering OK (170–172, allocated block) · ORM parity OK · mypy baseline OK (which caught real API mismatches: `emit_audit` signature, `CredentialVault` construction — fixed, not ignored) · ruff clean · claim matrix **+3 GATED rows, 410 — 401/9/0** recomputed by the script · readme_gates OK · OpenAPI regenerated (additive) · README's "not a SIEM replacement" sentence updated to the proven scope · new ops doc `operations/lake-archive` in the sidebar. ## Could not verify - GCS/Azure arms: the client interface is S3-compatible-first; GCS interop/Azure need their own arms (stated in docs, not claimed). - WORM/Object-Lock: bucket properties this service does not manage; recorded as a declaration and reported as such, never as verified. - The sweep worker's scheduling is wired through the same guarded-lease path as the other workers but was exercised via `run_once` in the live suite, not through a multi-hour soak. |
||
|
|
4c9b24a5d1 |
feat(hunt): bounded campaigns, hypothesis selection and lead verification (WS6) (#2010)
## What WS6 of the gap-closure program: agentic hunting campaigns. WS6.3 (governed intake) shipped earlier in PR #1116; this PR is 6.1, 6.2 and 6.4, plus 6.3's approval gate carried into campaign selection. ## WS6.1 — Bounded campaigns (`app/hunt/campaign.py`) A campaign is a **sequence of distinct closed-schema plans**. The single-hunt agent is untouched — one plan, one correction, the model never writes query text (`check_hunt_agent_boundary` unchanged and green). The campaign adds the loop under rules that keep a loop honest: - **Summaries, never rows**: the next step's prompt carries row counts and top values passed through the egress pseudonymizer (`app/privacy`) — the test asserts the raw hostname is ABSENT from the second prompt while counts survive. - **Budgets gate BEFORE each step** (steps / rows / model calls / wall clock): an exhausted budget prevents the step — the test proves step two never executes. - **Not a retry loop**: every step must state the NEW question it answers; a repeated question stops the campaign, an identical plan under new words stops it, and two refused plans in a row trip the one-correction rule (a flag-reset bug here was caught by the test's first run — the budget absorbed the loop — and fixed with a streak counter). - **Outcomes kept apart**: ranked leads; **no-finding with a coverage statement** naming sources, fields searched and max lookback; could-not-check. Every step, refusal and stop lands in the Investigation Ledger with the budget state. ## WS6.2 — The hypothesis scheduler (`app/hunt/hypothesis_scheduler.py`, migration 179) Three deterministic schedulers existed; none SELECTED hypotheses or dispatched the LLM hunt agent. This is the selection layer: per tenant, **opt-in (default OFF)**, cadenced (`hunt_campaign_policies`), budgeted (per-tenant `CampaignBudgets` overrides), capped per tick, and **every selection is recorded in the ledger WITH its reason before the campaign starts**. Selection sources this revision: **approved hunt requests** not yet campaigned (`campaigned_at` marks one-request-one-campaign). **Recorded follow-ups, named rather than silently absent**: the coverage-gap ranker, KEV-exposure matches, and new-intel sources plug into the same `select_for_tenant` seam. ## WS6.3 remainder — approval precedes execution `_APPROVED_UNCAMPAIGNED_SQL` selects only `approved_at IS NOT NULL`; the test proves an unapproved request is never selected and the campaign runner is never awaited. ## WS6.4 — Lead verification and the real proposal id - **Leads → the investigation agent**: each top lead (capped at 3 — the investigator is the expensive half) becomes a `HUNT LEAD`-labelled state run through `run_deep_investigation` under its own run; verdicts ride back on the lead dicts. - **The long-declared, never-assigned `proposal_id` is finally real**: a productive campaign posts to the new `POST /agent-tools/hunt-plan/propose-detection` (same `rules:write`-governed surface class as the operator path), which writes the same DRAFT scaffold the saved-hunt path writes (`source: hunt-campaign`) — the reviewer reads the campaign's questions and plans, and **nothing auto-promotes**. ## Testing - `test_hunt_campaign.py` — **9 cases** through the real plan validator (summary hand-off with scrubbing asserted at the prompt; budget prevention; both repeat-stops; one-correction; coverage statement; could-not-check; count-preserving scrub). - `test_hypothesis_scheduler.py` — **5 cases** (approved-runs-once with reason recorded BEFORE launch; unapproved-never-selected; per-tick cap 2-of-5; verify-then-propose ordering; investigator cap + labelling). - Full targeted agents suites green; the 41 collection errors in the local venv are pre-existing (identical on the clean tree — this venv lacks `mcp`; CI's agents env carries it). ## Gates check_hunt_agent_boundary OK · migration_numbering OK (179, allocated) · mypy baseline OK · ruff clean · claim matrix **+2 GATED rows** (tallies recomputed) · readme_gates OK · OpenAPI regenerated (additive — the propose-detection route). ## Could not verify - A live LLM driving a campaign end-to-end (no funded key in this environment): every step runs through the real validator and the scripted-invoke seam is the same one the single-hunt suite uses. - The scheduler against live Postgres: its SQL mirrors shapes proven live elsewhere (policy enumeration, marked-once updates); the fake honours the approval gate the way the WHERE clause does, and the live migration applies in CI's chain. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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). |
||
|
|
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.
|
||
|
|
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).
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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.
|
||
|
|
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. |
||
|
|
0553d9aebf |
fix(pipeline): sink-rejection durability, dead Zscaler feed, realtime consumer teardown (#1996)
## Data-pipeline integrity wave A full review of the data pipelines and integrations: 96-hour soak-log harvest from a live stack, live reproduction of each finding, vendor-contract verification, and an end-to-end ingest → fusion → alert → AI-triage pass. Three product defects found and fixed. ### 1. Threat-intel: a sink that refuses documents had them marked as stored (permanent per-sink gap) `async_bulk(raise_on_error=False)` reports per-item rejections by **returning** them, so a disk flood-stage 429 (`cluster_block_exception`) came back through the no-exception path, the pipeline recorded per-sink dedup keys for documents OpenSearch had **refused**, and every later poll read them as duplicates. Reproduced live: the KEV corpus in Qdrant and Neo4j, **zero documents in `threatintel-iocs`, permanently** — the index `match_ioc_values` (actor attribution) reads. The warning log said only "4 bulk errors", hiding the one string an operator needed. Fix: `bulk_index_iocs` returns a `BulkIndexOutcome` naming rejected ids + vendor reasons (now logged); the pipeline withholds exactly the refused documents from its dedup record so they re-offer next poll (idempotent upserts — re-requests, never duplicates). This completes the #1278 backfill for the rejected-not-unreachable failure mode. Tests: `test_pipeline_sink_rejection.py` (4) — re-offer of exactly the refused docs, wholesale-block backfill after the block clears, dedup positive control, outcome extraction with reasons. Suite cannot pass pre-fix. ### 2. Zscaler connector: polling a route the vendor does not serve (never returned an event anywhere) `fetch_alerts` POSTed `startTime/endTime/pageSize` to `/api/v1/webApplicationRules` — in Zscaler's published API that's Cloud App Control **policy CRUD** (routes are `GET|POST /webApplicationRules/{rule_type}`; the POST *creates a rule*), so the request matched no route. Independently, `_obfuscate_api_key` skipped the published algorithm's first loop and the `+2` offset — **authentication could never have succeeded either**. ZIA has no pull API for web logs (NSS push only). Fix: rewritten against the one pull feed ZIA documents — the **admin audit log report** (`POST /auditlogEntryReport` → poll `statusId` to `COMPLETE` → download CSV): event-time cursor + one-interval overlap (#1970/#1971), continuation across the vendor's 1,000-record report cap (announced when the bound binds), stable digest ids for id-less rows, admin-timezone timestamps parsed to UTC where unambiguous (unparseable keeps the row), **no invented severity** (audit entries publish none — the Sophos rule). Paging debt ceiling falls **48 → 47**; checkpoint-adopter registry records zscaler. Docs regenerated from the schema. Tests: `test_zscaler.py` (12) — obfuscation against an independently-written reference, CSV preamble/timezone/id parsing, full report flow, 401-reauth-once, ERRORED with vendor reason, page continuation, nothing touches `webApplicationRules`, schema honesty. ### 3. Realtime: crashed Kafka consumers leaked (16 instances over the soak) The supervisor reattached after kafkajs crashes (offset-manager `TypeError`, fetch timeouts) but never disconnected the crashed instance — each crash leaked a consumer's sockets and timers for the process lifetime. Starters now return the consumer handle; the supervisor tears it down best-effort before replacing it (and tolerates the disabled-by-config starter). Type-check + 41 realtime tests green. ### Live E2E evidence (current images) - ingest accept → fusion alert row: **1.6 s**; auto-triage verdict `true_positive` @0.8 on the local model (1,235/126 tokens, 31 s CPU), below the 0.85 default-deny threshold → escalated, ledger-persisted. - Console read path: login → alert envelope (narrative, 5 entities, status `triaged`). Dead-letters: 0/24 h. - Enrichment auth: garbage bearer → **401**; authenticated → 200 honest-empty (no provider keys). One deployment finding, no code change: a QA stack ran a **mixed-version fleet** (enrichment/ueba on v21.0.0 `:latest` pulled pre-GHSA-qf6m, rest v23.5.0) — on the stale image the enrichment auth of GHSA-qf6m is absent. Current images verified correct; the stack was refreshed to v23.6.1. `make upgrade` (which pulls) prevents this; a bare `up` after a partial pull does not. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
7eea286f6a |
feat(notifications): per-device minimum severity for Web Push (carry of #1978 by @knowlet) (#1979)
Carry of #1978 by @knowlet — all code and commits are theirs, authorship preserved on every commit. ## Why a carry #1978 went `CONFLICTING` after #1977 merged: both PRs append to the `[Unreleased]` section of `CHANGELOG.md`. The branch lives on a fork this repository's token cannot push to by any route, so the conflict cannot be resolved in place. This branch is #1978's head merged onto current `main`, with the one `CHANGELOG.md` conflict resolved by keeping both PRs' entries verbatim (`### Added` for this PR, above #1977's `### Fixed`, matching the section order every released section uses). ## What ships (from #1978) - **Per-device minimum severity for fused-alert Web Push notifications** in Settings → Notifications and Responder settings (Critical / High / Medium / Low), with the threshold enforced in `services/realtime` push dispatch. - Existing subscriptions without a stored threshold keep receiving High and Critical alerts. - The Desktop notifications control scopes only fused-alert pushes — agent approvals, on-call hand-offs and manual test pushes are not silenced. - Docs: `apps/docs/docs/operations/notifications.md` walkthrough with console screenshots. - Tests: realtime severity + topic-retention suites, console/PWA notification settings tests. ## Verification - Only `CHANGELOG.md` conflicted in the merge; everything else is #1978's diff untouched. - `python3 scripts/check_changelog_frozen.py` — OK - `python3 scripts/check_attribution.py --diff-base origin/main` — OK (16 files scanned) - Pushed head tree verified identical to the locally merged tree. Closes #1978. --------- Signed-off-by: knowlet <4388697+knowlet@users.noreply.github.com> Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com> Co-authored-by: Albert Hsieh <knowlet@users.noreply.github.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
2bf19641fa |
docs: restore backticks around the huntress subdomain placeholder (#1963)
## What Restores the multi-token MDX placeholder escape in `scripts/generate_connector_docs.py` (with the docstring that records why it exists) and regenerates `apps/docs/docs/connectors/huntress.md` — two files, ten lines. ## Why [#1961](https://github.com/beenuar/AiSOC/pull/1961) regressed `_mdx_safe` to the single-token placeholder pattern and deleted the comment warning against exactly that: `<your subdomain>` parses in MDX as an unclosed JSX tag (`your` with a boolean `subdomain` attribute), and this precise Huntress help text once broke the docs deploy for six days. The regenerated page shipped without backticks, and **Deploy Docs to GitHub Pages failed on the merge commit** ([run 44238855720](https://github.com/beenuar/AiSOC/actions/runs/44238855720), `end-tag-mismatch`, line 22). The Docusaurus build only runs on push to `main`, so #1961's 129 green checks never exercised it; the connector-docs gate *did* catch the first draft of this fix when it patched the page without the generator — the page is generated, so the fix has to be at the source. ## Verification - `python3 scripts/generate_connector_docs.py --check`: OK — 97 connectors documented; the restored generator reproduces the fixed `huntress.md` byte-for-byte (0 pages rewritten after the manual fix). - `pnpm --filter @aisoc/docs build` passes on this tree; the identical tree without the fix is the failing CI run above. - `ruff format --check` / `ruff check` green on the changed script. - A sweep of every docs file #1961 touched (fence- and inline-code-aware) found no other unbackticked angle-bracket placeholder. Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
6887191e76 |
docs(visuals): refresh README screenshots + walkthrough on a live v23.5.0 stack (#1961)
## What Every README/console image and the deployment walkthrough, re-captured against a **real v23.5.0 deployment** — images pulled from `ghcr.io`, demo mode off, nothing seeded, driven through the console's own flows. The user asked for full product visibility with a great demo and *nothing faked*; this is that, and refusing to fake it surfaced two real defects (fixed below). ### Visuals - **17 console tiles** re-shot at v23.5.0 (footer reads `v23.5.0`), plus two new ones for this release's headline features: the **entity-risk queue** with the hosts each entity was *seen on*, and the **related-cases** panel resolving a genuinely shared alert. - **`attack-graph.png` is now a genuine full-profile capture** with Neo4j live (users/hosts/IPs/network-paths over real ingested telemetry), replacing the back-level v10.0.0 still — the honesty caveat in the guide is simply gone. - **`demo.mp4` (2 m 1 s) and `hero.gif` re-cut.** Opening card → real cold `make up` (asciinema, idle capped, password `sed`-filtered) → sign-in → sample load through the real ingest path → alert queue → **real local-model triage verdict** in the rail → entity-risk queue → KEV feed → cost dashboard → `make smoke` 10/10. All five alerts were triaged by the bundled `llama3.2:3b` through the gateway (~1,245 prompt tokens, ~25 s each on CPU), **not** the deterministic fallback the old recording showed. - Both provenance READMEs and the **technical guide** rewritten to match (KEV 1,754→1,782, catalogue 2,614→3,045, playbooks 63→64, graph caption, the `?status=open` paragraph), guide → v1.5, **PDF re-rendered** (papers digest gate green). - Screenshots palette-quantized (near-lossless on flat dark UI) and the PDF reduced from 6.5 MB → 3.1 MB, so the refresh adds **~5 MB to a clone, not ~15 MB**. ### Two real defects found while capturing (fixed here, tree-derived tests) 1. **The v23.5.0 "sixteenth secret" never reached the service that enforces it.** The actor-attribution token the release notes describe was neither generated by `ensure_env` nor delivered by compose to `threatintel` (enforcer) or `agents` (caller), so a fresh `make up` answered **503 for every `/api/v1/actors/*` call** with all secrets "correctly" generated. Now generated and wired to both ends; pinned by `tests/test_threatintel_token_wiring.py`, which discovers the readers from source and asserts compose delivers to each. 2. **`GET /cases?status=open` matched zero rows.** `open` is a write-path alias the read path string-matched literally, so the console's *add to existing case* picker always showed an empty list and the related-cases path was unreachable. The alias now expands to `case_status.OPEN_STATUSES`; pinned by `services/api/tests/test_cases_open_alias.py`. ## Provenance / honesty Captured on 2026-11-18 from a v23.5.0 stack carrying the two fixes above. Demo mode off, no hosted provider ever configured, the two cases created through the console's escalate flow and their relationship resolved from a real shared alert. Every claim in the screenshot captions was checked against the pixels. No secrets or machine paths in the tree (swept). ## Verification - `tests/test_threatintel_token_wiring.py` (3) + `services/api/tests/test_cases_open_alias.py` (2) pass; `test_cases_tenant_isolation.py` still green. - `render_white_paper.py --check`, `readme_gates.py`, `check_competitor_names.py`, `check_attribution.py --all` all green locally. - Live end-to-end: fresh `make up` → wizard sample load → 5/5 alerts triaged by the local model → `make smoke` 10/10; `make up-full` → Neo4j populated (1,782 IOCs + users/hosts/IPs) → graph renders. --------- Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
c123ad6312 |
fix(docs): escape the raw placeholder that broke every docs deploy since Nov 12 (#1960)
## What One character class, six days of silent breakage: the Huntress setup table's `api_secret` cell says the secret is "Generated with the API key at <your subdomain>.huntress.io" — and MDX parses a bare angle-bracket placeholder in prose as an unclosed JSX tag (`Expected a closing tag for \`<your>\``), which fails the whole Docusaurus build. **Deploy Docs to GitHub Pages has failed on every push to main since the connector landed** — last green deploy 2026-11-12 (`468abb5b9`), 15 consecutive failures since — so the live portal is frozen on pre-v23.4.0 content. The v23.4.0 and v23.5.0 docs, including the three new connector pages (ESET PROTECT, WithSecure Elements, Vectra AI Platform), never published. Per-PR CI never caught it because the Docusaurus build only runs in the deploy workflow, on push to main. ## Fix Backtick-wrap the hostname so it is a code span, which MDX does not parse. One line. ## Verification Ran the deploy job's own command locally from this tree: `pnpm build` in `apps/docs` compiles both bundles and generates static files (`[SUCCESS] Generated static files`). The build walks every doc, so this also confirms huntress.md was the tree's only prose-context raw tag — a strip-fences-and-code-spans scan over `apps/docs` agreed (every other candidate sits inside a fence or a multi-line code span, in files older than the breakage window). |
||
|
|
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> |
||
|
|
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> |
||
|
|
ef5d9d30a4 |
Merge pull request #1952 from knowlet/feat/explainable-related-cases
feat(cases): expose related cases with shared evidence |
||
|
|
6d6300c0dc |
fix(fusion): preserve Wazuh event identity and repeat occurrences
Signed-off-by: Albert Hsieh <knowlet@users.noreply.github.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
fcbed0fae3 |
chore(env): the sixteenth generated secret ships its empty line and its published count
The placeholder gate holds three surfaces to one fact: a secret ensure_env generates must appear (empty) in .env.example, and the counted prose in README.md and the docker guide must say how many there are. All three move together for AISOC_THREATINTEL_SERVICE_TOKEN. |
||
|
|
520b94b7b1 |
Merge pull request #1905 from beenuar/carry/ms-cert-auth
feat(connectors): certificate auth for Entra ID and M365 audit (carries #1897) |
||
|
|
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. |
||
|
|
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> |
||
|
|
6854d4a32d |
fix(connectors): eset_protect opens its window at the occurTime cursor (#1892)
## Summary Closes #1890, the follow-up filed at #1885's merge. ESET filters `/v1/detections` on `occurTime` — when the detection happened on the device — so a laptop that spent the night offline uploads last night's detections stamped inside windows already polled, and the clock-derived `[now − since, now)` never requested them again. The connector shipped documenting that honestly as a vendor property; this makes it a swept gap instead of a permanent one. ## Mechanism — the same watermark Wazuh uses (#1866) - `checkpoint_time_field = ("occurTime",)`, `checkpoint_id_field = ("uuid",)` — both top-level on every detection, so the base accessors read them without overrides. - `fetch_alerts` opens the request window at `checkpointed_since_seconds(since_seconds)`: successful-but-empty polls hold the left edge, the window grows over a gap instead of sliding past it, growth bounded by the seven-day cap. - `apply_checkpoint(inside)` drops what the overlap re-reads and stages the advance on the **newest `occurTime` read** — not the wall clock — so a reconnecting endpoint's backlog is swept on the next poll; the scheduler persists the cursor only after ingest accepts the batch. ## Tests (five, driving the real connector + real checkpoint machinery, transport faked) - No cursor → the window is since_seconds unchanged (first-poll behaviour identical). - A cursor eight hours back → the request opens there and the late-uploaded detection is raised. - The row the cursor itself names → deduplicated, not re-raised. - The staged advance lands on the newest `occurTime` read, with its uuid. - A 30-day-old cursor → bounded at `max_checkpoint_lookback_seconds`. 94/94 locally with the existing ESET suite; paging gate OK; changelog freeze OK. Docs caution rewritten from "isn't requested again" to the sweep semantics. --------- Co-authored-by: beenuar <beenuar@users.noreply.github.com> |
||
|
|
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> |
||
|
|
14e3e5a1c9 |
docs(federated-search): document the feature as on-by-default, not opt-in
AISOC_FEATURE_FED_SEARCH defaults to true in the API config, so federated search is served on a stock install. The "Enabling it" section was backwards: it told operators to set the flag to true to turn it on and said an unset flag yields 404. The flag is opt-out — 404 is returned only when it is explicitly false. Reframe the section as "Turning it off". Signed-off-by: Kyrylo N <98964984+43n51c@users.noreply.github.com> |
||
|
|
b97e703ba3 |
fix(wazuh): open the poll window at the durable cursor so a source-side outage backfills (#1860) (#1866)
## Summary Fixes **#1860**: a source-side outage permanently deleted its window from the lake. @pitimon proved it in production with canary events — the Wazuh indexer spent ~8h behind a flood-stage watermark while the connector polled *successfully* the whole time (empty windows, fresh `last_sync`, zero errors), so the outage-backfill worker — keyed on the connector's **own** failures — never fired, and when filebeat drained, the canaries landed with original timestamps inside windows already polled. `[now - since, now]` had moved on; nothing ever requested them again. ## Fix Direction (1) from the issue, built on the checkpoint machinery the platform already has: - **The wazuh alert stream declares the event-time watermark** (`_source.@timestamp` + `_id`, with the row accessors overridden for the indexer's nesting). The scheduler already persists the staged cursor only after ingest accepts every submitted event, so the cursor is exactly "the last *accepted* event". - **New in the base contract: `checkpointed_since_seconds()`** — the first place the cursor *opens the request window* rather than only de-duplicating it. Successful-but-empty polls hold the window's left edge in place, so the window **grows over the gap** instead of sliding past it; the late backlog is requested the moment it becomes queryable, and `apply_checkpoint` drops what the 60s clock-skew overlap re-reads before resubmission. - **Bounded**: one poll widens at most 7 days past the cursor (`max_checkpoint_lookback_seconds`), with the cap binding logged at warning — a capped backfill is a data-loss decision an operator should see. - **Composes with #1820's paging into incremental backfill**: a backlog larger than the page cap advances the cursor exactly as far as was read; the next poll resumes there. - **Manual backfill** (direction 3) falls out of the same knob: `PATCH /api/v1/connectors/{id}` with `connector_config.checkpoint.time` rewound re-reads from there, duplicates collapsed downstream. Documented in the wazuh connector page's new "Backfill after a source-side outage" section. - The vulnerability stream deliberately stays on the clock window — one instance persists one cursor, and splitting it across two streams would let whichever read last drag the other's left edge forward (stated in its docstring). ## Tests `test_wazuh_checkpoint_backfill.py` drives the issue's reported sequence end to end against the real connector and real checkpoint machinery (only the HTTP transport stubbed): healthy poll → cursor persists; outage poll succeeds empty → cursor held; recovery poll **requests the whole 8h gap and both canaries come out**, cursor advancing past them. Plus: no-cursor first poll identical to today, lookback cap bound, unparseable cursor falls back to the clock window, and overlap rows are deduped, not resubmitted. **Negative control reproduced: 5 of 6 tests fail against `main`'s connector** (the passing one is the unchanged no-cursor baseline). The checkpoint-contract roster records wazuh with the reason. Full connectors suite: **1,759 passed**. Conformance matrix check OK; ruff + format clean; changelog freeze OK. ## Scope note Every watermark connector shares this failure shape — the helper is on `BaseConnector` precisely so adoption is a two-line change per connector — but each adoption needs its own window-semantics review (ordered drain assumptions, vendor timestamp fields), so this PR converts wazuh (the proven case) and leaves the class-wide rollout as follow-up work rather than bulk-editing 90 connectors unreviewed. |
||
|
|
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> |
||
|
|
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. |
||
|
|
eaefdbfc1c |
chore(huntress): re-derive generated surfaces against post-v23.3.0 main
The carry lands after cisco_secure_endpoint and the v23.3.0 cut, so the marketplace indexes and curated manifest are regenerated rather than hand-merged, and plugins/huntress/plugin.yaml names 23.4.0 — the first release that will contain the connector — instead of the 23.2.0 the branch was authored against. Co-authored-by: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> |
||
|
|
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>
|
||
|
|
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. |
||
|
|
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> |
||
|
|
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). |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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. |
||
|
|
b3d619fe9b |
fix(connectors): validate the Splunk index token before it reaches SPL; stop the hunt tutorial promising replay-grading the community tier never runs (#1810)
Three queued follow-ups from today's security review and the #1804 merge, landed as one small PR. ## 1. Splunk `index=` token validation (defence in depth) Both ad-hoc search paths — `_dispatch()` on the polling side and `query()` on the federated side — strip `index=` from the operator-supplied `saved_search` and interpolate the remainder **unquoted** into SPL, so a configured value like `main | collect index=other` dispatched a two-stage pipeline the configuration never meant to write. Not exploitable across a trust boundary (the operator already holds the Splunk token), but nothing downstream re-validates, so the connector now holds the same line the AQL translator holds for identifiers: - `re.fullmatch(r"[A-Za-z0-9_*:\-]+", index)` on the stripped token, in both paths; - on refusal, fall back to the default `notable` index with a `splunk.index_token.rejected` warning naming the rejected value — never dispatch a search the configuration never meant to write; - wildcards, cluster prefixes (`cluster:sec_ops-*`), underscores and dashes pass through unchanged — a validator that rejects real index names trades an injection for a broken deployment. Tests pin both directions on both paths (hostile value → `search index=notable …` with no `collect`; full legitimate charset survives verbatim). Suites run: `test_splunk_connector.py` + `test_federated.py` (26 passed), `test_federated_aql.py` (4 passed). ## 2. `hello-hunt.md` honesty fix The tutorial told contributors a community rule is "replay-graded against its fixtures". It is not: `scripts/validate_detections.py` calls `replay_fixture` only for `tier == "native"` (the rules with a compiled spec; see ~L466) — community fixtures ship alongside the rule and are first replayed at promotion. The `enabled` bullet now says exactly that. Wording verified against the validator's actual behaviour, not its docstring. ## 3. Technical-guide count re-sync — checked, deliberately unchanged The community rule merged in #1804 moved the on-disk detection total 7,407 → 7,408. `apps/web/content/papers/aisoc-technical-guide.md` quotes **no** on-disk total anywhere; its only corpus figure is "2,966 executable detection rules", which matches the regenerated `corpus-stats.json` exactly (community rules are catalogue-only and do not move the executable count). No markdown change, no PDF regeneration needed. ## Eval harness Not applicable — no substrate, playbook, or detection-content change (docs wording + connector input validation only). _Ruff format and lint are clean on every Python file this PR touches._ --------- Signed-off-by: beenuar <beenu.a.arora@gmail.com> |
||
|
|
6cb8030738 |
feat(detections): flag AI agents reading credential files, and fix the two catalogue claims that were false (#1804)
## Summary Adds the first community detection rule: an AI agent's file tool reading a credential file (`~/.ssh/id_rsa`, `~/.aws/credentials`, …) — T1552.001, which prompt-level secret scanning cannot see, because the prompt is clean and the disclosure happens on the way out (into the model context, a tool argument, or a second call). Writing it surfaced three catalogue/portability bugs, all fixed here: the `quarantine_reason` fallback asserted `enabled: false` about a rule file the builder never opened; the marketplace, corpus-stats, truth-table, llms and curation generators wrote the platform's line endings and `str(Path)` separators, so their `--check` compared text that had already translated the difference away; and `hello-hunt.md` instructed contributors to do the one thing `detection_truth_table.py --check` rejects. Regenerated: the marketplace index (three copies), the corpus stats, the detection truth table, and the llms.txt pair. The published rule counts follow: 7408 on disk, 4442 not loaded. ## Type of change - [x] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [x] Documentation update - [ ] Refactor / tech debt - [ ] CI / infra change ## Related issues Nothing closed by this PR; no tracking issue existed for these bugs. - Relates to #357 (detection rule contributions wanted / community rules) — this is the first rule under `detections/community/application/`. - Relates to #978 and #898, which introduced and later widened the `quarantine_reason` / executable-split surface corrected here. ## Changes **New rule + fixtures** - `detections/community/application/ai-agent-credential-file-read.yaml` — `community-toufiqtoufiqbo-ai-agent-credential-file-read`, high, `application`, T1552.001. Matches the `ai_runtime` fields the `aisoc-ai-sdk` actually emits (`tool_name`, `resource` — both string literals in `aisoc_ai/client.py`), excludes public-key reads (`*.pub`, `authorized_keys`), and does not fire on model calls. It ships `enabled: false` with a `quarantine_reason`, because the truth-table gate refuses an enabled rule the engine never loads and nothing walks `detections/community/` into the compiled rule set. - `detections/fixtures/{positive,negative}/ai-agent-credential-file-read.json`. **Truthful `quarantine_reason`** - `scripts/build_marketplace.py` — new `_why_not_executable()`. The old fallback told every non-quarantined, non-executable row that it was "disabled in the rule file (`enabled: false`)" — a claim about a file the builder never opened, reached precisely when it had not looked. The reason now names the real cause per tier, and the rule's own `quarantine_reason` still wins when the file carries one. - `apps/docs/docs/detections/hello-hunt.md` — the tutorial said "`enabled: true` controls whether the rule runs in production. Community rules ship as `true` by default." Both halves are false: nothing loads a community rule, and `detection_truth_table.py --check` fails one that claims to be enabled. It now says what the gate enforces — `enabled: false` plus a `quarantine_reason` naming what promotion would take. - `tests/test_marketplace_executable_split.py` — `test_a_reason_that_names_the_rule_file_is_true_of_it` walks every reference-only entry whose reason quotes `enabled: false` (99 today), reads the rule file it cites, and fails if the flag disagrees. It also fails if it ever ends up checking nothing. **LF / POSIX artefacts, byte-level `--check`** - `scripts/build_marketplace.py`, `scripts/curate_detections.py`, `scripts/generate_corpus_stats.py`, `scripts/detection_truth_table.py`, `scripts/generate_llms_txt.py` — explicit `newline="\n"` on every artefact write; manifest `path` fields via `.as_posix()`. - The `--check` modes now compare **bytes** and reject `b"\r"`. In text mode the read translated CRLF away, so a CRLF file and an LF template agreed with each other and the drift was invisible. - `scripts/curate_detections.py` — the curated selection's `path` field used `str(Path)`. On Windows that is 601 backslashed paths, so `pnpm marketplace:curate --check` could never pass there and regenerating rewrote every entry. Now `.as_posix()`, and the check passes on Windows and Linux alike. **Regenerated** - `marketplace/index.json`, `apps/web/public/marketplace/index.json`, `services/api/app/data/marketplace/index.json` — byte-identical, LF, POSIX paths, 7582 items. - `apps/web/src/data/corpus-stats.json` — 2966 executable, 7408 on disk, 4442 quarantined. - `docs/detections/truth-table.md` — 7408 on disk, community 2, `enabled: false` 229. - `apps/docs/static/llms.txt`, `apps/docs/static/llms-full.txt` — the gate that first caught the stale on-disk count. - `README.md`, `apps/docs/docs/concepts/detections.md` — the published on-disk count (7407 → 7408), the tier line (`community=1` → `community=2`) and the not-loaded figure (4441 → 4442). `marketplace/curated.json` and `apps/docs/docs/detections/coverage.md` are deliberately unchanged: the curated selection is byte-identical once paths are POSIX, so there is nothing to regenerate, and touching them would rewrite all 601 entries for no content change. ## Testing - [x] Unit tests added / updated - [ ] Integration tests pass locally — see the two environment-only failures below - [x] Manually tested (describe steps below) <details> <summary>Manual test steps</summary> All commands run in the pushed tree, with `AISOC_REPO_ROOT` set (this machine has no `git` binary) and `PYTHONUTF8=1`. 1. Rule validator — all 7408 rules, including the new one, and its fixtures: ```text Validated 7408 rules — 7408 passed, 0 failed, 0 fixture warnings Tiers: community=2, imported=6113, native=1293 Executable (loaded by the engine): 2966; not loaded: 4442 ``` 2. Engine replay of the rule through the engine's own `_sigma_fallback`, five cases — the fourth is a Windows path, which `pathlib` would have normalised away before the `.as_posix()` fix: ```text PASS positive (private key): matched=1 expected=1 PASS negative (benign pdf): matched=0 expected=0 PASS public key exclusion: matched=0 expected=0 PASS windows credential path: matched=1 expected=1 PASS model call is not a file read: matched=0 expected=0 ``` 3. Artefact gates, all four, on Windows: ```text OK: detection truth table current — 2966 executable / 7408 on disk marketplace index is up to date in 3 locations (7582 items). check_marketplace_index_parity: OK — 3 identical copies, 7582 items all carrying a digest corpus-stats OK — 2966 executable across 7 categories, 7408 indexed on disk (4442 quarantined), 85 plugins, 64 playbook packs OK: llms.txt and llms-full.txt match their sources (2 files). curation up to date (601 curated, 122 techniques). ``` 4. `python -m pytest tests/test_marketplace_executable_split.py -q` → `10 passed` (was 9; the new test is the truthfulness one). 5. `ruff format --check .` clean over the whole tree (2979 files) and `ruff check services/ scripts/ tests/ tools/` clean — the two commands CI runs. 6. Byte-level check of all touched paths: all LF, no `\r` anywhere, including the three 11 MB index copies. 7. Regeneration is a no-op: every `--check` above passes immediately after the committed artefacts, on a Windows checkout — the platform the bugs were invisible on. **Two pre-existing local failures, not caused by this PR:** `tests/test_attribution_gate.py` and `tests/test_detection_attribution_gate.py` fail on this machine because they shell out to `git` and `bash`, neither of which exists here. They are untouched by this diff. </details> ## Screenshots (if UI changes) None — no UI change. (`corpus-stats.json` moves the counts the landing page reads; the numbers change, not the rendering.) ## Checklist - [x] My code follows the style guidelines of this project (`ruff`, `eslint`, `gofmt`) - [x] I have performed a self-review of my own code - [x] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally — all except the two `git`/`bash`-dependent gates noted above - [x] I have updated documentation as needed (README, CHANGELOG, CONTRIBUTING) - [x] My changes do not introduce new linter warnings - [x] I have checked for sensitive data / credentials in my diff ## Eval harness (required for substrate / playbook / detection changes) `python3 scripts/run_evals.py --json` on `3ec5fb1` (before) and on this branch (after), same machine, same synthetic dataset (200 deterministic cases). Both runs `all_passed: true`. The new rule is catalogue-only — it lives under `detections/community/`, which no engine path loads — so no eval input changes and the suites are identical, as expected. No axis regressed. <details> <summary><strong>Before</strong> (<code>scripts/run_evals.py</code> on <code>3ec5fb1</code>)</summary> ```text suite metric value target passed mitre_accuracy accuracy 0.97 >=0.8 true alert_reduction reduction_ratio 0.753 >=0.7 true investigation_completeness mean_keyword_coverage 0.9425 >=0.85 true response_quality mean_rubric_score 1.0 >=0.8 true hunt_corpus positive_scenario_catch_rate 1.0 >=1.0 true adversary_eval graceful_degradation_catch 0.475 >=0.4 true confidence_calibration investigation_brier_score 0.0646 <=0.18 true memory_recall memory_recall_accuracy 1.0 >=1.0 true override_accuracy override_accuracy 1.0 >=1.0 true playbook_completion_rate completion_rate 0.735 >=0.5 true detection_fp_rate worst_per_rule_fp_rate 0.0031 <=0.05 true all_passed: true ``` </details> <details> <summary><strong>After</strong> (<code>scripts/run_evals.py</code> on this branch)</summary> ```text suite metric value target passed mitre_accuracy accuracy 0.97 >=0.8 true alert_reduction reduction_ratio 0.753 >=0.7 true investigation_completeness mean_keyword_coverage 0.9425 >=0.85 true response_quality mean_rubric_score 1.0 >=0.8 true hunt_corpus positive_scenario_catch_rate 1.0 >=1.0 true adversary_eval graceful_degradation_catch 0.475 >=0.4 true confidence_calibration investigation_brier_score 0.0646 <=0.18 true memory_recall memory_recall_accuracy 1.0 >=1.0 true override_accuracy override_accuracy 1.0 >=1.0 true playbook_completion_rate completion_rate 0.735 >=0.5 true detection_fp_rate worst_per_rule_fp_rate 0.0031 <=0.05 true all_passed: true ``` </details> - [ ] Not applicable — this PR does not touch substrate, playbooks, detections, or eval inputs - [x] No axis regressed - [ ] An axis regressed; rationale and follow-up are described in the Summary above Signed-off-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com> Co-authored-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com> |