2 Commits
Author SHA1 Message Date
Beenu Arora d559f4f1a5 depth2(2.1-2.5): detection depth — scenario families, long-horizon identity, weak signals, API behaviour, coverage-gap ranking (#1602)
* chore(depth2): Lane C claims migrations 159-161 and ADR 0023

* fix(connectors): lift nested vendor fields into the engine namespace

The engine flattens raw_event exactly one level. Slack's signing-in
address is context.ip_address, an OAuth app's scopes are
entity.app.scopes, a Cloud Audit method is protoPayload.methodName --
all two or three levels down, so a rule clausing on any of them read
None and could never fire. Same shape as the Okta outcome.result
defect; fixed at the connector, not the matcher.

Six connectors lift 36 fields: slack_audit, salesforce, snowflake,
onepassword, gcp_cloud_audit, box. Snowflake additionally infers its
row shape from its own columns, because _kind is stamped only by this
connector's poller and a row arriving by replay fell to a branch that
emitted no event_type, no actor and no src_ip.

scripts/check_connector_field_lift.py runs the real connector over a
real-shaped vendor payload and asserts each name reaches the namespace.
Against a detached worktree at the pre-fix commit it exits 1 naming 35
of the 36 fields.

* feat(detections): named scenario families for Workspace, Apps Script, SaaS (depth2 2.1)

83 new executable rules in five declared families: workspace-takeover,
apps-script-impersonation, third-party-access, saas-data-movement and
saas-authentication-abuse. The family travels on the spec, through
export_detection_ruleset.py, into the artefact the engine loads, so the
console and make stats read one declared string rather than guessing a
family from a slug.

Two more connector lifts were needed first. google_workspace puts
everything that distinguishes one activity from another inside
events[].parameters -- the OAuth scopes a consent granted, the
visibility a share opened -- and events is a list, so the one-level
raw_event flatten could not reach any of it; each parameter is now
lifted as param_<name>. gcp_cloud_audit states whether a service or a
person acted, which is the discriminating clause of the Apps Script
family.

Refused rather than shipped: the plan's 'recovery changed, then the
password, within minutes' sequence. The windowed engine counts and
does not order, and 24 rules were already refused on that ground.
Ordered pairs go to the weak-signal aggregator in item 2.3.

Native executable 760 -> 843; unreachable rules unchanged at the
floor of 2.

* feat(stats): count cloud/identity/SaaS/code conditions, and delete 44 orphan rule files

make stats gains the depth plan 3.6 line: 565 conditions (cloud 301,
identity 134, saas 119, code 11), with the grouping pinned in code so
the figure stops being re-derivable two ways -- the first depth plan
measured it as both 461 and 395. --check ratchets the figure and prints
the 235-rule shortfall against the 800 target every run rather than
leaving the gap unstated.

Allocating ids for the new rules exposed a pre-existing defect.
generate_detections.py writes a YAML per spec and has never deleted one
whose spec went away, so 40 files from an earlier run carried ids no
spec owns. That is quiet until the lock reissues the number: the truth
table classifies a file as executable by asking whether its id is in
the engine's set, so two files sharing an id are counted twice. Four
collided immediately and the truth table published 2,617 against an
engine loading 2,613. 44 stale files deleted;
scripts/check_detection_yaml_orphans.py refuses both an unowned id and
a duplicated one, and exits 1 against the tree before the deletion.

Pinned counts moved together: README, REPOSITORY_REALITY, the claim
matrix, llms.txt, llms-full.txt, the truth table, corpus stats and the
marketplace index. Executable 2530 -> 2613; on disk 7015 -> 7054.

* feat(fusion): long-horizon identity accumulation over weeks (depth2 2.2)

The windowed engine's longest window is one day and it answers one
question: is a count high inside this window. An attack spread
deliberately thin against one account crosses no hourly threshold and
is forgotten by the next day. What separates it from a travelling
employee is not the count but the shape -- an attack widens the set of
networks that FAIL against one account while the succeeding set stays
small; a traveller widens both together.

services/fusion/app/services/long_horizon_identity.py accumulates
distinct source ASNs, countries and IPs per account per day over a
30-day horizon on the same Redis the baseline store uses, and publishes
breadth per side plus the ratio. Folded into the namespace by
DetectionEngine.evaluate_async beside the baseline store. Four rules
read it as the long-horizon-identity family.

Absent, not zero, throughout: an account with fewer than three active
days publishes no key, an unreachable store publishes no key, and the
ratio is undefined rather than enormous when no success was observed --
so a dormant account cannot fire the ratio rule. A saturated day is
reported as saturated rather than truncated, because being reached from
more networks than are worth enumerating is itself the finding.

Thresholds are a recorded rationale, NOT a measurement, and say so.
scripts/derive_long_horizon_thresholds.py surveyed 502 events across
the two telemetry corpora and found 0 carrying an account, a source
network and an outcome together, so it refuses to publish a derived
number and writes measured: false with the return-to-measured
condition.

* feat(fusion): weak-signal aggregation into one finding (depth2 2.3)

Several individually unalarming signals -- a new ASN, a new client
family, an anonymizing egress, a sub-principal deviation, a vendor risk
verdict, a credential change -- accumulate per session and per principal
inside an hour, and past a strength threshold become ONE finding listing
every contributor and its weight.

The plan's invariant that one geography or ASN change alone is never a
finding is held as a property of the weight table rather than left to
the next editor: a test asserts every weight is below the threshold, and
MIN_DISTINCT_KINDS stops one noisy integration repeating its way past
it. Strength counts each kind once at its weight plus a small increment
for repeats, so forty copies of one risk event cannot outscore a genuine
four-kind sequence.

This is where item 2.1's refused ordered pair lands. 'Recovery email
changed, then the password' is a sequence, the windowed engine counts
and does not order, and 24 rules were already refused on that ground --
so the pair accumulates here and the finding lists both halves in
arrival order.

Severity is the strongest contributor on the five-tier ladder;
confidence is a separate 0-100 derived from how far past the threshold
the strength sits and how many distinct kinds contributed.

The threshold is a RATIONALE, not a measurement, and says so.
scripts/calibrate_weak_signals.py loads all 72 balanced corpus items and
refuses to publish a sweep: the corpus carries vendor alert evidence
while every signal here is produced by fusion's enrichment, so all 72
score zero. Publishing recall 0.0000 would have stated 'the aggregator
detects nothing' having measured 'the corpus carries none of its
inputs'.

* feat(fusion): API behaviour from access logs (depth2 2.4)

Access logs AiSOC already ingests carried a path, a query, a method and
a status, and nothing read them as a shape -- /api/users/4821 and
/api/users/4822 were two unrelated strings, so neither an unknown
parameter on a known endpoint nor a walk across identifiers was visible.

services/fusion/app/services/api_behaviour.py templates the path,
learns per template which parameter names appear, what coarse type each
carries and which statuses it returns, and raises three signals:
unknown parameter, parameter type change, and one client walking many
identifiers. Three rules read them as the api-behaviour family.

Templating is deliberately conservative -- a segment is replaced only
when it is unambiguously an identifier, never because it looks unusual.
Over-templating merges genuinely different endpoints into one mixed
profile; under-templating leaves identifiers in the key and learns
nothing. A test pins both directions.

Off by default per tenant, checked before any Redis call, so a
deployment that ingests no access logs does no work. A template with
fewer than 50 requests reports nothing: on a new endpoint every
parameter is new, which is a property of the history rather than of the
request, and one client's walk is keyed by client so two clients cannot
pool into one enumeration.

* feat(api): rank detection coverage gaps against connected sources (depth2 2.5)

The governed proposal flow already ran end to end -- propose, evaluate,
backtest, decide with a separate approver, promote. What it never had
was a reason to start, so coverage grew wherever attention fell.

services/api/app/services/detection_coverage_gaps.py joins two things
the tree already knew and nothing had joined: which connectors this
tenant has enabled, and which executable rules and scenario families
exist for each connector's product. Exposed read-only at
GET /api/v1/detection-proposals/coverage-gaps, scoped to the caller's
own tenant.

It writes no proposal. Ranking a gap and drafting a rule are different
authorities, and the drafting path's separate-approver requirement
would be meaningless if the ranker could reach past it. An unmapped
connector is skipped rather than reported as a gap, because 'AiSOC has
no rules for this' and 'this ranker does not know what this connector
emits' are different statements and the second is a defect here.

A test proves the compiled corpus is readable from the API service: its
build context cannot see services/fusion, so a silent empty read would
report every connected source as uncovered -- the most alarming
possible way to be broken.

Eight claim-matrix rows added for Phase 2, two of them PARTIAL by the
author: the cloud/identity/SaaS/code count at 569 against the 800
target, and the weak-signal threshold whose calibration refuses. All
three tallies moved together.

* ci: wire the Phase 2 detection gates into validate-detections

check_scenario_family_alignment, check_connector_field_lift,
check_detection_yaml_orphans, project_stats --check and both threshold
derivations ran in no workflow, while the claim-matrix rows named
ci.yml :: python-lint as their gate. A gate nothing invokes is
indistinguishable from no gate and its presence implies coverage, which
is the defect check_gate_coverage.py exists to find -- and it found
these two directions apart: four by my own reading, two more
(calibrate_weak_signals, derive_long_horizon_thresholds) only because
their --check modes make them gates too.

Matrix rows corrected to name the workflow that actually runs them.

* fix(connectors): lift Entra audit targets, M365 parameters, GitLab and Confluence

Four more instances of the one-level flatten. Entra puts the account a
role was granted to inside targetResources -- a list -- with the role
itself nested again under modifiedProperties, so a role-grant rule could
name the category and nothing about what was granted. M365 puts the
address an inbox rule forwards to inside Parameters, which is the entire
content of the business-email-compromise detections. GitLab builds
event_type from a free-text custom_message so it carries spaces
('gitlab.added deploy key'), and its details dict held the object acted
on. Confluence's event_type carries the audit category, grouping every
permission change in the site under one value, with the granted account
and the new permission in two more lists.

Each gets a stable underscored key beside the original so a rule has
something to clause on and an analyst still reads the vendor's wording.
Only the first target of a list is lifted: almost every record has
exactly one, and a target_2 field a rule could not rely on would pass
its fixture and miss the real shape.

check_connector_field_lift now pins 61 fields across 10 connectors.
Against a detached worktree at origin/main it exits 1 naming 59 of
the 61.

* feat(detections): close depth plan 3.6 at 899 cloud/identity/SaaS/code conditions

330 new executable rules across GCP, Entra, Kubernetes, GitHub, GitLab,
M365, Okta, Atlassian, Box, Dropbox, 1Password, Salesforce and
Snowflake. 569 -> 899, so the 800 target is met and project_stats
--check now ASSERTS it rather than only ratcheting; the shortfall line
still prints either way, because that property is what made the earlier
PARTIAL honest.

Every rule is replayed through its real connector and the real engine
and watched to fire: the alignment gate covers 413 rules across 15
products, up from 83 across 8. Each spec carries the vendor envelope
that proves it, written in the vendor's own nesting -- a rule clausing
on new_value is proven by a payload carrying it three levels down in
targetResources[0].modifiedProperties[0].newValue, which a
clause-derived sample would never have. Keeping proof and rule adjacent
means a rule edited without its proof fails immediately.

A second id defect surfaced: a slug used twice in one category writes
ONE YAML and exports TWO engine rules, so the published total exceeds
the file count by the number of collisions -- the truth table read
2,949 against an engine loading 2,950. check_detection_yaml_orphans
now refuses a duplicate slug alongside a duplicate and an unowned id.

Unreachable rules unchanged at the floor of 2. Executable 2,620 ->
2,950; on disk 7,061 -> 7,391.

* feat(detections): depth plan 3.6 met — 907 cloud/identity/SaaS/code conditions

338 new executable rules, every one replayed through its real connector
and the real engine and watched to fire. 569 -> 907, so make stats
--check now ASSERTS the 800 target as well as ratcheting the measured
floor; the shortfall line still prints, because that property is what
made the PARTIAL honest and a reader needs to see the headroom.

Per-source minimums all met: aws 120/120, gcp 121/120, azure 151/150,
kubernetes 63/60, okta 63/60, github+gitlab 51/40, and every SaaS source
with a connector at or above 20.

The alignment gate covers 421 rules across 16 products, up from 83
across 8. Each spec carries the vendor envelope that proves it, written
in the vendor's own nesting; a rule edited without its proof fails
immediately. Four more connectors were lifted first (Entra audit
targets, M365 parameters, GitLab details, Confluence affected objects).

Two id defects found and gated, both in the class where the published
total exceeds the files: 44 orphans with ids no spec owns, and a slug
used twice in one category, which writes ONE YAML while exporting TWO
rules. check_detection_yaml_orphans refuses all three shapes and found
the second one itself -- the AWS batch collided with two existing
slugs, which were dropped rather than renamed because a second rule for
the same condition is noise.

The CloudTrail proof is worth recording: the connector reads the
LookupEvents envelope, so a sample shaped like a raw CloudTrail record
normalises with event_name empty and every identity field None. That
was the first attempt, and the replay is what caught it.

Matrix row flipped PARTIAL -> GATED by reaching the target, not by
relabelling. Executable 2,620 -> 2,958; on disk 7,061 -> 7,399;
unreachable unchanged at the floor of 2.

* fix(api): resync the packaged ruleset and move the catalogue pins

The API image carries a byte-identical copy of the compiled rulesets
because its build context cannot see services/fusion, and the merge
regeneration left it a step behind. Resynced, and the two pins the
catalogue test holds moved with it: the native artefact 764 -> 1192 and
the loaded catalogue total 2,613 -> 3,041.

Both are pins on what the engine actually loads, re-derived by running
fusion's own loaders rather than asserted, so moving them without the
artefact would have been the failure they exist to catch.

* fix(security): re-pin the rule-id lock's gitleaks fingerprints after 338 new rules

The allow-list pins by `path:rule:line`, so taking the lock from 865 slugs
to 1293 invalidated every entry below the first insertion. Re-derived with
the allow-list moved aside -- 28 fingerprints, up from 16 -- because the
findings a run reports *with* it in place are only the rotted ones, and
pinning that set silently drops every pin that was still landing.

Each addition was read first: all are the generic-api-key heuristic firing
on a detection slug that names what the rule hunts for, with a `det-*` rule
id as the value. Verified against the version CI pins, 8.21.2.

* chore: regenerate docs/openapi.yaml for the coverage-gap ranker

Item 2.5 added `GET /api/v1/detection-proposals/coverage-gaps` and the
committed spec had not been re-exported. A pure addition -- 56 lines, no
removals -- so the breaking-change policy is unaffected.

Exported under the version services/api/poetry.lock pins (pydantic 2.14.1);
the exporter refuses a drifted one precisely because a spec generated from
a venv that moved reads as a change nobody made.

* fix(detections): prove wave-2 2.1's thirty GitHub rules against the real connector

The scenario-family work added 30 GitHub-product specs and registered none
of them with `check_github_rule_alignment.py`, which requires a real-shaped
audit entry per rule. A genuine gap, not a stale artefact: `main` carries no
`gh-*` spec at all, so the gate was passing there for want of subjects.

Each entry carries the unprefixed action GitHub documents, cross-checked
against the independently transcribed vocabulary in
`vendor_event_vocabulary.py` rather than copied off the rule it proves --
the prefixing to `github.{action}` is the connector's work, and the point of
the gate is that the two agree. Issue #1545 found 11 of 12 rules clausing on
names nothing emits and one on an action GitHub does not have.

Not vacuous: substituting a plausible-but-wrong `org.member_added` for
`org.add_member` exits 1 naming the rule and both clause keys.

* docs(roadmap): collapse the Phase A line eight merges had duplicated

Every lane merge keeps both sides of ROADMAP.md, and the resolver only
dedupes table rows -- so the one Phase A line carrying a drifting rule
count forked instead of collapsing: four copies reached `main` saying
2538 and this branch added four saying 2966. The count gate caught it,
because a figure that disagrees with the tree is what it is for.

One line, the current number.

* fix(fusion): wire wave-2 items 2.2, 2.3 and 2.4 into the production path

All three modules were built, unit-tested and imported by nothing that
runs -- the defect `check_module_reachability.py` exists to name, and the
reason it is not cosmetic: a passing test on an uncalled module is
indistinguishable from a working feature. The engine had even grown a
`long_horizon` parameter for 2.2 that no caller ever supplied.

2.2 and 2.4 publish derived fields, so they join first-seen and baselines
in the enrichment pass before the corpus runs. That pass had a latent bug
of its own: the guard required first-seen or baselines to be present, so a
deployment configuring only the later stores skipped enrichment entirely.
Each store is now independent.

2.3 returns findings rather than fields, so the worker promotes each into
one alert naming every contributing signal in arrival order -- the whole
claim being that no single signal could have fired. It is fed the *same*
namespace the corpus just saw, through `DetectionEngine.namespace()`,
because it reads the first-seen novelty booleans and baseline deviation
scores computed directly above and a second caller deriving them its own
way is how two readers of one event come to disagree. Advisory like the
AI-estate recorder: an aggregator that cannot reach Redis logs and lets
the event keep its detections.

2.4 stays off per tenant, as the plan requires and the cost justifies.

`RawAlert` has no confidence field, so the aggregator's figure goes in the
description rather than being silently dropped by pydantic.

* chore: recompute after the third main merge (tally 360/354/6/0, 91 connectors)

* fix(detections): record the Okta proof envelope with the session-projection gate

`okta_entry()` builds a System Log event in Okta's own envelope for the
scenario-family proofs, and the gate flags any file naming
`externalSessionId` because the session key must have exactly one producer.

The field here is written and never read -- one occurrence, inside the dict
literal -- so there is no second derivation to disagree with session.go.
That is byte-for-byte the case the gate already allows for
`test_okta_identity_rules_are_reachable.py` beside it, and it is recorded
the same way rather than by dropping the field: a proof payload missing a
key every real Okta event carries is a less faithful stand-in for the event
it proves, which is the worse trade.

The gate's own self-test still detects a second deriver, a drifted closed
set, an invented fallback key and a missing declaration.

* chore: recompute after the fourth main merge

Tally 361/355/6/0 in all three published places, and the sandbox corpus
figures re-synced: main landed `sync_sandbox_corpus_figures.py` while this
branch was moving the corpus, so the generated `_corpus.py` was describing
a tree that no longer existed.

* docs(evidence-pack): drop the stale PARTIAL count a merge left beside the current one

The add/add resolution kept both sides of the sentence that indexes the
claim-to-gate matrix, so the paragraph stated 6 PARTIAL and 5 PARTIAL one
line apart. The matrix is the authority at 363 rows / 357 GATED / 6
PARTIAL, so the 5 is the stale half and is removed.

readme_gates.py cross-checks this sentence but matched the first copy and
passed over the second, which is why it reported OK against both figures.

* test(detections): derive the packaged-corpus total instead of typing it

`Python — Tests` failed on

    assert '2617 rules' in result.stdout
    E  assert ... 'OK — 4 identical artefact(s), 3045 rules'

The corpus is correct and the assertion was stale: this lane adds rules, so
the packaged total moved 2617 -> 3045. The figure was a literal inside a
*positive control* — the case whose whole job is to show the gate's clean
verdict means something — so it failed for a reason that says nothing about
whether the gate works, and the obvious repair is to retype 3045 and wait
for the next lane to hit it.

Summed from the four artefacts the control already copies, counted the way
`sync_packaged_detection_rulesets` counts them, so it cannot go stale. Still
an assertion rather than a tautology: it also refuses a zero total, and
dropping one artefact from the sum fails the control, which is the shape it
exists to catch — a clean run that reported a subset of the corpus.

* style: apply the pinned ruff formatter to the derived-total helper
2026-11-02 17:53:00 -08:00
Beenu Arora b751b47543 fix(detections): align GitHub rules with what the connector actually emits (#1545) (#1547)
* fix(detections): align GitHub rules with what the connector actually emits

Issue #1545 reported that GitHub native rules clause on event names and
fields the GitHub connector never produces. Measured by replaying
real-shaped audit entries through the real connector normalize() and the
real DetectionEngine: 1 of 12 GitHub rules could fire.

Fixed (meaning preserved, re-claused to GitHub's documented vocabulary):
- app-deploy-key-added-github: deploy_key.create is not a GitHub audit
  action; a deploy-key add is public_key.create with a repo slug.
- app-protected-branch-disabled: the two protected_branch.* values are
  real but were claused on event_type, which the connector prefixes
  github.{action}; now claused on the raw entry's action.
- github-public-repo-flip: repo.visibility_change does not exist; the
  action is repo.access and the entry carries public_repo, not visibility.
- app-self-hosted-runner-external: runner_register does not exist
  (org/repo.register_self_hosted_runner do), and ip_is_internal is now a
  real derived field computed from src_ip (absent, not false, when the
  org does not disclose IPs).
- ident-github-deploy-key-added-org-wide (windowed): action fixed to
  public_key.create and distinct_by fixed from repository to repo, the
  key audit entries actually carry.

Retired with recorded reasons (enrichment_decisions.py) because the org
audit log cannot carry their evidence: app-ci-workflow-modified-by-non-owner
(file paths, approver role), github-protected-branch-bypass (ref, actor
role), github-pii-pattern-push (diff contents),
ident-github-pat-classic-created-with-broad-scopes (classic-PAT creation
is not an org audit event; no created-token scopes anywhere),
app-token-broad-default (no permission map on app installs).

Verified correct and untouched: ident-github-org-2fa-disabled,
ta-github-rare-action-on-org-settings, ta-github-clone-volume-spike,
wd-ident-github-org-collaborator-removed-bulk.

New gate scripts/check_github_rule_alignment.py replays every GitHub rule
through the real connector and engine in validate-detections.yml, with a
self-test that injects the unprefixed-event_type defect and requires it
caught. The connector's _HIGH_RISK_ACTIONS drops two strings naming
actions GitHub never emits. README executable-rule counts move 2535 to
2530 and the previously unregistered claim site in the opening paragraph
is now pinned by generate_corpus_stats.py.

Closes #1545

* fix(detections): regenerate llms.txt + sync curated.json; drop unused self-test bindings

Three CI findings on #1547: the llms.txt artifacts embed the corpus
figures and went stale when the executable count moved to 2530; the
public copy of marketplace/curated.json was not refreshed when
curate_detections rewrote the canonical one; and CodeQL flagged the
alignment gate's self-test binding four locals it never reads — the
self-test proves the checker over a synthetic corpus, and the real
tree's inputs are exercised by --check immediately before it.

* fix(detections): move the catalogue figure to 2,609 everywhere it is pinned

The five issue #1545 retirements move the loaded catalogue 2,614 to
2,609 (760 + 1,770 stateless, 76 windowed, 3 sequence). The catalogue
tests pin the total deliberately so an accidental corpus change is loud;
this change is deliberate, so the pins move with it: the catalogue test
constants, the packaged-corpus positive control, the API route
descriptions that quote the figure (and the OpenAPI spec regenerated
from them under the API's locked dependency set — four description
lines, no structural drift), and the claim-to-gate matrix row.
2026-10-28 14:26:38 -07:00