diff --git a/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md b/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md new file mode 100644 index 00000000..49171360 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-13-rust-r0-verify.md @@ -0,0 +1,58 @@ +# CONTRACT — Rust R0 foundation (whole phase, for the fresh verifier) +- date: 2026-10-13 | flow: ad-hoc phase (owner go 2026-10-12, BDR-045) | branch: feature/rust-r0-foundation (base develop = 5fec065) +- status: active (amended 2026-10-13 after verifier pass 1: criteria 10 and 14 oracles counted comment lines; CHECKs tightened, no code change) +- spec: docs/development/RUST_ARCHITECTURE_REVIEW.md (Part III, Annex B, Annex C), docs/development/RUST.md (what was built and proven) +- evidence logs (runs made by the orchestrator on this host, readable): /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/{pnpm-check.log,worker-test-build-5.log,worker-image-build-2.log,builder-build-2.log} + +## REQUEST (owner brief 2026-10-12, condensed — IMMUTABLE) +Implement R0 per Annex B: Cargo workspace with crates core, wasm, worker; pinned Rust and dependencies; reproducible Docker builder (no Rust on the VPS); native and WebAssembly compilation; working TypeScript bindings; JSON contracts compatible with the current data; first wasm size and performance measurements; applicable security and isolation tests; CI integration; development and deployment documentation. The seven proofs run in the real environment where possible (serialisation, wasm panics, musl, seccomp verified experimentally; a proof that cannot be obtained is reported, not assumed). Compatibility: the React app, Report v3, PDF v2/v3, Supabase, the interfaces and the existing tests stay unchanged; the frontend does not load the module. No migration of anatomy, PDF or business validations (R2–R5); no avatar business processing (R1). Everything dockerised; production images built in CI and pulled by the VPS; live deployment unchanged; no tag or merge into main. + +## ACCEPTANCE CRITERIA +1. Workspace with exactly three crates, toolchain pinned identically in the three places. + CHECK: grep -c '"crates/core", "crates/wasm", "crates/worker"' Cargo.toml; grep -c 'channel = "1.99.0"' rust-toolchain.toml; grep -c "FROM rust:1.99.0-bookworm" docker/rust-builder.Dockerfile; grep -c "FROM rust:1.99.0-alpine3.24" crates/worker/Dockerfile; ls crates + EXPECT: 1 ; 1 ; 1 ; 1 ; core wasm worker +2. wasm-bindgen crate and CLI locked to one version, refused up front on mismatch. + CHECK: grep -c 'wasm-bindgen = "=0.2.129"' Cargo.toml; grep -c "WASM_BINDGEN_VERSION=0.2.129" docker/rust-builder.Dockerfile; grep -c 'lock_version" != "$cli_version"' docker/wasm-build.sh + EXPECT: 1 ; 1 ; 1 +3. The core takes ids, time and bytes as inputs: no I/O, clock or env in crates/core/src, lint-enforced. + CHECK: grep -rn "std::fs\|std::env\|std::time\|SystemTime\|Instant::now" crates/core/src | wc -l; grep -c "disallowed_methods = \"deny\"" Cargo.toml; grep -c "std::fs::read\|std::env::var\|SystemTime::now" clippy.toml; grep -c "^serde\|^serde_json\|^ts-rs" crates/core/Cargo.toml + EXPECT: 0 ; 1 ; >= 3 ; 3 +4. JSON contract: preserve_order and float_roundtrip enabled; the JavaScript number formatter and the pretty formatter exist with their unit tests. + CHECK: grep -c '"preserve_order", "float_roundtrip"' Cargo.toml; grep -c "pub fn js_number\|pub struct JsPrettyFormatter\|pub fn to_js_pretty\|pub fn pretty_js_round_trip" crates/core/src/json.rs; bash docker/rust-run.sh cargo test -p faunosteo-core --locked 2>&1 | grep -E "^test result" | head -2 + EXPECT: 1 ; 4 ; two lines "ok. 10 passed" and "ok. 2 passed" +5. Report contract types mirror the Zod rules: optional fields skipped when None, nullable field plain Option, Unresolved = literal true; committed ts-rs types equal a fresh export. + CHECK: grep -c 'skip_serializing_if = "Option::is_none"' crates/core/src/domain/report.rs; grep -c "pub version_id: Option" crates/core/src/domain/report.rs; grep -c 'ts(optional, type = "true")' crates/core/src/domain/report.rs; bash docker/rust-run.sh cargo test -p faunosteo-core --features ts --locked 2>&1 | grep -c "test result: ok"; git diff --exit-code -- packages/core-wasm/types && echo SAME + EXPECT: 5 ; 1 ; 1 ; >= 1 ; SAME +6. Browser facade exposes exactly core_version, call, panic_for_test, recurse_for_test; the loader never imports pkg statically; every proof file skips when pkg is absent. + CHECK: grep -c "^pub fn core_version\|^pub fn call\|^pub fn panic_for_test\|^pub fn recurse_for_test" crates/wasm/src/lib.rs; grep -c "^import .* from '../pkg" packages/core-wasm/src/index.ts; grep -l "describe.skipIf(!coreBuilt)" packages/core-wasm/tests/*.test.ts | wc -l + EXPECT: 4 ; 0 ; 4 +7. The wasm proofs pass on the built module (byte equality with JSON.stringify on the four documents, number corpus, Zod readers, panic and stack traps, fresh-instance recovery, size budget). + CHECK: ls packages/core-wasm/pkg/faunosteo_wasm_bg.wasm; corepack pnpm --filter @faunosteo/core-wasm test:run 2>&1 | grep -E "Tests |Test Files"; grep -c "float_roundtrip\|memory access out of bounds\|wasm-unsafe-eval" docs/development/RUST.md + EXPECT: file exists (built by the orchestrator; if absent run `pnpm wasm:build` first) ; "4 passed" and "14 passed" ; >= 3 +8. Worker process model: plain main without an async runtime; decode checks the environment, then the thread count, then rlimits, then seccomp, before reading input. + CHECK: grep -c "tokio" crates/worker/Cargo.toml; grep -n "vars_os().next().is_some()\|sandbox::apply(\|read_to_end(&mut input)" crates/worker/src/decode.rs | head -3; grep -n "ensure_single_thread()?;\|set_rlimits(limits)?;\|install_seccomp()?;" crates/worker/src/sandbox.rs | head -3 + EXPECT: 0 ; the three lines appear in that order (env check line < sandbox line < read line) ; the three calls appear in that order +9. seccomp allowlist is the traced set plus the abort path, denies every file and process syscall, and was derived and proven on the musl binary. + CHECK: sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; sed -n '/^pub const ABORT_PATH_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; grep -c "open\|execve\|clone\|socket" <(sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs); grep -E "test result: ok. 13 passed|allowlist covers the trace" /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/worker-test-build-5.log | sed -E 's/^#[0-9]+ [0-9.]+ //' | sort -u + EXPECT: 7 ; 7 ; 0 ; both lines present +10. The keyed parent never decodes: spawn.rs and webp_check.rs use no image decoder; output capped at 512 KiB; the RIFF check allowlists four chunk types and refuses the rest. + CHECK: grep -c "image::" crates/worker/src/spawn.rs crates/worker/src/webp_check.rs; grep -c "MAX_OUTPUT_BYTES: usize = 512 \* 1024" crates/worker/src/limits.rs; grep -c 'b"VP8X", b"VP8 ", b"VP8L", b"ALPH"' crates/worker/src/webp_check.rs; grep -c "return Err(WebpIssue::ForbiddenChunk(fourcc))" crates/worker/src/webp_check.rs + EXPECT: 0 for both files ; 1 ; 1 ; 1 +11. libwebp confined to the child and its version controlled: FFI only in decode.rs with SAFETY comments, minimum 1.6.0 checked by a test and by `run --check`. + CHECK: grep -l "libwebp_sys::" crates/worker/src/*.rs; grep -c "// SAFETY:" crates/worker/src/decode.rs; grep -c "MIN_LIBWEBP_VERSION: (u8, u8, u8) = (1, 6, 0)" crates/worker/src/limits.rs; grep -c "the_linked_libwebp_is_recent_enough" crates/worker/tests/sandbox.rs + EXPECT: crates/worker/src/decode.rs only ; >= 4 ; 1 ; 1 +12. Test hooks never ship: release build without features; the runtime image is distroless static, non-root, with `run --check` as its command. + CHECK: grep -n "cargo build -p faunosteo-worker --release --locked" crates/worker/Dockerfile | grep -c "features"; grep -c "FROM gcr.io/distroless/static-debian12:nonroot" crates/worker/Dockerfile; grep -c "^USER nonroot" crates/worker/Dockerfile; grep -c 'CMD \["run", "--check"\]' crates/worker/Dockerfile; tail -1 /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/worker-image-build-2.log + EXPECT: 0 ; 1 ; 1 ; 1 ; exit=0 +13. Frontend, live deployment and database untouched; the existing suites still pass. + CHECK: git diff --stat 5fec065..HEAD -- apps/app Dockerfile docker-compose.yml docker/nginx.conf docker/entrypoint.sh supabase packages/domain packages/anatomy packages/pdf packages/supabase | wc -l; tail -1 /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/pnpm-check.log; grep -E "apps/app test:run:\s+Tests|packages/pdf test:run:\s+Tests|packages/anatomy test:run:\s+Tests" /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/pnpm-check.log + EXPECT: 0 ; exit=0 ; 278, 137, 130 passed +14. CI: rust job before check through the builder image with the types drift check; docker job builds the worker test stage and starts the runtime image read-only with every capability dropped; advisories nightly; release-images manual only and deploys nothing. + CHECK: grep -c "needs: rust" .gitea/workflows/ci.yml; grep -c "docker/rust-check.sh\|git diff --exit-code -- packages/core-wasm/types" .gitea/workflows/ci.yml; grep -c -- "--target test\|--read-only --cap-drop ALL" .gitea/workflows/ci.yml; grep -v "^#" .gitea/workflows/release-images.yml | grep -c "^ workflow_dispatch:"; grep -v "^#" .gitea/workflows/release-images.yml | grep -cE "^\s*(push|pull_request|schedule):|ssh |scp |compose (up|pull)"; grep -c "cron:" .gitea/workflows/rust-advisories.yml + EXPECT: 1 ; 2 ; 2 ; 1 ; 0 ; 1 +15. Docs: RUST.md carries the seven proofs with numbers and the hypothetical list; DEPLOY.md carries the prepared digest procedure and the CSP note while the live procedure stays; CLAUDE.md, WORKSPACE.md, TEST_STRATEGY.md, packages/README.md, CHANGELOG updated. + CHECK: grep -c "^### 5\.[1-7]" docs/development/RUST.md; grep -c "^## 7. What stays hypothetical" docs/development/RUST.md; grep -c "^## Image deploy by digest (prepared at R0, not yet applied)" DEPLOY.md; grep -c "docker compose up --build -d" DEPLOY.md; grep -c "wasm-unsafe-eval" DEPLOY.md; grep -c "pnpm rust:check" CLAUDE.md; grep -c "crates/worker" docs/development/WORKSPACE.md; grep -c "Worker sandbox" docs/development/TEST_STRATEGY.md; grep -c "core-wasm" packages/README.md; grep -c "Rust foundation, plan R0" CHANGELOG.md + EXPECT: 7 ; 1 ; 1 ; >= 2 (live procedure kept) ; >= 2 ; >= 1 ; >= 1 ; 1 ; >= 1 ; 1 +16. No secret and no credential in the new files; the worker's env check and the CI secrets usage are the only places naming keys. + CHECK: git diff 5fec065..HEAD | grep -E "^\+" | grep -Ei "eyJ[a-zA-Z0-9_-]{20,}|sk_live|service_role_key *= *\"[^\"]+\"|password *= *\"" | wc -l; grep -c "secrets.REGISTRY_TOKEN" .gitea/workflows/release-images.yml + EXPECT: 0 ; 1 diff --git a/.gitea/workflows/release-images.yml b/.gitea/workflows/release-images.yml index 64b9b8a2..88099ecb 100644 --- a/.gitea/workflows/release-images.yml +++ b/.gitea/workflows/release-images.yml @@ -1,7 +1,16 @@ # Production images, built in CI and identified by digest (D-R13, owner amendment of # 2026-10-12): the VPS pulls them and never compiles. Manual only (workflow_dispatch), never # on push: no publication or promotion of a production image without an explicit run and -# a validation. Nothing here deploys; DEPLOY.md "Image deploy (prepared)" is the runbook. +# a validation. Nothing here deploys; DEPLOY.md "Image deploy by digest (prepared at R0, not +# yet applied)" is the runbook. +# +# Hardening (security audit of R0): the dispatch input is a typed choice re-validated in +# the shell through an environment variable (never interpolated into a script); secrets +# reach the shell through env only, the registry login lives in a per-job DOCKER_CONFIG +# removed at the end; images are built by an ephemeral buildx builder with its own cache, +# so nothing a PR build left in the daemon's cache mounts or volumes can reach a release +# image; the RustSec advisories gate runs before any push; only main and develop may be +# released; the checkout action is pinned to a commit. # # Secrets expected on the forge: REGISTRY (host, e.g. the Gitea container registry of this # forge), REGISTRY_USER, REGISTRY_TOKEN (write:package scope). Images are pushed as @@ -14,25 +23,55 @@ on: inputs: sheet_bundle: description: 'SHEET_BUNDLE for the app image (none = production default, draft = preview)' - required: false - default: 'none' + required: true + type: choice + options: + - none + - draft + default: none jobs: images: + if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' runs-on: ubuntu-latest + env: + SHEET_BUNDLE: ${{ inputs.sheet_bundle }} + REGISTRY: ${{ secrets.REGISTRY }} + REGISTRY_USER: ${{ secrets.REGISTRY_USER }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + NAMESPACE: ${{ github.repository_owner }} + GIT_SHA: ${{ github.sha }} steps: - - uses: actions/checkout@v4 - - name: Registry login - run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ secrets.REGISTRY }}" -u "${{ secrets.REGISTRY_USER }}" --password-stdin + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Validate the dispatch input (the shell trusts the env value only after this) + run: | + case "$SHEET_BUNDLE" in + none|draft) ;; + *) echo "refused SHEET_BUNDLE value" >&2; exit 1 ;; + esac + - name: RustSec advisories gate (release only; CI runs it nightly) + run: | + docker build -f docker/rust-builder.Dockerfile -t faunosteo_rust_builder:1.99.0 docker + bash docker/rust-run.sh cargo deny check advisories + - name: Ephemeral builder with its own cache and a per-job Docker config + run: | + echo "DOCKER_CONFIG=$(mktemp -d)" >> "$GITHUB_ENV" + docker buildx create --name "faunosteo_release_$GIT_SHA" --driver docker-container --use + - name: Registry login (token from env, never on the command line) + run: printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin - name: Build and push the application image run: | - image="${{ secrets.REGISTRY }}/${{ github.repository_owner }}/faunosteo_app:${{ github.sha }}" - docker build --build-arg SHEET_BUNDLE="${{ github.event.inputs.sheet_bundle }}" -t "$image" . - docker push "$image" - echo "app: $(docker inspect --format='{{index .RepoDigests 0}}' "$image")" >> "$GITHUB_STEP_SUMMARY" + image="$REGISTRY/$NAMESPACE/faunosteo_app:$GIT_SHA" + docker buildx build --push --provenance=false --build-arg "SHEET_BUNDLE=$SHEET_BUNDLE" -t "$image" . + echo "app: $(docker buildx imagetools inspect "$image" --format '{{json .Manifest.Digest}}')" >> "$GITHUB_STEP_SUMMARY" - name: Build and push the worker image run: | - image="${{ secrets.REGISTRY }}/${{ github.repository_owner }}/faunosteo_worker:${{ github.sha }}" - docker build -f crates/worker/Dockerfile -t "$image" . - docker push "$image" - echo "worker: $(docker inspect --format='{{index .RepoDigests 0}}' "$image")" >> "$GITHUB_STEP_SUMMARY" + image="$REGISTRY/$NAMESPACE/faunosteo_worker:$GIT_SHA" + docker buildx build --push --provenance=false -f crates/worker/Dockerfile -t "$image" . + echo "worker: $(docker buildx imagetools inspect "$image" --format '{{json .Manifest.Digest}}')" >> "$GITHUB_STEP_SUMMARY" + - name: Logout, remove the builder and the per-job Docker config + if: always() + run: | + docker logout "$REGISTRY" || true + docker buildx rm "faunosteo_release_$GIT_SHA" || true + rm -rf "$DOCKER_CONFIG" diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index b1d7ff8c..15cbcaa1 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -11,6 +11,12 @@ publish.workspace = true crate-type = ["cdylib", "rlib"] path = "src/lib.rs" +[features] +default = [] +# The R0 trap proofs (panic_for_test, recurse_for_test): built for the proofs, never for the +# module the application ships (docker/wasm-build.sh passes it until R2 wires the real loader). +proofs = [] + [dependencies] faunosteo-core = { path = "../core" } wasm-bindgen.workspace = true diff --git a/crates/wasm/src/lib.rs b/crates/wasm/src/lib.rs index 6ffd632f..7dcafbf9 100644 --- a/crates/wasm/src/lib.rs +++ b/crates/wasm/src/lib.rs @@ -19,17 +19,20 @@ pub fn call(op: &str, input: &str) -> String { /// R0 proof: on wasm32 a panic is a trap (panic = abort), reaching JavaScript as a /// `WebAssembly.RuntimeError`; the caller re-instantiates the module. +#[cfg(feature = "proofs")] #[wasm_bindgen] pub fn panic_for_test() { panic!("deliberate panic for the R0 proof"); } /// R0 proof: exhausting the shadow stack traps instead of corrupting memory. +#[cfg(feature = "proofs")] #[wasm_bindgen] pub fn recurse_for_test(depth: u32) -> u32 { recurse(depth) } +#[cfg(feature = "proofs")] #[inline(never)] fn recurse(depth: u32) -> u32 { let mut frame = [depth; 32]; diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml index 44c32d35..dc9fda62 100644 --- a/crates/worker/Cargo.toml +++ b/crates/worker/Cargo.toml @@ -29,9 +29,10 @@ libc.workspace = true crc32fast = { version = "1.4", optional = true } # The worker owns I/O (it is the process boundary), so the core's disallowed_methods lint is -# off here; unsafe is allowed for the libwebp FFI only, each block carries a SAFETY comment. +# off here. unsafe stays denied crate-wide; the libwebp FFI and the prctl call carry a local +# #[allow(unsafe_code)] with a SAFETY comment each (forbid would not allow the local override). [lints.rust] -unsafe_code = "allow" +unsafe_code = "deny" [lints.clippy] unwrap_used = "deny" diff --git a/crates/worker/Dockerfile b/crates/worker/Dockerfile index 6890654c..6f3b4fd0 100644 --- a/crates/worker/Dockerfile +++ b/crates/worker/Dockerfile @@ -19,13 +19,14 @@ RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/ cargo build -p faunosteo-worker --release --locked \ && cp target/release/faunosteo-worker /faunosteo-worker -# The tests run against the musl binary that ships, inside the default Docker seccomp -# profile (the inner filter is allowed by it). strace serves the allowlist derivation. +# The tests and the derivation run on the release profile (LTO, panic = abort) plus the +# test-hooks feature, inside the default Docker seccomp profile (the inner filter is allowed +# by it): the binary under test differs from the shipped one by the feature-gated hooks only. FROM base AS test RUN apk add --no-cache strace RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/registry \ --mount=type=cache,id=faunosteo_target_musl,target=/w/target \ - cargo test -p faunosteo-worker --features test-hooks --locked -- --test-threads=4 + cargo test -p faunosteo-worker --release --features test-hooks --locked -- --test-threads=4 RUN --mount=type=cache,id=faunosteo_cargo_registry_musl,target=/usr/local/cargo/registry \ --mount=type=cache,id=faunosteo_target_musl,target=/w/target \ sh crates/worker/scripts/derive-seccomp.sh diff --git a/crates/worker/scripts/derive-seccomp.sh b/crates/worker/scripts/derive-seccomp.sh index a1684092..60d946d6 100755 --- a/crates/worker/scripts/derive-seccomp.sh +++ b/crates/worker/scripts/derive-seccomp.sh @@ -9,8 +9,8 @@ # review (the abort path is expected there). set -eu -bin=target/debug/faunosteo-worker -cargo build -p faunosteo-worker --features test-hooks --locked +bin=target/release/faunosteo-worker +cargo build -p faunosteo-worker --release --features test-hooks --locked work=$(mktemp -d) fixtures="png jpeg webp big-jpeg big-png" @@ -18,15 +18,22 @@ fixtures="png jpeg webp big-jpeg big-png" for kind in $fixtures; do "$bin" fixture "$kind" > "$work/$kind.bin" # `env -i`: the child refuses a non-empty environment; `--no-seccomp` keeps the rlimits - # and prints the marker where the filter would be installed. + # and makes one sched_yield where the filter would be installed (strace cannot read the + # child's memory once PR_SET_DUMPABLE is 0, so the marker is a syscall, not a string). env -i strace -f -qq -o "$work/trace.$kind" "$bin" decode --no-seccomp \ < "$work/$kind.bin" > "$work/$kind.webp" - awk 'found { print } /SECCOMP-MARKER/ { found = 1 }' "$work/trace.$kind" \ + awk 'found { print } /sched_yield\(/ { found = 1 }' "$work/trace.$kind" \ | sed -E 's/^[0-9]+ +//; /^(\+\+\+|---)/d; s/^<\.\.\. ([a-z0-9_]+) resumed>.*/\1/; s/\(.*//' \ | grep -E '^[a-z0-9_]+$' >> "$work/traced.raw" || true done sort -u "$work/traced.raw" > "$work/traced.txt" "$bin" print-allowlist | sort -u > "$work/allowed.txt" +if [ ! -s "$work/traced.txt" ]; then + echo "== NO SYSCALL TRACED AFTER THE MARKER: the derivation is broken, not the allowlist" >&2 + echo "== tail of the png trace:" >&2 + tail -n 40 "$work/trace.png" >&2 + exit 1 +fi echo "== syscalls traced after the sandbox marker" cat "$work/traced.txt" diff --git a/crates/worker/src/decode.rs b/crates/worker/src/decode.rs index fab9dedf..3f7b1255 100644 --- a/crates/worker/src/decode.rs +++ b/crates/worker/src/decode.rs @@ -133,6 +133,7 @@ fn map_image_error(error: ImageError) -> Reject { } /// Encodes an RGBA buffer as lossy WebP through libwebp (D-R4: C confined to this process). +#[allow(unsafe_code)] pub fn encode_webp(rgba: &[u8], width: u32, height: u32, quality: f32) -> Result, Reject> { let expected = (width as usize) .checked_mul(height as usize) @@ -164,6 +165,7 @@ pub fn encode_webp(rgba: &[u8], width: u32, height: u32, quality: f32) -> Result } /// Version of the libwebp linked into this binary, as (major, minor, revision). +#[allow(unsafe_code)] pub fn libwebp_version() -> (u8, u8, u8) { // SAFETY: a pure getter of the FFI without arguments or side effects. let packed = unsafe { libwebp_sys::WebPGetEncoderVersion() }; @@ -235,8 +237,11 @@ impl TestHooks { #[cfg(feature = "test-hooks")] fn run_after_sandbox(&self, stdout: &mut dyn Write, stderr: &mut dyn Write) -> Option { if !self.seccomp { - // Marker for crates/worker/scripts/derive-seccomp.sh: syscalls after this line - // are the ones the filter must allow. + // Marker for crates/worker/scripts/derive-seccomp.sh: one `sched_yield`, a syscall + // the decode path never makes, right where the filter would be installed. The + // syscalls after it are the ones the filter must allow. (A string marker is not + // readable by strace once PR_SET_DUMPABLE is 0.) + std::thread::yield_now(); let _ = stderr.write_all(b"SECCOMP-MARKER\n"); } match self.action? { diff --git a/crates/worker/src/exit_codes.rs b/crates/worker/src/exit_codes.rs index fb82a550..570f659d 100644 --- a/crates/worker/src/exit_codes.rs +++ b/crates/worker/src/exit_codes.rs @@ -14,6 +14,12 @@ pub const ENCODE_FAILED: i32 = 16; pub const OUTPUT_FAILED: i32 = 17; pub const INTERNAL: i32 = 18; +/// Codes that judge the content (the upload is refused); every other non-zero code means +/// the child's environment is broken and the parent must alert rather than reject. +pub fn is_content_rejection(code: i32) -> bool { + (INPUT_TOO_LARGE..=OUTPUT_FAILED).contains(&code) +} + /// Stable name of an exit code for logs and tests. pub fn name(code: i32) -> &'static str { match code { diff --git a/crates/worker/src/sandbox.rs b/crates/worker/src/sandbox.rs index 0f52603e..44f080cf 100644 --- a/crates/worker/src/sandbox.rs +++ b/crates/worker/src/sandbox.rs @@ -6,7 +6,10 @@ use std::collections::BTreeMap; use std::fmt; -use seccompiler::{BpfProgram, SeccompAction, SeccompFilter, SeccompRule, TargetArch}; +use seccompiler::{ + BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, + SeccompRule, TargetArch, +}; use crate::limits; @@ -84,6 +87,7 @@ impl std::error::Error for SandboxError {} /// derivation run of the test stage); a release child always passes `true`. pub fn apply(limits: &Limits, seccomp: bool) -> Result<(), SandboxError> { ensure_single_thread()?; + disable_core_dumps()?; set_rlimits(limits)?; if seccomp { install_seccomp()?; @@ -91,6 +95,20 @@ pub fn apply(limits: &Limits, seccomp: bool) -> Result<(), SandboxError> { Ok(()) } +/// No core dump of the child: a dump would hold the uploaded photo (personal data) and +/// could fill the VPS disk (SIGABRT under `RLIMIT_AS`, SIGSYS, SIGXCPU all dump by default). +/// `PR_SET_DUMPABLE 0` is the kernel-side stop, `RLIMIT_CORE 0` the belt. +#[allow(unsafe_code)] +fn disable_core_dumps() -> Result<(), SandboxError> { + // SAFETY: prctl(PR_SET_DUMPABLE, 0) takes no pointer and changes only this process. + let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) }; + if rc != 0 { + return Err(SandboxError::Rlimit("PR_SET_DUMPABLE".to_owned())); + } + rlimit::setrlimit(rlimit::Resource::CORE, 0, 0) + .map_err(|error| SandboxError::Rlimit(format!("RLIMIT_CORE: {error}"))) +} + /// Every syscall name the filter allows, for the derivation script and the tests. pub fn allowed_names() -> Vec<&'static str> { ALLOWED_SYSCALLS @@ -137,12 +155,46 @@ fn set_rlimits(limits: &Limits) -> Result<(), SandboxError> { } /// Builds the BPF program: allow the listed syscalls, kill the process on anything else. +/// +/// Argument filters on the abort path and on `mmap`: `tkill`/`tgkill` may only send SIGABRT +/// to this very process (the child is single-threaded, so tid == pid), never a signal to the +/// keyed parent or a sibling; `mmap` may not map executable memory. pub fn build_filter() -> Result { - let rules: BTreeMap> = ALLOWED_SYSCALLS + let pid = u64::from(std::process::id()); + let sigabrt = u64::try_from(libc::SIGABRT).unwrap_or(6); + let prot_exec = u64::try_from(libc::PROT_EXEC).unwrap_or(4); + let mut rules: BTreeMap> = ALLOWED_SYSCALLS .iter() .chain(ABORT_PATH_SYSCALLS) .map(|(_, number)| (*number, Vec::new())) .collect(); + let seccomp_err = |error: seccompiler::BackendError| SandboxError::Seccomp(error.to_string()); + let eq = |index: u8, value: u64| { + SeccompCondition::new(index, SeccompCmpArgLen::Qword, SeccompCmpOp::Eq, value) + .map_err(seccomp_err) + }; + rules.insert( + libc::SYS_tkill, + vec![SeccompRule::new(vec![eq(0, pid)?, eq(1, sigabrt)?]).map_err(seccomp_err)?], + ); + rules.insert( + libc::SYS_tgkill, + vec![ + SeccompRule::new(vec![eq(0, pid)?, eq(1, pid)?, eq(2, sigabrt)?]) + .map_err(seccomp_err)?, + ], + ); + let no_exec = SeccompCondition::new( + 2, + SeccompCmpArgLen::Qword, + SeccompCmpOp::MaskedEq(prot_exec), + 0, + ) + .map_err(seccomp_err)?; + rules.insert( + libc::SYS_mmap, + vec![SeccompRule::new(vec![no_exec]).map_err(seccomp_err)?], + ); let filter = SeccompFilter::new( rules, SeccompAction::KillProcess, @@ -150,9 +202,7 @@ pub fn build_filter() -> Result { target_arch()?, ) .map_err(|error| SandboxError::Seccomp(error.to_string()))?; - filter - .try_into() - .map_err(|error: seccompiler::BackendError| SandboxError::Seccomp(error.to_string())) + filter.try_into().map_err(seccomp_err) } fn install_seccomp() -> Result<(), SandboxError> { diff --git a/crates/worker/src/spawn.rs b/crates/worker/src/spawn.rs index 0aaf52a3..3cde1f12 100644 --- a/crates/worker/src/spawn.rs +++ b/crates/worker/src/spawn.rs @@ -17,8 +17,12 @@ use crate::{exit_codes, webp_check}; pub enum ChildOutcome { /// A 512 × 512 WebP whose container passed the parent's check. Produced(Vec), - /// The child refused the input with one of its exit codes. + /// The child refused the input with one of its content exit codes (12 to 17). Rejected { code: i32, name: &'static str }, + /// The child could not even start properly (usage, non-empty environment, sandbox + /// failure, internal error): the confinement environment is broken, not the upload. + /// R1 alerts and stops on this outcome instead of rejecting the job. + Broken { code: i32, name: &'static str }, /// The child died from a signal (SIGSYS 31 = seccomp, SIGABRT 6 = allocation failure, /// SIGXCPU 24 = CPU limit, SIGKILL 9 = the parent). Signalled { signal: i32 }, @@ -30,7 +34,8 @@ pub enum ChildOutcome { Failed(String), } -/// A finished child run. +/// A finished child run. `stderr` is text the child controls (up to 4 KiB): never logged +/// raw by R1, control characters escaped and the field allowlist applied (LRN-044). #[derive(Debug)] pub struct ChildRun { pub outcome: ChildOutcome, @@ -124,7 +129,11 @@ impl Spawner { } std::thread::sleep(Duration::from_millis(20)); } - Err(error) => return failed(format!("wait: {error}")), + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + return failed(format!("wait: {error}")); + } } }; let _ = writer.join(); @@ -150,7 +159,11 @@ fn classify(status: ExitStatus, output: Vec) -> ChildOutcome { Ok(_) => ChildOutcome::Produced(output), Err(issue) => ChildOutcome::Failed(format!("output refused: {issue}")), }, - Some(code) => ChildOutcome::Rejected { + Some(code) if exit_codes::is_content_rejection(code) => ChildOutcome::Rejected { + code, + name: exit_codes::name(code), + }, + Some(code) => ChildOutcome::Broken { code, name: exit_codes::name(code), }, diff --git a/crates/worker/src/webp_check.rs b/crates/worker/src/webp_check.rs index cd0f96c4..0fc9457e 100644 --- a/crates/worker/src/webp_check.rs +++ b/crates/worker/src/webp_check.rs @@ -79,13 +79,20 @@ pub fn inspect(bytes: &[u8]) -> Result { if !ALLOWED_CHUNKS.contains(&&fourcc) { return Err(WebpIssue::ForbiddenChunk(fourcc)); } - if dimensions.is_none() { - dimensions = match &fourcc { - b"VP8X" => Some(parse_vp8x(payload)?), - b"VP8 " => Some(parse_vp8(payload)?), - b"VP8L" => Some(parse_vp8l(payload)?), - _ => None, - }; + let declared = match &fourcc { + b"VP8X" => Some(parse_vp8x(payload)?), + b"VP8 " => Some(parse_vp8(payload)?), + b"VP8L" => Some(parse_vp8l(payload)?), + _ => None, + }; + // The canvas (VP8X) and the frame (VP8 / VP8L) must agree: a container whose frame + // disagrees with its canvas is not something the encoder produces. + match (dimensions, declared) { + (None, Some(size)) => dimensions = Some(size), + (Some(canvas), Some(frame)) if canvas != frame => { + return Err(WebpIssue::BadBitstream); + } + _ => {} } chunks.push(fourcc); offset = end + (size & 1); @@ -164,11 +171,25 @@ mod tests { #[test] fn a_square_vp8x_file_passes() { - let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"VP8 ", &[0; 20])]); + let mut vp8 = vec![0u8; 20]; + vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]); + vp8[6..8].copy_from_slice(&512u16.to_le_bytes()); + vp8[8..10].copy_from_slice(&512u16.to_le_bytes()); + let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"VP8 ", &vp8)]); let summary = expect_square(&bytes, 512); assert_eq!(summary.map(|s| (s.width, s.height)), Ok((512, 512))); } + #[test] + fn a_frame_disagreeing_with_its_canvas_is_refused() { + let mut vp8 = vec![0u8; 10]; + vp8[3..6].copy_from_slice(&[0x9d, 0x01, 0x2a]); + vp8[6..8].copy_from_slice(&256u16.to_le_bytes()); + vp8[8..10].copy_from_slice(&512u16.to_le_bytes()); + let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"VP8 ", &vp8)]); + assert_eq!(inspect(&bytes), Err(WebpIssue::BadBitstream)); + } + #[test] fn metadata_chunks_are_refused() { let bytes = riff(&[(b"VP8X", &vp8x(512, 512)), (b"EXIF", b"x")]); @@ -177,7 +198,7 @@ mod tests { #[test] fn wrong_sizes_are_refused() { - let bytes = riff(&[(b"VP8X", &vp8x(511, 512)), (b"VP8 ", &[0; 20])]); + let bytes = riff(&[(b"VP8X", &vp8x(511, 512))]); assert_eq!( expect_square(&bytes, 512), Err(WebpIssue::Dimensions { diff --git a/docker/wasm-build.sh b/docker/wasm-build.sh index c2f6c840..a8844045 100755 --- a/docker/wasm-build.sh +++ b/docker/wasm-build.sh @@ -14,7 +14,8 @@ if [ "$lock_version" != "$cli_version" ]; then exit 1 fi -cargo build -p faunosteo-wasm --release --target wasm32-unknown-unknown --locked +# `proofs`: the R0 trap exports; dropped when R2 builds the module the application ships. +cargo build -p faunosteo-wasm --release --target wasm32-unknown-unknown --locked --features proofs out=packages/core-wasm/pkg rm -rf "$out" diff --git a/docs/development/RUST.md b/docs/development/RUST.md index 9b9b63cd..10fec644 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -89,9 +89,13 @@ a plain `main` (no async runtime, no thread), so `decode` installs its sandbox in a single-threaded process: - `decode`: refuses a non-empty environment; checks `Threads: 1` in - `/proc/self/status`; `RLIMIT_AS` 512 MiB, `RLIMIT_CPU` 10 s soft / 12 s - hard (soft = hard made the kernel SIGKILL first, finding §5.4); seccomp - allowlist installed with TSYNC, `KillProcess` on anything else; then reads + `/proc/self/status`; disables core dumps (`PR_SET_DUMPABLE 0`, + `RLIMIT_CORE 0`: a dump would hold the uploaded photo); `RLIMIT_AS` + 512 MiB, `RLIMIT_CPU` 10 s soft / 12 s hard (soft = hard made the kernel + SIGKILL first, finding §5.4); seccomp allowlist installed with TSYNC, + `KillProcess` on anything else, with argument filters: `tkill`/`tgkill` + may only send SIGABRT to the child's own pid (never a signal to the keyed + parent or a sibling), `mmap` may not map `PROT_EXEC`; then reads ≤ 5 MiB on stdin, sniffs the format (JPEG, PNG, WebP), decodes with `image::Limits` (sides ≤ 4096, alloc 256 MiB), applies the EXIF orientation, `resize_to_fill` 512 × 512, encodes lossy WebP (q 82) through @@ -100,11 +104,16 @@ sandbox in a single-threaded process: - the parent side (`spawn::Spawner`, used by the tests now and by R1): `env_clear`, stdin/stdout/stderr piped, output read up to 512 KiB (the child is killed past it), 20 s deadline, classification of every exit - (`Produced`, `Rejected{code}`, `Signalled{signal}`, `OutputOverflow`, - `Timeout`, `Failed`). The parent **never decodes**: `webp_check::inspect` - parses the RIFF container only (chunk allowlist `VP8X`, `VP8 `, `VP8L`, - `ALPH`; canvas size from the headers; any `EXIF`, `XMP `, `ICCP` or unknown - chunk refuses the output; owner amendment of D-R4). + (`Produced`, `Rejected{code}` for the content codes 12 to 17, + `Broken{code}` when the child could not even start (usage, non-empty + environment, sandbox failure, internal: R1 alerts instead of blaming the + upload), `Signalled{signal}`, `OutputOverflow`, `Timeout`, `Failed`). The + parent **never decodes**: `webp_check::inspect` parses the RIFF container + only (chunk allowlist `VP8X`, `VP8 `, `VP8L`, `ALPH`; canvas size from the + headers, the frame size must agree with the canvas; any `EXIF`, `XMP `, + `ICCP` or unknown chunk refuses the output; owner amendment of D-R4). The + child's stderr (≤ 4 KiB) is child-controlled text: R1 never logs it raw + (LRN-044). - `run --check`: prints the resolved configuration without secrets (which variables are set, the linked libwebp version, refused below 1.6.0). A plain `run` does nothing before R1 and says so. @@ -116,7 +125,9 @@ sandbox in a single-threaded process: `print-allowlist`. Image: `crates/worker/Dockerfile`, stages `build` (release, static), -`test` (sandbox tests + `scripts/derive-seccomp.sh`), `runtime` +`test` (sandbox tests and `scripts/derive-seccomp.sh` on the **release +profile** with the `test-hooks` feature, so the binary under test differs +from the shipped one by the feature-gated hooks only), `runtime` (`gcr.io/distroless/static-debian12:nonroot`, `USER nonroot`, `ENTRYPOINT /faunosteo-worker`, `CMD run --check`). Measured 2026-10-12: image 8.7 MB (one static binary), `run --check` exits 0 with `--read-only --cap-drop ALL @@ -134,9 +145,15 @@ binary), `run --check` exits 0 with `--read-only --cap-drop ALL started once with `--read-only --cap-drop ALL`. - `rust-advisories.yml`: nightly and manual `cargo deny check advisories`, out of the blocking path on purpose. -- `release-images.yml`: manual only; builds and pushes `faunosteo_app:` - and `faunosteo_worker:` to the registry of the `REGISTRY` secret and - prints their digests. Deploys nothing (DEPLOY.md "Image deploy by digest"). +- `release-images.yml`: manual only, on `main` or `develop`; the dispatch + input is a typed choice re-validated through an environment variable; + the RustSec advisories gate runs first; an ephemeral `buildx` builder with + its own cache builds the images (nothing a PR build left in the daemon's + cache mounts or volumes can reach a release image); secrets reach the + shell through env only, the login lives in a per-job `DOCKER_CONFIG` + removed at the end; `actions/checkout` pinned to a commit. It pushes + `faunosteo_app:` and `faunosteo_worker:` and prints their + digests. Deploys nothing (DEPLOY.md "Image deploy by digest"). Not measured here: the forge runner's cache behaviour and cold build times (the runner was not available from this host). The builder image build took @@ -196,8 +213,8 @@ static binary. neither `brk` nor `mprotect`; no `futex` in a single-threaded decode. The allowlist is that set plus the abort path (`rt_sigaction`, `rt_sigprocmask`, `getpid`, `gettid`, `tkill`, `tgkill`, `exit`). -- Proven on the musl binary that ships, inside Docker's default seccomp - profile: 13 tests green (`png_jpeg_and_webp_decode_through_the_full_sandbox`, +- Proven on the release-profile musl binary with the test hooks, inside + Docker's default seccomp profile: 13 tests green (`png_jpeg_and_webp_decode_through_the_full_sandbox`, `inputs_at_the_caps_decode_within_the_limits` (4096²), dimensions 32 px and 20 000² header, GIF and SVG refused, truncated PNG, non-empty environment refused, `--violate` → SIGSYS 31, `--flood` → output cut, @@ -249,6 +266,13 @@ CHROME= bash docker/csp-proof/run.sh # §5.5 (playwright-core ## 7. What stays hypothetical after R0 +- Follow-ups from the R0 security audit, owned by R1 unless stated: base + images pinned by digest in the three Dockerfiles (today by tag, as the + existing `Dockerfile`); a verification decode of the child's output in a + second sandboxed child (the RIFF check validates the container, not the + bitstream); the shared BuildKit cache mounts of the CI builds (the + release workflow already uses its own builder); `actions/*@v4` tags in + `ci.yml` (pre-existing practice) to pin by commit at Step 27. - The browser-side fresh-instance mechanism (static glue URL with a cache-busting query under Vite, or a Worker per instance) is designed, not built: R2 builds and tests it.