Compare commits

..

10 commits
main ... v2.1.6

Author SHA1 Message Date
Breadway
c10e8dc5e8 Switch to tag-pinned bread-ecosystem deps; bump version to v2.1.6
All checks were successful
Mirror to GitHub / mirror (push) Successful in 2s
release / build (push) Successful in 38s
Build and publish package / package (push) Successful in 46s
2026-07-19 03:52:39 +08:00
Breadway
59416fb273 Promote util::run to bread_utils::proc; delegate write_atomic
This crate's util::run/run_with_stdin/run_ok/Output was cited as the one
correct, timeout-guarded subprocess implementation in the ecosystem worth
sharing — it's now promoted verbatim into bread-utils and re-exported here
so every existing crate::util::{run, ...} call site (notify.rs, nm.rs,
status.rs, tailscale.rs) keeps working unchanged. write_atomic similarly
delegates to bread_utils::atomic::write_atomic (path dependency for now,
see the TODO in Cargo.toml). home_dir/command_exists/timestamp stay local
— they're breadcrumbs-specific, not duplicated elsewhere.

New worktree for this repo (none existed from tonight's earlier passes,
since breadcrumbs needed no audit fixes then).

Builds clean; all 74 unit tests + 25 CLI integration tests pass.
2026-07-17 09:35:23 +08:00
Breadway
b786060517 Stop injecting phantom core profiles into a customized profile set
All checks were successful
Mirror to GitHub / mirror (push) Successful in 2s
release / build (push) Successful in 38s
Build and publish package / package (push) Successful in 45s
ensure_core_profiles() was unconditionally backfilling home/work/away
into the in-memory config on every load, even when the user had
already defined their own profiles (e.g. Home/Away/School). This
showed up as duplicate/phantom lowercase entries in `breadcrumbs
profile list`, and downstream in breadbar and bos-settings.

Now the self-heal only fires when the profile set is completely
empty (a genuinely fresh or corrupted config), never padding an
existing customized set.
2026-07-10 13:37:41 +08:00
Breadway
941742c5b6 2.1.4: fix blank exit-node rendering, relabel for clarity
Some checks failed
Mirror to GitHub / mirror (push) Successful in 4s
Build and publish package / package (push) Successful in 1m19s
release / build (push) Failing after 52s
"(exit: , optional)" printed with nothing after the colon whenever no
Tailscale exit node was configured (the default). Now renders "none",
and relabels "exit:" to "exit node:" -- the abbreviated form read as an
exit *code* at a glance, which is what led to this being misdiagnosed
as a process-exit-code formatting bug in the first place.
2026-07-05 09:14:46 +08:00
Breadway
b8121ae00f Fix breadcrumbs.service: default.target not graphical-session.target
All checks were successful
Mirror to GitHub / mirror (push) Successful in 1s
release / build (push) Successful in 35s
Build and publish package / package (push) Successful in 44s
graphical-session.target ships RefuseManualStart=yes and BOS has no
session manager to activate it properly (the same issue worked around
for breadclipd) - breadcrumbs doesn't need a Wayland session anyway,
so default.target avoids the problem entirely.
2026-07-03 17:59:38 +08:00
Breadway
2418cb900c Add systemd --user service for the watch daemon
All checks were successful
Mirror to GitHub / mirror (push) Successful in 1s
release / build (push) Successful in 37s
Build and publish package / package (push) Successful in 1m0s
breadcrumbs had a watch subcommand meant to run continuously but no
systemd unit anywhere, so bakery installs never actually started it -
Wi-Fi profile config in bos-settings had no daemon consuming it.
2026-07-03 17:56:06 +08:00
Breadway
3b6e37ecfe CI: migrate release workflow from GitHub Actions to Forgejo Actions
All checks were successful
Mirror to GitHub / mirror (push) Successful in 1s
GitHub Actions self-hosted runners need per-repo registration on a
personal account; Forgejo Actions' runner already serves every repo
with zero setup. Moves release publishing there (dl.breadway.dev stays
the primary bakery target; GitHub release upload is kept as the
fallback via an explicit token, since Forgejo Actions has no ambient
GITHUB_TOKEN) and adds a mirror workflow to keep GitHub in sync
automatically.
2026-07-03 14:10:05 +08:00
Breadway
0fdac8e07c Add join, networks, and scan-list commands; bump to v2.1.1
All checks were successful
Mirror to GitHub / mirror (push) Successful in 3s
2026-06-24 07:04:31 +08:00
Breadway
d3c1e19ba3 Release v2.1.0: backend test seam, captive-portal detection, JSON status, robustness
Features:
- Introduce a Backend trait + System impl so flow/status/watch can be unit
  tested against a fake; add 11 connect-state-machine tests.
- Captive-portal detection: status::connectivity returns Online/Portal/Offline;
  surfaced in status, JSON, connect notes, and a dedicated watch state.
- `status --json` for bars/scripts; `profile add`/`profile remove`; detect now
  scores by number of in-range markers.

Robustness:
- Pin LC_ALL=C/LANG=C on child processes for locale-independent parsing.
- Atomic config/state writes (temp + rename); 0600 config never world-readable.
- Transient PSK file written to $XDG_RUNTIME_DIR when available.

Fixes (from prior audit):
- Feed Wi-Fi PSK to nmcli via stdin/passwd-file, never argv.
- mask() no longer panics on multi-byte passwords.
- Connectivity check requires HTTP 204 (no captive-portal false positives).
- nmcli NAME,TYPE parsing handles escaped colons.
- Strip CIDR suffix from displayed IP; PKGBUILD/Cargo version aligned (2.1.0).
2026-06-23 12:13:34 +08:00
Breadway
8aceab7857 CI: use /tmp for ecosystem clone; fix rustfmt violations
All checks were successful
Mirror to GitHub / mirror (push) Successful in 2s
2026-06-19 08:38:40 +08:00
39 changed files with 2902 additions and 8069 deletions

View file

@ -1,24 +0,0 @@
name: check
# Fast-fail lint/test on short-lived work branches, before it ever reaches
# main and triggers a dev-track release build.
on:
push:
branches: ['feature/**', 'fix/**']
jobs:
check:
runs-on: [self-hosted, hestia]
steps:
- name: checkout
run: |
set -euo pipefail
rm -rf src && mkdir src
git clone --branch "${GITHUB_REF_NAME}" --depth 1 \
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" src
- name: clippy
run: cd src && bash ci/build.sh cargo clippy --all-targets --locked -- -D warnings
- name: test
run: cd src && bash ci/build.sh cargo test --release --locked

View file

@ -1,77 +0,0 @@
name: dev release
# Publishes a dev-track build on every push to `main` (the trunk
# branch — there is no separate `dev` branch). See bread-ecosystem's
# docs/release-channels.md for the release-track policy this is part of.
on:
push:
branches: ['main']
jobs:
build:
runs-on: [self-hosted, hestia]
steps:
- name: checkout
run: |
set -euo pipefail
rm -rf src && mkdir src
git clone --branch main --depth 1 \
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" src
- name: build
run: cd src && bash ci/build.sh cargo build --release --locked
- name: compute dev version
run: |
set -euo pipefail
cd src
# Base the dev version off the latest published stable tag,
# not Cargo.toml — Cargo.toml can go stale relative to the last
# real release (seen in practice: breadbox/breadpad/breadcrumbs/
# breadpaper), which would make a dev build sort as OLDER than
# what's already installed and bakery would correctly refuse it.
LATEST_TAG="$(git ls-remote --tags --refs \
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" 'v*' \
| awk -F/ '{print $NF}' | sed 's/^v//' | (grep -v -- '-' || true) | sort -V | tail -1)"
if [ -n "${LATEST_TAG}" ]; then
CUR="${LATEST_TAG}"
else
CUR="$(grep -m1 '^version' Cargo.toml | sed -E 's/.*"(.*)".*/\1/')"
fi
IFS='.' read -r MA MI PA <<< "${CUR}"
SHA="$(git rev-parse --short HEAD)"
TS="$(date -u +%Y%m%d%H%M%S)"
echo "VERSION=${MA}.${MI}.$((PA + 1))-dev.${TS}+${SHA}" >> "$GITHUB_ENV"
- name: prepare artifacts
run: |
set -euo pipefail
PKG_DIR="/srv/breadway-dl/dev/breadcrumbs/${VERSION}"
mkdir -p "${PKG_DIR}"
cp "src/target/release/breadcrumbs" "${PKG_DIR}/breadcrumbs-x86_64"
strip "${PKG_DIR}/breadcrumbs-x86_64"
sha256sum "${PKG_DIR}/breadcrumbs-x86_64" | awk '{print $1}' \
> "${PKG_DIR}/breadcrumbs-x86_64.sha256"
cp src/breadcrumbs.example.toml "${PKG_DIR}/"
cp src/LICENSE "${PKG_DIR}/"
cp src/bakery.toml "${PKG_DIR}/bakery.toml"
ln -sfn "${VERSION}" "/srv/breadway-dl/dev/breadcrumbs/latest"
# No GitHub Release upload — dev, like the other non-stable track,
# is only distributed via dl.breadway.dev/dev/.
- name: regenerate dev index.json
env:
MINISIGN_SEC_KEY: ${{ secrets.BAKERY_MINISIGN_SEC_KEY_PATH }}
run: |
set -euo pipefail
if [ -z "${MINISIGN_SEC_KEY:-}" ]; then
echo "::error::BAKERY_MINISIGN_SEC_KEY_PATH secret not set — refusing to regenerate dev index.json unsigned (would leave a stale signature mismatched against fresh content and break bakery for everyone on the dev track)"
exit 1
fi
rm -rf /tmp/bread-ecosystem-ci-* 2>/dev/null || true
# mktemp: a fixed clone path races when multiple repos' dev/beta
# workflows run close together on the same self-hosted runner.
ECOSYSTEM_CI_DIR="$(mktemp -d /tmp/bread-ecosystem-ci-XXXXXX)"
git clone --branch main https://git.breadway.dev/Breadway/bread-ecosystem.git "${ECOSYSTEM_CI_DIR}"
TRACK=dev bash "${ECOSYSTEM_CI_DIR}/scripts/gen-index.sh"
rm -rf "${ECOSYSTEM_CI_DIR}"

View file

@ -0,0 +1,19 @@
name: Mirror to GitHub
on:
push:
branches: ['**']
tags: ['**']
jobs:
mirror:
runs-on: [self-hosted, hestia]
steps:
- name: Mirror to GitHub
run: |
set -euo pipefail
git clone --mirror "https://git.breadway.dev/${GITHUB_REPOSITORY}.git" repo.git
cd repo.git
git push --prune \
"https://x-access-token:${{ secrets.MIRROR_TOKEN }}@github.com/Breadway/breadcrumbs.git" \
'+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'

View file

@ -0,0 +1,40 @@
name: Build and publish package
on:
push:
tags: ['v*']
jobs:
package:
runs-on: [self-hosted, hestia]
container:
image: archlinux:latest
steps:
# Note: no actions/checkout — the archlinux image has no Node, which JS
# actions require. Everything runs as shell steps and clones manually.
- name: Build and publish
env:
PUBLISH_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
pacman -Syu --noconfirm base-devel git rust cargo networkmanager
useradd -m builder
git config --global --add safe.directory '*'
git clone --branch "${GITHUB_REF_NAME}" --depth 1 \
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" /home/builder/src
cd /home/builder/src
git archive --format=tar.gz --prefix="breadcrumbs-${VERSION}/" HEAD \
> packaging/arch/breadcrumbs-${VERSION}.tar.gz
SHA=$(sha256sum packaging/arch/breadcrumbs-${VERSION}.tar.gz | awk '{print $1}')
sed -i "s/^pkgver=.*/pkgver=${VERSION}/" packaging/arch/PKGBUILD
sed -i "s/^sha256sums=.*/sha256sums=('${SHA}')/" packaging/arch/PKGBUILD
chown -R builder:builder /home/builder/src
# --nocheck: packaging builds the artifact; tests belong in a CI job.
su builder -c "cd /home/builder/src/packaging/arch && makepkg -f --noconfirm --nocheck"
PKG=$(find /home/builder/src/packaging/arch -name '*.pkg.tar.zst' | head -1)
curl -fsS -X PUT \
-H "Authorization: token ${PUBLISH_TOKEN}" \
-H "Content-Type: application/octet-stream" \
--data-binary "@${PKG}" \
"https://git.breadway.dev/api/packages/Breadway/arch/os"

View file

@ -1,58 +0,0 @@
name: beta (rc) release
# Publishes a beta-track build for any `vX.Y.Z-rc.N` prerelease tag
# pushed to `main` — there is no separate `beta` branch; "freezing" is
# just pausing pushes to main while an RC gets tested. See
# bread-ecosystem's docs/release-channels.md for the release-track policy.
on:
push:
tags: ['v*']
jobs:
build:
if: ${{ contains(github.ref_name, '-rc.') }}
runs-on: [self-hosted, hestia]
steps:
- name: checkout
run: |
set -euo pipefail
rm -rf src && mkdir src
git clone --branch "${GITHUB_REF_NAME}" --depth 1 \
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" src
- name: build
run: cd src && bash ci/build.sh cargo build --release --locked
- name: prepare artifacts
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
PKG_DIR="/srv/breadway-dl/beta/breadcrumbs/${VERSION}"
mkdir -p "${PKG_DIR}"
cp "src/target/release/breadcrumbs" "${PKG_DIR}/breadcrumbs-x86_64"
strip "${PKG_DIR}/breadcrumbs-x86_64"
sha256sum "${PKG_DIR}/breadcrumbs-x86_64" | awk '{print $1}' \
> "${PKG_DIR}/breadcrumbs-x86_64.sha256"
cp src/breadcrumbs.example.toml "${PKG_DIR}/"
cp src/LICENSE "${PKG_DIR}/"
cp src/bakery.toml "${PKG_DIR}/bakery.toml"
ln -sfn "${VERSION}" "/srv/breadway-dl/beta/breadcrumbs/latest"
# No GitHub Release upload — beta, like dev, is only distributed via
# dl.breadway.dev/beta/.
- name: regenerate beta index.json
env:
MINISIGN_SEC_KEY: ${{ secrets.BAKERY_MINISIGN_SEC_KEY_PATH }}
run: |
set -euo pipefail
if [ -z "${MINISIGN_SEC_KEY:-}" ]; then
echo "::error::BAKERY_MINISIGN_SEC_KEY_PATH secret not set — refusing to regenerate beta index.json unsigned (would leave a stale signature mismatched against fresh content and break bakery for everyone on the beta track)"
exit 1
fi
rm -rf /tmp/bread-ecosystem-ci-* 2>/dev/null || true
# mktemp: a fixed clone path races when multiple repos' dev/beta
# workflows run close together on the same self-hosted runner.
ECOSYSTEM_CI_DIR="$(mktemp -d /tmp/bread-ecosystem-ci-XXXXXX)"
git clone https://git.breadway.dev/Breadway/bread-ecosystem.git "${ECOSYSTEM_CI_DIR}"
TRACK=beta bash "${ECOSYSTEM_CI_DIR}/scripts/gen-index.sh"
rm -rf "${ECOSYSTEM_CI_DIR}"

View file

@ -6,7 +6,6 @@ on:
jobs:
build:
if: ${{ !contains(github.ref_name, '-rc.') }}
runs-on: [self-hosted, hestia]
steps:
- name: checkout
@ -17,19 +16,10 @@ jobs:
"https://git.breadway.dev/${GITHUB_REPOSITORY}.git" src
- name: build
run: |
set -euo pipefail
if [ ! -f src/ci/build.sh ]; then
echo "::error::ci/build.sh is missing — bakery release builds must go through the shared CI wrapper"
exit 1
fi
cd src && bash ci/build.sh cargo build --release --locked || {
echo "::error::cargo build --release --locked failed. If Cargo.lock drifted, update and commit it; do not drop --locked."
exit 1
}
run: cd src && cargo build --release --locked
- name: test
run: cd src && bash ci/build.sh cargo test --release --locked
run: cd src && cargo test --release --locked
- name: prepare artifacts
run: |
@ -42,19 +32,13 @@ jobs:
sha256sum "${PKG_DIR}/breadcrumbs-x86_64" | awk '{print $1}' \
> "${PKG_DIR}/breadcrumbs-x86_64.sha256"
cp src/breadcrumbs.example.toml "${PKG_DIR}/"
cp src/LICENSE "${PKG_DIR}/"
cp src/bakery.toml "${PKG_DIR}/bakery.toml"
cp src/contrib/breadcrumbs.service "${PKG_DIR}/"
ln -sfn "${VERSION}" "/srv/breadway-dl/breadcrumbs/latest"
- name: regenerate index.json
env:
MINISIGN_SEC_KEY: ${{ secrets.BAKERY_MINISIGN_SEC_KEY_PATH }}
run: |
set -euo pipefail
if [ -z "${MINISIGN_SEC_KEY:-}" ]; then
echo "::error::BAKERY_MINISIGN_SEC_KEY_PATH secret not set — refusing to regenerate index.json unsigned (would leave a stale signature mismatched against fresh content and break bakery for everyone)"
exit 1
fi
rm -rf /tmp/bread-ecosystem-ci
git clone https://git.breadway.dev/Breadway/bread-ecosystem.git /tmp/bread-ecosystem-ci
bash /tmp/bread-ecosystem-ci/scripts/gen-index.sh

View file

@ -1,38 +0,0 @@
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
RUSTFLAGS: "-D warnings"
jobs:
test:
name: fmt · clippy · test · build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Cache cargo
uses: Swatinem/rust-cache@v2
- name: Format check
run: cargo fmt --all -- --check
- name: Clippy
run: cargo clippy --all-targets -- -D warnings
- name: Test
run: cargo test --all --verbose
- name: Release build
run: cargo build --release --verbose

View file

@ -1,65 +0,0 @@
name: release
on:
push:
tags: ["v*"]
permissions:
contents: write
env:
DL_DIR: /srv/breadway-dl
ECOSYSTEM_DIR: /home/breadway/Projects/bread-ecosystem
jobs:
build:
runs-on: [self-hosted, hestia]
steps:
- uses: actions/checkout@v4
- name: install build deps
run: sudo apt-get install -y libnm-dev libdbus-1-dev pkg-config 2>/dev/null || true
- name: build
run: cargo build --release --locked
- name: test
run: cargo test --release --locked
- name: prepare artifacts
run: |
VERSION="${GITHUB_REF_NAME#v}"
PKG_DIR="${DL_DIR}/breadcrumbs/${VERSION}"
mkdir -p "${PKG_DIR}"
cp target/release/breadcrumbs "${PKG_DIR}/breadcrumbs-x86_64"
strip "${PKG_DIR}/breadcrumbs-x86_64"
sha256sum "${PKG_DIR}/breadcrumbs-x86_64" | awk '{print $1}' \
> "${PKG_DIR}/breadcrumbs-x86_64.sha256"
cp breadcrumbs.example.toml "${PKG_DIR}/"
cp bakery.toml "${PKG_DIR}/bakery.toml"
ln -sfn "${VERSION}" "${DL_DIR}/breadcrumbs/latest"
- name: ensure bread-ecosystem
run: |
if [[ -d "${ECOSYSTEM_DIR}/.git" ]]; then
git -C "${ECOSYSTEM_DIR}" pull --ff-only
else
mkdir -p "$(dirname "${ECOSYSTEM_DIR}")"
git clone https://github.com/Breadway/bread-ecosystem.git "${ECOSYSTEM_DIR}"
fi
- name: regenerate index.json
run: bash "${ECOSYSTEM_DIR}/scripts/gen-index.sh"
- name: upload to GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
VERSION="${GITHUB_REF_NAME#v}"
PKG_DIR="${DL_DIR}/breadcrumbs/${VERSION}"
gh release create "${GITHUB_REF_NAME}" \
--title "breadcrumbs v${VERSION}" --generate-notes 2>/dev/null || true
gh release upload "${GITHUB_REF_NAME}" \
"${PKG_DIR}/breadcrumbs-x86_64" \
"${PKG_DIR}/breadcrumbs-x86_64.sha256" \
--clobber

13
.gitignore vendored
View file

@ -1,12 +1,9 @@
# Build output
/target/
# Secrets: live config holds plaintext Wi-Fi passwords (until NetworkManager
# takes over each one on first connect — see README's "Credential handling").
# Keep local only; see breadcrumbs.example.toml / networks.example.toml for
# the schemas.
# Secrets: live config holds plaintext Wi-Fi passwords.
# Keep local only; see breadcrumbs.example.toml for the schema.
/breadcrumbs.toml
/networks.toml
# Legacy plaintext credential store (migrated into breadcrumbs.toml on first run)
/Networks/
@ -37,9 +34,3 @@ desktop.ini
# Claude Code local state
.claude/
# Local hygiene notes (not for commit)
CLAUDE.md
# graphify knowledge-graph output (local tool cache, not for commit)
graphify-out/

View file

@ -1,50 +0,0 @@
# AGENTS.md — Repo hygiene
Scope: this file covers *repo hygiene* — branching, remotes, CI, cleanup. It is not project documentation.
This repo follows the branch/release workflow documented in `CONTRIBUTING.md`
— read and follow it for any git, branch, or release work here (the
single-trunk model, `feature/x`/`fix/x` branch naming, how RC tags work,
etc). Don't improvise a different workflow. The short version: there is one
long-lived branch, `main` — no `dev` or `beta` branch exists. `main`
auto-publishes a dev-track build on every push. "Beta" and "stable" are both
just tags, not branches: push a `vX.Y.Z-rc.N` tag to publish a beta-track
build, push a plain `vX.Y.Z` tag to cut the signed stable release.
"Freezing" for stabilization means pausing pushes to `main`, not moving a
branch. This replaced an earlier three-branch (`dev`/`beta`/`main`) model
after `main` was found to have silently rotted out of sync with `dev`/`beta`
across most repos in this ecosystem — a manual "merge beta into main
monthly" step nobody reliably did across a dozen-plus repos. Collapsing to
one branch removes the class of bug; there's nothing left that can fall out
of sync.
## Remotes
- `origin` — Forgejo (`git.breadway.dev` via Hestia, SSH) — authoritative.
- `github` — GitHub mirror. Push both when publishing. Agents push `origin` only; the GitHub remote auto-mirrors.
## Distribution
- Bakery-only. `bakery.toml` is the product manifest; there is no
`packaging/arch/PKGBUILD` in this repo.
- Tracks: `bakery track set {dev,beta,stable}` then `bakery update breadcrumbs`
(or `bakery update --all`). See CONTRIBUTING.md and bread-ecosystem's
`docs/release-channels.md`.
## Events
- Bread bus contract: `EVENTS.md`. App id is `crumbs`.
- Fail-silent: breadcrumbs behaves the same whether `breadd` is running or
not. Commands (`bread.command.crumbs.*`) are only received while
`breadcrumbs watch` / the user systemd unit is up.
## CI
- `check.yml` — clippy + `cargo test --release` on `feature/**` and `fix/**`.
- `dev-release.yml` — triggered on push to `main` (dev-track bakery publish).
- `rc-release.yml` — triggered on any `vX.Y.Z-rc.N` tag push (beta track).
- `release.yml` — triggered on any other `v*` tag push (signed stable).
All CI runs on a self-hosted runner. No build/lint/test CI runs on ordinary
commits or PRs to `main` beyond the dev-track workflow above.
## Don't
- Don't embed credentials in remote URLs — SSH or a credential helper only.
- Don't invent bread command verbs that have no real breadcrumbs feature
behind them. See EVENTS.md.

View file

