feat(peer)!: cut over to authenticated catalog sharing

Replace address-only trust and pushed peer state with installation identities,
SPKI-pinned QUIC, candidate-only discovery, and bounded responder-owned
protocol-8 pulls. The runtime now owns each network generation and all admitted
work through shutdown.

Add exact bundled content identities, reproducible manifest publishing,
capability-confined downloads, streaming BLAKE3 verification, quarantine and
retry, and crash-recoverable download and install transactions. Ship generated
fixture catalogs and fail closed when production manifests are absent.

The Tauri backend exposes durable sharing policy, redacted identity state, and
attempt-keyed transfer snapshots. Frontend consumption follows in the next
commit. Repository-wide test certificates and protocol-7 paths are removed.

BREAKING CHANGE: peers must use protocol 8 and exact catalog content artifacts;
protocol-7 frames and shared-certificate identities are no longer accepted.

Test Plan:
- `just test` -- passed on the completed stack (708 workspace tests)
- `just clippy` -- passed on the completed stack
- `just build` -- passed with fixture catalogs on the completed stack
- `just catalog-check-production` -- failed closed because the external
  production manifest corpus is absent
- `git diff --cached --check` -- passed
This commit is contained in:
ddidderr committed 2026-08-10 13:59:18 +02:00
1 parent 36c4785775
commit 60fd7ba0c2
128 files changed
+51759 -10784

No files matched your search

