Files
AiSOC/scripts/upgrade_fixture.sql
T
Beenu Arora 92aef462e7 fix(wave5): hunting, intel, sandbox and operations wiring (5.1-5.8) (#1120)
* fix(wave5): retro-hunts can be turned on; the stable channel stops at a major

Item 5.1. RETRO_HUNT_ENABLED appeared in no compose file and no .env.example,
and compose passes only the variables it names, so the retro-hunt consumer
could not start on any compose deployment however the host environment was
set. The tenant's half defaults to FALSE under a comment reading 'Off until a
tenant asks' and there was nowhere to ask -- no route, no console surface --
so opting in meant an UPDATE by hand. Both halves now exist, with nine live
tests against real Postgres driving the handlers; reverting the upsert to a
plain UPDATE fails four of them, which is the branch that matters because a
tenant with no row would have been updated successfully and silently.

Item 5.5. The channel rule refused vX.0.0 and nothing else, so v16.0.0
declined the tag and v16.1.0 took it the next day. That is how stable reached
v12, v13 and v15, and asking one release at a time always gave the right
answer, which is why the test did not see it. The workflow now tracks which
major the channel is on, read from the registry, and the test replays ladders.
The chart gains the channel it was scoped with and never got.

Item 5.6. The upgrade fixture inserted into 'cases', which 083 renames, so it
would have failed under ON_ERROR_STOP the moment the previous release became
16.x. Reproduced against a fully-migrated database: 'relation cases does not
exist'. The fixture, the before-snapshot and the archive assertion now resolve
the name at run time.

* fix(wave5): KEV exposure gets data, and three defects behind it

Item 5.2. asset_vulnerabilities had one writer in the whole tree: a route a
human calls by hand. The Tenable connector modelled findings as alerts and
fetched an endpoint carrying neither a CVE nor an asset, with normalize()
setting host: None outright. So _tenant_has_vulnerability_data -- which exists
to tell 'you are not exposed' apart from 'nobody has told me what you run' --
returned the second for every scanner tenant, forever.

The connector now fetches per-asset findings and the plugin details carrying
CVEs, capped at 60 lookups because one request per plugin against a customer's
scanner is a denial of service aimed at the customer. The write happens in the
connectors service, which already has an engine and the tenant id; posting to
the API would have meant granting a write verb to a credential whose own
docstring says database writes are absent on purpose.

Creating that data for the first time exposed three things downstream that had
never executed: the case insert used status='open', which the CHECK rejects;
CaseTask and CaseTimeline named case_tasks and case_timeline, tables no
migration creates, with four declared columns that do not exist; and the task
status 'pending' is not one of the three the CHECK allows. Each was reachable
only from data the product could not produce, which is why a passing suite
never saw them.

Seven live tests against real Postgres cover the chain, including the control
that matters: a tenant with data who is not running the vulnerable thing comes
back not exposed, which is a different answer from no data.

* fix(wave5): perf thresholds derived from the claims, and two tools wired in

Item 5.8. The gate asserted a floor of 5 events/s and a ceiling of 120,000 ms
against published figures of 80.1 alerts/s and a 1,091 ms p95 -- 16x below and
110x above, so a regression had to be catastrophic by two orders of magnitude
before the job that said it was measuring noticed. The workflow's own comment
defended this on the grounds that a gate tuned close to a measurement flaps and
gets disabled, which is right and argues for a stated margin rather than for a
constant that relates to nothing. The thresholds are now 7.3x and 19.2x from
the published numbers, with the arithmetic in the workflow and a test that
parses both the workflow and the published page and fails if the ratio drifts
in either direction.

check_perf_results.py accepted a results directory covering one of the two
published deployments and had no freshness bound at all. It now requires both
and caps the newest result at 400 days, with the coverage check proven to fire
against a tree with the kind results removed.

load_profiles.py and throughput_claims.py had no caller anywhere. They could
not be pointed at a real run because the harness recorded none of the context
they require, so the harness now records the load's shape -- batch size,
workers, target rate, host count, commit -- and --from-harness translates a
harness result into claim shape. That takes the missing-context findings from
eight to zero. The one remaining problem is real and stated rather than
absorbed: the harness does not measure what fraction of pushed events the rule
engine evaluated, so an ingest rate published beside nothing reads as 'every
event was fully analysed'. It is tolerated by an explicit --allow naming that
kind, and still printed on every run.

* docs(wave5): changelog entry for the performance gate work

* fix(wave5): scope the vulnerability touch to its tenant

check_tenant_query_predicates caught this on the first version of the module,
and it is right: the id handed to the UPDATE came from a tenant-scoped SELECT,
which is not the same as the write being scoped. How a row was addressed is
irrelevant to what the statement can reach, now or after a later edit. The
write carries its own predicate and a live test names another tenant's id
against the real statement and asserts it touches nothing; removing the
predicate fails it.

* fix(wave5): sandbox and air-gap settings reach the API, and absence is said out loud

Item 5.4, four defects with one theme: the deployment could not configure file
analysis, and when it was unconfigured the product did not say so.

Compose passed neither AISOC_AIRGAPPED nor any sandbox provider setting to the
api service, and compose passes only the variables it names. The air-gap
overlay set the flag on agents alone while seventeen modules across four
services read it, so a deployment that believed it was air-gapped had one
service that knew -- including the API's STIX publisher and both query runners,
each a path that can make an outbound call on a host that is not supposed to
have one.

With only the mock provider, _attachment_indicators did 'if not block:
continue', so a phishing verdict carried no attachment indicator at all, which
a reader takes for 'checked and clean'. It now records that no provider is
configured and says that is not a clean verdict.

And the agent's sandbox tool reported every 403 as air-gap mode. A 403 is
equally an expired token, a revoked scope or a tenant policy forbidding file
analysis; naming the networking posture sends an analyst to debug a network
when the fix is a credential.

* fix(wave5): the hunt corpus can actually be compiled against the lake

Item 5.3. The README publishes the 68-hunt library as Stable, 'replayed
against tenant events'. Measured against lake_hunt.py's field map the corpus
used 114 distinct field names and zero resolved to a lake column: all 243 uses
were reported unsupported, so every hunt returned an unfiltered table or
nothing.

Every one of the 68 filters on a bare 'source', which the lake stores as
connector_type and the map never mentioned. The other 113 are vendor names
with no column -- EventID, CommandLine, eventName -- that the stored payload
does carry, and nothing reached into raw_payload. Both fixed; all 114 compile
now. The payload extraction tries the EventData and System nestings as well as
the flat path, because Windows puts its payload one level below anything flat,
which is the same nesting that once made 2,173 Sigma rules unable to fire.

The field name is bound as a query parameter and never interpolated, and is
additionally refused unless it is a plain identifier -- 'the value is escaped'
is not a reason to accept a field name that cannot be a field name.

The agents image also shipped with no ClickHouse driver, so lake-live.yml
installed one by hand and proved something about a package set the published
image does not have; and the full profile gave the agents container no
ClickHouse address. Both fixed, lock regenerated with the pinned poetry.

The README row now says 'compiled against' rather than 'replayed': a payload
extraction finds a field if the event carries it, which is a property of the
connector's output rather than of this compiler.

* fix(wave5): run the fusion chaos grader live on a schedule

Item 5.7. chaos.yml ran only fusion_restart.py --self-test, which exercises the
grading arithmetic against fixtures and proves nothing about fusion; the live
run had happened once, by hand, which is a measurement with no expiry and no
witness. integration.yml's kill test is not a substitute -- it posts a single
event while fusion is down and checks only for loss, and one event cannot show
a duplicate, which is the half an at-least-once consumer gets wrong.

The new job boots the spine, pushes 3,000 events, destroys the fusion container
at the halfway mark and asserts against the alerts table that every accepted
sequence number appears exactly once. Scheduled rather than per-PR for the same
reason the store outages are: it is minutes, not seconds.

The claim row's caveat said this needed a three-node cluster with two fusion
replicas. It does not: the property under test is the consumer's commit
discipline and the sink's idempotency, and one replica killed mid-stream
exercises both. A multi-replica run additionally exercises rebalance, and
REPOSITORY_REALITY.md still records the one hand-run cluster test as a dated
event rather than implying it recurs.

* fix(wave5): CI follow-ups on the perf gate test and the chaos job

Three real findings, all mine.

The new perf test's helpers had a mixed return and four union-attr findings:
`_harness_args` fell through to `pytest.fail()` rather than raising, and a
`re.search(...).group(1)` chain assumed a match. CodeQL flagged the first as
py/mixed-returns and mypy the rest. Both are the same defect -- an unhandled
None -- and on the day somebody renames a flag the old code would have raised
AttributeError: 'NoneType' instead of saying what it could not find. Replaced
with a `_flag()` helper that raises with the flag name.

The chaos job copied go-version 1.23 while every other workflow and every
Dockerfile pins 1.26, so check_toolchain_pins correctly reported CI testing a
runtime nothing ships.

And the tenable change incidentally resolved a banked arg-type finding, so the
baseline is updated to record it rather than leaving headroom that would
silently absorb the next one.

* fix(wave5): declare RETRO_HUNT_ENABLED as a real default

The .env.example line added for item 5.1 is neither a placeholder nor a
declared default, which test_env_placeholder_gate correctly refuses: the gate
exists so a contributor adding a value has to say which it is rather than
leaving the two lists to drift. Off is the correct value for every deployment,
because a sweep reads back over a tenant's history -- a cost and a privacy
decision -- so it waits for both this switch and the tenant's own opt-in.

Worth noting for the next person: CI reported this as a job that died at 5%
with no failure line, because the log was truncated before pytest printed its
summary. Running the same command locally named it in one line.
2026-10-04 11:22:26 -07:00

94 lines
4.4 KiB
PL/PgSQL

-- Data the upgrade test carries across a migration chain.
--
-- A fresh install applies every migration to an empty schema, which is the one
-- case that cannot go wrong. The defects that reach operators need rows to be
-- there: an `ADD COLUMN ... NOT NULL` with no default, a unique index created
-- over rows that already violate it, a backfill reading a column it is about
-- to create, a type change that succeeds on zero rows.
--
-- Ids are fixed literals rather than generated, because the assertion after
-- the upgrade reads specific rows back by id. A count alone would pass over a
-- table that was dropped and repopulated with the same number of fabricated
-- rows, which is precisely the migration a real deployment cannot survive.
--
-- Written against the owner role (`aisoc`), which is also what applies the
-- migration chain. Every row carries `is_synthetic = true` where the column
-- exists, so a fixture can never be mistaken for a tenant's real state.
BEGIN;
INSERT INTO tenants (id, name, slug)
VALUES ('00000000-0000-0000-0000-0000000000aa', 'Upgrade Fixture Tenant', 'upgrade-fixture')
ON CONFLICT (id) DO NOTHING;
INSERT INTO users (id, tenant_id, email, username, hashed_password)
VALUES (
'33333333-3333-3333-3333-333333333333',
'00000000-0000-0000-0000-0000000000aa',
'fixture@example.com', -- RFC 2606, unregistrable
'upgrade-fixture',
-- Not a usable credential: a deliberately invalid bcrypt-shaped string,
-- so nothing can sign in as this row even if a fixture escaped into a
-- real database.
'$2b$12$invalid.fixture.hash.not.a.real.credential.000000000000'
)
ON CONFLICT (id) DO NOTHING;
-- One alert per severity, so a migration that rewrites the severity ladder or
-- adds a constraint to it meets every value rather than one.
INSERT INTO alerts (id, tenant_id, title, description, severity, status, is_synthetic)
VALUES
('11111111-1111-1111-1111-111111111111', '00000000-0000-0000-0000-0000000000aa',
'pre-upgrade alert (critical)', 'Seeded before the migration chain ran.', 'critical', 'new', true),
('11111111-1111-1111-1111-111111111112', '00000000-0000-0000-0000-0000000000aa',
'pre-upgrade alert (high)', 'Seeded before the migration chain ran.', 'high', 'investigating', true),
('11111111-1111-1111-1111-111111111113', '00000000-0000-0000-0000-0000000000aa',
'pre-upgrade alert (medium)', 'Seeded before the migration chain ran.', 'medium', 'new', true),
('11111111-1111-1111-1111-111111111114', '00000000-0000-0000-0000-0000000000aa',
'pre-upgrade alert (low)', 'Seeded before the migration chain ran.', 'low', 'closed', true),
('11111111-1111-1111-1111-111111111115', '00000000-0000-0000-0000-0000000000aa',
'pre-upgrade alert (info)', 'Seeded before the migration chain ran.', 'info', 'closed', true)
ON CONFLICT (id) DO NOTHING;
-- The case table is named differently on either side of 083, which renames
-- `cases` to `cases_pre_consolidation` and consolidates into `aisoc_cases`.
-- This fixture runs against *the previous release's* schema, so which name
-- exists depends on which release that is: a hard-coded `cases` worked while
-- the previous release was 15.x and breaks the moment it is 16.x, under
-- `ON_ERROR_STOP=1`, with `relation "cases" does not exist`.
--
-- Resolving the name at run time rather than pinning either one keeps the
-- fixture working across the rename in both directions, which matters because
-- this is the one test whose whole job is to meet an older schema.
DO $$
DECLARE
target text := COALESCE(
to_regclass('public.aisoc_cases')::text,
to_regclass('public.cases')::text
);
BEGIN
IF target IS NULL THEN
RAISE EXCEPTION 'neither `aisoc_cases` nor `cases` exists; the previous '
'release applied no case table at all, which is not a '
'shape this fixture can seed';
END IF;
EXECUTE format(
'INSERT INTO %I (id, tenant_id, case_number, title, description) '
'VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING',
target
)
USING '22222222-2222-2222-2222-222222222222'::uuid,
'00000000-0000-0000-0000-0000000000aa'::uuid,
'CASE-UPGRADE-0001',
'pre-upgrade case',
'Seeded before the migration chain ran, so a case-table migration meets a populated table.';
RAISE NOTICE 'upgrade fixture seeded one case into %', target;
END
$$;
COMMIT;
\echo 'upgrade fixture: seeded 1 tenant, 1 user, 5 alerts, 1 case'