Metadata-Version: 2.5
Name: perquisition
Version: 0.7.3
Summary: Reference library for perquisition audit envelopes: validation, SQLite, findings, SBOM
Project-URL: Repository, https://github.com/athoune/perquisition-python
Project-URL: Issues, https://github.com/athoune/perquisition-python/issues
Project-URL: Probe, https://github.com/athoune/perquisition
Author: Mathieu Lecarme
License-Expression: MIT
License-File: LICENSE
Keywords: audit,cyclonedx,inventory,sbom,security
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Security
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.11
Requires-Dist: jsonschema>=4.18
Description-Content-Type: text/markdown

# perquisition (Python library)

The reference library for audits produced by the `perquisition` probe. The probe
runs on the remote host and prints one JSON envelope on its STDOUT; this library
validates it, puts it into SQLite, and gives consumers the typed view, the
snapshot type, the findings document, the conformance kit and the SBOM/Grype path.

The probe collects only: facts, not standards. Everything here is the
*consumer* side, and the one thing treated as carefully as the probe treats its
read-only contract is the boundary: **an audit loaded with the wrong assumptions
is worse than an audit refused**, because the report it feeds will say "no
problem" with confidence.

## The contract

The envelope's source of truth is
[`schema/envelope.schema.json`](https://github.com/athoune/perquisition/blob/main/schema/envelope.schema.json)
in the probe repository. This library vendors a copy at a probe tag, inside the
package (`perquisition/schema/envelope.schema.json`), and **validation is that
schema being executed** — there is no second hand-written description of the
envelope to drift from it.

```sh
tools/refresh-upstream v0.6.1   # the only supported way to change the copies
```

While the probe repository is private, that command needs a token with `repo`
read scope in `GITHUB_TOKEN` or `GH_TOKEN`; once it is published, the token
becomes optional. Raw GitHub URLs are not used on purpose: they carry no
`Authorization` header, so a private repository answers them with 404 — which is
indistinguishable from "the tag does not carry the schema yet".

The tag that was vendored is recorded in `tests/fixtures/UPSTREAM`, and a test
fails when the schema and the fixture disagree on the envelope major — the
half-refresh alarm — or when that tag and the table below name different probe
series. Reading the probe's Go source is never necessary: the schema and
`SPECS.md` §6 (per-collector `data` shapes) are the whole contract.

## What this release was tested against

| probe | library | envelope |
|---|---|---|
| v0.9 | 0.7.x | 1.0 |
| v0.6 | 0.6.x | 1.0 |
| v0.5 | 0.5.x | 1.0 |
| v0.3 | 0.4.x | 1.0 |
| v0.3 | 0.2.x | 1.0 |
| v0.2 | 0.1.x | 1.0 |

A row is added only after the pair has actually been run together, and the
vendoring it describes is recorded in `tests/fixtures/UPSTREAM` — a table row
with no corresponding tag is a claim, not a result. The library column names the
series: a patch release that leaves the contract alone keeps its row, a minor
adds one.

v0.9 is the newest row, and the first whose refresh moved something
code-adjacent rather than only `data`: the envelope is still 1.0 and the schema
is byte-identical, but 0.7.0 handed the container inventory from
`packages[].containers` to §6.18's `containers` collector — a move this library
had already implemented in `containers_of` and `container_distro`, and the
v0.9.2 fixture is the first that carries the new owner as an `ok`, empty
inventory (a `--root` tree has no running container, which its note says). The
audit vendored here is a stamped build — probe `0.9.2`, commit `213064c`, 22
collectors over the same miniature root — so the row's work was not code: it
was the test doubles, which seeded the inventory in the old owner and had to
follow the move (`add_container` publishes in §6.18's result; the refusal tests
remove *that* result, and the selection entry with it, to reach the `packages`
fallback older audits still use).

v0.5 is the same story as v0.3: it added the `supervisors` collector (§6.19)
and left the envelope alone — so the refresh from `v0.5` changed `UPSTREAM` and
not one byte of the schema or the published fixture, and the new collector
reached this side as a `data` key the loader already stores. The pair was run as this release was prepared: probe 0.5.0 (the
`v0.5` tag, whose commit travels in `probe.commit`) auditing
`tests/fixtures/root` — twenty collectors, `supervisors` `ok` behind its
`--root` note — loaded here into SQLite and read back with `json_extract`. That
audit is committed as `tests/fixtures/audit-supervisors.json`.

v0.3 is the case the table exists for: it added the `ip` collector (§6.16) and
changed nothing in the envelope, so this library answers it with no new code. A
probe minor can only reach this side through `data`, and only `packages` is ever
projected out of JSON — a new collector is a query, not a migration.

The pair was run as this release was prepared: probe 0.3.0 auditing a live
container — sixteen collectors, `ip` `partial` behind nine notes — loaded here
into SQLite, and read back with `json_extract`. That audit is committed as
`tests/fixtures/audit-ip.json`, so the row is reproducible rather than
remembered.

Tags are never moved: a moved tag silently changes what a past report was
tested against, which is the one thing provenance cannot survive.

## Use it

```sh
uv sync                                  # once; commits to uv.lock
uv run perquisition-analysis load audit-2026-11-26.json
# -> audit-2026-11-26.sqlite next to the audit; --db chooses, --force replaces

uv run perquisition-analysis summary --db audit-2026-11-26.sqlite
uv run ruff check . && uv run ruff format --check .   # lint — CI runs both
uv run pytest                           # tests
```

`load` refuses an envelope it cannot honestly interpret:

- `schema_version` major ≠ 1 → refused (the probe and the analysis are
  upgraded together);
- an unknown **status** or a malformed structured error → refused;
- `ok` carrying an error, `skipped`/`error` carrying neither error nor note →
  refused (the invariants `Result.Validate()` guarantees probe-side);
- an unknown **error code** → accepted and recorded as-is: the probe's code
  list grows with a minor bump, and this library records what the probe said
  rather than guessing it away;
- an **undeclared field** → refused: the schema is closed, so a field the probe
  emits without declaring it is a contract bug, not a feature.

A load is one transaction: a rejected audit leaves no half-loaded database.

## The schema

| Table | Row | Content |
|---|---|---|
| `audit` | one per `audit.id` | run context: identity, mode, privileges, probe version, `loaded_at` (ingestion provenance) |
| `collector_result` | one per audit × collector | status, structured error, and the raw `data` as JSON |
| `note` | one per audit × collector × note | human context the probe attached |
| `package` | one per audit × record | projection of `results['packages'].data.packages` (SPECS.md §6.10) |

Decisions worth knowing:

- **A database holds many audits.** The envelope correlates successive audits
  of a machine on `audit.id`, so every table carries `audit_id`; load a week of
  audits into one file and compare them with plain SQL.
- **Only `packages` gets a table.** It is the analysis flagship and the input
  of the SBOM/Grype branch to come. Every other collector stays reachable
  through `json_extract(collector_result.data, '$.…')` — a projection that
  drops a field is a bug found only after it is trusted. Adding a table means
  the projection became the thing you query every day.
- **`package.version` can be NULL, and the NULL is a fact.** dpkg keeps
  entries it never unpacked (`install ok not-installed`, typically a foreign
  architecture) and records no `Version:` for them; the probe reports
  `"version": null` rather than dropping the entry and disagreeing with the
  database's own tally (SPECS.md §1.3 — `null` plus a note beats a confident
  wrong value). So `WHERE version IS NULL` is a real query, and `version = ''`
  never happens: an empty string is refused at load time, like a missing field.
