<!--
SPDX-License-Identifier: Apache-2.0
SPDX-FileCopyrightText: 2026 ndaal Informationstechnik GmbH & Co KG, Cologne
SPDX-FileCopyrightText: Author: Pierre Gronau <Pierre.Gronau@ndaal.eu>
-->
# Developer Guide
Architecture, conventions and the QA toolchain for `sarif-viewer`.
## Architecture
A single binary crate. The raw `serde_json::Value` is the source of truth for
each SARIF log; [`model`](../src/model.rs) extracts typed views for display and
export. See [`structure.md`](../structure.md) for the file map.
Data flow:
```text
file/stdin ─▶ import ─▶ validation (schema gate) ─▶ store (in-memory)
│
web routes / CLI ◀───────────┘
│
export ─▶ build_artifacts ─▶ cap-std write + sidecars
```
Upload (`upload`, `routes::upload`) joins that flow at `import::admit_bytes`,
the one function that validates bytes and admits them to the store; Import
reads a file and calls it too.
Where things live:
| Module | Job |
| ----------------------------------------------------------- | ---------------------------------------------------------- |
| `schema`, `validation` | the JSON-Schema gate, run on every import and export |
| `model`, `store` | typed views over a log; the in-memory collection |
| `import`, `export`, `export_pdf`, `sidecar` | the import and export pipelines |
| `upload` | the multipart parser behind `POST /upload` |
| `router`, `static_files`, `html`, `routes`, `server`, `tls` | the web layer |
| `info` | the Info-menu document pages (see below) |
| `listen_port` | the listen-port rule: `ListenPort`, 1025-65535 (see below) |
| `updater` | offline-first, checksum-verified self-update |
| `path_security` | capability-scoped file access |
The web layer reuses the ndaal OSCAL viewer's `matchit` router and
security-header middleware; the export engine (Markdown/ODT via `lo_writer`, PDF
via an embedded-font renderer, checksum sidecars) and the TLS + QUIC listeners
are reused from the ndaal CSAF-CRUD and OSCAL projects.
### POST routes and the request body
The router started GET-only. `RouterBuilder::post` registers a body route, whose
handler receives the request body as `Bytes`, already read under
`router::MAX_BODY_BYTES` (64 MiB). The router reads it, not the handler: for
HTTP/1.1 and HTTP/2 through `read_body_limited` (`413` over the cap, `400` for a
broken stream), and for HTTP/3 through `read_h3_body` in `server.rs`. Both are
needed, because the HTTP/3 request loop used to discard the body.
Rules for a new write route:
1. Call `router::same_origin(&parts)` first and answer `403` when it is false.
2. Never put a client-supplied name in a filesystem path.
3. Escape anything user-derived before it reaches `html::alert`, which inserts
its text as-is.
4. Test it through `SharedRouter::handle_with_body`, with plain bytes; see
`tests/test_upload.rs`. Over HTTP/3, `tests/test_upload_h3.rs` is a real
QUIC client against the real endpoint.
An unregistered method on a known path gets `405` with an `Allow` header that
lists the methods registered for that path.
## Conventions
- `#![forbid(unsafe_code)]` across the crate. A macro that expands to `unsafe`
(for example `assert_eq_size_val!`) is therefore unavailable.
- The lint policy (`Cargo.toml [lints.clippy]`, `clippy.toml`) denies
`unwrap`/`expect`/`panic`, unchecked arithmetic (`arithmetic_side_effects`)
and unchecked indexing (`indexing_slicing`) in production code; Clippy
pedantic + nursery run at warn. Test code is exempt through the
`allow-*-in-tests` settings in `clippy.toml`.
- `clippy.toml` also bans the print and debug macros, `std::env::var`, spawning
a `Command`, and
`std::fs::{read_to_string, write, create_dir, create_dir_all}`. The few places
that legitimately need them are single, audited sinks in `src/main.rs`
(`out_line`, `err_line`, `env_var`), each carrying one
`#[expect(lint, reason = "...")]`. Write new suppressions in that form:
`expect` fails the build once the suppression stops being needed, so none
outlives its reason. A few older test modules still carry a bare `#[allow]`;
do not copy it.
- Paths from outside the binary: writes go through a capability-scoped `cap-std`
`Dir`; operator-named reads use `std::fs` annotated `// allow-std-fs:` (see
`path_security`).
- Everything shown to the user passes through `html::escape`. It also
neutralises Unicode bidirectional controls (Trojan Source), so a crafted SARIF
string cannot reorder what an analyst reads.
- Fonts and icons are bundled in the binary. Nothing is loaded from a CDN.
## The Info menu
The Info dropdown follows the ndaal design standard: twelve entries in a fixed
order, two dividers, nothing after Troubleshooting. `src/html.rs` holds the menu
table (`INFO_MENU`); `src/info/` holds the six document pages.
A document page shows one repository file as pure Markdown: the text is embedded
at compile time (`include_str!`), HTML-escaped and placed in a `<pre>`. It is
never rendered to HTML, so a document cannot inject markup or script, and there
is no JavaScript. The icon is hidden from assistive technology, and the scroll
region is named by its heading and takes keyboard focus.
To add a document page:
1. Add a `DocPage` constant in `src/info/documents.rs`, and list it in
`DOC_PAGES` in `src/info/mod.rs` in menu order.
2. Add the entry to `INFO_MENU` in `src/html.rs`. A test fails if the menu and
`DOC_PAGES` disagree on route, icon or label.
3. Add a handler in `src/routes/info.rs` and a `.get(...)` in
`src/routes/mod.rs`.
4. List the source file in the `include` array of `Cargo.toml`. A test fails if
it is missing; without it the published crate does not build.
5. Add a Bruno request under `test/bruno/collections/info/` and the route to the
lists in `tests/test_routes.rs`.
## Listen ports
Every listen port (`--port`, `--quic-port`, `SARIF_PORT`, `SARIF_QUIC_PORT`)
goes through one type, `listen_port::ListenPort`, vendored from
`skills/rust-ip-ports` as a hidden module (`#[doc(hidden)]`, so the documented
API and `cargo semver-checks` are unchanged). The rule: a port is accepted if
and only if it is a canonical decimal number in 1025..=65535.
- Take a port as a `ListenPort`, never as a bare `u16`. Do not parse one with
`str::parse::<u16>()`: it accepts `+8080` and `08080`.
- Write a default with `ListenPort::from_const::<8580>()`. A wrong default is a
build error (`E0080`), not a failure at the first start.
- The variables are read by `port_from` in `src/main.rs`, not by clap's `env =`,
so an error names the variable. The flag wins over the variable, the variable
over the default. `resolve_serve_config` runs first in `run_serve`, so a
refused port stops the program before anything is loaded or bound.
- `exit_status` maps a clap error to 64 (a refused port, `ValueValidation`) or
to clap's own status. That is only sound while no other argument has a value
parser that can fail with that kind; a unit test fails if one is added.
- The module has no `Default`, no infallible `From<u16>` and no serde impls;
`tests/static_assertions_invariants.rs` pins the first two at compile time.
Decision record: `documentation/adr/0001-listen-port-rule.md`. Quality
scenarios: `documentation/arc42/en/10-quality-requirements.md`.
## Head tags and the social preview image
Every full page carries 14 tags: description, author, Open Graph and Twitter
card. They are one constant, `HEAD_META` in `src/html.rs`, written by `page`,
the only function that writes a head. Never paste them into a second template.
The values are fixed English text and absolute `https://sarif.ndaal.eu/` URLs.
In the `og:` tags `content` comes before `property`, because htmlhint's
`attr-sorted` rule requires it.
Change the tags in four places together: `HEAD_META`, `HEAD_TAGS` in
`tests/test_routes.rs`, the two Bruno requests (`pages/05`, `info/13`) and
`test/playwright/tests/head-meta.spec.ts`. The specification, with the rules and
the failure modes, is `skills/html-meta-tags-sarif` in the nvulnlookup skills.
`GET /social-preview.png` serves the 1200 x 630 image the tags name, from the
binary (`static_files::serve_social_preview`). Its source is
`src/static/img/social-preview.svg`, drawn from ndaal design tokens, the bundled
Roboto and the bundled logo. It has not had a design review. To regenerate the
PNG from the repository root:
```bash
resvg --skip-system-fonts --width 1200 --height 630 \
--use-font-file src/static/fonts/roboto/roboto-regular.ttf \
--use-font-file src/static/fonts/roboto/roboto-bold.ttf \
--font-family Roboto \
src/static/img/social-preview.svg src/static/img/social-preview.png
oxipng -o4 --strip safe src/static/img/social-preview.png
```
The PNG is stored through Git LFS, like the logo: a checkout without LFS holds a
pointer file, not the image.
## QA toolchain
Run the same checks a commit hook would, in this order:
```bash
cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-targets --all-features
cargo test --workspace --all-features --doc
RUSTDOCFLAGS='-D warnings' cargo doc --no-deps
typos
cargo deny check # advisories, licences, bans (deny.toml)
cargo audit # RustSec advisories (audit.toml)
```
`--all-targets` leaves out doctests, hence the separate `--doc` pass. Never gate
on `cargo test --lib`: it skips every integration test.
### Fuzzing
```bash
cargo +nightly fuzz run fuzz_safe_join -- -max_total_time=60
fuzz/run-all.sh 60 # every target
```
There are 28 targets under `fuzz/fuzz_targets/`, covering the path and URL
parsers, HTML escaping and rendering, the document pipeline, the Info document
renderer, the export renderers, the updater's parsers, the language switcher's
redirect target and the upload path: the multipart parser, the CSRF gate and
the whole upload pipeline.
`cargo fuzz run <target>` builds only the target it is given, so a target that
no longer compiles goes unnoticed until someone runs it. Compile them all after
any signature change:
```bash
(cd fuzz && cargo +nightly check --bins --keep-going)
```
### Property-based tests
`tests/proptest_invariants.rs` restates the security-critical invariants as
`proptest` properties: segment safety, `safe_join` containment, the `escape` XSS
boundary, the checksum sidecars, the URL/query and export-token parsers, the
totality of `static_files::serve` and `routes::query_pairs`, and the model's
severity tally.
`tests/proptest_boundaries.rs` covers three boundaries that had only examples:
the language switcher's redirect target stays on this origin, `parse_query`
round-trips a percent-encoded value, and every checksum sidecar holds the digest
an independent hash crate computes. `tests/proptest_upload.rs` covers the upload
path: the CSRF gate, verbatim multipart content, a safe basename for any client
file name, the exact 413 boundary, `405` with `Allow` for any other method, and
`admit_bytes` never overwriting a log. `tests/proptest_state_machine_store.rs`
is a `proptest-state-machine` model test of `SarifStore`: a model of ids in
insertion order runs beside the real store over random sequences of inserts,
unique inserts, removes and gets.
`tests/proptest_pipeline.rs` covers the document pipeline behind them: version
detection, the store as an ordered set of unique ids, validation-gated export
(output exists if and only if the validator accepts), and containment of written
artifacts. `src/main.rs` has two more for the listener configuration and the
update-action precedence.
```bash
bash tests/scripts/test_proptest.sh # 256 cases per property
bash tests/scripts/test_proptest.sh --long-sweep # 4096
```
A failing property saves its counterexample under a `proptest-regressions`
directory. Commit it: the counterexample then runs on every future build.
The rule itself has more layers:
- `tests/listen_port_rules.rs` (one named test per rule and boundary),
`tests/listen_port_exhaustive.rs` (every `u16`, every decimal up to 99999,
every leading-zero and signed spelling) and `tests/proptest_listen_port.rs`
(arbitrary text against a reference built from `std` alone).
- `tests/listen_port_clap_kinds.rs` pins which clap `ErrorKind` and which exit
status each kind of bad command line gets, so a clap upgrade that changes one
fails by name.
- A Kani proof (`cargo kani`) that `try_new` is right for every `u16`, and the
fuzz target `fuzz_listen_port_parse` against the same `std` reference.
### Compile-time invariants
`tests/static_assertions_invariants.rs` pins what a runtime test cannot. It
fails the build, not a test, when `AppState`, `SarifStore`, `LoadedLog` or the
router lose `Send + Sync`; when `SarifStore` becomes `Clone` (a copy would fork
the state); when an error type stops satisfying
`Error + Debug + Display + Send + Sync`; or when a field the exporters depend on
is renamed.
### Model checking, undefined behaviour and concurrency
```bash
bash tests/scripts/test_kani.sh # 8 proofs: 7 in src/verification.rs, 1 in src/listen_port.rs
bash tests/scripts/test_miri.sh # pure-logic modules under Miri
bash tests/scripts/test_loom.sh # every interleaving of the shared state
```
Kani proves properties for all inputs up to a bound; the harnesses sit behind
`#[cfg(kani)]` and cost nothing in a normal build. Miri runs the pure-logic unit
tests under the Rust abstract machine with strict provenance. The Loom models
live in the standalone `loom-harness/` crate, because `--cfg loom` breaks
tokio's `net` module; they model the store and the connection limiter and
include an executable negative control.
### Mutation testing
```bash
bash tests/scripts/test_cargo_mutants.sh
```
Line coverage proves a line ran; a mutation score proves a test notices when it
misbehaves. The runner scores with `jaq` against a minimum of 90%. It copies the
tree into a sandbox first, because cargo-mutants copies the tree once per job. A
whole-crate run takes hours; scope it with `--file` while working on one module.
Every surviving mutant is either a missing test or dead code.
### CLI contract tests
`tests/cli_contract.rs` drives the real binary with `assert_cmd`. For a command
line, the exit code, the stream a message goes to and the files left on disk are
the API, so the tests pin all three: `validate` on valid, invalid, malformed and
missing files; `export` and its sidecars; `--overwrite`; and `--self-update`
refused by `--no-self-update` and by `SARIF_NO_SELF_UPDATE`.
### Golden transcripts (trycmd)
`tests/cli_transcripts.rs` replays `tests/cmd/*.trycmd`: the full `--help` texts
and the port-refusal messages with their exit status. A reworded help text or
message is a diff to review, never silent drift. `trycmd` is a test library
(`cargo install trycmd` fails); it is a dev-dependency with only the
`filesystem` and `diff` features. Bless only after reading the diff, and only
the one test, so the two controls (a correct transcript passes, a drifted one
fails) keep running unblessed:
```bash
TRYCMD=overwrite cargo test --test cli_transcripts -- cli_transcripts
```
### Live listen-port test (nmap, rustscan, lsof)
```bash
bash tests/scripts/test_listen_ports_live.sh # debug build
bash tests/scripts/test_listen_ports_live.sh --release
bash tests/scripts/test_listen_ports_live.sh --evidence-root target/ip-ports
```
It builds the viewer, takes an nmap baseline of ports 1-1024, then proves from
outside, on `127.0.0.1` only, that every refused port (as a flag, as a variable,
for both ports) exits 64 without binding anything and without creating a file,
that accepted ports serve `GET /` and show up in nmap and rustscan, that lsof
sees exactly the expected TCP and UDP sockets, and that nothing is left after
SIGTERM. Each run gets a private `HOME`. Evidence (every scanner output and
verdict) goes to `documentation/rust/ip-ports/<UTC>/`. A missing scanner is a
failure unless `--allow-missing-scanners` turns it into explicit SKIPs. The bats
sibling runs the script against a fake app with planted defects to show that its
checks can fail. The script needs nmap, rustscan, lsof and curl.
### Benchmarks
```bash
bash tests/scripts/test_cargo_criterion.sh # quick smoke run
bash tests/scripts/test_cargo_criterion.sh --full # full sampling + HTML
```
`benches/pipeline.rs` times each stage a file passes through: validation, the
model, export per format, PDF rendering, the checksum digests, HTML escaping and
the store. The HTML report is `target/criterion/report/index.html`. Criterion
measures wall-clock time, which is noisy on a loaded machine; compare runs on an
idle one.
### Bruno API tests
```bash
sarif-viewer serve --port 8580 &
test/bruno/run.sh development
```
The requests under `test/bruno/collections/` cover the pages, the actions, the
lifecycle, the upload route (`upload/`: `303`, `422`, `400`, `403`, `405`), the
security headers and the static assets. A file named in `@file(...)` is resolved
relative to the `collections` directory. The `info` collection has
one request per Info-menu entry.
### Browser tests
`test/playwright/` drives the viewer in a real browser: navigation, the theme
toggle, the dashboard, the upload flow, the lifecycle and the security headers.
Specs run in parallel against one server, so a test must assert on the log it
created, never on a count of all logs.
```bash
test/playwright/run.sh
```
## Testing workflow
- Unit tests live beside the code in `#[cfg(test)]` modules.
- `tests/test_routes.rs` drives `SharedRouter::handle_parts` over every route.
- `tests/test_path_security.rs` is the path-traversal regression corpus.
- `tests/self_update_is_mandatory.rs` stops compiling if the updater is ever put
behind a cargo feature.
- Write the test first and watch it fail for the right reason. A test that has
never been red proves nothing.
- A test must be able to fail when the behaviour it guards changes. If a
mutation of the code leaves the suite green, the suite is missing a test.
## README mirrors
`README.md` is the source of truth; `LIESMICH.md` (German), `LISEZMOI.md`
(French), `LEEME.md` (Spanish) and `LEGGIMI.md` (Italian) mirror it. A change to
the README is made in all five files in the same commit. What must stay
identical is the structure, not the prose: heading count, levels and order, the
fenced code blocks byte for byte, the inline code spans and the link targets.
Comments inside code blocks stay in English in every file, so a translated
comment can never make the byte-identity check fail.
```bash
bash skills/readme/scripts/check_translation_mirrors.sh
```
The check verifies structure only; read the translation once end to end, because
a green check does not prove that a sentence still says what it said. The wording
rules (register, anglicisms, typography) are in `skills/liesmich`,
`skills/lisezmoi`, `skills/leeme` and `skills/leggimi`.
## Contribution checklist
- [ ] `cargo fmt`, `cargo clippy ... -D warnings`, `cargo test` (including
`--doc`) clean.
- [ ] New `std::fs` call sites confined to `cap-std` or annotated
`// allow-std-fs: <reason>`.
- [ ] New suppressions use `#[expect(lint, reason = "...")]`.
- [ ] `CHANGELOG.md` updated.
- [ ] Docs updated: this guide, the other guides, `REFERENCE.md`, and every
README mirror (`README.md`, `LIESMICH.md`, `LISEZMOI.md`, `LEEME.md`,
`LEGGIMI.md`) with the mirror check passing.
- [ ] New parsers and guards have a fuzz target and, where there is a clean
invariant, a `proptest` property.
- [ ] A new Info page is added to `INFO_MENU`, `DOC_PAGES`, the `Cargo.toml`
`include` list and the Bruno collection.