From f82f6678eb23eca17b376ff36583417afc90a30a Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 00:02:38 -0600 Subject: [PATCH] feat(id): transport advertisement minter + .well-known serving (#8214 slice 4) --- pkgs/id/crates/id-cli/src/commands/serve.rs | 75 ++++++ .../id-core/src/transport_advertisement.rs | 245 +++++++++++++++++- pkgs/id/crates/id-web/src/lib.rs | 23 ++ pkgs/id/crates/id-web/src/routes.rs | 4 + pkgs/id/crates/id-web/src/transport_ad.rs | 191 ++++++++++++++ 5 files changed, 536 insertions(+), 2 deletions(-) create mode 100644 pkgs/id/crates/id-web/src/transport_ad.rs diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 6eb982ac3a..665e8dc8bd 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1064,6 +1064,44 @@ impl ServeWorlds { /// `--groups-log` option when given, else the default file name — /// resolved with the group commands' semantics (#2778; serve used /// to hardcode the default and ignore the option). +/// The transport set this node currently advertises (#8214 +/// slice 4): its endpoint's direct UDP socket addresses and its +/// home relay, in the #5671 fallback order (direct first, relay +/// second). Recomputed from the live endpoint address, so a +/// watcher re-minting on change always signs the current set. +fn ad_transports( + endpoint: &iroh::endpoint::Endpoint, +) -> Vec { + use id_core::transport_advertisement::{TransportEntry, TransportKind}; + let mut out = Vec::new(); + for addr in endpoint.addr().addrs { + match addr { + iroh::TransportAddr::Ip(socket) => out.push(TransportEntry { + kind: TransportKind::Udp, + endpoint: socket.to_string(), + priority: 10, + broker: None, + }), + iroh::TransportAddr::Relay(url) => out.push(TransportEntry { + kind: TransportKind::RelayUdp, + endpoint: url.to_string(), + priority: 20, + broker: None, + }), + _ => {} + } + } + out +} + +/// Unix seconds now, for advertisement minting. +fn ad_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + fn serve_groups_log_path(path: Option) -> PathBuf { crate::commands::group::log_path(path) } @@ -2230,6 +2268,42 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); #[cfg(not(feature = "world"))] let seitan_state = id_web::SeitanState::default(); + // #8214 slice 4: the transport-advertisement minter the + // web surface serves at + // /.well-known/id-transport-advertisement — signed by + // the node key, its sequence counter beside the + // identity key (KEY_FILE), first mint over the + // endpoint's current transports. A watcher re-mints + // when the endpoint's address set changes (Decision 3: + // mint on any transport change); the minter itself + // re-mints per TTL when the handler asks for the + // current bytes. + let transport_ad_minter = { + let minter = std::sync::Arc::new(id_core::transport_advertisement::AdMinter::new( + ed25519_dalek::SigningKey::from_bytes(&key.to_bytes()), + id_core::transport_advertisement::SequenceFile::new( + std::path::Path::new(KEY_FILE).with_file_name(".transport-ad-sequence"), + ), + id_core::transport_advertisement::RECOMMENDED_TTL_SECONDS, + )); + if let Err(error) = minter.refresh(ad_transports(&endpoint), ad_now()) { + warn!("transport advertisement: initial mint failed: {error}"); + } + let watcher_minter = std::sync::Arc::clone(&minter); + let watcher_endpoint = endpoint.clone(); + tokio::spawn(async move { + let mut tick = tokio::time::interval(std::time::Duration::from_secs(30)); + loop { + tick.tick().await; + if let Err(error) = + watcher_minter.refresh(ad_transports(&watcher_endpoint), ad_now()) + { + warn!("transport advertisement: refresh failed: {error}"); + } + } + }); + minter + }; let (web_routers, surface) = id_web::web_routers_with_surface( store_handle.clone(), Some(peer_discovery.clone()), @@ -2245,6 +2319,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { Some(groups_log.clone()), seitan_state, Some(endpoint.clone()), + Some(std::sync::Arc::clone(&transport_ad_minter)), ) .await?; publication_surface = Some(surface); diff --git a/pkgs/id/crates/id-core/src/transport_advertisement.rs b/pkgs/id/crates/id-core/src/transport_advertisement.rs index a5fc92dbaf..6a045b153c 100644 --- a/pkgs/id/crates/id-core/src/transport_advertisement.rs +++ b/pkgs/id/crates/id-core/src/transport_advertisement.rs @@ -10,8 +10,12 @@ //! (record Decision 1). This module is slice 1 of #8214: the type, //! the domain-separated canonical encoding, sign/verify, the //! freshest-valid-wins selection rule (Decisions 1+3), and the -//! durable sequence counter (invariant 8). Fetch/cache transport -//! and the `.well-known` serving handler are later slices. +//! durable sequence counter (invariant 8). Slice 2 added the +//! last-known-good cache and substrate resolution; slice 4 adds the +//! server side: `AdMinter` (minting on transport change and per +//! TTL, Decision 3), whose current bytes the `.well-known` handler +//! in id-web serves byte-for-byte. Fetch-side HTTPS substrates are +//! the remaining slice. //! //! The oracle for the tests below is the decision record itself: //! invariants 1–3 and 8, and the #8214 acceptance tests @@ -340,6 +344,132 @@ impl SequenceFile { } } +/// The TTL the record recommends for minted ads (Decision 1: +/// TTL <= 24 h, 1 h RECOMMENDED). +pub const RECOMMENDED_TTL_SECONDS: u64 = 60 * 60; + +/// Server-side minter (#8214 slice 4): owns the subject identity +/// key and the durable SequenceFile beside it, and produces the +/// one current signed advertisement the server publishes (Decision +/// 1). Minting follows Decision 3: a new ad (sequence + 1) is +/// minted on any transport change and at least once per TTL; +/// between those events the current ad's bytes are stable, so +/// every substrate (the .well-known handler, a broker mirror, the +/// Workers push) serves the identical object byte-for-byte +/// (Decision 2 parity). +pub struct AdMinter { + key: SigningKey, + sequence: SequenceFile, + ttl_seconds: u64, + current: std::sync::Mutex>, +} + +struct MintedAd { + transports: Vec, + signed: SignedAdvertisement, + /// The exact bytes substrates serve: the serde JSON of the + /// SignedAdvertisement, captured at mint time so a later + /// serializer change can never alter what an already-minted + /// ad serves as. + bytes: Vec, +} + +impl AdMinter { + /// A minter for the given identity key, issuing sequences from + /// the counter file that lives beside the identity key. The + /// TTL is clamped to the record's 24 h maximum. + pub fn new(key: SigningKey, sequence: SequenceFile, ttl_seconds: u64) -> Self { + Self { + key, + sequence, + ttl_seconds: ttl_seconds.clamp(1, MAX_TTL_SECONDS), + current: std::sync::Mutex::new(None), + } + } + + /// The subject fingerprint this minter signs for. + pub fn subject(&self) -> String { + TransportAdvertisement::subject_for(&self.key.verifying_key()) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Option> { + self.current + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn mint_locked( + &self, + slot: &mut Option, + transports: Vec, + now: u64, + ) -> std::io::Result> { + let sequence = self.sequence.next_sequence()?; + let ad = TransportAdvertisement { + subject: self.subject(), + transports, + issued_at: now, + expires_at: now.saturating_add(self.ttl_seconds), + sequence, + }; + let signed = ad.sign(&self.key); + let bytes = serde_json::to_vec(&signed).map_err(std::io::Error::other)?; + *slot = Some(MintedAd { + transports: ad.transports.clone(), + signed, + bytes: bytes.clone(), + }); + Ok(bytes) + } + + /// Mint a new ad over the transports unconditionally + /// (sequence + 1) and return the bytes substrates should + /// serve. + pub fn mint(&self, transports: Vec, now: u64) -> std::io::Result> { + let mut slot = self.lock(); + self.mint_locked(&mut slot, transports, now) + } + + /// The Decision 3 refresh: mint only when there is no current + /// ad, the transport set changed, or the current ad has + /// expired; otherwise return the current bytes unchanged (a + /// no-op refresh consumes no sequence). + pub fn refresh(&self, transports: Vec, now: u64) -> std::io::Result> { + let mut slot = self.lock(); + let stale = match &*slot { + None => true, + Some(minted) => { + minted.transports != transports || minted.signed.advertisement.expires_at <= now + } + }; + if stale { + return self.mint_locked(&mut slot, transports, now); + } + Ok(slot.as_ref().map(|m| m.bytes.clone()).unwrap_or_default()) + } + + /// The bytes to serve right now, or None when nothing was + /// ever minted. An expired current ad is re-minted in place + /// over its last transport set (the per-TTL mint Decision 3 + /// requires), so a server that is asked always answers with + /// a fresh ad. + pub fn current_bytes(&self, now: u64) -> std::io::Result>> { + let mut slot = self.lock(); + let expired = matches!( + &*slot, + Some(minted) if minted.signed.advertisement.expires_at <= now + ); + if expired { + let transports = slot + .as_ref() + .map(|m| m.transports.clone()) + .unwrap_or_default(); + return self.mint_locked(&mut slot, transports, now).map(Some); + } + Ok(slot.as_ref().map(|m| m.bytes.clone())) + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -716,3 +846,114 @@ mod cache_tests { assert_eq!(sel.advertisement.sequence, 4); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod minter_tests { + use super::*; + + // Oracle: the #5793 decision record, Decision 3 (mint on + // transport change and at least once per TTL) and invariant 8 + // (sequence durably monotonic per subject). + + const NOW: u64 = 1_700_000_000; + + fn key() -> SigningKey { + SigningKey::from_bytes(&[7u8; 32]) + } + + fn transports(port: u16) -> Vec { + vec![TransportEntry { + kind: TransportKind::Tcp, + endpoint: format!("203.0.113.7:{port}"), + priority: 30, + broker: None, + }] + } + + fn parse(bytes: &[u8]) -> SignedAdvertisement { + serde_json::from_slice(bytes).expect("served bytes parse as a SignedAdvertisement") + } + + fn minter(dir: &std::path::Path, ttl: u64) -> AdMinter { + AdMinter::new( + key(), + SequenceFile::new(dir.join("transport-ad.sequence")), + ttl, + ) + } + + #[test] + fn minted_ad_verifies_and_carries_the_recommended_shape() { + let dir = tempfile::tempdir().unwrap(); + let m = minter(dir.path(), RECOMMENDED_TTL_SECONDS); + let bytes = m.mint(transports(443), NOW).unwrap(); + let signed = parse(&bytes); + let ad = signed + .verify(&m.subject()) + .expect("a minted ad verifies against its subject"); + assert_eq!(ad.sequence, 1); + assert_eq!(ad.expires_at - ad.issued_at, RECOMMENDED_TTL_SECONDS); + // Serving is byte-for-byte: what current_bytes returns is + // exactly what mint produced. + assert_eq!( + m.current_bytes(NOW).unwrap().as_deref(), + Some(bytes.as_slice()) + ); + } + + #[test] + fn refresh_mints_only_on_change_or_expiry() { + let dir = tempfile::tempdir().unwrap(); + let m = minter(dir.path(), 3600); + let first = m.refresh(transports(443), NOW).unwrap(); + // Same transports, still fresh: no new sequence. + let again = m.refresh(transports(443), NOW + 60).unwrap(); + assert_eq!(first, again); + assert_eq!(parse(&again).advertisement.sequence, 1); + // Transport change: Decision 3 mints sequence + 1. + let changed = m.refresh(transports(8443), NOW + 120).unwrap(); + assert_eq!(parse(&changed).advertisement.sequence, 2); + // Expiry of the current ad: the per-TTL mint fires even + // with unchanged transports. + let expired = m.refresh(transports(8443), NOW + 120 + 3600).unwrap(); + assert_eq!(parse(&expired).advertisement.sequence, 3); + } + + #[test] + fn current_bytes_remints_an_expired_ad() { + let dir = tempfile::tempdir().unwrap(); + let m = minter(dir.path(), 3600); + assert!(m.current_bytes(NOW).unwrap().is_none()); + m.mint(transports(443), NOW).unwrap(); + let bytes = m.current_bytes(NOW + 3600).unwrap().expect("re-minted"); + let ad = parse(&bytes).advertisement; + assert_eq!(ad.sequence, 2); + assert_eq!(ad.issued_at, NOW + 3600); + } + + #[test] + fn sequence_never_regresses_across_minter_restarts() { + // Invariant 8: the counter lives beside the identity key, + // so a restarted minter continues from the persisted + // sequence instead of reissuing a lower one. + let dir = tempfile::tempdir().unwrap(); + { + let m = minter(dir.path(), 3600); + m.mint(transports(443), NOW).unwrap(); + m.mint(transports(443), NOW + 10).unwrap(); + } + let restarted = minter(dir.path(), 3600); + let bytes = restarted.mint(transports(443), NOW + 20).unwrap(); + assert_eq!(parse(&bytes).advertisement.sequence, 3); + } + + #[test] + fn ttl_is_clamped_to_the_record_maximum() { + let dir = tempfile::tempdir().unwrap(); + let m = minter(dir.path(), MAX_TTL_SECONDS * 10); + let bytes = m.mint(transports(443), NOW).unwrap(); + let ad = parse(&bytes).advertisement; + assert_eq!(ad.expires_at - ad.issued_at, MAX_TTL_SECONDS); + } +} diff --git a/pkgs/id/crates/id-web/src/lib.rs b/pkgs/id/crates/id-web/src/lib.rs index 539255fc70..f8a16526bc 100644 --- a/pkgs/id/crates/id-web/src/lib.rs +++ b/pkgs/id/crates/id-web/src/lib.rs @@ -58,6 +58,7 @@ mod security; mod seitan; mod tags_ws; mod templates; +mod transport_ad; pub mod world_ws; pub use content_mode::{ContentMode, MediaType, detect_mode, detect_mode_with_content}; @@ -492,6 +493,13 @@ pub struct AppState { /// for states built outside `id serve` (tests, embedded surfaces) — /// the send route then answers 503 rather than inventing an identity. pub transfer_endpoint: Option, + /// The transport-advertisement minter whose current signed ad + /// the `/.well-known/id-transport-advertisement` handler serves + /// (#8214 slice 4). `id serve` wires its node's minter in + /// through [`web_routers_with_surface`]; `None` for states + /// built anywhere else — the handler then answers 404 rather + /// than inventing an ad. + pub transport_ad: Option>, /// State for collaborative editing sessions. pub collab: Arc, /// Asset URLs (with cache-busting hashes). @@ -568,6 +576,7 @@ impl std::fmt::Debug for AppState { .field("cookie_secure", &self.cookie_secure) .field("groups_log", &self.groups_log) .field("seitan", &self.seitan) + .field("transport_ad", &self.transport_ad.is_some()) .finish() } } @@ -618,6 +627,7 @@ impl AppState { Ok(Self { store, transfer_endpoint: None, + transport_ad: None, collab: Arc::new(CollabState::new()), assets: load_asset_urls(), peers, @@ -654,6 +664,16 @@ impl AppState { pub fn set_transfer_endpoint(&mut self, endpoint: Option) { self.transfer_endpoint = endpoint; } + + /// Wire the serving node's transport-advertisement minter in + /// (#8214 slice 4). `id serve` passes its minter through + /// [`web_routers_with_surface`]; see [`AppState::transport_ad`]. + pub fn set_transport_ad( + &mut self, + minter: Option>, + ) { + self.transport_ad = minter; + } } /// Load asset URLs from the embedded manifest. @@ -829,6 +849,7 @@ pub async fn web_routers( groups_log, seitan, None, + None, ) .await?; Ok(routers) @@ -908,6 +929,7 @@ pub async fn web_routers_with_surface( groups_log: Option, seitan: SeitanState, transfer_endpoint: Option, + transport_ad: Option>, ) -> anyhow::Result<(Vec, WebSurfaceFactory)> { let mut state = match local_events { Some(events) => { @@ -935,6 +957,7 @@ pub async fn web_routers_with_surface( } }; state.set_transfer_endpoint(transfer_endpoint); + state.set_transport_ad(transport_ad); let surface = WebSurfaceFactory { state: state.clone(), world: world.clone(), diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index c815d6e0ec..0a5b2cf630 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -581,6 +581,10 @@ fn create_router_inner(state: AppState) -> Router { let router = Router::new() // Page routes (return full HTML pages) .route("/", get(index_handler)) + .route( + "/.well-known/id-transport-advertisement", + get(super::transport_ad::transport_advertisement_handler), + ) .route("/files", get(files_page_handler)) .route(&world_route, get(world_page_handler)) .route("/settings", get(settings_handler)) diff --git a/pkgs/id/crates/id-web/src/transport_ad.rs b/pkgs/id/crates/id-web/src/transport_ad.rs new file mode 100644 index 0000000000..c468f07254 --- /dev/null +++ b/pkgs/id/crates/id-web/src/transport_ad.rs @@ -0,0 +1,191 @@ +//! The `.well-known/id-transport-advertisement` endpoint (#8214 +//! slice 4, implementing Decision 2.2 of the #5793 record): the +//! server's own HTTPS endpoint serves its current signed transport +//! advertisement. This is the authoritative self-hosted substrate +//! — the handler serves the minter's current bytes byte-for-byte +//! and never re-encodes, re-signs, or invents an ad: with no +//! minter wired (any state built outside `id serve`) or a subject +//! that is not this server's, the answer is 404. The signature, +//! not this endpoint, is what the client trusts (Decision 1), so +//! the handler needs no per-request authorization logic of its +//! own beyond the router-wide WebSecurity guard every route here +//! already sits behind. + +use std::collections::HashMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::{ + extract::{Query, State}, + http::{StatusCode, header}, + response::{IntoResponse, Response}, +}; + +use super::AppState; + +/// `GET /.well-known/id-transport-advertisement?subject=`: +/// serve the current signed advertisement byte-for-byte. The +/// `subject` query parameter is the client's assertion of which +/// server it wants; this server publishes exactly one ad, so a +/// mismatched subject is a 404, never a different ad. An absent +/// subject serves the one ad (a browser or operator fetching the +/// endpoint directly gets the same bytes a client would). +pub(crate) async fn transport_advertisement_handler( + State(state): State, + Query(params): Query>, +) -> Response { + let Some(minter) = &state.transport_ad else { + return StatusCode::NOT_FOUND.into_response(); + }; + if let Some(subject) = params.get("subject") { + if subject != &minter.subject() { + return StatusCode::NOT_FOUND.into_response(); + } + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + match minter.current_bytes(now) { + Ok(Some(bytes)) => ( + StatusCode::OK, + [(header::CONTENT_TYPE, "application/json")], + bytes, + ) + .into_response(), + Ok(None) => StatusCode::NOT_FOUND.into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::{AppState, WebSecurity, create_router}; + use axum::{Router, body::Body, http::Request}; + use ed25519_dalek::SigningKey; + use id_core::transport_advertisement::{AdMinter, SequenceFile, TransportEntry, TransportKind}; + use id_store::tags::TagStore; + use iroh::endpoint::{Endpoint, RelayMode, presets}; + use iroh_blobs::{api::Store, store::mem::MemStore}; + use iroh_docs::protocol::Docs; + use iroh_gossip::net::Gossip; + use std::sync::Arc; + use tower::ServiceExt as _; + + // Oracle: the #5793 decision record, Decision 2.2 (well-known + // HTTPS serves the current signed ad byte-for-byte) and + // Decision 1 (the client trusts the signature, not the + // substrate). + + fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) + } + + async fn bare_state() -> (AppState, tempfile::TempDir) { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, "transport-ad-test", dir.path().join("meta")) + .await + .unwrap(), + ); + let state = AppState::new( + store, + None, + "transport-ad-test".to_owned(), + tags, + [9; 32], + dir.path().join(".identity.redb"), + ) + .await + .unwrap(); + (state, dir) + } + + async fn state_with_minter() -> (AppState, Arc, tempfile::TempDir) { + let (mut state, dir) = bare_state().await; + let minter = Arc::new(AdMinter::new( + SigningKey::from_bytes(&[7u8; 32]), + SequenceFile::new(dir.path().join("transport-ad.sequence")), + 3600, + )); + minter + .mint( + vec![TransportEntry { + kind: TransportKind::Tcp, + endpoint: "203.0.113.7:443".to_string(), + priority: 30, + broker: None, + }], + now(), + ) + .unwrap(); + state.transport_ad = Some(Arc::clone(&minter)); + (state, minter, dir) + } + + async fn get(router: Router, uri: &str) -> (StatusCode, Vec) { + let resp = router + .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + (status, bytes) + } + + #[tokio::test] + async fn serves_the_current_ad_byte_for_byte() { + let (state, minter, _dir) = state_with_minter().await; + let router = create_router(state, WebSecurity::default()); + let uri = format!( + "/.well-known/id-transport-advertisement?subject={}", + minter.subject() + ); + let (status, body) = get(router, &uri).await; + assert_eq!(status, StatusCode::OK); + let expected = minter.current_bytes(now()).unwrap().unwrap(); + assert_eq!( + body, expected, + "the handler serves the minted bytes verbatim" + ); + // And the served object is the verifiable signed ad. + let signed: id_core::transport_advertisement::SignedAdvertisement = + serde_json::from_slice(&body).unwrap(); + signed.verify(&minter.subject()).unwrap(); + } + + #[tokio::test] + async fn subject_mismatch_and_missing_minter_are_404() { + let (state, _minter, _dir) = state_with_minter().await; + let router = create_router(state, WebSecurity::default()); + let (status, _) = get( + router, + "/.well-known/id-transport-advertisement?subject=0000", + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let (bare_state, _dir2) = bare_state().await; + let router = create_router(bare_state, WebSecurity::default()); + let (status, _) = get(router, "/.well-known/id-transport-advertisement").await; + assert_eq!(status, StatusCode::NOT_FOUND); + } +}