- **`data` keeps the JSON.** The SQLite is a lossless projection of the JSON,
  never a replacement for it; the raw audit file remains the source of truth.

```sql
-- What did the two audits disagree about?
SELECT a.hostname, c.collector, c.status
FROM collector_result c JOIN audit a USING (audit_id)
ORDER BY a.started_at;

-- Dpkg inventory across every loaded audit
SELECT DISTINCT name, version FROM package WHERE manager = 'dpkg' ORDER BY name;

-- Collector failures worth a look, by the probe's own reason codes
SELECT error_code, COUNT(*) FROM collector_result
WHERE status IN ('partial', 'error') GROUP BY error_code ORDER BY 2 DESC;

-- v0.3's ip collector, untouched: flat addresses with a nullable dev
SELECT json_extract(a.value, '$.dev')     AS dev,
       json_extract(a.value, '$.address') AS address
FROM collector_result c, json_each(c.data, '$.addresses') a
WHERE c.collector = 'ip';
```

### The join `ip` + `network`

§6.16's reason for a separate collector was this question: *which listener is
reachable on which prefix* — a join across two `results` entries. The database
makes it one query, and every column below is a fact the probe published;
nothing here decides whether an exposure is a problem:

```sql
WITH addr AS (   -- the addresses, with the interface that carries each one
    SELECT json_extract(a.value, '$.dev')     AS dev,
           json_extract(a.value, '$.family')  AS family,
           json_extract(a.value, '$.address') AS address
      FROM collector_result c, json_each(c.data, '$.addresses') a
     WHERE c.collector = 'ip'
), iface AS (
    SELECT json_extract(i.value, '$.name')      AS dev,
           json_extract(i.value, '$.operstate') AS operstate
      FROM collector_result c, json_each(c.data, '$.interfaces') i
     WHERE c.collector = 'ip'
), sock AS (     -- the sockets, with the family their proto implies
    SELECT json_extract(s.value, '$.proto')         AS proto,
           json_extract(s.value, '$.local_address') AS address,
           json_extract(s.value, '$.local_port')    AS port,
           json_extract(s.value, '$.comm')          AS comm,
           CASE WHEN json_extract(s.value, '$.proto') LIKE '%6'
                THEN 'inet6' ELSE 'inet' END        AS family
      FROM collector_result c, json_each(c.data, '$.sockets') s
     WHERE c.collector = 'network'
)
SELECT sock.proto                       AS proto,
       sock.address || ':' || sock.port AS socket,
       sock.comm                        AS comm,
       CASE WHEN sock.address IN ('0.0.0.0', '::')
              THEN 'wildcard: every ' || sock.family || ' interface'
            -- 127/8 is local whether or not the address is assigned: the
            -- stub resolver binds 127.0.0.53, which no interface carries.
            WHEN sock.address LIKE '127.%' OR sock.address = '::1'
              THEN 'loopback'
            WHEN addr.dev IS NULL
              THEN 'address not in the ip facts'
            ELSE addr.dev
                 || CASE WHEN iface.operstate = 'up' THEN ''
                         ELSE ' (' || iface.operstate || ')' END
       END                              AS boundary
  FROM sock
  LEFT JOIN addr  ON addr.family = sock.family AND addr.address = sock.address
  LEFT JOIN iface ON iface.dev = addr.dev
 ORDER BY sock.address, sock.port;
```

