readings-window
aien-dev/readings-window
Brought by drakestapleton
GitHub aien-dev/readings-window#11 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/readings-window/patches/37a23293d272cf1c.bundle -o 37a23293d272cf1c.bundle git fetch 37a23293d272cf1c.bundle refs/pull/11/head
Provenance
github-import 1
aien-dev/readings-window
11
908ba5de5e0ba46064a97dec19c1373ffb9e145d
{"kind":"github-import","owner":"aien-dev","repo":"readings-window","number":11,"url":"https://github.com/aien-dev/readings-window/pull/11","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:28Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..86b5e83 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,72 @@ +# readings-window (read-only HTTPS window onto the Spark's GPU and CPU readings) + +> A small Rust service that runs on the project's Raspberry Pi house server. `readings-window collect` fetches one JSON line of readings from the DGX Spark over ssh and keeps 30 days of history; `readings-window serve` hands the readings, cached status and results files, the exposure-watch result and the agent chat feeds to anyone holding the bearer token, over HTTPS on port 9443. `scripts/` holds the exposure watch, a shell script and systemd timer that scans the house's own public IP. There is no CI in this repository. + +Shared rules: read https://www.aienos.com/agents/RULES.md first. This file adds what is specific to this repository; where the two differ, this file wins here. + +## Scope + +- Applies to the whole repository: the crate (`src/main.rs`, `src/tls.rs`) and the exposure watch (`scripts/exposure-watch.sh`, `.service`, `.timer`). +- The service is read-only by design. It serves files and runs fixed read commands on the Spark; it never writes to the Spark and never accepts uploads. Keep it that way. +- Not in this repository: the Spark-side `spark-readings` script, the `readings-collect` timer and `readings-window` service units on the Pi, the token, the TLS key and certificate, and the exposure baseline. `NOTES.md` describes where they live. +- `target/` and `.crumb.local` are ignored (`.gitignore`). Never commit them. + +## Installation + +```bash +git clone https://github.com/aien-dev/readings-window.git +cd readings-window +cargo build --release +``` + +Needs a stable Rust toolchain only. Dependencies are `rustls` (ring provider, TLS 1.2 and 1.3) and `serde_json`; `rcgen` is a dev-dependency for the TLS tests. No Python. The binary is `target/release/readings-window`. + +## Configuration + +There are no flags, environment variables or config files. Everything is a constant in `src/main.rs`: + +- Pi-side files: token `/etc/readings-window/token`, certificate `/etc/readings-window/fullchain.pem`, key `/etc/readings-window/key.pem`; data under `/var/lib/readings-window/` (`history.jsonl`, `status.json`, `results.json`, `exposure.json`). +- Listen address `0.0.0.0:9443` (`serve`). +- The Spark host addresses (`SPARK_HOSTS`), the ssh key path, the Spark-side status and results files and the agent archive paths (`AGENTS`, five fixed names). Changing one of these is a deployment change; say so in the pull request. +- Limits: history `?hours=` default 24, max 720 (`DEFAULT_HOURS`, `MAX_HOURS`); chat `?lines=` default 500, max 50000; HTTP head cap 16 KiB and at most 64 connections (`src/tls.rs`); history kept 30 days (`KEEP_SECS`). +- The exposure watch reads its baseline from `/etc/exposure-watch/baseline.json` (created on first run) and writes `/var/lib/readings-window/exposure.json`, which `/v1/exposure` serves. + +## Usage + +```bash +# Unit tests (20 tests: request parsing, routes, auth, TLS handshake with a generated cert) +cargo test + +# Lint (clean at the time of writing) +cargo clippy --all-targets + +# Syntax check of the exposure watch +bash -n scripts/exposure-watch.sh +``` + +Running the binary with no argument prints `usage: readings-window collect|serve` and exits 1. Do not run `collect` or `serve` on a development machine: `collect` needs root, the Pi's ssh key and the Spark on the network; `serve` needs the token, key and certificate under `/etc/readings-window/` and binds port 9443. Do not run `scripts/exposure-watch.sh` either: it scans the public IP with `nmap`, queries UPnP and writes under `/etc` and `/var/lib`. All three only make sense on the Pi. + +Endpoints are listed in `README.md`: `/health` needs no token; every `/v1/*` route needs `Authorization: Bearer <token>`. Wrong or missing token gives 401, unknown path 404, non-GET 405. + +## Conventions + +- Keep the dependency set minimal. The hand-written HTTP/1.1 reader in `src/tls.rs` replaced `tiny_http` because it pinned a rustls with a security advisory; do not bring back a framework without a reason in the pull request. +- Nothing user-supplied reaches the remote shell. Agent names are matched exactly against the allow-list and mapped to constant paths; `?lines=` is parsed to an integer and clamped. Keep both properties, and add a test when you touch a route. +- Tests live in `#[cfg(test)]` modules at the bottom of `src/main.rs` and `src/tls.rs`. +- `cargo fmt --check` does not pass on the current tree. Do not reformat files you are not otherwise changing; a formatting-only change belongs in its own pull request. +- Dependency updates for advisories are separate commits that name the advisory (for example `RUSTSEC-2026-0382`). +- Record operational changes (new route, new file, new unit) in `NOTES.md` and the endpoint list in `README.md`. + +## Safety and approvals + +- Never commit the token, TLS key, certificate, ssh keys or the exposure baseline. They exist only on the Pi. +- Never widen what the service exposes (a new route, a new remote command, a write path, auth removed from a route) without explicit approval from the maintainer. +- Ask before changing the listen port, the host list or any path constant; the live Pi deployment depends on them. +- The exposure watch must scan only the house's own public IP. Never point it at another host. +- Deploying to the Pi is out of scope for an agent working from a clone. Merge through a pull request; the maintainer deploys. + +## Further reading + +- `README.md`: endpoints, commands and current status. +- `NOTES.md`: deployment layout on the Pi, unit names, feed history and known unverified points. +- `src/tls.rs`: the TLS listener and HTTP reader, with its limits. diff --git a/Cargo.lock b/Cargo.lock index e103d3d..bc72201 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,22 +3,64 @@ version = 4 [[package]] -name = "ascii" -version = "1.1.0" +name = "asn1-rs" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "base64" -version = "0.13.1" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] -name = "bumpalo" -version = "3.20.3" +name = "bit-vec" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "cc" @@ -37,10 +79,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] -name = "chunked_transfer" -version = "1.5.0" +name = "data-encoding" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] [[package]] name = "find-msvc-tools" @@ -59,12 +132,6 @@ dependencies = [ "wasi", ] -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "itoa" version = "1.0.18" @@ -72,14 +139,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] -name = "js-sys" -version = "0.3.106" +name = "lazy_static" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" @@ -87,24 +150,93 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -124,26 +256,26 @@ dependencies = [ ] [[package]] -name = "readings-window" -version = "0.1.0" +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ - "serde_json", - "tiny_http", + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", ] [[package]] -name = "ring" -version = "0.16.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +name = "readings-window" +version = "0.1.0" dependencies = [ - "cc", - "libc", - "once_cell", - "spin", - "untrusted 0.7.1", - "web-sys", - "winapi", + "rcgen", + "rustls", + "serde_json", ] [[package]] @@ -156,45 +288,51 @@ dependencies = [ "cfg-if", "getrandom", "libc", - "untrusted 0.9.0", + "untrusted", "windows-sys", ] [[package]] -name = "rustls" -version = "0.20.9" +name = "rusticata-macros" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" dependencies = [ - "log", - "ring 0.16.20", - "sct", - "webpki", + "nom", ] [[package]] -name = "rustls-pemfile" -version = "0.2.1" +name = "rustls" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eebeaeb360c87bfb72e84abdb3447159c0eaececf1bef2aecd65a8be949d1c9" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ - "base64", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", ] [[package]] -name = "rustversion" -version = "1.0.23" +name = "rustls-pki-types" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] [[package]] -name = "sct" -version = "0.7.1" +name = "rustls-webpki" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ - "ring 0.17.14", - "untrusted 0.9.0", + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -204,6 +342,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -223,7 +362,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -246,16 +385,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] -name = "spin" -version = "0.5.2" +name = "subtle" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "3.0.6" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" dependencies = [ "proc-macro2", "quote", @@ -263,130 +402,94 @@ dependencies = [ ] [[package]] -name = "tiny_http" -version = "0.12.0" +name = "syn" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ - "ascii", - "chunked_transfer", - "httpdate", - "log", - "rustls", - "rustls-pemfile", - "zeroize", + "proc-macro2", + "quote", + "unicode-ident", ] [[package]] -name = "unicode-ident" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasm-bindgen" -version = "0.2.129" +name = "synstructure" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "wasm-bindgen-macro" -version = "0.2.129" +name = "thiserror" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "quote", - "wasm-bindgen-macro-support", + "thiserror-impl", ] [[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.129" +name = "thiserror-impl" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ - "bumpalo", "proc-macro2", "quote", - "syn", - "wasm-bindgen-shared", + "syn 3.0.6", ] [[package]] -name = "wasm-bindgen-shared" -version = "0.2.129" +name = "time" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ - "unicode-ident", + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", ] [[package]] -name = "web-sys" -version = "0.3.106" +name = "time-core" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" -dependencies = [ - "js-sys", - "wasm-bindgen", -] +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] -name = "webpki" -version = "0.22.4" +name = "time-macros" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ - "ring 0.17.14", - "untrusted 0.9.0", + "num-conv", + "time-core", ] [[package]] -name = "winapi" -version = "0.3.9" +name = "unicode-ident" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" +name = "untrusted" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "windows-sys" @@ -461,6 +564,34 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "zeroize" version = "1.9.0" diff --git a/Cargo.toml b/Cargo.toml index 368f63b..7020ad3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,9 +6,12 @@ license = "AGPL-3.0-or-later" description = "Read-only, token-protected HTTPS window onto the Spark's GPU/CPU readings" [dependencies] -tiny_http = { version = "0.12", features = ["ssl-rustls"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } serde_json = "1" +[dev-dependencies] +rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] } + [profile.release] opt-level = "s" strip = true diff --git a/NOTES.md b/NOTES.md index f2c3784..fd3184f 100644 --- a/NOTES.md +++ b/NOTES.md @@ -24,7 +24,7 @@ Read-only, token-protected HTTPS window onto the Spark's GPU/CPU readings, hoste Fields: ts, gpu_util_pct, gpu_temp_c, gpu_power_w, load1, load5, load15, cpu_temp_c, mem_used_mb, mem_total_mb. Wrong/missing token 401; unknown path 404; non-GET 405. Note: cpu_temp_c is max over all thermal zones (the Spark's zones are all type "acpitz", none say "cpu"). -tiny_http 0.12 pulls rustls 0.20 (older); acceptable for read-only data, UNVERIFIED against heavy scanning. +TLS is terminated by rustls 0.23 (ring provider, TLS 1.2 and 1.3 only) in `src/tls.rs`; a minimal HTTP/1.1 reader (one request per connection, 16 KiB head cap, 64 connections max) replaced tiny_http, which pinned rustls 0.20 (RUSTSEC-2024-0336). ## Status and results feeds (added 2026-10-04) - Spark files (written by the orchestrator, see ~/status/README.md): `~/status/current.json`, `~/status/results.json`. diff --git a/src/main.rs b/src/main.rs index 12c1251..6c1f8b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,11 @@ //! readings-window: read-only HTTPS endpoint for Spark readings. //! `collect` appends one reading to the history file; `serve` publishes it. use serde_json::Value; +mod tls; use std::fs; use std::io::Write; use std::process::Command; use std::time::{SystemTime, UNIX_EPOCH}; -use tiny_http::{Header, Method, Response, Server, SslConfig}; const HISTORY: &str = "/var/lib/readings-window/history.jsonl"; const TOKEN: &str = "/etc/readings-window/token"; @@ -270,13 +270,7 @@ fn chat_feed(feed: &ChatFeed, q: Option<&str>) -> (u16, String, &'static str) { } } -fn resp(code: u16, ctype: &str, body: String) -> Response<std::io::Cursor<Vec<u8>>> { - Response::from_string(body) - .with_status_code(code) - .with_header(Header::from_bytes("Content-Type", ctype).unwrap()) -} - -fn handle(method: &Method, url: &str, auth: Option<&str>, token: &str) -> (u16, String, &'static str) { +fn handle(method: &str, url: &str, auth: Option<&str>, token: &str) -> (u16, String, &'static str) { let (path, query) = match url.split_once('?') { Some((p, q)) => (p, Some(q)), None => (url, None), @@ -286,7 +280,7 @@ fn handle(method: &Method, url: &str, auth: Option<&str>, token: &str) -> (u16, if !known { return (404, r#"{"error":"not found"}"#.into(), JSON_TYPE); } - if *method != Method::Get { + if method != "GET" { return (405, r#"{"error":"method not allowed"}"#.into(), JSON_TYPE); } if path == "/health" { @@ -332,16 +326,9 @@ fn serve() -> Result<(), String> { if token.len() < 32 { return Err("token too short".into()); } - let ssl = SslConfig { - certificate: fs::read(CERT).map_err(|e| format!("cert: {e}"))?, - private_key: fs::read(KEY).map_err(|e| format!("key: {e}"))?, - }; - let server = Server::https("0.0.0.0:9443", ssl).map_err(|e| format!("bind: {e}"))?; - for req in server.incoming_requests() { - let auth = req.headers().iter().find(|h| h.field.equiv("Authorization")).map(|h| h.value.to_string()); - let (code, body, ctype) = handle(req.method(), req.url(), auth.as_deref(), &token); - let _ = req.respond(resp(code, ctype, body)); - } + let cfg = tls::tls_config(&fs::read(CERT).map_err(|e| format!("cert: {e}"))?, &fs::read(KEY).map_err(|e| format!("key: {e}"))?)?; + let listener = std::net::TcpListener::bind("0.0.0.0:9443").map_err(|e| format!("bind: {e}"))?; + tls::serve_on(listener, cfg, token); Ok(()) } @@ -470,8 +457,8 @@ mod tests { assert_eq!(chat_route(bad), None, "{bad}"); } let tok = "s3cret"; - assert_eq!(handle(&Method::Get, "/v1/chat/other", Some("Bearer s3cret"), tok).0, 404); - assert_eq!(handle(&Method::Get, "/v1/chat/claude.txt", None, tok).0, 404); + assert_eq!(handle("GET", "/v1/chat/other", Some("Bearer s3cret"), tok).0, 404); + assert_eq!(handle("GET", "/v1/chat/claude.txt", None, tok).0, 404); } #[test] fn chat_auth_and_method() { @@ -482,14 +469,14 @@ mod tests { paths.push(format!("/v1/chat/{a}.jsonl")); } for p in &paths { - assert_eq!(handle(&Method::Get, p, None, tok).0, 401, "{p}"); - assert_eq!(handle(&Method::Get, &format!("{p}?lines=5"), Some("Bearer wrong"), tok).0, 401, "{p}"); - assert_eq!(handle(&Method::Post, p, None, tok).0, 405, "{p}"); + assert_eq!(handle("GET", p, None, tok).0, 401, "{p}"); + assert_eq!(handle("GET", &format!("{p}?lines=5"), Some("Bearer wrong"), tok).0, 401, "{p}"); + assert_eq!(handle("POST", p, None, tok).0, 405, "{p}"); } } #[test] fn chat_agent_list() { - let (code, body, ctype) = handle(&Method::Get, "/v1/chat", Some("Bearer s3cret"), "s3cret"); + let (code, body, ctype) = handle("GET", "/v1/chat", Some("Bearer s3cret"), "s3cret"); assert_eq!((code, ctype), (200, "application/json")); assert_eq!(body, r#"{"agents":["claude","codex","opencode","gemini","muse"]}"#); let v: Value = serde_json::from_str(&body).unwrap(); diff --git a/src/tls.rs b/src/tls.rs new file mode 100644 index 0000000..5c48e2d --- /dev/null +++ b/src/tls.rs @@ -0,0 +1,272 @@ +//! HTTPS front end: rustls 0.23 terminates TLS, then a deliberately tiny HTTP/1.1 +//! reader hands (method, target, Authorization) to `handle`. One request per connection. +use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer}; +use rustls::{ServerConfig, ServerConnection, StreamOwned}; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const MAX_HEAD: usize = 16 * 1024; +const MAX_CONNS: usize = 64; +const IO_TIMEOUT: Duration = Duration::from_secs(10); +const HEAD_DEADLINE: Duration = Duration::from_secs(15); + +/// TLS 1.2 and 1.3 only (rustls does not implement older versions), no client certificates. +pub fn tls_config(cert_pem: &[u8], key_pem: &[u8]) -> Result<Arc<ServerConfig>, String> { + let certs = CertificateDer::pem_slice_iter(cert_pem) + .collect::<Result<Vec<_>, _>>() + .map_err(|e| format!("cert: {e}"))?; + let key = PrivateKeyDer::from_pem_slice(key_pem).map_err(|e| format!("key: {e}"))?; + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12]) + .map_err(|e| format!("tls: {e}"))? + .with_no_client_auth() + .with_single_cert(certs, key) + .map_err(|e| format!("cert/key: {e}"))?; + Ok(Arc::new(cfg)) +} + +/// Parsed request head: method, target, Authorization header value. +pub fn parse_head(head: &[u8]) -> Option<(String, String, Option<String>)> { + let text = std::str::from_utf8(head).ok()?; + let mut lines = text.split("\r\n"); + let mut parts = lines.next()?.split(' '); + let (method, target, version) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() || !version.starts_with("HTTP/1.") || !target.starts_with('/') { + return None; + } + let auth = lines.take_while(|l| !l.is_empty()).find_map(|l| { + let (k, v) = l.split_once(':')?; + k.trim() + .eq_ignore_ascii_case("authorization") + .then(|| v.trim().to_string()) + }); + Some((method.to_string(), target.to_string(), auth)) +} + +fn reason(code: u16) -> &'static str { + match code { + 200 => "OK", + 400 => "Bad Request", + 401 => "Unauthorized", + 404 => "Not Found", + 405 => "Method Not Allowed", + 502 => "Bad Gateway", + _ => "Error", + } +} + +fn response_bytes(code: u16, ctype: &str, body: &str) -> Vec<u8> { + let mut out = format!( + "HTTP/1.1 {code} {}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + reason(code), + body.len() + ) + .into_bytes(); + out.extend_from_slice(body.as_bytes()); + out +} + +fn read_head<S: Read>(s: &mut S) -> Option<Vec<u8>> { + let start = Instant::now(); + let mut buf = Vec::new(); + let mut chunk = [0u8; 2048]; + while start.elapsed() < HEAD_DEADLINE { + let n = s.read(&mut chunk).ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + // Bound the complete wire head, not body bytes read in the same chunk. + if i + 4 > MAX_HEAD { + return None; + } + buf.truncate(i + 2); + return Some(buf); + } + if buf.len() > MAX_HEAD { + return None; + } + } + None +} + +fn serve_conn(tcp: TcpStream, cfg: Arc<ServerConfig>, token: &str) { + let _ = tcp.set_read_timeout(Some(IO_TIMEOUT)); + let _ = tcp.set_write_timeout(Some(IO_TIMEOUT)); + let Ok(conn) = ServerConnection::new(cfg) else { + return; + }; + let mut tls = StreamOwned::new(conn, tcp); + let Some(head) = read_head(&mut tls) else { + return; + }; + let out = match parse_head(&head) { + Some((m, t, a)) => { + let (code, body, ctype) = crate::handle(&m, &t, a.as_deref(), token); + response_bytes(code, ctype, &body) + } + None => response_bytes(400, crate::JSON_TYPE, r#"{"error":"bad request"}"#), + }; + let _ = tls.write_all(&out); + tls.conn.send_close_notify(); + let _ = tls.flush(); +} + +/// Accept loop: one thread per connection, at most MAX_CONNS at once. +pub fn serve_on(listener: TcpListener, cfg: Arc<ServerConfig>, token: String) { + let live = Arc::new(AtomicUsize::new(0)); + let token = Arc::new(token); + for tcp in listener.incoming().flatten() { + if live.fetch_add(1, Ordering::SeqCst) >= MAX_CONNS { + live.fetch_sub(1, Ordering::SeqCst); + continue; // dropped: shed load instead of queueing + } + let (cfg, live, token) = (cfg.clone(), live.clone(), token.clone()); + std::thread::spawn(move || { + serve_conn(tcp, cfg, &token); + live.fetch_sub(1, Ordering::SeqCst); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rustls::{pki_types::ServerName, ClientConfig, ClientConnection, RootCertStore}; + + const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + fn start() -> (std::net::SocketAddr, CertificateDer<'static>) { + let ck = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); + let cfg = tls_config( + ck.cert.pem().as_bytes(), + ck.signing_key.serialize_pem().as_bytes(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + std::thread::spawn(move || serve_on(listener, cfg, TOKEN.to_string())); + (addr, ck.cert.der().clone()) + } + + fn get( + addr: std::net::SocketAddr, + cert: &CertificateDer<'static>, + auth: Option<&str>, + ) -> String { + let mut roots = RootCertStore::empty(); + roots.add(cert.clone()).unwrap(); + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + let conn = ClientConnection::new(Arc::new(cfg), ServerName::try_from("localhost").unwrap()) + .unwrap(); + let mut s = StreamOwned::new(conn, TcpStream::connect(addr).unwrap()); + let a = auth + .map(|a| format!("Authorization: {a}\r\n")) + .unwrap_or_default(); + s.write_all(format!("GET /v1/status HTTP/1.1\r\nHost: localhost\r\n{a}\r\n").as_bytes()) + .unwrap(); + let mut out = String::new(); + let _ = s.read_to_string(&mut out); // server closes without close_notify on some paths + out + } + + #[test] + fn handshake_with_token_serves_and_without_is_refused() { + let (addr, cert) = start(); + let ok = get(addr, &cert, Some(&format!("Bearer {TOKEN}"))); + assert!(ok.starts_with("HTTP/1.1 200 OK"), "{ok}"); + assert!(ok.contains(r#""label""#), "{ok}"); + let no = get(addr, &cert, None); + assert!(no.starts_with("HTTP/1.1 401"), "{no}"); + let bad = get(addr, &cert, Some("Bearer wrong")); + assert!(bad.starts_with("HTTP/1.1 401"), "{bad}"); + } + + #[test] + fn tls10_and_tls11_clients_are_refused() { + let (addr, _) = start(); + for minor in [0x01u8, 0x02] { + // ClientHello: legacy version TLS 1.0/1.1, one CBC suite, no extensions. + let mut hello = vec![0x03, minor]; + hello.extend([0u8; 32]); // random + hello.push(0); // session id + hello.extend([0x00, 0x02, 0x00, 0x2f]); // TLS_RSA_WITH_AES_128_CBC_SHA + hello.extend([0x01, 0x00]); // null compression + let mut hs = vec![0x01, 0, 0, hello.len() as u8]; + hs.extend(hello); + let mut rec = vec![0x16, 0x03, 0x01, 0, hs.len() as u8]; + rec.extend(hs); + let mut s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + s.write_all(&rec).unwrap(); + let mut buf = [0u8; 64]; + let n = s.read(&mut buf).unwrap_or(0); + // Either closed, or a TLS alert (0x15). Never a ServerHello (0x16). + assert!( + n == 0 || buf[0] == 0x15, + "TLS 1.{minor} got {:?}", + &buf[..n.min(8)] + ); + } + } + + #[test] + fn head_size_limit_includes_terminator() { + for size in [MAX_HEAD - 1, MAX_HEAD, MAX_HEAD + 1, MAX_HEAD + 2048] { + let mut head = b"GET /health HTTP/1.1\r\nX-Pad: ".to_vec(); + head.resize(size - 4, b'a'); + head.extend_from_slice(b"\r\n\r\n"); + let result = read_head(&mut std::io::Cursor::new(&head)); + if size <= MAX_HEAD { + assert_eq!(result.as_deref(), Some(&head[..size - 2]), "size {size}"); + } else { + assert!(result.is_none(), "accepted oversized head: {size}"); + } + } + } + + #[test] + fn head_size_limit_ignores_trailing_body() { + struct Chunked<'a>(&'a [u8]); + impl Read for Chunked<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + let limit = buf.len().min(1000); + self.0.read(&mut buf[..limit]) + } + } + let mut input = b"GET /health HTTP/1.1\r\nX-Pad: ".to_vec(); + input.resize(MAX_HEAD - 104, b'a'); + input.extend_from_slice(b"\r\n\r\n"); + let head_end = input.len(); + input.extend_from_slice(&[b'b'; 4096]); + // The last read crosses MAX_HEAD, but the terminator precedes that limit. + let result = read_head(&mut Chunked(&input)); + assert_eq!(result.as_deref(), Some(&input[..head_end - 2])); + } + + #[test] + fn head_size_limit_rejects_unterminated_input() { + assert!(read_head(&mut std::io::Cursor::new(vec![b'a'; MAX_HEAD + 1])).is_none()); + } + + #[test] + fn head_parsing() { + let h = b"GET /x?y=1 HTTP/1.1\r\nHost: a\r\nauthorization: Bearer t \r\n"; + assert_eq!( + parse_head(h), + Some(("GET".into(), "/x?y=1".into(), Some("Bearer t".into()))) + ); + assert!(parse_head(b"GET x HTTP/1.1\r\n").is_none()); + assert!(parse_head(b"GET / SPDY\r\n").is_none()); + } +}