diff --git a/.altru/DECISIONS.md b/.altru/DECISIONS.md index 26e37f8..a964f0e 100644 --- a/.altru/DECISIONS.md +++ b/.altru/DECISIONS.md @@ -2,3 +2,7 @@ - 2026-12-05: Open core. Apache-2.0 for code and schema, CC BY 4.0 for docs and standards registry; names/logos not licensed; future hosted/enterprise features under separate terms outside this repo - because security users must be able to audit the rules, and Apache needs no contributor agreement for an open-core model. - 2026-12-05: Position PostQuantum as the assurance layer (claims -> evidence -> signed verdicts), importing discovery via CycloneDX CBOM instead of competing with CBOMkit, Keylens, xgrep and commercial scanners - because plain discovery is crowded and nobody proves scoped claims. - 2026-12-05: CLI name `pqcheck` must change before release (taken on PyPI by another PQC scanner). Candidates: pqwitness, pqdocket. +- 2026-12-05: Product/CLI name `pqdocket` (repo stays PostQuantum) - free on PyPI; a docket is a case file, which avoids implying the authors vouch. +- 2026-12-05: Signature features F1-F9 added to roadmap; priority F1 self-verifying record, F4 next step per gap, F6 release evidence; then F3 disproof-first verdicts. +- 2026-12-05: Operators sign their own evidence records; authors/ALTRU.dev never sign or vouch for verdicts. +- 2026-12-05: Release evidence (F6) = stdlib script + GitHub build provenance attestation (Sigstore, keyless) in the release workflow; actions pinned to commit SHAs. diff --git a/.altru/STATE.md b/.altru/STATE.md index 74dfb07..a4741b8 100644 --- a/.altru/STATE.md +++ b/.altru/STATE.md @@ -2,7 +2,7 @@ Updated: 2026-12-05 ## Now -R0 foundation nearly done. Licensed (Apache-2.0 code, CC BY 4.0 docs/registry). 42 tests, ruff and mypy --strict clean. +R0 code complete pending merge: CI, strict schema 1.1.0, files_not_scanned count, release evidence + attestation. 54 tests. ## Last session - Chose open-core licensing; added LICENSE, NOTICE, LICENSING.md; removed LICENSE-DECISION.md. @@ -12,12 +12,14 @@ R0 foundation nearly done. Licensed (Apache-2.0 code, CC BY 4.0 docs/registry). - Oversized files now counted as skipped. ## Next -1. Pick the new CLI/product name, then add CI (pytest, ruff, mypy) to close R0. +1. Enable private vulnerability reporting; tag v0.1.0 to produce the first release evidence record. 2. R1: CycloneDX CBOM import/export. ## Gotchas +- Workflow files may need pushing from the VPS (token with `workflow` scope). +- Release evidence fails on a dirty tree, failed tests, or a tag/version mismatch by design. - Direction changed 2026-12-05: assurance layer, not a scanner. Read docs/PRODUCT_SPEC.md and docs/ROADMAP.md first. -- `pqcheck` is taken on PyPI; `shorline` too (both PQC scanners). +- Renamed to `pqdocket` (module src/pqdocket). `pqcheck` and `shorline` are taken on PyPI by other PQC scanners. - Repo About/settings: chat sandbox proxy blocks settings writes; use gh on the VPS (signed in as altrudev). - Private vulnerability reporting is off, but SECURITY.md refers to it. - Rules are hardcoded in rules.py; standards/registry.yaml is not loaded by code yet. diff --git a/.altru/TASKS.md b/.altru/TASKS.md index ca485f0..62cba78 100644 --- a/.altru/TASKS.md +++ b/.altru/TASKS.md @@ -3,13 +3,16 @@ ## R0 finish - [x] License files and LICENSING.md - check: LICENSE md5 matches canonical Apache-2.0 - [x] Skip-dir, PQC-as-DSA and missed-signal fixes - check: pytest -- [ ] CI workflow - check: green run on a PR -- [ ] Schema validation of reports in CI +- [x] CI workflow - check: green run on a PR +- [x] Schema validation of reports in CI +- [x] Release evidence record (F6) - check: tests/test_release_evidence.py +- [ ] Tag v0.1.0 - [ ] Enable GitHub private vulnerability reporting ## Repositioning - [x] Rewrite spec, roadmap, backlog, architecture around assurance layer -- [ ] Choose new CLI/product name and rename package +- [x] Choose new CLI/product name and rename package (pqdocket) +- [x] Add signature features F1-F9 to roadmap ## Backlog - Load rules from standards/registry.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0e80fac --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12", "3.13", "3.14"] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install + run: python -m pip install -e ".[dev]" + - name: Lint + run: ruff check . + - name: Type check + run: mypy src + - name: Test + run: pytest + - name: Scan this repository and validate the report against the schema + run: | + pqdocket scan . --output pqc-report.json + python -c "import json, jsonschema; jsonschema.validate(json.load(open('pqc-report.json')), json.load(open('schemas/scan-report.schema.json'))); print('report valid')" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8ea4153 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,51 @@ +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write # create the GitHub release + id-token: write # sign the build provenance attestation (Sigstore) + attestations: write # store the attestation + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - name: Install + run: python -m pip install -e ".[dev]" build + - name: Check tag matches package version + run: | + version=$(python -c "import pqdocket; print(pqdocket.__version__)") + test "v$version" = "$GITHUB_REF_NAME" || { echo "Tag $GITHUB_REF_NAME does not match version $version"; exit 1; } + - name: Lint, type check, test + run: | + ruff check . + mypy src + pytest --junitxml=junit.xml + - name: Build + run: python -m build + - name: Release evidence record + run: python scripts/release_evidence.py --dist dist --junit junit.xml --out release-evidence.json + - name: Attest build provenance + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + dist/* + release-evidence.json + - name: Publish GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" dist/* release-evidence.json \ + --title "pqdocket $GITHUB_REF_NAME" \ + --notes "Includes release-evidence.json, this release's own evidence record. Verify artifacts with: gh attestation verify --repo $GITHUB_REPOSITORY" diff --git a/.gitignore b/.gitignore index 44129f4..bc13e81 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ build/ *.egg-info/ # Scan reports can contain source excerpts and paths; keep them out of git. pqc-report*.json +junit.xml +release-evidence.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc58de1..3e7557b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,4 +12,6 @@ mypy src Licensing: contributions are accepted under the license of the files they change (Apache-2.0 for code and schemas, CC BY 4.0 for docs and the standards registry). See LICENSING.md. +Releases: bump `__version__` in `src/pqdocket/__init__.py`, merge, then push a tag `v`. The release workflow refuses to publish if the tag and version differ, tests fail, or the tree is dirty, and it publishes `release-evidence.json` with a build provenance attestation. + PR checklist: tests; docs/limitations; standards source checked; no secrets; schema changes versioned; false-positive behavior considered. diff --git a/LICENSING.md b/LICENSING.md index 24db721..2c02371 100644 --- a/LICENSING.md +++ b/LICENSING.md @@ -16,7 +16,7 @@ Copyright 2026 Valentyn Rukhaylo (ALTRU.dev). - The docs and registry are reference material; CC BY 4.0 lets anyone reuse them with credit. ## Names and logos -The licenses above cover code and content only. They grant no rights to the project names or logos ("PostQuantum", "pqcheck", "ALTRU.dev"). You may say that your work is based on or compatible with this project, but don't present a fork as the official project. +The licenses above cover code and content only. They grant no rights to the project names or logos ("PostQuantum", "pqdocket", "ALTRU.dev"). You may say that your work is based on or compatible with this project, but don't present a fork as the official project. ## No warranty, no attestation The software is provided "as is", without warranties or conditions of any kind (Apache-2.0 sections 7 and 8). Running PostQuantum does not make its authors or ALTRU.dev a verifier, auditor, assessor, or certification body for your systems. Evidence records and verdicts are produced and signed by whoever runs the tool, and that party alone is responsible for statements made with them. The authors do not sign, review, or vouch for any user's records or verdicts. diff --git a/NOTICE b/NOTICE index 9945951..c457bec 100644 --- a/NOTICE +++ b/NOTICE @@ -1,4 +1,4 @@ -PostQuantum (pqcheck) +PostQuantum (pqdocket) Copyright 2026 Valentyn Rukhaylo (ALTRU.dev) This product is licensed under the Apache License, Version 2.0 (see LICENSE). diff --git a/README.md b/README.md index b9679ee..f81633c 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Requires Python 3.11+. python -m venv .venv source .venv/bin/activate # Windows: .venv\\Scripts\\Activate.ps1 python -m pip install -e ".[dev]" -pqcheck scan . --format json --output pqc-report.json +pqdocket scan . --format json --output pqc-report.json pytest ``` @@ -31,18 +31,23 @@ pytest - Line-level evidence, rule IDs, confidence, and file SHA-256. - JSON report output and versioned schema. - Hybrid (X25519MLKEM768), pre-standard (Kyber, Dilithium), JWT (RS256, ES256) and finite-field DH indicators. -- Oversized and unreadable files are counted as skipped, never silently dropped. +- Oversized and unreadable files are counted as skipped, and files of types it doesn't read (e.g. Dockerfile, .pem) are counted as not scanned; nothing is dropped silently. +- Strict, versioned report schema (1.1.0), validated in CI. +- CI on Python 3.11 to 3.14 (lint, type check, tests, self-scan). +- Every release ships its own evidence record (`release-evidence.json`) and a signed build provenance attestation. - Tests for representative detection and false-positive cases. ## Not implemented -CBOM import/export; claims and assurance evaluator; signed evidence records; CI; schema validation of reports; semantic/data-flow analysis; lockfile/SBOM correlation; TLS/SSH/VPN/certificate inspection; runtime-use verification; PQC correctness/interoperability tests; risk scoring; migration automation; dashboard; GitHub App. +CBOM import/export; claims and assurance evaluator; signed evidence records for user verdicts; semantic/data-flow analysis; lockfile/SBOM correlation; TLS/SSH/VPN/certificate inspection; runtime-use verification; PQC correctness/interoperability tests; risk scoring; migration automation; dashboard; GitHub App. ## Layout - `docs/`: product, architecture, threat model, assurance, risk, roadmap, backlog. - `standards/`: versioned algorithm registry. - `schemas/`: machine-readable report schema. -- `src/pqcheck/`: CLI and discovery engine. +- `src/pqdocket/`: CLI and discovery engine. - `tests/`: unit tests and regression fixtures. +- `scripts/`: release tooling (release evidence record). +- `.github/workflows/`: CI and release. ## Standards references - NIST FIPS 203 / ML-KEM: https://csrc.nist.gov/pubs/fips/203/final diff --git a/SECURITY.md b/SECURITY.md index 20e3a7f..59649fb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -3,3 +3,12 @@ This is an early-stage local source scanner, not a certification or production approval mechanism. Do not publish exploit details in public issues. Use GitHub private vulnerability reporting if enabled, or the maintainer's configured security contact. Never include private keys, credentials, customer source, or confidential production reports in public issues. Only the latest development branch is currently supported. + +## Verifying a release +Each GitHub release includes `release-evidence.json` (the release's own evidence record: commit, test results, rule set, schema and artifact hashes) and a build provenance attestation signed in the release workflow. Verify any downloaded file with: + +```bash +gh attestation verify --repo altrudev/PostQuantum +``` + +The evidence record describes the pqdocket release only. It is not an assessment of any system pqdocket scans. diff --git a/docs/ASSURANCE_MODEL.md b/docs/ASSURANCE_MODEL.md index c38ddee..fcbc62b 100644 --- a/docs/ASSURANCE_MODEL.md +++ b/docs/ASSURANCE_MODEL.md @@ -21,7 +21,7 @@ Evidence ID; rule/adapter and version; scanner version; asset and source; observ Require provider and version, parameter set, reachable application/protocol call path, deployed negotiation/configuration evidence, correctness/interoperability results, and explicit scope/date. A manifest entry alone is insufficient. ## Decision rules -Missing data never defaults to secure. Conflicts remain visible. Standard name does not prove conformance. Library capability does not prove runtime use. Unit tests do not prove deployment configuration. Every assurance statement lists scope, evidence, date, and limitations. +A claim reaches `verified` only after the template's disproof checks (classical fallbacks, downgrade paths, alternate endpoints or versions) have run and failed to break it; each attempt is recorded. Missing data never defaults to secure. Conflicts remain visible. Standard name does not prove conformance. Library capability does not prove runtime use. Unit tests do not prove deployment configuration. Every assurance statement lists scope, evidence, date, and limitations. ## Who signs and who vouches PostQuantum is a tool, not a verifier. The organization that runs it signs its own evidence records with its own key. That signature means "we ran this evaluation, with these inputs and tool versions, on this date, and the record has not changed since". It is not an endorsement by the PostQuantum authors or ALTRU.dev, who never sign, review, or vouch for anyone's verdicts and do not act as an auditor, assessor, or certification body. Anyone relying on a record (customer, auditor, regulator) relies on the organization that signed it, and can re-run the evaluation to check it. diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f423faa..2af9366 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -9,10 +9,13 @@ - [x] Run tests/lint in target environment. - [x] Choose license (Apache-2.0 code, CC BY 4.0 docs/registry). - [x] Skip-folder check limited to paths inside the target. -- [ ] CI workflow (pytest, ruff, mypy). -- [ ] Tighten report schema (types, enums) and validate reports in CI. -- [ ] Report files with unlisted extensions as not scanned. -- [ ] Rename CLI (`pqcheck` is taken on PyPI). +- [x] CI workflow (pytest, ruff, mypy, self-scan) on Python 3.11 to 3.14. +- [x] F6: release evidence record (tests, rules, schema and artifact hashes) plus Sigstore build provenance attestation in the release workflow. +- [x] Tighten report schema (types, enums) and validate reports in CI. +- [x] Report files with unlisted extensions as not scanned. +- [x] Rename CLI and package to `pqdocket` (`pqcheck` is taken on PyPI). +- [ ] Enable GitHub private vulnerability reporting (referenced by SECURITY.md). +- [ ] Cut first release `v0.1.0`. ## R1 — Interoperability - [ ] CycloneDX CBOM importer with provenance. @@ -26,6 +29,9 @@ - [ ] Evidence requirement profiles for the first three templates. - [ ] Evaluator producing verdicts and gap lists. - [ ] Known-good and known-bad fixtures per template. +- [ ] F3: disproof checks per template (fallbacks, downgrades, alternate endpoints/versions). +- [ ] F4: next-step command for every gap. +- [ ] F5: plain-English claim parser that echoes the exact claim evaluated. ## R3 — Evidence graph - [ ] Graph node and edge types; observed vs inferred links. @@ -36,6 +42,8 @@ - [ ] Content-hashed verdict bundle format. - [ ] Detached signature and offline verifier. - [ ] Evaluate in-toto/DSSE and ML-DSA signing. +- [ ] F1: self-verifying offline HTML record (PWX-style packaging, in-page signature check). +- [ ] F2: FreeTSA (RFC 3161) and OpenTimestamps stamps in every record. ## R5 — Deployment collectors - [ ] TLS handshake observer (negotiated group, signature algorithm) with allowlist. @@ -44,5 +52,7 @@ ## R6+ — Product surface - [ ] GitHub Action gating on verdicts. -- [ ] HTML report of verdicts and gaps. +- [ ] F7: verifiable README badges linked to records. +- [ ] F8: questionnaire answer export linked to records. +- [ ] F9: opt-in public transparency log (R8). - [ ] Commercial layer (outside this repository). diff --git a/docs/PRODUCT_SPEC.md b/docs/PRODUCT_SPEC.md index b5263c6..7b20861 100644 --- a/docs/PRODUCT_SPEC.md +++ b/docs/PRODUCT_SPEC.md @@ -29,10 +29,10 @@ Security and platform engineers proving migration progress; product security tea ## Workflows 1. Import inventories: CycloneDX CBOMs from external tools, plus the built-in scanner. 2. Normalize records into the evidence graph, keeping observed and inferred links distinct. -3. State claims from templates for named assets and scopes. -4. Evaluate claims against requirement profiles; produce verdicts and a gap list ("to verify this, provide: negotiated group from a TLS handshake of host Y"). +3. State claims in plain English or from templates for named assets and scopes; pqdocket shows the exact claim it evaluated. +4. Evaluate claims against requirement profiles, including attempts to disprove them; produce verdicts and a gap list where every gap names the action that would close it ("to verify this, provide: negotiated group from a TLS handshake of host Y"). 5. Collect missing evidence with authorized collectors (e.g. TLS handshake observation) or attach it manually. -6. Sign verdicts as evidence records. +6. Sign verdicts as evidence records: a self-verifying offline HTML file with outside time stamps. 7. Re-evaluate on new scans; diff verdicts between releases and flag regressions. ## Functional requirements diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1264cf4..5d85d7e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,32 +1,50 @@ # Roadmap and release gates -Direction: PostQuantum is the assurance layer, not another scanner. Discovery is imported wherever possible; effort goes into claims, evidence, and verdicts. +Direction: PostQuantum (CLI `pqdocket`) is the assurance layer, not another scanner. Discovery is imported wherever possible; effort goes into claims, evidence, and verdicts. + +## Signature features +What should make pqdocket stand out. Each is tied to a release below. + +| # | Feature | What it means for the user | Release | +|---|---|---|---| +| F1 | Self-verifying evidence record | A verdict is one signed, offline HTML file. Double-click it in any browser: a plain green/amber/grey verdict, a "what's missing" list, and an in-page signature check. No install, account, or network. | R4 | +| F2 | Trusted time stamps | Each record carries outside time stamps (FreeTSA RFC 3161 and OpenTimestamps), proving when the evidence existed, so migration dates cannot be backdated. | R4 | +| F3 | Disproof-first verdicts | Before `verified`, the evaluator tries to break the claim (classical fallbacks, downgrade paths, other endpoints or versions, legacy libraries). The record lists every attempt. | R2 | +| F4 | Every unknown has a next step | Each gap names the exact action that would close it, e.g. `pqdocket collect tls api.example.com`. | R2 | +| F5 | Claims in plain English | Write `api.example.com uses hybrid ML-KEM`; pqdocket maps it to a claim template and shows the precise form it evaluated. | R2 | +| F6 | Release evidence | Every pqdocket release ships its own evidence record: reproducible build, signed artifacts, and results of all known-good and known-bad fixtures. | R0 onward | +| F7 | Verifiable badges | A README badge (e.g. "No classical key transport: verified Dec 2026") that links to the self-verifying record. | R6 | +| F8 | Questionnaire answers | Turn verdicts into ready-to-paste answers for customer security questionnaires, each linked to its record. | R6 | +| F9 | Public transparency log (opt-in) | Organizations may publish records to an append-only public log, like certificate transparency, so customers can look up vendor claims. The log stores records; it never vouches for them. | R8 | ## R0 — Foundation -Package and CLI, lexical scanner, JSON report and schema, licensing, docs, tests, CI. Exit: clean install; tests, lint, and schema validation pass in CI; limitations explicit. +Package and CLI, lexical scanner, JSON report and schema, licensing, docs, tests, CI, first release evidence record (F6). Exit: clean install; tests, lint, and schema validation pass in CI; limitations explicit. ## R1 — Inventory interoperability CycloneDX CBOM (1.6+) import and export; normalized inventory schema; provenance per record (source tool, version, method). Built-in scanner findings exported as CBOM. Exit: round-trips CBOMs from at least two external open-source tools without losing fields; unknown fields preserved. ## R2 — Claims and assurance evaluator -Claim templates and evidence requirement profiles; verdict states; gap reports. First templates: `no-classical-key-transport` (source scope), `uses-mlkem-provider` (dependency scope), `negotiates-hybrid-mlkem` (deployment scope). Exit: every verdict lists scope, evidence, missing evidence, date, and limitations; missing evidence yields `unknown`; known-good and known-bad fixtures per template. +Claim templates and evidence requirement profiles; verdict states; gap reports. First templates: `no-classical-key-transport` (source scope), `uses-mlkem-provider` (dependency scope), `negotiates-hybrid-mlkem` (deployment scope). Includes disproof attempts (F3), a next step for every gap (F4), and plain-English claim input (F5). Exit: every verdict lists scope, evidence, missing evidence, disproof attempts, date, and limitations; missing evidence yields `unknown`; plain-English input always shows the exact claim evaluated; known-good and known-bad fixtures per template. ## R3 — Evidence graph and re-evaluation Graph of assets, records, claims, evidence, and verdicts; stable fingerprints across line movement; verdict diffs between scans and releases; regression flags. Exit: inferred links never shown as observed; verdict changes always explained. ## R4 — Signed evidence records -Content-hashed verdict bundles with a detached signature made with the operator's own key (never a key held by the PostQuantum authors), verifiable offline. Evaluate interoperable formats (e.g. in-toto/DSSE attestations) and a post-quantum signature option (ML-DSA) for the records themselves. Exit: third-party verification without PostQuantum installed; tampering detected in tests. +Content-hashed verdict bundles with a detached signature made with the operator's own key (never a key held by the PostQuantum authors), verifiable offline. Delivered as a self-verifying offline HTML record (F1) with outside time stamps (F2), reusing the PWX packaging and FreeTSA/OpenTimestamps work. Check current browser WebCrypto algorithm support when building the in-page verifier. Evaluate interoperable formats (e.g. in-toto/DSSE attestations) and a post-quantum signature option (ML-DSA) for the records themselves. Exit: third-party verification without PostQuantum installed, in a browser and on the command line; tampering and backdating detected in tests; record works fully offline. ## R5 — Deployment evidence collectors Authorized, bounded collectors that produce evidence for deployment-scope claims: TLS and SSH handshake observation (negotiated groups and signature algorithms), certificate metadata. Exit: explicit allowlist; non-invasive probes; scope recorded in every evidence item. ## R6 — CI and governance -GitHub Action that evaluates claims on pull requests; policy gates on verdicts, never on a composite score; baselines. Exit: least-privilege tokens; advisory mode proven before blocking. +GitHub Action that evaluates claims on pull requests; policy gates on verdicts, never on a composite score; baselines; verifiable badges (F7); questionnaire answers (F8). Exit: least-privilege tokens; advisory mode proven before blocking. ## R7 — Commercial layer (outside this repository) Multi-repository claim tracking, dashboard, evidence retention, auditor exports, self-hosted deployment. Offered under separate terms per LICENSING.md. Exit: security and privacy review, access-control and backup/restore tests. +## R8 — Public transparency log (opt-in) +Append-only public log for evidence records (F9), modelled on certificate transparency: inclusion proofs, signed tree heads, independent monitors. Publishing is always the operator's choice. Exit: log stores and proves inclusion only; it never signs or endorses verdicts; privacy review of published fields. + ## Built-in scanner Maintained as a zero-dependency fallback for environments without other tools. Improvements limited to correctness and coverage reporting; language-aware parsing is imported via CBOM rather than rebuilt. -Every release records commit, tests, coverage, limitations, dependency and security review, schema versions, and artifact hashes. +Every release records commit, tests, coverage, limitations, dependency and security review, schema versions, and artifact hashes, published as that release's own evidence record (F6). diff --git a/pyproject.toml b/pyproject.toml index 288dbaa..db681c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,9 +3,9 @@ requires = ["hatchling>=1.27"] build-backend = "hatchling.build" [project] -name = "postquantum-checker" +name = "pqdocket" version = "0.1.0" -description = "Evidence-led cryptographic discovery and PQC migration analysis" +description = "Evidence-led assurance for post-quantum migration: prove specific claims, not scores" readme = "README.md" requires-python = ">=3.11" license = "Apache-2.0" @@ -14,13 +14,13 @@ authors = [{ name = "Valentyn Rukhaylo (ALTRU.dev)" }] dependencies = [] [project.optional-dependencies] -dev = ["pytest>=8.0", "ruff>=0.5", "mypy>=1.10"] +dev = ["pytest>=8.0", "ruff>=0.5", "mypy>=1.10", "jsonschema>=4.18"] [project.scripts] -pqcheck = "pqcheck.cli:main" +pqdocket = "pqdocket.cli:main" [tool.hatch.build.targets.wheel] -packages = ["src/pqcheck"] +packages = ["src/pqdocket"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/schemas/scan-report.schema.json b/schemas/scan-report.schema.json index 4bf0534..1da22d9 100644 --- a/schemas/scan-report.schema.json +++ b/schemas/scan-report.schema.json @@ -1,7 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "PostQuantum Checker Scan Report", + "$id": "https://github.com/altrudev/PostQuantum/schemas/scan-report.schema.json", + "title": "pqdocket Scan Report", + "description": "Lexical scan report. Findings are candidate indicators only; runtime use is not established.", "type": "object", + "additionalProperties": false, "required": [ "schema_version", "scanner", @@ -12,49 +15,207 @@ ], "properties": { "schema_version": { - "type": "string" + "type": "string", + "pattern": "^1\\.\\d+\\.\\d+$" }, "generated_at": { "type": "string", "format": "date-time" }, "target": { - "type": "string" + "type": "string", + "minLength": 1 }, "scanner": { "type": "object", + "additionalProperties": false, "required": [ "name", "version" - ] + ], + "properties": { + "name": { + "const": "pqdocket" + }, + "version": { + "type": "string", + "minLength": 1 + } + } }, "summary": { "type": "object", + "additionalProperties": false, "required": [ "files_scanned", "files_skipped", + "files_not_scanned", "findings", "by_severity" - ] + ], + "properties": { + "files_scanned": { + "type": "integer", + "minimum": 0 + }, + "files_skipped": { + "type": "integer", + "minimum": 0 + }, + "files_not_scanned": { + "type": "integer", + "minimum": 0 + }, + "findings": { + "type": "integer", + "minimum": 0 + }, + "by_severity": { + "type": "object", + "propertyNames": { + "enum": [ + "high", + "medium", + "low", + "info" + ] + }, + "additionalProperties": { + "type": "integer", + "minimum": 0 + } + } + } }, "findings": { "type": "array", "items": { - "type": "object", - "required": [ - "finding_id", - "rule_id", - "title", - "category", - "algorithm_family", - "quantum_relevance", - "severity", - "confidence", - "status", - "rationale", - "evidence", - "remediation_hint" - ] + "$ref": "#/$defs/finding" + } + } + }, + "$defs": { + "finding": { + "type": "object", + "additionalProperties": false, + "required": [ + "finding_id", + "rule_id", + "title", + "category", + "algorithm_family", + "quantum_relevance", + "severity", + "confidence", + "status", + "rationale", + "evidence", + "remediation_hint" + ], + "properties": { + "finding_id": { + "type": "string", + "pattern": "^[0-9a-f]{16}$" + }, + "rule_id": { + "type": "string", + "pattern": "^PQC-[A-Z]+-[0-9]{3}$" + }, + "title": { + "type": "string", + "minLength": 1 + }, + "category": { + "enum": [ + "hash", + "key_encapsulation", + "key_establishment", + "public_key", + "signature", + "symmetric_encryption" + ] + }, + "algorithm_family": { + "type": "string", + "minLength": 1 + }, + "quantum_relevance": { + "enum": [ + "draft_pqc_standard", + "pre_standard_pqc", + "quantum_security_margin_assessment", + "standardized_pqc_candidate", + "vulnerable_to_large_scale_shor" + ] + }, + "severity": { + "enum": [ + "high", + "medium", + "low", + "info" + ] + }, + "confidence": { + "enum": [ + "low", + "medium", + "high" + ] + }, + "status": { + "enum": [ + "detected", + "unknown", + "partial", + "verified", + "not_compliant" + ] + }, + "rationale": { + "type": "string", + "minLength": 1 + }, + "remediation_hint": { + "type": "string", + "minLength": 1 + }, + "evidence": { + "$ref": "#/$defs/evidence" + } + } + }, + "evidence": { + "type": "object", + "additionalProperties": false, + "required": [ + "path", + "line_start", + "line_end", + "excerpt", + "sha256" + ], + "properties": { + "path": { + "type": "string", + "minLength": 1 + }, + "line_start": { + "type": "integer", + "minimum": 1 + }, + "line_end": { + "type": "integer", + "minimum": 1 + }, + "excerpt": { + "type": "string", + "maxLength": 300 + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } } } } diff --git a/scripts/release_evidence.py b/scripts/release_evidence.py new file mode 100644 index 0000000..de51ae3 --- /dev/null +++ b/scripts/release_evidence.py @@ -0,0 +1,129 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Build the evidence record for a pqdocket release (roadmap F6). + +Describes the release itself: source commit, test results, rule set, schema and +artifact hashes. It is not an assessment of any system pqdocket scans. Standard +library only, so it runs anywhere the release is built. + +Usage: + python scripts/release_evidence.py --dist dist --junit junit.xml --out release-evidence.json +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import sys +import xml.etree.ElementTree as ET +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +RECORD_VERSION = "1.0.0" +STATEMENT = ( + "This record describes this pqdocket release only: what was built, from which commit, " + "and which tests passed. It is not an assessment of any system that pqdocket scans, and " + "it does not vouch for any user's verdicts." +) +LIMITATIONS = [ + "Lexical discovery only; findings do not establish runtime use.", + "Test results cover the fixtures in the repository at this commit, not all real-world code.", + "Artifact integrity is proven by the build provenance attestation published with the release.", +] + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + digest.update(chunk) + return digest.hexdigest() + + +def git(*args: str) -> str: + try: + return subprocess.run(["git", *args], cwd=ROOT, check=True, capture_output=True, + text=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return "" + + +def test_results(junit: Path) -> dict[str, int]: + root = ET.parse(junit).getroot() + suites = [root] if root.tag == "testsuite" else list(root.iter("testsuite")) + totals = {"total": 0, "failures": 0, "errors": 0, "skipped": 0} + for suite in suites: + totals["total"] += int(suite.get("tests", 0)) + totals["failures"] += int(suite.get("failures", 0)) + totals["errors"] += int(suite.get("errors", 0)) + totals["skipped"] += int(suite.get("skipped", 0)) + totals["passed"] = totals["total"] - totals["failures"] - totals["errors"] - totals["skipped"] + return totals + + +def build_record(dist: Path, junit: Path) -> dict[str, Any]: + sys.path.insert(0, str(ROOT / "src")) + from pqdocket import __version__ + from pqdocket.rules import RULES + from pqdocket.scanner import SCHEMA_VERSION + + artifacts = sorted(p for p in dist.iterdir() if p.is_file()) if dist.is_dir() else [] + schema = ROOT / "schemas" / "scan-report.schema.json" + return { + "record_type": "pqdocket-release-evidence", + "record_version": RECORD_VERSION, + "statement": STATEMENT, + "project": {"name": "pqdocket", "version": __version__, + "repository": "https://github.com/altrudev/PostQuantum"}, + "source": { + "commit": os.environ.get("GITHUB_SHA") or git("rev-parse", "HEAD"), + "ref": os.environ.get("GITHUB_REF") or git("rev-parse", "--abbrev-ref", "HEAD"), + "uncommitted_changes": bool(git("status", "--porcelain", "--untracked-files=no")), + }, + "built_at": datetime.now(UTC).isoformat(), + "environment": {"python": platform.python_version(), "platform": platform.platform()}, + "tests": test_results(junit), + "rules": {"count": len(RULES), "ids": [rule.rule_id for rule in RULES]}, + "schemas": {"scan_report": {"version": SCHEMA_VERSION, "sha256": sha256(schema)}}, + "artifacts": [{"name": p.name, "bytes": p.stat().st_size, "sha256": sha256(p)} + for p in artifacts], + "limitations": LIMITATIONS, + } + + +def problems(record: dict[str, Any]) -> list[str]: + tests, found = record["tests"], [] + if tests["total"] == 0: + found.append("no tests ran") + if tests["failures"] or tests["errors"]: + found.append(f"{tests['failures']} failed, {tests['errors']} errors") + if not record["artifacts"]: + found.append("no release artifacts found") + if not record["source"]["commit"]: + found.append("source commit unknown") + if record["source"]["uncommitted_changes"]: + found.append("working tree has uncommitted changes") + return found + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dist", type=Path, default=ROOT / "dist") + parser.add_argument("--junit", type=Path, required=True) + parser.add_argument("--out", type=Path, default=ROOT / "release-evidence.json") + args = parser.parse_args(argv) + record = build_record(args.dist, args.junit) + args.out.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + found = problems(record) + for item in found: + print(f"release_evidence: {item}", file=sys.stderr) + print(f"Release evidence written to {args.out}") + return 1 if found else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/pqcheck/__init__.py b/src/pqcheck/__init__.py deleted file mode 100644 index 6e060f3..0000000 --- a/src/pqcheck/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""PostQuantum Checker.""" - -__version__ = "0.1.0" diff --git a/src/pqdocket/__init__.py b/src/pqdocket/__init__.py new file mode 100644 index 0000000..4fed413 --- /dev/null +++ b/src/pqdocket/__init__.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +"""pqdocket: evidence-led assurance for post-quantum migration.""" + +__version__ = "0.1.0" diff --git a/src/pqcheck/__main__.py b/src/pqdocket/__main__.py similarity index 100% rename from src/pqcheck/__main__.py rename to src/pqdocket/__main__.py diff --git a/src/pqcheck/cli.py b/src/pqdocket/cli.py similarity index 88% rename from src/pqcheck/cli.py rename to src/pqdocket/cli.py index d980b04..81d0709 100644 --- a/src/pqcheck/cli.py +++ b/src/pqdocket/cli.py @@ -8,7 +8,7 @@ def main() -> int: - parser = argparse.ArgumentParser(prog="pqcheck") + parser = argparse.ArgumentParser(prog="pqdocket") sub = parser.add_subparsers(dest="command", required=True) scan = sub.add_parser("scan", help="Scan a local source directory or file") scan.add_argument("target") @@ -18,7 +18,7 @@ def main() -> int: try: report = scan_path(args.target) except (OSError, ValueError) as exc: - print(f"pqcheck: error: {exc}", file=sys.stderr) + print(f"pqdocket: error: {exc}", file=sys.stderr) return 2 rendered = json.dumps(report.to_dict(), indent=2, ensure_ascii=False) + "\n" if args.output: diff --git a/src/pqcheck/models.py b/src/pqdocket/models.py similarity index 97% rename from src/pqcheck/models.py rename to src/pqdocket/models.py index af2dc0d..7d46ec6 100644 --- a/src/pqcheck/models.py +++ b/src/pqdocket/models.py @@ -33,6 +33,7 @@ class Finding: class ScanSummary: files_scanned: int = 0 files_skipped: int = 0 + files_not_scanned: int = 0 findings: int = 0 by_severity: dict[str, int] = field(default_factory=dict) diff --git a/src/pqcheck/rules.py b/src/pqdocket/rules.py similarity index 100% rename from src/pqcheck/rules.py rename to src/pqdocket/rules.py diff --git a/src/pqcheck/scanner.py b/src/pqdocket/scanner.py similarity index 71% rename from src/pqcheck/scanner.py rename to src/pqdocket/scanner.py index b02cb92..18c24e6 100644 --- a/src/pqcheck/scanner.py +++ b/src/pqdocket/scanner.py @@ -16,15 +16,27 @@ MAX_FILE_BYTES = 2_000_000 -def _candidates(root: Path) -> list[Path]: +SCHEMA_VERSION = "1.1.0" + + +def _candidates(root: Path) -> tuple[list[Path], int]: + """Return files to scan and the number of files left out because of their type.""" if root.is_file(): - return [root] if not root.is_symlink() and root.suffix.lower() in EXTENSIONS else [] - # Only folders inside the target are checked, so a checkout at ~/build/app is still scanned. - return [ - p for p in root.rglob("*") if p.is_file() and not p.is_symlink() - and not any(part in SKIP_DIRS for part in p.relative_to(root).parts[:-1]) - and p.suffix.lower() in EXTENSIONS - ] + if root.is_symlink() or root.suffix.lower() not in EXTENSIONS: + return [], 1 + return [root], 0 + scan, not_scanned = [], 0 + for p in root.rglob("*"): + if not p.is_file() or p.is_symlink(): + continue + # Only folders inside the target are checked, so a checkout at ~/build/app is scanned. + if any(part in SKIP_DIRS for part in p.relative_to(root).parts[:-1]): + continue + if p.suffix.lower() in EXTENSIONS: + scan.append(p) + else: + not_scanned += 1 + return scan, not_scanned def scan_path(target: str | Path) -> ScanReport: @@ -32,7 +44,8 @@ def scan_path(target: str | Path) -> ScanReport: if not root.exists(): raise FileNotFoundError(f"Target does not exist: {root}") summary, findings = ScanSummary(), [] - for path in _candidates(root): + candidates, summary.files_not_scanned = _candidates(root) + for path in candidates: try: if path.stat().st_size > MAX_FILE_BYTES: summary.files_skipped += 1 @@ -58,5 +71,5 @@ def scan_path(target: str | Path) -> ScanReport: for finding in findings: summary.by_severity[finding.severity] = summary.by_severity.get(finding.severity, 0) + 1 summary.findings = len(findings) - return ScanReport("1.0.0", {"name": "pqcheck", "version": __version__}, + return ScanReport(SCHEMA_VERSION, {"name": "pqdocket", "version": __version__}, utc_now(), str(root), summary, findings) diff --git a/tests/test_release_evidence.py b/tests/test_release_evidence.py new file mode 100644 index 0000000..51c80f3 --- /dev/null +++ b/tests/test_release_evidence.py @@ -0,0 +1,56 @@ +import importlib.util +import json +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +_spec = importlib.util.spec_from_file_location("release_evidence", ROOT / "scripts" / "release_evidence.py") +assert _spec and _spec.loader +release_evidence = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(release_evidence) + + +def _junit(path: Path, tests: int, failures: int = 0) -> Path: + path.write_text( + f'', encoding="utf-8") + return path + + +def _dist(tmp_path: Path) -> Path: + dist = tmp_path / "dist" + dist.mkdir() + (dist / "pqdocket-0.1.0-py3-none-any.whl").write_bytes(b"wheel") + return dist + + +@pytest.fixture(autouse=True) +def _clean_source(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GITHUB_SHA", "a" * 40) + monkeypatch.setattr(release_evidence, "git", lambda *args: "") + + +def test_record_describes_release(tmp_path: Path) -> None: + out = tmp_path / "evidence.json" + code = release_evidence.main(["--dist", str(_dist(tmp_path)), + "--junit", str(_junit(tmp_path / "j.xml", 5)), "--out", str(out)]) + record = json.loads(out.read_text("utf-8")) + assert code == 0 + assert record["tests"]["passed"] == 5 + assert record["artifacts"][0]["sha256"] == release_evidence.hashlib.sha256(b"wheel").hexdigest() + assert record["rules"]["count"] == len(record["rules"]["ids"]) > 0 + assert "does not vouch" in record["statement"] + + +def test_failing_tests_block_release(tmp_path: Path) -> None: + code = release_evidence.main(["--dist", str(_dist(tmp_path)), "--junit", + str(_junit(tmp_path / "j.xml", 5, failures=1)), + "--out", str(tmp_path / "e.json")]) + assert code == 1 + + +def test_missing_artifacts_block_release(tmp_path: Path) -> None: + code = release_evidence.main(["--dist", str(tmp_path / "nothing"), "--junit", + str(_junit(tmp_path / "j.xml", 5)), "--out", str(tmp_path / "e.json")]) + assert code == 1 diff --git a/tests/test_rules.py b/tests/test_rules.py index bac7bbe..c63e5a9 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -1,6 +1,6 @@ import pytest -from pqcheck.rules import rules_for_line +from pqdocket.rules import rules_for_line def ids(line: str) -> set[str]: diff --git a/tests/test_scanner.py b/tests/test_scanner.py index faa5b42..18d3d22 100644 --- a/tests/test_scanner.py +++ b/tests/test_scanner.py @@ -1,8 +1,8 @@ import json from pathlib import Path -from pqcheck import scanner -from pqcheck.scanner import scan_path +from pqdocket import scanner +from pqdocket.scanner import scan_path def test_line_level_evidence(tmp_path: Path) -> None: @@ -47,3 +47,21 @@ def test_oversized_files_are_counted_as_skipped(tmp_path: Path, monkeypatch) -> big.write_text("key = RSA.generate(2048)\n", encoding="utf-8") assert scan_path(tmp_path).summary.files_skipped == 1 assert scan_path(big).summary.files_skipped == 1 + + +def test_files_of_unlisted_types_are_counted_not_hidden(tmp_path: Path) -> None: + (tmp_path / "app.py").write_text("RSA\n", encoding="utf-8") + (tmp_path / "Dockerfile").write_text("FROM x\n", encoding="utf-8") + (tmp_path / "server.pem").write_text("-----BEGIN CERTIFICATE-----\n", encoding="utf-8") + (tmp_path / "node_modules").mkdir() + (tmp_path / "node_modules" / "README").write_text("x\n", encoding="utf-8") + summary = scan_path(tmp_path).summary + assert summary.files_scanned == 1 + assert summary.files_not_scanned == 2 # skipped folders are excluded, not counted + + +def test_single_file_of_unlisted_type_is_counted(tmp_path: Path) -> None: + target = tmp_path / "Dockerfile" + target.write_text("FROM x\n", encoding="utf-8") + summary = scan_path(target).summary + assert (summary.files_scanned, summary.files_not_scanned) == (0, 1) diff --git a/tests/test_schema.py b/tests/test_schema.py new file mode 100644 index 0000000..d43a432 --- /dev/null +++ b/tests/test_schema.py @@ -0,0 +1,47 @@ +import json +from pathlib import Path + +import jsonschema +import pytest + +from pqdocket.rules import RULES +from pqdocket.scanner import SCHEMA_VERSION, scan_path + +SCHEMA = json.loads( + (Path(__file__).resolve().parents[1] / "schemas" / "scan-report.schema.json").read_text("utf-8") +) +FINDING = SCHEMA["$defs"]["finding"]["properties"] + + +def _report(tmp_path: Path) -> dict: # type: ignore[type-arg] + (tmp_path / "a.py").write_text("RSA ML-KEM-768 Kyber768 FN-DSA-512 AES SHA-256\n", "utf-8") + (tmp_path / "Dockerfile").write_text("FROM x\n", "utf-8") + return scan_path(tmp_path).to_dict() + + +def test_schema_is_valid_draft_2020_12() -> None: + jsonschema.Draft202012Validator.check_schema(SCHEMA) + + +def test_report_validates_against_schema(tmp_path: Path) -> None: + report = _report(tmp_path) + jsonschema.Draft202012Validator(SCHEMA, format_checker=jsonschema.FormatChecker()).validate(report) + assert report["schema_version"] == SCHEMA_VERSION + + +def test_schema_rejects_unknown_severity(tmp_path: Path) -> None: + report = _report(tmp_path) + report["findings"][0]["severity"] = "critical" + with pytest.raises(jsonschema.ValidationError): + jsonschema.validate(report, SCHEMA) + + +@pytest.mark.parametrize("field", ["category", "quantum_relevance", "severity"]) +def test_every_rule_value_is_allowed_by_schema(field: str) -> None: + allowed = set(FINDING[field]["enum"]) + assert {getattr(rule, field) for rule in RULES} <= allowed + + +def test_rule_ids_are_unique() -> None: + ids = [rule.rule_id for rule in RULES] + assert len(ids) == len(set(ids))