Two assumptions, stated rather than hidden: a `::` wildcard is expanded over
`inet6` interfaces only — whether a v6 socket also carries v4 is `IPV6_V6ONLY`,
a fact the envelope does not collect — and `boundary` names the interface the
address lives on, not what routing then does with it. A `wildcard:` socket
reaches every interface of its family, which is exactly why the interesting
ones are worth finding: ssh and a published container port look identical in a
`LISTEN` list.

## Grype

```sh
uv run perquisition-analysis grype --db audit-2026-11-26.sqlite
# --audit ID      when the database holds several audits
# --distro x:y    override the distro context (default: the audit's facts)
# --out DIR       where the SBOM and the report files go (default: <db>-grype/)
```

The command builds a CycloneDX SBOM from the `package` table, runs the local
`grype` binary on it (`sbom:` input), stores the report's matches in SQLite,
and writes **both documents untouched beside the database** — `sbom-<id>.json`
and `report-<id>.json`, with their sha256 in the `grype_run` row. The SQLite
is a projection of grype's answer, never its only copy.

What the pipeline refuses rather than reports:

| Refused | Why |
|---|---|
| no distribution facts, or a null `VERSION_ID` | Grype's OS matching is namespaced (`debian:12`); scanning blind answers "no vulnerabilities" for every OS package |
| a DB grype itself calls `valid: false` | "0 findings" from a database grype rejected is a lie — run `grype db update` |
| a report echoing another distro than requested | the matches were namespaced against the wrong distribution |
| an unknown report shape, a missing `descriptor.version` or `configuration` | the run must be attributable to a tool and a configuration |

