Skip to content

Review batch: CLI validation, replay read-only, export safety, docs and CI - #171

Merged
lance0 merged 21 commits into
masterfrom
fix/review-batch-2026-11
Nov 12, 2026
Merged

lance0 merged 21 commits into
masterfrom
fix/review-batch-2026-11

Conversation

@lance0

@lance0 lance0 commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Batch of low-risk fixes from a deep review of the codebase. One commit per fix. No probing behaviour, packet layout, or shutdown ordering changes: the two high-severity findings from the review are deliberately not here (see below).

What changes

CLI validation

  • derive_flow_hint compares the flow-port window in u32: --src-port 65520 --flows 16 (and --src-port 65535) is accepted by validation but overflowed the u16 bound to an empty window — a debug-build panic in the receiver thread, 100% loss in release.
  • Unknown --theme values are rejected with the offending name and the valid list, instead of silently starting in the default theme and then persisting that default over the saved one. Documented aliases (mono, futuristic, hacker, mocha, tokyo, tokyonight) still work.
  • --replay and --diff reject probe-only flags (positional target, -c, -i, -m, --timeout, -p, --port, --fixed-port, --flows, --src-port, --rate, --size, --dscp, --interface, --source-ip) that those modes accepted and silently ignored. Output and presentation flags are unaffected.

Replay is read-only

  • r and p on a session loaded from a file used to blank the hop table, drop dest_ttl and clear events, so the next e export wrote an all-zero session over the recording. They now report Replay is read-only, and the static-replay status bar no longer advertises reset.

TUI correctness

  • Three width budgets: the Settings footer shows Enter select (it never fit at the 48-column cap), a long status message keeps the highest-priority hint instead of blanking the row, and target rows pad by terminal cells so a double-width hostname no longer truncates the loss and RTT columns.
  • Settings opens with the active theme on screen instead of always at the top of the five-row list; a target added while monitoring is paused stays paused, so the badge and the engine agree.

Errors and export safety

  • Failed preference saves warn with the path instead of being discarded; --resolve-all names the host that failed to resolve; -c 0 with a batch output mode says a positive count is required instead of claiming -c was not set.
  • Exports refuse a symlinked destination. Export names are predictable and target-derived, so a planted link in the working directory could redirect the replacement onto any file the user can write. Preferences still follow dotfile symlinks deliberately.
  • CSV hostnames cannot inject spreadsheet formulas: a PTR record starting with =, +, -, @, tab or CR is prefixed with an apostrophe (CWE-1236).
  • The saved PeeringDB API key now applies to --json, --csv, --report, --stream-json and --daemon, not just the TUI, so cache refreshes in headless runs are no longer rate limited into ix: null.

Cleanup, docs, CI

  • Drop four dead pub helpers and ResponderStats::loss_pct; replace is-terminal with std::io::IsTerminal (std since 1.70, crate MSRV 1.88).
  • Docs: no --dns flag exists, the replay progress bar has no event count, route changes carry a response count rather than a timestamp, and FreeBSD interface binding is not implemented.
  • CI builds and lints the documented --no-default-features configuration, which no leg compiled before.

Deliberately not included

  • -c completion cancels the shared token (high): the first target to finish its rounds cancels every other engine and makes the receiver flush in-flight probes as timeouts, truncating multi-target runs and inventing loss. Changes shutdown ordering; wants a live testbed.
  • Final-round IPv6 Echo Replies are never drained (high): Linux delivers them only to the send socket, which is polled at the end of a round, after the -c check. Same reason: raw ICMPv6 socket behaviour that cannot be exercised without CAP_NET_RAW.
  • Deferred to their own review: route-flap hysteresis on per-packet-balanced hops, the unbounded per-hop responder map, the unbounded live probe-event log, add-target cancellation, LateReply replay accounting, pending probes surviving a stats reset, UDP quotes containing only the transport header, and PMTUD leaving DF set on the shared socket plus taking a write lock every tick. Each changes observable probe accounting, display bounds or export contents.

Verification

cargo test                                                       # 864 passed, 0 failed, 4 ignored (405 lib, 424 bin, 33 integration, 1 replay_size, 1 doctest)
cargo clippy --all-targets -- -D warnings                        # clean
cargo clippy --all-targets --no-default-features -- -D warnings   # clean
RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --document-private-items   # clean
cargo fmt -- --check                                             # clean