@ -1,84 +0,0 @@
# Contributing
`breadcrumbs` — Profile-aware Wi-Fi state machine with Tailscale integration.
Part of the bread ecosystem; this repo follows the same branch/release
workflow as every other ecosystem product.
## Branches
There is one long-lived branch: **`main`**. All day-to-day work lands here.
Every push to `main` automatically builds and publishes a **dev-track**
build (see Tracks below) — a real install you can test before cutting
anything more formal.
New work — features and bug fixes alike — goes on a short-lived branch:
```
feature/<short-name>
fix/<issue-number-or-short-name>
```
Branch off `main`, open a PR/push back into `main` when ready. Short-lived
branches get deleted on merge — they never accumulate the kind of drift a
second long-lived branch does.
## The release cycle
There's no separate `beta` or release branch — "stable" and "beta" are both
just **tags** on `main`, not branches that need to be kept in sync:
1. Work accumulates on `main` via `feature/x` / `fix/x` branches. Each push
auto-publishes a dev build — install it with `bakery track set dev` and
`bakery update --all`, then fix anything broken with another push.
2. When you want to stabilize before a real release, tag a release
candidate: `git tag vX.Y.Z-rc.1 && git push origin vX.Y.Z-rc.1` (push to
both remotes). That tag alone triggers a beta-track build —
"freezing" is just pausing pushes to `main` while you test it, not a
branch operation. Cut `-rc.2`, `-rc.3`, etc. for further fixes.
3. Once an RC has gone without issues, tag the real release:
`git tag vX.Y.Z && git push origin vX.Y.Z` — that's what triggers the
signed stable release build.
## Tracks, from a user's perspective
```
bakery track show # what you're currently on (defaults to stable)
bakery track set dev # or beta, or stable
bakery update --all # pull the latest build on your current track
```
| Track | What it is | Published from |
|--------|-----------|-----------------|
| `stable` | The last tagged release | a `vX.Y.Z` tag |
| `beta` | Latest release candidate | a `vX.Y.Z-rc.N` tag |
| `dev` | Bleeding edge | `main`, on every push |
Dev versions are auto-computed (`X.Y.Z-dev.<timestamp>+<sha>`) from the
latest published stable tag, so they always sort as newer than what you
have installed — no manual version bumping needed. Beta versions are just
the RC tag itself (already valid semver, already sorts below the real
release it's a candidate for).
## Local development
```sh
cargo build --release
cargo test --release
```
## CI
- `dev-release.yml` — triggered on push to `main`.
- `rc-release.yml` — triggered on any `vX.Y.Z-rc.N` tag push.
- `release.yml` — triggered on any other `v*` tag push, cuts the actual
stable release.
All CI runs on a self-hosted runner; nothing runs automatically on plain
commits or PRs beyond the track builds above. See
[bread-ecosystem's docs/release-channels.md](https://git.breadway.dev/Breadway/bread-ecosystem/src/branch/main/docs/release-channels.md)
for the full policy, including how a new product gets wired onto these tracks.
## Questions
Open an issue on this repo's Forgejo tracker.

987
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[package]
name = "breadcrumbs"
version = "2.1.7"
version = "2.1.6"
edition = "2021"
description = "Profile-aware Wi-Fi state machine with Tailscale handling and self-healing watch daemon"
license = "MIT"
@ -14,8 +14,8 @@ clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
toml = "0.8"
serde_json = "1"
zbus = "4"
bread-utils = { git = "https://git.breadway.dev/Breadway/bread-ecosystem", tag = "v0.7.2", features = ["bread-client"] }
# TODO(owner): switch to tag-pinned git dependency once bread-utils is merged and tagged, matching the bread-theme pattern
bread-utils = { git = "https://git.breadway.dev/Breadway/bread-ecosystem", tag = "v0.3.0" }
[profile.release]
opt-level = "s"

View file

@ -1,81 +0,0 @@
# breadcrumbs — bread event integration
breadcrumbs is a standalone Wi-Fi state machine: it works exactly the same
with or without `breadd` running. When breadd *is* present **and** the
`breadcrumbs watch` daemon (or the systemd user service it installs) is up,
breadcrumbs publishes events into the shared bread automation fabric and
listens for a small set of commands. See the parent `bread` repo's
`Documentation.md` — specifically its "Namespaces" and "Integrating a
bread\* app" sections — for the general convention this follows.
App id: **`crumbs`**. Transport: `bread-utils`'s `bread_client` module
(feature `bread-client`) — the watch process links it directly, since it's
the long-running piece that both emits on real transitions and holds the
command subscription open.
One-shot CLI invocations (`breadcrumbs status`, `profile set`, `init`, …)
do **not** emit or subscribe on their own. A `breadcrumbs profile set home`
while the watcher is running is picked up on the watcher's next tick
(state is re-read every loop) and *then* published as
`bread.crumbs.profile.changed`. If the watcher is not running, the CLI
still switches the profile on disk — there is just nobody listening for
`bread.command.crumbs.*`, and nobody emitting `bread.crumbs.*`.
## Events published (`bread.crumbs.*`)
| Event | Data | When |
|-------|------|------|
| `bread.crumbs.profile.changed` | `{ "from": "<name>", "to": "<name>" }` | The watch loop observes that the persisted active profile is no longer the one it last acted on (CLI `profile set`, `detect --apply`, `bread.command.crumbs.set_profile`, or a time-of-day schedule switch). Not emitted on watcher start just because a profile is already selected. |
| `bread.crumbs.health.changed` | `{ "profile": "<name>", "health": "<variant>", "ssid": <string or null>, "iface": <string or null>, "ip": <string or null>, "exit_node": "<string>", "tailscale": <variant or null> }` | The watch loop's health classification changes — including the first observation after start, and the forced re-evaluation after a profile change. **Not** emitted on every poll tick while the classification stays the same. |
| `bread.crumbs.network.changed` | `{ "from": <ssid or null>, "to": <ssid or null>, "profile": "<name>" }` | The active SSID changed between watch-loop ticks. `from` is `null` on the first association observed after start (or after a profile switch). |
| `bread.crumbs.tailscale.changed` | `{ "profile": "<name>", "state": <variant or null>, "exit_node": "<string>" }` | The Tailscale health state (or its mere presence) changed between ticks. `state` is the `TsHealth` variant name or `null` when Tailscale isn't installed. |
| `bread.crumbs.set_profile.done` | `{ "profile": "<name>" }` | `bread.command.crumbs.set_profile` persisted the new profile. |
| `bread.crumbs.set_profile.failed` | `{ "error": "<message>" }` | `bread.command.crumbs.set_profile` was received but rejected (unknown profile, missing `profile` field, config unreadable). |
`health` is the Rust enum variant name, not a prettier label:
| Variant | Meaning |
|---------|---------|
| `Up` | Adapter present, internet reachable, Tailscale healthy if the profile requires it. |
| `DownNoNet` | No internet. |
| `CaptivePortal` | No internet and an HTTP response arrived that wasn't the 204 generate_204 returns — traffic is being intercepted (captive/guest portal). Needs a browser sign-in, not a reconnect. |
| `DownTailscaleManual` | Tailscale required but needs login / isn't installed — cannot auto-fix. |
| `DownTailscaleOther` | Tailscale required and unhealthy for some other (usually auto-recoverable) reason. |
| `NoAdapter` | No Wi-Fi interface. |
| `UnknownProfile` | Persisted profile name is not in the config. |
`ssid` is the currently-associated SSID, or `null` when there isn't one
(no adapter, not associated, unknown profile).
## Commands honored (`bread.command.crumbs.*`)
These are only received while `breadcrumbs watch` / `breadcrumbs.service`
is running. Publishing a command with no subscriber is a silent no-op —
that is the documented bread convention, not a breadcrumbs bug.
| Verb | Data | Effect |
|------|------|--------|
| `set_profile` | `{ "profile": "<name>" }` | Persist `<name>` via the same `state::set_profile` path the CLI uses. Wakes the watch loop immediately so the new profile is classified (and recovered, if down) on the next tick rather than waiting out the current poll interval. Does **not** run `flow::run` on the command thread — that would race the watch loop. Emits `bread.crumbs.set_profile.done`/`.failed`. |
### Not implemented: extra verbs
There is no `pin`, `select`, `scan`, `init`, or other command verb. The
CLI already covers those as synchronous one-shots (`breadcrumbs init`,
`breadcrumbs scan`, …), and breadcrumbs has no "pinned network" concept
to hang a bus verb on. If/when that changes, the corresponding
`bread.command.crumbs.*` verb should be added at the same time, not
stubbed out ahead of it.
## Fail-safe behavior
- If breadd isn't installed or isn't running, `emit` is a silent no-op
(`BreadClient::emit` never blocks or errors the caller) and the
command subscription simply never receives anything — breadcrumbs'
actual Wi-Fi / Tailscale / watch functionality is entirely unaffected
either way.
- If breadd restarts, the command subscription reconnects automatically
(`BreadClient::subscribe`'s background thread has its own backoff loop);
no restart of the breadcrumbs watcher is needed.
- If the breadcrumbs watcher is not running, commands are a graceful
no-op at the bus (no subscriber) and no `bread.crumbs.*` events fire.
The CLI still works.

View file

@ -2,21 +2,23 @@
A profile-aware Wi-Fi state machine for Linux with Tailscale exit-node management and a self-healing watch daemon.
breadcrumbs sits on top of NetworkManager's **D-Bus API** (`org.freedesktop.NetworkManager` on the system bus — no `nmcli` subprocesses) and manages your Wi-Fi based on **location profiles**. Switch between home, work, school, or any other context with a single command — it handles scanning, connecting, DNS pinning, and Tailscale setup automatically.
breadcrumbs sits on top of NetworkManager (`nmcli`) and manages your Wi-Fi based on **location profiles**. Switch between home, work, school, or any other context with a single command — it handles scanning, connecting, DNS pinning, and Tailscale setup automatically.
## Features
- **Profile-based connection management** — define ordered network priority lists per location
- **Bootstrap + Tailscale gating** — connect to an interim network first, bring up Tailscale, then move to the target network
- **Self-healing watch daemon** — monitors for drops, auto-recovers, reacts within seconds via NetworkManager D-Bus signals
- **Auto-detection** — scans visible SSIDs and guesses your location from config-defined markers
- **Credential handling** — a saved network's password is only needed the *first* time breadcrumbs connects to it. Once that connect succeeds, NetworkManager durably owns the credential (a new connection profile, or an updated PSK on an existing one), so breadcrumbs clears its own local copy and stops writing it to disk. Both config files are `0600` (owner-only); saved networks live in a separate `networks.toml` from settings/profiles (see [Configuration](#configuration)). Secrets are never exposed in a process command line: everything travels inside D-Bus `Update2`/`AddAndActivateConnection2` settings payloads, invisible to other local users via `/proc/<pid>/cmdline`.
- **Self-healing watch daemon** — monitors for drops, auto-recovers, reacts within seconds via `nmcli monitor`
- **Auto-detection** — scans visible SSIDs and guesses your location from config-defined markers (picks the profile with the most markers in range)
- **Captive-portal detection** — distinguishes a real connection from a sign-in page and surfaces the portal URL instead of falsely reporting "online"
- **Secure credential handling** — passwords fed to `nmcli` out-of-band (via stdin with `--ask`, or a 0600 `passwd-file`), never in argv/`ps`; config stored at 0600
- **Machine-readable status**`breadcrumbs status --json` for bars/scripts
- **Desktop notifications** via `notify-send` (optional)
- **systemd user service** generation via `breadcrumbs install-service`
## Requirements
- Linux with NetworkManager running on the D-Bus system bus
- Linux with NetworkManager (`nmcli` in `$PATH`)
- Rust toolchain (to build from source)
- `tailscale` (optional — only needed if any profile sets `tailscale = true`)
- `notify-send` (optional — for desktop notifications)
@ -25,7 +27,7 @@ breadcrumbs sits on top of NetworkManager's **D-Bus API** (`org.freedesktop.Netw
## Installation
```bash
git clone https://github.com/breadway/breadcrumbs
git clone https://git.breadway.dev/Breadway/breadcrumbs
cd breadcrumbs
cargo build --release
# Copy to somewhere on your PATH:
@ -34,38 +36,32 @@ cp target/release/breadcrumbs ~/.local/bin/
## Configuration
On first run, breadcrumbs creates `~/.config/breadcrumbs/breadcrumbs.toml` (settings + profiles) and `~/.config/breadcrumbs/networks.toml` (saved networks) with default profiles. Copy `breadcrumbs.example.toml` as a starting point for the former:
On first run, breadcrumbs creates `~/.config/breadcrumbs/breadcrumbs.toml` with default profiles. Copy `breadcrumbs.example.toml` as a starting point and fill in your real network credentials:
```bash
cp breadcrumbs.example.toml ~/.config/breadcrumbs/breadcrumbs.toml
breadcrumbs edit # opens breadcrumbs.toml in $EDITOR
breadcrumbs edit # opens in $EDITOR
```
...then add your real networks with `breadcrumbs add`/`scan` rather than hand-editing `networks.toml` (see `networks.example.toml` if you want to see its shape or write it by hand anyway).
Config paths respect `$XDG_CONFIG_HOME` and `$XDG_STATE_HOME`.
### Config structure
Settings and location profiles live in `breadcrumbs.toml` — the file people actually hand-edit or dotfile:
```toml
[settings]
dns = "1.1.1.1" # DNS server pinned on every connection
connect_wait = 8 # seconds to wait for the device to reach the activated state (legacy key: nmcli_wait)
nmcli_wait = 8 # seconds to wait for nmcli connect
exit_node = "myhostname" # default Tailscale exit node
exit_nodes = ["a", "b"] # optional priority list; tried in order (fallback nodes)
interface = "wlan0" # optional preferred Wi-Fi interface
schedule = [] # optional time-of-day profile switches, e.g.
# [[settings.schedule]]
# profile = "home"
# from = "18:00"
# to = "08:00" # from >= to = overnight window
default_profile = "away"
watch_interval = 12 # seconds between health checks (minimum 4)
connectivity_url = "http://connectivitycheck.gstatic.com/generate_204"
ping_host = "1.1.1.1"
[[networks]]
ssid = "MyHomeNetwork"
password = "hunter2"
hidden = false
[profiles.home]
networks = ["MyHomeNetwork"] # priority-ordered SSIDs
tailscale = false
@ -80,26 +76,6 @@ exit_node = "jump-host" # per-profile override
detect_ssids = ["CorpWifi", "Corp-5G"]
```
Saved networks (SSID + optional local password) live separately, in `networks.toml`, managed via `add`/`scan`/`forget`:
```toml
[[networks]]
ssid = "MyHomeNetwork"
password = "hunter2" # optional — see "Credential handling" below
hidden = false
dns = "1.1.1.1" # optional per-network DNS override; "" disables pinning
# WPA-Enterprise (802.1x) networks use these instead of a PSK:
# [[networks]]
# ssid = "CorpEAP"
# eap = "peap" # or "tls"
# identity = "user@corp"
# password = "..." # 802.1x password
# ca_cert = "/etc/ssl/certs/corp-ca.pem" # optional
```
`password` is only needed the first time breadcrumbs connects to a network. Once NetworkManager durably saves the credential, breadcrumbs clears its local copy and omits the key on the next save — an existing config with `password = "..."` still loads fine either way, no migration step needed. A config with `[[networks]]` still written inline in `breadcrumbs.toml` (from before this split) also still loads: it's read once, then migrated into `networks.toml` automatically on the next save.
### Profiles
Each profile defines:
@ -111,8 +87,7 @@ Each profile defines:
| `bootstrap` | SSID to connect to first (e.g. guest Wi-Fi that allows Tailscale traffic). |
| `exit_node` | Tailscale exit node for this profile (overrides `settings.exit_node`). |
| `include_all_known` | After the priority list, also try every other known network. |
| `detect_ssids` | Any visible SSID in this list marks this profile as a candidate for `breadcrumbs detect`. Profiles with more matching markers win. |
| `learn` | If `true`, SSIDs this profile successfully connects to are appended to `detect_ssids` (bounded), so `detect` improves without hand-editing. Off by default. |
| `detect_ssids` | Any visible SSID in this list marks this profile as a candidate for `breadcrumbs detect`. |
## Usage
@ -122,17 +97,21 @@ breadcrumbs [--profile <name>] <command>
| Command | Description |
|---------|-------------|
| `status [--json]` | Show current Wi-Fi / Tailscale health (default) |
| `init [--wait <s>]` | Run the full connect sequence; `--wait` retries until connected or the timeout elapses |
| `status [--json]` | Show current Wi-Fi / Tailscale health (default); `--json` for scripts |
| `init` | Run the full connect sequence for the active profile |
| `watch [--no-initial]` | Self-healing daemon: monitors and auto-recovers drops |
| `profile get` | Print the active profile |
| `profile set <name>` | Switch profile (and apply it, unless `--no-apply`) |
| `profile list` | List all profiles |
| `detect [--apply] [--json]` | Guess profile from visible networks; optionally apply it |
| `add <ssid> [password]` | Add or update a saved network (`--dns`, `--eap`, `--identity`, `--ca-cert`, `--hidden`, `--to`, `--at`) |
| `profile add <name> [--detect <ssid>]…` | Create a new (empty) profile, optionally with detection markers |
| `profile remove <name>` | Delete a profile (core `home`/`work`/`away` are protected) |
| `detect [--apply]` | Guess profile from visible networks; optionally apply it |
| `add <ssid> [password]` | Add or update a saved network |
| `forget <ssid>` | Remove a network from config and NetworkManager |
| `prune [--dry-run]` | Remove NetworkManager wireless profiles whose SSID is no longer in the config |
| `join <ssid>` | Connect to a specific saved network by SSID, bypassing profile routing |
| `networks [--json]` | List saved network SSIDs |
| `scan [--to <profile>]` | Interactive scan, pick, connect and save |
| `scan-list [--json]` | Scan for visible networks and list them with signal strength |
| `list [--show-passwords]` | Show config: settings, networks, profiles |
| `edit` | Open config in `$EDITOR`, validate on exit |
| `doctor [--full]` | Quick connectivity and Tailscale diagnostics |
@ -169,20 +148,9 @@ breadcrumbs install-service
`breadcrumbs watch` is the recommended way to run breadcrumbs for daily use. It:
1. Polls health every `watch_interval` seconds (adaptive backoff on repeated failures)
2. Reacts immediately to link-state changes via NetworkManager D-Bus signals (`Device.StateChanged`, `Connectivity` property changes, hotplug events)
2. Reacts immediately to link-state changes via `nmcli monitor`
3. Runs `flow::run` (the connect state machine) on any detected drop
4. Handles profile changes live — re-reads config and state on every tick
5. Distinguishes captive portals from plain no-internet (a 200/301/302 instead
of the 204 generate_204 returns) and tells you to sign in instead of
pointlessly reconnecting
6. Applies a `[settings.schedule]` time-of-day profile switch, respecting a
30-minute grace window after a manual `profile set`
7. Detects suspend/resume (a large gap between ticks) and forces an immediate
recovery check instead of waiting out the poll interval
When a Tailscale profile is connected through a bootstrap network and the
connectivity check is intercepted, the watcher stays put and notifies once —
it does not churn reconnects against a portal.
Install as a systemd user service:

View file

@ -4,11 +4,16 @@ binaries = ["breadcrumbs"]
system_deps = ["networkmanager"]
optional_system_deps = ["tailscale", "sudo", "xdg-utils"]
bread_deps = []
license_file = "LICENSE"
[config]
dir = "~/.config/breadcrumbs"
example = "breadcrumbs.example.toml"
[[service]]
unit = "breadcrumbs.service"
enable = true
[install]
post_install = []
post_install = [
"systemctl --user is-active --quiet breadcrumbs || systemctl --user start breadcrumbs",
]

View file

@ -4,22 +4,33 @@
# just run breadcrumbs once (it generates a skeleton) and then use
# `breadcrumbs add` / `breadcrumbs edit` to fill in your networks.
# The real breadcrumbs.toml is gitignored and never committed.
#
# Saved networks (SSID + optional local password) live in a separate file,
# networks.toml, in the same directory — not here. See
# networks.example.toml for its format; in practice you never hand-edit it,
# `breadcrumbs add` / `scan` / `forget` manage it for you. This file is just
# settings + the location profiles built from those saved networks.
[settings]
dns = "1.1.1.1"
connect_wait = 8
nmcli_wait = 8
exit_node = "my-exit-node" # Tailscale hostname of your preferred exit node
default_profile = "away"
watch_interval = 12
# Must be a "generate_204"-style endpoint: only an empty HTTP 204 counts as
# online, so a captive portal (200 login page / 30x redirect) is detected.
connectivity_url = "http://connectivitycheck.gstatic.com/generate_204"
ping_host = "1.1.1.1"
[[networks]]
ssid = "HomeWifi"
password = "REPLACE_ME"
hidden = false
[[networks]]
ssid = "WorkGuest"
password = "REPLACE_ME"
hidden = false
[[networks]]
ssid = "CorpWifi"
password = "REPLACE_ME"
hidden = false
# Location state machine. Switch with: breadcrumbs profile set <name>
#
# detect_ssids: list any SSIDs that reliably indicate you are at this location.

View file

@ -1 +0,0 @@
147cfbbf96ae4b171027defa1130d2caddb934b1

View file

@ -1,21 +0,0 @@
#!/usr/bin/env bash
# Delegates to bread-ecosystem's shared CI build image/script, pinned to
# the commit in ci/bread-ecosystem.rev — not `main`. bread-ecosystem's CI
# files now affect every product's release pipeline, so bumping the pin
# is a deliberate act instead of silent drift (see the bread-theme test
# that broke here for exactly that reason, before it was pinned by rev).
#
# Usage: ci/build.sh cargo build --release --locked
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REV="$(cat "${ROOT}/ci/bread-ecosystem.rev")"
CACHE_DIR="/tmp/bread-ecosystem-ci-${REV}"
if [ ! -d "$CACHE_DIR" ]; then
rm -rf /tmp/bread-ecosystem-ci-*
git clone https://git.breadway.dev/Breadway/bread-ecosystem.git "$CACHE_DIR"
git -C "$CACHE_DIR" checkout --quiet "$REV"
fi
bash "${CACHE_DIR}/ci/build.sh" breadcrumbs "$ROOT" "$@"

View file

@ -0,0 +1,30 @@
[Unit]
Description=breadcrumbs Wi-Fi state machine watcher
Documentation=https://git.breadway.dev/Breadway/breadcrumbs
After=network.target NetworkManager.service
Wants=network.target
[Service]
Type=simple
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# ExecStart is rewritten at install time by bakery to point at the real
# bin_dir (patch_exec_start in bakery's install.rs) — this path is only a
# placeholder for local testing.
ExecStart=%h/.local/bin/breadcrumbs watch
Restart=always
RestartSec=5
Nice=5
# Forward stdout/stderr to the journal so `journalctl --user -u breadcrumbs` works
StandardOutput=journal
StandardError=journal
[Install]
# default.target, not graphical-session.target: breadcrumbs is a headless
# network daemon with no Wayland/GUI dependency, and graphical-session.target
# ships with RefuseManualStart=yes (only a session manager like uwsm can
# activate it — BOS doesn't use one, which is why breadclipd needs a manual
# `systemctl --user start` in hyprland.lua's exec-once instead of relying on
# WantedBy). default.target activates normally with the user session, no
# workaround needed.
WantedBy=default.target

View file

@ -1,29 +0,0 @@
# breadcrumbs saved-networks file.
#
# Lives alongside breadcrumbs.toml at ~/.config/breadcrumbs/networks.toml,
# 0600 permissions. Shown here purely for reference — you normally never
# hand-edit this file; use `breadcrumbs add` / `scan` / `forget` instead.
#
# `password` is optional and only needed the first time breadcrumbs connects
# to a network. Once NetworkManager has durably saved the credential (either
# a brand-new connection profile, or an updated PSK on an existing one),
# breadcrumbs clears its own local copy and omits the `password` key
# entirely on the next save — both the plaintext-on-disk copy and the
# argv exposure on every subsequent connect go away for that network from
# then on. Omit `password` altogether for a genuinely open (no-security)
# network, or for one NetworkManager already knows about.
[[networks]]
ssid = "HomeWifi"
password = "REPLACE_ME"
hidden = false
[[networks]]
ssid = "WorkGuest"
password = "REPLACE_ME"
hidden = false
[[networks]]
ssid = "CorpWifi"
password = "REPLACE_ME"
hidden = false

36
packaging/arch/PKGBUILD Normal file
View file

@ -0,0 +1,36 @@
# Maintainer: Breadway <plasticbread849@gmail.com>
pkgname=breadcrumbs
pkgver=2.1.0
pkgrel=1
pkgdesc="Profile-aware Wi-Fi state machine with Tailscale integration"
arch=('x86_64')
url="https://git.breadway.dev/Breadway/breadcrumbs"
license=('MIT')
# Some Rust deps (ring/mlua) build vendored C/asm into static archives; makepkg's
# default -flto=auto emits GCC LTO bitcode the Rust (lld) link cannot read,
# causing undefined-symbol errors. Disable LTO.
options=(!lto !debug)
depends=('networkmanager')
optdepends=(
'tailscale: Tailscale VPN profile integration'
)
makedepends=('rust' 'cargo')
source=("${pkgname}-${pkgver}.tar.gz")
sha256sums=('SKIP')
build() {
cd "${srcdir}/${pkgname}-${pkgver}"
cargo build --release --locked
}
check() {
cd "${srcdir}/${pkgname}-${pkgver}"
cargo test --release --locked
}
package() {
cd "${srcdir}/${pkgname}-${pkgver}"
install -Dm755 target/release/breadcrumbs "${pkgdir}/usr/bin/breadcrumbs"
install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
}

View file

@ -1,980 +0,0 @@
//! CLI argument parsing and command handlers. This is the only module
//! `src/main.rs` calls into; everything else (the actual state machine,
//! nmcli/tailscale wrappers, config, …) is exercised directly by library
//! consumers (including the integration tests under `tests/`).
use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;
use clap::{Parser, Subcommand};
use crate::config::{Config, NetworkDef};
use crate::state::{self, State};
use crate::util::{self, command_exists, home_dir};
use crate::{config, flow, nm, watch};
const C_RESET: &str = "\x1b[0m";
const C_BOLD: &str = "\x1b[1m";
const C_GREEN: &str = "\x1b[32m";
const C_RED: &str = "\x1b[31m";
const C_YELLOW: &str = "\x1b[33m";
const C_DIM: &str = "\x1b[2m";
#[derive(Parser)]
#[command(
name = "breadcrumbs",
version,
about = "Profile-aware Wi-Fi state machine with Tailscale handling",
disable_help_subcommand = true
)]
struct Cli {
/// Override the active profile for this run only (does not persist)
#[arg(long, short, global = true)]
profile: Option<String>,
#[command(subcommand)]
cmd: Option<Cmd>,
}
/// Optional flags for `add`. Flattened into the `Add` subcommand so the
/// CLI surface is unchanged while keeping `cmd_add`'s signature small.
#[derive(clap::Args)]
struct AddOpts {
/// Password (prompted if omitted)
password: Option<String>,
/// Network is hidden (does not broadcast its SSID).
/// `--hidden` sets it; `--hidden=false` clears it on an existing
/// entry; omitted leaves an existing entry's flag untouched.
#[arg(long, num_args = 0..=1, default_missing_value = "true")]
hidden: Option<bool>,
/// Per-network DNS override (empty string disables DNS pinning
/// for this network)
#[arg(long)]
dns: Option<String>,
/// 802.1x EAP method for enterprise networks (e.g. "peap", "tls")
#[arg(long)]
eap: Option<String>,
/// 802.1x identity for enterprise networks
#[arg(long)]
identity: Option<String>,
/// Path to a CA certificate for 802.1x
#[arg(long)]
ca_cert: Option<String>,
/// Attach this SSID to a profile's priority list
#[arg(long)]
to: Option<String>,
/// Position in the profile list (0 = highest priority)
#[arg(long)]
at: Option<usize>,
}
#[derive(Subcommand)]
enum Cmd {
/// Show current Wi-Fi / profile / Tailscale status (default)
Status {
/// Emit machine-readable JSON
#[arg(long)]
json: bool,
},
/// Run the full connect sequence for the active profile
#[command(visible_aliases = ["up", "connect", "i"])]
Init {
/// Retry until connected or this many seconds have elapsed
/// (0 = single attempt)
#[arg(long, default_value_t = 0)]
wait: u64,
},
/// Run as a daemon: watch for drops and auto-recover
Watch {
/// Skip the connect attempt on startup
#[arg(long)]
no_initial: bool,
},
/// Get / set / list location profiles (the state machine)
Profile {
#[command(subcommand)]
action: Option<ProfileCmd>,
},
/// Guess the profile from visible networks
Detect {
/// Set + apply the detected profile
#[arg(long)]
apply: bool,
/// Emit machine-readable JSON
#[arg(long)]
json: bool,
},
/// Add or update a saved network
Add {
ssid: String,
#[command(flatten)]
opts: AddOpts,
},
/// Remove a saved network (config + NetworkManager)
Forget { ssid: String },
/// Remove NetworkManager wireless profiles whose SSID is no longer in
/// the breadcrumbs config
Prune {
/// Only list what would be removed
#[arg(long)]
dry_run: bool,
},
/// Scan, pick, connect and save a network interactively
Scan {
/// Attach the saved network to this profile
#[arg(long)]
to: Option<String>,
},
/// List configured networks and profiles
List {
#[arg(long)]
show_passwords: bool,
},
/// Open the config file in $EDITOR
Edit,
/// Quick connectivity / Tailscale diagnostics
Doctor {
/// Run the full diag.sh report from the config directory
#[arg(long)]
full: bool,
},
/// Print the breadcrumbs config directory
Cd {
#[arg(long)]
shell: bool,
},
/// Install + enable the systemd user watcher service
InstallService {
/// Install the unit but do not enable/start it
#[arg(long)]
no_enable: bool,
},
}
#[derive(Subcommand)]
enum ProfileCmd {
/// Print the active profile
Get,
/// Set the active profile (and apply it unless --no-apply)
Set {
name: String,
#[arg(long)]
no_apply: bool,
},
/// List available profiles
List,
}
/// Parse `argv` and run the requested command. Returns the process exit code.
pub fn run() -> i32 {
let cli = Cli::parse();
match real_main(cli) {
Ok(c) => c,
Err(e) => {
eprintln!("{C_RED}error:{C_RESET} {e}");
1
}
}
}
fn active_profile(cfg: &Config, override_p: &Option<String>) -> String {
if let Some(p) = override_p {
return p.clone();
}
State::load(&cfg.settings.default_profile).profile
}
fn real_main(cli: Cli) -> Result<i32, String> {
let cmd = cli.cmd.unwrap_or(Cmd::Status { json: false });
// `cd` and `install-service` don't need a parsed config first.
if let Cmd::Cd { shell } = &cmd {
return cmd_cd(*shell);
}
let mut cfg = Config::load()?;
match cmd {
Cmd::Status { json } => cmd_status(&cfg, &cli.profile, json),
Cmd::Init { wait } => cmd_init(&mut cfg, &cli.profile, wait),
Cmd::Watch { no_initial } => Ok(watch::run(cfg, !no_initial)),
Cmd::Profile { action } => cmd_profile(&mut cfg, action),
Cmd::Detect { apply, json } => cmd_detect(&mut cfg, apply, json),
Cmd::Add { ssid, opts } => cmd_add(&mut cfg, ssid, opts),
Cmd::Forget { ssid } => cmd_forget(&mut cfg, &ssid),
Cmd::Prune { dry_run } => cmd_prune(&cfg, dry_run),
Cmd::Scan { to } => cmd_scan(&mut cfg, to),
Cmd::List { show_passwords } => cmd_list(&cfg, show_passwords),
Cmd::Edit => cmd_edit(),
Cmd::Doctor { full } => cmd_doctor(&cfg, &cli.profile, full),
Cmd::InstallService { no_enable } => cmd_install_service(!no_enable),
Cmd::Cd { .. } => unreachable!(),
}
}
fn cmd_init(cfg: &mut Config, override_p: &Option<String>, wait: u64) -> Result<i32, String> {
let p = active_profile(cfg, override_p);
let deadline = std::time::Instant::now() + Duration::from_secs(wait);
let mut attempt = 0;
loop {
// First attempt notifies normally (user-initiated); retries are
// quiet so a long --wait run doesn't spam notifications.
let outcome = if attempt == 0 {
flow::run(cfg, &p)
} else {
flow::run_quiet(cfg, &p)
};
if outcome.ok() {
print_outcome(&p, &outcome);
return Ok(0);
}
if wait == 0 || std::time::Instant::now() >= deadline {
print_outcome(&p, &outcome);
return Ok(1);
}
attempt += 1;
println!("{C_DIM}not connected yet — retrying in 3s…{C_RESET}");
std::thread::sleep(Duration::from_secs(3));
}
}
fn print_outcome(profile: &str, o: &flow::Outcome) {
match o {
flow::Outcome::Connected { ssid, note } => {
print!("{C_GREEN}connected{C_RESET} {C_BOLD}{ssid}{C_RESET} ({profile})");
match note {
Some(n) => println!(" {C_YELLOW}{n}{C_RESET}"),
None => println!(),
}
}
flow::Outcome::TailscaleError { ssid, health } => {
println!(
"{C_RED}tailscale error{C_RESET}: {} {C_DIM}(on {}){C_RESET}",
health.describe(),
ssid.clone().unwrap_or_else(|| "".into())
);
}
flow::Outcome::NoInterface => {
println!("{C_RED}no Wi-Fi adapter{C_RESET} — hardware issue")
}
flow::Outcome::NoNetworks => {
println!("{C_RED}no known networks in range{C_RESET} (profile {profile})")
}
flow::Outcome::UnknownProfile(p) => {
println!("{C_RED}unknown profile{C_RESET}: {p}")
}
}
}
fn cmd_status(cfg: &Config, override_p: &Option<String>, json: bool) -> Result<i32, String> {
let p = active_profile(cfg, override_p);
let s = crate::status::gather(cfg, &p);
let healthy = s.internet
&& s.iface.is_some()
&& (!s.tailscale_required || s.tailscale.as_ref().map(|h| h.is_ok()).unwrap_or(false));
if json {
let tailscale = s.tailscale.as_ref().map(|h| h.state_str());
println!(
"{}",
serde_json::json!({
"profile": p,
"iface": s.iface,
"ssid": s.ssid,
"ip": s.ip,
"internet": s.internet,
"portal": s.portal,
"tailscale_required": s.tailscale_required,
"tailscale": tailscale,
"exit_node": s.exit_node,
"healthy": healthy,
})
);
return Ok(if healthy { 0 } else { 1 });
}
let dot = |ok: bool| {
if ok {
format!("{C_GREEN}{C_RESET}")
} else {
format!("{C_RED}{C_RESET}")
}
};
println!("{C_BOLD}breadcrumbs{C_RESET}");
println!(" profile {C_BOLD}{p}{C_RESET}");
println!(
" adapter {}",
s.iface
.clone()
.unwrap_or_else(|| format!("{C_RED}none{C_RESET}"))
);
println!(
" ssid {}",
s.ssid
.clone()
.unwrap_or_else(|| format!("{C_DIM}{C_RESET}"))
);
println!(
" ip {}",
s.ip.clone().unwrap_or_else(|| format!("{C_DIM}{C_RESET}"))
);
println!(
" internet {} {}",
dot(s.internet),
if s.internet { "ok" } else { "down" }
);
match (&s.tailscale, s.tailscale_required) {
(Some(h), req) => {
let ok = h.is_ok();
println!(
" tailscale {} {} {C_DIM}(exit: {}{}){C_RESET}",
dot(ok || !req),
h.describe(),
s.exit_node,
if req { "" } else { ", optional" }
);
}
(None, _) => println!(" tailscale {C_DIM}not installed{C_RESET}"),
}
println!(
" state {}",
if healthy {
format!("{C_GREEN}healthy{C_RESET}")
} else {
format!("{C_YELLOW}needs attention{C_RESET} — run `breadcrumbs init`")
}
);
Ok(if healthy { 0 } else { 1 })
}
fn cmd_profile(cfg: &mut Config, action: Option<ProfileCmd>) -> Result<i32, String> {
match action.unwrap_or(ProfileCmd::Get) {
ProfileCmd::Get => {
println!("{}", State::load(&cfg.settings.default_profile).profile);
Ok(0)
}
ProfileCmd::List => {
let cur = State::load(&cfg.settings.default_profile).profile;
for name in cfg.profiles.keys() {
let mark = if *name == cur { "*" } else { " " };
println!("{mark} {name}");
}
Ok(0)
}
ProfileCmd::Set { name, no_apply } => {
state::set_profile(cfg, &name)?;
println!("profile = {C_BOLD}{name}{C_RESET}");
if no_apply {
return Ok(0);
}
let outcome = flow::run(cfg, &name);
print_outcome(&name, &outcome);
Ok(if outcome.ok() { 0 } else { 1 })
}
}
}
fn detect_profile(cfg: &Config) -> Option<String> {
let iface = nm::wifi_interface_preferred(cfg.settings.interface.as_deref())?;
nm::radio_on();
nm::rescan(&iface, &[]);
let visible = nm::visible_signals(&iface);
// Scored detection: the profile with the most matching markers wins, so
// a 2-marker match beats a 1-marker one. Profiles are stored in a
// BTreeMap, so ties resolve deterministically (alphabetically first).
let mut best: Option<(String, usize)> = None;
for (name, profile) in &cfg.profiles {
if profile.detect_ssids.is_empty() {
continue;
}
let count = profile
.detect_ssids
.iter()
.filter(|s| visible.contains_key(s.as_str()))
.count();
if count > 0 {
let better = match &best {
None => true,
Some((_, c)) => count > *c,
};
if better {
best = Some((name.clone(), count));
}
}
}
best.map(|(p, _)| p).or_else(|| {
// Fall back to the default profile if no markers matched — but only
// if it actually exists: a stale `default_profile` name is a config
// error, not a detection result, and persisting it would wedge the
// watcher in UnknownProfile forever.
if cfg.profiles.contains_key(&cfg.settings.default_profile) {
Some(cfg.settings.default_profile.clone())
} else {
None
}
})
}
fn cmd_detect(cfg: &mut Config, apply: bool, json: bool) -> Result<i32, String> {
match detect_profile(cfg) {
Some(p) => {
if json && !apply {
println!("{}", serde_json::json!({ "profile": p }));
return Ok(0);
}
if apply {
if json {
println!("{}", serde_json::json!({ "profile": p }));
} else {
println!("{p}");
}
// Route through state::set_profile (like the CLI and the
// bread bus do) so an unknown fallback is rejected with a
// proper error instead of being persisted as active.
state::set_profile(cfg, &p)?;
let outcome = flow::run(cfg, &p);
print_outcome(&p, &outcome);
return Ok(if outcome.ok() { 0 } else { 1 });
}
println!("{p}");
Ok(0)
}
None => Err("could not detect a profile (no Wi-Fi adapter, or no \
profile matches and the default is misconfigured)"
.into()),
}
}
fn prompt_line(msg: &str) -> String {
print!("{msg}");
let _ = std::io::stdout().flush();
let mut s = String::new();
let _ = std::io::stdin().lock().read_line(&mut s);
s.trim_end_matches(['\n', '\r']).to_string()
}
/// An empty string entered for a password (CLI arg or a blank prompt
/// response) means "this network has no password" (open Wi-Fi) — normalize
/// it to `None` right at the point of entry so it flows the same way a
/// genuinely absent/cleared password does. Without this, `Some("")` would
/// make `nm::connect_verbose` send an empty PSK in the settings payload,
/// which NetworkManager treats as "secured with a blank password" rather
/// than "open", and the connect fails against a real open SSID.
fn non_empty(s: String) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s)
}
}
fn prompt_secret(msg: &str) -> String {
// `util::run` redirects child stdin to /dev/null, so plain `stty -echo`
// would target the wrong fd and silently leave echo ON (leaking the
// password to the screen). `-F /dev/tty` makes stty act on the controlling
// terminal directly. If there is no tty we fall back to visible input.
let had_tty = util::run("stty", &["-F", "/dev/tty", "-echo"], Duration::from_secs(2)).success;
let val = prompt_line(msg);
if had_tty {
let _ = util::run("stty", &["-F", "/dev/tty", "echo"], Duration::from_secs(2));
println!();
}
val
}
fn cmd_add(cfg: &mut Config, ssid: String, opts: AddOpts) -> Result<i32, String> {
let AddOpts {
password,
hidden,
dns,
eap,
identity,
ca_cert,
to,
at,
} = opts;
// `--dns ""` is the explicit "don't pin DNS" opt-out; normalize an
// absent flag to None (use the global setting).
let dns = match dns {
Some(s) if s.is_empty() => Some(String::new()),
Some(s) => Some(s),
None => None,
};
// For enterprise networks, the password is the 802.1x password.
let password = match password {
Some(p) => p,
None if eap.is_some() => prompt_secret(&format!("802.1x password for '{ssid}': ")),
None => prompt_secret(&format!("Password for '{ssid}': ")),
};
let password = non_empty(password);
match cfg.networks.iter_mut().find(|n| n.ssid == ssid) {
Some(n) => {
n.password = password;
// `--hidden` / `--hidden=false` set the flag explicitly; when
// the flag is omitted, leave an existing entry's hidden state
// alone (a password-only update must not un-hide a network).
if let Some(h) = hidden {
n.hidden = h;
}
if dns.is_some() {
n.dns = dns;
}
if eap.is_some() {
n.eap = eap;
}
if identity.is_some() {
n.identity = identity;
}
if ca_cert.is_some() {
n.ca_cert = ca_cert;
}
}
None => cfg.networks.push(NetworkDef {
ssid: ssid.clone(),
password,
dns,
eap,
identity,
ca_cert,
hidden: hidden.unwrap_or(false),
}),
}
if let Some(prof_name) = to {
let prof = cfg
.profiles
.get_mut(&prof_name)
.ok_or_else(|| format!("unknown profile '{prof_name}'"))?;
prof.networks.retain(|s| s != &ssid);
let idx = at.unwrap_or(prof.networks.len()).min(prof.networks.len());
prof.networks.insert(idx, ssid.clone());
}
cfg.save()?;
println!("{C_GREEN}saved{C_RESET} {ssid}");
Ok(0)
}
fn cmd_forget(cfg: &mut Config, ssid: &str) -> Result<i32, String> {
let before = cfg.networks.len();
cfg.networks.retain(|n| n.ssid != ssid);
for p in cfg.profiles.values_mut() {
p.networks.retain(|s| s != ssid);
if p.bootstrap.as_deref() == Some(ssid) {
p.bootstrap = None;
}
}
cfg.save()?;
let removed = nm::delete_connections_for_ssid(ssid);
println!(
"{C_GREEN}forgot{C_RESET} {ssid} (config: {}, NetworkManager: {})",
if cfg.networks.len() < before {
"removed"
} else {
"not present"
},
if removed { "removed" } else { "not present" }
);
Ok(0)
}
/// Remove NetworkManager wireless profiles whose SSID is no longer known to
/// breadcrumbs (config `networks`, or any profile's priority list or
/// bootstrap). `--dry-run` only lists. Returns the number removed.
fn cmd_prune(cfg: &Config, dry_run: bool) -> Result<i32, String> {
let known: Vec<&str> = cfg
.networks
.iter()
.map(|n| n.ssid.as_str())
.chain(
cfg.profiles
.values()
.flat_map(|p| p.networks.iter().map(|s| s.as_str()).chain(p.bootstrap.iter().map(|s| s.as_str()))),
)
.collect();
let stale: Vec<(String, String)> = nm::wireless_profiles()
.into_iter()
.filter(|(_name, ssid)| !known.contains(&ssid.as_str()))
.collect();
if stale.is_empty() {
println!("{C_GREEN}nothing to prune{C_RESET}");
return Ok(0);
}
for (name, ssid) in &stale {
if dry_run {
println!("{C_DIM}would remove{C_RESET} {name} ({ssid})");
} else {
println!("{C_GREEN}removed{C_RESET} {name} ({ssid})");
let _ = nm::delete_connections_for_ssid(ssid);
}
}
Ok(0)
}
fn cmd_scan(cfg: &mut Config, to: Option<String>) -> Result<i32, String> {
// Validate `--to` up front, before any side effects (connecting is
// one): `add --to` errors on an unknown profile, so `scan --to` must
// too instead of silently saving a network that never gets attached.
if let Some(prof_name) = &to {
if !cfg.profiles.contains_key(prof_name) {
return Err(format!("unknown profile '{prof_name}'"));
}
}
let iface = nm::wifi_interface_preferred(cfg.settings.interface.as_deref())
.ok_or("no Wi-Fi adapter")?;
nm::radio_on();
nm::rescan(&iface, &[]);
let entries = nm::scan_list(&iface);
if entries.is_empty() {
return Err("no networks found".into());
}
for (i, e) in entries.iter().enumerate() {
println!(
"{:>2}. {C_BOLD}{}{C_RESET} {C_DIM}sig {} {}{C_RESET}",
i + 1,
if e.ssid.is_empty() {
"<hidden>"
} else {
&e.ssid
},
e.signal,
e.security
);
}
let sel = prompt_line("Select number: ");
let idx: usize = sel
.parse::<usize>()
.ok()
.filter(|n| *n >= 1 && *n <= entries.len())
.ok_or("invalid selection")?;
let ssid = entries[idx - 1].ssid.clone();
if ssid.is_empty() {
return Err("cannot select a hidden SSID here; use `breadcrumbs add`".into());
}
let password = non_empty(prompt_secret(&format!("Password for '{ssid}': ")));
let mut def = NetworkDef {
ssid: ssid.clone(),
password,
dns: None,
eap: None,
identity: None,
ca_cert: None,
hidden: false,
};
if !nm::connect(&iface, &def, cfg.settings.connect_wait, &cfg.settings.dns) {
return Err(format!("failed to connect to {ssid}"));
}
// A successful connect means NetworkManager now durably holds the PSK
// (either in a freshly created profile, or one whose PSK we just set) —
// breadcrumbs no longer needs to keep its own plaintext copy.
def.password = None;
match cfg.networks.iter_mut().find(|n| n.ssid == ssid) {
Some(n) => n.password = None,
None => cfg.networks.push(def),
}
if let Some(prof_name) = to {
if let Some(prof) = cfg.profiles.get_mut(&prof_name) {
if !prof.networks.contains(&ssid) {
prof.networks.push(ssid.clone());
}
}
}
cfg.save()?;
println!("{C_GREEN}connected + saved{C_RESET} {ssid}");
Ok(0)
}
/// Mask a secret for display. Always renders the same fixed-length
/// placeholder so the output reveals neither the secret's length nor any
/// character of it (a fixed placeholder is what password managers show;
/// length-hiding also means multi-byte UTF-8 passwords need no special
/// handling).
fn mask(_p: &str) -> String {
"".repeat(8)
}
fn cmd_list(cfg: &Config, show_pw: bool) -> Result<i32, String> {
println!("{C_BOLD}settings{C_RESET}");
println!(" dns {}", cfg.settings.dns);
println!(" exit_node {}", cfg.settings.exit_node);
println!(" default {}", cfg.settings.default_profile);
println!(" watch every {}s", cfg.settings.watch_interval);
println!("\n{C_BOLD}networks{C_RESET}");
for n in &cfg.networks {
let pw_display = match &n.password {
Some(p) if show_pw => p.clone(),
Some(p) => mask(p),
// No local secret: NetworkManager already owns the credential for
// this SSID, so there is nothing to mask — showing dots here
// would falsely imply breadcrumbs is still hiding a password.
None => format!("{C_DIM}managed by NetworkManager{C_RESET}"),
};
println!(
" {C_BOLD}{}{C_RESET} {C_DIM}{}{}{C_RESET}",
n.ssid,
pw_display,
if n.hidden { " (hidden)" } else { "" }
);
}
println!("\n{C_BOLD}profiles{C_RESET}");
let cur = State::load(&cfg.settings.default_profile).profile;
for (name, p) in &cfg.profiles {
let mark = if *name == cur {
format!("{C_GREEN}*{C_RESET}")
} else {
" ".into()
};
println!("{mark} {C_BOLD}{name}{C_RESET}");
if let Some(b) = &p.bootstrap {
println!(" bootstrap {b}");
}
if p.tailscale {
println!(
" tailscale required (exit: {})",
p.exit_node
.clone()
.unwrap_or_else(|| cfg.settings.exit_node.clone())
);
}
let mut order: Vec<String> = p.networks.clone();
if p.include_all_known {
order.push("…all other known networks".into());
}
println!(" priority {}", order.join(" > "));
}
Ok(0)
}
fn cmd_edit() -> Result<i32, String> {
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "nano".into());
let path = config::config_path();
// EDITOR values routinely carry arguments ("code -w", "subl -w"), so
// split on whitespace: the first token is the program, the rest are its
// arguments. The path stays a separate argument — never interpolated
// into a shell string — so it can't be used for injection.
let mut parts = editor.split_whitespace();
let prog = parts.next().unwrap_or("nano");
let mut cmd = Command::new(prog);
cmd.args(parts);
let status = cmd
.arg(&path)
.status()
.map_err(|e| format!("launching {editor}: {e}"))?;
if !status.success() {
return Err("editor exited with error".into());
}
match Config::load() {
Ok(_) => {
println!("{C_GREEN}config OK{C_RESET}");
Ok(0)
}
Err(e) => Err(format!("config is now invalid: {e}")),
}
}
fn cmd_doctor(cfg: &Config, override_p: &Option<String>, full: bool) -> Result<i32, String> {
if full {
let script = config::config_dir().join("diag.sh");
if !script.exists() {
return Err(format!(
"diag.sh not found (expected at {})",
script.display()
));
}
let st = Command::new("bash")
.arg(&script)
.status()
.map_err(|e| format!("running diag: {e}"))?;
return Ok(st.code().unwrap_or(1));
}
let p = active_profile(cfg, override_p);
let s = crate::status::gather(cfg, &p);
println!("{C_BOLD}breadcrumbs doctor{C_RESET} (profile {p})");
println!(
" network-manager {}",
if nm::available() {
"present (D-Bus)"
} else {
"MISSING"
}
);
println!(
" tailscale {}",
if command_exists("tailscale") {
"present"
} else {
"absent"
}
);
println!(
" adapter {}",
s.iface.clone().unwrap_or_else(|| "none".into())
);
println!(
" ssid {}",
s.ssid.clone().unwrap_or_else(|| "".into())
);
println!(
" ip {}",
s.ip.clone().unwrap_or_else(|| "".into())
);
println!(" internet {}", if s.internet { "ok" } else { "DOWN" });
if let Some(h) = &s.tailscale {
println!(" tailscale {} (exit {})", h.describe(), s.exit_node);
}
if let Some(iface) = &s.iface {
let visible = nm::visible_ssids(iface);
let known: Vec<&str> = cfg
.networks
.iter()
.filter(|n| visible.contains(&n.ssid))
.map(|n| n.ssid.as_str())
.collect();
println!(
" in range {}",
if known.is_empty() {
"none of your saved networks".into()
} else {
known.join(", ")
}
);
}
println!("\nFull report: {C_DIM}breadcrumbs doctor --full{C_RESET}");
Ok(0)
}
fn cmd_cd(shell: bool) -> Result<i32, String> {
let dir = config::config_dir();
if shell {
let sh = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
let err = exec_replace(&sh, &dir);
return Err(err);
}
println!("{}", dir.display());
Ok(0)
}
/// Re-exec into an interactive login shell inside `dir`, replacing the
/// current process. `dir` is passed as `$1` to the shell script rather than
/// interpolated into the script text — the config dir can come from
/// `$XDG_CONFIG_HOME`/`$HOME`, and string-formatting an arbitrary path
/// straight into a `sh -c` command would let shell metacharacters (`$(...)`,
/// backticks, etc.) in that path execute as commands.
fn exec_replace(prog: &str, dir: &std::path::Path) -> String {
use std::os::unix::process::CommandExt;
let e = Command::new(prog)
.arg("-lc")
.arg("cd \"$1\" && exec \"$0\"")
.arg(prog)
.arg(dir)
.exec();
format!("exec {prog} failed: {e}")
}
fn cmd_install_service(enable: bool) -> Result<i32, String> {
// Honor XDG_CONFIG_HOME like the rest of the app: systemd --user units
// live in $XDG_CONFIG_HOME/systemd/user (default ~/.config/systemd/user).
let unit_dir = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".config"))
.join("systemd")
.join("user");
std::fs::create_dir_all(&unit_dir)
.map_err(|e| format!("creating {}: {e}", unit_dir.display()))?;
let bin = std::env::current_exe().map_err(|e| format!("resolving current executable: {e}"))?;
// Ordering against graphical-session.target lets the watcher inherit the
// session's DISPLAY/WAYLAND_DISPLAY/DBUS so notify-send and the Tailscale
// login browser-open actually work. PATH is pinned because systemd --user
// units do not get the login shell's PATH, and the watcher shells out to
// tailscale/sudo/xdg-open by name (NetworkManager is reached over D-Bus,
// so no nmcli is needed).
let unit = format!(
"[Unit]\n\
Description=breadcrumbs Wi-Fi state machine watcher\n\
After=network.target NetworkManager.service graphical-session.target\n\
Wants=network.target graphical-session.target\n\n\
[Service]\n\
Type=simple\n\
Environment=PATH=/usr/local/bin:/usr/bin:/bin\n\
ExecStart={bin} watch\n\
Restart=always\n\
RestartSec=5\n\
Nice=5\n\n\
[Install]\n\
WantedBy=default.target\n",
bin = bin.display()
);
let unit_path = unit_dir.join("breadcrumbs.service");
std::fs::write(&unit_path, unit)
.map_err(|e| format!("writing {}: {e}", unit_path.display()))?;
println!("{C_GREEN}wrote{C_RESET} {}", unit_path.display());
let _ = util::run(
"systemctl",
&["--user", "daemon-reload"],
Duration::from_secs(10),
);
if enable {
let o = util::run(
"systemctl",
&["--user", "enable", "--now", "breadcrumbs.service"],
Duration::from_secs(15),
);
if o.success {
println!("{C_GREEN}enabled + started{C_RESET} breadcrumbs.service");
} else {
println!(
"{C_YELLOW}unit installed{C_RESET}; enable failed: {}",
o.stderr.trim()
);
return Ok(1);
}
} else {
println!("Run: systemctl --user enable --now breadcrumbs.service");
}
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mask_is_fixed_length_regardless_of_secret() {
// Fixed-length masking: the output must reveal neither the secret's
// length nor any character of it — for empty, short, and long
// secrets alike.
assert_eq!(mask(""), "".repeat(8));
assert_eq!(mask("a"), "".repeat(8));
assert_eq!(mask("ab"), "".repeat(8));
assert_eq!(mask("hunter2"), "".repeat(8));
assert!(!mask("hunter2").contains('h'));
}
#[test]
fn mask_multibyte_password_does_not_panic() {
// Regression test: the old byte-slicing `&p[..1]` panicked whenever
// the first character of the password was multi-byte UTF-8 (e.g. an
// emoji or accented character), since byte index 1 can land mid-char.
let pw = "日本語パスワード";
let masked = mask(pw);
assert_eq!(masked, "".repeat(8));
assert!(masked.chars().all(|c| c == '•'));
}
#[test]
fn mask_emoji_first_character_does_not_panic() {
let pw = "🔒password123";
assert_eq!(mask(pw), "".repeat(8));
}
}

80
src/backend.rs Normal file
View file

@ -0,0 +1,80 @@
//! The seam between breadcrumbs' decision logic and the outside world.
//!
//! Every interaction with NetworkManager, Tailscale, connectivity probes,
//! notifications and logging goes through the [`Backend`] trait. Production code
//! uses [`System`], which delegates to the `nm`/`tailscale`/`status`/`notify`
//! modules that shell out. Tests inject a fake so the connect state machine
//! (`flow`) and watch classifier can be exercised without touching the host.
use std::collections::HashSet;
use crate::config::{Config, NetworkDef};
use crate::nm;
use crate::notify::{self, Urgency};
use crate::status::{self, Connectivity};
use crate::tailscale::{self, TsHealth};
pub trait Backend {
fn wifi_interface(&self) -> Option<String>;
fn radio_on(&self);
fn rescan(&self, iface: &str, ssids: &[String]);
fn visible_ssids(&self, iface: &str) -> HashSet<String>;
fn active_ssid(&self, iface: &str) -> Option<String>;
fn ipv4(&self, iface: &str) -> Option<String>;
fn device_connected(&self, iface: &str) -> bool;
fn connect(&self, iface: &str, net: &NetworkDef, wait: u32, dns: &str) -> Result<(), String>;
fn tailscale_installed(&self) -> bool;
fn ensure_exit_node(&self, node: &str) -> TsHealth;
fn tailscale_check(&self, node: &str) -> TsHealth;
fn connectivity(&self, cfg: &Config) -> Connectivity;
fn notify(&self, summary: &str, body: &str, urgency: Urgency);
fn log(&self, line: &str);
}
/// The real backend: every method delegates to the system-facing modules.
pub struct System;
impl Backend for System {
fn wifi_interface(&self) -> Option<String> {
nm::wifi_interface()
}
fn radio_on(&self) {
nm::radio_on()
}
fn rescan(&self, iface: &str, ssids: &[String]) {
nm::rescan(iface, ssids)
}
fn visible_ssids(&self, iface: &str) -> HashSet<String> {
nm::visible_ssids(iface)
}
fn active_ssid(&self, iface: &str) -> Option<String> {
nm::active_ssid(iface)
}
fn ipv4(&self, iface: &str) -> Option<String> {
status::ipv4(iface)
}
fn device_connected(&self, iface: &str) -> bool {
nm::device_connected(iface)
}
fn connect(&self, iface: &str, net: &NetworkDef, wait: u32, dns: &str) -> Result<(), String> {
nm::connect_verbose(iface, net, wait, dns)
}
fn tailscale_installed(&self) -> bool {
tailscale::installed()
}
fn ensure_exit_node(&self, node: &str) -> TsHealth {
tailscale::ensure_exit_node(node)
}
fn tailscale_check(&self, node: &str) -> TsHealth {
tailscale::check(node)
}
fn connectivity(&self, cfg: &Config) -> Connectivity {
status::connectivity(cfg)
}
fn notify(&self, summary: &str, body: &str, urgency: Urgency) {
notify::notify(summary, body, urgency)
}
fn log(&self, line: &str) {
notify::log(line)
}
}

View file

@ -1,156 +0,0 @@
//! `bread.crumbs.*` event integration — optional, non-blocking. See
//! `EVENTS.md` at the repo root for the full contract. breadcrumbs works
//! identically with or without breadd running; every call here is
//! fire-and-forget (`BreadClient::emit` never blocks or errors this
//! process) so a missing or restarting breadd never affects Wi-Fi
//! automation itself.
use bread_utils::bread_client::{BreadClient, BreadEvent};
use crate::config::Config;
use crate::state;
/// This app's id in bread's sibling-app namespace registry
/// (`bread_shared::apps::KNOWN_APPS`) — events publish as `bread.crumbs.*`,
/// commands arrive on `bread.command.crumbs.*`.
pub const APP_ID: &str = "crumbs";
pub fn client() -> BreadClient {
BreadClient::connect(APP_ID)
}
pub fn emit_profile_changed(client: &BreadClient, from: &str, to: &str) {
client.emit(
"bread.crumbs.profile.changed",
serde_json::json!({ "from": from, "to": to }),
);
}
/// Payload for `bread.crumbs.health.changed`. Constructed by the watch
/// loop from a classification and passed as a unit so the emit functions
/// stay small.
pub struct HealthChanged<'a> {
pub profile: &'a str,
pub health: &'a str,
pub ssid: Option<&'a str>,
pub iface: Option<&'a str>,
pub ip: Option<&'a str>,
pub exit_node: &'a str,
pub tailscale: Option<&'a str>,
}
pub fn emit_health_changed(client: &BreadClient, ev: HealthChanged<'_>) {
client.emit(
"bread.crumbs.health.changed",
serde_json::json!({
"profile": ev.profile,
"health": ev.health,
"ssid": ev.ssid,
"iface": ev.iface,
"ip": ev.ip,
"exit_node": ev.exit_node,
"tailscale": ev.tailscale,
}),
);
}
/// `bread.crumbs.network.changed` — the watch loop observed the active SSID
/// transition. `from` is `null` when there was no previous association.
pub fn emit_network_changed(client: &BreadClient, from: Option<&str>, to: Option<&str>, profile: &str) {
client.emit(
"bread.crumbs.network.changed",
serde_json::json!({ "from": from, "to": to, "profile": profile }),
);
}
/// `bread.crumbs.tailscale.changed` — the Tailscale health state (or its
/// mere presence) changed between watch-loop ticks.
pub fn emit_tailscale_changed(
client: &BreadClient,
profile: &str,
state: Option<&str>,
exit_node: &str,
) {
client.emit(
"bread.crumbs.tailscale.changed",
serde_json::json!({
"profile": profile,
"state": state,
"exit_node": exit_node,
}),
);
}
/// What a `bread.command.crumbs.*` event asks the watch loop to do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommandAction {
/// Persist this profile via [`state::set_profile`]. Applied on the
/// watch loop thread — the single owner of config/state file access —
/// never on the subscription thread, which would race the loop's own
/// `Config::load`/`save`.
SetProfile(String),
/// Nothing to do: unknown verb, or a validation failure already
/// reported via `bread.crumbs.set_profile.failed`.
Ignore,
}
/// Reacts to `bread.command.crumbs.*` verbs. Only `set_profile` maps to
/// real, existing breadcrumbs functionality today — there is no pin/select
/// (or other) verb because breadcrumbs has no such concept. Unrecognized
/// verbs are ignored, not stubbed as no-ops that pretend to succeed.
///
/// This only *parses and validates* the command — it performs no file I/O
/// (that would race the watch loop's own config access from a second
/// thread). The returned [`CommandAction`] is forwarded to the loop, which
/// applies it via [`apply_set_profile`].
pub fn handle_command(event: &BreadEvent) -> CommandAction {
let Some(verb) = event.event.strip_prefix("bread.command.crumbs.") else {
return CommandAction::Ignore;
};
match verb {
"set_profile" => match event.data.get("profile").and_then(|v| v.as_str()) {
Some(name) if !name.trim().is_empty() => CommandAction::SetProfile(name.to_string()),
_ => {
emit_set_profile_failed("missing string \"profile\" in command data");
CommandAction::Ignore
}
},
other => {
crate::notify::log(&format!(
"watch: ignoring unrecognized bread.command.crumbs.{other}"
));
CommandAction::Ignore
}
}
}
/// Apply a `set_profile` command on the watch loop thread and emit the
/// `done`/`failed` confirmation. Kept separate from [`handle_command`] so
/// the bread subscription thread never touches config/state files
/// concurrently with the loop.
pub fn apply_set_profile(name: &str) {
match Config::load().and_then(|cfg| state::set_profile(&cfg, name)) {
Ok(()) => {
crate::notify::log(&format!(
"watch: profile set via bread.command.crumbs.set_profile -> {name}"
));
client().emit(
"bread.crumbs.set_profile.done",
serde_json::json!({ "profile": name }),
);
}
Err(e) => {
emit_set_profile_failed(&e);
}
}
}
fn emit_set_profile_failed(error: &str) {
crate::notify::log(&format!(
"watch: bread.command.crumbs.set_profile failed: {error}"
));
client().emit(
"bread.crumbs.set_profile.failed",
serde_json::json!({ "error": error }),
);
}

View file

@ -9,7 +9,7 @@ use crate::util::home_dir;
fn default_dns() -> String {
"1.1.1.1".to_string()
}
fn default_connect_wait() -> u32 {
fn default_nmcli_wait() -> u32 {
8
}
fn default_exit_node() -> String {
@ -28,59 +28,12 @@ fn default_ping_host() -> String {
"1.1.1.1".to_string()
}
/// Parse "HH:MM" (24h) into minutes since midnight; `None` if malformed.
pub fn hhmm_to_minutes(s: &str) -> Option<u32> {
let (h, m) = s.trim().split_once(':')?;
let h: u32 = h.parse().ok()?;
let m: u32 = m.parse().ok()?;
if h > 23 || m > 59 {
return None;
}
Some(h * 60 + m)
}
/// Does the window `[from, to)` (minutes since midnight) contain `now`?
/// `from >= to` means an overnight window (e.g. 22:0007:00).
pub fn window_contains(from: u32, to: u32, now: u32) -> bool {
if from < to {
now >= from && now < to
} else {
now >= from || now < to
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScheduleEntry {
/// Profile to switch to while the window is active.
pub profile: String,
/// "HH:MM", inclusive start.
pub from: String,
/// "HH:MM", exclusive end (`from >= to` means overnight).
pub to: String,
}
impl ScheduleEntry {
/// Whether the window contains `now_minutes` (minutes since midnight).
pub fn contains(&self, now_minutes: u32) -> bool {
match (hhmm_to_minutes(&self.from), hhmm_to_minutes(&self.to)) {
(Some(f), Some(t)) => window_contains(f, t, now_minutes),
_ => false,
}
}
}
fn is_false(b: &bool) -> bool {
!b
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
#[serde(default = "default_dns")]
pub dns: String,
/// Seconds to wait for a connect to reach the ACTIVATED device state.
/// `nmcli_wait` is accepted as a legacy alias.
#[serde(default = "default_connect_wait", alias = "nmcli_wait")]
pub connect_wait: u32,
#[serde(default = "default_nmcli_wait")]
pub nmcli_wait: u32,
#[serde(default = "default_exit_node")]
pub exit_node: String,
#[serde(default = "default_profile_name")]
@ -91,101 +44,30 @@ pub struct Settings {
pub connectivity_url: String,
#[serde(default = "default_ping_host")]
pub ping_host: String,
/// Set the first time the config is saved. Core profiles (`home` /
/// `work` / `away`) are only backfilled for genuinely fresh or legacy
/// configs; once the user owns the file, a profile they deliberately
/// deleted stays deleted instead of being silently resurrected on the
/// next load. Omits itself from the TOML until set, so existing
/// configs keep parsing exactly as before.
#[serde(default, skip_serializing_if = "is_false")]
pub core_profiles_initialized: bool,
/// Preferred Wi-Fi interface (e.g. "wlan0"). When set, this exact
/// device is used if present; otherwise the first Wi-Fi device wins.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interface: Option<String>,
/// Priority-ordered fallback exit nodes. Tried in order by the flow;
/// the first healthy one is selected. Falls back to `exit_node` when
/// empty.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exit_nodes: Vec<String>,
/// Optional time-of-day schedule: at a given time, switch to the listed
/// profile automatically (respecting a manual-override grace window;
/// see the watch loop). First matching rule wins; outside every window
/// nothing is switched.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub schedule: Vec<ScheduleEntry>,
}
impl Default for Settings {
fn default() -> Self {
Settings {
dns: default_dns(),
connect_wait: default_connect_wait(),
nmcli_wait: default_nmcli_wait(),
exit_node: default_exit_node(),
default_profile: default_profile_name(),
watch_interval: default_watch_interval(),
connectivity_url: default_connectivity_url(),
ping_host: default_ping_host(),
core_profiles_initialized: false,
interface: None,
exit_nodes: Vec::new(),
schedule: Vec::new(),
}
}
}
impl Settings {
/// The profile a time-of-day schedule picks for `now_minutes` (minutes
/// since midnight), if any — first matching rule wins.
pub fn scheduled_profile(&self, now_minutes: u32) -> Option<String> {
self.schedule
.iter()
.find(|e| e.contains(now_minutes))
.map(|e| e.profile.clone())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkDef {
pub ssid: String,
/// A password is only needed once. On first successful connect,
/// NetworkManager durably saves the credential (a new connection
/// profile, or an updated PSK on an existing one); breadcrumbs then
/// clears this field and, on the next save, omits the key entirely
/// rather than writing a plaintext copy that's no longer needed. `None`
/// means either "NetworkManager already owns this secret" or "this is
/// an open (unsecured) network" — both cases behave the same way on
/// connect: no PSK is sent to nmcli at all. When `Some`, the PSK is
/// fed to `nmcli --ask` on stdin, never as an argv element.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
/// Per-network DNS override. `None` falls back to `settings.dns`;
/// an explicitly empty string disables DNS pinning for this network.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dns: Option<String>,
/// WPA-Enterprise (802.1x). When `eap` is set the network is treated as
/// enterprise: `identity` + `password` (reused) + optional `ca_cert`
/// path. `eap` is e.g. "peap" or "tls".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub eap: Option<String>,
/// 802.1x identity (e.g. `user@corp`) for enterprise networks.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
/// Path to a CA certificate for 802.1x (optional).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ca_cert: Option<String>,
pub password: String,
#[serde(default)]
pub hidden: bool,
}
impl NetworkDef {
/// The DNS to pin for this network: the per-network override if set,
/// otherwise the global setting.
pub fn effective_dns<'a>(&'a self, fallback: &'a str) -> &'a str {
self.dns.as_deref().unwrap_or(fallback)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Profile {
/// Optional SSID connected first to bootstrap connectivity (e.g. for Tailscale).
@ -207,41 +89,18 @@ pub struct Profile {
/// Used by `breadcrumbs detect` to guess the active profile.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub detect_ssids: Vec<String>,
/// Opt-in learning: on a successful connect, the SSID is appended to
/// `detect_ssids` (bounded) so `breadcrumbs detect` improves without
/// hand-editing. Off by default to keep detect predictable.
#[serde(default, skip_serializing_if = "is_false")]
pub learn: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub settings: Settings,
/// Saved networks (SSID + optional local password). Persisted to the
/// separate `networks.toml` file (see [`networks_path`]), not to
/// `breadcrumbs.toml` — kept here, and still deserialized from a
/// `[[networks]]` block if one is present in `breadcrumbs.toml`, purely
/// for backward compatibility with configs written before the secrets
/// split: an old-format file's inline networks load in on first read and
/// migrate to `networks.toml` automatically on the next `save()`, no
/// explicit migration step required.
#[serde(default, rename = "networks", skip_serializing)]
#[serde(default, rename = "networks")]
pub networks: Vec<NetworkDef>,
#[serde(default)]
pub profiles: BTreeMap<String, Profile>,
}
/// The on-disk shape of `networks.toml`: just the `[[networks]]` array,
/// split out of the main config so a file that's mostly just settings and
/// profiles (the parts people actually hand-edit or dotfile) doesn't also
/// carry whatever plaintext Wi-Fi credentials breadcrumbs still holds.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct NetworksFile {
#[serde(default, rename = "networks")]
networks: Vec<NetworkDef>,
}
pub fn config_dir() -> PathBuf {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
@ -253,13 +112,6 @@ pub fn config_path() -> PathBuf {
config_dir().join("breadcrumbs.toml")
}
/// Where saved networks (SSID + optional local password) live, split out of
/// `breadcrumbs.toml`. Not meant to be hand-edited — managed via
/// `breadcrumbs add` / `scan` / `forget`.
pub fn networks_path() -> PathBuf {
config_dir().join("networks.toml")
}
pub fn state_dir() -> PathBuf {
std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
@ -284,119 +136,36 @@ impl Config {
self.networks.iter().find(|n| n.ssid == ssid)
}
/// The effective exit-node list for a profile, in priority order:
/// per-profile `exit_node`, else `settings.exit_nodes`, else
/// `settings.exit_node`. Empty entries are filtered out.
pub fn exit_nodes_for(&self, profile: &str) -> Vec<String> {
if let Some(p) = self.profiles.get(profile).and_then(|p| p.exit_node.clone()) {
return vec![p];
}
let list = if self.settings.exit_nodes.is_empty() {
vec![self.settings.exit_node.clone()]
} else {
self.settings.exit_nodes.clone()
};
list.into_iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
/// Load config, creating a skeleton one on first run.
pub fn load() -> Result<Config, String> {
let path = config_path();
if !path.exists() {
let mut cfg = build_initial_config();
let cfg = build_initial_config();
cfg.save()?;
return Ok(cfg);
}
let text =
fs::read_to_string(&path).map_err(|e| format!("reading {}: {e}", path.display()))?;
// May carry a legacy inline `[[networks]]` block (pre-split
// configs) — that's fine, see the field doc on `Config::networks`.
let mut cfg: Config =
toml::from_str(&text).map_err(|e| format!("parsing {}: {e}", path.display()))?;
let net_path = networks_path();
if net_path.exists() {
let net_text = fs::read_to_string(&net_path)
.map_err(|e| format!("reading {}: {e}", net_path.display()))?;
let nf: NetworksFile = toml::from_str(&net_text)
.map_err(|e| format!("parsing {}: {e}", net_path.display()))?;
// Merge, don't overwrite: a legacy config can still carry an
// inline `[[networks]]` block, and those entries must survive
// even when networks.toml already exists — otherwise the next
// save() (which writes only networks.toml) would silently drop
// hand-added inline networks. networks.toml wins on SSID
// conflicts; inline-only entries are appended and migrated.
let mut merged = nf.networks;
for def in std::mem::take(&mut cfg.networks) {
if !merged.iter().any(|n| n.ssid == def.ssid) {
merged.push(def);
}
}
cfg.networks = merged;
}
// else: no networks.toml yet — keep whatever legacy inline networks
// were read from breadcrumbs.toml above (or none, on a genuinely
// fresh config). The next `save()` writes them to networks.toml and
// stops writing them into breadcrumbs.toml, completing the migration.
// Enforce the documented minimum so `list` and the watch loop agree
// on the poll interval (watch silently clamps to 4 otherwise).
if cfg.settings.watch_interval < 4 {
cfg.settings.watch_interval = 4;
}
// Self-heal: guarantee the three core profiles always exist.
ensure_core_profiles(&mut cfg);
Ok(cfg)
}
/// Persist settings + profiles to `breadcrumbs.toml` and networks to the
/// separate `networks.toml`, both `0600`. Every mutating command (`add`,
/// `forget`, `scan`, `profile set`, and `flow::run`'s own credential
/// clearing) goes through this single method so the two files never
/// drift out of sync with each other.
pub fn save(&mut self) -> Result<(), String> {
// The first save marks the config as user-owned: core profiles are
// backfilled only for genuinely fresh/legacy configs, never
// resurrected after the user has edited (or deleted) them.
self.settings.core_profiles_initialized = true;
pub fn save(&self) -> Result<(), String> {
let dir = config_dir();
fs::create_dir_all(&dir).map_err(|e| format!("creating {}: {e}", dir.display()))?;
let text = toml::to_string_pretty(self).map_err(|e| format!("serializing config: {e}"))?;
let path = config_path();
fs::write(&path, text).map_err(|e| format!("writing {}: {e}", path.display()))?;
secure_permissions(&path);
let nf = NetworksFile {
networks: self.networks.clone(),
};
let net_text =
toml::to_string_pretty(&nf).map_err(|e| format!("serializing networks: {e}"))?;
let net_path = networks_path();
fs::write(&net_path, net_text)
.map_err(|e| format!("writing {}: {e}", net_path.display()))?;
secure_permissions(&net_path);
// Plaintext Wi-Fi passwords live here: write atomically and owner-only,
// so there's no torn read and no world-readable window.
crate::util::write_atomic(&path, &text, 0o600)
.map_err(|e| format!("writing {}: {e}", path.display()))?;
Ok(())
}
}
/// Any local Wi-Fi passwords still held (pre-first-connect, or a network
/// breadcrumbs doesn't yet know NetworkManager owns) live in plaintext on
/// disk — keep both config files owner-only. Best-effort: a failure here
/// isn't fatal to saving the config itself.
#[cfg(unix)]
fn secure_permissions(path: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
}
#[cfg(not(unix))]
fn secure_permissions(_path: &std::path::Path) {}
/// Initial skeleton networks generated for a brand-new installation.
/// Passwords are intentionally blank — secrets never live in source.
/// Users fill them via `breadcrumbs add`, `breadcrumbs scan`, or
@ -421,7 +190,6 @@ fn core_profiles() -> BTreeMap<String, Profile> {
exit_node: None,
include_all_known: false,
detect_ssids: vec![],
learn: false,
},
);
p.insert(
@ -433,7 +201,6 @@ fn core_profiles() -> BTreeMap<String, Profile> {
exit_node: None,
include_all_known: false,
detect_ssids: vec![],
learn: false,
},
);
p.insert(
@ -445,22 +212,21 @@ fn core_profiles() -> BTreeMap<String, Profile> {
exit_node: None,
include_all_known: true,
detect_ssids: vec![],
learn: false,
},
);
p
}
fn ensure_core_profiles(cfg: &mut Config) {
// Backfill missing core profiles only until the user has taken
// ownership of the config (`core_profiles_initialized` is set by the
// first save). After that, a profile the user deliberately deleted
// stays deleted.
if cfg.settings.core_profiles_initialized {
// Only self-heal a genuinely empty/corrupted profile set. A user who has
// defined their own profiles (any names, any case) should never have
// unused core-profile stubs ("home"/"work"/"away") silently padded in
// alongside them.
if !cfg.profiles.is_empty() {
return;
}
for (name, prof) in core_profiles() {
cfg.profiles.entry(name).or_insert(prof);
cfg.profiles.insert(name, prof);
}
}
@ -514,279 +280,141 @@ mod tests {
}
#[test]
fn ensure_core_profiles_skips_backfill_once_initialized() {
// After the first save the config is user-owned: a deliberately
// deleted core profile must stay deleted instead of being
// resurrected on every load.
let mut cfg = Config {
settings: Settings {
core_profiles_initialized: true,
..Default::default()
},
networks: vec![],
profiles: BTreeMap::new(),
};
ensure_core_profiles(&mut cfg);
assert!(cfg.profiles.is_empty(), "no backfill once user-owned");
}
#[test]
fn ensure_core_profiles_preserves_user_customized_core_profile() {
// A user-edited "home" (custom SSIDs) must not be clobbered by the
// self-heal backfill — only genuinely *missing* core profiles should
// be inserted.
let mut profiles = BTreeMap::new();
profiles.insert(
"home".to_string(),
Profile {
networks: vec!["CustomSSID".into()],
..Default::default()
},
);
fn ensure_core_profiles_does_not_overwrite_existing() {
let mut cfg = Config {
settings: Settings::default(),
networks: vec![],
profiles,
profiles: BTreeMap::new(),
};
ensure_core_profiles(&mut cfg);
assert_eq!(
cfg.profile("home").unwrap().networks,
vec!["CustomSSID".to_string()]
cfg.profiles.insert(
"home".to_string(),
Profile {
tailscale: true,
exit_node: Some("mynode".into()),
..Default::default()
},
);
// Still backfills the ones that were actually missing.
assert!(cfg.profile("work").is_some());
assert!(cfg.profile("away").is_some());
ensure_core_profiles(&mut cfg);
let home = cfg.profile("home").unwrap();
assert!(home.tailscale, "existing field should be preserved");
assert_eq!(home.exit_node.as_deref(), Some("mynode"));
}
#[test]
fn settings_default_matches_documented_defaults() {
fn ensure_core_profiles_does_not_pad_a_customized_profile_set() {
let mut cfg = Config {
settings: Settings::default(),
networks: vec![],
profiles: BTreeMap::new(),
};
cfg.profiles.insert("Home".to_string(), Profile::default());
cfg.profiles.insert("Away".to_string(), Profile::default());
cfg.profiles.insert("School".to_string(), Profile::default());
ensure_core_profiles(&mut cfg);
// The user's own profile names are untouched, and no unused
// core-profile stubs (home/work/away) get injected alongside them.
assert_eq!(cfg.profiles.len(), 3);
assert!(cfg.profile("home").is_none());
assert!(cfg.profile("work").is_none());
assert!(cfg.profile("away").is_none());
}
#[test]
fn network_lookup_found_and_not_found() {
let mut cfg = build_initial_config();
cfg.networks.push(NetworkDef {
ssid: "TestNet".into(),
password: "secret".into(),
hidden: false,
});
let found = cfg.network("TestNet");
assert!(found.is_some());
assert_eq!(found.unwrap().password, "secret");
assert!(cfg.network("NoSuchSSID").is_none());
}
#[test]
fn profile_lookup_found_and_not_found() {
let cfg = build_initial_config();
assert!(cfg.profile("home").is_some());
assert!(cfg.profile("nonexistent").is_none());
}
#[test]
fn settings_default_values() {
let s = Settings::default();
assert_eq!(s.dns, "1.1.1.1");
assert_eq!(s.connect_wait, 8);
assert_eq!(s.nmcli_wait, 8);
assert!(s.exit_node.is_empty());
assert_eq!(s.default_profile, "away");
assert_eq!(s.watch_interval, 12);
assert_eq!(s.ping_host, "1.1.1.1");
assert!(s.exit_node.is_empty());
assert!(!s.connectivity_url.is_empty());
assert!(!s.ping_host.is_empty());
}
#[test]
fn network_def_hidden_defaults_false_when_omitted() {
let text = r#"ssid = "Cafe"
password = "pw""#;
let n: NetworkDef = toml::from_str(text).unwrap();
assert!(!n.hidden);
}
#[test]
fn network_def_password_defaults_to_none_when_key_absent() {
// No `password` key at all — e.g. a network whose secret breadcrumbs
// already cleared after NetworkManager took it over.
let text = r#"ssid = "Cafe"
hidden = false"#;
let n: NetworkDef = toml::from_str(text).unwrap();
assert_eq!(n.password, None);
}
#[test]
fn network_def_omits_password_key_entirely_when_none() {
// Round-tripping a cleared password must not write `password = ""`
// (which would read back as "has an empty secret") or any other
// stand-in — the key should be gone, full stop.
let n = NetworkDef {
ssid: "Cafe".into(),
password: None,
dns: None,
eap: None,
identity: None,
ca_cert: None,
hidden: false,
};
let text = toml::to_string_pretty(&n).unwrap();
assert!(!text.contains("password"), "text: {text}");
}
#[test]
fn network_def_password_round_trips_through_toml() {
let n = NetworkDef {
ssid: "Cafe".into(),
password: Some("hunter2".into()),
dns: None,
eap: None,
identity: None,
ca_cert: None,
hidden: false,
};
let text = toml::to_string_pretty(&n).unwrap();
assert!(text.contains("hunter2"));
let back: NetworkDef = toml::from_str(&text).unwrap();
assert_eq!(back.password, Some("hunter2".to_string()));
}
// Note: `Config::save`/`Config::load`'s real filesystem behavior (the
// networks.toml split, and a cleared password actually landing on disk)
// is covered by `tests/cli.rs`'s Sandbox-isolated integration tests
// (`networks_are_stored_separately_from_settings_and_profiles`,
// `password_is_cleared_after_first_connect_and_never_sent_again`) rather
// than here — this module's tests stay pure per the project's test
// discipline (no real fs/env/subprocess access from a `#[cfg(test)]`
// unit test).
#[test]
fn profile_default_has_no_bootstrap_or_tailscale() {
let p = Profile::default();
assert!(p.bootstrap.is_none());
assert!(!p.tailscale);
assert!(!p.include_all_known);
assert!(p.networks.is_empty());
assert!(p.detect_ssids.is_empty());
}
#[test]
fn malformed_toml_fails_to_parse() {
let bad = "this is not [ valid toml";
assert!(toml::from_str::<Config>(bad).is_err());
}
#[test]
fn config_with_only_settings_defaults_networks_and_profiles() {
// A hand-written config that only sets `[settings]` shouldn't require
// `networks`/`profiles` sections — both must fall back to `#[serde(default)]`.
let text = r#"[settings]
dns = "9.9.9.9""#;
let cfg: Config = toml::from_str(text).unwrap();
assert_eq!(cfg.settings.dns, "9.9.9.9");
assert!(cfg.networks.is_empty());
assert!(cfg.profiles.is_empty());
}
#[test]
fn exit_nodes_for_prioritizes_profile_then_list_then_single_node() {
fn config_toml_roundtrip_with_hidden_network() {
let mut cfg = build_initial_config();
cfg.settings.exit_node = "global".into();
cfg.settings.exit_nodes = vec!["listA".into(), "listB".into()];
cfg.profiles.get_mut("home").unwrap().exit_node = Some("profile".into());
// Per-profile override wins outright.
assert_eq!(cfg.exit_nodes_for("home"), vec!["profile".to_string()]);
// Otherwise the priority list is used verbatim.
cfg.profiles.get_mut("home").unwrap().exit_node = None;
assert_eq!(
cfg.exit_nodes_for("home"),
vec!["listA".to_string(), "listB".to_string()]
);
// Without a list, the single setting is the (one-element) fallback.
cfg.settings.exit_nodes = vec![];
assert_eq!(cfg.exit_nodes_for("home"), vec!["global".to_string()]);
}
#[test]
fn exit_nodes_for_filters_empty_and_whitespace_entries() {
let mut cfg = build_initial_config();
cfg.settings.exit_nodes = vec![
" ".into(),
"nodeA".into(),
"".into(),
" nodeB ".into(),
];
assert_eq!(
cfg.exit_nodes_for("home"),
vec!["nodeA".to_string(), "nodeB".to_string()]
);
}
#[test]
fn hhmm_to_minutes_parses_and_rejects_malformed() {
assert_eq!(hhmm_to_minutes("09:30"), Some(570));
assert_eq!(hhmm_to_minutes("00:00"), Some(0));
assert_eq!(hhmm_to_minutes("23:59"), Some(1439));
assert_eq!(hhmm_to_minutes("9:30"), Some(570)); // lenient about padding
assert_eq!(hhmm_to_minutes("24:00"), None); // hour out of range
assert_eq!(hhmm_to_minutes("12:60"), None); // minute out of range
assert_eq!(hhmm_to_minutes("0930"), None); // no colon
assert_eq!(hhmm_to_minutes(""), None);
}
#[test]
fn window_contains_handles_same_day_and_overnight() {
// Same-day window 09:0017:00 (end exclusive).
assert!(window_contains(540, 1020, 600));
assert!(!window_contains(540, 1020, 1020));
assert!(!window_contains(540, 1020, 500));
// Overnight window 22:0007:00.
assert!(window_contains(1320, 420, 1380)); // 23:00
assert!(window_contains(1320, 420, 60)); // 01:00
assert!(!window_contains(1320, 420, 720)); // 12:00
}
#[test]
fn scheduled_profile_returns_first_matching_rule() {
let mut cfg = build_initial_config();
cfg.settings.schedule = vec![
ScheduleEntry {
profile: "work".into(),
from: "09:00".into(),
to: "17:00".into(),
},
ScheduleEntry {
profile: "home".into(),
from: "09:30".into(),
to: "18:00".into(),
},
];
// 10:00 matches both — the first rule (work) wins.
assert_eq!(cfg.settings.scheduled_profile(600), Some("work".into()));
// Outside every window → no schedule applies.
assert_eq!(cfg.settings.scheduled_profile(60), None);
}
#[test]
fn effective_dns_uses_per_network_override_then_global_fallback() {
let n = NetworkDef {
ssid: "x".into(),
password: None,
dns: Some("9.9.9.9".into()),
eap: None,
identity: None,
ca_cert: None,
cfg.networks.push(NetworkDef {
ssid: "HiddenNet".into(),
password: "pw".into(),
hidden: true,
});
cfg.networks.push(NetworkDef {
ssid: "VisibleNet".into(),
password: "pw2".into(),
hidden: false,
};
assert_eq!(n.effective_dns("1.1.1.1"), "9.9.9.9");
let n2 = NetworkDef { dns: None, ..n.clone() };
assert_eq!(n2.effective_dns("1.1.1.1"), "1.1.1.1");
// An explicit empty string is a valid per-network opt-out.
let n3 = NetworkDef { dns: Some(String::new()), ..n.clone() };
assert_eq!(n3.effective_dns("1.1.1.1"), "");
});
let text = toml::to_string_pretty(&cfg).unwrap();
let back: Config = toml::from_str(&text).unwrap();
assert_eq!(back.networks.len(), 2);
let hidden = back.network("HiddenNet").unwrap();
assert!(hidden.hidden);
let visible = back.network("VisibleNet").unwrap();
assert!(!visible.hidden);
}
#[test]
fn enterprise_fields_round_trip_and_omit_when_none() {
let n = NetworkDef {
ssid: "Corp".into(),
password: Some("pw".into()),
dns: None,
eap: Some("peap".into()),
identity: Some("user@corp".into()),
ca_cert: Some("/etc/ca.pem".into()),
hidden: false,
};
let text = toml::to_string_pretty(&n).unwrap();
assert!(text.contains("eap") && text.contains("identity") && text.contains("ca_cert"));
let back: NetworkDef = toml::from_str(&text).unwrap();
assert_eq!(back.eap.as_deref(), Some("peap"));
assert_eq!(back.identity.as_deref(), Some("user@corp"));
assert_eq!(back.ca_cert.as_deref(), Some("/etc/ca.pem"));
fn config_toml_roundtrip_with_full_profile_fields() {
let mut cfg = build_initial_config();
let work = cfg.profiles.get_mut("work").unwrap();
work.tailscale = true;
work.exit_node = Some("myexit".into());
work.bootstrap = Some("BootstrapSSID".into());
work.detect_ssids = vec!["WorkWifi".into(), "CorpGuest".into()];
work.networks = vec!["WorkWifi".into()];
let text = toml::to_string_pretty(&cfg).unwrap();
let back: Config = toml::from_str(&text).unwrap();
let w = back.profile("work").unwrap();
assert!(w.tailscale);
assert_eq!(w.exit_node.as_deref(), Some("myexit"));
assert_eq!(w.bootstrap.as_deref(), Some("BootstrapSSID"));
assert_eq!(w.detect_ssids, vec!["WorkWifi", "CorpGuest"]);
assert_eq!(w.networks, vec!["WorkWifi"]);
}
let plain = NetworkDef {
eap: None,
identity: None,
ca_cert: None,
..n
};
let t2 = toml::to_string_pretty(&plain).unwrap();
assert!(!t2.contains("eap") && !t2.contains("identity") && !t2.contains("ca_cert"));
#[test]
fn config_deserialization_applies_settings_defaults_for_missing_fields() {
let toml_str = r#"
[settings]
dns = "8.8.8.8"
"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert_eq!(cfg.settings.dns, "8.8.8.8");
// Fields not specified should get their defaults.
assert_eq!(cfg.settings.nmcli_wait, 8);
assert_eq!(cfg.settings.default_profile, "away");
assert_eq!(cfg.settings.watch_interval, 12);
}
#[test]
fn network_def_hidden_defaults_to_false() {
let toml_str = r#"
[[networks]]
ssid = "MyNet"
password = "pass"
"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert!(!cfg.networks[0].hidden);
}
}

View file

@ -1,11 +1,8 @@
use std::thread;
use std::time::Duration;
use crate::backend::Backend;
use crate::config::{Config, NetworkDef};
use crate::nm;
use crate::notify::{log, notify, Urgency};
use crate::status::internet_ok;
use crate::tailscale::{self, TsHealth};
use crate::notify::Urgency;
use crate::status::Connectivity;
use crate::tailscale::TsHealth;
#[derive(Debug)]
pub enum Outcome {
@ -30,153 +27,84 @@ impl Outcome {
}
}
/// Resolve a profile's priority list to concrete network definitions.
///
/// Returns owned clones rather than borrows of `cfg` — small structs, and it
/// decouples the result's lifetime from `cfg` so callers (namely [`run`]) can
/// still mutate `cfg` (to clear a used password and persist it) while a
/// candidate from this list is being acted on.
fn resolve_candidates(cfg: &Config, p: &crate::config::Profile) -> Vec<NetworkDef> {
let mut out: Vec<NetworkDef> = Vec::new();
fn resolve_candidates<'a>(cfg: &'a Config, p: &crate::config::Profile) -> Vec<&'a NetworkDef> {
let mut out: Vec<&NetworkDef> = Vec::new();
for ssid in &p.networks {
if let Some(def) = cfg.network(ssid) {
if !out.iter().any(|d| d.ssid == def.ssid) {
out.push(def.clone());
out.push(def);
}
}
}
if p.include_all_known {
for def in &cfg.networks {
if !out.iter().any(|d| d.ssid == def.ssid) {
out.push(def.clone());
out.push(def);
}
}
}
out
}
/// A network was just connected to using a local password, and NetworkManager
/// now durably holds that secret — either in a freshly created connection
/// profile (`device wifi connect --ask`) or an existing one whose PSK we just
/// supplied via `--ask connection up`. Either way breadcrumbs no longer needs
/// its own plaintext copy: clear it and persist immediately so it doesn't sit
/// on disk any longer than necessary. A no-op (no save) if the network has no
/// local password to begin with.
fn clear_password_if_used(cfg: &mut Config, ssid: &str) {
let Some(def) = cfg.networks.iter_mut().find(|n| n.ssid == ssid) else {
return;
};
if def.password.is_none() {
return;
}
def.password = None;
if let Err(e) = cfg.save() {
log(&format!(
"failed to persist cleared password for {ssid}: {e}"
));
/// Try to connect + confirm it actually carries traffic.
/// Returns Ok(()) on success, Err(reason) on failure.
fn connect_and_verify(
be: &dyn Backend,
iface: &str,
def: &NetworkDef,
cfg: &Config,
) -> Result<(), String> {
be.connect(iface, def, cfg.settings.nmcli_wait, &cfg.settings.dns)?;
if !be.device_connected(iface) {
return Err("device not connected after nmcli success".into());
}
Ok(())
}
/// Opt-in learning (`profiles.<name>.learn = true`): remember the SSIDs a
/// profile successfully connects to so `breadcrumbs detect` improves without
/// hand-editing. Bounded to keep the list sane; never touches an existing
/// marker.
fn learn_ssid(cfg: &mut Config, profile: &str, ssid: &str) {
let Some(p) = cfg.profiles.get_mut(profile) else {
return;
};
if !p.learn || p.detect_ssids.len() >= 8 || p.detect_ssids.iter().any(|s| s == ssid) {
return;
/// Describe post-association connectivity as an optional caveat note.
fn connectivity_note(be: &dyn Backend, cfg: &Config) -> Option<String> {
match be.connectivity(cfg) {
Connectivity::Online => None,
Connectivity::Portal(Some(url)) => Some(format!("captive portal — sign in at {url}")),
Connectivity::Portal(None) => Some("captive portal — sign in required".into()),
Connectivity::Offline => Some("associated but no internet yet".into()),
}
p.detect_ssids.push(ssid.to_string());
if let Err(e) = cfg.save() {
log(&format!("failed to persist learned SSID {ssid} for {profile}: {e}"));
}
}
/// Try to connect + confirm the device actually landed on the *requested*
/// SSID. Returns Ok(()) on success, Err(reason) on failure.
fn connect_and_verify(iface: &str, def: &NetworkDef, cfg: &Config) -> Result<(), String> {
nm::connect_verbose(iface, def, cfg.settings.connect_wait, def.effective_dns(&cfg.settings.dns))?;
// Confirm the SSID, not just "device connected": NM autoconnect can win
// a race and leave the device on a different network, and the wifi list
// can lag activation by a moment — so poll briefly before giving up.
for _ in 0..8 {
match nm::active_ssid(iface) {
// Explicitly on the requested network — success.
Some(active) if active == def.ssid => return Ok(()),
// Associated with a *different* network — the failure this
// check exists to catch.
Some(_) => break,
// Scan list stale right after activation — keep polling while
// the device is at least connected.
None => {
if !nm::device_connected(iface) {
break;
}
}
}
thread::sleep(Duration::from_millis(250));
}
Err(format!("not associated with '{}' after connect", def.ssid))
}
/// Run the connection state machine for `profile_name`, with desktop
/// notifications enabled. See [`run_quiet`] for the daemon-facing variant.
pub fn run(cfg: &mut Config, profile_name: &str) -> Outcome {
run_inner(cfg, profile_name, true)
}
/// Same state machine, but suppresses desktop notifications. Used by the
/// watch loop, which does its own transition-gated notifications — without
/// this, a persistent failure (e.g. a stopped Tailscale daemon) would
/// re-notify on every recovery retry instead of once per state change.
pub fn run_quiet(cfg: &mut Config, profile_name: &str) -> Outcome {
run_inner(cfg, profile_name, false)
}
/// Run the connection state machine for `profile_name`.
///
/// Takes `cfg` mutably: a successful connect that used a local password
/// clears that network's `password` field and persists the config
/// immediately (see [`clear_password_if_used`]) — this is the only way that
/// clearing happens for the `init` / `profile set --apply` / `detect --apply`
/// commands and the watch loop, all of which route through here.
fn run_inner(cfg: &mut Config, profile_name: &str, notify_user: bool) -> Outcome {
pub fn run(be: &dyn Backend, cfg: &Config, profile_name: &str) -> Outcome {
let profile = match cfg.profile(profile_name) {
Some(p) => p.clone(),
None => {
if notify_user {
notify(
"breadcrumbs: unknown profile",
&format!("'{profile_name}' is not defined in breadcrumbs.toml"),
Urgency::Critical,
);
}
be.notify(
"breadcrumbs: unknown profile",
&format!("'{profile_name}' is not defined in breadcrumbs.toml"),
Urgency::Critical,
);
return Outcome::UnknownProfile(profile_name.to_string());
}
};
let iface = match nm::wifi_interface_preferred(cfg.settings.interface.as_deref()) {
let iface = match be.wifi_interface() {
Some(i) => i,
None => {
if notify_user {
notify(
"breadcrumbs: no Wi-Fi adapter",
"Hardware issue — Wi-Fi device not found. Manual check needed.",
Urgency::Critical,
);
}
be.notify(
"breadcrumbs: no Wi-Fi adapter",
"Hardware issue — Wi-Fi device not found. Manual check needed.",
Urgency::Critical,
);
return Outcome::NoInterface;
}
};
nm::radio_on();
be.radio_on();
let exit_nodes = cfg.exit_nodes_for(profile_name);
let exit_node = exit_nodes.first().cloned().unwrap_or_default();
let exit_node = profile
.exit_node
.clone()
.unwrap_or_else(|| cfg.settings.exit_node.clone());
let candidates = resolve_candidates(cfg, &profile);
log(&format!(
be.log(&format!(
"flow start: profile={profile_name} iface={iface} tailscale={} candidates=[{}]",
profile.tailscale,
candidates
@ -191,116 +119,89 @@ fn run_inner(cfg: &mut Config, profile_name: &str, notify_user: bool) -> Outcome
if let Some(bs) = &profile.bootstrap {
scan_targets.push(bs.clone());
}
nm::rescan(&iface, &scan_targets);
let visible = nm::visible_ssids(&iface);
be.rescan(&iface, &scan_targets);
let visible = be.visible_ssids(&iface);
// ---- Tailscale-gated profiles (e.g. school) -------------------------
let mut on_bootstrap = false;
if profile.tailscale {
if let Some(bs_ssid) = profile.bootstrap.clone() {
// Owned clone (not a borrow of `cfg`) so we're free to mutate
// `cfg` below on a successful connect.
match cfg.network(&bs_ssid).cloned() {
match cfg.network(&bs_ssid) {
Some(bdef) => {
if visible.contains(&bdef.ssid) || bdef.hidden {
match connect_and_verify(&iface, &bdef, cfg) {
match connect_and_verify(be, &iface, bdef, cfg) {
Ok(()) => {
on_bootstrap = true;
log(&format!("bootstrap connected: {}", bdef.ssid));
clear_password_if_used(cfg, &bdef.ssid);
be.log(&format!("bootstrap connected: {}", bdef.ssid));
}
Err(e) => {
log(&format!("bootstrap connect failed: {}{e}", bdef.ssid))
be.log(&format!("bootstrap connect failed: {}{e}", bdef.ssid))
}
}
} else {
log(&format!("bootstrap not in range: {}", bdef.ssid));
be.log(&format!("bootstrap not in range: {}", bdef.ssid));
}
}
None => log(&format!(
None => be.log(&format!(
"bootstrap SSID '{bs_ssid}' has no credentials in config"
)),
}
}
let ts = tailscale::ensure_exit_node(&exit_nodes);
let ts = be.ensure_exit_node(&exit_node);
if !ts.is_ok() {
let ssid = nm::active_ssid(&iface).or_else(|| profile.bootstrap.clone());
if notify_user {
notify(
"Tailscale Error",
&format!(
"{} — staying on {}",
ts.describe(),
ssid.clone().unwrap_or_else(|| "Wi-Fi".into())
),
Urgency::Critical,
);
}
let ssid = be.active_ssid(&iface).or_else(|| profile.bootstrap.clone());
be.notify(
"Tailscale Error",
&format!(
"{} — staying on {}",
ts.describe(),
ssid.clone().unwrap_or_else(|| "Wi-Fi".into())
),
Urgency::Critical,
);
return Outcome::TailscaleError { ssid, health: ts };
}
log(&format!("tailscale healthy via exit node {exit_node}"));
be.log(&format!("tailscale healthy via exit node {exit_node}"));
// Refresh visibility before moving to the target network.
nm::rescan(&iface, &scan_targets);
be.rescan(&iface, &scan_targets);
}
// Signals are re-read after the Tailscale gate so pass 1 can prefer the
// strongest AP among a profile's visible networks.
let visible_sig = nm::visible_signals(&iface);
let visible = be.visible_ssids(&iface);
// ---- Connect to the priority list ----------------------------------
// Pass 1: visible networks, strongest signal first (priority order is
// the stable tiebreaker for equal signals).
let mut visible_candidates: Vec<&NetworkDef> = candidates
.iter()
.filter(|d| visible_sig.contains_key(&d.ssid))
.collect();
visible_candidates.sort_by(|a, b| {
visible_sig
.get(&b.ssid)
.cmp(&visible_sig.get(&a.ssid))
});
// Pass 1: visible networks in priority order.
let mut any_attempted = false;
for def in &visible_candidates {
any_attempted = true;
match connect_and_verify(&iface, def, cfg) {
Ok(()) => {
clear_password_if_used(cfg, &def.ssid);
learn_ssid(cfg, profile_name, &def.ssid);
let note = if internet_ok(cfg) {
None
} else {
Some("associated but no internet yet".to_string())
};
finish_connected(&def.ssid, profile_name, &note, notify_user);
return Outcome::Connected {
ssid: def.ssid.clone(),
note,
};
for def in &candidates {
if visible.contains(&def.ssid) {
any_attempted = true;
match connect_and_verify(be, &iface, def, cfg) {
Ok(()) => {
let note = connectivity_note(be, cfg);
finish_connected(be, &def.ssid, profile_name, &note);
return Outcome::Connected {
ssid: def.ssid.clone(),
note,
};
}
Err(e) => be.log(&format!("connect failed (visible): {}{e}", def.ssid)),
}
Err(e) => log(&format!("connect failed (visible): {}{e}", def.ssid)),
}
}
// Pass 2: hidden networks we couldn't see in the scan.
for def in &candidates {
if def.hidden && !visible.contains(&def.ssid) {
any_attempted = true;
match connect_and_verify(&iface, def, cfg) {
match connect_and_verify(be, &iface, def, cfg) {
Ok(()) => {
clear_password_if_used(cfg, &def.ssid);
learn_ssid(cfg, profile_name, &def.ssid);
let note = if internet_ok(cfg) {
None
} else {
Some("associated but no internet yet".to_string())
};
finish_connected(&def.ssid, profile_name, &note, notify_user);
let note = connectivity_note(be, cfg);
finish_connected(be, &def.ssid, profile_name, &note);
return Outcome::Connected {
ssid: def.ssid.clone(),
note,
};
}
Err(e) => log(&format!("connect failed (hidden): {}{e}", def.ssid)),
Err(e) => be.log(&format!("connect failed (hidden): {}{e}", def.ssid)),
}
}
}
@ -313,21 +214,12 @@ fn run_inner(cfg: &mut Config, profile_name: &str, notify_user: bool) -> Outcome
.bootstrap
.clone()
.unwrap_or_else(|| "bootstrap".into());
if !nm::device_connected(&iface) {
// Owned clone (not a borrow of `cfg`) so a successful reconnect
// is free to mutate `cfg` to clear the used password.
if let Some(bdef) = profile
.bootstrap
.as_deref()
.and_then(|s| cfg.network(s).cloned())
{
match connect_and_verify(&iface, &bdef, cfg) {
Ok(()) => {
log(&format!("bootstrap reconnected: {}", bdef.ssid));
clear_password_if_used(cfg, &bdef.ssid);
}
if !be.device_connected(&iface) {
if let Some(bdef) = profile.bootstrap.as_deref().and_then(|s| cfg.network(s)) {
match connect_and_verify(be, &iface, bdef, cfg) {
Ok(()) => be.log(&format!("bootstrap reconnected: {}", bdef.ssid)),
Err(e) => {
log(&format!("bootstrap reconnect failed: {}{e}", bdef.ssid));
be.log(&format!("bootstrap reconnect failed: {}{e}", bdef.ssid));
on_bootstrap = false;
}
}
@ -339,10 +231,8 @@ fn run_inner(cfg: &mut Config, profile_name: &str, notify_user: bool) -> Outcome
} else {
format!("target network not in range — staying on {bs_ssid} (Tailscale OK)")
};
if notify_user {
notify("breadcrumbs: using bootstrap", &reason, Urgency::Normal);
}
log(&format!("flow end: on bootstrap {bs_ssid}; {reason}"));
be.notify("breadcrumbs: using bootstrap", &reason, Urgency::Normal);
be.log(&format!("flow end: on bootstrap {bs_ssid}; {reason}"));
return Outcome::Connected {
ssid: bs_ssid,
note: Some(reason),
@ -355,41 +245,34 @@ fn run_inner(cfg: &mut Config, profile_name: &str, notify_user: bool) -> Outcome
.map(|c| c.ssid.as_str())
.collect::<Vec<_>>()
.join(", ");
let msg = if candidates.is_empty() {
format!("profile '{profile_name}' has no networks configured")
} else {
format!("profile '{profile_name}': none of [{names}] are in range")
};
if notify_user {
notify("breadcrumbs: no known networks", &msg, Urgency::Critical);
}
log(&format!(
be.notify(
"breadcrumbs: no known networks",
&format!("profile '{profile_name}': none of [{names}] are in range"),
Urgency::Critical,
);
be.log(&format!(
"flow end: no networks connected (profile={profile_name})"
));
Outcome::NoNetworks
}
fn finish_connected(ssid: &str, profile: &str, note: &Option<String>, notify_user: bool) {
fn finish_connected(be: &dyn Backend, ssid: &str, profile: &str, note: &Option<String>) {
match note {
None => {
if notify_user {
notify(
"breadcrumbs: connected",
&format!("{ssid} ({profile})"),
Urgency::Low,
);
}
log(&format!("flow end: connected {ssid} (profile={profile})"));
be.notify(
"breadcrumbs: connected",
&format!("{ssid} ({profile})"),
Urgency::Low,
);
be.log(&format!("flow end: connected {ssid} (profile={profile})"));
}
Some(n) => {
if notify_user {
notify(
"breadcrumbs: connected (degraded)",
&format!("{ssid} ({profile}) — {n}"),
Urgency::Normal,
);
}
log(&format!(
be.notify(
"breadcrumbs: connected (degraded)",
&format!("{ssid} ({profile}) — {n}"),
Urgency::Normal,
);
be.log(&format!(
"flow end: connected {ssid} (profile={profile}) note={n}"
));
}
@ -400,16 +283,13 @@ fn finish_connected(ssid: &str, profile: &str, note: &Option<String>, notify_use
mod tests {
use super::*;
use crate::config::{Profile, Settings};
use crate::tailscale::TsHealth;
use std::collections::BTreeMap;
fn net(ssid: &str) -> NetworkDef {
NetworkDef {
ssid: ssid.into(),
password: Some("x".into()),
dns: None,
eap: None,
identity: None,
ca_cert: None,
password: "x".into(),
hidden: false,
}
}
@ -427,6 +307,341 @@ mod tests {
}
}
// --- a scriptable in-memory Backend for testing the state machine ---
use std::cell::RefCell;
use std::collections::HashSet;
struct Fake {
iface: Option<String>,
visible: HashSet<String>,
connectable: HashSet<String>,
connected: RefCell<Option<String>>,
ts: TsHealth,
conn: Connectivity,
notes: RefCell<Vec<String>>,
}
impl Fake {
fn new() -> Fake {
Fake {
iface: Some("wlan0".into()),
visible: HashSet::new(),
connectable: HashSet::new(),
connected: RefCell::new(None),
ts: TsHealth::Ok,
conn: Connectivity::Online,
notes: RefCell::new(Vec::new()),
}
}
fn set(ssids: &[&str]) -> HashSet<String> {
ssids.iter().map(|s| s.to_string()).collect()
}
fn visible(mut self, ssids: &[&str]) -> Self {
self.visible = Fake::set(ssids);
self
}
fn connectable(mut self, ssids: &[&str]) -> Self {
self.connectable = Fake::set(ssids);
self
}
fn ts(mut self, h: TsHealth) -> Self {
self.ts = h;
self
}
fn conn(mut self, c: Connectivity) -> Self {
self.conn = c;
self
}
fn no_iface(mut self) -> Self {
self.iface = None;
self
}
fn notified(&self, needle: &str) -> bool {
self.notes.borrow().iter().any(|n| n.contains(needle))
}
}
impl Backend for Fake {
fn wifi_interface(&self) -> Option<String> {
self.iface.clone()
}
fn radio_on(&self) {}
fn rescan(&self, _: &str, _: &[String]) {}
fn visible_ssids(&self, _: &str) -> HashSet<String> {
self.visible.clone()
}
fn active_ssid(&self, _: &str) -> Option<String> {
self.connected.borrow().clone()
}
fn ipv4(&self, _: &str) -> Option<String> {
self.connected.borrow().as_ref().map(|_| "10.0.0.2".into())
}
fn device_connected(&self, _: &str) -> bool {
self.connected.borrow().is_some()
}
fn connect(&self, _: &str, net: &NetworkDef, _: u32, _: &str) -> Result<(), String> {
if self.connectable.contains(&net.ssid) {
*self.connected.borrow_mut() = Some(net.ssid.clone());
Ok(())
} else {
// A failed association drops the current link, like nmcli.
*self.connected.borrow_mut() = None;
Err(format!("cannot connect to {}", net.ssid))
}
}
fn tailscale_installed(&self) -> bool {
true
}
fn ensure_exit_node(&self, _: &str) -> TsHealth {
self.ts.clone()
}
fn tailscale_check(&self, _: &str) -> TsHealth {
self.ts.clone()
}
fn connectivity(&self, _: &Config) -> Connectivity {
self.conn.clone()
}
fn notify(&self, summary: &str, _: &str, _: Urgency) {
self.notes.borrow_mut().push(summary.to_string());
}
fn log(&self, _: &str) {}
}
fn with_profile(name: &str, p: Profile) -> Config {
let mut c = cfg();
c.profiles.insert(name.to_string(), p);
c
}
fn connected(o: &Outcome) -> (&str, &Option<String>) {
match o {
Outcome::Connected { ssid, note } => (ssid.as_str(), note),
other => panic!("expected Connected, got {other:?}"),
}
}
// --- flow::run state machine ---
#[test]
fn run_unknown_profile_returns_unknown_and_notifies() {
let be = Fake::new();
let o = run(&be, &cfg(), "ghost");
assert!(matches!(o, Outcome::UnknownProfile(p) if p == "ghost"));
assert!(be.notified("unknown profile"));
}
#[test]
fn run_no_interface_returns_no_interface() {
let be = Fake::new().no_iface();
let c = with_profile(
"home",
Profile {
networks: vec!["HomeWifi".into()],
..Default::default()
},
);
assert!(matches!(run(&be, &c, "home"), Outcome::NoInterface));
}
#[test]
fn run_connects_to_visible_priority_network() {
let c = with_profile(
"home",
Profile {
networks: vec!["HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new()
.visible(&["HomeWifi", "CafeWifi"])
.connectable(&["HomeWifi"]);
let o = run(&be, &c, "home");
let (ssid, note) = connected(&o);
assert_eq!(ssid, "HomeWifi");
assert!(note.is_none());
}
#[test]
fn run_follows_priority_order() {
let c = with_profile(
"home",
Profile {
networks: vec!["WorkNet".into(), "HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new()
.visible(&["WorkNet", "HomeWifi"])
.connectable(&["WorkNet", "HomeWifi"]);
assert_eq!(connected(&run(&be, &c, "home")).0, "WorkNet");
}
#[test]
fn run_skips_failing_network_and_tries_next() {
let c = with_profile(
"home",
Profile {
networks: vec!["WorkNet".into(), "HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new()
.visible(&["WorkNet", "HomeWifi"])
.connectable(&["HomeWifi"]); // WorkNet fails
assert_eq!(connected(&run(&be, &c, "home")).0, "HomeWifi");
}
#[test]
fn run_no_networks_in_range_returns_no_networks() {
let c = with_profile(
"home",
Profile {
networks: vec!["HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new().visible(&["SomeoneElse"]);
assert!(matches!(run(&be, &c, "home"), Outcome::NoNetworks));
assert!(be.notified("no known networks"));
}
#[test]
fn run_captive_portal_surfaces_as_note() {
let c = with_profile(
"home",
Profile {
networks: vec!["HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new()
.visible(&["HomeWifi"])
.connectable(&["HomeWifi"])
.conn(Connectivity::Portal(Some("http://login.test".into())));
let o = run(&be, &c, "home");
let (_, note) = connected(&o);
assert!(note.as_ref().unwrap().contains("captive portal"));
assert!(note.as_ref().unwrap().contains("http://login.test"));
}
#[test]
fn run_offline_after_associate_is_degraded_note() {
let c = with_profile(
"home",
Profile {
networks: vec!["HomeWifi".into()],
..Default::default()
},
);
let be = Fake::new()
.visible(&["HomeWifi"])
.connectable(&["HomeWifi"])
.conn(Connectivity::Offline);
let o = run(&be, &c, "home");
let (_, note) = connected(&o);
assert!(note.as_ref().unwrap().contains("no internet"));
}
#[test]
fn run_tailscale_gated_moves_to_target_when_healthy() {
let c = with_profile(
"work",
Profile {
bootstrap: Some("CafeWifi".into()),
networks: vec!["WorkNet".into()],
tailscale: true,
..Default::default()
},
);
let be = Fake::new()
.visible(&["CafeWifi", "WorkNet"])
.connectable(&["CafeWifi", "WorkNet"])
.ts(TsHealth::Ok);
assert_eq!(connected(&run(&be, &c, "work")).0, "WorkNet");
}
#[test]
fn run_tailscale_unhealthy_stays_on_bootstrap() {
let c = with_profile(
"work",
Profile {
bootstrap: Some("CafeWifi".into()),
networks: vec!["WorkNet".into()],
tailscale: true,
..Default::default()
},
);
let be = Fake::new()
.visible(&["CafeWifi", "WorkNet"])
.connectable(&["CafeWifi", "WorkNet"])
.ts(TsHealth::NeedsLogin);
match run(&be, &c, "work") {
Outcome::TailscaleError { ssid, health } => {
assert_eq!(ssid.as_deref(), Some("CafeWifi"));
assert_eq!(health, TsHealth::NeedsLogin);
}
other => panic!("expected TailscaleError, got {other:?}"),
}
assert!(be.notified("Tailscale"));
}
#[test]
fn run_tailscale_ok_but_target_out_of_range_keeps_bootstrap() {
let c = with_profile(
"work",
Profile {
bootstrap: Some("CafeWifi".into()),
networks: vec!["WorkNet".into()],
tailscale: true,
..Default::default()
},
);
let be = Fake::new()
.visible(&["CafeWifi"]) // WorkNet not in range
.connectable(&["CafeWifi"])
.ts(TsHealth::Ok);
let o = run(&be, &c, "work");
let (ssid, note) = connected(&o);
assert_eq!(ssid, "CafeWifi");
assert!(note.as_ref().unwrap().contains("not in range"));
}
// --- Outcome::ok ---
#[test]
fn outcome_ok_true_for_connected_with_and_without_note() {
assert!(Outcome::Connected {
ssid: "x".into(),
note: None
}
.ok());
assert!(Outcome::Connected {
ssid: "x".into(),
note: Some("associated but no internet yet".into()),
}
.ok());
}
#[test]
fn outcome_ok_false_for_all_error_variants() {
assert!(!Outcome::NoInterface.ok());
assert!(!Outcome::NoNetworks.ok());
assert!(!Outcome::UnknownProfile("p".into()).ok());
assert!(!Outcome::TailscaleError {
ssid: None,
health: TsHealth::NeedsLogin,
}
.ok());
assert!(!Outcome::TailscaleError {
ssid: Some("boot".into()),
health: TsHealth::ExitNodeOffline,
}
.ok());
}
// --- resolve_candidates ---
#[test]
fn candidates_follow_priority_order() {
let c = cfg();
@ -434,8 +649,10 @@ mod tests {
networks: vec!["FallbackNet".into(), "HomeWifi".into()],
..Default::default()
};
let candidates = resolve_candidates(&c, &p);
let got: Vec<&str> = candidates.iter().map(|n| n.ssid.as_str()).collect();
let got: Vec<&str> = resolve_candidates(&c, &p)
.iter()
.map(|n| n.ssid.as_str())
.collect();
assert_eq!(got, vec!["FallbackNet", "HomeWifi"]);
}
@ -447,8 +664,10 @@ mod tests {
include_all_known: true,
..Default::default()
};
let candidates = resolve_candidates(&c, &p);
let got: Vec<&str> = candidates.iter().map(|n| n.ssid.as_str()).collect();
let got: Vec<&str> = resolve_candidates(&c, &p)
.iter()
.map(|n| n.ssid.as_str())
.collect();
assert_eq!(got[0], "HomeWifi");
assert_eq!(got.len(), 4);
assert!(got.contains(&"WorkNet"));
@ -463,71 +682,56 @@ mod tests {
networks: vec!["Ghost".into(), "WorkNet".into()],
..Default::default()
};
let candidates = resolve_candidates(&c, &p);
let got: Vec<&str> = candidates.iter().map(|n| n.ssid.as_str()).collect();
let got: Vec<&str> = resolve_candidates(&c, &p)
.iter()
.map(|n| n.ssid.as_str())
.collect();
assert_eq!(got, vec!["WorkNet"]);
}
#[test]
fn empty_profile_network_list_yields_no_candidates() {
fn candidates_empty_when_profile_has_no_networks() {
let c = cfg();
let p = Profile::default();
assert!(resolve_candidates(&c, &p).is_empty());
}
#[test]
fn duplicate_ssids_within_profile_list_are_deduped() {
fn candidates_include_all_known_only_no_explicit_networks() {
let c = cfg();
let p = Profile {
include_all_known: true,
..Default::default()
};
let got: Vec<&str> = resolve_candidates(&c, &p)
.iter()
.map(|n| n.ssid.as_str())
.collect();
assert_eq!(got.len(), 4);
assert_eq!(got[0], "HomeWifi");
}
#[test]
fn candidates_deduplicates_repeated_ssid_in_explicit_list() {
let c = cfg();
let p = Profile {
networks: vec!["HomeWifi".into(), "HomeWifi".into(), "WorkNet".into()],
..Default::default()
};
let candidates = resolve_candidates(&c, &p);
let got: Vec<&str> = candidates.iter().map(|n| n.ssid.as_str()).collect();
let got: Vec<&str> = resolve_candidates(&c, &p)
.iter()
.map(|n| n.ssid.as_str())
.collect();
assert_eq!(got, vec!["HomeWifi", "WorkNet"]);
}
#[test]
fn include_all_known_with_full_priority_list_appends_nothing_new() {
fn candidates_all_unknown_ssids_returns_empty() {
let c = cfg();
let p = Profile {
networks: vec![
"HomeWifi".into(),
"WorkNet".into(),
"CafeWifi".into(),
"FallbackNet".into(),
],
include_all_known: true,
networks: vec!["Ghost1".into(), "Ghost2".into()],
..Default::default()
};
let got = resolve_candidates(&c, &p);
assert_eq!(got.len(), 4);
}
#[test]
fn include_all_known_on_empty_priority_list_returns_all_networks() {
let c = cfg();
let p = Profile {
include_all_known: true,
..Default::default()
};
assert_eq!(resolve_candidates(&c, &p).len(), 4);
}
#[test]
fn outcome_ok_is_true_only_for_connected() {
assert!(Outcome::Connected {
ssid: "x".into(),
note: None
}
.ok());
assert!(!Outcome::NoInterface.ok());
assert!(!Outcome::NoNetworks.ok());
assert!(!Outcome::UnknownProfile("ghost".into()).ok());
assert!(!Outcome::TailscaleError {
ssid: None,
health: crate::tailscale::TsHealth::NotInstalled
}
.ok());
assert!(resolve_candidates(&c, &p).is_empty());
}
}

View file

@ -1,20 +0,0 @@
//! breadcrumbs library crate.
//!
//! All actual logic lives here; `src/main.rs` is a thin binary shim that
//! parses no arguments itself — it just calls [`app::run`]. Splitting things
//! this way means integration tests can link against `breadcrumbs` as an
//! ordinary library crate and drive the real state machine (`flow::run`,
//! `watch::classify`, …) in-process, instead of only being able to spawn the
//! compiled binary.
pub mod app;
pub mod bread_events;
pub mod config;
pub mod flow;
pub mod nm;
pub mod notify;
pub mod state;
pub mod status;
pub mod tailscale;
pub mod util;
pub mod watch;

View file

@ -1,7 +1,909 @@
//! Thin binary entry point. All argument parsing and command logic lives in
//! the library crate (`breadcrumbs::app`) so it can also be exercised
//! in-process by the integration tests under `tests/`.
mod backend;
mod config;
mod flow;
mod nm;
mod notify;
mod state;
mod status;
mod tailscale;
mod util;
mod watch;
use std::io::{BufRead, Write};
use std::process::Command;
use std::time::Duration;
use clap::{Parser, Subcommand};
use backend::Backend;
use config::{Config, NetworkDef};
use state::State;
use util::{command_exists, home_dir, run};
const C_RESET: &str = "\x1b[0m";
const C_BOLD: &str = "\x1b[1m";
const C_GREEN: &str = "\x1b[32m";
const C_RED: &str = "\x1b[31m";
const C_YELLOW: &str = "\x1b[33m";
const C_DIM: &str = "\x1b[2m";
#[derive(Parser)]
#[command(
name = "breadcrumbs",
version,
about = "Profile-aware Wi-Fi state machine with Tailscale handling",
disable_help_subcommand = true
)]
struct Cli {
/// Override the active profile for this run only (does not persist)
#[arg(long, short, global = true)]
profile: Option<String>,
#[command(subcommand)]
cmd: Option<Cmd>,
}
#[derive(Subcommand)]
enum Cmd {
/// Show current Wi-Fi / profile / Tailscale status (default)
Status {
/// Emit machine-readable JSON instead of the human summary
#[arg(long)]
json: bool,
},
/// Run the full connect sequence for the active profile
#[command(visible_aliases = ["up", "connect", "i"])]
Init,
/// Run as a daemon: watch for drops and auto-recover
Watch {
/// Skip the connect attempt on startup
#[arg(long)]
no_initial: bool,
},
/// Get / set / list location profiles (the state machine)
Profile {
#[command(subcommand)]
action: Option<ProfileCmd>,
},
/// Guess the profile from visible networks
Detect {
/// Set + apply the detected profile
#[arg(long)]
apply: bool,
},
/// Add or update a saved network
Add {
ssid: String,
/// Password (prompted if omitted)
password: Option<String>,
/// Network is hidden (does not broadcast its SSID)
#[arg(long)]
hidden: bool,
/// Attach this SSID to a profile's priority list
#[arg(long)]
to: Option<String>,
/// Position in the profile list (0 = highest priority)
#[arg(long)]
at: Option<usize>,
},
/// Remove a saved network (config + NetworkManager)
Forget { ssid: String },
/// Scan, pick, connect and save a network interactively
Scan {
/// Attach the saved network to this profile
#[arg(long)]
to: Option<String>,
},
/// List configured networks and profiles
List {
#[arg(long)]
show_passwords: bool,
},
/// Connect to a specific saved network by SSID, bypassing profile routing
Join { ssid: String },
/// List saved network SSIDs
Networks {
/// Emit a JSON array instead of one-per-line
#[arg(long)]
json: bool,
},
/// Scan for visible networks and list them with signal strength
ScanList {
/// Emit JSON instead of human-readable output
#[arg(long)]
json: bool,
},
/// Open the config file in $EDITOR
Edit,
/// Quick connectivity / Tailscale diagnostics
Doctor {
/// Run the full diag.sh report from the config directory
#[arg(long)]
full: bool,
},
/// Print the breadcrumbs config directory
Cd {
#[arg(long)]
shell: bool,
},
/// Install + enable the systemd user watcher service
InstallService {
/// Install the unit but do not enable/start it
#[arg(long)]
no_enable: bool,
},
}
#[derive(Subcommand)]
enum ProfileCmd {
/// Print the active profile
Get,
/// Set the active profile (and apply it unless --no-apply)
Set {
name: String,
#[arg(long)]
no_apply: bool,
},
/// List available profiles
List,
/// Create a new (empty) profile
Add {
name: String,
/// SSID whose presence marks this location (repeatable, for `detect`)
#[arg(long = "detect")]
detect: Vec<String>,
},
/// Delete a profile (core profiles home/work/away cannot be removed)
Remove { name: String },
}
fn main() {
std::process::exit(breadcrumbs::app::run());
let cli = Cli::parse();
let code = match real_main(cli) {
Ok(c) => c,
Err(e) => {
eprintln!("{C_RED}error:{C_RESET} {e}");
1
}
};
std::process::exit(code);
}
fn active_profile(cfg: &Config, override_p: &Option<String>) -> String {
if let Some(p) = override_p {
return p.clone();
}
State::load(&cfg.settings.default_profile).profile
}
fn real_main(cli: Cli) -> Result<i32, String> {
let cmd = cli.cmd.unwrap_or(Cmd::Status { json: false });
// `cd` and `install-service` don't need a parsed config first.
if let Cmd::Cd { shell } = &cmd {
return cmd_cd(*shell);
}
let mut cfg = Config::load()?;
let be = backend::System;
match cmd {
Cmd::Status { json } => cmd_status(&be, &cfg, &cli.profile, json),
Cmd::Init => {
let p = active_profile(&cfg, &cli.profile);
let outcome = flow::run(&be, &cfg, &p);
print_outcome(&p, &outcome);
Ok(if outcome.ok() { 0 } else { 1 })
}
Cmd::Watch { no_initial } => Ok(watch::run(cfg, !no_initial)),
Cmd::Profile { action } => cmd_profile(&be, &mut cfg, action),
Cmd::Detect { apply } => cmd_detect(&be, &cfg, apply),
Cmd::Add {
ssid,
password,
hidden,
to,
at,
} => cmd_add(&mut cfg, ssid, password, hidden, to, at),
Cmd::Forget { ssid } => cmd_forget(&mut cfg, &ssid),
Cmd::Join { ssid } => cmd_join(&be, &cfg, &ssid),
Cmd::Networks { json } => cmd_networks(&cfg, json),
Cmd::ScanList { json } => cmd_scan_list(&cfg, json),
Cmd::Scan { to } => cmd_scan(&mut cfg, to),
Cmd::List { show_passwords } => cmd_list(&cfg, show_passwords),
Cmd::Edit => cmd_edit(),
Cmd::Doctor { full } => cmd_doctor(&be, &cfg, &cli.profile, full),
Cmd::InstallService { no_enable } => cmd_install_service(!no_enable),
Cmd::Cd { .. } => unreachable!(),
}
}
fn print_outcome(profile: &str, o: &flow::Outcome) {
match o {
flow::Outcome::Connected { ssid, note } => {
print!("{C_GREEN}connected{C_RESET} {C_BOLD}{ssid}{C_RESET} ({profile})");
match note {
Some(n) => println!(" {C_YELLOW}{n}{C_RESET}"),
None => println!(),
}
}
flow::Outcome::TailscaleError { ssid, health } => {
println!(
"{C_RED}tailscale error{C_RESET}: {} {C_DIM}(on {}){C_RESET}",
health.describe(),
ssid.clone().unwrap_or_else(|| "".into())
);
}
flow::Outcome::NoInterface => {
println!("{C_RED}no Wi-Fi adapter{C_RESET} — hardware issue")
}
flow::Outcome::NoNetworks => {
println!("{C_RED}no known networks in range{C_RESET} (profile {profile})")
}
flow::Outcome::UnknownProfile(p) => {
println!("{C_RED}unknown profile{C_RESET}: {p}")
}
}
}
fn status_healthy(s: &status::Status) -> bool {
s.internet
&& s.iface.is_some()
&& (!s.tailscale_required || s.tailscale.as_ref().map(|h| h.is_ok()).unwrap_or(false))
}
fn cmd_status(
be: &dyn Backend,
cfg: &Config,
override_p: &Option<String>,
json: bool,
) -> Result<i32, String> {
let p = active_profile(cfg, override_p);
let s = status::gather(be, cfg, &p);
let healthy = status_healthy(&s);
if json {
let v = serde_json::json!({
"profile": p,
"adapter": s.iface,
"ssid": s.ssid,
"ip": s.ip,
"internet": s.internet,
"captive_portal": s.portal,
"tailscale": {
"required": s.tailscale_required,
"installed": s.tailscale.is_some(),
"ok": s.tailscale.as_ref().map(|h| h.is_ok()),
"health": s.tailscale.as_ref().map(|h| h.describe()),
"exit_node": s.exit_node,
},
"healthy": healthy,
});
println!(
"{}",
serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".into())
);
return Ok(if healthy { 0 } else { 1 });
}
let dot = |ok: bool| {
if ok {
format!("{C_GREEN}{C_RESET}")
} else {
format!("{C_RED}{C_RESET}")
}
};
println!("{C_BOLD}breadcrumbs{C_RESET}");
println!(" profile {C_BOLD}{p}{C_RESET}");
println!(
" adapter {}",
s.iface
.clone()
.unwrap_or_else(|| format!("{C_RED}none{C_RESET}"))
);
println!(
" ssid {}",
s.ssid
.clone()
.unwrap_or_else(|| format!("{C_DIM}{C_RESET}"))
);
println!(
" ip {}",
s.ip.clone().unwrap_or_else(|| format!("{C_DIM}{C_RESET}"))
);
println!(
" internet {} {}",
dot(s.internet),
if s.internet { "ok" } else { "down" }
);
if let Some(portal) = &s.portal {
let detail = if portal.is_empty() {
"sign-in required".to_string()
} else {
portal.clone()
};
println!(" portal {C_YELLOW}captive portal{C_RESET} {C_DIM}{detail}{C_RESET}");
}
match (&s.tailscale, s.tailscale_required) {
(Some(h), req) => {
let ok = h.is_ok();
println!(
" tailscale {} {} {C_DIM}(exit node: {}{}){C_RESET}",
dot(ok || !req),
h.describe(),
if s.exit_node.is_empty() { "none" } else { &s.exit_node },
if req { "" } else { ", optional" }
);
}
(None, _) => println!(" tailscale {C_DIM}not installed{C_RESET}"),
}
println!(
" state {}",
if healthy {
format!("{C_GREEN}healthy{C_RESET}")
} else {
format!("{C_YELLOW}needs attention{C_RESET} — run `breadcrumbs init`")
}
);
Ok(if healthy { 0 } else { 1 })
}
const CORE_PROFILES: [&str; 3] = ["home", "work", "away"];
fn cmd_profile(
be: &dyn Backend,
cfg: &mut Config,
action: Option<ProfileCmd>,
) -> Result<i32, String> {
match action.unwrap_or(ProfileCmd::Get) {
ProfileCmd::Get => {
println!("{}", State::load(&cfg.settings.default_profile).profile);
Ok(0)
}
ProfileCmd::List => {
let cur = State::load(&cfg.settings.default_profile).profile;
for name in cfg.profiles.keys() {
let mark = if *name == cur { "*" } else { " " };
println!("{mark} {name}");
}
Ok(0)
}
ProfileCmd::Add { name, detect } => {
if cfg.profiles.contains_key(&name) {
return Err(format!("profile '{name}' already exists"));
}
cfg.profiles.insert(
name.clone(),
config::Profile {
detect_ssids: detect,
..Default::default()
},
);
cfg.save()?;
println!("{C_GREEN}added{C_RESET} profile {name}");
Ok(0)
}
ProfileCmd::Remove { name } => {
if CORE_PROFILES.contains(&name.as_str()) {
return Err(format!(
"'{name}' is a core profile and is always recreated; clear its networks instead"
));
}
if cfg.profiles.remove(&name).is_none() {
return Err(format!("unknown profile '{name}'"));
}
cfg.save()?;
println!("{C_GREEN}removed{C_RESET} profile {name}");
Ok(0)
}
ProfileCmd::Set { name, no_apply } => {
if !cfg.profiles.contains_key(&name) {
let avail: Vec<&String> = cfg.profiles.keys().collect();
return Err(format!("unknown profile '{name}'. Available: {avail:?}"));
}
let st = State {
profile: name.clone(),
updated: util::timestamp(),
};
st.save()?;
notify::log(&format!("profile set -> {name}"));
println!("profile = {C_BOLD}{name}{C_RESET}");
if no_apply {
return Ok(0);
}
let outcome = flow::run(be, cfg, &name);
print_outcome(&name, &outcome);
Ok(if outcome.ok() { 0 } else { 1 })
}
}
}
fn detect_profile(be: &dyn Backend, cfg: &Config) -> Option<String> {
let iface = be.wifi_interface()?;
be.radio_on();
be.rescan(&iface, &[]);
let visible = be.visible_ssids(&iface);
// Pick the profile with the most marker SSIDs in range, so overlapping
// locations disambiguate by strength of evidence. Profiles iterate in
// BTreeMap (alphabetical) order, which deterministically breaks ties.
let mut best: Option<(usize, String)> = None;
for (name, profile) in &cfg.profiles {
let score = profile
.detect_ssids
.iter()
.filter(|s| visible.contains(s.as_str()))
.count();
if score == 0 {
continue;
}
if best.as_ref().map(|(s, _)| score > *s).unwrap_or(true) {
best = Some((score, name.clone()));
}
}
// Fall back to the default profile if no markers matched.
Some(
best.map(|(_, name)| name)
.unwrap_or_else(|| cfg.settings.default_profile.clone()),
)
}
fn cmd_detect(be: &dyn Backend, cfg: &Config, apply: bool) -> Result<i32, String> {
match detect_profile(be, cfg) {
Some(p) => {
println!("{p}");
if apply {
State {
profile: p.clone(),
updated: util::timestamp(),
}
.save()?;
let outcome = flow::run(be, cfg, &p);
print_outcome(&p, &outcome);
return Ok(if outcome.ok() { 0 } else { 1 });
}
Ok(0)
}
None => Err("could not detect a profile (no Wi-Fi adapter?)".into()),
}
}
fn prompt_line(msg: &str) -> String {
print!("{msg}");
let _ = std::io::stdout().flush();
let mut s = String::new();
let _ = std::io::stdin().lock().read_line(&mut s);
s.trim_end_matches(['\n', '\r']).to_string()
}
fn prompt_secret(msg: &str) -> String {
// `util::run` redirects child stdin to /dev/null, so plain `stty -echo`
// would target the wrong fd and silently leave echo ON (leaking the
// password to the screen). `-F /dev/tty` makes stty act on the controlling
// terminal directly. If there is no tty we fall back to visible input.
let had_tty = run("stty", &["-F", "/dev/tty", "-echo"], Duration::from_secs(2)).success;
let val = prompt_line(msg);
if had_tty {
let _ = run("stty", &["-F", "/dev/tty", "echo"], Duration::from_secs(2));
println!();
}
val
}
fn cmd_add(
cfg: &mut Config,
ssid: String,
password: Option<String>,
hidden: bool,
to: Option<String>,
at: Option<usize>,
) -> Result<i32, String> {
let password = match password {
Some(p) => p,
None => prompt_secret(&format!("Password for '{ssid}': ")),
};
match cfg.networks.iter_mut().find(|n| n.ssid == ssid) {
Some(n) => {
n.password = password;
n.hidden = hidden || n.hidden;
}
None => cfg.networks.push(NetworkDef {
ssid: ssid.clone(),
password,
hidden,
}),
}
if let Some(prof_name) = to {
let prof = cfg
.profiles
.get_mut(&prof_name)
.ok_or_else(|| format!("unknown profile '{prof_name}'"))?;
prof.networks.retain(|s| s != &ssid);
let idx = at.unwrap_or(prof.networks.len()).min(prof.networks.len());
prof.networks.insert(idx, ssid.clone());
}
cfg.save()?;
println!("{C_GREEN}saved{C_RESET} {ssid}");
Ok(0)
}
fn cmd_join(be: &dyn Backend, cfg: &Config, ssid: &str) -> Result<i32, String> {
let net = cfg
.network(ssid)
.ok_or_else(|| format!("no saved network '{ssid}' — add it first with `breadcrumbs add {ssid}`"))?;
let iface = be
.wifi_interface()
.ok_or_else(|| "no Wi-Fi adapter found".to_string())?;
be.radio_on();
match nm::connect_verbose(&iface, net, cfg.settings.nmcli_wait, &cfg.settings.dns) {
Ok(()) => {
println!("{C_GREEN}connected{C_RESET} {C_BOLD}{ssid}{C_RESET}");
Ok(0)
}
Err(e) => {
eprintln!("{C_RED}connect failed{C_RESET}: {e}");
Ok(1)
}
}
}
fn cmd_scan_list(cfg: &Config, json: bool) -> Result<i32, String> {
let iface = nm::wifi_interface().ok_or("no Wi-Fi adapter found")?;
let entries = nm::scan_list(&iface);
let saved: std::collections::HashSet<&str> =
cfg.networks.iter().map(|n| n.ssid.as_str()).collect();
if json {
let v: Vec<serde_json::Value> = entries
.iter()
.map(|e| {
serde_json::json!({
"ssid": e.ssid,
"signal": e.signal,
"security": e.security,
"saved": saved.contains(e.ssid.as_str()),
})
})
.collect();
println!("{}", serde_json::to_string(&v).unwrap_or_else(|_| "[]".into()));
} else {
for e in &entries {
let mark = if saved.contains(e.ssid.as_str()) { "*" } else { " " };
println!("{mark} {:>3}% {} {}", e.signal, e.ssid, e.security);
}
}
Ok(0)
}
fn cmd_networks(cfg: &Config, json: bool) -> Result<i32, String> {
let ssids: Vec<&str> = cfg.networks.iter().map(|n| n.ssid.as_str()).collect();
if json {
println!("{}", serde_json::to_string(&ssids).unwrap_or_else(|_| "[]".into()));
} else {
for ssid in &ssids {
println!("{ssid}");
}
}
Ok(0)
}
fn cmd_forget(cfg: &mut Config, ssid: &str) -> Result<i32, String> {
let before = cfg.networks.len();
cfg.networks.retain(|n| n.ssid != ssid);
for p in cfg.profiles.values_mut() {
p.networks.retain(|s| s != ssid);
if p.bootstrap.as_deref() == Some(ssid) {
p.bootstrap = None;
}
}
cfg.save()?;
let removed = nm::delete_connections_for_ssid(ssid);
println!(
"{C_GREEN}forgot{C_RESET} {ssid} (config: {}, NetworkManager: {})",
if cfg.networks.len() < before {
"removed"
} else {
"not present"
},
if removed { "removed" } else { "not present" }
);
Ok(0)
}
fn cmd_scan(cfg: &mut Config, to: Option<String>) -> Result<i32, String> {
let iface = nm::wifi_interface().ok_or("no Wi-Fi adapter")?;
nm::radio_on();
nm::rescan(&iface, &[]);
let entries = nm::scan_list(&iface);
if entries.is_empty() {
return Err("no networks found".into());
}
for (i, e) in entries.iter().enumerate() {
println!(
"{:>2}. {C_BOLD}{}{C_RESET} {C_DIM}sig {} {}{C_RESET}",
i + 1,
if e.ssid.is_empty() {
"<hidden>"
} else {
&e.ssid
},
e.signal,
e.security
);
}
let sel = prompt_line("Select number: ");
let idx: usize = sel
.parse::<usize>()
.ok()
.filter(|n| *n >= 1 && *n <= entries.len())
.ok_or("invalid selection")?;
let ssid = entries[idx - 1].ssid.clone();
if ssid.is_empty() {
return Err("cannot select a hidden SSID here; use `breadcrumbs add`".into());
}
let password = prompt_secret(&format!("Password for '{ssid}': "));
let def = NetworkDef {
ssid: ssid.clone(),
password: password.clone(),
hidden: false,
};
if !nm::connect(&iface, &def, cfg.settings.nmcli_wait, &cfg.settings.dns) {
return Err(format!("failed to connect to {ssid}"));
}
match cfg.networks.iter_mut().find(|n| n.ssid == ssid) {
Some(n) => n.password = password,
None => cfg.networks.push(def),
}
if let Some(prof_name) = to {
if let Some(prof) = cfg.profiles.get_mut(&prof_name) {
if !prof.networks.contains(&ssid) {
prof.networks.push(ssid.clone());
}
}
}
cfg.save()?;
println!("{C_GREEN}connected + saved{C_RESET} {ssid}");
Ok(0)
}
fn mask(p: &str) -> String {
// Count by characters, not bytes: slicing &p[..1] would panic on a
// multi-byte first character (valid in WPA passphrases).
let count = p.chars().count();
if count <= 2 {
"••".into()
} else {
let first: String = p.chars().take(1).collect();
format!("{}{}", first, "".repeat(count - 1))
}
}
fn cmd_list(cfg: &Config, show_pw: bool) -> Result<i32, String> {
println!("{C_BOLD}settings{C_RESET}");
println!(" dns {}", cfg.settings.dns);
println!(" exit_node {}", cfg.settings.exit_node);
println!(" default {}", cfg.settings.default_profile);
println!(" watch every {}s", cfg.settings.watch_interval);
println!("\n{C_BOLD}networks{C_RESET}");
for n in &cfg.networks {
println!(
" {C_BOLD}{}{C_RESET} {C_DIM}{}{}{C_RESET}",
n.ssid,
if show_pw {
n.password.clone()
} else {
mask(&n.password)
},
if n.hidden { " (hidden)" } else { "" }
);
}
println!("\n{C_BOLD}profiles{C_RESET}");
let cur = State::load(&cfg.settings.default_profile).profile;
for (name, p) in &cfg.profiles {
let mark = if *name == cur {
format!("{C_GREEN}*{C_RESET}")
} else {
" ".into()
};
println!("{mark} {C_BOLD}{name}{C_RESET}");
if let Some(b) = &p.bootstrap {
println!(" bootstrap {b}");
}
if p.tailscale {
let exit_node = p
.exit_node
.clone()
.unwrap_or_else(|| cfg.settings.exit_node.clone());
println!(
" tailscale required (exit node: {})",
if exit_node.is_empty() { "none".to_string() } else { exit_node }
);
}
let mut order: Vec<String> = p.networks.clone();
if p.include_all_known {
order.push("…all other known networks".into());
}
println!(" priority {}", order.join(" > "));
}
Ok(0)
}
fn cmd_edit() -> Result<i32, String> {
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "nano".into());
let path = config::config_path();
let status = Command::new(&editor)
.arg(&path)
.status()
.map_err(|e| format!("launching {editor}: {e}"))?;
if !status.success() {
return Err("editor exited with error".into());
}
match Config::load() {
Ok(_) => {
println!("{C_GREEN}config OK{C_RESET}");
Ok(0)
}
Err(e) => Err(format!("config is now invalid: {e}")),
}
}
fn cmd_doctor(
be: &dyn Backend,
cfg: &Config,
override_p: &Option<String>,
full: bool,
) -> Result<i32, String> {
if full {
let script = config::config_dir().join("diag.sh");
if !script.exists() {
return Err(format!(
"diag.sh not found (expected at {})",
script.display()
));
}
let st = Command::new("bash")
.arg(&script)
.status()
.map_err(|e| format!("running diag: {e}"))?;
return Ok(st.code().unwrap_or(1));
}
let p = active_profile(cfg, override_p);
let s = status::gather(be, cfg, &p);
println!("{C_BOLD}breadcrumbs doctor{C_RESET} (profile {p})");
println!(
" nmcli {}",
if command_exists("nmcli") {
"present"
} else {
"MISSING"
}
);
println!(
" tailscale {}",
if command_exists("tailscale") {
"present"
} else {
"absent"
}
);
println!(
" adapter {}",
s.iface.clone().unwrap_or_else(|| "none".into())
);
println!(
" ssid {}",
s.ssid.clone().unwrap_or_else(|| "".into())
);
println!(
" ip {}",
s.ip.clone().unwrap_or_else(|| "".into())
);
println!(" internet {}", if s.internet { "ok" } else { "DOWN" });
if let Some(h) = &s.tailscale {
println!(
" tailscale {} (exit node: {})",
h.describe(),
if s.exit_node.is_empty() { "none" } else { &s.exit_node }
);
}
if let Some(iface) = &s.iface {
let visible = nm::visible_ssids(iface);
let known: Vec<&str> = cfg
.networks
.iter()
.filter(|n| visible.contains(&n.ssid))
.map(|n| n.ssid.as_str())
.collect();
println!(
" in range {}",
if known.is_empty() {
"none of your saved networks".into()
} else {
known.join(", ")
}
);
}
println!("\nFull report: {C_DIM}breadcrumbs doctor --full{C_RESET}");
Ok(0)
}
fn cmd_cd(shell: bool) -> Result<i32, String> {
let dir = config::config_dir();
if shell {
let sh = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
let err = exec_replace(&sh, &["-lc", &format!("cd {:?} && exec {sh}", dir)]);
return Err(err);
}
println!("{}", dir.display());
Ok(0)
}
fn exec_replace(prog: &str, args: &[&str]) -> String {
use std::os::unix::process::CommandExt;
let e = Command::new(prog).args(args).exec();
format!("exec {prog} failed: {e}")
}
fn cmd_install_service(enable: bool) -> Result<i32, String> {
let unit_dir = home_dir().join(".config/systemd/user");
std::fs::create_dir_all(&unit_dir)
.map_err(|e| format!("creating {}: {e}", unit_dir.display()))?;
let bin = std::env::current_exe().map_err(|e| format!("resolving current executable: {e}"))?;
// Ordering against graphical-session.target lets the watcher inherit the
// session's DISPLAY/WAYLAND_DISPLAY/DBUS so notify-send and the Tailscale
// login browser-open actually work. PATH is pinned because systemd --user
// units do not get the login shell's PATH, and the watcher shells out to
// nmcli/tailscale/sudo/xdg-open by name.
let unit = format!(
"[Unit]\n\
Description=breadcrumbs Wi-Fi state machine watcher\n\
After=network.target NetworkManager.service graphical-session.target\n\
Wants=network.target graphical-session.target\n\n\
[Service]\n\
Type=simple\n\
Environment=PATH=/usr/local/bin:/usr/bin:/bin\n\
ExecStart={bin} watch\n\
Restart=always\n\
RestartSec=5\n\
Nice=5\n\n\
[Install]\n\
WantedBy=default.target\n",
bin = bin.display()
);
let unit_path = unit_dir.join("breadcrumbs.service");
std::fs::write(&unit_path, unit)
.map_err(|e| format!("writing {}: {e}", unit_path.display()))?;
println!("{C_GREEN}wrote{C_RESET} {}", unit_path.display());
let _ = run(
"systemctl",
&["--user", "daemon-reload"],
Duration::from_secs(10),
);
if enable {
let o = run(
"systemctl",
&["--user", "enable", "--now", "breadcrumbs.service"],
Duration::from_secs(15),
);
if o.success {
println!("{C_GREEN}enabled + started{C_RESET} breadcrumbs.service");
} else {
println!(
"{C_YELLOW}unit installed{C_RESET}; enable failed: {}",
o.stderr.trim()
);
return Ok(1);
}
} else {
println!("Run: systemctl --user enable --now breadcrumbs.service");
}
Ok(0)
}

1180
src/nm.rs

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@ use std::fs;
use serde::{Deserialize, Serialize};
use crate::config::{state_dir, state_path, Config};
use crate::config::{state_dir, state_path};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct State {
@ -29,25 +29,7 @@ impl State {
pub fn save(&self) -> Result<(), String> {
fs::create_dir_all(state_dir()).map_err(|e| format!("creating state dir: {e}"))?;
let text = toml::to_string_pretty(self).map_err(|e| format!("serializing state: {e}"))?;
fs::write(state_path(), text).map_err(|e| format!("writing state: {e}"))
crate::util::write_atomic(&state_path(), &text, 0o644)
.map_err(|e| format!("writing state: {e}"))
}
}
/// Persist `name` as the active profile if it exists in `cfg`. Shared by the
/// CLI `profile set` path and `bread.command.crumbs.set_profile` so they
/// cannot drift. Does not run [`crate::flow::run`] — the CLI applies
/// afterwards unless `--no-apply`, and the watch daemon picks the new
/// profile up on its next tick.
pub fn set_profile(cfg: &Config, name: &str) -> Result<(), String> {
if !cfg.profiles.contains_key(name) {
let avail: Vec<&String> = cfg.profiles.keys().collect();
return Err(format!("unknown profile '{name}'. Available: {avail:?}"));
}
State {
profile: name.to_string(),
updated: crate::util::timestamp(),
}
.save()?;
crate::notify::log(&format!("profile set -> {name}"));
Ok(())
}

View file

@ -1,22 +1,30 @@
use std::time::Duration;
use crate::backend::Backend;
use crate::config::Config;
use crate::nm;
use crate::tailscale::{self, TsHealth};
use crate::tailscale::TsHealth;
use crate::util::{command_exists, run};
/// Connectivity verdict. `Portal` is the interesting case: an HTTP response
/// arrived (200/301/302) but it wasn't the 204 the generate_204 endpoint
/// returns for genuine internet — the classic captive/guest-portal
/// signature, and the reason `classify` can tell "no internet at all" from
/// "internet but intercepted".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Result of a connectivity probe. `Portal` distinguishes a captive portal
/// (associated, but traffic is being intercepted) from real internet or a hard
/// outage — the optional string is the portal's sign-in URL when known.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Connectivity {
Online,
Portal,
NoNet,
Portal(Option<String>),
Offline,
}
impl Connectivity {
pub fn online(&self) -> bool {
matches!(self, Connectivity::Online)
}
}
/// Probe connectivity. Only an empty HTTP 204 from the generate_204-style
/// endpoint counts as online; a 200/redirect means a captive portal is
/// intercepting traffic. If the HTTP probe is inconclusive (timeout/5xx) we fall
/// back to ICMP, which reaching the host treats as online.
pub fn connectivity(cfg: &Config) -> Connectivity {
if command_exists("curl") {
let o = run(
@ -26,43 +34,61 @@ pub fn connectivity(cfg: &Config) -> Connectivity {
"-o",
"/dev/null",
"-w",
"%{http_code}",
"%{http_code} %{redirect_url}",
"--max-time",
"4",
&cfg.settings.connectivity_url,
],
Duration::from_secs(6),
);
// Only a 204 counts as real internet. Captive/guest portals answer
// 200 (a login page) or 302 (a redirect to it). The default endpoint
// is generate_204, which returns 204 precisely when traffic isn't
// being intercepted.
let code = o.stdout.trim();
if code == "204" {
return Connectivity::Online;
}
if code == "200" || code == "301" || code == "302" {
return Connectivity::Portal;
let mut parts = o.stdout.split_whitespace();
let code = parts.next().unwrap_or("");
let redirect = parts.next().unwrap_or("").trim();
match code {
"204" => return Connectivity::Online,
"200" | "301" | "302" | "303" | "307" | "308" => {
let url = if redirect.is_empty() {
None
} else {
Some(redirect.to_string())
};
return Connectivity::Portal(url);
}
// 000/timeout/5xx → inconclusive, try ICMP below.
_ => {}
}
}
// Fallback: ICMP to the configured host. A working ping overrides a
// non-204 curl answer that wasn't portal-shaped (e.g. a 403 from an
// overzealous firewall); a portal usually blocks ICMP too, so this
// stays Portal for the genuine case.
let ping = run(
"ping",
&["-c", "1", "-W", "2", &cfg.settings.ping_host],
Duration::from_secs(4),
);
if ping.success {
)
.success;
if ping {
Connectivity::Online
} else {
Connectivity::NoNet
Connectivity::Offline
}
}
pub fn internet_ok(cfg: &Config) -> bool {
matches!(connectivity(cfg), Connectivity::Online)
/// Best-effort IPv4 address of `iface` via nmcli, with the CIDR prefix stripped.
pub fn ipv4(iface: &str) -> Option<String> {
let o = run(
"nmcli",
&["-g", "IP4.ADDRESS", "device", "show", iface],
Duration::from_secs(6),
);
if !o.success {
return None;
}
let s = o.stdout.trim();
if s.is_empty() {
None
} else {
// nmcli reports "192.168.1.5/24"; drop the prefix length for display.
let first = s.lines().next().unwrap_or(s).trim();
Some(first.split('/').next().unwrap_or(first).to_string())
}
}
pub struct Status {
@ -70,40 +96,33 @@ pub struct Status {
pub ssid: Option<String>,
pub ip: Option<String>,
pub internet: bool,
/// True when traffic is being intercepted (captive/guest portal).
pub portal: bool,
/// Set when a captive portal was detected; inner string is its URL if known.
pub portal: Option<String>,
pub tailscale_required: bool,
pub tailscale: Option<TsHealth>,
pub exit_node: String,
}
pub fn gather(cfg: &Config, profile_name: &str) -> Status {
let iface = nm::wifi_interface_preferred(cfg.settings.interface.as_deref());
let ssid = iface.as_deref().and_then(nm::active_ssid);
let ip = iface.as_deref().and_then(nm::ipv4_address);
// Skip the (potentially 4s-blocking) connectivity probe when there's no
// Wi-Fi interface at all: the watch loop classifies NoAdapter and would
// otherwise burn a network round-trip (curl/ping) every tick for nothing.
let (internet, portal) = if iface.is_some() {
match connectivity(cfg) {
Connectivity::Online => (true, false),
Connectivity::Portal => (false, true),
Connectivity::NoNet => (false, false),
}
} else {
(false, false)
pub fn gather(be: &dyn Backend, cfg: &Config, profile_name: &str) -> Status {
let iface = be.wifi_interface();
let ssid = iface.as_deref().and_then(|i| be.active_ssid(i));
let ip = iface.as_deref().and_then(|i| be.ipv4(i));
let conn = be.connectivity(cfg);
let internet = conn.online();
let portal = match conn {
Connectivity::Portal(url) => Some(url.unwrap_or_default()),
_ => None,
};
let prof = cfg.profile(profile_name);
let ts_required = prof.map(|p| p.tailscale).unwrap_or(false);
let exit_nodes = cfg.exit_nodes_for(profile_name);
let exit_node = exit_nodes.first().cloned().unwrap_or_default();
let exit_node = prof
.and_then(|p| p.exit_node.clone())
.unwrap_or_else(|| cfg.settings.exit_node.clone());
// Checked whenever tailscale is installed so `status`/`doctor` can show
// it even for non-required profiles; classify only consults it when the
// profile requires Tailscale.
let tailscale = if tailscale::installed() {
Some(tailscale::check(&exit_nodes))
let tailscale = if be.tailscale_installed() {
Some(be.tailscale_check(&exit_node))
} else {
None
};

View file

@ -21,10 +21,6 @@ pub enum TsHealth {
ExitNodeMissing,
/// The exit node exists but is offline.
ExitNodeOffline,
/// The profile requires an exit node but none is configured
/// (`settings.exit_node` / per-profile `exit_node` empty). Cannot be
/// auto-fixed — the user must configure one.
NoExitNode,
Error(String),
}
@ -33,21 +29,6 @@ impl TsHealth {
matches!(self, TsHealth::Ok)
}
/// Wire name for `bread.crumbs.*` event payloads (variant name, like
/// `Health::as_str`).
pub fn state_str(&self) -> &'static str {
match self {
TsHealth::Ok => "Ok",
TsHealth::NotInstalled => "NotInstalled",
TsHealth::NeedsLogin => "NeedsLogin",
TsHealth::Stopped => "Stopped",
TsHealth::ExitNodeMissing => "ExitNodeMissing",
TsHealth::ExitNodeOffline => "ExitNodeOffline",
TsHealth::NoExitNode => "NoExitNode",
TsHealth::Error(_) => "Error",
}
}
pub fn describe(&self) -> String {
match self {
TsHealth::Ok => "ok".into(),
@ -56,7 +37,6 @@ impl TsHealth {
TsHealth::Stopped => "backend stopped".into(),
TsHealth::ExitNodeMissing => "exit node not found in tailnet".into(),
TsHealth::ExitNodeOffline => "exit node is offline".into(),
TsHealth::NoExitNode => "no exit node configured".into(),
TsHealth::Error(e) => format!("error: {e}"),
}
}
@ -239,82 +219,16 @@ fn run_login() {
}
}
/// Strip whitespace and drop empty entries from the acceptable-node list.
fn effective_nodes(nodes: &[String]) -> Vec<String> {
nodes
.iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
/// Given a status JSON and the acceptable exit nodes, report `Ok` when the
/// active selection is one of them and online; otherwise the closest
/// actionable failure: not-selected (present + online, flow must select),
/// offline, or missing.
fn exit_node_health(nodes: &[String], v: &Value) -> TsHealth {
let mut any_exists = false;
let mut any_online = false;
let mut any_selected = false;
for node in nodes {
let (exists, online, selected) = exit_node_state(v, node);
if exists {
any_exists = true;
if online {
any_online = true;
}
if selected {
any_selected = true;
}
}
}
if any_selected && any_online {
TsHealth::Ok
} else if any_selected {
// The active exit node is one of ours but offline.
TsHealth::ExitNodeOffline
} else if any_online {
// Present + online but not selected — the flow will select it.
TsHealth::Error("exit node not selected".into())
} else if any_exists {
TsHealth::ExitNodeOffline
} else {
TsHealth::ExitNodeMissing
}
}
/// Bring Tailscale to a state where one of `nodes` (priority order) is the
/// active, online exit node. Performs at most one bring-up/login, then one
/// `tailscale set` per node until one takes.
pub fn ensure_exit_node(nodes: &[String]) -> TsHealth {
/// Bring Tailscale to a state where `node` is the active, online exit node.
/// Performs at most one bring-up/login and one `tailscale set` attempt.
pub fn ensure_exit_node(node: &str) -> TsHealth {
if !installed() {
return TsHealth::NotInstalled;
}
let eff = effective_nodes(nodes);
if eff.is_empty() {
// Never run `tailscale set --exit-node=` with an empty node — that
// would clear the user's current exit-node selection. This is a
// config error, surfaced as its own health state.
return TsHealth::NoExitNode;
}
let v = match status_json() {
Some(v) => v,
None => {
// Daemon unreachable — usually *not running*: a stopped daemon
// prints its error to stderr and leaves stdout empty, which is
// exactly why this branch used to be dead code (the
// BackendState "Stopped" case below only fires when the daemon
// is up but the backend is stopped). Try to bring it up before
// giving up; `tailscale up` is idempotent when already running
// and fails fast (no sudo prompt — stdin is /dev/null) when
// the caller lacks permission to manage the daemon.
let _ = run("tailscale", &["up"], Duration::from_secs(20));
match status_json() {
Some(v2) => v2,
None => return TsHealth::Error("could not read tailscale status".into()),
}
}
None => return TsHealth::Error("could not read tailscale status".into()),
};
match backend_state(&v).as_str() {
@ -335,45 +249,43 @@ pub fn ensure_exit_node(nodes: &[String]) -> TsHealth {
_ => {}
}
// Failover: try each acceptable node in priority order until one is
// selected and online.
for node in &eff {
let _ = run(
"tailscale",
&["set", &format!("--exit-node={node}")],
Duration::from_secs(10),
);
if let Some(v2) = status_json() {
if matches!(exit_node_health(std::slice::from_ref(node), &v2), TsHealth::Ok) {
return TsHealth::Ok;
}
}
}
// Select the exit node (idempotent).
let _ = run(
"tailscale",
&["set", &format!("--exit-node={node}")],
Duration::from_secs(10),
);
let v = match status_json() {
Some(v) => v,
None => return TsHealth::Error("could not re-read tailscale status".into()),
};
match backend_state(&v).as_str() {
"Running" => {}
"NeedsLogin" | "NoState" => return TsHealth::NeedsLogin,
"Stopped" => return TsHealth::Stopped,
other => return TsHealth::Error(format!("backend state: {other}")),
}
exit_node_health(&eff, &v)
let (exists, online, selected) = exit_node_state(&v, node);
if !exists {
TsHealth::ExitNodeMissing
} else if !online {
TsHealth::ExitNodeOffline
} else if !selected {
// Online and present but our set didn't take — treat as missing/selectable error.
TsHealth::Error("exit node not selected".into())
} else {
TsHealth::Ok
}
}
/// Lightweight health check without trying to (re)configure anything.
pub fn check(nodes: &[String]) -> TsHealth {
pub fn check(node: &str) -> TsHealth {
if !installed() {
return TsHealth::NotInstalled;
}
let eff = effective_nodes(nodes);
if eff.is_empty() {
// Read-only check, so never runs `tailscale set` — an empty node is
// a config error, not something this probe can fix.
return TsHealth::NoExitNode;
}
let v = match status_json() {
Some(v) => v,
None => return TsHealth::Error("status unavailable".into()),
@ -384,7 +296,16 @@ pub fn check(nodes: &[String]) -> TsHealth {
"Stopped" => return TsHealth::Stopped,
other => return TsHealth::Error(format!("backend state: {other}")),
}
exit_node_health(&eff, &v)
let (exists, online, selected) = exit_node_state(&v, node);
if !exists {
TsHealth::ExitNodeMissing
} else if !online {
TsHealth::ExitNodeOffline
} else if !selected {
TsHealth::Error("exit node not selected".into())
} else {
TsHealth::Ok
}
}
#[cfg(test)]
@ -392,6 +313,54 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn ts_health_is_ok_only_for_ok_variant() {
assert!(TsHealth::Ok.is_ok());
assert!(!TsHealth::NotInstalled.is_ok());
assert!(!TsHealth::NeedsLogin.is_ok());
assert!(!TsHealth::Stopped.is_ok());
assert!(!TsHealth::ExitNodeMissing.is_ok());
assert!(!TsHealth::ExitNodeOffline.is_ok());
assert!(!TsHealth::Error("x".into()).is_ok());
}
#[test]
fn ts_health_describe_covers_all_variants() {
assert_eq!(TsHealth::Ok.describe(), "ok");
assert!(TsHealth::NotInstalled.describe().contains("not installed"));
assert!(TsHealth::NeedsLogin.describe().contains("not logged in"));
assert!(TsHealth::Stopped.describe().contains("stopped"));
assert!(TsHealth::ExitNodeMissing.describe().contains("not found"));
assert!(TsHealth::ExitNodeOffline.describe().contains("offline"));
let msg = TsHealth::Error("boom".into()).describe();
assert!(msg.contains("boom"));
}
#[test]
fn extract_url_finds_https_url() {
assert_eq!(
extract_url("To authenticate, visit https://login.tailscale.com/a/xxx"),
Some("https://login.tailscale.com/a/xxx".into())
);
}
#[test]
fn extract_url_returns_none_when_no_url() {
assert_eq!(extract_url("Waiting for login..."), None);
assert_eq!(extract_url(""), None);
}
#[test]
fn extract_url_picks_first_https_token() {
let line = "Try https://first.example.com https://second.example.com";
assert_eq!(extract_url(line), Some("https://first.example.com".into()));
}
#[test]
fn extract_url_does_not_match_plain_http() {
assert_eq!(extract_url("see http://example.com for info"), None);
}
#[test]
fn backend_state_extraction() {
assert_eq!(
@ -401,6 +370,13 @@ mod tests {
assert_eq!(backend_state(&json!({})), "");
}
#[test]
fn backend_state_all_known_values() {
for state in ["Running", "NeedsLogin", "NoState", "Stopped"] {
assert_eq!(backend_state(&json!({"BackendState": state})), state);
}
}
#[test]
fn exit_node_healthy_and_selected() {
let v = json!({
@ -462,149 +438,57 @@ mod tests {
}
#[test]
fn exit_node_lookup_is_case_insensitive() {
fn exit_node_state_empty_peer_map() {
let v = json!({ "BackendState": "Running", "Peer": {} });
assert_eq!(exit_node_state(&v, "anynode"), (false, false, false));
}
#[test]
fn exit_node_state_no_peer_field() {
let v = json!({ "BackendState": "Running" });
assert_eq!(exit_node_state(&v, "anynode"), (false, false, false));
}
#[test]
fn exit_node_state_case_insensitive_hostname() {
let v = json!({
"Peer": {
"k1": { "HostName": "ExitNode", "DNSName": "ExitNode.ts.net.",
"k1": { "HostName": "MYNODE", "DNSName": "mynode.ts.net.",
"Online": true, "ExitNode": true, "ExitNodeOption": true }
}
});
assert_eq!(exit_node_state(&v, "EXITNODE"), (true, true, true));
let (exists, online, selected) = exit_node_state(&v, "mynode");
assert!(exists && online && selected);
}
#[test]
fn exit_node_state_with_no_peers_is_all_false() {
let v = json!({ "BackendState": "Running" });
assert_eq!(exit_node_state(&v, "exitnode"), (false, false, false));
}
#[test]
fn exit_node_state_empty_node_name_matches_nothing() {
fn exit_node_status_overrides_peer_online_when_selected() {
// ExitNodeStatus.Online=false should override the peer's Online=true
// when the peer is the currently-selected exit node.
let v = json!({
"ExitNodeStatus": { "Online": false },
"Peer": {
"k1": { "HostName": "exitnode", "DNSName": "exitnode.ts.net.",
"Online": true, "ExitNode": true, "ExitNodeOption": true }
}
});
assert_eq!(exit_node_state(&v, ""), (false, false, false));
let (exists, online, selected) = exit_node_state(&v, "exitnode");
assert!(exists);
assert!(
!online,
"ExitNodeStatus.Online=false should override peer Online"
);
assert!(selected);
}
#[test]
fn exit_node_status_online_only_applies_when_selected() {
// ExitNodeStatus.Online reflects the currently *active* exit node —
// it must not leak into the reported state of a peer that merely
// matches by name but isn't the one actually selected.
fn exit_node_state_wrong_node_name_not_matched() {
let v = json!({
"ExitNodeStatus": { "Online": true },
"Peer": {
"k1": { "HostName": "other", "DNSName": "other.ts.net.",
"Online": false, "ExitNode": false, "ExitNodeOption": true }
}
});
assert_eq!(exit_node_state(&v, "other"), (true, false, false));
}
#[test]
fn ts_health_is_ok_only_for_ok_variant() {
assert!(TsHealth::Ok.is_ok());
assert!(!TsHealth::NotInstalled.is_ok());
assert!(!TsHealth::NeedsLogin.is_ok());
assert!(!TsHealth::Stopped.is_ok());
assert!(!TsHealth::ExitNodeMissing.is_ok());
assert!(!TsHealth::ExitNodeOffline.is_ok());
assert!(!TsHealth::NoExitNode.is_ok());
assert!(!TsHealth::Error("x".into()).is_ok());
}
#[test]
fn ts_health_describe_is_human_readable() {
assert_eq!(TsHealth::Ok.describe(), "ok");
assert_eq!(
TsHealth::NeedsLogin.describe(),
"not logged in (run: tailscale up)"
);
assert_eq!(TsHealth::NoExitNode.describe(), "no exit node configured");
assert_eq!(TsHealth::Error("boom".into()).describe(), "error: boom");
}
#[test]
fn extract_url_finds_https_token_among_others() {
assert_eq!(
extract_url("To authenticate, visit: https://login.tailscale.com/abc"),
Some("https://login.tailscale.com/abc".to_string())
);
assert_eq!(extract_url("no url on this line"), None);
}
#[test]
fn effective_nodes_trims_and_drops_empties() {
assert_eq!(
effective_nodes(&[" a ".into(), "".into(), "b".into()]),
vec!["a".to_string(), "b".to_string()]
);
}
#[test]
fn exit_node_health_ok_when_any_node_selected_and_online() {
let v = json!({
"BackendState": "Running",
"Peer": {
"k1": { "HostName": "nodeB", "DNSName": "nodeB.ts.net.",
"k1": { "HostName": "othernode", "DNSName": "othernode.ts.net.",
"Online": true, "ExitNode": true, "ExitNodeOption": true }
}
});
assert_eq!(
exit_node_health(&["nodeA".into(), "nodeB".into()], &v),
TsHealth::Ok
);
}
#[test]
fn exit_node_health_reports_not_selected_when_a_node_is_online_but_unselected() {
let v = json!({
"Peer": {
"k1": { "HostName": "nodeA", "DNSName": "nodeA.ts.net.",
"Online": true, "ExitNode": false, "ExitNodeOption": true }
}
});
assert_eq!(
exit_node_health(&["nodeA".into()], &v),
TsHealth::Error("exit node not selected".into())
);
}
#[test]
fn exit_node_health_reports_offline_when_all_exist_but_none_online() {
let v = json!({
"Peer": {
"k1": { "HostName": "nodeA", "DNSName": "nodeA.ts.net.",
"Online": false, "ExitNode": false, "ExitNodeOption": true }
}
});
assert_eq!(
exit_node_health(&["nodeA".into()], &v),
TsHealth::ExitNodeOffline
);
}
#[test]
fn exit_node_health_reports_missing_when_no_node_present() {
let v = json!({ "BackendState": "Running" });
assert_eq!(
exit_node_health(&["nodeA".into()], &v),
TsHealth::ExitNodeMissing
);
}
#[test]
fn state_str_is_the_variant_name() {
assert_eq!(TsHealth::Ok.state_str(), "Ok");
assert_eq!(TsHealth::NotInstalled.state_str(), "NotInstalled");
assert_eq!(TsHealth::NeedsLogin.state_str(), "NeedsLogin");
assert_eq!(TsHealth::Stopped.state_str(), "Stopped");
assert_eq!(TsHealth::ExitNodeMissing.state_str(), "ExitNodeMissing");
assert_eq!(TsHealth::ExitNodeOffline.state_str(), "ExitNodeOffline");
assert_eq!(TsHealth::NoExitNode.state_str(), "NoExitNode");
assert_eq!(TsHealth::Error("x".into()).state_str(), "Error");
assert_eq!(exit_node_state(&v, "exitnode"), (false, false, false));
}
}

View file

@ -1,9 +1,5 @@
use std::cell::RefCell;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub fn home_dir() -> PathBuf {
std::env::var_os("HOME")
@ -11,64 +7,21 @@ pub fn home_dir() -> PathBuf {
.unwrap_or_else(|| PathBuf::from("/root"))
}
#[derive(Debug, Clone)]
pub struct Output {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
impl Output {
pub fn failed() -> Output {
Output {
success: false,
stdout: String::new(),
stderr: String::new(),
}
}
}
/// Everything breadcrumbs does to touch the outside world *other than* its
/// own file I/O and env var reads: spawning an external program, and
/// checking whether one is available at all. Every call site in this crate
/// (`nm.rs`, `tailscale.rs`, `status.rs`, `notify.rs`, `app.rs`) goes through
/// the free functions below (`run`/`run_with_stdin`/`run_ok`/
/// `command_exists`), which are thin wrappers dispatching to whatever
/// `Runner` is currently installed in the thread-local slot — `RealRunner` by
/// default.
/// Atomically replace `path` with `contents`: write a sibling temp file (created
/// with `mode` on unix) and `rename` it over the target. Avoids torn reads by a
/// concurrent reader (the watch daemon reloads config every tick) and never
/// leaves a half-written file behind on crash. Because the temp file is created
/// with `mode` up front, secrets never exist world-readable even briefly.
///
/// Tests swap in a fake implementation via [`with_runner`] so real call
/// chains (`flow::run`, `watch::classify`, …) can be driven in-process
/// against canned output, with no subprocess ever spawned and full
/// visibility into exactly what *would* have been executed — the natural
/// mechanism for asserting things like "no password ever reaches nmcli's
/// argv on a repeat connect" (see the credential tests under `tests/`).
///
/// A thread-local (rather than an explicit parameter threaded through every
/// function) was chosen so the large existing call surface in `nm.rs` et al.
/// didn't need every signature rewritten to carry a `&dyn Runner` — call
/// sites are unchanged, only `util`'s internals dispatch differently. It's
/// safe across `cargo test`'s parallel test threads because each thread gets
/// its own independent slot, defaulting to `RealRunner`, so tests that don't
/// install a fake are unaffected by ones that do.
pub trait Runner {
fn run(&self, prog: &str, args: &[&str], stdin: Option<&str>, timeout: Duration) -> Output;
fn command_exists(&self, name: &str) -> bool;
/// Delegates to `bread_utils::atomic::write_atomic` — this crate's own
/// version of this function was promoted verbatim into the shared
/// `bread-utils` crate (see that crate's `atomic` module doc comment) as
/// the one implementation in the ecosystem that already got this right.
pub fn write_atomic(path: &Path, contents: &str, mode: u32) -> std::io::Result<()> {
bread_utils::atomic::write_atomic(path, contents, Some(mode))
}
struct RealRunner;
impl Runner for RealRunner {
fn run(&self, prog: &str, args: &[&str], stdin: Option<&str>, timeout: Duration) -> Output {
spawn_run(prog, args, stdin, timeout)
}
fn command_exists(&self, name: &str) -> bool {
path_lookup_exists(name)
}
}
fn path_lookup_exists(name: &str) -> bool {
pub fn command_exists(name: &str) -> bool {
if let Some(paths) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&paths) {
if dir.join(name).is_file() {
@ -79,132 +32,14 @@ fn path_lookup_exists(name: &str) -> bool {
false
}
thread_local! {
static RUNNER: RefCell<Box<dyn Runner>> = RefCell::new(Box::new(RealRunner));
}
pub fn command_exists(name: &str) -> bool {
RUNNER.with(|r| r.borrow().command_exists(name))
}
/// Run a command with a hard timeout. The child is killed if it overruns so a
/// hung subprocess can never wedge the daemon.
pub fn run(prog: &str, args: &[&str], timeout: Duration) -> Output {
run_with_stdin(prog, args, None, timeout)
}
/// Like [`run`], but feeds `stdin` to the child's standard input.
/// (Wi-Fi secrets no longer go through here: `nm` sends them inside D-Bus
/// payloads, never on a command line.)
pub fn run_with_stdin(prog: &str, args: &[&str], stdin: Option<&str>, timeout: Duration) -> Output {
RUNNER.with(|r| r.borrow().run(prog, args, stdin, timeout))
}
pub fn run_ok(prog: &str, args: &[&str], timeout: Duration) -> bool {
run(prog, args, timeout).success
}
/// Swap the thread-local [`Runner`] for `runner` for the duration of `f`,
/// restoring whatever was previously installed afterward — even if `f`
/// panics, so a failing assertion inside a test can't leak a fake runner
/// into whatever test happens to run next on this thread. This is the seam
/// integration tests use to drive real logic without spawning subprocesses.
pub fn with_runner<R, T>(runner: R, f: impl FnOnce() -> T) -> T
where
R: Runner + 'static,
{
let prev = RUNNER.with(|r| std::mem::replace(&mut *r.borrow_mut(), Box::new(runner)));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
RUNNER.with(|r| *r.borrow_mut() = prev);
match result {
Ok(v) => v,
Err(payload) => std::panic::resume_unwind(payload),
}
}
fn spawn_run(prog: &str, args: &[&str], stdin: Option<&str>, timeout: Duration) -> Output {
let stdin_cfg = if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
};
let mut child = match Command::new(prog)
.args(args)
.stdin(stdin_cfg)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(c) => c,
Err(_) => return Output::failed(),
};
let mut stdout_pipe = child.stdout.take();
let mut stderr_pipe = child.stderr.take();
let out_handle = thread::spawn(move || {
let mut buf = String::new();
if let Some(ref mut p) = stdout_pipe {
let _ = p.read_to_string(&mut buf);
}
buf
});
let err_handle = thread::spawn(move || {
let mut buf = String::new();
if let Some(ref mut p) = stderr_pipe {
let _ = p.read_to_string(&mut buf);
}
buf
});
// Feed stdin only now that the reader threads are draining stdout and
// stderr: a chatty child could otherwise fill its stdout pipe while we
// block writing stdin, deadlocking both sides.
if let Some(data) = stdin {
if let Some(mut sink) = child.stdin.take() {
let _ = sink.write_all(data.as_bytes());
// Drop closes the pipe so the child's read sees EOF.
}
}
let start = Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(s)) => break Some(s),
Ok(None) => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
break None;
}
thread::sleep(Duration::from_millis(50));
}
Err(_) => break None,
}
};
let stdout = out_handle.join().unwrap_or_default();
let stderr = err_handle.join().unwrap_or_default();
Output {
success: status.map(|s| s.success()).unwrap_or(false),
stdout,
stderr,
}
}
/// Current local "HH:MM" (24h), for the time-of-day schedule. `None` if the
/// clock can't be read — the schedule is skipped, never guessed.
pub fn local_hhmm() -> Option<String> {
let o = run("date", &["+%H:%M"], Duration::from_secs(2));
if o.success {
let t = o.stdout.trim().to_string();
if t.len() == 5 && t.as_bytes()[2] == b':' {
return Some(t);
}
}
None
}
// `Output`, `run`, `run_with_stdin`, and `run_ok` used to be implemented
// directly in this module; that implementation was promoted verbatim into
// `bread_utils::proc` as the shared timeout-guarded subprocess runner for
// the whole ecosystem (several sibling repos shelled out with no timeout at
// all). Re-exported here so every existing `crate::util::{run, ...}` call
// site in this crate keeps working unchanged.
#[allow(unused_imports)] // Output isn't named directly elsewhere in this crate, but stays part of this module's public API.
pub use bread_utils::proc::{run, run_ok, run_with_stdin, Output};
/// Local "YYYY-MM-DD HH:MM:SS". Uses `date` for correct local time, falling
/// back to a dependency-free UTC computation if it is unavailable.
@ -265,39 +100,56 @@ mod tests {
}
#[test]
fn fmt_epoch_pre_1970_is_handled() {
// The div_euclid/rem_euclid split must stay correct for negative
// epoch seconds (dates before 1970), not just the common positive case.
fn fmt_epoch_year_2000_century_divisible_by_400_leap() {
// 2000-01-01 00:00:00 UTC — divisible by 400, so it IS a leap year.
assert_eq!(fmt_epoch(946_684_800), "2000-01-01 00:00:00");
}
#[test]
fn fmt_epoch_end_of_year_boundary() {
// 2023-12-31 23:59:59 UTC
assert_eq!(fmt_epoch(1_704_067_199), "2023-12-31 23:59:59");
}
#[test]
fn fmt_epoch_negative_before_unix_epoch() {
// 1969-12-31 23:59:59 UTC
assert_eq!(fmt_epoch(-1), "1969-12-31 23:59:59");
// 1969-12-31 00:00:00 UTC
assert_eq!(fmt_epoch(-86_400), "1969-12-31 00:00:00");
}
#[test]
fn fmt_epoch_year_and_month_boundaries() {
assert_eq!(fmt_epoch(1_704_067_199), "2023-12-31 23:59:59");
assert_eq!(fmt_epoch(1_735_689_600), "2025-01-01 00:00:00");
// Last second of October (non-leap-day month boundary).
assert_eq!(fmt_epoch(1_730_419_199), "2024-10-31 23:59:59");
fn fmt_epoch_february_non_leap_year_boundary() {
// 2023-02-28 00:00:00 UTC (2023 is not a leap year)
assert_eq!(fmt_epoch(1_677_542_400), "2023-02-28 00:00:00");
// 2023-03-01 00:00:00 UTC — next day after Feb 28 in non-leap year
assert_eq!(fmt_epoch(1_677_628_800), "2023-03-01 00:00:00");
}
#[test]
fn command_exists_false_for_bogus_binary() {
assert!(!command_exists("definitely-not-a-real-binary-xyz123"));
fn fmt_epoch_century_non_leap_year_1900_equivalent() {
// 1900 is NOT a leap year (div by 100 but not 400).
// 1900-03-01 00:00:00 UTC: days from epoch = (1900-1970)*365.25 ≈ use known anchor.
// 2100-02-28 00:00:00 UTC = epoch 4107456000; next day is Mar 1 (not Feb 29).
// We verify via the leap day boundary: 2100-02-28 + 86400 must be 2100-03-01.
assert_eq!(fmt_epoch(4_107_456_000), "2100-02-28 00:00:00");
assert_eq!(fmt_epoch(4_107_456_000 + 86_400), "2100-03-01 00:00:00");
}
#[test]
fn command_exists_true_for_a_real_binary() {
// `sh` is guaranteed present on any POSIX system this runs on.
assert!(command_exists("sh"));
fn fmt_epoch_midnight_vs_end_of_day() {
// 2022-06-15 00:00:00 UTC
assert_eq!(fmt_epoch(1_655_251_200), "2022-06-15 00:00:00");
// 2022-06-15 23:59:59 UTC
assert_eq!(fmt_epoch(1_655_337_599), "2022-06-15 23:59:59");
}
#[test]
fn run_on_missing_binary_fails_cleanly_instead_of_panicking() {
let o = run(
"definitely-not-a-real-binary-xyz123",
&[],
Duration::from_secs(1),
);
assert!(!o.success);
assert_eq!(o.stdout, "");
fn fmt_epoch_time_of_day_components() {
// 1970-01-01 01:02:03 UTC
assert_eq!(fmt_epoch(3723), "1970-01-01 01:02:03");
// 1970-01-01 23:59:59 UTC
assert_eq!(fmt_epoch(86_399), "1970-01-01 23:59:59");
}
}

View file

@ -1,266 +1,98 @@
use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::{Duration, Instant};
use bread_utils::bread_client::BreadClient;
use zbus::blocking::{Connection, Proxy};
use zbus::zvariant::OwnedValue;
use crate::bread_events;
use crate::backend::{Backend, System};
use crate::config::Config;
use crate::flow;
use crate::nm;
use crate::notify::{log, notify, Urgency};
use crate::state::{self, State};
use crate::state::State;
use crate::status::{self};
use crate::tailscale::TsHealth;
const NM_DEST: &str = "org.freedesktop.NetworkManager";
const NM_PATH: &str = "/org/freedesktop/NetworkManager";
const NM_IFACE: &str = "org.freedesktop.NetworkManager";
const DEV_IFACE: &str = "org.freedesktop.NetworkManager.Device";
const PROPS_IFACE: &str = "org.freedesktop.DBus.Properties";
/// Coarse health classification the watch loop reacts to each tick. `pub`
/// (and so is [`classify`]) purely so integration tests can drive the real
/// classification logic in-process against a faked [`crate::util::Runner`],
/// instead of only being able to observe it indirectly through the watch
/// loop's side effects.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Health {
enum Health {
Up,
DownNoNet,
/// Traffic is being intercepted — a captive/guest portal answered the
/// connectivity check with 200/301/302 instead of 204. Not something
/// reconnecting fixes; the user must sign in.
/// Associated, but a captive portal is intercepting traffic (manual login).
CaptivePortal,
DownTailscaleManual,
DownTailscaleOther,
NoAdapter,
/// `profile` isn't defined in the config (e.g. state still points at a
/// custom profile the user deleted from breadcrumbs.toml).
UnknownProfile,
}
impl Health {
/// Wire name used in `bread.crumbs.health.changed` — the Rust variant
/// as a string, not a prettier label.
pub fn as_str(&self) -> &'static str {
match self {
Health::Up => "Up",
Health::DownNoNet => "DownNoNet",
Health::CaptivePortal => "CaptivePortal",
Health::DownTailscaleManual => "DownTailscaleManual",
Health::DownTailscaleOther => "DownTailscaleOther",
Health::NoAdapter => "NoAdapter",
Health::UnknownProfile => "UnknownProfile",
}
}
}
/// Everything the watch loop needs to know about one health observation:
/// the classification plus the context used for events and notifications.
#[derive(Debug, Clone)]
pub struct Classification {
pub health: Health,
pub ssid: Option<String>,
pub iface: Option<String>,
pub ip: Option<String>,
pub tailscale: Option<TsHealth>,
pub exit_node: String,
}
pub fn classify(cfg: &Config, profile: &str) -> Classification {
// Checked before gather(): a profile missing from config would otherwise
// silently fall back to "tailscale not required" and read as healthy off
// of nothing but a bare internet check, never surfacing the misconfig.
if cfg.profile(profile).is_none() {
return Classification {
health: Health::UnknownProfile,
ssid: None,
iface: None,
ip: None,
tailscale: None,
exit_node: String::new(),
};
}
let s = status::gather(cfg, profile);
if s.iface.is_none() {
return Classification {
health: Health::NoAdapter,
ssid: None,
iface: None,
ip: None,
tailscale: None,
exit_node: s.exit_node,
};
}
let ssid = s.ssid.clone();
let health = if !s.internet {
if s.portal {
Health::CaptivePortal
} else {
Health::DownNoNet
}
fn classify(be: &dyn Backend, cfg: &Config, profile: &str) -> (Health, status::Status) {
let s = status::gather(be, cfg, profile);
let health = if s.iface.is_none() {
Health::NoAdapter
} else if s.portal.is_some() {
Health::CaptivePortal
} else if !s.internet {
Health::DownNoNet
} else if s.tailscale_required {
match s.tailscale {
Some(TsHealth::Ok) => Health::Up,
// NeedsLogin / NotInstalled / NoExitNode all need human action:
// a missing exit-node config can't be auto-fixed either.
Some(TsHealth::NeedsLogin)
| Some(TsHealth::NotInstalled)
| Some(TsHealth::NoExitNode) => Health::DownTailscaleManual,
Some(TsHealth::NeedsLogin) | Some(TsHealth::NotInstalled) => {
Health::DownTailscaleManual
}
Some(_) => Health::DownTailscaleOther,
None => Health::DownTailscaleManual,
}
} else {
Health::Up
};
Classification {
health,
ssid,
iface: s.iface,
ip: s.ip,
tailscale: s.tailscale,
exit_node: s.exit_node,
}
(health, s)
}
/// Whether a debounced signal is allowed to fire. `None` (never fired) always
/// fires; otherwise it fires only once more than `gap` has elapsed since the
/// last fire. Pulled out as a pure helper so the debounce logic is testable and
/// so the "first event fires immediately" case is expressed without the
/// panic-prone `Instant::now() - gap` seed.
fn debounce_ready(last: Option<Instant>, gap: Duration) -> bool {
last.map(|t| t.elapsed() > gap).unwrap_or(true)
}
/// Whether the flow-recovery cooldown has elapsed since the last `flow::run`
/// (or one never ran). Pure so the recovery pacing is unit-testable.
fn recovery_due(last_flow_at: Option<Instant>, now: Instant, cooldown_secs: u64) -> bool {
last_flow_at
.map(|t| now.duration_since(t).as_secs())
.unwrap_or(u64::MAX)
>= cooldown_secs
}
/// A wake signal for the watch loop. `SetProfile` is an *action* (applied on
/// the loop thread), `LinkChurn` is just "go look" — the distinction keeps
/// every config/state file access on the single loop thread, so the bread
/// subscription thread can never race the loop's own `Config::load`/`save`.
enum Wake {
LinkChurn,
SetProfile(String),
}
/// Whether a `PropertiesChanged` message on the NM root changes the
/// `Connectivity` property of the NetworkManager interface — the signal
/// that catches "still connected but lost the internet" (portal, DHCP
/// failure) without waiting out the poll interval.
fn props_changed_connectivity(msg: &zbus::Message) -> bool {
let Ok(body) = msg.body().deserialize::<(String, HashMap<String, OwnedValue>, Vec<String>)>() else {
return false;
};
body.0 == NM_IFACE && body.1.contains_key("Connectivity")
}
/// Subscribe to a D-Bus signal from NetworkManager and ping the channel for
/// each matching message, reconnecting on bus/NM restarts. One thread per
/// subscription (a handful at most); each owns its own connection so a dead
/// bus can't wedge the others.
fn spawn_signal_watcher<F>(tx: mpsc::Sender<Wake>, path: String, iface: &'static str, signal: &'static str, mut on_msg: F)
where
F: FnMut(&zbus::Message) -> bool + Send + 'static,
{
/// Tail `nmcli monitor` and ping the channel on link-state churn so we react
/// to drops within a second instead of waiting out the poll interval.
fn spawn_nm_monitor(tx: mpsc::Sender<()>) {
thread::spawn(move || loop {
let Ok(conn) = Connection::system() else {
thread::sleep(Duration::from_secs(10));
continue;
let child = Command::new("nmcli")
.arg("monitor")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn();
let mut child = match child {
Ok(c) => c,
Err(_) => {
thread::sleep(Duration::from_secs(10));
continue;
}
};
let Ok(proxy) = Proxy::new(&conn, NM_DEST, path.as_str(), iface) else {
thread::sleep(Duration::from_secs(10));
continue;
};
let Ok(mut iter) = proxy.receive_signal(signal) else {
thread::sleep(Duration::from_secs(10));
continue;
};
// `None` means "haven't fired yet, so fire on the first interesting
// signal". Storing an `Option` instead of seeding with
// `Instant::now() - 10s` avoids a panic: `Instant - Duration`
// underflows (and panics) when the monotonic clock is younger than
// the offset, which happens if `watch` starts within ~10s of boot —
// exactly when the systemd unit (ordered after graphical-session)
// tends to launch.
let mut last: Option<Instant> = None;
for msg in iter.by_ref() {
if on_msg(&msg) && debounce_ready(last, Duration::from_millis(1500)) {
last = Some(Instant::now());
let _ = tx.send(Wake::LinkChurn);
if let Some(out) = child.stdout.take() {
let reader = BufReader::new(out);
let mut last = Instant::now() - Duration::from_secs(10);
for line in reader.lines().map_while(Result::ok) {
let l = line.to_lowercase();
let interesting =
l.contains("disconnect") || l.contains("unavailable") || l.contains("failed");
if interesting && last.elapsed() > Duration::from_millis(1500) {
last = Instant::now();
let _ = tx.send(());
}
}
}
// Subscription died (NM or bus restart) — back off and resubscribe.
let _ = child.wait();
// monitor died (NM restart?) — back off and respawn.
thread::sleep(Duration::from_secs(5));
});
}
/// Subscribe to NetworkManager D-Bus signals and ping the channel on
/// link-state churn so we react to drops within a second instead of waiting
/// out the poll interval. Replaces the old `nmcli monitor` subprocess: the
/// same events are observed, but as structured D-Bus signals.
///
/// Watched signals:
/// - `PropertiesChanged` on the NM root object, filtered to the
/// `Connectivity` property — catches captive portals / DHCP failures that
/// keep the device "connected" while losing the internet;
/// - `DeviceAdded` / `DeviceRemoved` — hotplug;
/// - `Device.StateChanged` on every Wi-Fi device — drops and reconnects.
fn spawn_nm_monitor(tx: mpsc::Sender<Wake>) {
spawn_signal_watcher(
tx.clone(),
NM_PATH.to_string(),
PROPS_IFACE,
"PropertiesChanged",
props_changed_connectivity,
);
spawn_signal_watcher(tx.clone(), NM_PATH.to_string(), NM_IFACE, "DeviceAdded", |_| true);
spawn_signal_watcher(tx.clone(), NM_PATH.to_string(), NM_IFACE, "DeviceRemoved", |_| true);
// StateChanged on each Wi-Fi device. Devices added later (USB dongle
// hotplug) are caught by the DeviceAdded watcher waking the loop; the
// poll interval covers anything else.
for path in nm::wifi_device_paths() {
spawn_signal_watcher(tx.clone(), path, DEV_IFACE, "StateChanged", |_| true);
}
}
/// Sleep up to `dur`, but wake early if the D-Bus signal monitor signals
/// link churn or a `set_profile` command arrives. Returns the pending
/// action, if any.
fn wait_for_tick(rx: &Receiver<Wake>, dur: Duration) -> Option<Wake> {
/// Sleep up to `dur`, but wake early if `nmcli monitor` signals link churn.
fn wait_for_tick(rx: &Receiver<()>, dur: Duration) {
match rx.recv_timeout(dur) {
Ok(first) => {
// Drain any burst of churn signals so we don't re-fire
// immediately, but never drop a queued set_profile — it's an
// action, not a signal, and the earliest one wins.
let mut pending = match &first {
Wake::SetProfile(_) => Some(first),
Wake::LinkChurn => None,
};
while let Ok(w) = rx.try_recv() {
if pending.is_none() && matches!(&w, Wake::SetProfile(_)) {
pending = Some(w);
}
}
pending
Ok(()) => {
// Drain any burst of events so we don't re-fire immediately.
while rx.try_recv().is_ok() {}
}
Err(mpsc::RecvTimeoutError::Timeout) => None,
Err(mpsc::RecvTimeoutError::Timeout) => {}
// Monitor thread gone (shouldn't happen: we hold the sender) — fall
// back to a plain sleep so we don't busy-spin.
Err(mpsc::RecvTimeoutError::Disconnected) => {
thread::sleep(dur);
None
}
Err(mpsc::RecvTimeoutError::Disconnected) => thread::sleep(dur),
}
}
@ -273,112 +105,37 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
);
log("watch: started");
let (tx, rx) = mpsc::channel::<Wake>();
spawn_nm_monitor(tx.clone());
// Long-lived, so this uses BreadClient::subscribe (a persistent
// background thread with its own reconnect/backoff loop). breadd being
// absent or restarting is transparent: the subscription just quietly
// stops delivering commands until it reconnects. The callback only
// *validates* the command and forwards an action through the channel —
// it never touches config/state files itself (that would race this
// loop's own Config::load/save), so all file access stays on this one
// thread.
let bread = BreadClient::connect(bread_events::APP_ID);
let wake = tx;
let _commands = bread.subscribe("bread.command.crumbs.**", move |event| {
match bread_events::handle_command(&event) {
bread_events::CommandAction::SetProfile(name) => {
let _ = wake.send(Wake::SetProfile(name));
}
bread_events::CommandAction::Ignore => {}
}
});
let (tx, rx) = mpsc::channel::<()>();
spawn_nm_monitor(tx);
let be = System;
let mut profile = State::load(&cfg.settings.default_profile).profile;
if run_initial {
// Don't churn an already-working connection on (re)start.
let class = classify(&cfg, &profile);
if class.health == Health::Up {
let (h, _) = classify(&be, &cfg, &profile);
if h == Health::Up {
log(&format!(
"watch: already healthy on start (profile={profile}); skipping initial flow"
));
} else {
log(&format!("watch: initial flow for profile={profile}"));
let _ = flow::run_quiet(&mut cfg, &profile);
let _ = flow::run(&be, &cfg, &profile);
}
}
let mut prev_health: Option<Health> = None;
let mut prev_profile = profile.clone();
let mut prev_ssid: Option<String> = None;
let mut prev_ts: Option<&'static str> = None;
let mut fail_streak: u32 = 0;
let mut last_flow_at: Option<Instant> = None;
const FLOW_COOLDOWN: u64 = 20;
const RESUME_SLACK: Duration = Duration::from_secs(60);
const SCHEDULE_GRACE: Duration = Duration::from_secs(30 * 60);
let mut prev_wait = Duration::from_secs(base);
let mut last_tick_at = Instant::now();
// Tracks what the *schedule* last applied, so the loop can tell a
// manual `profile set` (CLI or bus) apart from its own switch and give
// manual changes a grace window before the schedule overrides them.
let mut last_schedule_applied: Option<String> = Some(profile.clone());
let mut manual_set_at: Option<Instant> = None;
loop {
// Reload config + state so edits and `profile set` take effect live.
// This always runs *before* `flow::run` below (never after, within
// the same tick), so a password `flow::run` clears-and-saves this
// iteration is durably on disk by the time the *next* iteration's
// reload runs. All config/state file access happens on this loop
// thread: `set_profile` commands from the bread bus are queued as
// [`Wake::SetProfile`] and applied here (see the bottom of the
// loop), never on the subscription thread.
if let Ok(fresh) = Config::load() {
cfg = fresh;
}
profile = State::load(&cfg.settings.default_profile).profile;
// Suspend/resume: the D-Bus signal monitor sees nothing while the
// machine sleeps, so a large wall-clock gap means the network state
// may have changed underneath us — allow an immediate recovery run
// instead of waiting out any remaining flow cooldown.
if last_tick_at.elapsed() > prev_wait + RESUME_SLACK {
log("watch: large gap since last tick (suspend/resume?) — forcing recovery check");
last_flow_at = None;
}
// Time-of-day schedule: switch to the scheduled profile when its
// window is active, unless the user manually set the profile within
// the grace window.
if last_schedule_applied.as_deref() != Some(profile.as_str()) {
// The persisted profile changed and it wasn't our own schedule
// switch — a manual set (CLI or bus). Start the grace window.
if last_schedule_applied.is_some() {
manual_set_at = Some(Instant::now());
}
last_schedule_applied = Some(profile.clone());
}
if let Some(sched) = scheduled_profile_now(&cfg) {
if sched != profile {
let grace_ok = manual_set_at
.map(|t| t.elapsed() >= SCHEDULE_GRACE)
.unwrap_or(true);
if grace_ok {
if state::set_profile(&cfg, &sched).is_ok() {
log(&format!("watch: schedule applied profile {sched}"));
last_schedule_applied = Some(sched.clone());
manual_set_at = None;
}
} else {
log(&format!(
"watch: schedule would switch to {sched}, but a manual set is still in grace"
));
}
}
}
let profile_changed = profile != prev_profile;
if profile_changed {
log(&format!(
@ -389,46 +146,14 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
&format!("{prev_profile} -> {profile}"),
Urgency::Low,
);
bread_events::emit_profile_changed(&bread, &prev_profile, &profile);
prev_profile = profile.clone();
prev_health = None; // force re-evaluation/recovery for new profile
prev_ssid = None; // a profile switch is a fresh network context
prev_ts = None;
last_flow_at = None; // allow immediate recovery on profile change
}
let class = classify(&cfg, &profile);
let health = class.health.clone();
let ssid = class.ssid.clone();
let (health, s) = classify(&be, &cfg, &profile);
let ssid = s.ssid.clone();
let transition = prev_health.as_ref() != Some(&health);
if transition {
bread_events::emit_health_changed(
&bread,
bread_events::HealthChanged {
profile: &profile,
health: health.as_str(),
ssid: ssid.as_deref(),
iface: class.iface.as_deref(),
ip: class.ip.as_deref(),
exit_node: &class.exit_node,
tailscale: class.tailscale.as_ref().map(|t| t.state_str()),
},
);
}
if class.ssid != prev_ssid {
bread_events::emit_network_changed(
&bread,
prev_ssid.as_deref(),
class.ssid.as_deref(),
&profile,
);
prev_ssid = class.ssid.clone();
}
let ts_state = class.tailscale.as_ref().map(|t| t.state_str());
if ts_state != prev_ts {
bread_events::emit_tailscale_changed(&bread, &profile, ts_state, &class.exit_node);
prev_ts = ts_state;
}
match &health {
Health::Up => {
@ -444,6 +169,18 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
}
fail_streak = 0;
}
Health::CaptivePortal => {
// Associated but gated behind a sign-in page we can't automate;
// notify once and don't hammer flow (reconnecting won't help).
if transition {
let body = match s.portal.as_deref().filter(|u| !u.is_empty()) {
Some(url) => format!("Sign in to continue: {url}"),
None => format!("Sign in to continue ({profile})."),
};
notify("breadcrumbs: captive portal", &body, Urgency::Normal);
}
fail_streak = 0;
}
Health::NoAdapter => {
if transition {
notify(
@ -454,56 +191,22 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
}
fail_streak = fail_streak.saturating_add(1);
}
Health::UnknownProfile => {
// flow::run() is quiet from here, so surface the misconfig
// ourselves — once per transition/change, not every tick.
if transition || profile_changed {
notify(
"breadcrumbs: unknown profile",
&format!("'{profile}' is not defined in breadcrumbs.toml"),
Urgency::Critical,
);
}
fail_streak = fail_streak.saturating_add(1);
}
Health::CaptivePortal => {
if transition {
notify(
"breadcrumbs: captive portal detected",
"Traffic is being intercepted — open a browser and sign in.",
Urgency::Normal,
);
}
// Reconnecting won't fix a portal; keep the poll fast (don't
// count it as a failure) so a successful sign-in is noticed
// promptly and the state flips back to Up.
fail_streak = 0;
}
Health::DownTailscaleManual => {
// Can't be auto-fixed (login / install / exit-node config).
// Notify once per transition.
// Can't be auto-fixed (login / not installed). Notify once.
if transition {
notify(
"Tailscale Error",
"Tailscale needs manual attention (login / install / \
exit node config). Other Wi-Fi automation paused \
until resolved.",
"Tailscale needs manual attention (login / install). \
Other Wi-Fi automation paused until resolved.",
Urgency::Critical,
);
}
// Re-attempt periodically and on the transition into this
// state: login may have completed since the last attempt, or
// the user may have missed the browser window. Quiet — a
// still-broken state must not re-notify on every retry.
if recovery_due(last_flow_at, Instant::now(), FLOW_COOLDOWN) {
let outcome = flow::run_quiet(&mut cfg, &profile);
// Re-run flow only on transition so we land on the bootstrap net.
if transition || profile_changed {
let _ = flow::run(&be, &cfg, &profile);
last_flow_at = Some(Instant::now());
fail_streak = if outcome.ok() {
0
} else {
fail_streak.saturating_add(1)
};
}
fail_streak = fail_streak.saturating_add(1);
}
Health::DownNoNet | Health::DownTailscaleOther => {
if transition {
@ -513,12 +216,15 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
Urgency::Normal,
);
}
if recovery_due(last_flow_at, Instant::now(), FLOW_COOLDOWN) {
let elapsed = last_flow_at
.map(|t| t.elapsed().as_secs())
.unwrap_or(u64::MAX);
if elapsed >= FLOW_COOLDOWN {
log(&format!(
"watch: down ({:?}) profile={profile} ssid={:?} — running flow",
health, ssid
));
let outcome = flow::run_quiet(&mut cfg, &profile);
let outcome = flow::run(&be, &cfg, &profile);
log(&format!("watch: recovery outcome = {:?}", outcome));
last_flow_at = Some(Instant::now());
fail_streak = if outcome.ok() {
@ -528,7 +234,7 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
};
} else {
log(&format!(
"watch: down ({:?}) — cooldown, skipping flow",
"watch: down ({:?}) — cooldown ({elapsed}s/{FLOW_COOLDOWN}s), skipping flow",
health
));
}
@ -540,101 +246,6 @@ pub fn run(mut cfg: Config, run_initial: bool) -> i32 {
// Adaptive backoff: healthy -> base; failing -> grow up to ~6x.
let mult = 1 + fail_streak.min(5);
let dur = Duration::from_secs(base * mult as u64);
prev_wait = dur;
last_tick_at = Instant::now();
// Apply a queued set_profile on this thread — the single owner of
// config/state file access — and emit the confirmation. The next
// iteration's reload sees the new profile and recovers accordingly.
if let Some(Wake::SetProfile(name)) = wait_for_tick(&rx, dur) {
bread_events::apply_set_profile(&name);
}
}
}
/// The profile a time-of-day schedule wants right now, if any. Returns
/// `None` when no schedule is configured or the local time can't be read.
fn scheduled_profile_now(cfg: &Config) -> Option<String> {
let hhmm = crate::util::local_hhmm()?;
let mins = crate::config::hhmm_to_minutes(&hhmm)?;
cfg.settings.scheduled_profile(mins)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debounce_fires_immediately_when_never_fired() {
// Regression guard for the old `Instant::now() - Duration::from_secs(10)`
// seed, which panicked near boot. `None` must fire without any
// subtraction on the clock.
assert!(debounce_ready(None, Duration::from_millis(1500)));
}
#[test]
fn debounce_suppresses_immediately_after_firing() {
let just_now = Instant::now();
assert!(!debounce_ready(Some(just_now), Duration::from_secs(3600)));
}
#[test]
fn debounce_fires_again_after_gap_elapses() {
// A zero gap is always already-elapsed, so a prior fire doesn't block.
let earlier = Instant::now();
assert!(debounce_ready(Some(earlier), Duration::from_millis(0)));
}
#[test]
fn health_as_str_is_the_variant_name() {
assert_eq!(Health::Up.as_str(), "Up");
assert_eq!(Health::DownNoNet.as_str(), "DownNoNet");
assert_eq!(Health::DownTailscaleManual.as_str(), "DownTailscaleManual");
assert_eq!(Health::DownTailscaleOther.as_str(), "DownTailscaleOther");
assert_eq!(Health::NoAdapter.as_str(), "NoAdapter");
assert_eq!(Health::UnknownProfile.as_str(), "UnknownProfile");
}
#[test]
fn wait_for_tick_returns_pending_set_profile_and_drains_churn() {
// A queued set_profile is an action, not a signal: it must survive
// the churn-burst drain and be returned to the loop.
let (tx, rx) = mpsc::channel::<Wake>();
let _ = tx.send(Wake::LinkChurn);
let _ = tx.send(Wake::SetProfile("home".into()));
let _ = tx.send(Wake::LinkChurn);
let wake = wait_for_tick(&rx, Duration::from_millis(10));
assert!(matches!(wake, Some(Wake::SetProfile(n)) if n == "home"));
// The burst was fully drained.
assert!(rx.try_recv().is_err());
}
#[test]
fn wait_for_tick_drains_churn_burst_without_action() {
// A burst of monitor signals collapses to one wake with no action.
let (tx, rx) = mpsc::channel::<Wake>();
let _ = tx.send(Wake::LinkChurn);
let _ = tx.send(Wake::LinkChurn);
let _ = tx.send(Wake::LinkChurn);
assert!(wait_for_tick(&rx, Duration::from_millis(10)).is_none());
assert!(rx.try_recv().is_err());
}
#[test]
fn wait_for_tick_times_out_with_no_signal() {
let (_tx, rx) = mpsc::channel::<Wake>();
assert!(wait_for_tick(&rx, Duration::from_millis(10)).is_none());
}
#[test]
fn recovery_due_fires_when_never_run_and_after_cooldown() {
// Never run → due immediately (the map() to u64::MAX path).
assert!(recovery_due(None, Instant::now(), 20));
// Just ran → not due again yet.
let now = Instant::now();
assert!(!recovery_due(Some(now), now, 20));
// A zero cooldown is always already-elapsed.
assert!(recovery_due(Some(now), now, 0));
wait_for_tick(&rx, dur);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,252 +0,0 @@
//! Shared test infrastructure for in-process integration tests (as opposed
//! to `tests/cli.rs`'s black-box `Sandbox`, which spawns the compiled
//! binary). This module is `mod`-included by each test file that needs it —
//! see `tests/flow_watch.rs`.
//!
//! Two pieces:
//!
//! - [`FakeRunner`]: a `breadcrumbs::util::Runner` implementation driven by
//! rules ("if the program+args match this predicate, return this canned
//! `Output`"), which also records every invocation so a test can assert
//! exactly what was — or, just as importantly, was *not* — passed (e.g.
//! that a password argument never reaches a fake subprocess).
//! - [`EnvSandbox`]: real logic (`flow::run`, `watch::classify`) still does
//! its own best-effort file logging via `notify::log`, which resolves a
//! path from `$HOME`/`$XDG_STATE_HOME`. `EnvSandbox` points those at a
//! throwaway tempdir for the duration of a test so nothing lands in the
//! developer's real `~/.local/state/breadcrumbs`. Mutating process env is
//! inherently cross-test-within-this-binary racy, so it's guarded by a
//! process-wide mutex — tests using it serialize against each other but
//! not against unrelated tests (each `tests/*.rs` file is its own binary).
//! - [`fake_nm`]: a real fake NetworkManager D-Bus service on a private
//! `dbus-daemon`. The production `nm` module talks to it over real D-Bus
//! marshalling (`Connection::system()` honors `DBUS_SYSTEM_BUS_ADDRESS`),
//! replacing the old fake-`nmcli`-argv rules.
#![allow(dead_code)] // not every test file uses every helper here
pub mod fake_nm;
use std::cell::RefCell;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use breadcrumbs::util::{Output, Runner};
/// One recorded call to the fake `Runner::run`.
#[derive(Debug, Clone)]
pub struct RecordedCall {
pub prog: String,
pub args: Vec<String>,
pub stdin: Option<String>,
}
impl RecordedCall {
/// Convenience for glob-style assertions, e.g.
/// `call.argv().contains(&"connection")`.
pub fn argv(&self) -> Vec<&str> {
std::iter::once(self.prog.as_str())
.chain(self.args.iter().map(String::as_str))
.collect()
}
}
type Matcher = Box<dyn Fn(&str, &[&str]) -> bool>;
type DynamicRule = (Matcher, Box<dyn Fn(&str, &[&str]) -> Output>);
/// A canned, rule-based [`Runner`]. Rules are tried in registration order;
/// the first whose matcher returns `true` supplies the response. No rule
/// matching falls back to [`Output::failed`] — the same "closed" default the
/// old empty-`PATH` sandbox relied on, so an un-anticipated call fails loud
/// (a wrong exit code) rather than silently returning success.
pub struct FakeRunner {
rules: Vec<(Matcher, Output)>,
dynamic_rules: Vec<DynamicRule>,
commands: HashSet<String>,
calls: Rc<RefCell<Vec<RecordedCall>>>,
}
impl FakeRunner {
pub fn new() -> Self {
FakeRunner {
rules: Vec::new(),
dynamic_rules: Vec::new(),
commands: HashSet::new(),
calls: Rc::new(RefCell::new(Vec::new())),
}
}
/// Handle to inspect recorded calls after the runner has been consumed by
/// [`breadcrumbs::util::with_runner`] (which takes it by value).
pub fn calls_handle(&self) -> Rc<RefCell<Vec<RecordedCall>>> {
self.calls.clone()
}
/// Make `breadcrumbs::util::command_exists(name)` report present.
pub fn with_command(mut self, name: &str) -> Self {
self.commands.insert(name.to_string());
self
}
/// Register a canned response: the first registered matcher that returns
/// `true` for a given `(prog, args)` supplies the `Output`.
pub fn on(mut self, matcher: impl Fn(&str, &[&str]) -> bool + 'static, output: Output) -> Self {
self.rules.push((Box::new(matcher), output));
self
}
/// Shorthand for matching on `prog` plus a whitespace-joined view of
/// `args` containing `substr` (handy for `tailscale`/`curl` calls, whose
/// interesting bit is usually a subcommand somewhere in the middle).
pub fn on_contains(self, prog: &'static str, substr: &'static str, output: Output) -> Self {
self.on(
move |p, args| p == prog && args.join(" ").contains(substr),
output,
)
}
/// Register a rule whose *response* is computed at call time (rather
/// than canned), enabling stateful fakes — e.g. answering "which SSID is
/// active?" with the SSID of the most recently dialed connection.
/// Dynamic rules are tried after the static ones.
pub fn on_dynamic(
mut self,
matcher: impl Fn(&str, &[&str]) -> bool + 'static,
out: impl Fn(&str, &[&str]) -> Output + 'static,
) -> Self {
self.dynamic_rules
.push((Box::new(matcher), Box::new(out)));
self
}
}
impl Default for FakeRunner {
fn default() -> Self {
Self::new()
}
}
impl Runner for FakeRunner {
fn run(&self, prog: &str, args: &[&str], stdin: Option<&str>, _timeout: Duration) -> Output {
self.calls.borrow_mut().push(RecordedCall {
prog: prog.to_string(),
args: args.iter().map(|s| s.to_string()).collect(),
stdin: stdin.map(|s| s.to_string()),
});
for (matcher, out) in &self.rules {
if matcher(prog, args) {
return out.clone();
}
}
for (matcher, out) in &self.dynamic_rules {
if matcher(prog, args) {
return out(prog, args);
}
}
Output::failed()
}
fn command_exists(&self, name: &str) -> bool {
self.commands.contains(name)
}
}
pub fn ok(stdout: &str) -> Output {
Output {
success: true,
stdout: stdout.to_string(),
stderr: String::new(),
}
}
pub fn ok_empty() -> Output {
ok("")
}
pub fn fail(stderr: &str) -> Output {
Output {
success: false,
stdout: String::new(),
stderr: stderr.to_string(),
}
}
fn env_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
static SANDBOX_COUNTER: AtomicU32 = AtomicU32::new(0);
/// Points `HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME` at a throwaway
/// tempdir for its lifetime, so any real filesystem side effect
/// (`notify::log`'s best-effort log file, `Config::save`, …) that in-process
/// logic performs during a test lands there instead of the developer's real
/// home directory. Holds a process-wide lock for its lifetime — construct
/// one per test, drop it (or let it go out of scope) before the test ends.
pub struct EnvSandbox {
_guard: MutexGuard<'static, ()>,
root: PathBuf,
prev: Vec<(&'static str, Option<String>)>,
}
const ENV_VARS: [&str; 3] = ["HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME"];
impl EnvSandbox {
pub fn new() -> Self {
let guard = env_lock().lock().unwrap_or_else(|e| e.into_inner());
let n = SANDBOX_COUNTER.fetch_add(1, Ordering::SeqCst);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!(
"breadcrumbs-inproc-{}-{}-{}",
std::process::id(),
n,
nanos
));
std::fs::create_dir_all(&root).expect("create EnvSandbox root");
let prev: Vec<(&'static str, Option<String>)> = ENV_VARS
.iter()
.map(|v| (*v, std::env::var(v).ok()))
.collect();
std::env::set_var("HOME", &root);
std::env::set_var("XDG_CONFIG_HOME", root.join("config"));
std::env::set_var("XDG_STATE_HOME", root.join("state"));
EnvSandbox {
_guard: guard,
root,
prev,
}
}
pub fn root(&self) -> &Path {
&self.root
}
}
impl Default for EnvSandbox {
fn default() -> Self {
Self::new()
}
}
impl Drop for EnvSandbox {
fn drop(&mut self) {
for (k, v) in &self.prev {
match v {
Some(val) => std::env::set_var(k, val),
None => std::env::remove_var(k),
}
}
let _ = std::fs::remove_dir_all(&self.root);
}
}

View file

@ -1,968 +0,0 @@
//! In-process tests for the actual state machine (`flow::run`) and the watch
//! loop's health classification (`watch::classify`). NetworkManager is a real
//! fake NM D-Bus service on a private bus (see `tests/common::fake_nm`), so
//! every `nm` call is exercised over genuine D-Bus marshalling. Everything
//! else (tailscale, curl/ping, notify) is faked through a
//! `breadcrumbs::util::Runner` (see `tests/common`). This complements
//! `tests/cli.rs`'s black-box coverage (which spawns the real binary) with
//! fast, precise coverage of the logic itself: candidate priority order, the
//! bootstrap+Tailscale gate, and every `watch::Health` transition.
mod common;
use std::collections::BTreeMap;
use bread_utils::bread_client::BreadEvent;
use breadcrumbs::bread_events;
use breadcrumbs::config::{Config, NetworkDef, Profile, Settings};
use breadcrumbs::flow;
use breadcrumbs::state::{self, State};
use breadcrumbs::util::with_runner;
use breadcrumbs::watch::{classify, Health};
use common::fake_nm::{self, Security, SharedNm};
use common::{fail, ok, EnvSandbox, FakeRunner};
fn net(ssid: &str, password: Option<&str>) -> NetworkDef {
NetworkDef {
ssid: ssid.to_string(),
password: password.map(str::to_string),
dns: None,
eap: None,
identity: None,
ca_cert: None,
hidden: false,
}
}
fn hidden_net(ssid: &str, password: Option<&str>) -> NetworkDef {
NetworkDef {
ssid: ssid.to_string(),
password: password.map(str::to_string),
dns: None,
eap: None,
identity: None,
ca_cert: None,
hidden: true,
}
}
fn base_config() -> Config {
Config {
settings: Settings::default(),
networks: Vec::new(),
profiles: BTreeMap::new(),
}
}
/// Reset the shared fake-NM bus and put a Wi-Fi device on it with one AP per
/// SSID at the given signal strength. Returns the bus guard (held for the
/// whole test so tests serialize) and the device path.
fn setup_wifi(ssids: &[(&str, u8)]) -> (SharedNm, String) {
let nm = fake_nm::shared();
nm.reset();
let dev = nm.add_wifi_device("wlan0", 100);
for (ssid, strength) in ssids {
nm.add_ap(&dev, ssid, *strength, Security::Wpa2);
}
(nm, dev)
}
/// A runner that fakes the non-NM subprocesses a successful `flow::run`
/// needs: curl (internet check) and nothing else.
fn healthy_runner() -> FakeRunner {
FakeRunner::new()
.with_command("curl")
.on(|prog, _| prog == "curl", ok("204"))
}
/// The runner used by `classify` tests: internet check + optional tailscale.
fn classify_runner(curl: &str, tailscale_status: Option<&str>) -> FakeRunner {
let mut r = FakeRunner::new().with_command("curl").on(|p, _| p == "curl", ok(curl));
if let Some(json) = tailscale_status {
r = r
.with_command("tailscale")
.on(|p, args| p == "tailscale" && args.contains(&"status"), ok(json));
}
r
}
/// Make the device report being associated with `ssid` (for classify tests).
fn associate(nm: &SharedNm, dev: &str, ssid: &str) {
let ap = nm.add_ap(dev, ssid, 80, Security::Wpa2);
nm.set_active_ap(dev, &ap);
}
fn tailscale_json_ok(exit_node: &str) -> String {
format!(
r#"{{"BackendState":"Running","Peer":{{"k1":{{"HostName":"{exit_node}","DNSName":"{exit_node}.ts.net.","Online":true,"ExitNode":true,"ExitNodeOption":true}}}}}}"#
)
}
fn tailscale_json_missing() -> &'static str {
r#"{"BackendState":"Running","Peer":{}}"#
}
// ---------------------------------------------------------------------
// flow::run — candidate priority (pass 1 / pass 2)
// ---------------------------------------------------------------------
#[test]
fn flow_run_connects_to_first_visible_candidate_in_priority_order() {
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("First", 80), ("Second", 80)]);
let mut cfg = base_config();
cfg.networks = vec![net("First", Some("pw1")), net("Second", Some("pw2"))];
cfg.profiles.insert(
"home".into(),
Profile {
networks: vec!["First".into(), "Second".into()],
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "home"));
match outcome {
flow::Outcome::Connected { ssid, note } => {
assert_eq!(ssid, "First");
assert_eq!(note, None);
}
other => panic!("expected Connected, got {other:?}"),
}
// Priority order actually mattered: "Second" was never activated even
// though it was visible and would have succeeded too.
assert_eq!(
nm.activated_ssids(),
vec!["First".to_string()],
"Second must not be dialed when First wins"
);
// The password used for the winning connect is now NM's problem, not
// breadcrumbs' — cleared and (via clear_password_if_used) persisted.
assert_eq!(cfg.network("First").unwrap().password, None);
// Never touched, so its password is untouched too.
assert_eq!(
cfg.network("Second").unwrap().password,
Some("pw2".to_string())
);
}
#[test]
fn flow_run_pass2_falls_back_to_hidden_candidate_not_in_scan() {
let _env = EnvSandbox::new();
// Nothing is visible; connecting creates the AP on the fly (hidden
// networks appear only after association).
let (nm, _dev) = setup_wifi(&[]);
nm.set_connect_any(true);
let mut cfg = base_config();
// "Ghost" is neither visible nor hidden, so pass 1 *and* pass 2 both
// skip it outright — it should never be dialed.
cfg.networks = vec![net("Ghost", Some("pw-ghost")), hidden_net("Shadow", Some("pw-shadow"))];
cfg.profiles.insert(
"away".into(),
Profile {
networks: vec!["Ghost".into(), "Shadow".into()],
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "away"));
match outcome {
flow::Outcome::Connected { ssid, .. } => assert_eq!(ssid, "Shadow"),
other => panic!("expected Connected to Shadow, got {other:?}"),
}
assert_eq!(
nm.activated_ssids(),
vec!["Shadow".to_string()],
"Ghost must never have been dialed"
);
}
#[test]
fn flow_run_unknown_profile_short_circuits_before_touching_nm() {
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset();
let mut cfg = base_config();
let runner = FakeRunner::new(); // no rules at all
let outcome = with_runner(runner, || flow::run(&mut cfg, "does-not-exist"));
assert!(matches!(outcome, flow::Outcome::UnknownProfile(p) if p == "does-not-exist"));
// The fake NetworkManager must never be touched for a profile that
// doesn't exist (no devices, no scans, no activations).
assert!(
nm.calls().is_empty(),
"unknown-profile path should never call NetworkManager: {:?}",
nm.calls()
);
}
// ---------------------------------------------------------------------
// flow::run — bootstrap + Tailscale gating
// ---------------------------------------------------------------------
#[test]
fn flow_run_moves_past_bootstrap_once_tailscale_is_healthy() {
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("Guest", 80), ("Corp", 80)]);
let mut cfg = base_config();
cfg.settings.exit_node = "exitnode".into();
cfg.networks = vec![net("Guest", Some("guest-pw")), net("Corp", Some("corp-pw"))];
cfg.profiles.insert(
"work".into(),
Profile {
bootstrap: Some("Guest".into()),
networks: vec!["Corp".into()],
tailscale: true,
..Default::default()
},
);
let runner = healthy_runner()
.with_command("tailscale")
.on_contains("tailscale", "status", ok(&tailscale_json_ok("exitnode")))
.on_contains("tailscale", "set", ok(""));
let outcome = with_runner(runner, || flow::run(&mut cfg, "work"));
match outcome {
flow::Outcome::Connected { ssid, .. } => assert_eq!(ssid, "Corp"),
other => panic!("expected Connected to Corp, got {other:?}"),
}
// Both the bootstrap and target connects used a local password, so both
// should have been cleared once NetworkManager took over.
assert_eq!(cfg.network("Guest").unwrap().password, None);
assert_eq!(cfg.network("Corp").unwrap().password, None);
assert_eq!(
nm.activated_ssids(),
vec!["Guest".to_string(), "Corp".to_string()],
"bootstrap must be dialed before the target"
);
}
#[test]
fn flow_run_stays_on_bootstrap_and_never_dials_target_when_tailscale_unhealthy() {
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("Guest", 80), ("Corp", 80)]);
let mut cfg = base_config();
cfg.settings.exit_node = "exitnode".into();
cfg.networks = vec![net("Guest", Some("guest-pw")), net("Corp", Some("corp-pw"))];
cfg.profiles.insert(
"work".into(),
Profile {
bootstrap: Some("Guest".into()),
networks: vec!["Corp".into()],
tailscale: true,
..Default::default()
},
);
let runner = healthy_runner()
.with_command("tailscale")
.on(|p, args| p == "tailscale" && args.contains(&"status"), ok(tailscale_json_missing()))
.on(|p, args| p == "tailscale" && args.contains(&"set"), ok(""));
let outcome = with_runner(runner, || flow::run(&mut cfg, "work"));
match &outcome {
flow::Outcome::TailscaleError { ssid, health } => {
assert_eq!(ssid.as_deref(), Some("Guest"));
assert_eq!(*health, breadcrumbs::tailscale::TsHealth::ExitNodeMissing);
}
other => panic!("expected TailscaleError, got {other:?}"),
}
assert_eq!(
nm.activated_ssids(),
vec!["Guest".to_string()],
"target network must never be dialed while Tailscale is unhealthy"
);
// The bootstrap connect *did* use a password and succeeded, so it's
// cleared even though the overall flow ends in an error.
assert_eq!(cfg.network("Guest").unwrap().password, None);
}
// ---------------------------------------------------------------------
// watch::classify — health-state transitions
// ---------------------------------------------------------------------
#[test]
fn classify_reports_unknown_profile_without_touching_nm() {
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset();
let cfg = base_config(); // no profiles at all
let runner = FakeRunner::new();
let calls = runner.calls_handle();
let class = with_runner(runner, || classify(&cfg, "ghost"));
assert_eq!(class.health, Health::UnknownProfile);
assert_eq!(class.ssid, None);
assert!(calls.borrow().is_empty());
assert!(
nm.calls().is_empty(),
"unknown-profile classify must not touch NetworkManager"
);
}
#[test]
fn classify_reports_no_adapter_when_wifi_interface_absent() {
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset(); // no devices at all
let mut cfg = base_config();
cfg.profiles.insert("away".into(), Profile::default());
let class = with_runner(FakeRunner::new(), || classify(&cfg, "away"));
assert_eq!(class.health, Health::NoAdapter);
}
#[test]
fn classify_reports_down_no_net_when_internet_check_fails() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "HomeWifi");
let mut cfg = base_config();
cfg.profiles.insert("away".into(), Profile::default());
let runner = FakeRunner::new().on(|prog, _| prog == "curl" || prog == "ping", fail(""));
let class = with_runner(runner, || classify(&cfg, "away"));
assert_eq!(class.health, Health::DownNoNet);
assert_eq!(class.ssid, Some("HomeWifi".to_string()));
}
#[test]
fn classify_reports_up_when_healthy_and_tailscale_not_required() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "HomeWifi");
let mut cfg = base_config();
cfg.profiles.insert("home".into(), Profile::default()); // tailscale: false
let class = with_runner(healthy_runner(), || classify(&cfg, "home"));
assert_eq!(class.health, Health::Up);
assert_eq!(class.ssid, Some("HomeWifi".to_string()));
}
#[test]
fn classify_reports_down_tailscale_manual_when_not_installed() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "CorpWifi");
let mut cfg = base_config();
cfg.profiles.insert(
"work".into(),
Profile {
tailscale: true,
..Default::default()
},
);
// No `with_command("tailscale")`, so `tailscale::installed()` is false.
let class = with_runner(healthy_runner(), || classify(&cfg, "work"));
assert_eq!(class.health, Health::DownTailscaleManual);
}
#[test]
fn classify_reports_down_tailscale_manual_when_needs_login() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "CorpWifi");
let mut cfg = base_config();
cfg.profiles.insert(
"work".into(),
Profile {
tailscale: true,
..Default::default()
},
);
let runner = classify_runner("204", Some(r#"{"BackendState":"NeedsLogin"}"#));
let class = with_runner(runner, || classify(&cfg, "work"));
assert_eq!(class.health, Health::DownTailscaleManual);
}
#[test]
fn classify_reports_down_tailscale_other_when_exit_node_offline() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "CorpWifi");
let mut cfg = base_config();
cfg.settings.exit_node = "exitnode".into();
cfg.profiles.insert(
"work".into(),
Profile {
tailscale: true,
..Default::default()
},
);
let json = r#"{"BackendState":"Running","Peer":{"k1":{"HostName":"exitnode","Online":false,"ExitNode":false,"ExitNodeOption":true}}}"#;
let runner = classify_runner("204", Some(json));
let class = with_runner(runner, || classify(&cfg, "work"));
assert_eq!(class.health, Health::DownTailscaleOther);
}
#[test]
fn classify_reports_up_when_tailscale_healthy() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "CorpWifi");
let mut cfg = base_config();
cfg.settings.exit_node = "exitnode".into();
cfg.profiles.insert(
"work".into(),
Profile {
tailscale: true,
..Default::default()
},
);
let runner = classify_runner("204", Some(&tailscale_json_ok("exitnode")));
let class = with_runner(runner, || classify(&cfg, "work"));
assert_eq!(class.health, Health::Up);
}
// ---------------------------------------------------------------------
// bread.command.crumbs.set_profile — persists via the same path as the
// CLI, and must not depend on breadd being reachable (`emit` is
// fire-and-forget).
// ---------------------------------------------------------------------
fn command_event(event: &str, data: serde_json::Value) -> BreadEvent {
BreadEvent {
event: event.to_string(),
timestamp: 0,
data,
}
}
#[test]
fn set_profile_command_persists_even_with_no_daemon_reachable() {
let _env = EnvSandbox::new();
let cfg = Config::load().expect("fresh config");
state::set_profile(&cfg, "away").unwrap();
assert_eq!(State::load("away").profile, "away");
// handle_command only parses/validates (no file I/O on the subscription
// thread); the loop thread then applies the action.
let action = bread_events::handle_command(&command_event(
"bread.command.crumbs.set_profile",
serde_json::json!({ "profile": "home" }),
));
assert!(
matches!(action, bread_events::CommandAction::SetProfile(n) if n == "home"),
"a known profile must yield a SetProfile action"
);
bread_events::apply_set_profile("home");
assert_eq!(State::load("away").profile, "home");
}
#[test]
fn set_profile_command_rejects_unknown_profile() {
let _env = EnvSandbox::new();
let cfg = Config::load().expect("fresh config");
state::set_profile(&cfg, "away").unwrap();
let action = bread_events::handle_command(&command_event(
"bread.command.crumbs.set_profile",
serde_json::json!({ "profile": "bogus" }),
));
assert!(matches!(action, bread_events::CommandAction::SetProfile(n) if n == "bogus"));
// The rejection happens when the loop thread applies it: state is
// untouched and the failure event is emitted (a no-op without breadd).
bread_events::apply_set_profile("bogus");
assert_eq!(
State::load("away").profile,
"away",
"a rejected set_profile must not touch state"
);
}
#[test]
fn set_profile_command_rejects_missing_profile_field() {
let _env = EnvSandbox::new();
let cfg = Config::load().expect("fresh config");
state::set_profile(&cfg, "away").unwrap();
let action = bread_events::handle_command(&command_event(
"bread.command.crumbs.set_profile",
serde_json::json!({}),
));
assert!(matches!(action, bread_events::CommandAction::Ignore));
assert_eq!(State::load("away").profile, "away");
}
#[test]
fn handle_command_ignores_unrecognized_verb() {
let _env = EnvSandbox::new();
let cfg = Config::load().expect("fresh config");
state::set_profile(&cfg, "away").unwrap();
let action = bread_events::handle_command(&command_event(
"bread.command.crumbs.pin",
serde_json::json!({}),
));
assert!(matches!(action, bread_events::CommandAction::Ignore));
assert_eq!(
State::load("away").profile,
"away",
"an unrecognized verb must not touch state"
);
}
#[test]
fn handle_command_ignores_events_outside_its_own_command_namespace() {
let _env = EnvSandbox::new();
let cfg = Config::load().expect("fresh config");
state::set_profile(&cfg, "away").unwrap();
assert!(matches!(
bread_events::handle_command(&command_event(
"bread.command.clip.clear",
serde_json::json!({}),
)),
bread_events::CommandAction::Ignore
));
assert!(matches!(
bread_events::handle_command(&command_event(
"bread.crumbs.profile.changed",
serde_json::json!({ "from": "away", "to": "home" }),
)),
bread_events::CommandAction::Ignore
));
assert_eq!(State::load("away").profile, "away");
}
// ---------------------------------------------------------------------
// Regression tests for the audit fixes.
// ---------------------------------------------------------------------
#[test]
fn flow_run_reports_no_exit_node_and_never_clears_selection() {
// A tailscale profile with no exit node configured must report
// TsHealth::NoExitNode — and must never run `tailscale set --exit-node=`
// with an empty value, which would clear the user's current selection.
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("Corp", 80)]);
let mut cfg = base_config();
cfg.networks = vec![net("Corp", Some("corp-pw"))];
cfg.profiles.insert(
"work".into(),
Profile {
networks: vec!["Corp".into()],
tailscale: true,
..Default::default()
},
);
let runner = FakeRunner::new().with_command("tailscale");
let calls = runner.calls_handle();
let outcome = with_runner(runner, || flow::run(&mut cfg, "work"));
match &outcome {
flow::Outcome::TailscaleError { health, .. } => {
assert_eq!(*health, breadcrumbs::tailscale::TsHealth::NoExitNode);
}
other => panic!("expected TailscaleError(NoExitNode), got {other:?}"),
}
assert!(
!calls.borrow().iter().any(|c| c.prog == "tailscale"),
"with no exit node configured, tailscale must not be touched: {:?}",
calls.borrow()
);
assert!(
nm.activated_ssids().is_empty(),
"with no exit node configured, no network must be dialed: {:?}",
nm.activated_ssids()
);
}
#[test]
fn classify_reports_down_tailscale_manual_when_no_exit_node_configured() {
// An unset exit node needs human action (config edit), so it must
// classify as DownTailscaleManual — not DownTailscaleOther, which would
// make the watcher spin auto-recovery forever.
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "CorpWifi");
let mut cfg = base_config();
cfg.profiles.insert(
"work".into(),
Profile {
tailscale: true,
..Default::default()
},
);
let runner = classify_runner("204", None).with_command("tailscale");
let class = with_runner(runner, || classify(&cfg, "work"));
assert_eq!(class.health, Health::DownTailscaleManual);
assert_eq!(class.ssid, Some("CorpWifi".to_string()));
}
#[test]
fn ensure_exit_node_attempts_to_start_unreachable_daemon() {
// `tailscale status --json` with empty stdout is the "daemon not
// running" signature (the error goes to stderr). ensure_exit_node must
// try `tailscale up` and re-read instead of bailing out with an opaque
// error — the old dead-code path that made the Stopped recovery
// unreachable.
let _env = EnvSandbox::new();
let runner = FakeRunner::new()
.with_command("tailscale")
.on(|p, args| p == "tailscale" && args.contains(&"status"), ok(""))
.on(|p, args| p == "tailscale" && args.contains(&"up"), ok(""));
let calls = runner.calls_handle();
let health = with_runner(runner, || {
breadcrumbs::tailscale::ensure_exit_node(&["exitnode".to_string()])
});
assert!(
matches!(health, breadcrumbs::tailscale::TsHealth::Error(_)),
"daemon still unreachable after `up` → Error, got {health:?}"
);
let tailscale_calls: Vec<String> = calls
.borrow()
.iter()
.filter(|c| c.prog == "tailscale")
.map(|c| c.args.join(" "))
.collect();
assert!(
tailscale_calls.iter().any(|c| c.starts_with("up")),
"must attempt `tailscale up` when the daemon is unreachable: {tailscale_calls:?}"
);
}
#[test]
fn flow_run_fails_when_device_lands_on_wrong_ssid() {
// NM autoconnect race: the connect succeeds but the device ends up on a
// *different* network than requested. flow must not report Connected to
// the requested SSID, and must not clear its password.
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("First", 80), ("OtherNet", 90)]);
nm.set_land_on(Some("OtherNet"));
let mut cfg = base_config();
cfg.networks = vec![net("First", Some("pw1"))];
cfg.profiles.insert(
"home".into(),
Profile {
networks: vec!["First".into()],
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "home"));
assert!(
!matches!(outcome, flow::Outcome::Connected { .. }),
"must not report Connected when the device is on a different SSID: {outcome:?}"
);
assert_eq!(
cfg.network("First").unwrap().password,
Some("pw1".to_string()),
"password must not be cleared for a network that was never joined"
);
}
#[test]
fn run_quiet_suppresses_notifications_that_run_emits() {
// The watch loop calls flow::run_quiet so a persistent failure doesn't
// re-notify on every retry; the CLI keeps flow::run's notifications.
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset();
let mut cfg = base_config(); // no profiles → UnknownProfile path notifies
let runner = FakeRunner::new().with_command("notify-send");
let calls = runner.calls_handle();
with_runner(runner, || flow::run_quiet(&mut cfg, "ghost"));
assert!(
!calls.borrow().iter().any(|c| c.prog == "notify-send"),
"run_quiet must not fire desktop notifications: {:?}",
calls.borrow()
);
let runner = FakeRunner::new().with_command("notify-send");
let calls = runner.calls_handle();
with_runner(runner, || flow::run(&mut cfg, "ghost"));
assert!(
calls.borrow().iter().any(|c| c.prog == "notify-send"),
"run (CLI path) must still notify: {:?}",
calls.borrow()
);
}
#[test]
fn internet_ok_requires_204_and_falls_back_to_ping() {
// Only 204 counts as internet: captive/guest portals answer 200/301/302
// with a login page or redirect, so those must not report healthy.
let _env = EnvSandbox::new();
let cfg = base_config();
let r = FakeRunner::new().with_command("curl").on(|p, _| p == "curl", ok("204"));
assert!(with_runner(r, || breadcrumbs::status::internet_ok(&cfg)));
for code in ["200", "301", "302"] {
let r = FakeRunner::new()
.with_command("curl")
.on(|p, _| p == "curl", ok(code))
.on(|p, _| p == "ping", fail(""));
assert!(
!with_runner(r, || breadcrumbs::status::internet_ok(&cfg)),
"{code} must not count as internet"
);
}
// curl absent → the ping fallback decides.
let r = FakeRunner::new().with_command("ping").on(|p, _| p == "ping", ok(""));
assert!(with_runner(r, || breadcrumbs::status::internet_ok(&cfg)));
}
#[test]
fn scan_list_dedups_by_ssid_keeping_strongest_signal() {
// One entry per SSID, at its strongest signal (not the first, possibly
// weak, listing). Hidden (empty-SSID) APs are skipped.
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
nm.add_ap(&dev, "Cafe", 40, Security::Wpa2);
nm.add_ap(&dev, "Cafe", 80, Security::Wpa2);
nm.add_ap(&dev, "Office", 60, Security::Wpa3);
nm.add_ap(&dev, "Cafe", 90, Security::Wpa2);
let list = breadcrumbs::nm::scan_list("wlan0");
assert_eq!(list.len(), 2, "dedup by SSID: {list:?}");
let cafe = list.iter().find(|e| e.ssid == "Cafe").unwrap();
assert_eq!(cafe.signal, "90", "strongest signal wins");
let office = list.iter().find(|e| e.ssid == "Office").unwrap();
assert_eq!(office.signal, "60");
assert_eq!(office.security, "WPA3");
}
// ---------------------------------------------------------------------
// New features: signal-aware selection, per-network DNS, learning,
// captive portals, exit-node failover, preferred interface, enterprise
// (802.1x) connect.
// ---------------------------------------------------------------------
#[test]
fn flow_run_prefers_strongest_visible_signal_over_priority_order() {
let _env = EnvSandbox::new();
// "Weak" is listed first (higher priority), but "Strong" has the better
// signal — signal-aware selection must dial Strong first.
let (nm, _dev) = setup_wifi(&[("Weak", 40), ("Strong", 90)]);
let mut cfg = base_config();
cfg.networks = vec![net("Weak", Some("pw1")), net("Strong", Some("pw2"))];
cfg.profiles.insert(
"home".into(),
Profile {
networks: vec!["Weak".into(), "Strong".into()],
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "home"));
match &outcome {
flow::Outcome::Connected { ssid, .. } => assert_eq!(ssid, "Strong"),
other => panic!("expected Connected to Strong, got {other:?}"),
}
assert_eq!(
nm.activated_ssids(),
vec!["Strong".to_string()],
"the stronger network must be dialed, and only it"
);
}
#[test]
fn flow_run_pins_per_network_dns_override() {
let _env = EnvSandbox::new();
let (nm, _dev) = setup_wifi(&[("Home", 80)]);
let mut cfg = base_config();
cfg.settings.dns = "1.1.1.1".into();
let mut def = net("Home", Some("pw"));
def.dns = Some("9.9.9.9".into());
cfg.networks = vec![def];
cfg.profiles.insert(
"home".into(),
Profile {
networks: vec!["Home".into()],
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "home"));
assert!(matches!(outcome, flow::Outcome::Connected { .. }));
// The DNS-pinned profile must carry the per-network override, not the
// global 1.1.1.1.
let st = nm.state.lock().unwrap();
let conn = st.connections.values().next().expect("a profile was saved");
let dns = conn
.get("ipv4")
.and_then(|m| m.get("dns"))
.and_then(fake_nm::value_str_list);
assert_eq!(dns, Some(vec!["9.9.9.9".to_string()]));
}
#[test]
fn flow_run_appends_learned_ssid_to_detect_ssids() {
let _env = EnvSandbox::new();
let (_nm, _dev) = setup_wifi(&[("Home", 80)]);
let mut cfg = base_config();
cfg.networks = vec![net("Home", Some("pw"))];
cfg.profiles.insert(
"home".into(),
Profile {
networks: vec!["Home".into()],
learn: true,
..Default::default()
},
);
let outcome = with_runner(healthy_runner(), || flow::run(&mut cfg, "home"));
assert!(matches!(outcome, flow::Outcome::Connected { .. }));
assert_eq!(
cfg.profile("home").unwrap().detect_ssids,
vec!["Home".to_string()],
"a successful connect on a learn=true profile must record the SSID"
);
}
#[test]
fn classify_reports_captive_portal_when_connectivity_returns_200() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
associate(&nm, &dev, "HomeWifi");
let mut cfg = base_config();
cfg.profiles.insert("home".into(), Profile::default());
let runner = classify_runner("200", None);
let class = with_runner(runner, || classify(&cfg, "home"));
assert_eq!(class.health, Health::CaptivePortal);
assert_eq!(class.ssid, Some("HomeWifi".to_string()));
}
#[test]
fn ensure_exit_node_failover_tries_nodes_in_priority_order() {
// The status never shows nodeA; it always shows nodeB selected + online.
// ensure_exit_node must therefore try nodeA (fail), then nodeB (succeed),
// in that exact priority order.
let _env = EnvSandbox::new();
let json = r#"{"BackendState":"Running","Peer":{"k1":{"HostName":"nodeB","DNSName":"nodeB.ts.net.","Online":true,"ExitNode":true,"ExitNodeOption":true}}}"#;
let runner = FakeRunner::new()
.with_command("tailscale")
.on_contains("tailscale", "status", ok(json))
.on(|p, args| p == "tailscale" && args.contains(&"set"), ok(""));
let calls = runner.calls_handle();
let health = with_runner(runner, || {
breadcrumbs::tailscale::ensure_exit_node(&["nodeA".into(), "nodeB".into()])
});
assert_eq!(health, breadcrumbs::tailscale::TsHealth::Ok);
let sets: Vec<String> = calls
.borrow()
.iter()
.filter(|c| c.args.iter().any(|a| a == "set"))
.map(|c| c.args.join(" "))
.collect();
assert_eq!(
sets,
vec!["set --exit-node=nodeA".to_string(), "set --exit-node=nodeB".to_string()],
"failover must try nodes in priority order"
);
}
#[test]
fn wifi_interface_preferred_picks_named_device_over_first_wifi() {
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset();
nm.add_wifi_device("wlan0", 100);
nm.add_wifi_device("wlan1", 100);
assert_eq!(breadcrumbs::nm::wifi_interface_preferred(Some("wlan1")).as_deref(), Some("wlan1"));
}
#[test]
fn wifi_interface_preferred_falls_back_to_first_wifi_when_pref_missing() {
let _env = EnvSandbox::new();
let nm = fake_nm::shared();
nm.reset();
nm.add_wifi_device("wlan0", 100);
nm.add_wifi_device("wlan1", 100);
assert_eq!(breadcrumbs::nm::wifi_interface_preferred(Some("wlan9")).as_deref(), Some("wlan0"));
}
#[test]
fn visible_signals_dedups_by_strongest_signal() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
nm.add_ap(&dev, "Cafe", 40, Security::Wpa2);
nm.add_ap(&dev, "Cafe", 85, Security::Wpa2);
nm.add_ap(&dev, "Office", 60, Security::Wpa2);
let map = breadcrumbs::nm::visible_signals("wlan0");
assert_eq!(map.get("Cafe"), Some(&85));
assert_eq!(map.get("Office"), Some(&60));
}
#[test]
fn connect_verbose_enterprise_creates_8021x_profile() {
let _env = EnvSandbox::new();
let (nm, dev) = setup_wifi(&[]);
nm.add_ap(&dev, "Corp", 80, Security::Enterprise);
let mut def = net("Corp", Some("pw"));
def.eap = Some("peap".into());
def.identity = Some("user@corp".into());
def.ca_cert = Some("/etc/ca.pem".into());
let res = breadcrumbs::nm::connect_verbose("wlan0", &def, 8, "1.1.1.1");
assert!(res.is_ok(), "enterprise connect should succeed: {res:?}");
let st = nm.state.lock().unwrap();
let (_, settings) = st.connections.iter().next().expect("a profile was saved");
let x1 = settings.get("802-1x").expect("802-1x section");
assert_eq!(
x1.get("identity").and_then(|v| v.downcast_ref::<String>().ok()).as_deref(),
Some("user@corp")
);
let eap = x1.get("eap").and_then(fake_nm::value_str_list);
assert_eq!(eap.as_deref(), Some(&["peap".to_string()][..]));
// ca-cert is a GBytes (`ay`) holding the conventional `file://` URI for
// a filesystem path — never a bare string.
let ca = x1.get("ca-cert").and_then(fake_nm::value_bytes);
assert_eq!(ca.as_deref(), Some(b"file:///etc/ca.pem".as_slice()));
let sec = settings.get("802-11-wireless-security").expect("security section");
assert_eq!(
sec.get("key-mgmt").and_then(|v| v.downcast_ref::<String>().ok()).as_deref(),
Some("wpa-eap")
);
}