Decisions worth knowing:

- **`--config` replaces grype's config discovery.** A `~/.grype.yaml` or a
  `.grype.yaml` in the working directory carries `ignore:` rules that
  silently delete matches (verified on 0.122.1: a cwd ignore drops the
  fixture from 54 matches to 53). Every run therefore uses the packaged
  `data/grype.yaml`, and grype's *effective* configuration is echoed inside
  the report itself (`descriptor.configuration`), whose sha256 is stored.
- **Runs are history, not overwrites.** Re-scanning after a DB refresh
  appends `run 2`, `run 3`…: yesterday's matches stay queryable next to
  today's.
- **`--fail-on` is never passed.** Exit codes belong to a threshold policy
  this tool does not have; it reads the report instead.
- **`package` rows without an honest purl get no purl.** `dpkg`/`apk`/`rpm`
  map to a scheme; `pacman`/`gentoo` records and versionless entries carry a
  `perquisition:purl_omitted` property instead of a guess — they will not be
  matched, and the SBOM says so out loud.

Useful queries:

```sql
-- Current findings for one audit, worst first
SELECT severity, vuln_id, package_name, fix_versions
FROM vulnerability v JOIN grype_run r USING (audit_id, run)
WHERE r.audit_id = ? ORDER BY r.run DESC, severity;

-- Did a DB refresh change the answer?
SELECT run, db_built, matches FROM grype_run WHERE audit_id = ? ORDER BY run;

-- What is still unfixed?
SELECT vuln_id, package_name FROM vulnerability
WHERE fix_state != 'fixed' ORDER BY severity;
```

## Fixtures

`tests/fixtures/audit-offline.json` is produced by the **real probe**, never
hand-written — a hand-written envelope drifts from SPECS.md §3 the day the
schema moves:

```sh
# the normal path: the fixture published with a probe release
tools/refresh-upstream v0.6.1

# a local fixture, for a case the published one does not cover.
# Needs the released `perquisition` binary on PATH, not its source tree.
perquisition --root tests/fixtures/root --sample 0 --pretty \
    | python3 tests/fixtures/sanitize.py > tests/fixtures/audit-offline.json

# audit-ip.json: a live container, because the published fixture predates
# v0.3's ip collector. One audit id per fixture (--id); the sanitizer keeps
# whatever else is real.
docker run --rm -v "$PWD/bin/perquisition:/p:ro" debian:bookworm-slim \
    /p --pretty --sample 0 \
    | python3 tests/fixtures/sanitize.py --id 00000000-0000-4000-8000-000000000002 \
    > tests/fixtures/audit-ip.json

# audit-accounts.json: the accounts collector (probe SPECS §6.20) over the
# committed root, built AT THE RELEASED TAG so its identity is a release:
#   git -C ../perquisition checkout v0.6.1   # main is the tag right after release
#   make -C ../perquisition build            # ldflags stamp version and commit
# `--version` must say 0.6.1 before this is committed: `go run` stamps
# buildinfo's placeholders (0.0.0-dev / unknown), and no `probe.version >= …`
# rule in this library accepts them — test_accounts_fixture holds the commit.
make -C ../perquisition build
../perquisition/bin/perquisition --root tests/fixtures/root --sample 0 --pretty \
    | python3 tests/fixtures/sanitize.py --id 00000000-0000-4000-8000-000000000003 \
    > tests/fixtures/audit-accounts.json

# audit-supervisors.json: the supervisors collector (probe SPECS §6.19), built
# at the released tag so the provenance IS the release — `probe.version`
# 0.5.0, `probe.commit` the tag's commit:
#   git -C ../perquisition worktree add --detach ../pq-v05 v0.5
#   make -C ../pq-v05 build
../pq-v05/bin/perquisition --root tests/fixtures/root --sample 0 --pretty \
    | python3 tests/fixtures/sanitize.py --id 00000000-0000-4000-8000-000000000004 \
    > tests/fixtures/audit-supervisors.json

tests/fixtures/regenerate-grype.sh   # real grype -> sbom + report fixtures
```

