mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* 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
637 lines
28 KiB
Python
637 lines
28 KiB
Python
#!/usr/bin/env python3
|
|
"""CI gate: a detection rule must match on fields some connector actually emits.
|
|
|
|
The detection matcher does a plain `event.get(field)` against the flat,
|
|
connector-normalized dict recovered from `raw_data`. There is no dotted-path
|
|
traversal and no aliasing. So a rule that names a field no connector ever
|
|
produces reads `None`, fails its first clause, and can never fire — while
|
|
still being loaded by the engine, still passing fixture replay, and still
|
|
counting toward the published executable total.
|
|
|
|
It passes fixture replay because fixtures are *synthesized from the rule*:
|
|
`build_positive(when)` in `scripts/detection_specs_part3_helpers.py` derives a
|
|
field value from the operator in the clause, so replaying it against the same
|
|
`match_when` is a tautology. The fixture gate proves the matcher works. It says
|
|
nothing about whether the field exists.
|
|
|
|
This gate closes that hole. It collects the field namespace connectors emit and
|
|
reports any rule that references something outside it.
|
|
|
|
Because the namespace is recovered by static analysis rather than by running
|
|
every connector, it deliberately **over**-approximates: every string-literal
|
|
dict key in a connector module counts as emitted. A false pass is a rule this
|
|
gate failed to catch; a false failure would be a rule wrongly blocked. Given
|
|
the gate's job is to stop regressions rather than to prove the corpus clean,
|
|
over-approximating is the safe direction.
|
|
|
|
Ratchet, not a clean bill of health. The corpus already contains unreachable
|
|
rules, and blocking CI on all of them would either stop every unrelated PR or
|
|
invite someone to weaken the gate. `MAX_UNREACHABLE` pins the current count so
|
|
it can only go down, exactly like `scripts/check_claim_gate_matrix.py`.
|
|
|
|
**Scope: native rules only.** This reads `detection_ruleset.json` and not the
|
|
imported ruleset beside it, which is deliberate rather than an oversight.
|
|
Imported rules are held to a stronger standard than this gate can apply:
|
|
`scripts/compile_sigma_ruleset.py` replays each one, as a vendor-shaped event,
|
|
through the real connector and the real engine, and ships it only if it fires.
|
|
That is direct evidence where this file has only static approximation, so
|
|
adding them here would substitute a weaker check for a stronger one.
|
|
|
|
Usage:
|
|
python3 scripts/check_detection_fields.py # enforce the ratchet
|
|
python3 scripts/check_detection_fields.py --list # name every rule
|
|
python3 scripts/check_detection_fields.py --fields # dump the namespace
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ast
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# `scripts/` is on sys.path when this file is run as a program, but not when a
|
|
# test loads it by path with importlib. gate_toolkit sits beside it either way.
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from gate_toolkit import repo_root, self_test_if_requested
|
|
|
|
self_test_if_requested(__file__)
|
|
|
|
ROOT = repo_root()
|
|
RULESET = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"
|
|
CONNECTORS = ROOT / "services" / "connectors" / "app" / "connectors"
|
|
#: The AI SDK is a first-party emitter too — it posts spans straight to an
|
|
#: inbox token, so the fields it produces are as real as a connector's.
|
|
AI_SDK = ROOT / "packages" / "aisoc-ai-sdk" / "aisoc_ai"
|
|
TEMPLATES = ROOT / "services" / "ingest" / "internal" / "normalizer" / "templates"
|
|
NORMALIZER = ROOT / "services" / "ingest" / "internal" / "normalizer" / "normalizer.go"
|
|
|
|
#: Current number of engine-loaded rules that depend on a DERIVED or STATEFUL
|
|
#: field. This may only ever decrease. Lower it in the same PR that fixes
|
|
#: rules; never raise it to make a red build green.
|
|
# 133 before parity 5.5, which closed the 15-rule per-tenant-allowlist
|
|
# family by deriving the booleans from the tenant overlay. 14 rules moved
|
|
# (one rule carried two clauses), leaving the four families that genuinely
|
|
# need engine or enrichment work.
|
|
#
|
|
# 119 before depth plan 3.1, which decided all 74 rules of the windowed
|
|
# family: 50 became `wd-*` rules replayed through the real engine, and 24
|
|
# were refused with a reason and stopped being published as executable
|
|
# (`scripts/windowed_translation.py`, gated by
|
|
# `scripts/check_windowed_translation.py`). Two of the 74 carried a second
|
|
# clause as well, which is why the identity-enrichment family moved from 24
|
|
# to 22 and the comparison family from 8 to 7.
|
|
#
|
|
# 45 before depth plan 3.3, which closed the rest in four steps and left two:
|
|
# * five rules were never unreachable — this gate's operator list had not
|
|
# been given `neq` when the matcher was, so `approver_role_neq` was read
|
|
# as a field name rather than as `approver_role` with `!=`;
|
|
# * 18 rules now resolve their `*_priv` booleans from the tenant's own
|
|
# directory import (`tenant_overlay.IDENTITY_FIELDS`);
|
|
# * 2 resolve from the per-tenant first-seen store (`first_seen.py`);
|
|
# * 18 are retired with a reason in `scripts/enrichment_decisions.py`,
|
|
# gated by `scripts/check_enrichment_decisions.py`, which refuses to let
|
|
# a rule whose fields *are* resolvable be retired to move this number.
|
|
#
|
|
# The two that remain both need the behavioural baseline of depth plan 3.4.
|
|
MAX_UNREACHABLE = 2
|
|
|
|
#: Fields that no telemetry carries because they are computed, not observed:
|
|
#: sliding-window counters, allowlist membership, privilege flags, and
|
|
#: actor/target comparisons. A rule naming one of these cannot fire no matter
|
|
#: which connector is attached, because nothing computes it.
|
|
#:
|
|
#: They need one of two things. The windowed family needs a `wd-*` rule in
|
|
#: `services/fusion/app/services/windowed_detection.py`; the rest need a
|
|
#: fusion-time enrichment step that resolves the predicate.
|
|
#:
|
|
#: This comment used to say the windowed engine "has three hardcoded rules
|
|
#: and no loader". That was true when written and has not been true since the
|
|
#: exporter landed: the engine loads `app/data/windowed_ruleset.json` on top
|
|
#: of its builtins, runs in the fusion consumer, and fires real alerts. The
|
|
#: stale half mattered, because it told a reader the engine was unusable when
|
|
#: the actual gap is narrower and more actionable — **nobody has translated
|
|
#: these `det-*` rules into windowed form.** The two corpora are disjoint:
|
|
#: not one of the `wd-*` ids appears in `detections/`, so building the engine
|
|
#: moved none of these rules off this list and the count did not move either.
|
|
#:
|
|
#: Migrating one means *authoring* a `wd-*` rule, not flipping a flag.
|
|
#: Parity 5.5 removed `_in_allowlist` from this pattern. It is no longer
|
|
#: a field nothing computes: `services/fusion/app/services/tenant_overlay.py`
|
|
#: derives it per tenant from the allowlists the console writes, and the
|
|
#: engine merges it into the match namespace before evaluating.
|
|
#:
|
|
#: Per tenant rather than in the shared derived-field pass, deliberately:
|
|
#: a global allowlist would make one tenant's exceptions apply to
|
|
#: everybody. An unconfigured allowlist contributes no key at all rather
|
|
#: than `False`, because a `not_in_allowlist` clause against a missing key
|
|
#: is true for every event, which is the negation-flips-on-absence failure
|
|
#: already recorded for the Sigma import.
|
|
_DERIVED_FIELD_PATTERN = re.compile(
|
|
r"(_count$|^count_|_per_|time_window|_window_"
|
|
r"|_priv$|_is_admin$|_is_dc$|_eq_|_neq|^is_"
|
|
r"|_age_days$|_age_hours$|_ratio$|_percent$"
|
|
r"|^active_|_baseline|_is_first_|_seen_before$|_deviation)"
|
|
)
|
|
|
|
#: Operator suffixes the matcher strips to recover the field name. Order
|
|
#: matters: longer suffixes must be tried first so `not_contains_any` is not
|
|
#: shortened to `contains_any`. Mirrors `OPERATORS` in
|
|
#: `services/fusion/app/services/detection_matcher.py`, and
|
|
#: `services/fusion/tests/test_detection_matcher_parity.py` asserts the two
|
|
#: lists agree in **both** directions.
|
|
#:
|
|
#: They did not. `neq` was added to the matcher and not here, so five rules
|
|
#: whose clauses the engine reads correctly as `<field>` + `!=` were reported
|
|
#: by this gate as naming a field called `<field>_neq` — unreachable,
|
|
#: ratcheted, and fine all along. A list that mirrors another and is checked
|
|
#: in one direction only drifts in exactly the direction things change.
|
|
_OPERATOR_SUFFIXES = (
|
|
"not_contains_any",
|
|
"not_startswith_any",
|
|
"not_endswith_any",
|
|
"not_startswith",
|
|
"not_endswith",
|
|
"contains_any",
|
|
"contains_all",
|
|
"pattern_match_any",
|
|
"pattern_match",
|
|
"startswith_any",
|
|
"startswith",
|
|
"endswith_any",
|
|
"endswith",
|
|
"match_any",
|
|
"has_any",
|
|
"not_in",
|
|
"contains",
|
|
"match",
|
|
"neq",
|
|
"gte",
|
|
"lte",
|
|
"in",
|
|
"gt",
|
|
"lt",
|
|
)
|
|
|
|
#: Fields the platform synthesizes rather than a connector emitting them:
|
|
#: fusion enrichment, the windowed engine's counters, and OCSF top-level keys
|
|
#: the engine falls back to when `raw_data` is absent.
|
|
_PLATFORM_FIELDS = frozenset(
|
|
{
|
|
"severity",
|
|
"severity_id",
|
|
"class_uid",
|
|
"category_uid",
|
|
"activity_id",
|
|
"connector_type",
|
|
"source",
|
|
"tenant_id",
|
|
"event_time",
|
|
"time",
|
|
"message",
|
|
"raw_data",
|
|
"raw_event",
|
|
"title",
|
|
"description",
|
|
"external_id",
|
|
"created_at",
|
|
}
|
|
)
|
|
|
|
|
|
def _strip_operator(key: str) -> str:
|
|
for suffix in _OPERATOR_SUFFIXES:
|
|
if key.endswith("_" + suffix):
|
|
return key[: -len(suffix) - 1]
|
|
return key
|
|
|
|
|
|
def _rule_fields(match_when: dict) -> set[str]:
|
|
"""Field names a `match_when` clause reads, descending into any_of/all_of."""
|
|
found: set[str] = set()
|
|
for key, value in match_when.items():
|
|
if key in {"any_of", "all_of"}:
|
|
if isinstance(value, list):
|
|
for sub in value:
|
|
if isinstance(sub, dict):
|
|
found |= _rule_fields(sub)
|
|
continue
|
|
found.add(_strip_operator(key))
|
|
return found
|
|
|
|
|
|
#: Fields the engine derives at match time from an event it already has.
|
|
#: `services/fusion/app/services/derived_fields.py` computes them, so a rule
|
|
#: matching on one is reachable even though no connector emits it.
|
|
#:
|
|
#: Named here rather than imported, for the reason the rest of this file is
|
|
#: parsed rather than imported: a field-coverage gate that needs the fusion
|
|
#: package installed is a gate that gets disabled the first time an import
|
|
#: breaks.
|
|
_DERIVED_TIME_FIELDS = frozenset({"is_business_hours", "is_after_hours", "is_weekend"})
|
|
|
|
#: The source-IP privacy boolean `derived_fields.ip_privacy_fields` computes
|
|
#: from `src_ip` (issue #1545). Named exactly rather than pattern-matched for
|
|
#: the same reason as the tenant set below: `ip_is_internal` is computed and
|
|
#: a hypothetical `registry_is_internal` would not be.
|
|
_DERIVED_IP_FIELDS = frozenset({"ip_is_internal"})
|
|
|
|
#: Booleans the **tenant overlay** computes, from that tenant's own directory
|
|
#: import (`identity_nodes.privilege_tier`). Depth plan 3.3.
|
|
#:
|
|
#: Named here rather than pattern-matched on `_priv$`, because four booleans
|
|
#: in the same family are deliberately *not* computed — `scope_priv`,
|
|
#: `act_as_user_priv`, `gpo_link_priv` and `account_is_dc` have no subject
|
|
#: field any source emits. A pattern would have swept those in and reported
|
|
#: four rules reachable that are not.
|
|
#:
|
|
#: `services/fusion/tests/test_tenant_tuning_overlay.py` asserts this set and
|
|
#: `tenant_overlay.IDENTITY_FIELDS` agree in both directions, so the list
|
|
#: cannot drift the way the operator list below did.
|
|
_TENANT_DERIVED_FIELDS = frozenset(
|
|
{
|
|
"user_priv",
|
|
"target_user_priv",
|
|
"role_priv",
|
|
"actor_role_priv",
|
|
"actor_is_admin",
|
|
}
|
|
)
|
|
|
|
#: Booleans and ages the **first-seen store** computes
|
|
#: (`services/fusion/app/services/first_seen.py`). Depth plan 3.3.
|
|
#:
|
|
#: Only observation-shaped subjects are here. `domain_age_days`,
|
|
#: `key_age_days` and the other ages-of-a-thing are not, and will not be:
|
|
#: answering "how old is this domain" with "when did we first see it" would
|
|
#: fire a newly-registered-domain rule on most of the internet.
|
|
#: `services/fusion/tests/test_first_seen.py` asserts this set and the
|
|
#: store's own tables agree in both directions.
|
|
_FIRST_SEEN_DERIVED_FIELDS = frozenset(
|
|
{
|
|
"publisher_ip_seen_before",
|
|
"device_fingerprint_seen_before",
|
|
"session_age_hours",
|
|
}
|
|
)
|
|
|
|
#: Per-principal behavioural scores the **baseline store** computes
|
|
#: (`services/fusion/app/services/baselines.py`). Depth plan 3.4.
|
|
#:
|
|
#: Every one is reported only when the principal has enough history to
|
|
#: support it, and is absent otherwise — so a rule reading one of these
|
|
#: fires on a measured deviation and not on a quiet tenant. `ADR-0011`
|
|
#: records why these are computed in fusion rather than in the
|
|
#: `full`-profile UEBA service.
|
|
#:
|
|
#: `services/fusion/tests/test_baselines.py` asserts this set and
|
|
#: `baselines.DERIVED_FIELDS` agree in both directions, so the two cannot
|
|
#: drift the way the matcher's operator list did.
|
|
_BASELINE_DERIVED_FIELDS = frozenset(
|
|
{
|
|
"baseline_action_rarity",
|
|
"baseline_resource_rarity",
|
|
"baseline_client_family_rarity",
|
|
"baseline_location_rarity",
|
|
"baseline_principal_volume_z",
|
|
"baseline_peer_deviation",
|
|
# Sub-principal baselines (wave-2 7.3, and wave-2 1.4's mechanism).
|
|
# `baselines.SUB_PRINCIPAL_FIELDS` generates these from its keys, so
|
|
# a kind added there must be added here too — which is precisely
|
|
# what the bidirectional test in `test_baselines.py` enforces, and
|
|
# what caught this list when the sub-principal table landed.
|
|
"baseline_oauth_app_volume_z",
|
|
"baseline_agent_volume_z",
|
|
"baseline_gateway_key_volume_z",
|
|
# Per-agent novelty and rate (depth 6.4's "tools, resources, volume,
|
|
# token spend, hours").
|
|
"baseline_agent_tool_rarity",
|
|
"baseline_agent_model_rarity",
|
|
"baseline_agent_hour_rarity",
|
|
"baseline_agent_token_spend_z",
|
|
"baseline_gateway_key_token_spend_z",
|
|
# Depth plan wave 2, 1.4 — per-sub-principal baselines. A token, an
|
|
# OAuth app, a service account or an AI agent acting for a human
|
|
# gets its own baseline, because a stolen credential acts *as* the
|
|
# user and leaves the user's own numbers untouched.
|
|
"baseline_sub_principal_kind",
|
|
"baseline_sub_principal_rarity",
|
|
"baseline_sub_principal_volume_z",
|
|
"baseline_token_cadence",
|
|
"baseline_token_cadence_shift",
|
|
"baseline_token_reactivated_after_idle",
|
|
"baseline_token_new_asn_after_creation",
|
|
}
|
|
)
|
|
|
|
#: Depth 2 wave 2 item 2.2. Distinct source networks that have failed and
|
|
#: succeeded against one account over weeks, from
|
|
#: `services/fusion/app/services/long_horizon_identity.py`, folded into the
|
|
#: namespace by `DetectionEngine.evaluate_async` beside the baseline store.
|
|
#: Absent for an account with too little history, which is why a rule
|
|
#: reading one fires on a measured breadth and never on a quiet account.
|
|
#:
|
|
#: `services/fusion/tests/test_long_horizon_identity.py` asserts this set and
|
|
#: `long_horizon_identity.DERIVED_FIELDS` agree in both directions.
|
|
_LONG_HORIZON_DERIVED_FIELDS = frozenset(
|
|
{
|
|
"lh_distinct_failed_asn",
|
|
"lh_distinct_failed_country",
|
|
"lh_distinct_failed_ip",
|
|
"lh_distinct_success_asn",
|
|
"lh_distinct_success_country",
|
|
"lh_distinct_success_ip",
|
|
"lh_failed_asn_saturated",
|
|
"lh_failed_country_saturated",
|
|
"lh_failed_ip_saturated",
|
|
"lh_success_asn_saturated",
|
|
"lh_success_country_saturated",
|
|
"lh_success_ip_saturated",
|
|
"lh_failed_to_success_asn_ratio",
|
|
"lh_horizon_days",
|
|
}
|
|
)
|
|
|
|
#: Depth 2 wave 2 item 2.4. Per-endpoint API behaviour from
|
|
#: `services/fusion/app/services/api_behaviour.py`, published only for a
|
|
#: tenant that opted in and only for a template with enough history — so a
|
|
#: rule reading one fires on a measured deviation from a learned shape and
|
|
#: never on the first request to a new endpoint.
|
|
#:
|
|
#: `services/fusion/tests/test_api_behaviour.py` asserts this set and
|
|
#: `api_behaviour.DERIVED_FIELDS` agree in both directions.
|
|
_API_BEHAVIOUR_DERIVED_FIELDS = frozenset(
|
|
{
|
|
"api_template",
|
|
"api_unknown_parameter",
|
|
"api_unknown_parameter_detail",
|
|
"api_parameter_type_change",
|
|
"api_parameter_type_change_detail",
|
|
"api_identifier_enumeration",
|
|
"api_identifier_enumeration_detail",
|
|
"api_enumeration_distinct",
|
|
}
|
|
)
|
|
|
|
#: `<left>_eq_<right>` / `<left>_neq_<right>`, resolved by comparing two
|
|
#: fields of the same event. Reachable only when *both* sides are in the
|
|
#: namespace — a comparison against a field nothing emits is still dead, and
|
|
#: counting it as covered would be the fake-gate failure this file exists to
|
|
#: prevent.
|
|
_DERIVED_COMPARISON_RE = re.compile(r"^(?P<left>.+?)_(?:eq|neq)_(?P<right>.+)$")
|
|
|
|
|
|
def _is_derivable(field: str, namespace: set[str]) -> bool:
|
|
"""True when the engine can compute this field from what it already has."""
|
|
if (
|
|
field in _DERIVED_TIME_FIELDS
|
|
or field in _DERIVED_IP_FIELDS
|
|
or field in _TENANT_DERIVED_FIELDS
|
|
or field in _FIRST_SEEN_DERIVED_FIELDS
|
|
or field in _BASELINE_DERIVED_FIELDS
|
|
or field in _LONG_HORIZON_DERIVED_FIELDS
|
|
or field in _API_BEHAVIOUR_DERIVED_FIELDS
|
|
):
|
|
return True
|
|
match = _DERIVED_COMPARISON_RE.match(field)
|
|
if not match:
|
|
return False
|
|
return match.group("left") in namespace and match.group("right") in namespace
|
|
|
|
|
|
#: What each unreachable field would need, so the headline number is
|
|
#: actionable rather than a bare count. "133 rules are dead" invites
|
|
#: someone to delete 133 rules; "73 need the windowed evaluator, 24 need
|
|
#: identity enrichment" names four pieces of work.
|
|
#:
|
|
#: Ordered: first match wins, so the more specific patterns come first.
|
|
_FIELD_FAMILIES: tuple[tuple[str, re.Pattern[str]], ...] = (
|
|
(
|
|
"windowed evaluator",
|
|
re.compile(r"_count$|^count_|_per_|time_window|_window_|_5min|_ratio$"),
|
|
),
|
|
("identity enrichment", re.compile(r"_priv$|_is_admin$|_is_dc$")),
|
|
("per-tenant allowlist", re.compile(r"_in_allowlist$|_not_in_allowlist$")),
|
|
("age / first-seen enrichment", re.compile(r"_age_days$|_age_hours$|_seen_before$")),
|
|
# Narrowed in depth plan 3.4. This used to read `^active_`, which is not
|
|
# a behavioural shape at all: it swept in `active_state` (a systemd unit
|
|
# state an endpoint agent would emit) and `active_p0_or_p1_incident` (an
|
|
# ITSM lookup), and reported both as blocked on a baseline that would
|
|
# never have helped either. The whole family therefore read "2 rules
|
|
# need depth plan 3.4" when the true answer was zero — a gate pointing
|
|
# at the wrong piece of work is worse than one pointing at none, because
|
|
# building the named thing does not move the number and the next reader
|
|
# concludes the fix failed.
|
|
#
|
|
# The shape a baseline field actually has is the one `baselines.py`
|
|
# produces, so the pattern now matches that and nothing else.
|
|
("behavioural baseline", re.compile(r"^baseline_|_baseline$|_deviation$")),
|
|
# Answered by a system outside the event and outside this platform: the
|
|
# tenant's ITSM, change calendar or ticket queue. Distinct from identity
|
|
# enrichment, which AiSOC can answer from its own directory import, and
|
|
# from "nothing emits it", which is a content mistake rather than a
|
|
# missing integration.
|
|
("external system context", re.compile(r"_incident$|^change_ticket|_approved_change$")),
|
|
(
|
|
# Both operands invented by the rule author. Distinct from the rest:
|
|
# the engine can compute a comparison, it just cannot compare two
|
|
# fields that do not exist. This is content work, not engine work.
|
|
"comparison over fields nothing emits",
|
|
_DERIVED_COMPARISON_RE,
|
|
),
|
|
)
|
|
|
|
|
|
def _family(field: str) -> str:
|
|
for name, pattern in _FIELD_FAMILIES:
|
|
if pattern.search(field):
|
|
return name
|
|
return "other"
|
|
|
|
|
|
def _module_field_names(path: Path) -> set[str]:
|
|
"""Every string-literal dict key appearing in one module."""
|
|
names: set[str] = set()
|
|
try:
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
except (SyntaxError, OSError):
|
|
return names
|
|
for node in ast.walk(tree):
|
|
if isinstance(node, ast.Dict):
|
|
for key in node.keys:
|
|
if isinstance(key, ast.Constant) and isinstance(key.value, str):
|
|
names.add(key.value)
|
|
# `d["key"] = v` and `d.get("key")` also declare a field name.
|
|
elif isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Constant):
|
|
if isinstance(node.slice.value, str):
|
|
names.add(node.slice.value)
|
|
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
|
if node.func.attr in {"get", "pop", "setdefault"} and node.args:
|
|
first = node.args[0]
|
|
if isinstance(first, ast.Constant) and isinstance(first.value, str):
|
|
names.add(first.value)
|
|
return names
|
|
|
|
|
|
def _connector_namespace_by_module() -> dict[str, set[str]]:
|
|
"""Connector module stem -> the field names that module names.
|
|
|
|
The union of this is what most callers want, but not every caller: a
|
|
rule declares the ``log_source.product`` it matches, and "some connector
|
|
somewhere names this field" is a weaker statement than "the source this
|
|
rule reads emits it". Keeping the split lets a caller ask the stronger
|
|
question. See ``check_enrichment_decisions``, which found a GitHub rule
|
|
credited with a ``scopes`` field only an unrelated connector emits.
|
|
"""
|
|
sources = list(CONNECTORS.rglob("*.py"))
|
|
if AI_SDK.is_dir():
|
|
sources += list(AI_SDK.rglob("*.py"))
|
|
return {path.stem: _module_field_names(path) for path in sorted(sources)}
|
|
|
|
|
|
def _connector_namespace() -> set[str]:
|
|
"""Every string-literal dict key appearing in a connector module.
|
|
|
|
Static over-approximation, by design: see the module docstring. Parsing the
|
|
AST rather than regexing means a key split across lines or built with an
|
|
f-string prefix is still picked up as a literal where one exists.
|
|
"""
|
|
namespace: set[str] = set(_PLATFORM_FIELDS)
|
|
for names in _connector_namespace_by_module().values():
|
|
namespace |= names
|
|
return namespace
|
|
|
|
|
|
def _template_namespace() -> set[str]:
|
|
"""Source field names declared by inbox webhook templates.
|
|
|
|
Read as text rather than with a YAML parser so this script has no
|
|
third-party dependency; the shape is a flat `a.b.c: x.y.z` mapping.
|
|
"""
|
|
namespace: set[str] = set()
|
|
if not TEMPLATES.is_dir():
|
|
return namespace
|
|
for path in sorted(TEMPLATES.glob("*.yaml")):
|
|
for line in path.read_text(encoding="utf-8").split("\n"):
|
|
match = re.match(r"^\s{2,}([A-Za-z0-9_.]+)\s*:", line)
|
|
if match:
|
|
# Both ends of the mapping are legitimate field names: the left
|
|
# is what arrives, the right is what the rule may match on.
|
|
namespace.add(match.group(1).split(".")[-1])
|
|
namespace.add(match.group(1))
|
|
return namespace
|
|
|
|
|
|
def _go_normalizer_namespace() -> set[str]:
|
|
"""Field names the Go OCSF normalizer maps, from its connectorProfiles."""
|
|
namespace: set[str] = set()
|
|
if not NORMALIZER.exists():
|
|
return namespace
|
|
for match in re.finditer(r'"([A-Za-z0-9_.]+)"\s*:\s*"([A-Za-z0-9_.]+)"', NORMALIZER.read_text(encoding="utf-8")):
|
|
for side in match.groups():
|
|
namespace.add(side)
|
|
namespace.add(side.split(".")[-1])
|
|
return namespace
|
|
|
|
|
|
def scan() -> tuple[list[tuple[str, list[str]]], list[tuple[str, list[str]]], set[str], int]:
|
|
"""Returns (derived-field rules, vendor-field rules, namespace, total).
|
|
|
|
Two classes, and only the first is a hard failure.
|
|
|
|
**Derived / stateful** — the field is computed, not observed. No connector
|
|
can ever supply it, so the rule is broken regardless of deployment. These
|
|
are ratcheted.
|
|
|
|
**Vendor payload** — the field is a real vendor key nested under
|
|
`raw_event`. `DetectionEngine._raw_fields` merges that payload into the
|
|
match namespace, so these are reachable whenever the attached vendor sends
|
|
the field. Whether any given deployment does cannot be known statically,
|
|
so these are reported for visibility rather than gated: failing on them
|
|
would block correct rules for vendors nobody has connected yet.
|
|
"""
|
|
if not RULESET.exists():
|
|
print(f"ERROR: {RULESET.relative_to(ROOT)} missing — run scripts/export_detection_ruleset.py", file=sys.stderr)
|
|
raise SystemExit(2)
|
|
|
|
namespace = _connector_namespace() | _template_namespace() | _go_normalizer_namespace()
|
|
rules = json.loads(RULESET.read_text(encoding="utf-8")).get("rules") or []
|
|
|
|
derived: list[tuple[str, list[str]]] = []
|
|
vendor: list[tuple[str, list[str]]] = []
|
|
for rule in rules:
|
|
missing = {f for f in _rule_fields(rule.get("match_when") or {}) if f not in namespace and not _is_derivable(f, namespace)}
|
|
if not missing:
|
|
continue
|
|
rule_id = str(rule.get("id", "?"))
|
|
computed = sorted(f for f in missing if _DERIVED_FIELD_PATTERN.search(f))
|
|
if computed:
|
|
derived.append((rule_id, computed))
|
|
else:
|
|
vendor.append((rule_id, sorted(missing)))
|
|
return derived, vendor, namespace, len(rules)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--list", action="store_true", help="name every unreachable rule")
|
|
parser.add_argument("--fields", action="store_true", help="dump the emitted field namespace")
|
|
parser.add_argument(
|
|
"--max-unreachable",
|
|
type=int,
|
|
default=MAX_UNREACHABLE,
|
|
help=f"ratchet ceiling (default {MAX_UNREACHABLE})",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
derived, vendor, namespace, total = scan()
|
|
|
|
if args.fields:
|
|
for name in sorted(namespace):
|
|
print(name)
|
|
return 0
|
|
|
|
if args.list:
|
|
print("# rules depending on a derived/stateful field (gated)")
|
|
for rule_id, missing in derived:
|
|
print(f"{rule_id}: {', '.join(missing)}")
|
|
print("\n# rules depending on a vendor-payload field (informational)")
|
|
for rule_id, missing in vendor:
|
|
print(f"{rule_id}: {', '.join(missing)}")
|
|
return 0
|
|
|
|
print(f"detection fields: {total} engine rules examined")
|
|
print(f" {len(derived)} depend on a derived/stateful field — cannot fire on any connector (gated)")
|
|
families: dict[str, int] = {}
|
|
for _rule_id, fields in derived:
|
|
for name in {_family(f) for f in fields}:
|
|
families[name] = families.get(name, 0) + 1
|
|
for name, count in sorted(families.items(), key=lambda kv: -kv[1]):
|
|
print(f" {count:4d} need {name}")
|
|
print(f" {len(vendor)} reference a vendor-payload field — reachable when that vendor is attached")
|
|
|
|
if len(derived) > args.max_unreachable:
|
|
print(
|
|
f"\nERROR: {len(derived)} rules depend on a computed field, over the ratchet "
|
|
f"ceiling of {args.max_unreachable}.\n"
|
|
"Such a field is never present in telemetry, so the rule cannot fire whatever\n"
|
|
"is connected. Fixture replay will not catch it, because fixtures are\n"
|
|
"synthesized from the rule being tested.\n"
|
|
"Run with --list to see which. The fix is either a windowed-engine rule or a\n"
|
|
"fusion-time enrichment that actually computes the predicate.",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
|
|
if len(derived) < args.max_unreachable:
|
|
print(f"\nThe ratchet can be tightened: lower MAX_UNREACHABLE to {len(derived)} in scripts/check_detection_fields.py.")
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|