+368 -35
View File
@@ -3,17 +3,27 @@
#![allow(clippy::missing_errors_doc)]
use std::{
fmt::Write as _,
net::SocketAddr,
path::{Path, PathBuf},
time::Duration,
};
use eyre::{Context, OptionExt};
use lanspread_peer::{CallToPlayEvent, UnpackFuture, Unpacker};
use lanspread_peer::{
CallToPlayLocalIntent,
PeerEndpoint,
PeerId,
ScopedProcess,
UnpackFuture,
Unpacker,
};
use serde::Serialize;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;
pub const DEFAULT_FIXTURE_VERSION: &str = "20250101";
const EXTERNAL_UNRAR_CAPTURE_LIMIT: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandEnvelope {
@@ -28,7 +38,10 @@ pub enum CliCommand {
ListGames,
ListCallToPlay,
PublishCallToPlay {
event: CallToPlayEvent,
intent: CallToPlayLocalIntent,
},
SetCallToPlayDisplayName {
display_name: String,
},
SetGameDir {
path: PathBuf,
@@ -39,6 +52,9 @@ pub enum CliCommand {
},
StreamInstall {
game_id: String,
account_name: Option<String>,
language: Option<String>,
persona_name: Option<String>,
},
CancelDownload {
game_id: String,
@@ -59,7 +75,7 @@ pub enum CliCommand {
timeout: Duration,
},
Connect {
addr: SocketAddr,
endpoint: PeerEndpoint,
},
Shutdown,
}
@@ -73,6 +89,7 @@ impl CliCommand {
Self::ListGames => "list-games",
Self::ListCallToPlay => "list-call-to-play",
Self::PublishCallToPlay { .. } => "publish-call-to-play",
Self::SetCallToPlayDisplayName { .. } => "set-call-to-play-display-name",
Self::SetGameDir { .. } => "set-game-dir",
Self::Download { .. } => "download",
Self::StreamInstall { .. } => "stream-install",
@@ -110,13 +127,16 @@ pub fn parse_command_value(value: &Value) -> eyre::Result<CommandEnvelope> {
"list-games" => CliCommand::ListGames,
"list-call-to-play" => CliCommand::ListCallToPlay,
"publish-call-to-play" => CliCommand::PublishCallToPlay {
event: serde_json::from_value(
intent: serde_json::from_value(
object
.get("event")
.get("intent")
.cloned()
.ok_or_eyre("publish-call-to-play must include event")?,
.ok_or_eyre("publish-call-to-play must include intent")?,
)
.wrap_err("invalid Call to Play event")?,
.wrap_err("invalid Call to Play intent")?,
},
"set-call-to-play-display-name" => CliCommand::SetCallToPlayDisplayName {
display_name: required_str(object, "display_name")?,
},
"set-game-dir" => CliCommand::SetGameDir {
path: PathBuf::from(required_str(object, "path")?),
@@ -127,6 +147,9 @@ pub fn parse_command_value(value: &Value) -> eyre::Result<CommandEnvelope> {
},
"stream-install" => CliCommand::StreamInstall {
game_id: game_id(object)?,
account_name: optional_str(object, "account_name")?,
language: optional_str(object, "language")?,
persona_name: optional_str(object, "persona_name")?,
},
"cancel-download" => CliCommand::CancelDownload {
game_id: game_id(object)?,
@@ -151,11 +174,17 @@ pub fn parse_command_value(value: &Value) -> eyre::Result<CommandEnvelope> {
.wrap_err("count does not fit in usize")?,
timeout: Duration::from_millis(required_u64(object, "timeout_ms")?),
},
"connect" | "direct-connect" => CliCommand::Connect {
addr: required_str(object, "addr")?
.parse()
.wrap_err("addr must be a socket address like 127.0.0.1:12345")?,
},
"connect" | "direct-connect" => {
let peer_id = required_str(object, "peer_id")?
.parse::<PeerId>()
.wrap_err("peer_id is not a canonical peer ID")?;
let addr = required_str(object, "addr")?
.parse::<SocketAddr>()
.wrap_err("addr must be a socket address like 127.0.0.1:12345")?;
CliCommand::Connect {
endpoint: PeerEndpoint::new(peer_id, addr),
}
}
"shutdown" => CliCommand::Shutdown,
other => eyre::bail!("unknown command: {other}"),
};
@@ -177,6 +206,21 @@ fn required_str(
.ok_or_else(|| eyre::eyre!("missing string field {field}"))
}
fn optional_str(
object: &serde_json::Map<String, Value>,
field: &'static str,
) -> eyre::Result<Option<String>> {
object
.get(field)
.map(|value| {
value
.as_str()
.map(ToOwned::to_owned)
.ok_or_else(|| eyre::eyre!("{field} must be a string when provided"))
})
.transpose()
}
fn required_u64(object: &serde_json::Map<String, Value>, field: &'static str) -> eyre::Result<u64> {
object
.get(field)
@@ -241,11 +285,28 @@ pub fn seed_fixture_game(game_dir: &Path, fixture_name: &str) -> eyre::Result<Fi
pub struct FixtureUnpacker;
impl Unpacker for FixtureUnpacker {
fn unpack<'a>(&'a self, archive: &'a Path, dest: &'a Path) -> UnpackFuture<'a> {
fn unpack<'a>(
&'a self,
archive: &'a Path,
dest: &'a Path,
cancel_token: CancellationToken,
) -> UnpackFuture<'a> {
Box::pin(async move {
tokio::fs::create_dir_all(dest).await?;
let payload = tokio::fs::read(archive).await?;
tokio::fs::write(dest.join("fixture-payload.txt"), payload).await?;
if cancel_token.is_cancelled() {
eyre::bail!("fixture extraction for {} was cancelled", archive.display());
}
// These fixture files are deliberately tiny. Keep each operation
// lexical: selecting against Tokio's filesystem helpers could drop
// their futures while blocking-pool work still touches staging.
std::fs::create_dir_all(dest)?;
if cancel_token.is_cancelled() {
eyre::bail!("fixture extraction for {} was cancelled", archive.display());
}
let payload = std::fs::read(archive)?;
if cancel_token.is_cancelled() {
eyre::bail!("fixture extraction for {} was cancelled", archive.display());
}
std::fs::write(dest.join("fixture-payload.txt"), payload)?;
Ok(())
})
}
@@ -263,20 +324,46 @@ impl ExternalUnrarUnpacker {
}
impl Unpacker for ExternalUnrarUnpacker {
fn unpack<'a>(&'a self, archive: &'a Path, dest: &'a Path) -> UnpackFuture<'a> {
fn unpack<'a>(
&'a self,
archive: &'a Path,
dest: &'a Path,
cancel_token: CancellationToken,
) -> UnpackFuture<'a> {
Box::pin(async move {
tokio::fs::create_dir_all(dest).await?;
let status = tokio::process::Command::new(&self.program)
.arg("x")
.arg("-o+")
.arg(archive)
.arg(dest)
.status()
.await?;
if !status.success() {
if cancel_token.is_cancelled() {
eyre::bail!("unrar extraction for {} was cancelled", archive.display());
}
// Directory creation is small and synchronous; keeping it lexical
// prevents a dropped Tokio fs future from outliving rollback.
std::fs::create_dir_all(dest)?;
if cancel_token.is_cancelled() {
eyre::bail!("unrar extraction for {} was cancelled", archive.display());
}
let process = ScopedProcess::spawn(
&self.program,
[
std::ffi::OsString::from("x"),
std::ffi::OsString::from("-o+"),
std::ffi::OsString::from("-p-"),
archive.as_os_str().to_owned(),
dest.as_os_str().to_owned(),
],
&cancel_token,
EXTERNAL_UNRAR_CAPTURE_LIMIT,
)?;
let output = process.wait().await?;
if !output.status.success() {
eyre::bail!(
"unrar failed for {} with status {status}",
archive.display()
"unrar failed for {} with status {}: {}",
archive.display(),
output.status,
format_captured_process_output(
&output.stderr,
output.stderr_truncated,
"stderr"
)
);
}
Ok(())
@@ -284,6 +371,14 @@ impl Unpacker for ExternalUnrarUnpacker {
}
}
fn format_captured_process_output(bytes: &[u8], truncated: bool, stream: &str) -> String {
let mut output = String::from_utf8_lossy(bytes).into_owned();
if truncated {
let _ = write!(output, "\n[{stream} truncated]");
}
output
}
pub fn result_line(id: &Option<Value>, command: &str, data: Value) -> eyre::Result<String> {
output_line(json!({
"type": "result",
@@ -317,6 +412,8 @@ fn output_line(value: Value) -> eyre::Result<String> {
#[cfg(test)]
mod tests {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt as _;
use std::sync::Arc;
use super::*;
@@ -374,6 +471,14 @@ mod tests {
assert_eq!(parsed["data"]["peer_count"], 0);
}
#[test]
fn captured_process_output_marks_truncation() {
assert_eq!(
format_captured_process_output(b"partial", true, "stderr"),
"partial\n[stderr truncated]"
);
}
#[test]
fn parses_stream_install_command() {
let parsed = parse_command_line(r#"{"cmd":"stream-install","game_id":"cnctw"}"#)
@@ -383,6 +488,27 @@ mod tests {
parsed.command,
CliCommand::StreamInstall {
game_id: "cnctw".to_string(),
account_name: None,
language: None,
persona_name: None,
}
);
}
#[test]
fn parses_optional_stream_install_settings_without_sanitizing_them() {
let parsed = parse_command_line(
r#"{"cmd":"stream-install","game_id":"cnctw","account_name":" Alice% ","language":"DE","persona_name":" Player% "}"#,
)
.expect("command should parse");
assert_eq!(
parsed.command,
CliCommand::StreamInstall {
game_id: "cnctw".to_string(),
account_name: Some(" Alice% ".to_string()),
language: Some("DE".to_string()),
persona_name: Some(" Player% ".to_string()),
}
);
}
@@ -401,18 +527,103 @@ mod tests {
}
#[test]
fn parses_call_to_play_event_command() {
fn parses_connect_as_an_authenticated_peer_endpoint() {
let parsed = parse_command_line(
r#"{"cmd":"publish-call-to-play","event":{"id":"event-1","call_id":"call-1","actor_id":"","actor_name":"Alice","at":1000,"action":{"Create":{"game_id":"game-1","max_players":4,"scheduled_for":null,"deadline":61000}}}}"#,
r#"{"cmd":"connect","peer_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","addr":"127.0.0.1:34567"}"#,
)
.expect("authenticated connect command should parse");
assert_eq!(
parsed.command,
CliCommand::Connect {
endpoint: PeerEndpoint::new(
PeerId::from_bytes([0; 32]),
"127.0.0.1:34567"
.parse()
.expect("test socket address should parse"),
),
}
);
}
#[test]
fn rejects_address_only_connect() {
let error = parse_command_line(r#"{"cmd":"connect","addr":"127.0.0.1:34567"}"#)
.expect_err("connect must require an authenticated peer identity");
assert!(error.to_string().contains("missing string field peer_id"));
}
#[test]
fn rejects_noncanonical_connect_peer_id() {
let error = parse_command_line(
r#"{"cmd":"connect","peer_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","addr":"127.0.0.1:34567"}"#,
)
.expect_err("connect must reject noncanonical peer IDs");
assert!(error.to_string().contains("canonical peer ID"));
}
#[test]
fn parses_intent_only_call_to_play_command() {
let parsed = parse_command_line(
r#"{"cmd":"publish-call-to-play","intent":{"call_id":null,"action":{"Create":{"game_id":"game-1","max_players":4,"scheduled_for":null,"deadline":61000}}}}"#,
)
.expect("command should parse");
let CliCommand::PublishCallToPlay { event } = parsed.command else {
let CliCommand::PublishCallToPlay { intent } = parsed.command else {
panic!("expected PublishCallToPlay");
};
assert_eq!(event.id, "event-1");
assert_eq!(event.call_id, "call-1");
assert_eq!(event.actor_name, "Alice");
assert!(intent.call_id.is_none());
assert!(matches!(
intent.action,
lanspread_peer::CallToPlayLocalAction::Create {
game_id,
max_players: 4,
scheduled_for: None,
deadline: 61_000,
} if game_id == "game-1"
));
}
#[test]
fn parses_existing_call_rsvp_and_chat_intents_used_by_late_join_scenarios() {
let call_id = format!("{}.{}", "a".repeat(52), "ab".repeat(16));
let rsvp = parse_command_line(&format!(
r#"{{"cmd":"publish-call-to-play","intent":{{"call_id":"{call_id}","action":"Rsvp"}}}}"#,
))
.expect("RSVP intent should parse");
let chat = parse_command_line(&format!(
r#"{{"cmd":"publish-call-to-play","intent":{{"call_id":"{call_id}","action":{{"SendMessage":{{"text":"I am in"}}}}}}}}"#,
))
.expect("chat intent should parse");
let CliCommand::PublishCallToPlay { intent: rsvp } = rsvp.command else {
panic!("expected RSVP PublishCallToPlay");
};
let CliCommand::PublishCallToPlay { intent: chat } = chat.command else {
panic!("expected chat PublishCallToPlay");
};
assert_eq!(rsvp.call_id, chat.call_id);
assert!(matches!(
rsvp.action,
lanspread_peer::CallToPlayLocalAction::Rsvp
));
assert!(matches!(
chat.action,
lanspread_peer::CallToPlayLocalAction::SendMessage { text }
if text == "I am in"
));
}
#[test]
fn rejects_client_authored_call_to_play_event_fields() {
let error = parse_command_line(
r#"{"cmd":"publish-call-to-play","intent":{"call_id":null,"id":"event-1","at":1000,"action":{"Rsvp":null}}}"#,
)
.expect_err("client-authored event identity and time must be rejected");
assert!(error.to_string().contains("invalid Call to Play intent"));
}
#[tokio::test]
@@ -421,7 +632,7 @@ mod tests {
let seed = seed_fixture_game(temp.path(), "fixture-one").expect("fixture should seed");
let dest = temp.path().join("staging");
Arc::new(FixtureUnpacker)
.unpack(&seed.archive, &dest)
.unpack(&seed.archive, &dest, CancellationToken::new())
.await
.expect("fixture archive should unpack");
@@ -429,4 +640,126 @@ mod tests {
.expect("payload should be written");
assert!(payload.contains("fixture-one"));
}
#[cfg(unix)]
fn controlled_unrar(temp: &TempDir) -> (Arc<ExternalUnrarUnpacker>, PathBuf, PathBuf) {
let program = temp.path().join("controlled-unrar");
std::fs::write(
&program,
r#"#!/bin/sh
set -eu
[ "$3" = "-p-" ]
dest=$5
printf '%s' "$$" > "$dest/child.pid"
printf 'started' > "$dest/started"
while [ ! -e "$dest/release" ]; do :; done
printf 'late' > "$dest/late-canary"
"#,
)
.expect("controlled unrar should be written");
let mut permissions = std::fs::metadata(&program)
.expect("controlled unrar metadata should be readable")
.permissions();
permissions.set_mode(0o700);
std::fs::set_permissions(&program, permissions)
.expect("controlled unrar should be executable");
let archive = temp.path().join("archive.eti");
std::fs::write(&archive, b"fixture").expect("archive should be written");
let destination = temp.path().join("destination");
(
Arc::new(ExternalUnrarUnpacker::new(program)),
archive,
destination,
)
}
#[cfg(unix)]
async fn wait_for_path(path: &Path) {
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while !path.exists() {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
})
.await
.expect("controlled child marker should appear");
}
#[cfg(target_os = "linux")]
async fn wait_for_process_exit(pid: u32) {
let process = PathBuf::from(format!("/proc/{pid}"));
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while process.exists() {
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
})
.await
.expect("controlled child should no longer exist");
}
#[cfg(target_os = "linux")]
fn controlled_child_pid(destination: &Path) -> u32 {
std::fs::read_to_string(destination.join("child.pid"))
.expect("controlled child pid should be readable")
.parse()
.expect("controlled child pid should be numeric")
}
#[cfg(unix)]
#[tokio::test]
async fn external_unrar_cancellation_kills_and_reaps_before_return() {
let temp = TempDir::new("lanspread-peer-cli-unrar-cancel");
let (unpacker, archive, destination) = controlled_unrar(&temp);
let cancel_token = CancellationToken::new();
let task_cancel_token = cancel_token.clone();
let task_destination = destination.clone();
let task = tokio::spawn(async move {
unpacker
.unpack(&archive, &task_destination, task_cancel_token)
.await
});
wait_for_path(&destination.join("started")).await;
#[cfg(target_os = "linux")]
let pid = controlled_child_pid(&destination);
cancel_token.cancel();
let error = tokio::time::timeout(std::time::Duration::from_secs(2), task)
.await
.expect("cancelled unpack should settle")
.expect("unpack task should not panic")
.expect_err("cancelled unpack should fail");
assert!(error.to_string().contains("cancelled"));
#[cfg(target_os = "linux")]
wait_for_process_exit(pid).await;
std::fs::write(destination.join("release"), b"").expect("release marker should be written");
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
assert!(!destination.join("late-canary").exists());
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_external_unrar_future_kills_child() {
let temp = TempDir::new("lanspread-peer-cli-unrar-drop");
let (unpacker, archive, destination) = controlled_unrar(&temp);
let task_destination = destination.clone();
let task = tokio::spawn(async move {
unpacker
.unpack(&archive, &task_destination, CancellationToken::new())
.await
});
wait_for_path(&destination.join("started")).await;
#[cfg(target_os = "linux")]
let pid = controlled_child_pid(&destination);
task.abort();
task.await
.expect_err("aborted unpack task should be cancelled");
#[cfg(target_os = "linux")]
wait_for_process_exit(pid).await;
std::fs::write(destination.join("release"), b"").expect("release marker should be written");
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
assert!(!destination.join("late-canary").exists());
}
}