The fixture root is a miniature Debian tree (os-release, dpkg status, and the
three account files the probe's `accounts` collector reads), so the envelope
carries real `distribution`, `packages` and `accounts` data alongside the
offline degradations (`offline_mode`, `not_found`, partial `init`). The
sanitizer strips host identity (hostname, machine_id, boot_id, absolute root
path) — an audit is confidential, fixture or not. Regenerate and commit the
diff after any envelope change, and never hand-write an envelope.

What it deliberately keeps is the `probe` block: every fixture here names the
build that produced it — `probe.version` stamped by the probe's ldflags and
`probe.commit` the source, because `0.0.0-dev` / `unknown` (what `go run`
stamps) is an audit no `probe.version >= …` rule accepts, including the ones
this library's own consumers write. The pin test holds the vendored fixture to
it; each side-fixture's test holds its own.

`audit-ip.json` is the second fixture, and it exists for one reason: a suite
that only ever loads v0.2 audits would call v0.3 support a claim. It carries a
live `ip` result (`partial`, nine notes) and the sixteen-collector set, and
`test_ip_collector.py` holds the collector's shape — flat addresses with a
nullable `dev`, nothing nested under an interface — against it.

`audit-accounts.json` is the third fixture, for the same reason one level
down: `audit-ip.json` predates the `accounts` collector (probe SPECS §6.20),
so a suite that only loads the first two would call "this library reads the
container posture facts" a claim. It is an offline run over the same root by
probe **0.6.1 at its tag** — stamped `probe.version`/`probe.commit`, and
`test_accounts_fixture` refuses a commit-less one — so its `results.accounts`
is complete: eight users sorted by uid, the `docker`
group's members, all three sources named with relative paths — while every
runtime collector degrades exactly as §4 says it must.
`test_accounts_fixture.py` holds that shape, tri-state lock state included:
`false` for a hash, `true` for the shadow file's own `!`/`*`, and `null` for
the account the shadow does not name, with a note that says which one.

`audit-supervisors.json` is the fourth, and what it exists for follows the
table rather than the collector count: a row is a claim about a pair that ran,
so the `| v0.5 | 0.5.x |` row needs an audit of *that* probe to stand on — an
audit from a newer probe says nothing about an older row. It is an offline run
over the same root by probe **0.5.0 at the `v0.5` tag** (`probe.commit` names
the tag's commit), carrying the twenty-collector set v0.5 shipped — v0.6's
twenty-first is absent on purpose: `supervisors` answers `ok` with an empty
`supervisors[]`, eleven `config` sources in `sources[]` — every one `absent`,
none of them absolute — and the note that says *why* the list is empty
(`--root` never consults runtime markers: our limit, not the image's).
`test_supervisors_fixture.py` holds that shape *and* that row: it asserts a
table row exists for the fixture's own series, and a `probe.commit` that names
a source — a row without an artifact, or an artifact without a source, fails.

`sbom-debian12.json` and `grype-report-debian12.json` are a real grype run
against that audit (needs grype + `grype db update`): the SBOM is
byte-deterministic, the report's matches are whatever the vulnerability
database said that day — refreshing the fixtures after a DB update is
expected, and the diff is the commit. Tests parse the committed report; only
`test_grype_real.py` touches a live grype, and it skips itself where grype or
its database is absent, so CI stays offline.

## Scope

- **Now**: envelope → SQLite (faithful and loud about disagreement), plus the
  SBOM/Grype path: CycloneDX from the package table, `--distro` from the
  distribution facts, raw report stored beside the load with its provenance.
- **Later**: EOL/lifecycle knowledge base, richer per-collector projections
  when a query earns one.