Each behavioural fix has a regression test, and three of them were confirmed to fail against the pre-fix code before being kept (target padding, theme scroll, export symlink). Runtime checks through the built binary: --theme dracul, --json -c 0, --replay x.json -c 5, --replay x.json 1.1.1.1, a read-only XDG_CONFIG_HOME (preference warning now printed with the path), and colour suppressed on a pipe with colour restored on a pty.

Not verified here: anything needing raw sockets (CAP_NET_RAW unavailable in this environment) and the TUI render loop itself (TERM=dumb, no interactive terminal).

derive_flow_hint compared the source port against
`src_port_base + num_flows` as a u16. Args::validate accepts
`src_port + flows - 1 <= u16::MAX`, so `--src-port 65520 --flows 16`
(and `--src-port 65535` with the default single flow) computed 65536:
a debug-build panic in the receiver thread, and in release a wrapped
bound of 0 that emptied the window, so every reply was reported as
unknown-flow and dropped as 100% loss.

Compare the offset in u32 instead, and cover the boundary at the
receiver rather than only in Args::validate.
`--theme` had no value parser or validation. An unknown name fell through
Theme::by_name to the default theme with no message, and quitting then
persisted that default over the theme the user had saved, so a one-letter
typo silently discarded the preference.

Split Theme::by_name into an Option-returning resolve plus a
Theme::is_known_name predicate over the same name/alias table, and reject
unknown values in Args::validate with the offending name and the valid
list.
--diff declared conflicts with targets and --replay did not, and the
replay/diff validation block only rejected --pmtud and --jumbo. So
`ttl --replay trace.json 1.1.1.1 -c 5 --flows 4` was accepted while the
target, round count, flows, port, rate, size, protocol, interface and
source address were all silently ignored: run_replay_mode reads none of
them.

Give --replay the same targets conflict as --diff, and reject deviations
from the probe defaults in either mode with an error naming the flag.
Output and presentation flags (--json/--csv/--report/--theme/--wide/
--animate/--no-update-check/--replay-size-limit) still apply.
The `r` handler was unconditional while `p` and `o` were guarded. A
session opened with --replay has no live epoch, so reset_stats blanked the
hop table, dropped dest_ttl, cleared events and made the trace look live;
pressing `e` afterwards exported an all-zero session over the recording.
The static-replay status bar advertised the key.

Gate reset and pause on the session having a live epoch, report
"Replay is read-only" instead of a lying "Stats reset"/"Resumed", and
drop the reset hint from the static-replay hint set. Factor the duplicated
live-pause body out of `p` and Space, which also makes the badge follow
the session's own paused flag rather than a separate copy.
1. The settings footer could never show `Enter select`: the popup is capped
   at 48 columns and `popup()` budgets hints as width - 6, so the four pairs
   (46 cells) never fit the 42-cell budget at any terminal size, even though
   Enter is the modal's only action key. Widen the popup to 52.

2. A long status message removed every key hint. The message was fitted to
   the full bar width and the remainder sized the hint line, so a 41-cell
   export message at width 50 left 5 cells, which fits no pair. Reserve the
   highest-priority hint before sizing the message, and cover the narrow
   widths the old test skipped.

3. The target list padded hostnames with `{:<width$}`, which pads by chars
   while `fit_text` bounds cells. A name of double-width characters
   overflowed `row_width`, and the resulting whole-line truncation dropped
   the loss and RTT columns. Pad by cells and size the name column in cells.
…sync

Settings always opened the theme list at scroll 0 while the list shows five
rows, so a theme picked with `t` before pressing `s` was off screen with no
selection marker, and Up/Down only scrolled it back into view once the index
walked into the first page. Initialise the scroll from the active index, and
share one VISIBLE_THEMES constant with the render window and move_down
instead of a third copy of 5.

Adding a target while paused left the badge claiming PAUSED while the new
session probed immediately. Propagate the pause to the session that just
joined, so the badge and the engine agree; the poll now takes the session map
and both call sites pass it.
…olve

Two errors were reported in a way the user could not act on:

* Both preference-save sites discarded the error (`let _ = final_prefs.save()`),
  so a read-only config directory silently lost the theme, display mode, API
  key and update-check changes. Warn to stderr with the failing path.
* `--resolve-all` wrapped the whole loop in a generic "Failed to resolve
  targets", so with several targets there was no way to tell which name was
  broken. Add the per-host context the single-target path already had.
* `--json -c 0` claimed `-c` was not set although it was: say that batch
  output needs a positive count and that `-c 0` runs until quit.
