From 3dc4728762f37c1e5bebdb988783c7683c50fb55 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 14:01:49 +0000 Subject: [PATCH 1/7] fix(abi): make the Stripping and Types Idris2 modules type-check Checked with Idris2 0.7.0 (the version proven-tests.yml pins). On main, two of the five src/abi modules did not compile: - Stripping.idr: a dangling `|||` doc block at the end of the file was a parse error. Behind it, `stripLineCommentsIdempotent` had two real type errors: a `case c of '/' => Refl` branch the comment called impossible was not refuted, and `decEq` was used without importing it. Matching on a Char literal only reduces when the character is a literal, so the proof stuck on a variable head. The model now classifies each character once (`cls`: Slash, Newline, Other) and steps on the class; each proof carries the class with the equation `cls c = k`, so every case reduces. The theorem statements and all seven sanity checks are unchanged and pass. The new model computes the same function as the old pattern-matching one: checked exhaustively on all 349,525 strings of length <= 9 over `/`, newline, `x` and space, with no mismatch. - Types.idr: a named field in a one-line data declaration, and an Ord instance with no Eq instance. Both fixed without changing meaning. Its header claimed three proofs the file does not contain; it now says it declares types only, and notes its drift from src/types.rs. Negative controls: a planted false lemma and a planted non-terminating definition are both rejected, so the check can fail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- src/abi/Stripping.idr | 263 ++++++++++++++++++++++-------------------- src/abi/Types.idr | 22 +++- 2 files changed, 154 insertions(+), 131 deletions(-) diff --git a/src/abi/Stripping.idr b/src/abi/Stripping.idr index 115fdeff..a3a1ea03 100644 --- a/src/abi/Stripping.idr +++ b/src/abi/Stripping.idr @@ -4,34 +4,30 @@ ||| Comment and String Stripping Idempotence (PROOF-PROGRAMME Layer 1.0) ||| -||| Closes the slash-slash inductive case left open by PR #111 (issue #113). +||| Models the line-comment slice of the analyzer's comment-stripping pass, +||| `src/assail/analyzer.rs` `strip_proof_comments(without_strings, "//", +||| Some(("/*", "*/")))`, and proves the model **idempotent**: running it +||| twice yields the same output as running it once. ||| -||| Mechanises the foundation lemma for every Layer-1 per-category -||| soundness proof: the analyzer's comment-stripping pass is -||| **idempotent** — running it twice yields the same output as running -||| it once. This justifies the analyzer's preprocessing step at -||| `src/assail/analyzer.rs:931 strip_proof_comments(without_strings, -||| "//", Some(("/*", "*/")))` as a sound normalising rewrite that -||| every category detector can rely on without re-stripping. +||| What this establishes, and what it does not: ||| -||| Differences from the PR #111 model: +||| * The theorem is about this Idris2 model, not the Rust function. The +||| correspondence between the two is a hand transcription that no tool +||| checks (recorded as ASSUMED in PROOF-NEEDS.adoc). Block comments and +||| string literals are not modelled. +||| * Multi-comment semantics: every `//` comment is stripped, not only the +||| first (the PR #111 model's error). `stripLineCommentBody` hands +||| control back to `stripLineComments` after each preserved newline. ||| -||| 1. **Multi-comment semantics.** PR #111's model only stripped the -||| first `//` comment encountered — subsequent comments after a -||| newline were preserved unstripped. The Rust pass strips ALL -||| comments in the input. This module uses mutual recursion -||| (`stripLineComments` ↔ `stripLineCommentBody`) so that the -||| body-stripper calls back into the main stripper after each -||| preserved newline. -||| -||| 2. **Idempotence is now provable by structural induction** because -||| both functions consume strictly-smaller inputs on each call. -||| Idris2's totality checker validates the recursion. -||| -||| 3. **Slash-slash case Qed-closes** via `bodyIsFixedPoint` — -||| the closure lemma `stripLineComments (stripLineCommentBody xs) -||| = stripLineCommentBody xs` proved by simultaneous induction on -||| the main theorem and the body theorem. +||| Proof shape. Matching on a `Char` literal only reduces when the +||| character is itself a literal, so a proof over a variable character +||| gets stuck. Each character is therefore classified once (`cls`), and +||| every step dispatches on the class. The proofs carry the class as an +||| explicit argument together with the equation `cls c = k`, so each +||| case reduces. `stripLineComments` and `stripLineCommentBody` compute +||| the same function as the earlier pattern-matching definitions; that +||| was checked exhaustively on every string of length at most 9 over +||| `/`, newline, `x` and space (349,525 inputs, no mismatch). module PanicAttack.ABI.Stripping %default total @@ -52,39 +48,67 @@ public export nl : Char nl = '\n' +||| The only distinctions the stripper makes between characters. +public export +data Cls = Slash | Newline | Other + +public export +cls : Char -> Cls +cls '/' = Slash +cls '\n' = Newline +cls _ = Other + -- ═══════════════════════════════════════════════════════════════════════ --- Stripping functions (mirror src/assail/analyzer.rs:931 strip_proof_comments) +-- Stripping functions (mirror src/assail/analyzer.rs strip_proof_comments) -- --- Mutual recursion: stripLineComments handles non-comment input and --- delegates comment bodies to stripLineCommentBody; stripLineCommentBody --- walks until the next newline and then returns control to the main --- stripper for the post-newline tail. +-- `stripStep`, `slashStep` and `bodyStep` take the class of the character +-- in hand, so each recursive call is on a strict sub-list and the +-- totality checker accepts the definition. -- ═══════════════════════════════════════════════════════════════════════ mutual - ||| The main line-comment stripper. Walks the input, replacing any - ||| `//` (and the comment body up to the next newline) with `sp sp` - ||| followed by spaces up to the newline, then continuing past the - ||| newline with another stripping pass. + ||| The main line-comment stripper. Replaces each `//` and the comment + ||| body up to the next newline with spaces, keeps the newline, and + ||| continues stripping after it. public export stripLineComments : List Char -> List Char stripLineComments [] = [] - stripLineComments ('/' :: '/' :: rest) = - sp :: sp :: stripLineCommentBody rest - stripLineComments (c :: rest) = c :: stripLineComments rest - - ||| `stripLineCommentBody` walks from JUST AFTER `//` until the - ||| next newline, replacing every character with `sp`. At the - ||| newline (or end of input) it returns control to - ||| `stripLineComments` for the remainder, so the entire input is - ||| processed in one pass. + stripLineComments (c :: rest) = stripStep (cls c) c rest + + ||| One step of `stripLineComments`, given the class of the head. + public export + stripStep : Cls -> Char -> List Char -> List Char + stripStep Slash c [] = [c] + stripStep Slash c (d :: r) = slashStep (cls d) c d r + stripStep Newline c rest = c :: stripLineComments rest + stripStep Other c rest = c :: stripLineComments rest + + ||| A `/` followed by `d`: a comment opens only when `d` is `/` too. + public export + slashStep : Cls -> Char -> Char -> List Char -> List Char + slashStep Slash c d r = sp :: sp :: stripLineCommentBody r + slashStep Newline c d r = c :: stripStep Newline d r + slashStep Other c d r = c :: stripStep Other d r + + ||| Walks from just after `//` to the next newline, replacing every + ||| character with `sp`, then hands the rest back to + ||| `stripLineComments`. public export stripLineCommentBody : List Char -> List Char stripLineCommentBody [] = [] - stripLineCommentBody (c :: rest) = - if c == nl - then nl :: stripLineComments rest - else sp :: stripLineCommentBody rest + stripLineCommentBody (c :: rest) = bodyStep (cls c) rest + + ||| One step of `stripLineCommentBody`, given the class of the head. + public export + bodyStep : Cls -> List Char -> List Char + bodyStep Newline rest = nl :: stripLineComments rest + bodyStep Slash rest = sp :: stripLineCommentBody rest + bodyStep Other rest = sp :: stripLineCommentBody rest + +||| `stripLineComments` on a cons cell, unfolded one step. +stripCons : (c : Char) -> (x : List Char) -> + stripLineComments (c :: x) = stripStep (cls c) c x +stripCons c x = Refl -- ═══════════════════════════════════════════════════════════════════════ -- Idempotence — main theorem + body fixed-point lemma, mutual induction @@ -97,66 +121,55 @@ mutual stripLineCommentsIdempotent : (cs : List Char) -> stripLineComments (stripLineComments cs) = stripLineComments cs stripLineCommentsIdempotent [] = Refl - stripLineCommentsIdempotent ('/' :: '/' :: rest) = - -- LHS = strip (strip ('/' :: '/' :: rest)) - -- = strip (sp :: sp :: stripBody rest) [by definition] - -- = sp :: strip (sp :: stripBody rest) [sp /= '/'] - -- = sp :: sp :: strip (stripBody rest) [sp /= '/'] - -- = sp :: sp :: stripBody rest [by bodyIsFixedPoint] - -- RHS = sp :: sp :: stripBody rest [by definition] - cong (\xs => sp :: sp :: xs) (bodyIsFixedPoint rest) - stripLineCommentsIdempotent ('/' :: c :: rest) = - -- Not a comment marker (c is not the immediate-second '/'). - -- The third clause of stripLineComments applies: the head '/' - -- is preserved and recursion continues on (c :: rest). - case c of - '/' => Refl -- impossible: the prior clause matched - _ => cong ('/' ::) (stripLineCommentsIdempotent (c :: rest)) - stripLineCommentsIdempotent (c :: rest) = - -- Generic non-comment-head case: c is not `/`. The outer strip - -- preserves the head and recurses, so idempotence reduces to - -- the inductive hypothesis. - case c of - '/' => case rest of - [] => Refl - _ :: _ => Refl -- covered by the prior two clauses - _ => cong (c ::) (stripLineCommentsIdempotent rest) + stripLineCommentsIdempotent (c :: rest) = stepIdem (cls c) c Refl rest + + ||| Idempotence of one step, for a head `c` of class `k`. + stepIdem : (k : Cls) -> (c : Char) -> cls c = k -> (rest : List Char) -> + stripLineComments (stripStep k c rest) = stripStep k c rest + stepIdem Slash c p [] = + rewrite stripCons c [] in rewrite p in Refl + stepIdem Slash c p (d :: r) = slashIdem (cls d) c p d Refl r + stepIdem Newline c p rest = + rewrite stripCons c (stripLineComments rest) in rewrite p in + cong (c ::) (stripLineCommentsIdempotent rest) + stepIdem Other c p rest = + rewrite stripCons c (stripLineComments rest) in rewrite p in + cong (c ::) (stripLineCommentsIdempotent rest) + + ||| Idempotence after a `/`, for a next character `d` of class `j`. + ||| When `j` is `Slash` a comment opens and the body lemma applies; + ||| otherwise the `/` is kept, and it still cannot pair with `d` on + ||| the second pass. + slashIdem : (j : Cls) -> (c : Char) -> cls c = Slash -> + (d : Char) -> cls d = j -> (r : List Char) -> + stripLineComments (slashStep j c d r) = slashStep j c d r + slashIdem Slash c p d q r = + cong (\xs => sp :: sp :: xs) (bodyIsFixedPoint r) + slashIdem Newline c p d q r = + rewrite stripCons c (d :: stripLineComments r) in rewrite p in + rewrite q in + cong (\xs => c :: d :: xs) (stripLineCommentsIdempotent r) + slashIdem Other c p d q r = + rewrite stripCons c (d :: stripLineComments r) in rewrite p in + rewrite q in + cong (\xs => c :: d :: xs) (stripLineCommentsIdempotent r) ||| **Body fixed-point lemma.** Applying the line-comment stripper - ||| to the output of the body-stripper is a no-op — the body - ||| output's pre-newline region is all `sp` (no further `//` can - ||| form), and the post-newline tail is whatever the body-stripper - ||| recursively passed to `stripLineComments`, which is already - ||| a fixed point by the main theorem. + ||| to the output of the body-stripper is a no-op: the pre-newline + ||| region is all `sp`, so no `//` can form, and the post-newline + ||| tail is already a fixed point by the main theorem. public export bodyIsFixedPoint : (cs : List Char) -> stripLineComments (stripLineCommentBody cs) = stripLineCommentBody cs bodyIsFixedPoint [] = Refl - bodyIsFixedPoint (c :: rest) = - -- Case split on whether c is the newline. - case decEq c nl of - Yes prf => - -- c = nl. Body returns `nl :: stripLineComments rest`. - -- strip applied to that = `nl :: strip (stripLineComments rest)` - -- (nl /= '/'). By main theorem on `rest`, that = - -- `nl :: stripLineComments rest`. - rewrite prf in - cong (nl ::) (stripLineCommentsIdempotent rest) - No cNotNl => - -- c /= nl. Body returns `sp :: stripLineCommentBody rest`. - -- strip applied to that = `sp :: strip (stripLineCommentBody rest)` - -- (sp /= '/'). By the body IH, that = `sp :: stripLineCommentBody rest`. - let - -- Establish that the body output starts with sp - -- under the c /= nl case. - bodyOutputShape : stripLineCommentBody (c :: rest) - = sp :: stripLineCommentBody rest - bodyOutputShape = case decEq c nl of - Yes y => absurd (cNotNl y) - No _ => Refl - in - rewrite bodyOutputShape in - cong (sp ::) (bodyIsFixedPoint rest) + bodyIsFixedPoint (c :: rest) = bodyStepFixed (cls c) rest + + ||| The body lemma for one step, for a head of class `k`. + bodyStepFixed : (k : Cls) -> (rest : List Char) -> + stripLineComments (bodyStep k rest) = bodyStep k rest + bodyStepFixed Newline rest = cong (nl ::) (stripLineCommentsIdempotent rest) + bodyStepFixed Slash rest = cong (sp ::) (bodyIsFixedPoint rest) + bodyStepFixed Other rest = cong (sp ::) (bodyIsFixedPoint rest) -- ═══════════════════════════════════════════════════════════════════════ -- Sanity tests @@ -219,27 +232,27 @@ sanityTwoComments = Refl -- What still remains (Layer 1.0 future slices) -- ═══════════════════════════════════════════════════════════════════════ -||| Future Layer-1.0 work (recorded in PROOF-NEEDS.md + issue #114): -||| -||| 1. **Stripping_Block.idr** — `/* … */` block-comment stripper. Same -||| mutual-recursion shape. The closing `*/` plays the role newlines -||| played here. -||| -||| 2. **Stripping_Strings.idr** — `"…"` string-literal stripper with -||| `\"` escape handling. Same mutual-recursion shape. -||| -||| 3. **Stripping_Composition.idr** — `strip = stripLineComments . -||| stripBlockComments . stripStrings` is itself idempotent given -||| each component is. Requires cross-component lemmas (e.g. line- -||| stripping the output of block-stripping doesn't introduce new -||| `/*` tokens). -||| -||| 4. **Stripping_PositionPreservation.idr** — for every index `i` -||| where `cs[i]` is OUTSIDE every comment/string region, -||| `strip cs ! i = cs[i]`. Justifies the analyzer reporting -||| locations against the stripped view as original-source -||| locations. -||| -||| Once all five land, every Layer-1.1..1.25 per-category proof can -||| assume `strip s` is a fixed point and the original-vs-stripped -||| position mapping is the identity on token boundaries. +-- Future Layer-1.0 work (recorded in PROOF-NEEDS.md + issue #114): +-- +-- 1. **Stripping_Block.idr** — `/* … */` block-comment stripper. Same +-- mutual-recursion shape. The closing `*/` plays the role newlines +-- played here. +-- +-- 2. **Stripping_Strings.idr** — `"…"` string-literal stripper with +-- `\"` escape handling. Same mutual-recursion shape. +-- +-- 3. **Stripping_Composition.idr** — `strip = stripLineComments . +-- stripBlockComments . stripStrings` is itself idempotent given +-- each component is. Requires cross-component lemmas (e.g. line- +-- stripping the output of block-stripping doesn't introduce new +-- `/*` tokens). +-- +-- 4. **Stripping_PositionPreservation.idr** — for every index `i` +-- where `cs[i]` is OUTSIDE every comment/string region, +-- `strip cs ! i = cs[i]`. Justifies the analyzer reporting +-- locations against the stripped view as original-source +-- locations. +-- +-- Once all five land, every Layer-1.1..1.25 per-category proof can +-- assume `strip s` is a fixed point and the original-vs-stripped +-- position mapping is the identity on token boundaries. diff --git a/src/abi/Types.idr b/src/abi/Types.idr index ee997b15..9cebcfe9 100644 --- a/src/abi/Types.idr +++ b/src/abi/Types.idr @@ -3,11 +3,13 @@ -- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) ||| ABI Types for panic-attack static analysis engine ||| -||| Defines the formal interface for the scanner's operations. -||| Proves that: -||| 1. Severity levels are totally ordered -||| 2. Scan results cannot be fabricated (constructive) -||| 3. Language coverage is bounded +||| Declares ABI-facing types and their C integer encodings. It contains no +||| theorems, and no other module imports it. The severity order is proved +||| in ClassificationSoundness.idr, over its own Severity type. +||| +||| Known drift (see PROOF-NEEDS.adoc): this Severity type does not match +||| src/types.rs, and LangId is bounded at 47 while src/types.rs has 52 +||| Language variants. module PanicAttack.ABI.Types import Data.Fin @@ -18,6 +20,14 @@ import Data.Fin public export data Severity = Info | Warning | Error | Critical +public export +Eq Severity where + Info == Info = True + Warning == Warning = True + Error == Error = True + Critical == Critical = True + _ == _ = False + ||| Total ordering on severity public export Ord Severity where @@ -43,7 +53,7 @@ data ScanOp ||| Language identifier (47 supported, bounded) public export -data LangId = MkLangId (n : Fin 47) +data LangId = MkLangId (Fin 47) -- ═══════════════════════════════════════════════════════════════════════ -- C ABI Exports From b1b1419f14cc630a629c30cd3d452f39f2e487e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 14:04:15 +0000 Subject: [PATCH 2/7] docs(proofs): record proof status against the estate proof policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PROOF-NEEDS.adoc now uses the proof policy's §5 status tokens and §1.2 verifier mapping, pinned to standards 9bdf864, in place of check marks. Each status rests on a recorded receipt: Idris2 0.7.0 run over src/abi at 3dc4728, with the invocation, pass criterion and negative controls. What the re-check found, and how it is now recorded: - Stripping: did not compile on main; repaired in 3dc4728. PROVEN for the model; model-to-Rust correspondence ASSUMED. - Attestation: PROVEN relative to its hypotheses. Two of them, an injective chain hash and perfect unforgeability, are symbolic-model idealisations stronger than collision resistance and EUF-CMA, so no computational result is claimed. - PA1 (pattern completeness): compiles but is vacuous, because a generic analyzer witness inhabits every language. rustc's exhaustiveness check on the `_ => analyze_generic` match already gives the guarantee. The model is also stale (50 of 52 languages; cross-language checks are now skipped for configuration files). - Implementation obligations on Rust behaviour (stripping, Patch Bridge reachability, taint analysis) are OPEN for Creusot/Pearlite and Verus. The missing CI gate for src/abi is OPEN. - The Kani note is backed by compiling every non-example target with unsafe_code forbidden. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- PROOF-NEEDS.adoc | 255 +++++++++++++++++++++++++++++------------------ 1 file changed, 159 insertions(+), 96 deletions(-) diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc index e09653d0..c1e8c652 100644 --- a/PROOF-NEEDS.adoc +++ b/PROOF-NEEDS.adoc @@ -1,102 +1,165 @@ -== PROOF-NEEDS.md — panic-attack - -=== Current State - -* **src/abi/*.idr**: 5 files — `+Types.idr+`, -`+PatternCompleteness.idr+` (PA1 ✅ 2026-04-11), -`+ClassificationSoundness.idr+` (PA2 ✅ 2026-04-11), `+Stripping.idr+` -(PROOF-PROGRAMME Layer 1.0 line-comment slice ✅ 2026-06-02 — -multi-comment semantics + slash-slash closure both Qed via -mutual-recursive `+bodyIsFixedPoint+`), -`+AttestationUnforgeability.idr+` (PROOF-PROGRAMME §3.2 ✅ 2026-06-04 — -conditional unforgeability from Ed25519 EUF-CMA + chain-hash -collision-resistance hypotheses) -* *Dangerous patterns*: 0 in own code (3 references are in the analyzer -that DETECTS believe_me in other repos); 282 `+unwrap()+` calls -* *LOC*: ~31,700 (Rust) -* *ABI layer*: Idris2 with completeness + soundness proofs + Layer-1.0 -stripping foundation - -=== Completed Proofs - -[width="100%",cols="26%,21%,53%",options="header",] += Proof status: panic-attack + +This file records each proof obligation in panic-attack, the verifier it +belongs to, and its status. The rules are the estate proof policy, +https://github.com/metadatastician/standards/blob/9bdf864cc7f2c8e24b4df84bf00d04158eee3ad5/3-practice/PROOF-POLICY.adoc[`standards/3-practice/PROOF-POLICY.adoc` +at `9bdf864cc7f2c8e24b4df84bf00d04158eee3ad5`]. Statuses use its closed §5 +vocabulary: `PROVEN`, `PROVEN-WITH-AXIOMS`, `TESTED`, `ASSUMED`, `OPEN`. + +None of these obligations is a theory theorem (§1), so none carries a Proof +Witness Grade. + +== Where each kind of obligation belongs + +* *Behaviour of first-party Rust code* (stripping, reachability, taint + propagation, dispatch): Creusot with Pearlite contracts, and Verus, on the + implementation (§1.2). An Idris2 model of a Rust function is not evidence + that the function is correct (§1, §2.2). +* *Interfaces, ABI encodings and cross-language protocols* (the attestation + chain, the C integer encodings): Idris2. +* *Statements true of any implementation* (for example, a taint lattice + and its fixed point stated abstractly): Agda, rechecked in Rocq and Lean + (§2). + +No Kani obligation arises (§4.1). With `unsafe_code` forbidden, +`cargo clippy --lib --bins --tests --benches --all-features -- -F unsafe_code` +compiles at `f2a6a70eaec0cb02331e3264e05f185b5faab0f7`. The only `unsafe` +is in `examples/vulnerable_program.rs`, a deliberately buggy program that +exists to be scanned. + +== Receipt for the Idris2 modules + +* *Checker:* Idris2 0.7.0, the version `proven-tests.yml` pins, built from + tag `v0.7.0` (`27780073c8631826d846499840b3857d9b9a4fd5`) on Chez Scheme + 9.5.8. +* *Source:* `src/abi/*.idr` at + `3dc4728762f37c1e5bebdb988783c7683c50fb55`. +* *Invocation:* the modules are named `PanicAttack.ABI.` but live in + `src/abi/`, so `idris2 --check src/abi/.idr` fails on a module-name + mismatch from any directory. Each was checked from a tree that places + `src/abi/.idr` at `PanicAttack/ABI/.idr`, with + `idris2 --check PanicAttack/ABI/.idr`. A pass is exit 0 *and* no + `Error:` line, because `idris2 --check` can exit 0 while printing an + error. +* *Result:* all five modules pass. Every module sets `%default total` and + uses no `believe_me`, `assert_total`, `postulate` or holes. +* *Negative controls:* a planted false lemma and a planted non-terminating + definition in `Stripping.idr` were both rejected, so the check can fail. +* *Gate:* no CI job runs this check. That obligation is `OPEN` below. Until + it closes, the statuses here rest on this one local run, and any change + to `src/abi/` invalidates them. + +== Ledger + +[cols="3,2,2,5",options="header"] |=== -|Proof |File |What it proves -|PA1 Pattern detection completeness |`+src/abi/PatternCompleteness.idr+` -|All 49 `+Lang+` constructors have an analyzer; all 20 `+WPCategory+` -constructors have at least one detector; cross-language checks applied -unconditionally to all languages. `+completeScanForAll+` is the -top-level theorem. - -|PA2 Classification soundness |`+src/abi/ClassificationSoundness.idr+` -|Severity (Low/Medium/High/Critical) is totally ordered (`+LTE+`); -`+maxSeverity+` is commutative and idempotent; numeric ABI encoding -preserves the ordering. - -|Layer 1.0 line-comment idempotence |`+src/abi/Stripping.idr+` -|*2026-06-02 close-out (issue #113)*: corrects PR #111’s single-comment -model to multi-comment via mutual recursion -(`+stripLineComments ↔ stripLineCommentBody+` — body calls back into -main after each preserved newline). Qed-closes -`+stripLineCommentsIdempotent+` for ALL cases including the slash-slash -inductive via the load-bearing `+bodyIsFixedPoint+` lemma proved by -mutual induction with the main theorem. 7 sanity-check theorems -including the two-comments-on-different-lines case PR #111 silently -mis-stripped. - -|Attestation chain unforgeability -|`+src/abi/AttestationUnforgeability.idr+` |*PROOF-PROGRAMME §3.2 -(2026-06-04, issue #123)*: models the intent→evidence→seal chain -(`+chain_hash = H(intent‖evidence‖report)+`, Ed25519-signed) with the -cryptographic facts as a `+parameters+` block (hypotheses, *not* -`+postulate+`). Under `+%default total+` Qed-closes `+integrity+` -(tampering any phase invalidates the seal), `+authenticity+` (a -verifying seal comes from the matching secret key), `+nonRepudiation+` -(a genuine seal verifies), plus 2 corollaries. Conditional on chain-hash -collision-resistance + Ed25519 EUF-CMA (message- and signer-binding) + -signature correctness. - -|Hexad↔Octad persistence round-trip |`+src/storage/mod.rs+` (proptest) -|*PROOF-PROGRAMME §3.1 (2026-06-04, #122)*: -`+hexad_json_roundtrip_is_identity+` tests an in-memory -`+serde_json::Value+` serialize/deserialize/serialize round-trip on generated -samples, not by a universal theorem. It does not call `+write_*_hexad+` or -`+load_hexad_dir+`; on-disk persistence correspondence remains a separate -obligation. The gateway octad projection is lossy by design, so this property -also does not establish a faithful hexad↔octad map. +|Obligation |Artefact |Status |Trust boundary and notes + +|Severity order: `Low < Medium < High < Critical` is a total order; +`sevMax` is an upper bound; the numeric encoding is monotone (PA2) +|`src/abi/ClassificationSoundness.idr` +|`PROVEN` (model) +|The model's `Severity` matches the variant names and order of +`src/types.rs`; that correspondence is `ASSUMED` (a hand transcription). +The Rust order itself comes from `#[derive(PartialOrd, Ord)]`. + +|Line-comment stripping is idempotent: `strip (strip s) = strip s` +|`src/abi/Stripping.idr` +|`PROVEN` (model) +|Did not compile on `main` before `3dc4728`; repaired there without +changing the theorem. The repaired model equals the previous one: +`TESTED`, exhaustively on all 349,525 strings of length at most 9 over +`/`, newline, `x` and space. The model covers line comments only; block +comments and string literals are not modelled. Model to Rust +`strip_proof_comments`: `ASSUMED`. + +|Attestation chain: integrity, authenticity, non-repudiation +|`src/abi/AttestationUnforgeability.idr` +|`PROVEN` (model), relative to the `ASSUMED` hypotheses listed here +|The module's `parameters` block assumes: + +* `chainCR`: the chain hash is *injective*. +* `sigCorrect`: an honest signature verifies. +* `sigBindsMessage`: a signature verifies only on the message signed. +* `sigOnlySigner`: a verifying signature was produced by the key holder, + with no exceptions. + +`chainCR` and `sigOnlySigner` are idealisations. They are stronger than +collision resistance and EUF-CMA, and false of any real fixed-length hash +or signature scheme. So these are theorems of a symbolic (Dolev-Yao style) +model, not a computational security reduction. Model to +`src/attestation/`: `ASSUMED`. A computational proof is not claimed. + +|Every language reaches an analyzer; every weak-point category has a +detector; cross-language checks run on every file (PA1) +|`src/abi/PatternCompleteness.idr` +|`PROVEN` (model); supports no claim about the Rust code +|The theorem is vacuous: `GenericAnalyzer : HasAnalyzer lang` inhabits +the witness type for every language, so it holds whatever the dispatch +does. The guarantee it was meant to give already holds in Rust: +`match file_lang` in `src/assail/analyzer.rs` ends in +`_ => analyze_generic`, and `rustc` checks the match is exhaustive. + +The model has also drifted. Its `Lang` has 50 constructors and +`src/types.rs` has 52; `C` and `Php` are missing. `crossLangAlwaysApplied` +says cross-language checks run on every file, but the Rust code skips them +when `configuration.is_some()`. That model claim is false of the +implementation. + +|Declarations for the ABI-facing types and their C integer encodings +|`src/abi/Types.idr` +|No theorem +|Repaired in `3dc4728` so it compiles. It contains no proof and nothing +imports it. Drift: its `Severity` is `Info / Warning / Error / Critical` +where `src/types.rs` has `Low / Medium / High / Critical`, and `LangId` is +bounded at 47 against 52 variants. + +|Hexad JSON round-trip is the identity +|`src/storage/mod.rs`, `hexad_json_roundtrip_is_identity` (proptest) +|`TESTED` +|A serialize, deserialize, serialize round trip on proptest-generated +hexads, compared as `serde_json::Value`. It does not call +`write_*_hexad` or `load_hexad_dir`, so on-disk persistence is a separate +obligation. The gateway octad projection is lossy by design, so this does +not establish a faithful hexad-to-octad map. |=== -=== What Still Needs Proving +== Open obligations -[width="100%",cols="51%,27%,22%",options="header",] +[cols="3,2,5",options="header"] |=== -|Component |What |Why -|*Layer 1.0 — stripBlockComments + Strings + Composition + -Position-Preservation* (issue #114) |Block-comment (`+/* */+`) and -string-literal (`+"..."+`) strippers with same mutual-recursive shape; -composition theorem proving the full pipeline is idempotent given each -component is; position-preservation theorem justifying analyzer -location-reporting against the stripped view as if it were -original-source. |Four slices: `+Stripping_Block.idr+`, -`+Stripping_Strings.idr+`, `+Stripping_Composition.idr+`, -`+Stripping_PositionPreservation.idr+`. - -|Bridge reachability soundness |Reachability analysis is sound (no -reachable dep wrongly classified as phantom) |Unreachable code marked -reachable wastes effort; reachable missed = security gap - -|Kanren taint analysis |Taint propagation tracks all tainted data flows -|Missed taint flow means missed vulnerability +|Obligation |Verifier (§1, §1.2) |Notes + +|Gate the Idris2 modules in CI +|CI +|Run the receipt's invocation on every change to `src/abi/`, failing on +any `Error:` line. Moving the files to `src/abi/PanicAttack/ABI/` would +let a plain `idris2 --check` work. + +|`strip_proof_comments` is idempotent and preserves positions outside +comments and strings +|Creusot/Pearlite and Verus +|On the Rust implementation. The Idris2 model above can guide the +contracts; it does not discharge them. The model's own remaining slices +(block comments, strings, composition, position preservation; issue #114) +are optional once the implementation proof exists. + +|Patch Bridge reachability is sound: no reachable dependency is classified +as phantom +|Creusot/Pearlite and Verus +|`src/bridge/reachability.rs`. A missed reachable dependency is a security +gap. + +|Kanren taint analysis tracks every tainted flow +|Creusot/Pearlite and Verus; Agda for the abstract theory +|Any implementation-independent statement (the lattice, monotonicity, the +fixed point) is theory and belongs in Agda with Rocq and Lean rechecks. +Its realisation in `src/kanren/` is a Rust obligation. + +|Replace or retire PA1 +|Creusot/Pearlite and Verus, or retire +|A non-vacuous statement would be, for example, that each language with +a dedicated analyzer is routed to it. If that is not wanted, retire the +module, because `rustc`'s exhaustiveness check already gives the current +guarantee. |=== - -=== Recommended Prover - -*Idris2* — Already in use. Taint analysis correctness proofs could use -*Agda* with relational semantics. The 282 unwrap() calls are a -significant debt (but separate from the proof obligations). - -=== Priority - -*MEDIUM* (was HIGH) — PA1 and PA2 completed 2026-04-11. The highest-risk -false-negative scenario (analyzer dispatch completeness) is now formally -proved. Remaining proofs are deeper semantic properties. From c78335ca7053dad4f65ca920009d96ffdc7611c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 14:15:38 +0000 Subject: [PATCH 3/7] ci(abi): gate the Idris2 proofs on every PR, with module-shaped paths The Idris2 modules are named PanicAttack.ABI. but lived in src/abi/, so `idris2 --check src/abi/.idr` failed on a module-name mismatch from any directory. No CI job checked them, which is how Stripping.idr sat on main not compiling while PROOF-NEEDS called it closed. - Move src/abi/*.idr to src/abi/PanicAttack/ABI/ (pure renames) and add src/abi/panic-attack-abi.ipkg listing the five modules. - Add the `abi-proofs` job to proven-tests.yml: every PR and push to main runs `idris2 --typecheck src/abi/panic-attack-abi.ipkg` and fails on a non-zero exit or any `Error:` line. It reuses the framework job's pinned installer and Idris2 cache key, and only the actions that workflow already locks, so actions.lock is unchanged. - PROOF-NEEDS.adoc: the gate is now the receipt; the first local receipt is kept; the gate row leaves the open list. EXPLAINME and PROOF-PROGRAMME point at the new paths. CHANGELOG history and the retired .a2ml files are left as they are. Checked locally: the package type-checks (Idris2 0.7.0); a planted false lemma and a planted missing import both fail it; the job's run step passes as written; actionlint 1.7.7 is clean; validate-sha-pins and check-allowed-actions pass with the checksum-pinned yq v4.54.1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- .github/workflows/proven-tests.yml | 56 ++++++++++++++++- EXPLAINME.adoc | 6 +- PROOF-NEEDS.adoc | 60 +++++++++---------- PROOF-PROGRAMME.adoc | 12 ++-- .../ABI}/AttestationUnforgeability.idr | 0 .../ABI}/ClassificationSoundness.idr | 0 .../ABI}/PatternCompleteness.idr | 0 src/abi/{ => PanicAttack/ABI}/Stripping.idr | 0 src/abi/{ => PanicAttack/ABI}/Types.idr | 0 src/abi/panic-attack-abi.ipkg | 15 +++++ 10 files changed, 107 insertions(+), 42 deletions(-) rename src/abi/{ => PanicAttack/ABI}/AttestationUnforgeability.idr (100%) rename src/abi/{ => PanicAttack/ABI}/ClassificationSoundness.idr (100%) rename src/abi/{ => PanicAttack/ABI}/PatternCompleteness.idr (100%) rename src/abi/{ => PanicAttack/ABI}/Stripping.idr (100%) rename src/abi/{ => PanicAttack/ABI}/Types.idr (100%) create mode 100644 src/abi/panic-attack-abi.ipkg diff --git a/.github/workflows/proven-tests.yml b/.github/workflows/proven-tests.yml index 82ab20c9..a31591e9 100644 --- a/.github/workflows/proven-tests.yml +++ b/.github/workflows/proven-tests.yml @@ -3,7 +3,7 @@ # # proven-tests.yml — the estate's evidence-graded test framework, wired. # -# THE TWO JOBS DO DIFFERENT THINGS AND NEITHER PRETENDS TO BE THE OTHER +# THE JOBS DO DIFFERENT THINGS AND NONE PRETENDS TO BE ANOTHER # --------------------------------------------------------------------- # `ledger` (every PR, blocking, minutes): derives a proven-tests run report from # THIS repo's suite — from a test inventory the runner emitted in the same @@ -22,6 +22,10 @@ # and it would make every contributor wait on a compiler that cannot change # for them. # +# `abi-proofs` (every PR, blocking): type-checks this repository's own Idris2 +# proofs in src/abi with the same pinned Idris2. It reuses the framework job's +# toolchain cache, so it costs a compiler build only on a cold cache. +# # WHY THE REPORT IS A FILE, NOT A PARAGRAPH: docs/INTEROP-PANIC-ATTACK.adoc in # proven-tests-and-benches fixes the mapping in prose; a report plus a verifier # is the same mapping with something at stake. @@ -142,6 +146,56 @@ jobs: retention-days: 30 if-no-files-found: warn + abi-proofs: + # Every PR: type-check this repo's own Idris2 ABI proofs (src/abi). Without + # this, src/abi/PanicAttack/ABI/Stripping.idr sat on main not compiling + # while PROOF-NEEDS.adoc called it closed. The toolchain comes from the same + # pinned installer and cache key as the framework job, so a warm cache makes + # this a type-check, not a compiler build. + name: Idris2 — src/abi proofs type-check + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - name: Checkout this repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Checkout proven-tests-and-benches at the pinned commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: hyperpolymath/proven-tests-and-benches + ref: ${{ env.PROVEN_TESTS_PIN }} + path: .proven-tests + persist-credentials: false + + - name: Cache the Idris2 toolchain + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.idris2 + key: idris2-v${{ env.IDRIS2_VERSION }}-${{ runner.os }} + + - name: Install Idris2 (chez backend) + working-directory: .proven-tests + env: + IDRIS2_VERSION: v${{ env.IDRIS2_VERSION }} + run: bash scripts/install-idris2.sh + + - name: Type-check src/abi + run: | + set -euo pipefail + export PATH="$HOME/.idris2/bin:$PATH" + idris2 --version + # `idris2 --check` can exit 0 while printing an error, so require + # both a zero exit and no `Error:` line. + status=0 + out="$(idris2 --typecheck src/abi/panic-attack-abi.ipkg 2>&1)" || status=$? + printf '%s\n' "$out" + if [ "$status" -ne 0 ] || grep -q '^Error' <<<"$out"; then + echo "::error::src/abi Idris2 proofs do not type-check (exit $status)" + exit 1 + fi + framework: name: Framework — the grader is exercised (scheduled) if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' diff --git a/EXPLAINME.adoc b/EXPLAINME.adoc index 8724d1ff..f2ea5532 100644 --- a/EXPLAINME.adoc +++ b/EXPLAINME.adoc @@ -52,9 +52,9 @@ The README makes claims. This file backs them up. | `src/comment_marker.rs` | Inline `// panic-attack: accepted [- reason]` suppression marker — `//` / `#` / `--` / `;` / `%` leaders, string-literal aware | `src/ffi_kind.rs` | UnsafeFFI (PA013) subtyping: BuildSystem (`build.zig` / `build.rs` — audit-accepted), RuntimeAbi (`bindings/` / `ffi/` / `sys/` / `cdef.zig`), TestMock (`tests/mocks/` / `_stub`), Unknown | `src/jit_context.rs` | JIT-framework classifier: Cranelift / Llvm / Wasm / Javascript / None; `transmute_targets_fn_ptr` recogniser for fn-ptr type-punning -| `src/abi/PatternCompleteness.idr` | PA1 Idris2 proof — every Lang/Category has a detector -| `src/abi/ClassificationSoundness.idr` | PA2 Idris2 proof — severity total order + maxSeverity commutativity -| `src/abi/Stripping.idr` | Layer 1.0 partial — line-comment-strip foundation (shape lemma + base cases of `stripLineCommentsIdempotent` Qed-closed) +| `src/abi/PanicAttack/ABI/PatternCompleteness.idr` | PA1 Idris2 model of analyzer dispatch; vacuous as stated (see `PROOF-NEEDS.adoc`) +| `src/abi/PanicAttack/ABI/ClassificationSoundness.idr` | PA2 Idris2 proof — severity total order, `sevMax` upper bounds, monotone encoding +| `src/abi/PanicAttack/ABI/Stripping.idr` | Layer 1.0 — Idris2 model of line-comment stripping, proved idempotent (`stripLineCommentsIdempotent`) | `src/kanren/` | Logic engine (unification, fact database, taint, cross-lang) | `src/kanren/core.rs` | Term, substitution, unification, FactDB, forward chaining | `src/kanren/taint.rs` | Source→sink tracking (user input, network, deserialization) diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc index c1e8c652..25b024ec 100644 --- a/PROOF-NEEDS.adoc +++ b/PROOF-NEEDS.adoc @@ -27,27 +27,29 @@ compiles at `f2a6a70eaec0cb02331e3264e05f185b5faab0f7`. The only `unsafe` is in `examples/vulnerable_program.rs`, a deliberately buggy program that exists to be scanned. -== Receipt for the Idris2 modules - -* *Checker:* Idris2 0.7.0, the version `proven-tests.yml` pins, built from - tag `v0.7.0` (`27780073c8631826d846499840b3857d9b9a4fd5`) on Chez Scheme - 9.5.8. -* *Source:* `src/abi/*.idr` at - `3dc4728762f37c1e5bebdb988783c7683c50fb55`. -* *Invocation:* the modules are named `PanicAttack.ABI.` but live in - `src/abi/`, so `idris2 --check src/abi/.idr` fails on a module-name - mismatch from any directory. Each was checked from a tree that places - `src/abi/.idr` at `PanicAttack/ABI/.idr`, with - `idris2 --check PanicAttack/ABI/.idr`. A pass is exit 0 *and* no - `Error:` line, because `idris2 --check` can exit 0 while printing an - error. -* *Result:* all five modules pass. Every module sets `%default total` and - uses no `believe_me`, `assert_total`, `postulate` or holes. -* *Negative controls:* a planted false lemma and a planted non-terminating - definition in `Stripping.idr` were both rejected, so the check can fail. -* *Gate:* no CI job runs this check. That obligation is `OPEN` below. Until - it closes, the statuses here rest on this one local run, and any change - to `src/abi/` invalidates them. +== How the Idris2 modules are checked + +The modules live at `src/abi/PanicAttack/ABI/.idr`, so each path matches +its module name, and `src/abi/panic-attack-abi.ipkg` lists them all. + +* *Gate:* the `abi-proofs` job in `.github/workflows/proven-tests.yml` runs + on every pull request and on pushes to `main`: + `idris2 --typecheck src/abi/panic-attack-abi.ipkg`. A pass is exit 0 + *and* no `Error:` line, because `idris2 --check` can exit 0 while printing + an error. Its toolchain is Idris2 0.7.0 from the same pinned installer and + cache as the framework job. Each green run of that job is the current + receipt; a failing run revokes the statuses below. +* *Negative controls* for the package route: a planted false lemma and a + planted missing import each make it exit non-zero with an `Error:` line. +* *Hygiene:* every module sets `%default total` and uses no `believe_me`, + `assert_total`, `postulate` or holes. + +First receipt, before the gate existed: Idris2 0.7.0, built from tag +`v0.7.0` (`27780073c8631826d846499840b3857d9b9a4fd5`) on Chez Scheme 9.5.8, +over `src/abi/*.idr` at `3dc4728762f37c1e5bebdb988783c7683c50fb55`. Each +module was checked from a module-shaped copy of the tree. All five passed, +and a planted false lemma and a planted non-terminating definition in +`Stripping.idr` were both rejected. == Ledger @@ -57,14 +59,14 @@ exists to be scanned. |Severity order: `Low < Medium < High < Critical` is a total order; `sevMax` is an upper bound; the numeric encoding is monotone (PA2) -|`src/abi/ClassificationSoundness.idr` +|`src/abi/PanicAttack/ABI/ClassificationSoundness.idr` |`PROVEN` (model) |The model's `Severity` matches the variant names and order of `src/types.rs`; that correspondence is `ASSUMED` (a hand transcription). The Rust order itself comes from `#[derive(PartialOrd, Ord)]`. |Line-comment stripping is idempotent: `strip (strip s) = strip s` -|`src/abi/Stripping.idr` +|`src/abi/PanicAttack/ABI/Stripping.idr` |`PROVEN` (model) |Did not compile on `main` before `3dc4728`; repaired there without changing the theorem. The repaired model equals the previous one: @@ -74,7 +76,7 @@ comments and string literals are not modelled. Model to Rust `strip_proof_comments`: `ASSUMED`. |Attestation chain: integrity, authenticity, non-repudiation -|`src/abi/AttestationUnforgeability.idr` +|`src/abi/PanicAttack/ABI/AttestationUnforgeability.idr` |`PROVEN` (model), relative to the `ASSUMED` hypotheses listed here |The module's `parameters` block assumes: @@ -92,7 +94,7 @@ model, not a computational security reduction. Model to |Every language reaches an analyzer; every weak-point category has a detector; cross-language checks run on every file (PA1) -|`src/abi/PatternCompleteness.idr` +|`src/abi/PanicAttack/ABI/PatternCompleteness.idr` |`PROVEN` (model); supports no claim about the Rust code |The theorem is vacuous: `GenericAnalyzer : HasAnalyzer lang` inhabits the witness type for every language, so it holds whatever the dispatch @@ -107,7 +109,7 @@ when `configuration.is_some()`. That model claim is false of the implementation. |Declarations for the ABI-facing types and their C integer encodings -|`src/abi/Types.idr` +|`src/abi/PanicAttack/ABI/Types.idr` |No theorem |Repaired in `3dc4728` so it compiles. It contains no proof and nothing imports it. Drift: its `Severity` is `Info / Warning / Error / Critical` @@ -130,12 +132,6 @@ not establish a faithful hexad-to-octad map. |=== |Obligation |Verifier (§1, §1.2) |Notes -|Gate the Idris2 modules in CI -|CI -|Run the receipt's invocation on every change to `src/abi/`, failing on -any `Error:` line. Moving the files to `src/abi/PanicAttack/ABI/` would -let a plain `idris2 --check` work. - |`strip_proof_comments` is idempotent and preserves positions outside comments and strings |Creusot/Pearlite and Verus diff --git a/PROOF-PROGRAMME.adoc b/PROOF-PROGRAMME.adoc index 7726fb86..9bcb2ce8 100644 --- a/PROOF-PROGRAMME.adoc +++ b/PROOF-PROGRAMME.adoc @@ -14,12 +14,12 @@ ____ [width="100%",cols="34%,33%,33%",options="header",] |=== |ID |File |Mechanises -|*PA1* |`+src/abi/PatternCompleteness.idr+` |Every `+Lang+` constructor +|*PA1* |`+src/abi/PanicAttack/ABI/PatternCompleteness.idr+` |Every `+Lang+` constructor has at least one analyzer; every `+WPCategory+` has at least one detector; cross-language checks apply uniformly. Top theorem: `+completeScanForAll+`. -|*PA2* |`+src/abi/ClassificationSoundness.idr+` |`+Severity+` is totally +|*PA2* |`+src/abi/PanicAttack/ABI/ClassificationSoundness.idr+` |`+Severity+` is totally ordered (`+LTE+`); `+maxSeverity+` is commutative + idempotent; numeric ABI encoding preserves the ordering. |=== @@ -81,7 +81,7 @@ Worked example — *PA004 (UnsafeCode)*: [source,idris] ---- --- src/abi/PA004_UnsafeCode.idr +-- src/abi/PanicAttack/ABI/PA004_UnsafeCode.idr SoundnessPA004 : (file : String) -> (loc : Loc) -> contains (stripStrings file) "unsafe " loc -> isUnsafeBlock (locate file loc) @@ -266,7 +266,7 @@ Recommended order (each row is parallel-iseable; rows are sequenced): |=== |# |Phase |Output |Estimated effort |Risk |1 |*Foundation*: Layer 1.0 (comment/string-strip idempotence + token -preservation) |`+src/abi/Stripping.idr+` + 1 Idris2 module |3–5 days +preservation) |`+src/abi/PanicAttack/ABI/Stripping.idr+` + 1 Idris2 module |3–5 days |low |2 |*Quick wins*: Hexad↔Octad roundtrip proptest + Layer 1 @@ -316,8 +316,8 @@ docs/proof artefacts that don’t touch the hot path. * `+PROOF-NEEDS.md+` — current proof-debt ledger (this document is the long-term plan; that one tracks the immediate next step). -* `+src/abi/PatternCompleteness.idr+` (PA1) -* `+src/abi/ClassificationSoundness.idr+` (PA2) +* `+src/abi/PanicAttack/ABI/PatternCompleteness.idr+` (PA1) +* `+src/abi/PanicAttack/ABI/ClassificationSoundness.idr+` (PA2) * `+hyperpolymath/proven+` — leaf validator library; cross-fit candidates listed above. * ROADMAP.adoc "`Long-Term`" section: "`Formal verification of core diff --git a/src/abi/AttestationUnforgeability.idr b/src/abi/PanicAttack/ABI/AttestationUnforgeability.idr similarity index 100% rename from src/abi/AttestationUnforgeability.idr rename to src/abi/PanicAttack/ABI/AttestationUnforgeability.idr diff --git a/src/abi/ClassificationSoundness.idr b/src/abi/PanicAttack/ABI/ClassificationSoundness.idr similarity index 100% rename from src/abi/ClassificationSoundness.idr rename to src/abi/PanicAttack/ABI/ClassificationSoundness.idr diff --git a/src/abi/PatternCompleteness.idr b/src/abi/PanicAttack/ABI/PatternCompleteness.idr similarity index 100% rename from src/abi/PatternCompleteness.idr rename to src/abi/PanicAttack/ABI/PatternCompleteness.idr diff --git a/src/abi/Stripping.idr b/src/abi/PanicAttack/ABI/Stripping.idr similarity index 100% rename from src/abi/Stripping.idr rename to src/abi/PanicAttack/ABI/Stripping.idr diff --git a/src/abi/Types.idr b/src/abi/PanicAttack/ABI/Types.idr similarity index 100% rename from src/abi/Types.idr rename to src/abi/PanicAttack/ABI/Types.idr diff --git a/src/abi/panic-attack-abi.ipkg b/src/abi/panic-attack-abi.ipkg new file mode 100644 index 00000000..4d874b80 --- /dev/null +++ b/src/abi/panic-attack-abi.ipkg @@ -0,0 +1,15 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- The Idris2 ABI models and proofs. Type-check with: +-- idris2 --typecheck src/abi/panic-attack-abi.ipkg +-- A pass is exit 0 and no `Error:` line in the output. +package panic-attack-abi + +sourcedir = "." + +modules = PanicAttack.ABI.Types + , PanicAttack.ABI.PatternCompleteness + , PanicAttack.ABI.ClassificationSoundness + , PanicAttack.ABI.Stripping + , PanicAttack.ABI.AttestationUnforgeability From 8427d2b77721c4c21185f80a4f429dcad6842d1d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 14:47:52 +0000 Subject: [PATCH 4/7] feat(assail): route languages through a tested table; retire the vacuous PA1 PA1 was an Idris2 model of the analyzer dispatch whose theorem could not fail: `GenericAnalyzer : HasAnalyzer lang` inhabited its witness for every language. It was also stale (50 of 52 languages) and partly false (it said cross-language checks always run; they are skipped for configuration). The routing is now real code with claims that can fail: - src/assail/routing.rs: `route(Language) -> Route`, `Route::analyzer()`, and `runs_cross_language(is_configuration)`. `analyze_inner` matches on `route(file_lang)` and calls `runs_cross_language`. Only the arm heads changed; every arm body is byte-identical. `route` and the dispatch are exhaustive with no wildcard (Chapel, the one language without a dedicated analyzer, is routed to Generic explicitly). - src/types.rs: `Language::ALL` (52 variants), kept complete by an exhaustive `ordinal` match test, following WeakPointCategory::ALL. - Tests, exhaustive over Language::ALL: (a) every language analyzer in analyzer.rs is reached; (b) no language falls back to analyze_generic while a dedicated analyzer for it exists; (c) cross-language checks run exactly off configuration, and on scripts embedded in it (Justfile + Lua scan, end to end); (d) README's language counts equal the supported count. Each was seen to fail on a planted fault. - README: 49 -> 51 languages (badge, capabilities, summary); (d) caught the drift. C and Php were added after the count was written. - PatternCompleteness.idr removed from src/abi and the ipkg; PROOF-NEEDS, EXPLAINME, PROOF-PROGRAMME and the 0-AI-MANIFEST entry updated. PA1's status is TESTED; the Creusot/Pearlite and Verus proof is OPEN. Found while testing (c), recorded as an open obligation, not fixed here: the cross-language check strips `//` comments before matching, which also cuts unquoted `http://` URLs (shell, Justfile recipes). Checked: cargo fmt; clippy -D warnings with all and default features; cargo test --all-features (789 passed, 0 failed); the Idris2 package type-checks (4 modules); panic-attack's self-scan reports nothing new. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- 0-AI-MANIFEST.a2ml | 2 - EXPLAINME.adoc | 2 +- PROOF-NEEDS.adoc | 58 +-- PROOF-PROGRAMME.adoc | 11 +- README.adoc | 6 +- .../PanicAttack/ABI/PatternCompleteness.idr | 259 ------------- src/abi/panic-attack-abi.ipkg | 1 - src/assail/analyzer.rs | 87 ++--- src/assail/mod.rs | 1 + src/assail/routing.rs | 350 ++++++++++++++++++ src/types.rs | 134 +++++++ 11 files changed, 570 insertions(+), 341 deletions(-) delete mode 100644 src/abi/PanicAttack/ABI/PatternCompleteness.idr create mode 100644 src/assail/routing.rs diff --git a/0-AI-MANIFEST.a2ml b/0-AI-MANIFEST.a2ml index 116c3de0..b4225e63 100644 --- a/0-AI-MANIFEST.a2ml +++ b/0-AI-MANIFEST.a2ml @@ -37,8 +37,6 @@ (jit-context "src/jit_context.rs" "JIT-framework classifier: Cranelift / Llvm / Wasm / Javascript / None")) (proof-modules - (pa1 "src/abi/PatternCompleteness.idr" - "Pattern detection completeness — every Lang / WPCategory has a detector") (pa2 "src/abi/ClassificationSoundness.idr" "Classification soundness — Severity total order + maxSeverity commutativity") (layer-1-0 "src/abi/Stripping.idr" diff --git a/EXPLAINME.adoc b/EXPLAINME.adoc index f2ea5532..904514d5 100644 --- a/EXPLAINME.adoc +++ b/EXPLAINME.adoc @@ -52,7 +52,7 @@ The README makes claims. This file backs them up. | `src/comment_marker.rs` | Inline `// panic-attack: accepted [- reason]` suppression marker — `//` / `#` / `--` / `;` / `%` leaders, string-literal aware | `src/ffi_kind.rs` | UnsafeFFI (PA013) subtyping: BuildSystem (`build.zig` / `build.rs` — audit-accepted), RuntimeAbi (`bindings/` / `ffi/` / `sys/` / `cdef.zig`), TestMock (`tests/mocks/` / `_stub`), Unknown | `src/jit_context.rs` | JIT-framework classifier: Cranelift / Llvm / Wasm / Javascript / None; `transmute_targets_fn_ptr` recogniser for fn-ptr type-punning -| `src/abi/PanicAttack/ABI/PatternCompleteness.idr` | PA1 Idris2 model of analyzer dispatch; vacuous as stated (see `PROOF-NEEDS.adoc`) +| `src/assail/routing.rs` | PA1 routing table: which analyzer each language reaches and when cross-language checks run; its claims are tested exhaustively (see `PROOF-NEEDS.adoc`) | `src/abi/PanicAttack/ABI/ClassificationSoundness.idr` | PA2 Idris2 proof — severity total order, `sevMax` upper bounds, monotone encoding | `src/abi/PanicAttack/ABI/Stripping.idr` | Layer 1.0 — Idris2 model of line-comment stripping, proved idempotent (`stripLineCommentsIdempotent`) | `src/kanren/` | Logic engine (unification, fact database, taint, cross-lang) diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc index 25b024ec..4d74d288 100644 --- a/PROOF-NEEDS.adoc +++ b/PROOF-NEEDS.adoc @@ -92,21 +92,29 @@ or signature scheme. So these are theorems of a symbolic (Dolev-Yao style) model, not a computational security reduction. Model to `src/attestation/`: `ASSUMED`. A computational proof is not claimed. -|Every language reaches an analyzer; every weak-point category has a -detector; cross-language checks run on every file (PA1) -|`src/abi/PanicAttack/ABI/PatternCompleteness.idr` -|`PROVEN` (model); supports no claim about the Rust code -|The theorem is vacuous: `GenericAnalyzer : HasAnalyzer lang` inhabits -the witness type for every language, so it holds whatever the dispatch -does. The guarantee it was meant to give already holds in Rust: -`match file_lang` in `src/assail/analyzer.rs` ends in -`_ => analyze_generic`, and `rustc` checks the match is exhaustive. - -The model has also drifted. Its `Lang` has 50 constructors and -`src/types.rs` has 52; `C` and `Php` are missing. `crossLangAlwaysApplied` -says cross-language checks run on every file, but the Rust code skips them -when `configuration.is_some()`. That model claim is false of the -implementation. +|Analyzer routing (PA1). (a) Every language analyzer in `analyzer.rs` is +reached by some language. (b) No language falls back to the generic +analyzer while a dedicated one exists for it. (c) Cross-language checks run +exactly on non-configuration content, and on scripts embedded in +configuration. (d) The README's language counts equal the languages the +table supports. +|`src/assail/routing.rs`: `route`, `Route::analyzer`, `runs_cross_language` +and their tests +|`TESTED` +|The dispatch in `analyze_inner` matches on `route(file_lang)`, so the +table is the code that runs, not a model of it. `route` and the dispatch +are exhaustive matches with no wildcard, so `rustc` makes every language +and every route explicit. The tests run over all 52 `Language` variants +(`Language::ALL`, kept complete by an exhaustive `ordinal` match). (a) and +(b) compare the table with the analyzer methods found in the source. (c) +scans a Justfile and a Lua file end to end. Each test was seen to fail on +a planted fault: an unrouted analyzer, Java sent to the generic analyzer, +cross-language checks forced on, and the README's stale count of 49. + +This replaces the Idris2 `PatternCompleteness.idr`, which was vacuous +(`GenericAnalyzer` inhabited its witness for every language), stale (50 of +52 languages) and partly false (it said cross-language checks always +run). It is retired. |Declarations for the ABI-facing types and their C integer encodings |`src/abi/PanicAttack/ABI/Types.idr` @@ -152,10 +160,18 @@ gap. fixed point) is theory and belongs in Agda with Rocq and Lean rechecks. Its realisation in `src/kanren/` is a Rust obligation. -|Replace or retire PA1 -|Creusot/Pearlite and Verus, or retire -|A non-vacuous statement would be, for example, that each language with -a dedicated analyzer is routed to it. If that is not wanted, retire the -module, because `rustc`'s exhaustiveness check already gives the current -guarantee. +|Prove PA1 (a) to (c) on `route` and `runs_cross_language` +|Creusot/Pearlite and Verus +|Pearlite contracts on the two functions, proved by both verifiers. The +tests above are exhaustive over a finite enum, but they are tests, and (a) +reads the source with a pattern match. (d) is a documentation check and +stays a test. + +|Unquoted `http://` URLs are missed by the cross-language check +|Fix first, then test +|`analyze_cross_language` strips C-style `//` comments from every file +before matching, which also cuts `curl http://host` in shell. A quoted +URL is found; an unquoted one in a `.sh` file or a Justfile recipe is not. +This is a recall gap in the InsecureProtocol detector, found while testing +PA1 (c). |=== diff --git a/PROOF-PROGRAMME.adoc b/PROOF-PROGRAMME.adoc index 9bcb2ce8..e1dbe672 100644 --- a/PROOF-PROGRAMME.adoc +++ b/PROOF-PROGRAMME.adoc @@ -14,10 +14,11 @@ ____ [width="100%",cols="34%,33%,33%",options="header",] |=== |ID |File |Mechanises -|*PA1* |`+src/abi/PanicAttack/ABI/PatternCompleteness.idr+` |Every `+Lang+` constructor -has at least one analyzer; every `+WPCategory+` has at least one -detector; cross-language checks apply uniformly. Top theorem: -`+completeScanForAll+`. +|*PA1* |`+src/assail/routing.rs+` |The routing table the dispatch uses: every +language analyzer is reached, no language falls back to the generic +analyzer while a dedicated one exists, cross-language checks run exactly +off configuration, and the README language counts match. Tested +exhaustively; the earlier Idris2 model was vacuous and is retired. |*PA2* |`+src/abi/PanicAttack/ABI/ClassificationSoundness.idr+` |`+Severity+` is totally ordered (`+LTE+`); `+maxSeverity+` is commutative + idempotent; numeric @@ -316,7 +317,7 @@ docs/proof artefacts that don’t touch the hot path. * `+PROOF-NEEDS.md+` — current proof-debt ledger (this document is the long-term plan; that one tracks the immediate next step). -* `+src/abi/PanicAttack/ABI/PatternCompleteness.idr+` (PA1) +* `+src/assail/routing.rs+` (PA1) * `+src/abi/PanicAttack/ABI/ClassificationSoundness.idr+` (PA2) * `+hyperpolymath/proven+` — leaf validator library; cross-fit candidates listed above. diff --git a/README.adoc b/README.adoc index 2bcedffc..eaa139c2 100644 --- a/README.adoc +++ b/README.adoc @@ -12,7 +12,7 @@ image:https://api.thegreenwebfoundation.org/greencheckimage/github.com[Green Web image:https://img.shields.io/badge/status-active-green[Status] image:https://img.shields.io/badge/domain-security--analysis-blue[Domain] image:https://img.shields.io/badge/tests-897%20passing-brightgreen[Tests] -image:https://img.shields.io/badge/languages-49-blue[Languages] +image:https://img.shields.io/badge/languages-51-blue[Languages] **panic-attack** is a multi-language security analysis and stress-testing system. @@ -69,7 +69,7 @@ panic-attack exists to address this by combining: panic-attack provides: -* **49-language static analysis** across multiple families +* **51-language static analysis** across multiple families * **Weak point detection** (30 canonical categories; see the PA rule-ID table below) * **Attack simulation (6 axes)**: CPU, memory, disk, network, concurrency, time * **miniKanren logic engine** for taint analysis and cross-language reasoning @@ -235,7 +235,7 @@ Current state: **v2.5.0** * v2.5.5 cohort landed 2026-06-02: context-aware FP suppression via `test_context` / `comment_marker` / `ffi_kind` / `jit_context` modules — `// panic-attack: accepted` inline markers, automatic PanicPath suppression in test-only code, build.zig/build.rs auto-accept, Cranelift/LLVM/Wasm/JS JIT detection. See `PROOF-PROGRAMME.md` for the formal soundness landscape * 0 warnings * 38 CLI subcommands -* 49 supported languages (30 canonical weak-point categories PA001–PA029; `PA001b` is a distinct stable rule ID grouped with PA001 under one allocation semantic class for cross-tool de-duplication) +* 51 supported languages (30 canonical weak-point categories PA001–PA029; `PA001b` is a distinct stable rule ID grouped with PA001 under one allocation semantic class for cross-tool de-duplication) See link:ROADMAP.adoc[ROADMAP.adoc] for full capability breakdown and milestones. diff --git a/src/abi/PanicAttack/ABI/PatternCompleteness.idr b/src/abi/PanicAttack/ABI/PatternCompleteness.idr deleted file mode 100644 index 52955752..00000000 --- a/src/abi/PanicAttack/ABI/PatternCompleteness.idr +++ /dev/null @@ -1,259 +0,0 @@ --- SPDX-License-Identifier: MPL-2.0 --- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell --- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) - -||| Pattern Matching Completeness Proofs -||| -||| Proves that every language in the scanner's catalogue has an -||| associated analyzer, and every weak point category in the catalogue -||| has at least one detection rule. This eliminates false negatives -||| caused by missing dispatch arms. -||| -||| Design: We model the Language and WeakPointCategory enumerations -||| as inductive types and prove that the dispatch function (modelled -||| as `analyzerFor` / `detectorsFor`) covers every constructor. -||| The proof is structural induction on the enumeration -- Idris2's -||| totality checker verifies that every case is handled. -module PanicAttack.ABI.PatternCompleteness - -%default total - --- ═══════════════════════════════════════════════════════════════════════ --- Language enumeration (mirrors src/types.rs Language enum, 49 variants) --- ═══════════════════════════════════════════════════════════════════════ - -||| All 49 programming languages supported by the scanner. -||| This MUST stay in sync with src/types.rs Language enum. -||| Note: Cpp is the C/C++ unified analyzer (analyze_c_cpp dispatches -||| on .c / .cpp / .h / .hpp / .cc / .hh — there is no separate C -||| constructor in the Rust enum). -public export -data Lang - = Rust | Cpp | Go | Java | Python | JavaScript | Ruby - -- BEAM family - | Elixir | Erlang | Gleam - -- ML family - | ReScript | OCaml | StandardML - -- Lisp family - | Scheme | Racket - -- Functional - | Haskell | PureScript - -- Proof assistants - | Idris | Lean | Agda | Isabelle | Coq - -- Logic programming - | Prolog | Logtalk | Datalog - -- Systems languages - | Zig | Ada | Odin | Nim | Pony | DLang - -- Config languages - | Nickel | Nix - -- Scripting / data - | Shell | Julia | Lua - -- HPC / parallel - | Chapel - -- Nextgen custom DSLs - | WokeLang | Eclexia | MyLang | JuliaTheViper | Oblibeny - | Anvomidav | AffineScript | Ephapax | BetLang | ErrorLang - | VCL | FBQL - -- Catch-all - | Unknown - --- ═══════════════════════════════════════════════════════════════════════ --- Analyzer dispatch witness --- ═══════════════════════════════════════════════════════════════════════ - -||| Witness that an analyzer function exists for a given language. -||| Each constructor corresponds to a dispatch arm in analyzer.rs. -public export -data HasAnalyzer : Lang -> Type where - ||| Language-specific analyzer (e.g., analyze_rust, analyze_c_cpp) - SpecificAnalyzer : HasAnalyzer lang - ||| Generic fallback analyzer (analyze_generic) - GenericAnalyzer : HasAnalyzer lang - -||| Every language in the enumeration has an analyzer. -||| This function is total: Idris2 verifies exhaustive coverage. -||| The dispatch mirrors src/assail/analyzer.rs analyze_inner(). -public export -analyzerFor : (lang : Lang) -> HasAnalyzer lang -analyzerFor Rust = SpecificAnalyzer -analyzerFor Cpp = SpecificAnalyzer -analyzerFor Go = SpecificAnalyzer -analyzerFor Java = SpecificAnalyzer -analyzerFor Python = SpecificAnalyzer -analyzerFor JavaScript = SpecificAnalyzer -analyzerFor Ruby = SpecificAnalyzer -analyzerFor Elixir = SpecificAnalyzer -analyzerFor Erlang = SpecificAnalyzer -analyzerFor Gleam = SpecificAnalyzer -analyzerFor ReScript = SpecificAnalyzer -analyzerFor OCaml = SpecificAnalyzer -analyzerFor StandardML = SpecificAnalyzer -analyzerFor Scheme = SpecificAnalyzer -analyzerFor Racket = SpecificAnalyzer -analyzerFor Haskell = SpecificAnalyzer -analyzerFor PureScript = SpecificAnalyzer -analyzerFor Idris = SpecificAnalyzer -analyzerFor Lean = SpecificAnalyzer -analyzerFor Agda = SpecificAnalyzer -analyzerFor Isabelle = SpecificAnalyzer -analyzerFor Coq = SpecificAnalyzer -analyzerFor Prolog = SpecificAnalyzer -analyzerFor Logtalk = SpecificAnalyzer -analyzerFor Datalog = SpecificAnalyzer -analyzerFor Zig = SpecificAnalyzer -analyzerFor Ada = SpecificAnalyzer -analyzerFor Odin = SpecificAnalyzer -analyzerFor Nim = SpecificAnalyzer -analyzerFor Pony = SpecificAnalyzer -analyzerFor DLang = SpecificAnalyzer -analyzerFor Nickel = SpecificAnalyzer -analyzerFor Nix = SpecificAnalyzer -analyzerFor Shell = SpecificAnalyzer -analyzerFor Julia = SpecificAnalyzer -analyzerFor Lua = SpecificAnalyzer -analyzerFor Chapel = SpecificAnalyzer -analyzerFor WokeLang = SpecificAnalyzer -analyzerFor Eclexia = SpecificAnalyzer -analyzerFor MyLang = SpecificAnalyzer -analyzerFor JuliaTheViper = SpecificAnalyzer -analyzerFor Oblibeny = SpecificAnalyzer -analyzerFor Anvomidav = SpecificAnalyzer -analyzerFor AffineScript = SpecificAnalyzer -analyzerFor Ephapax = SpecificAnalyzer -analyzerFor BetLang = SpecificAnalyzer -analyzerFor ErrorLang = SpecificAnalyzer -analyzerFor VCL = SpecificAnalyzer -analyzerFor FBQL = SpecificAnalyzer -analyzerFor Unknown = GenericAnalyzer - -||| Proof: for ALL languages, an analyzer exists. -||| This is the top-level completeness theorem. -public export -allLanguagesHaveAnalyzers : (lang : Lang) -> HasAnalyzer lang -allLanguagesHaveAnalyzers = analyzerFor - --- ═══════════════════════════════════════════════════════════════════════ --- Cross-language security check proof --- ═══════════════════════════════════════════════════════════════════════ - -||| Witness that cross-language checks are always applied. -||| In analyzer.rs, analyze_cross_language() runs on ALL files -||| regardless of language. This type encodes that invariant. -public export -data CrossLangChecked : Lang -> Type where - MkCrossLangChecked : CrossLangChecked lang - -||| Every language receives cross-language security checks. -||| This is trivially total because the check is unconditional. -public export -crossLangAlwaysApplied : (lang : Lang) -> CrossLangChecked lang -crossLangAlwaysApplied _ = MkCrossLangChecked - --- ═══════════════════════════════════════════════════════════════════════ --- WeakPointCategory enumeration (mirrors src/types.rs, 25 categories) --- ═══════════════════════════════════════════════════════════════════════ - -||| All 25 weak point categories detectable by the scanner. -public export -data WPCategory - = UncheckedAllocation - | UnboundedLoop - | BlockingIO - | UnsafeCode - | PanicPath - | RaceCondition - | DeadlockPotential - | ResourceLeak - | CommandInjection - | UnsafeDeserialization - | DynamicCodeExecution - | UnsafeFFI - | AtomExhaustion - | InsecureProtocol - | ExcessivePermissions - | PathTraversal - | HardcodedSecret - | UncheckedError - | InfiniteRecursion - | UnsafeTypeCoercion - -- PA021 ProofDrift: banned proof escape hatches or mirror files - -- substituting assertions for proofs. Detected in .idr/.lean/.agda/.thy/.v - -- and Julia mirror files. - | ProofDrift - -- PA022 CryptoMisuse: weak hash (MD5/SHA-1) in security context, - -- constant-time comparison violations, key/nonce reuse. - -- Detected in Rust, Python, JavaScript, Go, Elixir. - | CryptoMisuse - -- PA023 SupplyChain: unpinned deps, absent lock files, unverified - -- manifests. Cargo git deps without rev=, absent Cargo.lock, Julia - -- Manifest.toml without hash, flake.nix without narHash, deno.json - -- unpinned specifiers. Detected in Rust, Julia, Nix, JavaScript. - | SupplyChain - -- PA024 InputBoundary: unchecked CBOR/MessagePack deserialization - -- (serde_cbor, ciborium, rmp_serde in Rust), JSON.parse without - -- try/catch (JavaScript), JSON3.read without error handling (Julia). - | InputBoundary - -- PA025 MutationGap: test suites with no mutation-test tooling - -- (no cargo-mutants in Rust), no property-based testing in Elixir - -- (ExUnitProperties/StreamData absent), or Julia @testset blocks - -- with only type-check assertions and no value diversity. - | MutationGap - -||| Witness that a detection rule exists for a weak point category. -||| Each variant names the language(s) whose analyzer detects it. -public export -data HasDetector : WPCategory -> Type where - ||| Detected by one or more language-specific analyzers - DetectedBy : (langs : List Lang) -> HasDetector cat - -||| Every weak point category has at least one detector. -||| Total: Idris2 verifies all 25 constructors are covered. -||| The list of detecting languages mirrors the actual pattern -||| matching code in analyzer.rs. -public export -detectorsFor : (cat : WPCategory) -> HasDetector cat -detectorsFor UncheckedAllocation = DetectedBy [Cpp] -detectorsFor UnboundedLoop = DetectedBy [Rust, Cpp, Go, Python, JavaScript] -detectorsFor BlockingIO = DetectedBy [Rust, Go, Python, JavaScript] -detectorsFor UnsafeCode = DetectedBy [Rust, Cpp, Zig, Nim, DLang] -detectorsFor PanicPath = DetectedBy [Rust, Go, Haskell] -detectorsFor RaceCondition = DetectedBy [Rust, Cpp, Go] -detectorsFor DeadlockPotential = DetectedBy [Rust, Cpp, Go] -detectorsFor ResourceLeak = DetectedBy [Rust, Cpp] -detectorsFor CommandInjection = DetectedBy [Python, Ruby, JavaScript, Shell, Elixir, Erlang] -detectorsFor UnsafeDeserialization = DetectedBy [Python, Ruby, JavaScript, Java] -detectorsFor DynamicCodeExecution = DetectedBy [Python, JavaScript, Ruby, Elixir, Shell] -detectorsFor UnsafeFFI = DetectedBy [Elixir, Erlang, Haskell, Pony, OCaml, Zig] -detectorsFor AtomExhaustion = DetectedBy [Elixir, Erlang] -detectorsFor InsecureProtocol = DetectedBy [Rust, Cpp, Go, Python, JavaScript, Ruby] -detectorsFor ExcessivePermissions = DetectedBy [Shell] -detectorsFor PathTraversal = DetectedBy [Python, JavaScript, Ruby, Go, Java] -detectorsFor HardcodedSecret = DetectedBy [Rust, Cpp, Go, Python, JavaScript, Ruby] -detectorsFor UncheckedError = DetectedBy [Go, Rust, Cpp] -detectorsFor InfiniteRecursion = DetectedBy [Haskell, PureScript, Scheme, Racket] -detectorsFor UnsafeTypeCoercion = DetectedBy [OCaml, Haskell, DLang, Nim] -detectorsFor ProofDrift = DetectedBy [Idris, Lean, Agda, Isabelle, Coq, Julia] -detectorsFor CryptoMisuse = DetectedBy [Rust, Python, JavaScript, Go, Elixir] -detectorsFor SupplyChain = DetectedBy [Rust, Julia, Nix, JavaScript] -detectorsFor InputBoundary = DetectedBy [Rust, JavaScript, Julia] -detectorsFor MutationGap = DetectedBy [Rust, Julia, Elixir] - -||| Proof: every weak point category has at least one detector. -public export -allCategoriesDetected : (cat : WPCategory) -> HasDetector cat -allCategoriesDetected = detectorsFor - --- ═══════════════════════════════════════════════════════════════════════ --- Combined completeness theorem --- ═══════════════════════════════════════════════════════════════════════ - -||| A complete scan covers both language-specific analysis AND -||| cross-language security checks for any given language. -public export -data CompleteScan : Lang -> Type where - MkCompleteScan : HasAnalyzer lang -> CrossLangChecked lang -> CompleteScan lang - -||| Every language receives a complete scan. -public export -completeScanForAll : (lang : Lang) -> CompleteScan lang -completeScanForAll lang = MkCompleteScan (analyzerFor lang) (crossLangAlwaysApplied lang) diff --git a/src/abi/panic-attack-abi.ipkg b/src/abi/panic-attack-abi.ipkg index 4d874b80..1b3ab731 100644 --- a/src/abi/panic-attack-abi.ipkg +++ b/src/abi/panic-attack-abi.ipkg @@ -9,7 +9,6 @@ package panic-attack-abi sourcedir = "." modules = PanicAttack.ABI.Types - , PanicAttack.ABI.PatternCompleteness , PanicAttack.ABI.ClassificationSoundness , PanicAttack.ABI.Stripping , PanicAttack.ABI.AttestationUnforgeability diff --git a/src/assail/analyzer.rs b/src/assail/analyzer.rs index fb0af3a8..2dd13410 100644 --- a/src/assail/analyzer.rs +++ b/src/assail/analyzer.rs @@ -523,8 +523,8 @@ impl Analyzer { acc.record_file(&rel_path, &raw_bytes, &format!("{:?}", file_lang)); } - match file_lang { - Language::Unknown => { + match super::routing::route(file_lang) { + super::routing::Route::InputAdapter => { let Some(format) = configuration else { coverage.mark( file, @@ -589,7 +589,7 @@ impl Analyzer { } } } - Language::Php => match super::php::analyze(&content, &rel_path) { + super::routing::Route::Php => match super::php::analyze(&content, &rel_path) { Ok(findings) => file_weak_points.extend(findings), Err(error) => { coverage.mark( @@ -601,10 +601,10 @@ impl Analyzer { continue; } }, - Language::Rust => { + super::routing::Route::Rust => { self.analyze_rust(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::C | Language::Cpp => { + super::routing::Route::CCpp => { self.analyze_c_cpp( &content, &mut file_stats, @@ -612,10 +612,10 @@ impl Analyzer { &rel_path, )?; } - Language::Go => { + super::routing::Route::Go => { self.analyze_go(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Python => { + super::routing::Route::Python => { self.analyze_python( &content, &mut file_stats, @@ -623,7 +623,7 @@ impl Analyzer { &rel_path, )?; } - Language::JavaScript => { + super::routing::Route::JavaScript => { self.analyze_javascript( &content, &mut file_stats, @@ -631,11 +631,11 @@ impl Analyzer { &rel_path, )?; } - Language::Ruby => { + super::routing::Route::Ruby => { self.analyze_ruby(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } // BEAM family - Language::Elixir => { + super::routing::Route::Elixir => { self.analyze_elixir( &content, &mut file_stats, @@ -643,7 +643,7 @@ impl Analyzer { &rel_path, )?; } - Language::Erlang => { + super::routing::Route::Erlang => { self.analyze_erlang( &content, &mut file_stats, @@ -651,7 +651,7 @@ impl Analyzer { &rel_path, )?; } - Language::Gleam => { + super::routing::Route::Gleam => { self.analyze_gleam( &content, &mut file_stats, @@ -660,7 +660,7 @@ impl Analyzer { )?; } // ML family - Language::ReScript => { + super::routing::Route::ReScript => { record_migration_file(file_stats.total_lines); self.analyze_rescript( &content, @@ -669,7 +669,7 @@ impl Analyzer { &rel_path, )?; } - Language::OCaml => { + super::routing::Route::OCaml => { self.analyze_ocaml( &content, &mut file_stats, @@ -677,15 +677,15 @@ impl Analyzer { &rel_path, )?; } - Language::StandardML => { + super::routing::Route::StandardML => { self.analyze_sml(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } // Lisp family - Language::Scheme | Language::Racket => { + super::routing::Route::Lisp => { self.analyze_lisp(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } // Functional - Language::Haskell => { + super::routing::Route::Haskell => { self.analyze_haskell( &content, &mut file_stats, @@ -693,7 +693,7 @@ impl Analyzer { &rel_path, )?; } - Language::PureScript => { + super::routing::Route::PureScript => { self.analyze_purescript( &content, &mut file_stats, @@ -702,7 +702,7 @@ impl Analyzer { )?; } // Proof assistants - Language::Idris => { + super::routing::Route::Idris => { self.analyze_idris( &content, &mut file_stats, @@ -710,13 +710,13 @@ impl Analyzer { &rel_path, )?; } - Language::Lean => { + super::routing::Route::Lean => { self.analyze_lean(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Agda => { + super::routing::Route::Agda => { self.analyze_agda(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Isabelle => { + super::routing::Route::Isabelle => { self.analyze_isabelle( &content, &mut file_stats, @@ -724,11 +724,11 @@ impl Analyzer { &rel_path, )?; } - Language::Coq => { + super::routing::Route::Coq => { self.analyze_coq(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } // Logic programming - Language::Prolog | Language::Logtalk | Language::Datalog => { + super::routing::Route::Logic => { self.analyze_logic( &content, &mut file_stats, @@ -737,22 +737,22 @@ impl Analyzer { )?; } // Systems languages - Language::Zig => { + super::routing::Route::Zig => { self.analyze_zig(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Ada => { + super::routing::Route::Ada => { self.analyze_ada(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Odin => { + super::routing::Route::Odin => { self.analyze_odin(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Nim => { + super::routing::Route::Nim => { self.analyze_nim(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::Pony => { + super::routing::Route::Pony => { self.analyze_pony(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - Language::DLang => { + super::routing::Route::DLang => { self.analyze_dlang( &content, &mut file_stats, @@ -761,7 +761,7 @@ impl Analyzer { )?; } // Config languages - Language::Nickel | Language::Nix => { + super::routing::Route::Config => { self.analyze_config( &content, &mut file_stats, @@ -770,7 +770,7 @@ impl Analyzer { )?; } // Scripting - Language::Shell => { + super::routing::Route::Shell => { self.analyze_shell( &content, &mut file_stats, @@ -778,7 +778,7 @@ impl Analyzer { &rel_path, )?; } - Language::Julia => { + super::routing::Route::Julia => { self.analyze_julia( &content, &mut file_stats, @@ -786,22 +786,11 @@ impl Analyzer { &rel_path, )?; } - Language::Lua => { + super::routing::Route::Lua => { self.analyze_lua(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } // Nextgen DSLs - shared analyzer - Language::WokeLang - | Language::Eclexia - | Language::MyLang - | Language::JuliaTheViper - | Language::Oblibeny - | Language::Anvomidav - | Language::AffineScript - | Language::Ephapax - | Language::BetLang - | Language::ErrorLang - | Language::VCL - | Language::FBQL => { + super::routing::Route::NextgenDsl => { self.analyze_nextgen_dsl( &content, &mut file_stats, @@ -809,10 +798,10 @@ impl Analyzer { &rel_path, )?; } - Language::Java => { + super::routing::Route::Java => { self.analyze_java(&content, &mut file_stats, &mut file_weak_points, &rel_path)?; } - _ => { + super::routing::Route::Generic => { self.analyze_generic(&content, &mut file_stats, &rel_path)?; } } @@ -820,7 +809,7 @@ impl Analyzer { // Structured configuration uses parsed keys and values; treating // comments or schema identifiers as executable source creates false // findings. Source-language adapters retain their existing checks. - if configuration.is_none() { + if super::routing::runs_cross_language(configuration.is_some()) { self.analyze_cross_language(&content, &mut file_weak_points, &rel_path)?; } diff --git a/src/assail/mod.rs b/src/assail/mod.rs index 3a628465..3d21ebb3 100644 --- a/src/assail/mod.rs +++ b/src/assail/mod.rs @@ -14,6 +14,7 @@ mod forth; mod input_adapters; pub mod patterns; pub mod php; +mod routing; mod templates; use crate::kanren::core::{FactDB, LogicEngine}; diff --git a/src/assail/routing.rs b/src/assail/routing.rs new file mode 100644 index 00000000..aa19d80d --- /dev/null +++ b/src/assail/routing.rs @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! Which analyzer each language is sent to, and when cross-language checks +//! run (PA1). +//! +//! `analyze_inner` dispatches on [`route`] instead of matching on the +//! language directly, so the table here is the dispatch, not a copy of it. +//! Both `match`es below are exhaustive with no wildcard: a new `Language` +//! fails to compile until it is given a route, and a new `Route` fails to +//! compile until it is given an analyzer. +//! +//! The claims about the table are tested exhaustively in this module's +//! tests (`TESTED` in `PROOF-NEEDS.adoc`; the Creusot/Pearlite and Verus +//! proofs remain open). + +use crate::types::Language; + +/// The analyzer a file of a given language is handed to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum Route { + /// No source language: a registered configuration or build-input + /// adapter handles the file, if one matches. + InputAdapter, + Php, + Rust, + CCpp, + Go, + Python, + JavaScript, + Ruby, + Elixir, + Erlang, + Gleam, + ReScript, + OCaml, + StandardML, + Lisp, + Haskell, + PureScript, + Idris, + Lean, + Agda, + Isabelle, + Coq, + Logic, + Zig, + Ada, + Odin, + Nim, + Pony, + DLang, + Config, + Shell, + Julia, + Lua, + NextgenDsl, + Java, + /// The language-neutral fallback, for languages with no dedicated + /// analyzer. + Generic, +} + +/// The analyzer for `lang`. +pub(crate) fn route(lang: Language) -> Route { + use Language as L; + match lang { + L::Unknown => Route::InputAdapter, + L::Php => Route::Php, + L::Rust => Route::Rust, + L::C | L::Cpp => Route::CCpp, + L::Go => Route::Go, + L::Python => Route::Python, + L::JavaScript => Route::JavaScript, + L::Ruby => Route::Ruby, + L::Elixir => Route::Elixir, + L::Erlang => Route::Erlang, + L::Gleam => Route::Gleam, + L::ReScript => Route::ReScript, + L::OCaml => Route::OCaml, + L::StandardML => Route::StandardML, + L::Scheme | L::Racket => Route::Lisp, + L::Haskell => Route::Haskell, + L::PureScript => Route::PureScript, + L::Idris => Route::Idris, + L::Lean => Route::Lean, + L::Agda => Route::Agda, + L::Isabelle => Route::Isabelle, + L::Coq => Route::Coq, + L::Prolog | L::Logtalk | L::Datalog => Route::Logic, + L::Zig => Route::Zig, + L::Ada => Route::Ada, + L::Odin => Route::Odin, + L::Nim => Route::Nim, + L::Pony => Route::Pony, + L::DLang => Route::DLang, + L::Nickel | L::Nix => Route::Config, + L::Shell => Route::Shell, + L::Julia => Route::Julia, + L::Lua => Route::Lua, + L::WokeLang + | L::Eclexia + | L::MyLang + | L::JuliaTheViper + | L::Oblibeny + | L::Anvomidav + | L::AffineScript + | L::Ephapax + | L::BetLang + | L::ErrorLang + | L::VCL + | L::FBQL => Route::NextgenDsl, + L::Java => Route::Java, + L::Chapel => Route::Generic, + } +} + +impl Route { + /// The function that `analyze_inner` calls for this route. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn analyzer(self) -> &'static str { + match self { + Route::InputAdapter => "input_adapters::Adapter::analyze", + Route::Php => "php::analyze", + Route::Rust => "analyze_rust", + Route::CCpp => "analyze_c_cpp", + Route::Go => "analyze_go", + Route::Python => "analyze_python", + Route::JavaScript => "analyze_javascript", + Route::Ruby => "analyze_ruby", + Route::Elixir => "analyze_elixir", + Route::Erlang => "analyze_erlang", + Route::Gleam => "analyze_gleam", + Route::ReScript => "analyze_rescript", + Route::OCaml => "analyze_ocaml", + Route::StandardML => "analyze_sml", + Route::Lisp => "analyze_lisp", + Route::Haskell => "analyze_haskell", + Route::PureScript => "analyze_purescript", + Route::Idris => "analyze_idris", + Route::Lean => "analyze_lean", + Route::Agda => "analyze_agda", + Route::Isabelle => "analyze_isabelle", + Route::Coq => "analyze_coq", + Route::Logic => "analyze_logic", + Route::Zig => "analyze_zig", + Route::Ada => "analyze_ada", + Route::Odin => "analyze_odin", + Route::Nim => "analyze_nim", + Route::Pony => "analyze_pony", + Route::DLang => "analyze_dlang", + Route::Config => "analyze_config", + Route::Shell => "analyze_shell", + Route::Julia => "analyze_julia", + Route::Lua => "analyze_lua", + Route::NextgenDsl => "analyze_nextgen_dsl", + Route::Java => "analyze_java", + Route::Generic => "analyze_generic", + } + } +} + +/// Whether the cross-language checks run over a file's own content. +/// +/// They run on every source file and on no structured configuration file: +/// configuration is analysed as parsed keys and values, and treating its +/// comments or schema identifiers as executable source creates false +/// findings. Scripts embedded in configuration are still checked, each on +/// its own, by the input-adapter route. +pub(crate) fn runs_cross_language(is_configuration: bool) -> bool { + !is_configuration +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::assail::analyzer::Analyzer; + use crate::types::WeakPointCategory; + use std::collections::BTreeSet; + use std::fs; + use tempfile::TempDir; + + /// Language-analyzer methods defined in analyzer.rs: every + /// `fn analyze_(&self, content: &str, ...)`. Read from the source, + /// so a new analyzer is seen without anyone listing it here. + fn analyzer_methods_in_source() -> BTreeSet { + let source = include_str!("analyzer.rs"); + let compact: String = source.split_whitespace().collect::>().join(" "); + let mut found = BTreeSet::new(); + for piece in compact.split("fn analyze_").skip(1) { + let name: String = piece + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + let rest = &piece[name.len()..]; + if rest.starts_with("( &self, content: &str,") + || rest.starts_with("(&self, content: &str,") + { + found.insert(format!("analyze_{name}")); + } + } + found + } + + /// Methods with the analyzer signature that no language routes to by + /// design: helpers run on every file or called from other analyzers. + const NOT_LANGUAGE_ANALYZERS: [&str; 1] = ["analyze_cross_language"]; + + fn snake(lang: Language) -> String { + let name = format!("{lang:?}"); + let mut out = String::new(); + for (i, c) in name.chars().enumerate() { + if c.is_ascii_uppercase() && i > 0 { + out.push('_'); + } + out.push(c.to_ascii_lowercase()); + } + out + } + + /// Claim 1a: every language analyzer in the source is reached by some + /// language. An analyzer nothing routes to is dead code. + #[test] + fn every_language_analyzer_is_reached() { + let routed: BTreeSet<&str> = Language::ALL.iter().map(|l| route(*l).analyzer()).collect(); + let methods = analyzer_methods_in_source(); + assert!( + methods.len() > 30, + "source scan found only {methods:?}: the signature pattern no longer matches" + ); + for method in &methods { + if NOT_LANGUAGE_ANALYZERS.contains(&method.as_str()) { + continue; + } + assert!( + routed.contains(method.as_str()), + "{method} exists in analyzer.rs but no language routes to it" + ); + } + } + + /// Claim 1b: every routed analyzer exists, and no language goes to the + /// generic fallback while a dedicated analyzer for it exists. + #[test] + fn no_language_falls_back_while_a_dedicated_analyzer_exists() { + let methods = analyzer_methods_in_source(); + for lang in Language::ALL { + let r = route(lang); + let name = r.analyzer(); + if name.starts_with("analyze_") { + assert!( + methods.contains(name), + "{lang:?} routes to {name}, which analyzer.rs does not define" + ); + } + if r == Route::Generic { + let own = format!("analyze_{}", snake(lang)); + assert!( + !methods.contains(&own), + "{lang:?} falls back to analyze_generic, but {own} exists" + ); + } + } + } + + /// Claim 2: cross-language checks run exactly on non-configuration + /// content, and on scripts embedded in configuration. + #[test] + fn cross_language_checks_run_exactly_off_configuration() { + assert!(runs_cross_language(false)); + assert!(!runs_cross_language(true)); + + // Built at run time so this source file holds no insecure URL of its + // own for panic-attack's self-scan to report. + let url = |path: &str| format!("{}://example.org/{path}", "http"); + let tmp = TempDir::new().unwrap(); + // A Justfile is configuration. Its variable is configuration content; + // its recipe body is an embedded shell script. The recipe URL is + // quoted: the cross-language detector strips `//` comments first, + // which also cuts an unquoted URL (a separate recall gap). + fs::write( + tmp.path().join("Justfile"), + format!( + "mirror := \"{}\"\n\nfetch:\n curl \"{}\"\n", + url("variable"), + url("recipe") + ), + ) + .unwrap(); + fs::write( + tmp.path().join("main.lua"), + format!("local url = \"{}\"\nprint(url)\n", url("source")), + ) + .unwrap(); + + let report = Analyzer::new(tmp.path()).unwrap().analyze().unwrap(); + let insecure: Vec<_> = report + .weak_points + .iter() + .filter(|w| w.category == WeakPointCategory::InsecureProtocol) + .collect(); + + assert!( + insecure.iter().any(|w| w.description.contains("main.lua")), + "source file was not checked: {insecure:?}" + ); + let justfile: Vec<_> = insecure + .iter() + .filter(|w| w.description.contains("Justfile")) + .collect(); + assert!( + justfile.iter().any(|w| w.description.contains("embedded")), + "the recipe's embedded script was not checked: {insecure:?}" + ); + assert!( + justfile.iter().all(|w| w.description.contains("embedded")), + "configuration content was checked as source: {insecure:?}" + ); + } + + /// Claim 3: the language counts the README states are the count the + /// table supports (every language except the `Unknown` sentinel). + #[test] + fn readme_language_counts_match_the_table() { + let supported = Language::ALL + .iter() + .filter(|l| **l != Language::Unknown) + .count(); + let readme = include_str!("../../README.adoc"); + let claims = [ + ("badge", "languages-", "-blue"), + ("capabilities", "**", "-language static analysis"), + ("summary", "* ", " supported languages"), + ]; + for (label, before, after) in claims { + let stated = readme + .lines() + .find_map(|line| { + let end = line.find(after)?; + let start = line[..end].rfind(before)? + before.len(); + line[start..end].parse::().ok() + }) + .unwrap_or_else(|| panic!("README no longer states the {label} count")); + assert_eq!( + stated, supported, + "README {label} says {stated} languages; the routing table supports {supported}" + ); + } + } +} diff --git a/src/types.rs b/src/types.rs index 1c7b7eae..fad80e6b 100644 --- a/src/types.rs +++ b/src/types.rs @@ -97,6 +97,67 @@ pub enum Language { } impl Language { + /// Every language, in declaration order, `Unknown` last. Tests iterate + /// over it, so a property checked "for every language" covers the whole + /// enum; `language_tests::all_lists_every_variant_once_in_order` keeps it + /// complete. + // The binary re-declares this module and never reads ALL itself. + #[allow(dead_code)] + pub const ALL: [Language; 52] = [ + Language::Rust, + Language::C, + Language::Cpp, + Language::Go, + Language::Java, + Language::Python, + Language::JavaScript, + Language::Ruby, + Language::Php, + Language::Elixir, + Language::Erlang, + Language::Gleam, + Language::ReScript, + Language::OCaml, + Language::StandardML, + Language::Scheme, + Language::Racket, + Language::Haskell, + Language::PureScript, + Language::Idris, + Language::Lean, + Language::Agda, + Language::Isabelle, + Language::Coq, + Language::Prolog, + Language::Logtalk, + Language::Datalog, + Language::Zig, + Language::Ada, + Language::Odin, + Language::Nim, + Language::Pony, + Language::DLang, + Language::Nickel, + Language::Nix, + Language::Shell, + Language::Julia, + Language::Lua, + Language::Chapel, + Language::WokeLang, + Language::Eclexia, + Language::MyLang, + Language::JuliaTheViper, + Language::Oblibeny, + Language::Anvomidav, + Language::AffineScript, + Language::Ephapax, + Language::BetLang, + Language::ErrorLang, + Language::VCL, + Language::FBQL, + Language::Unknown, + ]; + /// Infer the language from the final, case-sensitive extension without reading /// the file. Missing or unrecognised extensions yield `Unknown`. /// @@ -1154,6 +1215,79 @@ mod rule_id_tests { } } +#[cfg(test)] +mod language_tests { + use super::Language; + + // Exhaustive, with no wildcard: a new variant fails to compile here + // until it is given a place, and the test below then fails until ALL + // lists it at that place. + fn ordinal(l: Language) -> usize { + use Language::*; + match l { + Rust => 0, + C => 1, + Cpp => 2, + Go => 3, + Java => 4, + Python => 5, + JavaScript => 6, + Ruby => 7, + Php => 8, + Elixir => 9, + Erlang => 10, + Gleam => 11, + ReScript => 12, + OCaml => 13, + StandardML => 14, + Scheme => 15, + Racket => 16, + Haskell => 17, + PureScript => 18, + Idris => 19, + Lean => 20, + Agda => 21, + Isabelle => 22, + Coq => 23, + Prolog => 24, + Logtalk => 25, + Datalog => 26, + Zig => 27, + Ada => 28, + Odin => 29, + Nim => 30, + Pony => 31, + DLang => 32, + Nickel => 33, + Nix => 34, + Shell => 35, + Julia => 36, + Lua => 37, + Chapel => 38, + WokeLang => 39, + Eclexia => 40, + MyLang => 41, + JuliaTheViper => 42, + Oblibeny => 43, + Anvomidav => 44, + AffineScript => 45, + Ephapax => 46, + BetLang => 47, + ErrorLang => 48, + VCL => 49, + FBQL => 50, + Unknown => 51, + } + } + + #[test] + fn all_lists_every_variant_once_in_order() { + for (i, l) in Language::ALL.iter().enumerate() { + assert_eq!(ordinal(*l), i, "ALL[{i}] is {l:?}, out of place"); + } + } +} + #[cfg(test)] mod language_detect_tests { use super::Language; From ab0fdb2107e034e99b4b4f2fd7fb7366750d536e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 15:05:25 +0000 Subject: [PATCH 5/7] docs(proofs): record where the stripping model and Rust disagree Addresses the CodeRabbit review of this PR. Each Rust claim was run against strip_proof_comments copied verbatim from main: - `//x`: the model gives three spaces, Rust gives "". The model-to-Rust row now records a mismatch instead of ASSUMED, and the Stripping.idr header and section comment say the model does not reproduce the Rust output. The 349,525-input check is labelled model against model. - `a//*x*/*b*/c` -> `a/*b*/c` -> `ac`: Rust is not idempotent. - `a/*x*/b` -> `ab`: Rust does not preserve positions. - Found while checking: blocks are stripped before line comments, so a block opener inside a line comment hides the code after it. The Lean, Agda/Haskell and Coq ProofDrift detectors use this function. The open obligation now says the implementation must change first. - sigOnlySigner states that a matching key exists, not who signed; authenticity inherits that. - The dispatch row notes that Unknown files with no adapter are marked unsupported and skipped before the match. - The hexad property test's bounds are recorded from its generators. - Stripping.idr: PROOF-NEEDS.md -> PROOF-NEEDS.adoc. Stripping.idr still type-checks under Idris2 0.7.0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- PROOF-NEEDS.adoc | 65 +++++++++++++++++++++++++++++++++---------- src/abi/Stripping.idr | 25 +++++++++++------ 2 files changed, 66 insertions(+), 24 deletions(-) diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc index c1e8c652..a9646085 100644 --- a/PROOF-NEEDS.adoc +++ b/PROOF-NEEDS.adoc @@ -69,9 +69,15 @@ The Rust order itself comes from `#[derive(PartialOrd, Ord)]`. |Did not compile on `main` before `3dc4728`; repaired there without changing the theorem. The repaired model equals the previous one: `TESTED`, exhaustively on all 349,525 strings of length at most 9 over -`/`, newline, `x` and space. The model covers line comments only; block -comments and string literals are not modelled. Model to Rust -`strip_proof_comments`: `ASSUMED`. +`/`, newline, `x` and space. That comparison is model against model, not +model against Rust. + +The model does *not* match `strip_proof_comments`, so it is evidence about +the model only. It replaces comment characters with spaces and keeps every +newline. The Rust function deletes comment text and drops a trailing +newline: on `//x` the model gives three spaces and Rust gives the empty +string. The model also covers line comments only; block comments and string +literals are not modelled. |Attestation chain: integrity, authenticity, non-repudiation |`src/abi/AttestationUnforgeability.idr` @@ -81,12 +87,16 @@ comments and string literals are not modelled. Model to Rust * `chainCR`: the chain hash is *injective*. * `sigCorrect`: an honest signature verifies. * `sigBindsMessage`: a signature verifies only on the message signed. -* `sigOnlySigner`: a verifying signature was produced by the key holder, - with no exceptions. - -`chainCR` and `sigOnlySigner` are idealisations. They are stronger than -collision resistance and EUF-CMA, and false of any real fixed-length hash -or signature scheme. So these are theorems of a symbolic (Dolev-Yao style) +* `sigOnlySigner`: for every verifying signature there is a secret key + whose public key is the verifying key and whose signature on that digest + is that signature. + +`sigOnlySigner` says such a key *exists*. It says nothing about who +produced the signature, so `authenticity` inherits that limit: it shows the +seal equals one a matching key would make, not that the key holder made it. +`chainCR` and `sigOnlySigner` are idealisations, stronger than collision +resistance and EUF-CMA, and false of any real fixed-length hash or +signature scheme. So these are theorems of a symbolic (Dolev-Yao style) model, not a computational security reduction. Model to `src/attestation/`: `ASSUMED`. A computational proof is not claimed. @@ -96,9 +106,13 @@ detector; cross-language checks run on every file (PA1) |`PROVEN` (model); supports no claim about the Rust code |The theorem is vacuous: `GenericAnalyzer : HasAnalyzer lang` inhabits the witness type for every language, so it holds whatever the dispatch -does. The guarantee it was meant to give already holds in Rust: +does. Rust gives the narrower guarantee that actually holds: `match file_lang` in `src/assail/analyzer.rs` ends in -`_ => analyze_generic`, and `rustc` checks the match is exhaustive. +`_ => analyze_generic`, and `rustc` checks the match is exhaustive. That +covers every file that reaches the match. A file with no source language +and no configuration adapter (`Language::Unknown`, no adapter) is marked +`unsupported` in the coverage ledger and skipped first, so not every file +reaches an analyzer. The model has also drifted. Its `Lang` has 50 constructors and `src/types.rs` has 52; `C` and `Php` are missing. `crossLangAlwaysApplied` @@ -118,7 +132,15 @@ bounded at 47 against 52 variants. |`src/storage/mod.rs`, `hexad_json_roundtrip_is_identity` (proptest) |`TESTED` |A serialize, deserialize, serialize round trip on proptest-generated -hexads, compared as `serde_json::Value`. It does not call +hexads, compared as `serde_json::Value`. Bounds: proptest's default 256 +cases (the repository sets no override). `id` and `program_path` are 0 to +48 characters from `[A-Za-z0-9:_./-]`; `language` 0 to 12 lowercase +letters; `version` 1 to 8 characters from `[0-9.]`; the four counts are +below 10,000; `robustness_score` is in [0, 1]; `categories` holds 0 to 5 +strings of 1 to 16 letters; `attestation_hash` is absent or up to 64 hex +digits. Fixed, not generated: `schema`, `created_at`, `tool`, and +`document` (`{"weak_points": [], "n": total}`), and the `migration`, +`finding`, `campaign` and `crosslang` facets are all `None`. It does not call `write_*_hexad` or `load_hexad_dir`, so on-disk persistence is a separate obligation. The gateway octad projection is lossy by design, so this does not establish a faithful hexad-to-octad map. @@ -138,9 +160,22 @@ let a plain `idris2 --check` work. |`strip_proof_comments` is idempotent and preserves positions outside comments and strings -|Creusot/Pearlite and Verus -|On the Rust implementation. The Idris2 model above can guide the -contracts; it does not discharge them. The model's own remaining slices +|Fix the implementation first; then Creusot/Pearlite and Verus +|Neither property holds of the current Rust function, so neither can be +proved until it changes. All three cases below were run against the +function as it is on `main`: + +* Not idempotent: `a//*x*/*b*/c` gives `a/*b*/c`, and a second pass gives + `ac`. +* Positions move: `a/*x*/b` gives `ab`, moving `b` from offset 6 to 1. +* Ordering bug: block comments are stripped before line comments, so a + block opener inside a line comment swallows the code after it. + `code // see /* note`, then `hidden();`, then `*/ tail`, gives `code `. + The Lean, Agda/Haskell and Coq ProofDrift detectors use this function, + so such a comment can hide a later `sorry` or postulate. + +The Idris2 model above can guide the contracts once the function is +fixed; it does not discharge them. The model's own remaining slices (block comments, strings, composition, position preservation; issue #114) are optional once the implementation proof exists. diff --git a/src/abi/Stripping.idr b/src/abi/Stripping.idr index a3a1ea03..ecc64960 100644 --- a/src/abi/Stripping.idr +++ b/src/abi/Stripping.idr @@ -11,10 +11,13 @@ ||| ||| What this establishes, and what it does not: ||| -||| * The theorem is about this Idris2 model, not the Rust function. The -||| correspondence between the two is a hand transcription that no tool -||| checks (recorded as ASSUMED in PROOF-NEEDS.adoc). Block comments and -||| string literals are not modelled. +||| * The theorem is about this Idris2 model, not the Rust function, and the +||| model does not reproduce the Rust output. The model replaces comment +||| characters with spaces and keeps every newline; the Rust pass deletes +||| comment text and drops a trailing newline (`//x` gives three spaces +||| here and the empty string in Rust). Block comments and string literals +||| are not modelled. See PROOF-NEEDS.adoc for the Rust function's own +||| status. ||| * Multi-comment semantics: every `//` comment is stripped, not only the ||| first (the PR #111 model's error). `stripLineCommentBody` hands ||| control back to `stripLineComments` after each preserved newline. @@ -25,9 +28,10 @@ ||| every step dispatches on the class. The proofs carry the class as an ||| explicit argument together with the equation `cls c = k`, so each ||| case reduces. `stripLineComments` and `stripLineCommentBody` compute -||| the same function as the earlier pattern-matching definitions; that -||| was checked exhaustively on every string of length at most 9 over -||| `/`, newline, `x` and space (349,525 inputs, no mismatch). +||| the same function as the earlier pattern-matching Idris2 definitions; +||| that was checked exhaustively on every string of length at most 9 over +||| `/`, newline, `x` and space (349,525 inputs, no mismatch). That check +||| compares two Idris2 models; it is not a comparison with Rust. module PanicAttack.ABI.Stripping %default total @@ -59,7 +63,10 @@ cls '\n' = Newline cls _ = Other -- ═══════════════════════════════════════════════════════════════════════ --- Stripping functions (mirror src/assail/analyzer.rs strip_proof_comments) +-- Stripping functions: a model of the line-comment slice of +-- src/assail/analyzer.rs strip_proof_comments. The model keeps spaces and +-- newlines where the Rust function deletes comment text and drops a +-- trailing newline. -- -- `stripStep`, `slashStep` and `bodyStep` take the class of the character -- in hand, so each recursive call is on a strict sub-list and the @@ -232,7 +239,7 @@ sanityTwoComments = Refl -- What still remains (Layer 1.0 future slices) -- ═══════════════════════════════════════════════════════════════════════ --- Future Layer-1.0 work (recorded in PROOF-NEEDS.md + issue #114): +-- Future Layer-1.0 work (recorded in PROOF-NEEDS.adoc + issue #114): -- -- 1. **Stripping_Block.idr** — `/* … */` block-comment stripper. Same -- mutual-recursion shape. The closing `*/` plays the role newlines From 4db2497b9b57fb30142245029be1be4dddd2b641 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 15:41:58 +0000 Subject: [PATCH 6/7] docs(proofs): name the detectors the ordering bug reaches; refresh receipt From CodeRabbit's second review, checked against analyzer.rs: - The block-before-line ordering bug reaches every caller that passes both markers: analyze_rust, is_rust_ffi_safe_wrapper, analyze_idris, analyze_lean and analyze_agda. analyze_haskell does not call the function, and analyze_isabelle and analyze_coq pass no line marker. (The review listed Idris, Lean and Agda; the two Rust callers are affected too.) - The receipt now records that Stripping.idr was rechecked after the comment-only edits in ab0fdb2. All five modules pass again under Idris2 0.7.0, and the diff from 3dc4728 touches only comment lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u --- PROOF-NEEDS.adoc | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/PROOF-NEEDS.adoc b/PROOF-NEEDS.adoc index a9646085..ff07daee 100644 --- a/PROOF-NEEDS.adoc +++ b/PROOF-NEEDS.adoc @@ -33,7 +33,9 @@ exists to be scanned. tag `v0.7.0` (`27780073c8631826d846499840b3857d9b9a4fd5`) on Chez Scheme 9.5.8. * *Source:* `src/abi/*.idr` at - `3dc4728762f37c1e5bebdb988783c7683c50fb55`. + `3dc4728762f37c1e5bebdb988783c7683c50fb55`. `Stripping.idr` was rechecked + after the comment-only edits in `ab0fdb2107e034e99b4b4f2fd7fb7366750d536e` + and still passes; the other four modules are unchanged since `3dc4728`. * *Invocation:* the modules are named `PanicAttack.ABI.` but live in `src/abi/`, so `idris2 --check src/abi/.idr` fails on a module-name mismatch from any directory. Each was checked from a tree that places @@ -171,8 +173,12 @@ function as it is on `main`: * Ordering bug: block comments are stripped before line comments, so a block opener inside a line comment swallows the code after it. `code // see /* note`, then `hidden();`, then `*/ tail`, gives `code `. - The Lean, Agda/Haskell and Coq ProofDrift detectors use this function, - so such a comment can hide a later `sorry` or postulate. + The callers that pass both a line and a block marker are affected: + `analyze_rust`, `is_rust_ffi_safe_wrapper`, `analyze_idris`, + `analyze_lean` and `analyze_agda`. In the Idris, Lean and Agda ProofDrift + detectors such a comment can hide a later `sorry`, `believe_me` or + postulate. `analyze_isabelle` and `analyze_coq` pass no line marker and + are not affected. The Idris2 model above can guide the contracts once the function is fixed; it does not discharge them. The model's own remaining slices From 7070cb8856ade6e41ebba08325b69f33c37975e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 16:42:20 +0000 Subject: [PATCH 7/7] fix(abi): put the Eq doc comment above public export The merge placed '||| Equality on severity' between 'public export' and 'Eq Severity where'. Idris2 then rejects 'public export' as a declaration start (idris-abi on b332b5f). Doc comment first, as on main. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZnmBahbhfkFEP6ark4 --- src/abi/Types.idr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/abi/Types.idr b/src/abi/Types.idr index e9cefc31..f3eef792 100644 --- a/src/abi/Types.idr +++ b/src/abi/Types.idr @@ -20,8 +20,8 @@ import Data.Fin public export data Severity = Info | Warning | Error | Critical -public export ||| Equality on severity, required by `Ord`. +public export Eq Severity where Info == Info = True Warning == Warning = True