Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends \
libdbus-1-dev libpam0g-dev libbluetooth-dev \
dbus-daemon libdbus-1-dev libpam0g-dev libbluetooth-dev \
pkg-config

- name: Install Rust (stable)
Expand Down Expand Up @@ -75,7 +75,7 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends \
libdbus-1-dev libpam0g-dev libbluetooth-dev \
dbus-daemon libdbus-1-dev libpam0g-dev libbluetooth-dev \
pkg-config

- name: Install Rust (stable)
Expand Down Expand Up @@ -106,7 +106,7 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends \
libdbus-1-dev libpam0g-dev libbluetooth-dev \
dbus-daemon libdbus-1-dev libpam0g-dev libbluetooth-dev \
pkg-config

- name: Install Rust (stable)
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
- name: Install the Debian 12 build toolchain
run: |
apt-get update -qq
apt-get install -y --no-install-recommends ca-certificates curl git build-essential pkg-config libdbus-1-dev libpam0g-dev libbluetooth-dev libssl-dev python3
apt-get install -y --no-install-recommends ca-certificates curl git build-essential pkg-config dbus-daemon libdbus-1-dev libpam0g-dev libbluetooth-dev libssl-dev python3
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 12 additions & 2 deletions crates/syauth-cli/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ pub enum DaemonProbeState {
/// timeout; the daemon's per-peer rows + boot wall-clock time
/// are carried in.
Up {
/// Live controller and advertisement readiness, if supported by the daemon.
transport_ready: Option<bool>,
/// Boot wall-clock time the daemon reported. Serialized as
/// epoch seconds on the JSON path for non-Rust consumers.
#[serde(with = "epoch_seconds")]
Expand Down Expand Up @@ -549,7 +551,15 @@ fn probe_daemon(socket: &Path) -> DaemonProbeState {
};
}
match read_frame_blocking::<_, Response>(&mut stream) {
Ok(Response::Status { peers, started_at }) => DaemonProbeState::Up { started_at, peers },
Ok(Response::Status {
peers,
started_at,
transport_ready,
}) => DaemonProbeState::Up {
started_at,
peers,
transport_ready,
},
Ok(_) => DaemonProbeState::Down {
reason: "unexpected-response".to_owned(),
},
Expand All @@ -576,7 +586,7 @@ fn connect_error_reason(err: &io::Error) -> String {
/// so a daemon-down case is never a silent empty section.
pub fn write_daemon_section(writer: &mut dyn Write, report: &CliStatusReport) -> Result<(), StatusError> {
match &report.daemon {
DaemonProbeState::Up { started_at, peers } => {
DaemonProbeState::Up { started_at, peers, .. } => {
let ts = format_rfc3339(*started_at);
writeln!(writer, "daemon=up started_at={ts}")?;
writeln!(
Expand Down
1 change: 1 addition & 0 deletions crates/syauth-cli/tests/doctor_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ impl FakeDaemon {
if let Ok(req) = read_frame_blocking::<_, Request>(&mut stream) {
if matches!(req, Request::Status) {
let resp = Response::Status {
transport_ready: Some(true),
peers: vec![],
started_at: SystemTime::now(),
};
Expand Down
27 changes: 26 additions & 1 deletion crates/syauth-cli/tests/status_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ struct FakeStatusDaemon {

impl FakeStatusDaemon {
fn new(socket: PathBuf, peers: Vec<PeerStatus>, started_at: SystemTime) -> Self {
Self::with_transport_health(socket, peers, started_at, true)
}

fn with_transport_health(socket: PathBuf, peers: Vec<PeerStatus>, started_at: SystemTime, ready: bool) -> Self {
let listener = UnixListener::bind(&socket).expect("bind fake daemon listener");
listener.set_nonblocking(false).expect("blocking listener");
let (tx, _rx) = mpsc::channel::<()>();
Expand All @@ -71,7 +75,11 @@ impl FakeStatusDaemon {
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
if let Ok(Request::Status) = read_frame_blocking::<_, Request>(&mut stream) {
let resp = Response::Status { peers, started_at };
let resp = Response::Status {
peers,
started_at,
transport_ready: Some(ready),
};
let _ = write_frame_blocking(&mut stream, &resp);
}
let mut buf = [0u8; 1];
Expand Down Expand Up @@ -188,3 +196,20 @@ fn json_mode_emits_typed_object() {
let state = daemon.get("state").and_then(|v| v.as_str()).expect("state token");
assert!(matches!(state, "up" | "down"), "unexpected state token {state}");
}

#[test]
fn json_reports_transport_failure_independently_of_daemon_liveness() {
let td = TempDir::new().expect("tempdir");
let socket = td.path().join("auth.sock");
let _daemon = FakeStatusDaemon::with_transport_health(socket.clone(), vec![peer_row("phone")], SystemTime::now(), false);
let out = syauth()
.args(["status", "--json", "--socket"])
.arg(&socket)
.args(["--adapter", "absent-adapter", "--bond-dir"])
.arg(td.path())
.assert()
.success();
let value: serde_json::Value = serde_json::from_slice(&out.get_output().stdout).expect("JSON");
assert_eq!(value["daemon"]["state"], "up");
assert_eq!(value["daemon"]["transport_ready"], false);
}
2 changes: 2 additions & 0 deletions crates/syauth-presenced/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,5 @@ time = { version = "0.3", features = ["macros"] }
# transport's `Peripheral` trait talks `uuid::Uuid` and the rotation
# audit short-hex render uses the same crate.
uuid = { version = "1" }
# Exercise the real BlueZ D-Bus boundary on a private bus, without a radio.
zbus = { version = "5", default-features = false, features = ["tokio"] }
7 changes: 3 additions & 4 deletions crates/syauth-presenced/dist/syauth-presenced.service
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Documentation=https://github.com/dmytrogajewski/syauth/blob/master/specs/unlock-
# locks ${XDG_RUNTIME_DIR}/syauth/presenced.pid (S-001), so the
# XDG_RUNTIME_DIR must exist before the unit starts.
ConditionPathIsDirectory=%t
# Keep retrying while a controller is absent, including suspend and USB resets.
StartLimitIntervalSec=0

[Service]
Type=simple
Expand All @@ -28,10 +30,7 @@ ExecStart=/usr/local/libexec/syauth-presenced
# drops the pidfile lock + unlinks the pidfile + exits within ~1s.
KillSignal=SIGTERM
TimeoutStopSec=5
# Restart on crash so a transient BlueZ adapter blip (S-003+) does
# not require operator intervention. S-001 has no crash conditions
# of its own; this setting is forward-looking for the BLE event loop
# that arrives in S-003+.
# Rebuild the GATT application and rotating advertisement after transport loss.
Restart=on-failure
RestartSec=2
# Sandboxing aligned with SPEC §7 Security ("only the daemon's own
Expand Down
37 changes: 35 additions & 2 deletions crates/syauth-presenced/src/orchestrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
use std::{
collections::{BTreeMap, HashMap, HashSet, VecDeque},
path::{Path, PathBuf},
sync::Arc,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration as StdDuration, SystemTime, UNIX_EPOCH},
};

Expand Down Expand Up @@ -393,6 +396,7 @@ pub struct ReloadCommand {
/// minimal `add_peer` / `remove_peer` calls before re-publishing the
/// fresh UUID union.
pub struct Orchestrator {
transport_ready: AtomicBool,
peripheral: Arc<dyn Peripheral + Send + Sync>,
/// In-memory mirror of the live peer set keyed by `peer_id`.
/// `BTreeMap` so iteration order is deterministic across runs
Expand Down Expand Up @@ -551,6 +555,7 @@ impl Orchestrator {
let (reload_tx, reload_rx) = mpsc::channel(RELOAD_CHANNEL_CAPACITY);
Self {
peripheral,
transport_ready: AtomicBool::new(false),
peers: tokio::sync::Mutex::new(map),
bonds_file,
keys_dir,
Expand All @@ -561,6 +566,32 @@ impl Orchestrator {
}
}

/// True after successful advertising and while transport health checks pass.
#[must_use]
pub fn transport_ready(&self) -> bool {
self.transport_ready.load(Ordering::Acquire)
}

/// Bound health probing so an unresponsive BlueZ cannot stall recovery.
pub async fn check_transport(&self) -> Result<(), PeripheralError> {
let result = match tokio::time::timeout(StdDuration::from_secs(1), self.peripheral.check_health()).await {
Ok(result) => result,
Err(_) => Err(PeripheralError::Backend {
reason: "transport health probe timed out".into(),
}),
};
if result.is_err() {
self.transport_ready.store(false, Ordering::Release);
}
result?;
if !self.transport_ready() {
return Err(PeripheralError::Backend {
reason: "advertising unavailable".into(),
});
}
Ok(())
}

/// Attach an audit-log appender after construction. Returns the
/// previously-installed log (if any). Useful for tests that
/// construct the orchestrator first and only later open the
Expand Down Expand Up @@ -634,7 +665,9 @@ impl Orchestrator {
let minute = minute_index(now);
let snapshot = self.snapshot_peers().await;
let union = build_uuid_union(&snapshot, minute);
match self.peripheral.set_session_uuids(union.clone()).await {
let result = self.peripheral.set_session_uuids(union.clone()).await;
self.transport_ready.store(result.is_ok(), Ordering::Release);
match result {
Ok(()) => {
for (peer_id, _) in &snapshot {
let uuid_bytes = session_uuid_for(snapshot_key(&snapshot, peer_id), minute);
Expand Down
23 changes: 23 additions & 0 deletions crates/syauth-presenced/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ pub enum Response {
/// Outcome of `Request::Status`. S-002 ships the wire shape with
/// an empty `peers` list; S-017 fills in the per-peer columns.
Status {
/// Advertising and controller health, independent of phone presence.
/// Missing for daemons predating transport health reporting.
#[serde(default)]
transport_ready: Option<bool>,
/// Per-peer liveness rows.
peers: Vec<PeerStatus>,
/// Daemon boot wall-clock time (UTC). Serialized as the
Expand Down Expand Up @@ -381,9 +385,28 @@ mod tests {
assert_eq!(round_trip_response(&original), original);
}

#[test]
fn legacy_status_has_unknown_transport_health() {
#[derive(Serialize)]
struct LegacyStatus {
kind: &'static str,
peers: Vec<PeerStatus>,
started_at: u64,
}
let bytes = encode_frame(&LegacyStatus {
kind: "status",
peers: vec![],
started_at: 0,
})
.expect("encode");
let response: Response = read_frame_blocking(&mut std::io::Cursor::new(bytes)).expect("legacy decode");
assert!(matches!(response, Response::Status { transport_ready: None, .. }));
}

#[test]
fn response_status_roundtrips() {
let original = Response::Status {
transport_ready: Some(true),
peers: vec![PeerStatus {
peer_id: "peer-a".to_string(),
last_challenge_ms_ago: Some(42_000),
Expand Down
Loading
Loading