A hop's PTR record is controlled by whoever runs that address, and the
hostname column is written verbatim. `=cmd|' /C calc'!A0.example` is a live
formula to Excel and LibreOffice, which is CWE-1236 on the analyst's
workstation.

Prefix a leading =, +, -, @, tab or CR with an apostrophe so the cell stays
literal, keeping the existing quoting rules (and so the field count) intact.
Only hostname passes through escape_csv; every other column is numeric.
`atomic_write` canonicalised the destination unconditionally, so a
planted `ttl-<target>-<timestamp>.json -> ~/.bashrc` in the directory the
user exports from redirected the rename onto the link target, replacing an
arbitrary user-writable file with trace JSON.

Following a link is deliberate for preferences (dotfile config links must
survive), so split the writer: exports use a non-resolving variant that
refuses a symlinked destination outright, while Prefs::save keeps the
canonicalising path and its existing test.
Four pub functions had no caller in src/, tests/ or examples/ and were kept
alive only by #[allow(dead_code)]: Session::discovered_hops,
Session::last_responding_hop, Session::first_nat_hop and
probe::interface::get_interface_source_ip. They are part of the crate's
public surface, so they constrained semver and documented filtering rules
nothing consumed. ResponderStats::loss_pct goes too — its own doc called it
inaccurate, Hop::loss_pct holds the real formula — along with the assertion
that only exercised it.

is-terminal 0.4 says in its own README that std::io::IsTerminal supersedes
it as of Rust 1.70, and this crate's MSRV is 1.88. Switch the two call sites
and drop the dependency.
The TUI set the key on its IxLookup; run_batch_mode and run_streaming_mode
called IxLookup::new() and never loaded Prefs, so a key configured in
Settings only helped interactive runs. After the 24 h IX cache expired,
`-c 10 --json`, `--report`, `--stream-json` and `--daemon --prometheus`
silently fell back to anonymous access, got rate limited, and exported
`ix: null` for every responder — the scripting path the docs recommend the
key for.

Route all three modes through one build_ix_lookup(config, prefs) so they
cannot drift again; PEERINGDB_API_KEY still wins inside the lookup.
* CHANGELOG 0.24.0 named an unreachable `--dns` server as the way to
  reproduce the cancelled-lookup fix. No such flag exists (only `--no-dns`
  and the system resolver); say "system resolver".
* docs/FEATURES.md promised the replay progress bar shows an event count. It
  shows clock and speed, and the test that pins the label is named
  replay_label_shows_clock_and_speed_without_event_counts.
* docs/FEATURES.md promised route-change history "with timestamps".
  RouteChange stores only from_ip, to_ip and at_seq, and the view renders
  "after N responses".

The fourth item — the module header in src/probe/interface.rs claiming
FreeBSD interface binding works — was fixed with the dead-code removal.
docs/INSTALL.md and docs/FEATURES.md tell packagers to build with
`--no-default-features` to drop the startup update check and the
update-informer dependency, but no CI leg ever built that configuration, so a
change referencing update_informer outside its cfg block would ship green.
Add a check and a clippy run for it to the build job.
@lance0
lance0 force-pushed the fix/review-batch-2026-11 branch from f1d4306 to b3610a3 Compare November 12, 2026 18:40
The read-only guard keyed on the session having no live epoch, but an
--animate replay draws into a fresh Session::new, which has one. Pressing
r mid-playback blanked the hops and events, later events rebuilt only part
of the trace, and an e export then wrote that partial session. Refuse the
reset whenever a replay is active, not only for a static replay.
Propagating the pause to the added target also ran when the reply said the
target already existed. Re-adding a running target while viewing a paused
one then silently paused the running target. For an existing target, only
select it and take the badge from that session's own paused flag.
The replay/diff probe-flag check compared the raw -p value against
"auto", while live mode lowercases it. So `--replay x.json -p AUTO`, a
no-op default, was rejected. Compare the lowercased protocol instead.
The new warning printed the error with {}, which for anyhow shows only the
outermost message: a read-only config directory reported "Failed to create
temporary save in <dir>" without the reason, and a failed create_dir_all
reported the OS error without any path. Give create_dir_all a path context
and print the whole chain.
@lance0
lance0 marked this pull request as ready for review November 12, 2026 23:17
@lance0
lance0 merged commit 47638fd into master Nov 12, 2026
7 checks passed
@lance0
lance0 deleted the fix/review-batch-2026-11 branch November 12, 2026 23:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant