readings-window
aien-dev/readings-window
Brought by drakestapleton
GitHub aien-dev/readings-window#13 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/readings-window/patches/f1af66277310ffc3.bundle -o f1af66277310ffc3.bundle git fetch f1af66277310ffc3.bundle refs/pull/13/head
Provenance
github-import 1
aien-dev/readings-window
13
1eab180db0d85f54160214c350373f0e0ef44924
{"kind":"github-import","owner":"aien-dev","repo":"readings-window","number":13,"url":"https://github.com/aien-dev/readings-window/pull/13","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:28Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.gitignore b/.gitignore index 95b19c1..1d64ec2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ target/ .crumb.local +spark.conf diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2cce321 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,73 @@ +# 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/`, `.crumb.local` and `spark.conf` are ignored (`.gitignore`). Never commit them or a real deployment target list. + +## 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 + +Spark SSH targets come from `/etc/readings-window/spark.conf`; `spark.conf.example` documents the format. Each nonempty `target=USER@HOST` value is tried in file order. Keep real targets local-only, with the same order when migrating an existing deployment. There are no environment-variable or flag overrides. + +- 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 target file is read on each fetch, not at server startup. Missing or unreadable config makes Spark fetches fail; `/health` can still return successfully because it reads local history. See the migration procedure in `NOTES.md`. +- Other settings remain constants in `src/main.rs`: the root SSH key path, home-relative Spark status/results and agent archive paths (`AGENTS`, five fixed names). The configured SSH user's home must contain those paths. 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..0e06812 100644 --- a/NOTES.md +++ b/NOTES.md @@ -6,7 +6,7 @@ Read-only, token-protected HTTPS window onto the Spark's GPU/CPU readings, hoste - Spark: `/usr/local/bin/spark-readings` (bash, one JSON line, ~0.05 s). - Hub: `/usr/local/bin/readings-window` (this crate). Runs as root (needs the key and the root ssh key). - `readings-collect.timer` (every 15 s) runs `readings-window collect`: ssh to the Spark - (LAN 192.168.1.108 first, private net 100.64.0.2 as fallback; the private-net address timed out when tested), + (targets from `/etc/readings-window/spark.conf`, local-only, format in `spark.conf.example`: LAN first, private net as fallback), appends to `/var/lib/readings-window/history.jsonl`, prunes lines older than 30 days. - `readings-window.service` runs `readings-window serve` on 0.0.0.0:9443 (HTTPS). - Secrets: `/etc/readings-window/token` (root 600), `/etc/readings-window/key.pem`. @@ -14,8 +14,25 @@ Read-only, token-protected HTTPS window onto the Spark's GPU/CPU readings, hoste - DNS: `gandi-ddns.sh` keeps both `hs` and `readings` A records at the home public IP. - Registered in pi-register as `readings-window` and `readings-collect`. +## Spark target configuration migration + +The target configuration introduced in PR #12 replaces embedded SSH targets. Before deploying that binary, recover the existing deployment's exact targets and fallback order into a private `spark.conf`. Do not copy the example's placeholders into production or publish recovered values in a PR, command output or logs. `spark.conf` is gitignored; keep backups outside the checkout. + +On the deployment host: + +1. Inspect both service identities with `systemctl show readings-window.service readings-collect.service -p Id -p User -p Group -p DynamicUser`. Empty `User=` with `DynamicUser=no` means root; confirm running processes with `ps -C readings-window -o user=,group=,args=`. +2. Check whether `/etc/readings-window/spark.conf` already exists, including a dangling symlink. Never overwrite an existing file as part of migration. If absent, stage the recovered bytes in a root-owned temporary file in `/etc/readings-window/`, set mode 600, then publish with `ln -T TEMP /etc/readings-window/spark.conf`. Hard-link creation refuses an existing destination; remove only the temporary name afterward. +3. Root-owned mode 600 is correct for the current root services. If a deployment uses a non-root identity, stop and establish an explicitly approved ownership/access policy first. That deployment also needs access to the fixed root SSH key path used by `fetch`; making this config readable alone is insufficient. +4. Compare the installed bytes to the private recovered file without printing either. Confirm owner, mode and readability as the actual service user. +5. Check the existing service without collecting or restarting it: `systemctl is-active readings-window.service` and `curl --fail --silent --show-error --resolve readings.aienos.com:9443:127.0.0.1 https://readings.aienos.com:9443/health`. + +The config is read on each Spark fetch; installing it does not require a restart. Installing config is not a binary deployment. `/health` checks local history and exposure state, not SSH reachability, config loading or chat retrieval. The source still uses a fixed root SSH identity and paths relative to the configured remote user's home. Collection and live-chat readiness need separate authorized checks; a health response alone does not establish them. + +On 2026-10-25, the missing config was restored from the original two targets in their original order. Both service units used root (`User=` empty, `DynamicUser=no`), and both running processes were root. The file was published without overwriting via a hard link, with owner/group root and mode 600; a byte comparison against the private recovered file matched. No binary was deployed and no service was restarted. +The read-only post-install smoke returned `active` from `systemctl is-active readings-window.service` and `{"status":"ok","last_reading_age_s":13,"exposure":"ok"}` from the local HTTPS `/health` request with certificate validation. No collection command, chat fetch or model request was made by this check. + ## How Muse calls it -- Needs router forward of 9443/tcp to 192.168.1.192 (Drake). +- Needs router forward of 9443/tcp to the hub's LAN address (Drake). - `GET https://readings.aienos.com:9443/health` (no auth): `{"status":"ok","last_reading_age_s":N}` - `GET /v1/readings/current`, `GET /v1/readings/history?hours=N` (default 24, max 720), header `Authorization: Bearer <token>`. @@ -24,7 +41,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`. @@ -40,13 +57,13 @@ tiny_http 0.12 pulls rustls 0.20 (older); acceptable for read-only data, UNVERIF ## Live Claude chat feed (added 2026-10-04) - Why: Drake wants the whole Claude chat stream visible to Muse on his MacBook and phone. -- `GET /v1/chat/claude` serves `/home/drakestapleton/shared/agents/claude-chat.txt`, `GET /v1/chat/claude.jsonl` serves `claude-chat.jsonl` (Bearer token). `?lines=N` (default 500, clamped 1..50000) runs `tail -n N` on the Spark; `?all=1` runs `cat`. Only constant paths and a parsed integer reach the remote shell. +- `GET /v1/chat/claude` serves `~/shared/agents/claude-chat.txt`, `GET /v1/chat/claude.jsonl` serves `claude-chat.jsonl` (Bearer token). `?lines=N` (default 500, clamped 1..50000) runs `tail -n N` on the Spark; `?all=1` runs `cat`. Only constant paths and a parsed integer reach the remote shell. - Proxied live over ssh on each request. NOTHING is written or cached on the hub, because its root disk is a fragile USB stick. Spark unreachable gives 502 `{"error":"spark unreachable"}`. - Each request blocks the single-threaded server for the ssh round trip (up to ~5 s connect timeout per host); `?all=1` on a large file is a big response. UNVERIFIED under load. ## Per-agent chat routes (added 2026-10-04, replaces the Claude-only feed above) - Why: Drake 2026-10-04 wants every agent's chat visible to Muse from one archive. Design: `~/handoffs/2026-10-04-agent-archive.md` (program `agent-archive`). - Allow-list, matched exactly, each name mapped to constant paths in code (the name is never put into a command): `claude`, `codex`, `opencode`, `gemini`, `muse`. `GET /v1/chat` lists them. -- Spark files: `/home/drakestapleton/archive/agent-chats/latest/<agent>.txt|.jsonl` (rolling, last 20000 lines) and `records/<agent>/<YYYY-MM-DD>.jsonl` (complete history). +- Spark files: `~/archive/agent-chats/latest/<agent>.txt|.jsonl` (rolling, last 20000 lines) and `records/<agent>/<YYYY-MM-DD>.jsonl` (complete history). - `?lines=N` runs `tail -n N` on the latest file. `?all=1`: plain runs `cat latest/<agent>.txt`; jsonl runs `cat records/<agent>/*.jsonl` (shell glob on the Spark, date order because file names sort by date). A missing file or an empty records folder makes the remote command fail, which shows as 502 "spark unreachable" (same code path as a real outage). - After the archive cutover `~/shared/agents/claude-chat.*` become symlinks to `latest/claude.*`; the hub no longer reads those paths. The hub must run this build and the archive must exist before `/v1/chat/*` returns data. Not deployed by this change. diff --git a/README.md b/README.md index a8e4d92..f0b0dcb 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ A small Rust service. `collect` fetches one JSON line of readings from the Spark - `readings-window collect`: fetch one reading from the Spark, append it to the history file and drop entries older than 30 days. It also refreshes the cached copies of the Spark's status and results files that `/v1/status` and `/v1/results` serve. - `readings-window serve`: HTTPS server on port 9443. +Spark SSH targets are local configuration, not source constants. Prepare `/etc/readings-window/spark.conf` using `spark.conf.example` and the migration procedure in `NOTES.md` before deploying a build that uses it. Keep real targets private. The current services run as root and use a root-owned mode-600 file. `/health` only reads local state and does not prove Spark fetch readiness. + `scripts/` holds the exposure watch: a 15-minute timer that scans our own public IP from inside the LAN (the router hairpin view, which is not the same as the internet view) and flags any change against an accepted baseline in `/etc/exposure-watch/baseline.json`. It also flags UPnP being on and the `hs` and `readings` DNS records not matching the public IP. Operational notes, unit names and the deployment layout are in `NOTES.md`. diff --git a/spark.conf.example b/spark.conf.example new file mode 100644 index 0000000..5a54c22 --- /dev/null +++ b/spark.conf.example @@ -0,0 +1,4 @@ +# Copy to /etc/readings-window/spark.conf (root 600) on the hub. Never commit the real file. +# One ssh target per line, tried in order. +target=USER@SPARK_LAN_ADDRESS +target=USER@SPARK_PRIVATE_NET_ADDRESS diff --git a/src/main.rs b/src/main.rs index 12c1251..7ec3d31 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"; @@ -73,15 +73,27 @@ fn validate(line: &str) -> Result<Value, String> { Ok(v) } -/// Spark addresses: LAN first (works today), private-net address as fallback. -const SPARK_HOSTS: [&str; 2] = ["192.168.1.108", "100.64.0.2"]; +/// Spark ssh targets (`user@host`, tried in order), one per `target=` line in SPARK_CONF. +/// The real file is local-only; see `spark.conf.example`. +const SPARK_CONF: &str = "/etc/readings-window/spark.conf"; +fn spark_targets(conf: &str) -> Vec<String> { + conf.lines() + .filter_map(|l| l.trim().strip_prefix("target=")) + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()) + .collect() +} + +/// Remote paths are relative: ssh runs the command in the Spark user's home directory. fn fetch(remote: &str) -> Result<std::process::Output, String> { + let conf = fs::read_to_string(SPARK_CONF).map_err(|e| format!("{SPARK_CONF}: {e}"))?; let mut last = String::from("no hosts"); - for host in SPARK_HOSTS { + for target in spark_targets(&conf) { + let host = ⌖ let r = Command::new("ssh") .args(["-i", "/root/.ssh/id_ed25519_headscale_backup", "-o", "BatchMode=yes", - "-o", "ConnectTimeout=5", &format!("drakestapleton@{host}"), remote]) + "-o", "ConnectTimeout=5", target.as_str(), remote]) .output(); match r { Ok(o) if o.status.success() => return Ok(o), @@ -205,9 +217,9 @@ macro_rules! agent { ($n:literal) => { Agent { name: $n, - latest_txt: concat!("/home/drakestapleton/archive/agent-chats/latest/", $n, ".txt"), - latest_jsonl: concat!("/home/drakestapleton/archive/agent-chats/latest/", $n, ".jsonl"), - records_glob: concat!("/home/drakestapleton/archive/agent-chats/records/", $n, "/*.jsonl"), + latest_txt: concat!("archive/agent-chats/latest/", $n, ".txt"), + latest_jsonl: concat!("archive/agent-chats/latest/", $n, ".jsonl"), + records_glob: concat!("archive/agent-chats/records/", $n, "/*.jsonl"), } }; } @@ -270,13 +282,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 +292,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 +338,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(()) } @@ -349,8 +348,8 @@ fn main() { let r = match std::env::args().nth(1).as_deref() { Some("collect") => { let r = collect(); - collect_feed("/home/drakestapleton/status/current.json", STATUS, validate_status); - collect_feed("/home/drakestapleton/status/results.json", RESULTS, validate_results); + collect_feed("status/current.json", STATUS, validate_status); + collect_feed("status/results.json", RESULTS, validate_results); r } Some("serve") => serve(), @@ -437,7 +436,12 @@ mod tests { assert_eq!(clamp_lines(Some("lines=1;rm -rf /")), 500); assert_eq!(clamp_lines(Some("lines=-5")), 500); } - const A: &str = "/home/drakestapleton/archive/agent-chats"; + const A: &str = "archive/agent-chats"; + #[test] + fn spark_targets_parse() { + let c = "# comment\ntarget=u@a\n target= u@b \ntarget=\nother=x\n"; + assert_eq!(spark_targets(c), vec!["u@a".to_string(), "u@b".to_string()]); + } fn route(p: &str) -> ChatFeed { chat_route(p).unwrap() } @@ -470,8 +474,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 +486,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()); + } +}