From 35b8caa716df6f705e12e378dc37ef2dee5ec235 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 00:54:16 -0400 Subject: [PATCH 1/3] feat(tui): ASCII chrome, invite wrap, alert truncate, remaining copy ONIONWIRE_ASCII (and NO_COLOR) switches truncation to ... and ASCII borders. Share/paste wrap at : so a mouse-copy cannot lose a mid-hex line. Alerts truncate to the frame; empty threads and paste errors keep the next-step hint. Skip the optional 40-row wordmark. --- docs/TUI.md | 60 ++++++++++++++++ src/tui.rs | 122 +++++++++++++++++++++++++++----- tests/tui_spec.rs | 173 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 337 insertions(+), 18 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 925d351..40e82e5 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert `tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three examples without adding a crate. + +## After frames (spacing / ASCII / wrap / copy) + +Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer, +1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged +here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line +header without buying hierarchy). + +### 80x24 — `draw_share` after (field-boundary wrap) + +Invite lines break on `:`. `sig=` hex that does not fit continues as an +all-hex line. Joining those lines (no extra spaces) is the original payload. + +``` +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│ │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│ │ +│onionwire:v1: │ +│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │ +│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │ +│spk=0101010101010101010101010101010101010101010101010101010101010101: │ +│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│ +│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`) + +No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`. + +``` ++(o) invite--------------------------------------------------------------------+ +|give this string to a friend; they F3 paste it | +| | +|fp ea4a6c63... | +|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion | +| | +|onionwire:v1: | +|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: | +|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: | +|spk=0101010101010101010101010101010101010101010101010101010101010101: | +|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0| +|5401b0af934cefea617f71466f406af4bef956847200a8e915190b | ++------------------------------------------------------------------------------+ +``` + +### 80x24 / 120x40 — main chrome after + +Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump: + +``` +cargo test --locked --test tui_spec -- --nocapture dump_spec_frames +``` + +Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is +`no messages` / `type below, Enter sends`; paste error is `{err}` then +`Enter resubmits Esc back`; alerts truncate to the frame width. diff --git a/src/tui.rs b/src/tui.rs index 2ce2eab..20eb4b6 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -5,6 +5,7 @@ use std::time::Duration; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; +use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; @@ -38,8 +39,90 @@ fn color_mode() -> ColorMode { } } +/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate. +pub fn ascii_chrome() -> bool { + std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some() +} + +const ASCII_BORDERS: border::Set = border::Set { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + fn ellipsis() -> &'static str { - "…" + if ascii_chrome() { "..." } else { "…" } +} + +/// Truncate or keep an alert so it cannot spill into the roster row. +pub fn alert_line(msg: &str, width: u16) -> String { + let mut text = msg.to_string(); + if color_mode() == ColorMode::None && !text.starts_with("! ") { + text = format!("! {text}"); + } + truncate_chars(&text, width as usize) +} + +/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. +/// Joining the lines (no extra spaces) reconstructs `payload`. +pub fn wrap_invite(payload: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + let mut lines: Vec = Vec::new(); + let mut cur = String::new(); + let parts: Vec<&str> = payload.split(':').collect(); + for (i, part) in parts.iter().enumerate() { + let piece = if i + 1 < parts.len() { + format!("{part}:") + } else { + (*part).to_string() + }; + for chunk in char_chunks(&piece, width) { + if cur.is_empty() { + cur = chunk; + } else if char_len(&cur) + char_len(&chunk) <= width { + cur.push_str(&chunk); + } else { + lines.push(std::mem::take(&mut cur)); + cur = chunk; + } + } + } + if !cur.is_empty() { + lines.push(cur); + } + lines.join("\n") +} + +fn char_chunks(s: &str, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + if char_len(s) <= width { + return vec![s.to_string()]; + } + let chars: Vec = s.chars().collect(); + chars.chunks(width).map(|c| c.iter().collect()).collect() +} + +/// Friend selected, no messages yet. +pub fn empty_friend_chat_text() -> &'static str { + "no messages\ntype below, Enter sends" +} + +/// Paste overlay copy. Error keeps the resubmit hint. +pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { + let hint = match err { + Some(e) => format!("{e}\nEnter resubmits Esc back"), + None => "paste onionwire:v1 payload, Enter to submit".to_string(), + }; + format!("{hint}\n\n{buf}") } fn char_len(s: &str) -> usize { @@ -1429,11 +1512,7 @@ impl App { f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); if let Some(msg) = &self.alert { - let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") { - format!("! {msg}") - } else { - msg.clone() - }; + let text = alert_line(msg, area.width); f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); } @@ -1559,7 +1638,10 @@ impl App { ]; }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) if msgs.is_empty() => vec!["no messages".into()], + Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), Ok(msgs) => msgs .iter() .map(|m| { @@ -1583,8 +1665,7 @@ impl App { } else { style_dim() }; - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(border) .title(title) .title_style(title_style) @@ -1699,9 +1780,17 @@ fn footer_hints(screen: &Screen) -> &'static str { } } +fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { + let block = block.borders(Borders::ALL); + if ascii_chrome() { + block.border_set(ASCII_BORDERS) + } else { + block + } +} + fn themed_block(title: &str) -> Block<'_> { - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(style_accent()) .title(title) .title_style(style_accent().add_modifier(Modifier::BOLD)) @@ -1712,8 +1801,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; + let inner = f.area().width.saturating_sub(2) as usize; + let invite = wrap_invite(payload, inner.max(1)); let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}" + "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" ); f.render_widget( Paragraph::new(body) @@ -1725,10 +1816,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) { } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { - let hint = err - .unwrap_or("paste onionwire:v1 payload, Enter to submit") - .to_string(); - let body = format!("{hint}\n\n{buf}"); + let inner = f.area().width.saturating_sub(2) as usize; + let shown = wrap_invite(buf, inner.max(1)); + let body = paste_screen_text(&shown, err); let style = if err.is_some() { style_alert() } else { diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index b29270f..2310487 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,17 +1,21 @@ //! Spec implementation tests for docs/TUI.md (this card). //! Does not own `tests/tui_frames.rs` (PR #23). +use onionwire::qr; use onionwire::tui::{ - draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width, - status_footer, + alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, + help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, + status_footer, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::layout::{Constraint, Layout}; use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap}; +use std::sync::Mutex; const FP: &str = "abcdef0123456789deadbeefcafebabe"; +static ASCII_ENV: Mutex<()> = Mutex::new(()); const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String { @@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() { #[test] fn dump_spec_frames() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; for (w, h) in [(80u16, 24u16), (120, 40)] { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -205,5 +211,168 @@ fn dump_spec_frames() { .expect("draw"); println!("===== AFTER help {w}x{h} ====="); print!("{}", screen_from(terminal.backend().buffer(), w, h)); + + let invite = sample_invite(); + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + println!("===== AFTER share {w}x{h} ====="); + print!("{}", screen_from(terminal.backend().buffer(), w, h)); } } + +fn sample_invite() -> String { + let sk = [7u8; 32]; + qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") +} + +fn invite_line_ok(line: &str) -> bool { + let t = line.trim(); + t.is_empty() + || t.starts_with("onionwire:") + || t.starts_with("k=") + || t.starts_with("o=") + || t.starts_with("spk=") + || t.starts_with("sig=") + || t.chars().all(|c| c.is_ascii_hexdigit()) +} + +#[test] +fn alert_line_truncates_to_frame_width() { + let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped"; + let line = alert_line(long, 80); + assert!( + line.chars().count() <= 80, + "alert wider than 80: {} {line:?}", + line.chars().count() + ); + assert!( + line.contains('…') || line.contains("..."), + "long alert was not truncated: {line:?}" + ); + assert!( + !line.contains("roster on the next row"), + "alert still has overflow tail: {line:?}" + ); +} + +#[test] +fn wrap_invite_breaks_on_field_boundaries() { + let invite = sample_invite(); + assert!(invite.len() > 78, "fixture too short to wrap: {invite}"); + let wrapped = wrap_invite(&invite, 78); + for line in wrapped.lines() { + assert!( + line.chars().count() <= 78, + "invite line wider than 78: {} {line:?}", + line.chars().count() + ); + assert!( + invite_line_ok(line), + "invite wrapped mid-token: {line:?}\n{wrapped}" + ); + } + assert!( + wrapped.contains("onionwire:v1:"), + "lost invite prefix:\n{wrapped}" + ); + assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); + assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); + let joined: String = wrapped.lines().map(str::trim).collect(); + assert_eq!( + joined, invite, + "wrap must be newline-joinable back to payload" + ); +} + +#[test] +fn draw_share_invite_does_not_wrap_mid_token() { + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + assert!( + screen.contains("onionwire:v1:"), + "missing prefix:\n{screen}" + ); + for raw in screen.lines() { + let inner = raw.trim_start_matches(['│', '|', ' ']); + let inner = inner.trim_end_matches(['│', '|', ' ']); + if inner.starts_with("onionwire:") + || inner.starts_with("k=") + || inner.starts_with("o=") + || inner.starts_with("spk=") + || inner.starts_with("sig=") + || inner.chars().all(|c| c.is_ascii_hexdigit()) + { + assert!( + invite_line_ok(inner), + "share pane mid-token wrap: {inner:?}\n{screen}" + ); + } + if inner.starts_with('c') && inner.contains(":o=") { + panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}"); + } + } +} + +#[test] +fn empty_friend_chat_has_send_hint() { + let text = empty_friend_chat_text(); + assert!(text.contains("no messages"), "{text:?}"); + assert!(text.contains("type below, Enter sends"), "{text:?}"); +} + +#[test] +fn paste_error_keeps_resubmit_hint() { + let body = paste_screen_text("", Some("bad invite")); + assert!(body.contains("bad invite"), "{body:?}"); + assert!(body.contains("Enter resubmits"), "{body:?}"); + assert!(body.contains("Esc back"), "{body:?}"); + let ok = paste_screen_text("onionwire:v1:k=x", None); + assert!( + ok.contains("paste onionwire:v1 payload"), + "happy-path hint lost: {ok:?}" + ); +} + +#[test] +fn ascii_switch_80x24_frame_is_pure_ascii() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; + assert!( + ascii_chrome(), + "ONIONWIRE_ASCII set but ascii_chrome() is false" + ); + let footer = status_footer(80, FP, ONION, None, main_footer_hints()); + assert!( + footer.contains("..."), + "ASCII truncation marker missing: {footer:?}" + ); + assert!( + !footer.contains('…'), + "unicode ellipsis still in footer: {footer:?}" + ); + + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + let non_ascii: Vec = screen.chars().filter(|c| !c.is_ascii()).collect(); + assert!( + non_ascii.is_empty(), + "ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}" + ); + assert!( + screen.contains("..."), + "truncation marker missing from ASCII frame:\n{screen}" + ); + assert!( + screen.contains('+') && screen.contains('|') && screen.contains('-'), + "ASCII borders missing:\n{screen}" + ); + println!("===== AFTER ascii share 80x24 =====\n{screen}"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} From 5dc6e78e2335cea72034a80cb37c10e9acaa7857 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 12:48:28 -0400 Subject: [PATCH 2/3] ci: watch upstream Arti/tor-* releases daily and file an upgrade issue .forgejo/workflows/arti-watch.yml runs daily (06:17 UTC) and via workflow_dispatch: scripts/arti-watch.py compares each tor-*/arti-* pin in Cargo.toml against crates.io and files one Forgejo issue per distinct major.minor bump, deduped on the title so a repeat run is a no-op. It changes no dependency. docs/ARTI_UPGRADE.md records the pinned set (arti-client, tor-cell, tor-hsservice, tor-rtcompat at 0.46), the lockstep rule, the rustc 1.91 floor, and the tests a bump must pass (tests/tor_hs.rs live publish + probe-connect + byte pipe, the 360s fail-closed wait and the src/hs.rs circuit-timeout workarounds in tests/hs.rs, the Android rustls build). Both artefacts state what this does not cover: Tor Project security announcements, a yanked crate, and a vulnerability with no version bump. --- .forgejo/workflows/arti-watch.yml | 72 ++++++++ docs/ARTI_UPGRADE.md | 143 +++++++++++++++ scripts/arti-watch.py | 279 ++++++++++++++++++++++++++++++ 3 files changed, 494 insertions(+) create mode 100644 .forgejo/workflows/arti-watch.yml create mode 100644 docs/ARTI_UPGRADE.md create mode 100644 scripts/arti-watch.py diff --git a/.forgejo/workflows/arti-watch.yml b/.forgejo/workflows/arti-watch.yml new file mode 100644 index 0000000..10a0e5f --- /dev/null +++ b/.forgejo/workflows/arti-watch.yml @@ -0,0 +1,72 @@ +name: arti-watch + +# Daily upstream check for the in-process Tor stack. Arti onion services are +# experimental (README) and tor-*/arti-* are the largest attack surface here, +# so when crates.io has a newer major.minor than the pins in Cargo.toml this +# files ONE Forgejo issue (deduped on the title — a second run is a no-op). +# +# Forgejo has no Dependabot: this workflow IS the dependency alert. It +# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain +# floor and the tests it must pass are in docs/ARTI_UPGRADE.md. +# +# NOT covered, by design: Tor Project security announcements (a fix that ships +# with no crates.io version bump is invisible here) and a yanked crate / +# vulnerability in a version that has not changed. Read +# https://blog.torproject.org/ yourself. +on: + schedule: + # 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose. + - cron: "17 6 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Compare and log only, file no issue (true/false) + required: false + type: string + default: "false" + simulate_pin: + description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.' + required: false + type: string + +# Never two watchers at once: two simultaneous runs could both see "no issue +# with this title yet" and file twice. +concurrency: + group: onionwire-arti-watch + cancel-in-progress: false + +jobs: + watch: + # Same Pi runner + `docker` job image as ci.yml / release.yml (which run + # python3 and curl there). No cargo, no docker: four crates.io GETs and at + # most one issue POST. + runs-on: docker + timeout-minutes: 10 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: Compare pins against crates.io and file an issue on a bump + shell: bash + env: + FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} + REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} + INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }} + INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }} + run: | + set -euo pipefail + args=(--cargo-toml Cargo.toml) + case "${INPUT_DRY_RUN:-false}" in + true|True|TRUE|1|yes|YES) args+=(--dry-run) ;; + esac + if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then + IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN" + for pair in "${pairs[@]}"; do + pair="${pair// /}" + if [ -n "$pair" ]; then + args+=(--simulate-pin "$pair") + fi + done + fi + echo "run: python3 scripts/arti-watch.py ${args[*]}" + python3 scripts/arti-watch.py "${args[@]}" diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md new file mode 100644 index 0000000..bb0ad7b --- /dev/null +++ b/docs/ARTI_UPGRADE.md @@ -0,0 +1,143 @@ +# Upgrading the Arti / Tor crates + +The in-process Tor stack is the largest attack surface in OnionWire. Arti's +onion services are still **experimental** and OnionWire does not fall back to a +C-tor subprocess, so an upstream fix only reaches users when we bump these +crates, rebuild, and cut a release. + +## What is pinned + +Direct dependencies that come from the Arti repository, exactly as +`Cargo.toml` has them: + +| crate | requirement | features in `Cargo.toml` | +|---|---|---| +| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` | +| `tor-cell` | `0.46` | — | +| `tor-hsservice` | `0.46` | — | +| `tor-rtcompat` | `0.46` | `tokio` | + +`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not +part of a Tor upgrade. + +Two crate features re-expose Arti's TLS backends, which Arti marks +**non-additive** — exactly one may be selected per build graph: + +* `native-tls` (default) → Linux TUI build, via OpenSSL. +* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has + no OpenSSL. + +Published Arti releases move all four crates together in lockstep. Bump them as +**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is +not a configuration anyone tests upstream, and cargo will usually refuse or +silently pick one `tor-*` version and mismatched `tor-*` internals fail at +runtime. + +## Toolchain floor + +**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`; +the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm` +(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`). + +A bump may raise the floor. Take the actual MSRV from the upstream release +notes / the crate's own `rust-version`, then raise it in the same PR: + +* `rust-version` in `Cargo.toml`, +* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`, +* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it + when that lands, or ask the owner). + +## How this gets noticed + +`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks +crates.io for the newest stable version of each crate above. If the +major.minor moved past the pin, it files one Forgejo issue titled +`Arti upstream: → `. It is deduped on that title across open +and closed issues, so re-running it never files a second issue and never +comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit. + +Test the alert path without waiting for upstream (it compares real crates.io +data against a pretend pin): + +``` +# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45 +python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45 +``` + +**What the watcher does not cover.** It does not subscribe to Tor Project +security announcements — a fix that ships without a crates.io version bump is +invisible to it. It will not catch a yanked crate, and it will not catch a +vulnerability in a version that has not changed. Watch + and yourself, and +treat a Tor security advisory as an instruction to bump **now**, ahead of any +issue the watcher files. + +## Procedure + +1. Read the upstream release notes (Arti tags: ) + and the CHANGELOG for breaking API changes. Check the new MSRV. +2. Branch from `main`; bump all four requirements in `[dependencies]` of + `Cargo.toml` together, and `rust-version` if the floor moved. +3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is + committed): + ``` + cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat + git diff --stat Cargo.lock + ``` + Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate + moving alone is a sign the set is not actually lockstep — stop and look. +4. Build and run the offline suite: + ``` + cargo test --locked + cargo clippy --locked --all-targets -- -D warnings + ``` +5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish + path is slow and its circuit timeouts misbehave on hidden-service circuits, + and an upstream fix or behaviour change can make any of them wrong: + + | constant | why | guard | + |---|---|---| + | `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` | + | `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` | + | `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` | + | `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` | + + Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure + the rend handler is spawned *before* the probe wait, or the probe cannot + succeed at all. +6. Run the live two-node test on a networked machine. This is the only test that + proves the hidden service actually publishes and that a second node can + reach it: + ``` + cargo test --locked --test tor_hs -- --ignored --nocapture + ``` + It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant` + covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir + descriptor upload, not a hang), probe-connect against a live HS, a byte pipe + in both directions, restart, and the dormant/offline path. +7. Confirm the fail-closed path by hand if the publish wait changed at all: + with the write timeout still 360s, a peer whose onion is down must fail the + send. There is no outbox in v1 — the message must not be silently queued. +8. Rebuild the Android target — Arti's TLS backends are non-additive, and this + is the build that exercises the `rustls` feature: + ``` + scripts/build-android-local.sh + ``` +9. Verify the ciphertext claim still holds after the bump: send a message + between the two nodes, then + ``` + grep -r "" + ``` + must find nothing. The bodies live in sqlite as ciphertext, and nothing about + the plaintext should appear in Arti's state directory. +10. Open a PR against `main` describing: crates bumped, MSRV, the live-test + output, and anything upstream changed that touches `src/hs.rs`. Do not push + `main`; releases are minted by `.forgejo/workflows/release.yml` from a merge. + +## Rolling back + +Revert the version bump and the lockfile stanza together, re-run step 3's +`cargo update` only if the revert leaves the lockfile inconsistent, and re-run +`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and +`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the +intent. diff --git a/scripts/arti-watch.py b/scripts/arti-watch.py new file mode 100644 index 0000000..c7de9ab --- /dev/null +++ b/scripts/arti-watch.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins. + +Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on +the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency +it reads the version requirement in Cargo.toml, asks crates.io for the newest +published versions, and — when the major.minor moved — files ONE Forgejo issue. +The issue title carries the compared pair, e.g. + + Arti upstream: tor-hsservice 0.46 -> 0.47 + +Dedupe is on that title across all issues (open and closed), so a second run is +a no-op: no duplicate issue, no repeated comment. Nothing here bumps a +dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md. + +What this does NOT cover, by design: + * It does not subscribe to Tor Project security announcements. A fix that + ships without a crates.io version bump is invisible to this script. + * It will not catch a yanked crate, and it will not catch a vulnerability in + a version that has not changed. crates.io `max_stable_version` already + ignores yanks, so a yank alone produces no alert. + Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself. + +Usage: + FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \ + scripts/arti-watch.py --cargo-toml Cargo.toml + scripts/arti-watch.py --dry-run # no API writes, no token + scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45 +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass + +CRATES_API = "https://crates.io/api/v1/crates/{name}" +# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in +# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own. +USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)" +WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$") +# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch. +SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$") + + +def log(msg: str) -> None: + print(msg, flush=True) + + +class HardFail(SystemExit): + def __init__(self, msg: str) -> None: + super().__init__(2) + self.msg = msg + + +def curl_json(url, token=None, method="GET", body=None): + """curl a JSON endpoint. Returns (http_status, parsed_body_or_None). + + curl rather than urllib: the Cloudflare front door 403s a python-urllib + User-Agent, and curl's --retry covers transient 5xx. + """ + cmd = [ + "curl", "-sS", "--http1.1", + "--retry", "5", "--retry-all-errors", "--retry-delay", "3", + "--connect-timeout", "20", "--max-time", "60", + "-H", f"User-Agent: {USER_AGENT}", + "-H", "Accept: application/json", + ] + if token: + cmd += ["-H", f"Authorization: Bearer {token}"] + if body is not None: + cmd += ["-H", "Content-Type: application/json", + "-X", method, "--data-binary", json.dumps(body)] + cmd += ["-w", "\n%{http_code}", url] + proc = subprocess.run(cmd, capture_output=True, text=True, check=False) + if proc.returncode != 0: + raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}") + raw, _, code = proc.stdout.rpartition("\n") + try: + parsed = json.loads(raw) if raw.strip() else None + except json.JSONDecodeError: + parsed = None + return int(code or 0), parsed + + +def ver(text: str): + """('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise + version format upstream is loud rather than silently 'not an upgrade'.""" + m = SEMVER.match(text.strip()) + if not m: + raise HardFail(f"cannot parse version {text!r}") + return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)) + + +def parse_pins(cargo_toml: str): + """{crate: version_requirement} for the [dependencies] table only.""" + pins: dict[str, str] = {} + section = "" + for line in cargo_toml.splitlines(): + stripped = line.strip() + if stripped.startswith("["): + section = stripped.strip("[]").strip() + continue + if section != "dependencies" or not stripped or stripped.startswith("#"): + continue + m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped) + if not m: + continue + name, rest = m.group(1), m.group(2).split("#", 1)[0].strip() + if not WATCHED.match(name): + continue + vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest) + if vm: + pins[name] = vm.group(1) + return pins + + +def crates_io(name: str): + """(stable, newest) version strings for a crate, as crates.io reports them.""" + status, data = curl_json(CRATES_API.format(name=name)) + if status != 200 or not isinstance(data, dict) or "crate" not in data: + raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})") + crate = data["crate"] + return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"] + + +@dataclass +class Row: + name: str + pin: str + pin_triple: tuple + stable: str + newest: str + source: str # "Cargo.toml" or "simulate-pin" + + @property + def pin_minor(self) -> str: + return f"{self.pin_triple[0]}.{self.pin_triple[1]}" + + @property + def upgrade(self) -> bool: + stable = ver(self.stable) + return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1]) + + +def issue_title(row: Row) -> str: + stable = ver(row.stable) + return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}" + + +def issue_body(row: Row) -> str: + if row.source == "Cargo.toml": + lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**." + else: + lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, " + f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came " + f"from a `workflow_dispatch` test run — the repository pin has not changed.") + return f"""{lead} + +| | | +|---|---| +| crate | `{row.name}` | +| pinned requirement | `"{row.pin}"` | +| pin source | {row.source} | +| newest stable upstream | `{row.stable}` | +| newest upstream (incl. pre-release) | `{row.newest}` | +| crates.io | https://crates.io/crates/{row.name} | +| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases | + +Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole +`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do +not bump this one alone. + +Procedure, toolchain floor, and the tests a bump must pass: +[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor +is rustc 1.91+ (Arti 0.46); a bump may raise it. + +The watcher does **not** subscribe to Tor Project security announcements, and it +cannot see a yanked crate or a vulnerability that ships without a version bump. +""" + + +def existing_titles(repo_api: str, token: str) -> dict: + """{title: issue_number} over every issue, open and closed, paginated.""" + seen: dict[str, int] = {} + page = 1 + while True: + url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}" + status, data = curl_json(url, token) + if status != 200 or not isinstance(data, list): + raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})") + for item in data: + seen[item["title"]] = item["number"] + if len(data) < 50: + return seen + page += 1 + + +def main() -> int: + ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) + ap.add_argument("--cargo-toml", default="Cargo.toml") + ap.add_argument("--dry-run", action="store_true", + help="compare and log only; file no issue and need no token") + ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION", + help="pretend CRATE is pinned at VERSION (test the alert path " + "against real crates.io data without waiting for upstream)") + args = ap.parse_args() + + with open(args.cargo_toml, encoding="utf-8") as fh: + pins = parse_pins(fh.read()) + if not pins: + raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}") + + overrides = {} + for pair in args.simulate_pin: + name, _, version = pair.partition("=") + name, version = name.strip(), version.strip() + if name not in pins or not version: + raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}") + overrides[name] = version + + rows = [] + for name in sorted(pins): + source = "Cargo.toml" + pin = pins[name] + if name in overrides: + pin, source = overrides[name], "simulate-pin" + pin_triple = ver(pin) + stable, newest = crates_io(name) + rows.append(Row(name, pin, pin_triple, stable, newest, source)) + + log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):") + for row in rows: + log(f" {row.name}: pinned={row.pin} (from {row.source}) " + f"upstream_stable={row.stable} upstream_newest={row.newest} " + f"upgrade={'yes' if row.upgrade else 'no'}") + + todo = [row for row in rows if row.upgrade] + if not todo: + log("no upgrade available: every pin already covers the newest upstream release") + return 0 + + if args.dry_run: + for row in todo: + log(f"dry-run: would file issue {issue_title(row)!r}") + return 0 + + repo_api = os.environ.get("REPO_API", "").rstrip("/") + token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split()) + if not repo_api or not token: + raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run") + + titles = existing_titles(repo_api, token) + filed = 0 + for row in todo: + title = issue_title(row) + if title in titles: + log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one") + continue + status, created = curl_json(f"{repo_api}/issues", token, "POST", + {"title": title, "body": issue_body(row)}) + if status != 201 or not isinstance(created, dict): + raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})") + filed += 1 + log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})") + log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except HardFail as exc: + log(f"error: {exc.msg}") + sys.exit(exc.code) From 6f96d19901861a7f1d38fb79de38a57978bc9b71 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 12:48:28 -0400 Subject: [PATCH 3/3] ci: watch upstream Arti/tor-* releases daily and file an upgrade issue .forgejo/workflows/arti-watch.yml runs daily (06:17 UTC) and via workflow_dispatch: scripts/arti-watch.py compares each tor-*/arti-* pin in Cargo.toml against crates.io and files one Forgejo issue per distinct major.minor bump, deduped on the title so a repeat run is a no-op. It changes no dependency. docs/ARTI_UPGRADE.md records the pinned set (arti-client, tor-cell, tor-hsservice, tor-rtcompat at 0.46), the lockstep rule, the rustc 1.91 floor, and the tests a bump must pass (tests/tor_hs.rs live publish + probe-connect + byte pipe, the 360s fail-closed wait and the src/hs.rs circuit-timeout workarounds in tests/hs.rs, the Android rustls build). Both artefacts state what this does not cover: Tor Project security announcements, a yanked crate, and a vulnerability with no version bump. --- .forgejo/workflows/arti-watch.yml | 72 ++++++++ docs/ARTI_UPGRADE.md | 143 +++++++++++++++ scripts/arti-watch.py | 279 ++++++++++++++++++++++++++++++ 3 files changed, 494 insertions(+) create mode 100644 .forgejo/workflows/arti-watch.yml create mode 100644 docs/ARTI_UPGRADE.md create mode 100644 scripts/arti-watch.py diff --git a/.forgejo/workflows/arti-watch.yml b/.forgejo/workflows/arti-watch.yml new file mode 100644 index 0000000..10a0e5f --- /dev/null +++ b/.forgejo/workflows/arti-watch.yml @@ -0,0 +1,72 @@ +name: arti-watch + +# Daily upstream check for the in-process Tor stack. Arti onion services are +# experimental (README) and tor-*/arti-* are the largest attack surface here, +# so when crates.io has a newer major.minor than the pins in Cargo.toml this +# files ONE Forgejo issue (deduped on the title — a second run is a no-op). +# +# Forgejo has no Dependabot: this workflow IS the dependency alert. It +# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain +# floor and the tests it must pass are in docs/ARTI_UPGRADE.md. +# +# NOT covered, by design: Tor Project security announcements (a fix that ships +# with no crates.io version bump is invisible here) and a yanked crate / +# vulnerability in a version that has not changed. Read +# https://blog.torproject.org/ yourself. +on: + schedule: + # 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose. + - cron: "17 6 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Compare and log only, file no issue (true/false) + required: false + type: string + default: "false" + simulate_pin: + description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.' + required: false + type: string + +# Never two watchers at once: two simultaneous runs could both see "no issue +# with this title yet" and file twice. +concurrency: + group: onionwire-arti-watch + cancel-in-progress: false + +jobs: + watch: + # Same Pi runner + `docker` job image as ci.yml / release.yml (which run + # python3 and curl there). No cargo, no docker: four crates.io GETs and at + # most one issue POST. + runs-on: docker + timeout-minutes: 10 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: Compare pins against crates.io and file an issue on a bump + shell: bash + env: + FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} + REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} + INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }} + INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }} + run: | + set -euo pipefail + args=(--cargo-toml Cargo.toml) + case "${INPUT_DRY_RUN:-false}" in + true|True|TRUE|1|yes|YES) args+=(--dry-run) ;; + esac + if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then + IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN" + for pair in "${pairs[@]}"; do + pair="${pair// /}" + if [ -n "$pair" ]; then + args+=(--simulate-pin "$pair") + fi + done + fi + echo "run: python3 scripts/arti-watch.py ${args[*]}" + python3 scripts/arti-watch.py "${args[@]}" diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md new file mode 100644 index 0000000..bb0ad7b --- /dev/null +++ b/docs/ARTI_UPGRADE.md @@ -0,0 +1,143 @@ +# Upgrading the Arti / Tor crates + +The in-process Tor stack is the largest attack surface in OnionWire. Arti's +onion services are still **experimental** and OnionWire does not fall back to a +C-tor subprocess, so an upstream fix only reaches users when we bump these +crates, rebuild, and cut a release. + +## What is pinned + +Direct dependencies that come from the Arti repository, exactly as +`Cargo.toml` has them: + +| crate | requirement | features in `Cargo.toml` | +|---|---|---| +| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` | +| `tor-cell` | `0.46` | — | +| `tor-hsservice` | `0.46` | — | +| `tor-rtcompat` | `0.46` | `tokio` | + +`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not +part of a Tor upgrade. + +Two crate features re-expose Arti's TLS backends, which Arti marks +**non-additive** — exactly one may be selected per build graph: + +* `native-tls` (default) → Linux TUI build, via OpenSSL. +* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has + no OpenSSL. + +Published Arti releases move all four crates together in lockstep. Bump them as +**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is +not a configuration anyone tests upstream, and cargo will usually refuse or +silently pick one `tor-*` version and mismatched `tor-*` internals fail at +runtime. + +## Toolchain floor + +**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`; +the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm` +(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`). + +A bump may raise the floor. Take the actual MSRV from the upstream release +notes / the crate's own `rust-version`, then raise it in the same PR: + +* `rust-version` in `Cargo.toml`, +* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`, +* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it + when that lands, or ask the owner). + +## How this gets noticed + +`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks +crates.io for the newest stable version of each crate above. If the +major.minor moved past the pin, it files one Forgejo issue titled +`Arti upstream: → `. It is deduped on that title across open +and closed issues, so re-running it never files a second issue and never +comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit. + +Test the alert path without waiting for upstream (it compares real crates.io +data against a pretend pin): + +``` +# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45 +python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45 +``` + +**What the watcher does not cover.** It does not subscribe to Tor Project +security announcements — a fix that ships without a crates.io version bump is +invisible to it. It will not catch a yanked crate, and it will not catch a +vulnerability in a version that has not changed. Watch + and yourself, and +treat a Tor security advisory as an instruction to bump **now**, ahead of any +issue the watcher files. + +## Procedure + +1. Read the upstream release notes (Arti tags: ) + and the CHANGELOG for breaking API changes. Check the new MSRV. +2. Branch from `main`; bump all four requirements in `[dependencies]` of + `Cargo.toml` together, and `rust-version` if the floor moved. +3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is + committed): + ``` + cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat + git diff --stat Cargo.lock + ``` + Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate + moving alone is a sign the set is not actually lockstep — stop and look. +4. Build and run the offline suite: + ``` + cargo test --locked + cargo clippy --locked --all-targets -- -D warnings + ``` +5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish + path is slow and its circuit timeouts misbehave on hidden-service circuits, + and an upstream fix or behaviour change can make any of them wrong: + + | constant | why | guard | + |---|---|---| + | `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` | + | `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` | + | `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` | + | `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` | + + Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure + the rend handler is spawned *before* the probe wait, or the probe cannot + succeed at all. +6. Run the live two-node test on a networked machine. This is the only test that + proves the hidden service actually publishes and that a second node can + reach it: + ``` + cargo test --locked --test tor_hs -- --ignored --nocapture + ``` + It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant` + covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir + descriptor upload, not a hang), probe-connect against a live HS, a byte pipe + in both directions, restart, and the dormant/offline path. +7. Confirm the fail-closed path by hand if the publish wait changed at all: + with the write timeout still 360s, a peer whose onion is down must fail the + send. There is no outbox in v1 — the message must not be silently queued. +8. Rebuild the Android target — Arti's TLS backends are non-additive, and this + is the build that exercises the `rustls` feature: + ``` + scripts/build-android-local.sh + ``` +9. Verify the ciphertext claim still holds after the bump: send a message + between the two nodes, then + ``` + grep -r "" + ``` + must find nothing. The bodies live in sqlite as ciphertext, and nothing about + the plaintext should appear in Arti's state directory. +10. Open a PR against `main` describing: crates bumped, MSRV, the live-test + output, and anything upstream changed that touches `src/hs.rs`. Do not push + `main`; releases are minted by `.forgejo/workflows/release.yml` from a merge. + +## Rolling back + +Revert the version bump and the lockfile stanza together, re-run step 3's +`cargo update` only if the revert leaves the lockfile inconsistent, and re-run +`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and +`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the +intent. diff --git a/scripts/arti-watch.py b/scripts/arti-watch.py new file mode 100644 index 0000000..c7de9ab --- /dev/null +++ b/scripts/arti-watch.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins. + +Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on +the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency +it reads the version requirement in Cargo.toml, asks crates.io for the newest +published versions, and — when the major.minor moved — files ONE Forgejo issue. +The issue title carries the compared pair, e.g. + + Arti upstream: tor-hsservice 0.46 -> 0.47 + +Dedupe is on that title across all issues (open and closed), so a second run is +a no-op: no duplicate issue, no repeated comment. Nothing here bumps a +dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md. + +What this does NOT cover, by design: + * It does not subscribe to Tor Project security announcements. A fix that + ships without a crates.io version bump is invisible to this script. + * It will not catch a yanked crate, and it will not catch a vulnerability in + a version that has not changed. crates.io `max_stable_version` already + ignores yanks, so a yank alone produces no alert. + Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself. + +Usage: + FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \ + scripts/arti-watch.py --cargo-toml Cargo.toml + scripts/arti-watch.py --dry-run # no API writes, no token + scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45 +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass + +CRATES_API = "https://crates.io/api/v1/crates/{name}" +# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in +# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own. +USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)" +WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$") +# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch. +SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$") + + +def log(msg: str) -> None: + print(msg, flush=True) + + +class HardFail(SystemExit): + def __init__(self, msg: str) -> None: + super().__init__(2) + self.msg = msg + + +def curl_json(url, token=None, method="GET", body=None): + """curl a JSON endpoint. Returns (http_status, parsed_body_or_None). + + curl rather than urllib: the Cloudflare front door 403s a python-urllib + User-Agent, and curl's --retry covers transient 5xx. + """ + cmd = [ + "curl", "-sS", "--http1.1", + "--retry", "5", "--retry-all-errors", "--retry-delay", "3", + "--connect-timeout", "20", "--max-time", "60", + "-H", f"User-Agent: {USER_AGENT}", + "-H", "Accept: application/json", + ] + if token: + cmd += ["-H", f"Authorization: Bearer {token}"] + if body is not None: + cmd += ["-H", "Content-Type: application/json", + "-X", method, "--data-binary", json.dumps(body)] + cmd += ["-w", "\n%{http_code}", url] + proc = subprocess.run(cmd, capture_output=True, text=True, check=False) + if proc.returncode != 0: + raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}") + raw, _, code = proc.stdout.rpartition("\n") + try: + parsed = json.loads(raw) if raw.strip() else None + except json.JSONDecodeError: + parsed = None + return int(code or 0), parsed + + +def ver(text: str): + """('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise + version format upstream is loud rather than silently 'not an upgrade'.""" + m = SEMVER.match(text.strip()) + if not m: + raise HardFail(f"cannot parse version {text!r}") + return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)) + + +def parse_pins(cargo_toml: str): + """{crate: version_requirement} for the [dependencies] table only.""" + pins: dict[str, str] = {} + section = "" + for line in cargo_toml.splitlines(): + stripped = line.strip() + if stripped.startswith("["): + section = stripped.strip("[]").strip() + continue + if section != "dependencies" or not stripped or stripped.startswith("#"): + continue + m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped) + if not m: + continue + name, rest = m.group(1), m.group(2).split("#", 1)[0].strip() + if not WATCHED.match(name): + continue + vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest) + if vm: + pins[name] = vm.group(1) + return pins + + +def crates_io(name: str): + """(stable, newest) version strings for a crate, as crates.io reports them.""" + status, data = curl_json(CRATES_API.format(name=name)) + if status != 200 or not isinstance(data, dict) or "crate" not in data: + raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})") + crate = data["crate"] + return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"] + + +@dataclass +class Row: + name: str + pin: str + pin_triple: tuple + stable: str + newest: str + source: str # "Cargo.toml" or "simulate-pin" + + @property + def pin_minor(self) -> str: + return f"{self.pin_triple[0]}.{self.pin_triple[1]}" + + @property + def upgrade(self) -> bool: + stable = ver(self.stable) + return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1]) + + +def issue_title(row: Row) -> str: + stable = ver(row.stable) + return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}" + + +def issue_body(row: Row) -> str: + if row.source == "Cargo.toml": + lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**." + else: + lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, " + f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came " + f"from a `workflow_dispatch` test run — the repository pin has not changed.") + return f"""{lead} + +| | | +|---|---| +| crate | `{row.name}` | +| pinned requirement | `"{row.pin}"` | +| pin source | {row.source} | +| newest stable upstream | `{row.stable}` | +| newest upstream (incl. pre-release) | `{row.newest}` | +| crates.io | https://crates.io/crates/{row.name} | +| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases | + +Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole +`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do +not bump this one alone. + +Procedure, toolchain floor, and the tests a bump must pass: +[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor +is rustc 1.91+ (Arti 0.46); a bump may raise it. + +The watcher does **not** subscribe to Tor Project security announcements, and it +cannot see a yanked crate or a vulnerability that ships without a version bump. +""" + + +def existing_titles(repo_api: str, token: str) -> dict: + """{title: issue_number} over every issue, open and closed, paginated.""" + seen: dict[str, int] = {} + page = 1 + while True: + url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}" + status, data = curl_json(url, token) + if status != 200 or not isinstance(data, list): + raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})") + for item in data: + seen[item["title"]] = item["number"] + if len(data) < 50: + return seen + page += 1 + + +def main() -> int: + ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) + ap.add_argument("--cargo-toml", default="Cargo.toml") + ap.add_argument("--dry-run", action="store_true", + help="compare and log only; file no issue and need no token") + ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION", + help="pretend CRATE is pinned at VERSION (test the alert path " + "against real crates.io data without waiting for upstream)") + args = ap.parse_args() + + with open(args.cargo_toml, encoding="utf-8") as fh: + pins = parse_pins(fh.read()) + if not pins: + raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}") + + overrides = {} + for pair in args.simulate_pin: + name, _, version = pair.partition("=") + name, version = name.strip(), version.strip() + if name not in pins or not version: + raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}") + overrides[name] = version + + rows = [] + for name in sorted(pins): + source = "Cargo.toml" + pin = pins[name] + if name in overrides: + pin, source = overrides[name], "simulate-pin" + pin_triple = ver(pin) + stable, newest = crates_io(name) + rows.append(Row(name, pin, pin_triple, stable, newest, source)) + + log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):") + for row in rows: + log(f" {row.name}: pinned={row.pin} (from {row.source}) " + f"upstream_stable={row.stable} upstream_newest={row.newest} " + f"upgrade={'yes' if row.upgrade else 'no'}") + + todo = [row for row in rows if row.upgrade] + if not todo: + log("no upgrade available: every pin already covers the newest upstream release") + return 0 + + if args.dry_run: + for row in todo: + log(f"dry-run: would file issue {issue_title(row)!r}") + return 0 + + repo_api = os.environ.get("REPO_API", "").rstrip("/") + token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split()) + if not repo_api or not token: + raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run") + + titles = existing_titles(repo_api, token) + filed = 0 + for row in todo: + title = issue_title(row) + if title in titles: + log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one") + continue + status, created = curl_json(f"{repo_api}/issues", token, "POST", + {"title": title, "body": issue_body(row)}) + if status != 201 or not isinstance(created, dict): + raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})") + filed += 1 + log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})") + log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except HardFail as exc: + log(f"error: {exc.msg}") + sys.exit(exc.code)