mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-12-03 10:57:40 +08:00
* fix(integrity): the wave-0 defects where a writer never existed
Eight mechanisms that were complete, tested and unreachable because the
table or column they depended on had nothing writing to it. A unit test
cannot see any of this: the code was correct, and the data never arrived.
**SSO could not sign anyone in.** `aisoc_sso_connections` has existed
since migration 080, `sso_provisioning.resolve_connection` selects from
it on every SAML and OIDC callback, and no code path anywhere wrote a
row — so both handlers raised SsoProvisioningError and answered 403 on
every deployment. There is now a tenant-scoped CRUD surface for it. The
role mapping is held to `role_grants.authorize_role_grant` rather than a
local list, because a connection is a standing grant to everyone who can
authenticate against that issuer and must meet the same bar as creating
one user with that role.
**The OIDC id_token was never verified.** It was decoded with
`verify_signature: False` under a comment saying to use JWKS in
production, and the nonce was generated, sent, and never compared. An
unverified id_token is a base64 blob anyone can author, and its claims
were merged into the identity. It is now verified against the provider's
published JWKS with issuer, audience and expiry checked, and a token
that fails is discarded rather than downgraded. The state store moved to
Redis: as a process dict it broke roughly (n-1)/n of sign-ins on an
n-replica deployment, because the browser returns to whichever instance
the load balancer picks.
**MTTA was a fabricated zero.** `alerts.first_seen_at` had no writer, so
`/insights/soc` and `/metrics/soc` averaged over NULL and published a
confident `0.0` — which reads as instant acknowledgement. It is now
written when an analyst claims an alert, with COALESCE so a re-claim
after a release does not reset the clock to measure the last handoff.
The openapi-breaking gate then caught me making those means nullable,
which was right: `/metrics/soc` had already taken this decision and
documented it on `mttd_sample_count`, choosing a denominator alongside
the mean precisely because nullable is a breaking response change. So
`InsightTile` grows `sample_count` the same way, the console renders
"not measured" when it is zero, and a delta is withheld when either
window measured nothing. Zero breaking changes against the v15.1.0 spec.
**The evidence chain was always empty.** Three readers, no writer, so
`GET /cases/{id}/evidence` returned `[]` under a heading saying
"Evidence Chain" — which an auditor reads as "no evidence was handled".
Entries are now appended on alert links and status changes, hash-chained
so an edit or a removal is detectable. It is tamper *evidence*, not
tamper proofing — anyone who can write the column can rewrite every
link consistently, and a test asserts exactly that so nobody concludes
otherwise.
**SLA reporting had nothing to aggregate.** `alert_sla_events` had one
writer, a manual POST nothing calls, so 350 lines of correct MTTD/MTTR/
MTTC arithmetic ran over an empty table everywhere. `acknowledged` is
emitted on claim and `resolved` on disposition; `detected` is backfilled
from the alert's own `created_at` rather than emitted by fusion, so the
ingest hot path is not coupled to reporting and the pair is always
complete.
**The console's Approve button could not succeed.** `/decide` answers
412 without a `candidate_rule` verdict and `/evaluate-rule` is its only
writer, which had no web client. The deeper half: fixtures were never
persisted, so even calling it directly meant re-deriving fixtures the
drafter had already produced and discarded. Migration 082 stores them on
the proposal, the eval falls back to them, and the console runs the gate
before approving.
**Marketplace installs were lost on restart** and disagreed between
replicas. `marketplace_installs` has existed since migration 056 with
the right columns and a UNIQUE constraint, and had no reader or writer.
29 tests, 10 of them against real Postgres because reachability is not
observable from a double. The negative control is recorded: reverting
migration 082 fails exactly the two fixture tests and no others.
`AlertAssetCorrelation` is still unwired and is deliberately left for
wave 11, where linking alerts to assets is what lets criticality reach
prioritisation instead of a prompt string.
One correction to the survey this plan was built from: `python3-saml`
*is* declared in `services/api/pyproject.toml` and present in the
lockfile. That half of the SAML finding was already fixed.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(cases): one case table, and one status vocabulary
The product shipped with two case tables that never synchronised. The
console wrote `aisoc_cases`; `resolution_time` — which owns the single
shared MTTR definition — read `cases`, as did `metrics`, `insights`,
`executive_digest`, `mssp_portfolio` and the GraphQL layer.
So every case an analyst created was invisible to every case metric. A
tenant could close fifty cases in the console and watch MTTR stay null,
and `cases_opened_7d` and `cases_closed_7d` counted only KEV-exposure
sweeps, scheduled-hunt cases and demo seed rows. Nothing errored. Both
tables existed, both queries were valid, and the symptom was an empty
number with no explanation attached.
Migration 083 widens `aisoc_cases` with the fifteen columns the ORM
model needed, moves the rows across, repoints the child foreign keys and
renames the old table to `cases_pre_consolidation` rather than dropping
it — a consolidation that lost a row nobody noticed is worse than two
tables. `alert_ids` is unpacked element by element rather than cast,
because `cases` stored JSONB where `aisoc_cases` stores `uuid[]` and a
cast would fail the whole migration on one malformed entry.
The second half matters as much as the first. The readers filtered
`status == "open"` and `status == "in_progress"`, and the console's
machine is new → triaged → investigating → contained → resolved →
closed. Neither of those states can exist, so both counters were
structurally zero rather than merely empty. And `resolved` is not
terminal: a case moves resolved → closed, only that last transition
writes `closed_at`, so counting "closed this week" as `status =
'resolved'` counted cases still on a queue and missed every one that
finished — clocked off `updated_at`, which moves whenever anyone edits
the case. Both now read from `app.services.case_status`, which the cases
endpoint imports too, so there is one copy.
`scripts/check_one_case_table.py` asks both questions. Writing it was
worth it twice over: it found four more reads of the retired table and
fourteen impossible statuses in the demo seed that I had missed by
grepping. Its first draft was case-insensitive and flagged the English
"Create and update cases" in a permissions seed, so it now strips
comments and matches SQL keywords case-sensitively — a gate with false
positives is one people learn to skip.
Negative control recorded: reintroducing a single `FROM cases` fails it
with the file and line.
Repointing the ORM alone was not enough, and the way it failed is worth
keeping. `case_tasks` and `case_timeline_events` both declared
`REFERENCES cases(id)`, so SQLAlchemy could not resolve `Case.tasks` at
mapper-configuration time and 257 tests failed at once on models that
have nothing to do with cases.
7 live tests against real Postgres, because the defect was entirely in
which table a query named — every unit test passed throughout, each
testing its query against whichever table the test itself seeded.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* feat(benchmark): a corpus that can actually grade an agent
An agent answering "true positive" to everything, without reading
anything, used to score **1.000** on this corpus. It now scores 0.727,
and that gap is the only reason any accuracy figure from it means
anything.
Three defects, and the second is the one nobody had named.
**The vocabulary did not match the scorer.** The corpus used
`malicious | suspicious | benign`; `replay` grades
`true_positive | benign_true_positive | false_positive | benign`. One
label of four in common, so the corpus was ungradeable by this package's
own scorer and nothing noticed.
**The benign class was fictitious.** `build_corpus._disposition` derived
it from `response_class == "monitor"`, and those eight incidents are
BloodHound domain enumeration tagged T1087.002 at medium severity. That
is a real attack with a monitoring response. Labelling it benign
conflates "low-severity threat" with "not a threat", which is the
distinction a triage agent exists to make. `response_class` says which
action to take and nothing about whether the finding was true.
So `corpus/benign_cases.py` authors one: fifteen shapes expanded to
seventy-five cases, split `benign` (the activity happened and was
authorised) from `false_positive` (the activity did not happen as
characterised) because those need different actions — an allowlist entry
versus a rule fix.
The cases deliberately look like attacks. PsExec at 02:00 inside a
change window, encoded PowerShell from a build agent, Nmap from the
scanner subnet, mimikatz on the detection-engineering lab. A benign
corpus of obviously boring events measures formatting, not judgement,
and the distinguishing evidence is in the content — a change ticket, a
known service account — which is what an analyst reads. They span
severities including critical, so the classes are not separable on
severity alone.
Four reference agents now land on four distinct scores: 0.727 for
always-malicious, 0.182 for always-benign, 1.000 for perfect, 0.473 for
a coin flip. If any two collapsed the corpus would not be measuring
anything.
**423 of 878 negative fixtures tested an impossible value.** They were
`f"not-{expected}"` — proving a rule ignores a string that cannot occur,
which is not what a false positive is. The fields carrying them are
enumerated (`event_type` 267, `event_name` 54, `syscall` 50), so the
generator now harvests each field's real vocabulary from the positive
fixtures and builds negatives from a different *real* value. 423 became
18, all 1,756 fixtures still replay correctly through the real engine,
and the fix is in the generator because the fixtures regenerate.
Also added: `false_negatives`, `false_negative_rate` and
`false_negative_verdicts` as named fields. All three are derivable from
the confusion matrix, and a reader should not have to compute the number
that matters most — a missed attack — from the one that reads best.
The verdict breakdown separates "it abstained on 40" from "it called 40
benign", which are different failures with different fixes.
**One finding worth separating out: the corpus shipped three real
routable address ranges**, 138 occurrences, including 185.220.101.0/24 —
a known Tor exit range — plus 45.142.122.x and 91.134.231.x. This corpus
is published and read by third-party agents through the benchmark
adapter, so an agent exercised on it could propose blocking an address
that belongs to somebody, and a reader could go and scan them. Replaced
with RFC 5737 documentation ranges at every generator, and a test now
refuses any address outside the documentation and private ranges.
The two injection-corpus digests moved as a result, which is the pinning
guard working: the injection corpus is built from
`synthetic_incidents.json`, and its docstring says a change to a base
incident must not land unnoticed. Both updated in this commit alongside
the diff that caused them, and `check_injection_eval --check` confirms
the guard rates are unchanged.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* style(benchmark): wrap an over-long note in the benign corpus
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(ci): keep `cases` readable for external SQL, and three smaller breaks
Four CI findings, and the first is a real design correction rather than
a test fix.
**The upgrade test was right to fail.** Migration 083 renamed `cases`,
and `upgrade-test.yml` seeds a case on the previous minor then reads it
back by that name. Renaming the table is correct for our own code and
wrong for everyone else's: a self-hoster with a Grafana panel, a
scheduled export or any SQL of their own would silently start erroring
on upgrade. `cases` now comes back as a **read-only view** over
`aisoc_cases`. External readers keep working; our own source does not,
because `check_one_case_table.py` still refuses `FROM cases` in tracked
code. The gate governs what we write, the view governs what we already
told other people to rely on. Verified end to end: seed on the
pre-083 schema, migrate, and the row reads back under both names.
Deliberately not updatable — a write through the view would bypass the
six-state machine, and failing on INSERT beats accepting a row nothing
can transition.
**The wave-0 SSO tests passed locally and failed in CI, and the reason
is worth keeping.** My local Postgres connected as the superuser, who
bypasses RLS entirely; CI connects as the DML-only `aisoc_app` role,
where `WITH CHECK (tenant_id = current_tenant_id())` refuses an unbound
insert. The local database was the more permissive test double — the
same shape as an over-capable mock, in infrastructure. The tests now
bind the tenant as a real request does, and were re-run against the
DML-only role rather than the superuser.
**Two TypeScript errors** from fields declared on the wrong interface:
`sample_count` landed on a neighbouring type instead of `InsightTile`,
and `candidate_rule` was read off the eval verdict without being
declared on it.
**A mypy baseline regression I caused by over-reaching.** `ruff format
packages/` reformatted fifteen files across three packages I had no
business touching, which moved a plugin-SDK tree from 3 findings to 5.
Reverted to `origin/main`; the only package changes left are the
benchmark ones this branch is actually about. The one new baseline entry
is `import-not-found` on the new test, matching its two siblings
exactly — mypy runs `--no-site-packages`, so the package is not
importable by design.
Also corrected a comment naming `services/sla.py`, which does not exist;
the module is `services/api/app/services/sla.py`.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(cases): ship the consolidation as the breaking change it is
The compatibility view was the wrong answer and the migration
idempotency check is what proved it.
A read-only `cases` view over `aisoc_cases` keeps external SQL working,
which is why I tried it. But every historical migration that does
`ALTER TABLE cases` or `CREATE INDEX ... ON cases` then fails on re-run
against a view — `001_init.sql`, `002_rls.sql` and
`046_detection_rules_cases_schema_drift_fix.sql` all did — and guarding
each of them scatters one decision through the entire migration history.
I guarded `002` and two more immediately surfaced, which is the signal
to stop.
So `cases` is renamed and gone, and that is recorded as a BREAKING
change rather than smoothed over. Erroring is the better outcome
anyway: external SQL now fails with "relation does not exist" instead of
quietly returning the pre-consolidation rows, and a query that silently
returned stale data would be worse than one that stops.
The rename is now idempotent, which it was not. On a second pass
`001_init.sql` recreates `cases` empty through CREATE TABLE IF NOT
EXISTS, so migration 083 ran again with nothing to move and an archive
that already existed, and the rename collided. The empty recreation is
dropped instead, leaving the original archive intact. Three full passes
over every migration are now clean.
The upgrade test follows the data to `aisoc_cases` and additionally
asserts the archive is still readable, so a consolidation that lost a
row stays detectable after the fact.
Two more findings, both from gates and both real:
**`check_tenant_query_predicates` caught a bug, not a style issue.** The
new SSO create handler pre-checked issuer uniqueness with a
cross-tenant SELECT, and under RLS as the DML-only role that query only
sees the caller's own rows — so it could not detect the case it existed
for, and the insert would then fail with a raw integrity error instead
of a 409. It is check-then-insert besides, which races. The unique index
now raises and the handler turns that into the 409.
**`check_python_route_state` is shrink-only and caught the allowlist
entry for `_installed` going stale.** Its own justification said the
in-memory store would get a table "where parity plan 5.4 makes install
write rows" — that is done, so the entry goes.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(cases): four test references the gate was blind to, and a stale digest
**The gate skipped `/tests/`, which is exactly where the misses were.**
Four live references to the retired table survived in
`test_resolution_time_parity.py` and `test_mssp_portfolio_isolation.py`,
and CI found them against real Postgres rather than the gate written to
find precisely that. A test that seeds `cases` is a test asserting the
consolidation did not happen, so the exclusion is removed: coverage goes
from 1,248 files to 1,818.
The benchmark page's injection block was stale because the two corpus
digests moved when `synthetic_incidents.json` was regenerated with
documentation addresses. Refreshed with `--write-benchmark`: only the
digests changed, and the guard rates — 98.1% tuned, 7.1% held out — are
identical.
On the remaining local failures: `tests/isolation/test_route_tenant_scope.py`
passes alone and fails in a whole-suite run. That is pre-existing test
pollution, not this branch — clean `origin/main` fails 22 in the same
invocation where this branch fails 9.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(cases): the reference the gate could not see, and the shape it now can
CI found a `DELETE FROM cases` after a literal search of every tracked
file came back clean, which is the interesting part. The table name was
not written out:
for table in ("alerts", "cases", "connectors"):
session.execute(text(f"DELETE FROM {table} WHERE tenant_id = ..."))
A string in a tuple, interpolated into SQL one line later. No grep for
`FROM cases` can see that, and neither could the gate written to catch
exactly this class.
So the gate now looks for the second shape too — and the way it was
narrowed matters as much as adding it. The first version flagged any
`"cases"` literal before a comma or bracket and produced 22 findings,
**every one a false positive**: the `/cases` route prefix, a saved-view
type, the `cases:write` permission resource, a UI label. A gate that
cries wolf is one people learn to suppress wholesale. It now requires
the same file to interpolate a name directly into a SQL verb, which is
what turns a string in a list into a table. That took 22 findings to
one, and the one was real — a table/column map in `seed_demo.py` that
re-anchors demo timestamps.
Both detection shapes are proven by injection: reintroducing a bare
`FROM cases` and reintroducing an interpolated `"cases"` each fail the
gate with the file and line, and the tree is clean with neither.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(gate): ask git for the repository root, not the directory tree
`check_gate_contract` refused the new gate for resolving its root from
`__file__` and never asking git. It is right to: two levels above the
script is whatever happens to be there — a worktree, a release tarball,
a container build context — and a gate that certifies the wrong tree is
worse than one that fails. Uses `gate_toolkit.repo_root()` like every
other gate here.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* fix(codeql): drop an unused logger in the new installs module
CodeQL #984, `py/unused-global-variable` at note severity. The module
declared a logger and then used it nowhere — the log calls went when the
error handling moved to the caller, and the handle stayed behind.
Worth noting the gate caught this on the PR *merge* ref rather than on
the branch head, which is the ref a reviewer is actually merging.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
* chore(security): lower the semgrep ceiling to the count this tree produces
103/39, down from 104/40. A real reduction, not the ±1 the file's own
note warns about: `main` reported exactly 40/104 on three consecutive
runs while this branch reported 39/103, so the delta is the tree rather
than the scanner. The finding that went is the unused module-level
logger removed in the previous commit.
Lowering locks the improvement in, which is what a shrink-only ratchet
is for. Raising one to make a scan pass is the thing that is never
allowed.
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
---------
Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>