sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s

Contracts with a ladder of checks, an end-of-turn gate, retrospectives and
shared lessons, time-to-delivery measurement, a library of 140 verification
techniques and 20 recipes, personal data kept outside the clone, and
releases with rollback. Standard library only.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 22:29:02 -07:00
commit 2fc1fe9c2d
223 files changed
+22163

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
---
id: codeql
title: CodeQL queries for data-flow security and custom bug classes
answers: Can untrusted input reach a dangerous call anywhere in this code?
rung: 2
section: safety
languages: any
kinds: general, parsing
cost: high
detect: codeql version
ran_here: no
verified: docs
---
## Use when
- The claim is about flow: user input reaching SQL, a shell, a file path or a deserialiser through several functions.
- You need a repeatable security scan in CI (GitHub code scanning runs the same engine).
- You want a custom query for a project-specific flow, such as "a value read from the request must pass `sanitize()` before `render()`".
## Do not use when
- Licence first: the CodeQL CLI terms (codeql-cli-binaries README) say it "can only be used on codebases that are released under an OSI-approved open source license, or to perform academic research" and "can't be used to generate CodeQL databases for or during automated analysis, continuous integration or continuous delivery" outside that; private commercial code needs GitHub code scanning (which is licensed) or a sales contract. Check this before putting it in a contract.
- A pattern match is enough; `static-analysis-semgrep` is far cheaper to set up.
- The language is not supported. The supported list is C/C++, C#, GitHub Actions workflows, Go, Java, Kotlin, JavaScript/TypeScript, Python, Ruby, Rust (editions 2021 and 2024, needs Cargo, no nightly features) and Swift (analysis needs macOS).
- You need to show behaviour is correct rather than safe.
## Set up
Download the CodeQL bundle (CLI plus the standard query packs) from the
`github/codeql-action` releases (assets `codeql-bundle-*`), unpack it and put
`codeql` on PATH. Then, per project; the database path comes last and must not exist yet:
codeql database create db --language=python --source-root=.
# compiled languages add: --command="make"
# --build-mode=none exists for C#, Java, JavaScript/TypeScript, Python and Ruby only
## Minimal example
Run the maintained security suite, then your own query pack:
codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db \
codeql/python-queries:codeql-suites/python-security-extended.qls
## Run
codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db <suite-or-pack>
python3 -c "import json,sys; r=json.load(open('out.sarif'))['runs'][0]['results']; print(len(r)); sys.exit(1 if r else 0)"
Passing looks like: the analyze command exits 0 and the result count is 0.
The CLI manual does not document exit codes for `analyze`; the usual behaviour (not confirmed here, the tool is not installed) is exit 0 even when it finds issues, so the count check is what fails. The manual also says `sarif-latest` output changes between CodeQL versions and is unsuitable for automation, so the pinned `sarifv2.1.0` is used here. `--threads=0` uses every core.
## As a contract check
{"id": "codeql-security", "claim": "CodeQL security-extended suite reports no results", "kind": "general", "rung": 2, "cmd": "codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db codeql/python-queries:codeql-suites/python-security-extended.qls && python3 -c \"import json,sys; sys.exit(1 if json.load(open('out.sarif'))['runs'][0]['results'] else 0)\"", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
## What a pass does not prove
Only the flows the queries model are found; custom sinks and sanitisers that
the library does not know produce misses or noise. A stale database
(created before your edit) gives a pass for old code, so recreate it each run.
Check the check: add a known-vulnerable line on a scratch branch and confirm it
is reported.
@@ -0,0 +1,60 @@
---
id: dependency-audit-general
title: Vulnerability scans for any ecosystem with osv-scanner, npm audit and pip-audit
answers: Do the packages this project depends on have known vulnerabilities?
rung: 2
section: safety
languages: any
kinds: general
cost: low
detect: osv-scanner --version
ran_here: no
verified: docs
---
Note: `npm audit --help` was read here, and the `pip-audit` commands below
were run here (pip-audit 2.10.1, in a throwaway virtualenv, needs network). `osv-scanner` is not
installed here; its commands and exit codes come from the osv-scanner
documentation (google.github.io/osv-scanner).
## Use when
- The change adds or upgrades a dependency, or you are about to release.
- The project spans several ecosystems (npm, PyPI, Go, Maven, crates): osv-scanner reads their lockfiles together.
- A scheduled job must catch advisories published after the code was written.
## Do not use when
- The project is Rust only and wants licence and source rules as well; use `dependency-audit-rust`.
- No lockfile is committed. Scans of loose version ranges give answers about a build nobody ran.
## Set up
go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest # needs a recent Go; or: brew install osv-scanner, or a release binary
pipx install pip-audit # needs Python 3.10 or newer
# npm audit ships with npm
## Minimal example
Commit the lockfiles (`package-lock.json`, `poetry.lock`, `requirements.txt` with
pins, `go.mod`), then scan them.
## Run
osv-scanner scan source -r .
npm audit --audit-level=high --omit=dev
pip-audit -r requirements.txt --strict
Passing looks like: osv-scanner exits 0 (the docs define 0 as "packages found, none match a vulnerability"; its exact message is not documented); `npm audit` exits
0 and prints "found 0 vulnerabilities" at or above the chosen level; `pip-audit`
exits 0 and prints "No known vulnerabilities found". Any finding exits 1 for all three. osv-scanner
also exits 128 when it found no packages to scan (wrong directory, no lockfile) and 127 on a general error: both are failures, not passes.
`pip-audit` with unpinned requirements resolves dependencies itself; `--strict` turns a failed resolution into a failure.
`--omit=dev` limits npm to what ships; drop it if build tools run on untrusted input.
## As a contract check
{"id": "dep-vulns", "claim": "No known vulnerabilities in locked dependencies", "kind": "general", "rung": 2, "cmd": "osv-scanner scan source -r .", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
## What a pass does not prove
osv-scanner reports vulnerabilities of every severity; the docs page for its CLI mentions no severity filter, so the contract above is "none at all", not "none above high". Use `npm audit --audit-level=high` if you want a severity cut.
Only advisories already in the database, for versions the lockfile names.
Network is needed; an offline run that silently skips the database must not
count (check the output says it queried). Ignoring a finding in a config file
is the usual way this check is defeated: review the diff of any ignore list. A
vulnerable package that is installed but unreachable is still reported, and a
reachable vulnerable function in an unreported package is not.
+63
View File
@@ -0,0 +1,63 @@
---
id: dependency-audit-rust
title: cargo-deny and cargo-audit for advisories, yanked crates, licences and sources
answers: Do my Rust dependencies have known vulnerabilities, yanked versions, disallowed licences or untrusted sources?
rung: 2
section: safety
languages: rust
kinds: general
cost: low
detect: cargo-deny --version
ran_here: yes
verified: ran
---
Ran here with cargo-deny 0.20.2 (licenses, bans, sources and advisories on a
tiny crate). cargo-audit was not installed; its command is from memory.
## Use when
- Any change to `Cargo.toml` or `Cargo.lock`, and on a schedule (new advisories appear without you changing code).
- You must ship under a licence and need to know no dependency conflicts with it.
- Before release, so no yanked crate or unknown git source goes out.
## Do not use when
- The project is not Rust; see `dependency-audit-general`.
- You want proof the dependency code is correct. This reports known problems only.
## Set up
cargo install cargo-deny --locked
cargo deny init # writes deny.toml; edit it as below
## Minimal example
`deny.toml`:
[advisories]
yanked = "deny"
[licenses]
allow = ["MIT", "Apache-2.0", "BSD-3-Clause", "ISC", "Unicode-3.0"]
[bans]
wildcards = "deny"
[sources]
unknown-registry = "deny"
unknown-git = "deny"
Record every exception beside its reason and a date, never on the command line.
## Run
cargo deny check advisories licenses bans sources
cargo audit # alternative advisory-only check
Passing looks like: `advisories ok, bans ok, licenses ok, sources ok`, exit 0.
Failure exits non-zero (4 in the run here) with `error[rejected]` or
`error[unlicensed]`. The default `deny init` file allows no licence, so a
fresh crate fails until `allow` is filled in. Advisory checks need network to
fetch the RustSec database.
## As a contract check
{"id": "cargo-deny", "claim": "No known advisories, yanked crates, disallowed licences or unknown sources", "kind": "general", "rung": 2, "cmd": "cargo deny check advisories licenses bans sources", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
Only known, reported problems. Today's pass says nothing about tomorrow's
advisory, so schedule it (see `check-tiering`). `ignore` entries and loosened
`allow` lists are how this check gets defeated: read the diff of `deny.toml`.
An unmaintained-crate notice is not a vulnerability; decide that on purpose.
+67
View File
@@ -0,0 +1,67 @@
---
id: licence-notices
title: Generating and checking third-party licence notices
answers: Does the shipped product carry the licence texts and copyright notices its dependencies require?
rung: 3
section: safety
languages: any
kinds: general
cost: medium
detect: command -v cargo-about
ran_here: no
verified: docs
---
Note: cargo-about is not usable here (the mise shim has no version set), so the
script was not run. The cargo-about install command and the `generate` and `init`
flags below were checked against its documentation (EmbarkStudios/cargo-about,
docs/src). The generate-then-compare shape is the one used by a working script in a Rust and Lean 4
project (a `scripts/notices.sh`), which also calls `cargo about generate --locked --all-features --offline`.
## Use when
- You ship a binary, package or image that contains other people's code. MIT, BSD, Apache-2.0 and ISC all require their text to travel with copies.
- A dependency was added, removed or upgraded.
- Before release (see `release-gate`).
## Do not use when
- You only run the code internally and never distribute it.
- The question is "is this licence allowed at all"; that is `dependency-audit-rust` (or the ecosystem's licence checker).
## Set up
Rust: `cargo install --locked --features cli cargo-about` (the `cli` feature is needed), then `cargo about init` for
`about.toml` and `about.hbs`. `about.toml` must carry an `accepted` list of licence ids (in priority order); cargo-about errors on a crate whose licence it cannot satisfy from that list. Other ecosystems: `pip-licenses`,
`license-checker`, or `go-licenses report`. Commit the generated file.
## Minimal example
`scripts/notices.sh` generates `THIRD-PARTY-NOTICES.txt`, or with `--check` fails
if the committed copy is stale:
#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT
cargo about generate --locked --all-features --fail about.hbs > "$tmp"
if [ "${1:-}" = "--check" ]; then
diff -q "$tmp" THIRD-PARTY-NOTICES.txt >/dev/null \
|| { echo "notices out of date: run scripts/notices.sh" >&2; exit 1; }
else cp "$tmp" THIRD-PARTY-NOTICES.txt; fi
`--fail` exits non-zero when a crate's licence cannot be determined; without it such crates are skipped. For a workspace add `--workspace`, or point `-m crates/app/Cargo.toml` at the one binary you ship, so the list is what the program contains. `--offline` (never touch the network) makes cargo-about use only the crates' packaged files, losing clarifications that fetch licence text from a repository. `-c about.toml` is the default config path.
The output must not contain dates or absolute paths, or the byte comparison
fails on every machine.
## Run
scripts/notices.sh --check
Passing looks like: exit 0, no output. Failure prints "notices out of date" and
exits 1; regenerate, read the diff, commit.
## As a contract check
{"id": "notices-current", "claim": "THIRD-PARTY-NOTICES.txt matches the dependencies", "kind": "general", "rung": 3, "cmd": "scripts/notices.sh --check", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
## What a pass does not prove
That the file is current, not that it is packaged. Also check the built package
contains it (see `release-gate`). Generators fall back to a licence's standard
text when a crate's own file does not match, which has a placeholder copyright
line; MIT and BSD want the real notice. Bundled fonts and vendored code are
outside the dependency graph and need their own entries.
+61
View File
@@ -0,0 +1,61 @@
---
id: rust-lints-strict
title: Clippy with warnings denied, pedantic groups and an unsafe policy
answers: Does the Rust code compile with zero warnings and no lint the project has chosen to forbid?
rung: 1
section: safety
languages: rust
kinds: general, money, parsing
cost: low
detect: cargo clippy --version
ran_here: yes
verified: ran
---
## Use when
- Any Rust change: this is the cheapest check there is and catches real bugs (lossy casts, unchecked indexing, missing `#[must_use]`).
- Code handles money or untrusted input, where `as` casts, `unwrap` and `panic` are hazards.
- You want "warnings are errors" stated once, so it is not a matter of taste.
## Do not use when
- You need to know the code does the right thing. Lints find shapes, not wrong answers.
## Set up
Put the policy in the manifest so every command sees it (`Cargo.toml`):
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "deny"
expect_used = "deny"
cast_possible_truncation = "deny"
indexing_slicing = "deny"
## Minimal example
`src/lib.rs`:
#[must_use]
pub fn add(a: u64, b: u64) -> Option<u64> { a.checked_add(b) }
## Run
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --all --check
Passing looks like: exit 0 and no `warning:` or `error:` lines. Failure shows as
`error: could not compile` with the lint name; here, dropping `#[must_use]`
fails with `clippy::must_use_candidate` (run here, clippy 0.1.100). `-D
warnings` promotes every enabled pedantic warning to an error, which is the
point. Do not fix a lint with a blanket `#![allow(...)]`; allow one item and
give the reason in a comment.
## As a contract check
{"id": "clippy-strict", "claim": "Zero clippy warnings including pedantic and the unsafe policy", "kind": "general", "rung": 1, "cmd": "cargo clippy --workspace --all-targets --all-features -- -D warnings", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
## What a pass does not prove
Not that the logic is right. `--all-targets` is needed or tests and examples
are skipped; `--all-features` is needed or feature-gated code is skipped. A
crate with `#![allow(clippy::all)]` or a `[lints]` override passes trivially:
grep for `allow(` additions in the diff. Check the check by adding a
deliberate `.unwrap()` and seeing it fail.
+61
View File
@@ -0,0 +1,61 @@
---
id: secret-scanning
title: Secret scanning with gitleaks or trufflehog on the diff and the history
answers: Did this change, or any earlier commit, put a password, key or token into the repository?
rung: 2
section: safety
languages: any
kinds: general
cost: low
detect: gitleaks version
ran_here: no
verified: docs
---
Note: neither gitleaks nor trufflehog is installed here, so nothing below was
run. Commands and exit codes were checked against the gitleaks README (v8.30.x,
which says gitleaks is "feature complete", with security patches only from now on;
the author's new project is Betterleaks, not covered here) and the trufflehog README.
## Use when
- Every change, before it is committed or pushed. A leaked key must be rotated, so catching it early is the whole value.
- Code touches configuration, tests with credentials, deployment files or `.env` handling.
- Before making a private repository public.
## Do not use when
- The worry is a secret that is not in the repository but in logs or output; see `sensitive-data-leak-test`.
## Set up
# gitleaks: brew install gitleaks, the docker image ghcr.io/gitleaks/gitleaks, or a release binary
gitleaks version
# trufflehog: brew install trufflehog, or the install script / docker image in its README
# optional allowlist for known fake values: .gitleaks.toml
## Minimal example
Scan only what is about to be committed, then the full history:
gitleaks git --staged --redact -v
gitleaks git --redact -v # all commits (`gitleaks dir` scans files without git history)
`--redact` keeps the secret itself out of the report, which matters because the
report may be pasted into a log or chat.
## Run
gitleaks git --redact --exit-code 1
trufflehog git file://. --results=verified --fail --no-update # alternative; verifies keys against the provider
Passing looks like: gitleaks exits 0 (README: "0 - no leaks present"). A finding exits 1 (the default, set with `--exit-code`) and names
the file, line and rule; an error also exits 1 and an unknown flag exits 126. trufflehog exits 0 with no results, 1 on an error, and 183 when results were found, which only happens with `--fail`.
`--results=verified` counts only keys the provider confirms are live; use `--results=verified,unknown` to also fail on keys it could not check.
`gitleaks detect` and `protect` still work but are deprecated since 8.19.0. If a real secret is found, rotate it first; removing it
from history does not make it safe again.
## As a contract check
{"id": "no-secrets", "claim": "No secrets in the working tree or history", "kind": "general", "rung": 2, "cmd": "gitleaks git --redact --exit-code 1", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
## What a pass does not prove
Scanners match known key shapes and high-entropy strings; a custom token format
or a password in prose is missed. A shallow CI clone hides history, so fetch
full depth. An allowlist entry that is too broad hides real leaks: read changes
to `.gitleaks.toml`. Check the check by committing a fake AWS-style key on a
scratch branch and confirming it is flagged.
@@ -0,0 +1,61 @@
---
id: sensitive-data-leak-test
title: Tests that a secret value never appears in files, logs, free text or errors
answers: Can the secret value (a tax id, a token, a password) appear anywhere it should not?
rung: 3
section: safety
languages: any
kinds: general
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- The code handles a value that must be stored in one place only (a vault) or never stored: tax ids, tokens, card numbers, health data.
- A bug report says a secret showed up in a log line, an exception message, a backup, an export or free-text notes.
- You changed logging, error formatting, serialisation or export code near such a value.
## Do not use when
- You are checking committed files for keys; use `secret-scanning`.
- The value can legitimately appear in output (the user's own page). Test a masked form instead.
## Set up
No tool. Pick one unmistakable canary value per secret (a real-shaped but fake
tax id such as `123-45-6789`) and list its variants: with and without
separators, reversed, URL-encoded, base64 if the code encodes it.
## Minimal example
Python, standard library (`test_leak.py`). Run every surface the program can write to
and assert the canary is in none:
SECRET = "123-45-6789"
VARIANTS = {SECRET, SECRET.replace("-", ""), SECRET[::-1]}
# ... call save_vendor(name, SECRET, outdir, log) and a failing call ...
surfaces = {f.name: f.read_text() for f in Path(d).rglob("*") if f.is_file()}
surfaces["logs"] = "\n".join(captured_log_lines)
surfaces["error"] = str(exc_info.exception)
for where, text in surfaces.items():
for v in VARIANTS:
assert v not in text, f"{v!r} leaked into {where}"
Add a test that the check can fail: assert the canary is found in a string you
build to contain it. Also exercise the failure paths (bad input, crash): leaks
live in error messages and tracebacks.
## Run
python3 -m unittest -q test_leak
Passing looks like: `OK`. Failure shows `AssertionError: '123-45-6789' leaked
into logs`. Scan the whole data directory, temp files and any export, not only
the files you expect.
## As a contract check
{"id": "no-secret-leak", "claim": "The secret canary appears in no file, log or error message", "kind": "general", "rung": 3, "cmd": "python3 -m unittest -q test_leak", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
## What a pass does not prove
Only the surfaces and variants you listed. A secret transformed in a way you did
not list (hashed with a weak hash, split across lines) is not caught. Memory,
swap, crash dumps and third-party services are outside it. Rung 3 is honest:
it is examples, not a proof that no path leaks.
+50
View File
@@ -0,0 +1,50 @@
---
id: shellcheck
title: ShellCheck for shell scripts
answers: Do my shell scripts have quoting, word-splitting or portability bugs?
rung: 2
section: safety
languages: any
kinds: general
cost: low
detect: shellcheck --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed any `.sh` script, CI step, git hook or `just` recipe body in bash.
- A script deletes, moves or loops over files, where an unquoted variable can be destructive.
- A script must run on more than one shell (`sh`, `dash`, `bash`).
## Do not use when
- The script is a few lines of fixed commands with no variables. Run it instead.
- You need to know the script produces the right result; ShellCheck cannot say so. Run it on test input.
## Set up
shellcheck --version # package manager: pacman -S shellcheck, apt install shellcheck
## Minimal example
`bad.sh`:
#!/usr/bin/env bash
for f in $(ls *.txt); do rm $f; done
## Run
shellcheck --severity=warning --shell=bash bad.sh
git ls-files '*.sh' | xargs -r shellcheck -x --severity=warning
Passing looks like: no output, exit 0. Failure here (run on this machine,
v0.11.0) prints `SC2045 (error): Iterating over ls output is fragile. Use globs.`
and exits 1. `-x` follows `source`d files. Pick the shell with `--shell` or a
`# shellcheck shell=bash` line, or the wrong dialect is checked. Fix the cause;
only disable a code with `# shellcheck disable=SC2034` plus a comment saying why.
## As a contract check
{"id": "shellcheck", "claim": "All shell scripts pass ShellCheck at warning level", "kind": "general", "rung": 2, "cmd": "git ls-files '*.sh' | xargs -r shellcheck -x --severity=warning", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
## What a pass does not prove
It checks syntax and well-known pitfalls only. `set -euo pipefail` mistakes,
logic errors, and wrong command arguments pass. Scripts without a `.sh`
extension or only a shebang (`bin/tool`) are skipped by the `git ls-files '*.sh'`
glob, so list them. A file full of `disable=` comments passes: grep the diff.
@@ -0,0 +1,72 @@
---
id: static-analysis-semgrep
title: Semgrep rules, including a custom rule for a project-specific mistake
answers: Does any code match a known-bad pattern, including a mistake this project keeps making?
rung: 2
section: safety
languages: any
kinds: general, parsing
cost: medium
detect: semgrep --version
ran_here: yes
verified: ran
---
## Use when
- You want a scan for a known class of bug (injection, unsafe deserialisation, hard-coded keys) across many languages.
- The project keeps repeating one mistake (calling `float()` on money, using `datetime.now()` where a clock is injected). Write a rule once; every later change is checked.
- You fixed a bug and want to make sure no sibling of it exists elsewhere.
## Do not use when
- The claim is about behaviour or values. Semgrep matches syntax, so it cannot show a result is right.
- You need data-flow across files and functions that Semgrep's free taint mode cannot follow; see `codeql` (which has licence limits on private code; check it).
## Set up
pipx install semgrep # README's preferred way; also: uv tool install semgrep, brew install semgrep
mkdir -p rules # not a hidden directory: `semgrep --test` found nothing under `.semgrep/`
Not installed globally here; the example below was run in a throwaway virtualenv (`pip install semgrep`, version 1.186.0).
## Minimal example
`rules/no-float-money.yml`:
rules:
- id: no-float-money
languages: [python]
severity: ERROR
message: Money must be Decimal or integer cents, not float.
pattern-either:
- pattern: float($X)
- pattern: $X = $Y / $Z
paths:
include: ["/src/billing/"]
`src/billing/bad.py` containing `total = float(price)` is reported. `paths.include` patterns are matched relative to the scan target, so scan from the project root (`.`) and anchor the pattern with a leading `/`. A bare `src/billing/` still works but prints a warning that it will change meaning.
## Run
semgrep scan --config rules/ --error --metrics=off .
Passing looks like: exit 0 and `Findings: 0`. With `--error` any finding exits 1; a fatal error (bad rule, bad config) exits 2. Without `--error`, findings still exit 0, so never drop the flag. Check the output also says `Targets scanned: N` with N above 0.
Test the rule itself. Next to the rule, in a file with the same base name and the language's extension (`rules/no-float-money.py`):
# ruleid: no-float-money
total = float(price)
# ok: no-float-money
total = price_cents
then `semgrep scan --test rules/`. It prints `1/1: ✓ All tests passed` and exits 0; a missed `ruleid:` line prints `missed lines: [N]` and exits 1.
## As a contract check
{"id": "semgrep-project-rules", "claim": "No code matches the project's banned patterns", "kind": "general", "rung": 2, "cmd": "semgrep scan --config rules/ --error --metrics=off . && semgrep scan --test rules/", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
## What a pass does not prove
A pass proves only that no code matches the patterns you wrote. A rule that
matches nothing passes forever. Two ways this happened while checking this
entry: a `paths.include` of `src/billing/` with the scan target `src/` scanned
zero files and exited 0, and `--test` against a hidden `.semgrep/` directory
printed "No unit tests found" and exited 0. So keep a `ruleid:` test file, run
`--test`, and read `Targets scanned`. Pattern rules miss aliasing, such as
`f = float; f(x)`. A rule is a sample of bad shapes, not a proof of safety.
Rule ids reported by `scan` carry the directory name as a prefix
(`rules.no-float-money`); the test annotations use the plain id.
@@ -0,0 +1,60 @@
---
id: threat-model-checklist
title: A short written threat model turned into checks
answers: Have I thought about who can attack this change and tested each way in?
rung: 5
section: safety
languages: any
kinds: general
cost: medium
detect:
ran_here: no
verified: docs
---
Note: this technique has no tool; there is nothing to run. `verified: docs`
means the method follows STRIDE as published by Microsoft.
## Use when
- The change crosses a trust boundary: parses data from outside, adds an endpoint, handles credentials, runs a subprocess, reads a user-supplied path, or changes who may do what.
- A security fix: the model says what attack the fix closes and what else is open.
- A new tool surface for agents, where input is untrusted text.
## Do not use when
- The change is internal and touches no boundary. A paragraph of ceremony costs more than it saves.
## Set up
Create `docs/threat-model/<change>.md`. No tool required.
## Minimal example
Five lines, then one check per threat:
Asset: the invoice PDF a customer uploads and we render.
Entry points: POST /upload (file, filename), the renderer subprocess.
Who: any signed-in customer; an attacker with a customer account.
Threats (STRIDE) and checks:
T1 Tampering: filename `../../etc/x` writes outside uploads/ -> test_upload_path_traversal
T2 Denial of service: 2 GB file exhausts disk -> test_upload_size_limit (413)
T3 Info disclosure: one customer reads another's PDF -> test_cross_tenant_download (404)
T4 Elevation: renderer runs with the app's environment -> test_renderer_env_is_empty
Out of scope, stated: DDoS at the network layer.
## Run
python3 - <<'PY'
import re,sys; t=open("docs/threat-model/upload.md").read()
bad=[l for l in t.splitlines() if re.match(r"\s*T\d+ ",l) and "->" not in l]
sys.exit(1 if bad else 0)
PY
pytest -k "traversal or size_limit or cross_tenant or renderer_env"
Passing looks like: every threat line names a check, and each named check
exists and passes. A threat with no check is listed as open, not dropped.
## As a contract check
{"id": "threat-checks", "claim": "Every threat in the model has a passing check", "kind": "general", "rung": 3, "cmd": "pytest -q -k 'traversal or size_limit or cross_tenant or renderer_env'", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
## What a pass does not prove
Only the threats you thought of. The value is the list, so have an independent
reader (a second model, or the human) add threats before you write checks, and
record disagreements. The rung is 5 for the model itself and 3 for the
executable checks derived from it.
+59
View File
@@ -0,0 +1,59 @@
---
id: unsafe-audit
title: Auditing and forbidding unsafe Rust
answers: Is there any unsafe code in this crate or its dependencies, and is what exists justified and tested?
rung: 1
section: safety
languages: rust
kinds: general, concurrency
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
Ran here: `#![forbid(unsafe_code)]` refusing an `unsafe` block. Not run here:
`cargo geiger` (not installed) and Miri (component not on this toolchain);
their flags are from memory.
## Use when
- The crate says it needs no `unsafe`: make the compiler enforce that.
- A change adds `unsafe`, or a dependency is added or upgraded and you want its unsafe footprint.
- Unsafe code exists and you need its undefined behaviour checked (Miri).
## Do not use when
- The crate is a thin wrapper over FFI, where unsafe is the job; audit each block by hand and test under sanitisers instead.
## Set up
# forbid: top of src/lib.rs and src/main.rs
#![forbid(unsafe_code)]
cargo install cargo-geiger # counts unsafe in the crate and dependencies
rustup +nightly component add miri
## Minimal example
`src/lib.rs`:
#![forbid(unsafe_code)]
pub fn first(v: &[u8]) -> Option<u8> { v.first().copied() }
Adding `unsafe { *v.get_unchecked(0) }` makes the build fail with
"usage of an `unsafe` block".
## Run
cargo build
cargo geiger --all-features # report; unsafe counts per dependency
cargo +nightly miri test # runs tests under the UB-detecting interpreter
Passing looks like: `cargo build` exits 0 under forbid; geiger shows 0 used
unsafe in your own crates (`🔒` rows); Miri exits 0. Failure: a compile error,
a non-zero geiger count in your crate, or a Miri "Undefined Behavior" message.
For concurrency, see `miri`, `loom` and `thread-sanitizer` in the concurrency section.
## As a contract check
{"id": "no-unsafe", "claim": "The crate forbids unsafe code and builds", "kind": "general", "rung": 1, "cmd": "grep -q 'forbid(unsafe_code)' src/lib.rs && cargo build --all-features", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
## What a pass does not prove
`forbid` covers your crate only; dependencies may still use unsafe (that is what
geiger reports, and it counts, it does not judge). Miri finds UB only on paths
the tests run, and cannot run most FFI or I/O. A `forbid` that someone moved
into `#![allow]` is a silent failure: keep the grep in the check.