From 3823d2a695d040bcde32c60ea5afc2342e119006 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 18:37:12 -0600 Subject: [PATCH 1/3] =?UTF-8?q?id(serve):=20apply=20dynamic=20publications?= =?UTF-8?q?=20live=20=E2=80=94=20web=20mounts,=20surface=20factory,=20serv?= =?UTF-8?q?e=20adapters=20(#2147=20slice=203a)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit id-web: PublicationMounts shared table on AppState; Explorer router intercepts mounted paths and serves the mounted world program surface (unmount restores the Explorer route); web_routers_with_surface + WebSurfaceFactory build program routers over the one shared state for dynamic listeners. id-cli: commands::serve_publications adapters (ServeListenerFactory binds real listeners with per-bind WebSecurity; ServeMountSink edits the shared mount table); cmd_serve constructs the PublicationManager over the persisted registry and restores it at boot — previously boot restore only logged the set. With no web surface, startup says the set was NOT applied instead of pretending. Tests: id-web publication filter 3 new tests (lookup x2, mount override/unmount restore) pass; id-cli serve_publications sink tests pass; publications suite 32 pass. --- pkgs/id/crates/id-cli/src/commands/mod.rs | 2 + pkgs/id/crates/id-cli/src/commands/serve.rs | 82 +++++- .../id-cli/src/commands/serve_publications.rs | 161 +++++++++++ pkgs/id/crates/id-web/src/lib.rs | 249 +++++++++++++++++- pkgs/id/crates/id-web/src/routes.rs | 115 +++++++- 5 files changed, 601 insertions(+), 8 deletions(-) create mode 100644 pkgs/id/crates/id-cli/src/commands/serve_publications.rs diff --git a/pkgs/id/crates/id-cli/src/commands/mod.rs b/pkgs/id/crates/id-cli/src/commands/mod.rs index e9f42fd7b5..8086644a05 100644 --- a/pkgs/id/crates/id-cli/src/commands/mod.rs +++ b/pkgs/id/crates/id-cli/src/commands/mod.rs @@ -71,6 +71,8 @@ pub mod put; pub mod repl; pub mod send; pub mod serve; +#[cfg(feature = "web")] +pub mod serve_publications; pub mod tag; pub mod text; #[cfg(feature = "world")] diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 531821dad9..b07ce8ea3a 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1534,9 +1534,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // startup log, and the boot shadow warnings the issue requires // are re-issued for any persisted mount that shadows an Explorer // route without an acknowledgement. Applying the set to live - // listeners is the next slice; a malformed registry fails startup - // loudly (in Registry::load) rather than restoring nothing - // silently. + // listeners happens below, once the web surface exists: the + // serve-owned PublicationManager restores it through the same + // apply path runtime publishes use (slice 3). A malformed + // registry fails startup loudly (in Registry::load) rather than + // restoring nothing silently. let publications = crate::publications::Registry::load(&crate::publications::publications_file())?; if !publications.publications.is_empty() { @@ -2157,6 +2159,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { } } + // #2147 slice 3: the web surface factory the configured + // listeners are built from, captured for the publication + // manager below (dynamic listeners and path mounts are built + // over the same shared web state). + #[cfg(feature = "web")] + let mut publication_surface: Option = None; + // Start the web servers now that the lock file is written: one // serve task per bound listener (#2145), each listener serving // the router for its #2146 content target (Explorer by default, @@ -2205,7 +2214,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); #[cfg(not(feature = "world"))] let seitan_state = id_web::SeitanState::default(); - let web_routers = id_web::web_routers( + let (web_routers, surface) = id_web::web_routers_with_surface( store_handle.clone(), Some(peer_discovery.clone()), node_id.to_string(), @@ -2221,6 +2230,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { seitan_state, ) .await?; + publication_surface = Some(surface); for ((listener_addr, listener, target), web_router) in web_listeners.into_iter().zip(web_routers) { @@ -2292,6 +2302,70 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { handles }; + // #2147 slice 3: apply the persisted publication set to the + // live web surface through the serve-owned PublicationManager: + // listener placements bind real listeners serving the published + // world's program surface, path mounts land in the Explorer + // routers' shared mount table. Restore goes through the same + // apply path as runtime publishes; a failure rolls back what + // was applied and fails startup loudly rather than serving a + // half-applied set. The manager stays alive for the life of + // the process (dropping it would orphan its listeners' handles + // without closing them; unpublish closes them explicitly). + // When no web surface is running there is nothing to apply a + // publication TO in this build/configuration: say so in the + // startup log instead of pretending the set was restored. + #[cfg(feature = "web")] + let _publication_manager: Option< + crate::commands::serve_publications::ServePublicationManager, + > = match publication_surface { + Some(surface) => { + let has_explorer = web_bindings + .iter() + .any(|binding| matches!(binding.target(), WebContentTarget::Explorer)); + let factory = crate::commands::serve_publications::ServeListenerFactory::new( + tokio::runtime::Handle::current(), + surface.clone(), + web_token.clone(), + ); + let sink = crate::commands::serve_publications::ServeMountSink::new( + surface.publication_mounts(), + has_explorer, + ); + let mut manager = crate::publications_runtime::PublicationManager::new( + publications, + crate::publications::publications_file(), + crate::publications::KNOWN_EXPLORER_ROUTES + .iter() + .map(|route| (*route).to_owned()) + .collect(), + factory, + sink, + ); + // Boot shadow warnings were already issued by the + // slice-1 block above; restore's copies are dropped. + let _warnings = manager.restore()?; + if !manager.registry().publications.is_empty() { + status!( + "publications: {} persisted publication(s) live", + manager.registry().publications.len() + ); + } + Some(manager) + } + None => { + if !publications.publications.is_empty() { + status!( + "publications: {} persisted publication(s) NOT applied \u{2014} \ + no web surface is running in this serve (dynamic \ + publications need the web interface)", + publications.publications.len() + ); + } + None + } + }; + #[cfg(feature = "ssh")] let ssh_handle = ssh.map(|(listener, ssh_port, hub, host_key, blobs)| { status!("world ssh: port {ssh_port} (ssh -p {ssh_port} @)"); diff --git a/pkgs/id/crates/id-cli/src/commands/serve_publications.rs b/pkgs/id/crates/id-cli/src/commands/serve_publications.rs new file mode 100644 index 0000000000..41ca3de74b --- /dev/null +++ b/pkgs/id/crates/id-cli/src/commands/serve_publications.rs @@ -0,0 +1,161 @@ +//! Serve-side adapters for dynamic publications (#2147 slice 3): +//! the real [`ListenerFactory`] / [`MountSink`] the serve-owned +//! [`PublicationManager`](crate::publications_runtime::PublicationManager) +//! drives. +//! +//! - The factory binds a real TCP listener and serves the published +//! world's program-only router (built by +//! [`id_web::WebSurfaceFactory`] over the serve process's one +//! shared web state) on a spawned task, with the per-bind +//! [`id_web::WebSecurity`] a configured listener for the same +//! address would get. Binding is synchronous at the socket level +//! (a staged listener exists before the manager persists the +//! publication, per the design's apply ordering); only serving is +//! async, on the captured runtime handle. +//! - The sink applies path mounts to the primary Explorer listener +//! by editing the shared [`id_web::PublicationMounts`] table the +//! Explorer routers consult per request, so a mount takes effect +//! -- and reverts -- with no router rebuild. + +use std::net::SocketAddr; + +use anyhow::{Context, Result}; + +use crate::publications_runtime::{ListenerFactory, LiveListener, MountSink}; + +/// The publication manager as `cmd_serve` instantiates it. +pub type ServePublicationManager = + crate::publications_runtime::PublicationManager; + +/// Opens live listeners for listener placements, serving the +/// published world's program surface on each. +pub struct ServeListenerFactory { + handle: tokio::runtime::Handle, + surface: id_web::WebSurfaceFactory, + web_token: Option, +} + +impl ServeListenerFactory { + /// A factory serving through `surface` (the serve process's + /// shared web state), guarding each dynamic listener with the + /// serve's web token policy for its bind address. + pub fn new( + handle: tokio::runtime::Handle, + surface: id_web::WebSurfaceFactory, + web_token: Option, + ) -> Self { + Self { + handle, + surface, + web_token, + } + } +} + +/// One live publication listener: a spawned `axum::serve` task. +struct ServeLiveListener { + actual_addr: SocketAddr, + task: tokio::task::JoinHandle<()>, +} + +impl LiveListener for ServeLiveListener { + fn actual_addr(&self) -> SocketAddr { + self.actual_addr + } + + fn close(self: Box) { + self.task.abort(); + } +} + +impl ListenerFactory for ServeListenerFactory { + fn bind(&mut self, world: &str, addr: SocketAddr) -> Result> { + let std_listener = std::net::TcpListener::bind(addr).with_context(|| { + format!("publication: failed to bind listener {addr} for world '{world}'") + })?; + std_listener.set_nonblocking(true)?; + let listener = tokio::net::TcpListener::from_std(std_listener)?; + let actual_addr = listener.local_addr()?; + // The same per-bind security a configured listener for this + // address receives in cmd_serve (#2145): token policy keyed + // to the bind IP, no extra grants. + let security = id_web::WebSecurity::for_bind(addr.ip(), self.web_token.clone(), &[]); + let router = self.surface.program_router(world, security); + let task = self.handle.spawn(async move { + if let Err(error) = axum::serve(listener, router).await { + tracing::error!("publication listener error: {error}"); + } + }); + Ok(Box::new(ServeLiveListener { actual_addr, task })) + } +} + +/// Applies path mounts to the primary Explorer listener through +/// the shared mount table. +pub struct ServeMountSink { + mounts: id_web::PublicationMounts, + has_explorer: bool, +} + +impl ServeMountSink { + /// A sink over the serve process's shared `mounts` table; + /// `has_explorer` records whether any configured listener + /// serves the Explorer surface (path mounts target the first + /// effective Explorer binding; with none, the manager refuses + /// the publish before persisting anything). + pub fn new(mounts: id_web::PublicationMounts, has_explorer: bool) -> Self { + Self { + mounts, + has_explorer, + } + } +} + +impl MountSink for ServeMountSink { + fn has_explorer(&self) -> bool { + self.has_explorer + } + + fn mount(&mut self, world: &str, path: &str) -> Result<()> { + self.mounts.mount(world, path); + Ok(()) + } + + fn unmount(&mut self, path: &str) -> Result<()> { + // PublicationMounts::unmount errors when nothing is mounted + // there, which is exactly this trait's contract: an error + // means the route was NOT removed. + self.mounts.unmount(path) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn sink_mounts_and_unmounts_through_the_shared_table() { + let mounts = id_web::PublicationMounts::new(); + let mut sink = ServeMountSink::new(mounts.clone(), true); + assert!(sink.has_explorer()); + sink.mount("arena", "/prog").unwrap(); + assert_eq!( + mounts.lookup("/prog"), + Some(("/prog".to_owned(), "arena".to_owned())) + ); + sink.unmount("/prog").unwrap(); + assert_eq!(mounts.lookup("/prog"), None); + // Contract: unmounting an absent mount errors. + assert!(sink.unmount("/prog").is_err()); + } + + #[test] + fn sink_without_explorer_reports_none() { + let mut sink = ServeMountSink::new(id_web::PublicationMounts::new(), false); + assert!(!sink.has_explorer()); + // Mounting itself is a table edit; the manager is what + // refuses it when has_explorer() is false. + sink.mount("arena", "/prog").unwrap(); + } +} diff --git a/pkgs/id/crates/id-web/src/lib.rs b/pkgs/id/crates/id-web/src/lib.rs index 8c596b0258..14d6170969 100644 --- a/pkgs/id/crates/id-web/src/lib.rs +++ b/pkgs/id/crates/id-web/src/lib.rs @@ -237,6 +237,99 @@ impl Drop for SavePermit { } } +/// Dynamic publication path mounts (#2147 slice 3): mount path -> +/// world name, shared by every clone of an [`AppState`] (all web +/// listeners of one serve process) and by the serve-owned publication +/// manager's mount sink. +/// +/// The Explorer router consults this table on every request, so a +/// mount applies and reverts at runtime without rebuilding any +/// router: publishing inserts a row, unpublishing removes it, and +/// the Explorer route the mount shadowed answers again. The table +/// is the live half only -- the persisted set is the publication +/// registry in `id-cli`, which owns validation (canonical paths, +/// shadow acknowledgement); rows here are already canonical. +#[derive(Clone, Default)] +pub struct PublicationMounts { + inner: Arc>>, +} + +impl std::fmt::Debug for PublicationMounts { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PublicationMounts") + .field("mounts", &self.snapshot()) + .finish() + } +} + +impl PublicationMounts { + /// An empty mount table. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + fn read(&self) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap> { + self.inner + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn write(&self) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.inner + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Mount `world` at the canonical mount `path`, replacing any + /// mount already there (the registry refuses a second publish + /// at a taken placement before this is ever called). + pub fn mount(&self, world: &str, path: &str) { + self.write().insert(path.to_owned(), world.to_owned()); + } + + /// Remove the mount at `path`, restoring the Explorer route. + /// + /// # Errors + /// + /// Fails when nothing is mounted at `path` -- the publication + /// manager's `MountSink` contract relies on this: an error + /// means the route was NOT removed, so the manager restores + /// the persisted registry entry it had already saved away. + pub fn unmount(&self, path: &str) -> anyhow::Result<()> { + anyhow::ensure!( + self.write().remove(path).is_some(), + "no publication is mounted at {path}" + ); + Ok(()) + } + + /// The mount governing `request_path`, if any: the longest + /// mount path that equals the request path or is a whole-segment + /// prefix of it. The root mount (`/`) governs every path. + /// Returns `(mount_path, world)`. + #[must_use] + pub fn lookup(&self, request_path: &str) -> Option<(String, String)> { + self.read() + .iter() + .filter(|(mount, _)| { + mount.as_str() == "/" + || request_path == mount.as_str() + || request_path + .strip_prefix(mount.as_str()) + .is_some_and(|rest| rest.starts_with('/')) + }) + .max_by_key(|(mount, _)| mount.len()) + .map(|(mount, world)| (mount.clone(), world.clone())) + } + + /// A snapshot of the live mounts (mount path -> world). + #[must_use] + pub fn snapshot(&self) -> std::collections::BTreeMap { + self.read().clone() + } +} + /// Shared application state for web handlers. /// /// Contains references to the blob store, collaborative editing state, @@ -282,6 +375,11 @@ pub struct AppState { /// phase 2), when this state's router is a program surface. /// `None` for Explorer routers. Set by `create_program_router`. pub program_world: Option, + /// Dynamic publication path mounts (#2147 slice 3), shared with + /// the serve-owned publication manager: the live mount table + /// the Explorer router consults per request. Empty (inert) for + /// states that serve no publications. + pub publication_mounts: PublicationMounts, /// Mark the directory explorer's session cookies `Secure`. pub cookie_secure: bool, /// The resolved group-log path for the read-only `/groups` page @@ -309,6 +407,7 @@ impl std::fmt::Debug for AppState { .field("identity", &self.identity) .field("local_events", &"") .field("world", &self.world) + .field("publication_mounts", &self.publication_mounts) .field("cookie_secure", &self.cookie_secure) .field("groups_log", &self.groups_log) .field("seitan", &self.seitan) @@ -379,6 +478,7 @@ impl AppState { web_route: "/world".to_owned(), web_socket: Some("/ws/world".to_owned()), program_world: None, + publication_mounts: PublicationMounts::new(), cookie_secure: false, groups_log: None, seitan: SeitanState::default(), @@ -544,6 +644,99 @@ pub async fn web_routers( groups_log: Option, seitan: SeitanState, ) -> anyhow::Result> { + let (routers, _surface) = web_routers_with_surface( + store, + peers, + node_id, + tag_store, + secret_key, + identity_db_path, + securities, + world, + cookie_secure, + local_events, + surfaces, + groups_log, + seitan, + ) + .await?; + Ok(routers) +} + +/// A factory for building further routers over the SAME shared +/// [`AppState`] the configured listeners were built from (#2147 +/// slice 3). The identity store opens exclusively, so a dynamic +/// publication listener cannot build a second state -- it builds +/// its program router here, over a clone of the one shared state, +/// with its own per-bind [`WebSecurity`]. The factory also carries +/// the process's [`PublicationMounts`] table (the same instance +/// every router clone consults), which is how the serve-owned +/// publication manager applies path mounts to the Explorer +/// listeners without rebuilding them. +#[derive(Clone)] +pub struct WebSurfaceFactory { + state: AppState, + world: Option, + cookie_secure: bool, + groups_log: Option, + seitan: SeitanState, +} + +impl std::fmt::Debug for WebSurfaceFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WebSurfaceFactory") + .field("publication_mounts", &self.state.publication_mounts) + .field("world", &self.world.is_some()) + .field("cookie_secure", &self.cookie_secure) + .field("groups_log", &self.groups_log) + .finish() + } +} + +impl WebSurfaceFactory { + /// The shared dynamic-publication mount table. + #[must_use] + pub fn publication_mounts(&self) -> PublicationMounts { + self.state.publication_mounts.clone() + } + + /// The program-only router for `world_name`, finished with + /// `security` -- exactly the router a configured program + /// listener for that world would serve (#2146 phase 2), built + /// on demand for a dynamic publication listener. + #[must_use] + pub fn program_router(&self, world_name: &str, security: WebSecurity) -> Router { + finish_router( + self.state.clone(), + security, + self.world.clone(), + self.cookie_secure, + Some(world_name.to_owned()), + self.groups_log.clone(), + self.seitan.clone(), + ) + } +} + +/// Like [`web_routers`], and also returns the [`WebSurfaceFactory`] +/// over the shared state, for dynamic publication listeners and +/// path mounts (#2147 slice 3). +#[allow(clippy::too_many_arguments)] +pub async fn web_routers_with_surface( + store: Store, + peers: Option, + node_id: String, + tag_store: Arc, + secret_key: [u8; 32], + identity_db_path: std::path::PathBuf, + securities: Vec, + world: Option, + cookie_secure: bool, + local_events: Option>>, + surfaces: Vec>, + groups_log: Option, + seitan: SeitanState, +) -> anyhow::Result<(Vec, WebSurfaceFactory)> { let state = match local_events { Some(events) => { AppState::with_local_events( @@ -569,7 +762,14 @@ pub async fn web_routers( .await? } }; - Ok(securities + let surface = WebSurfaceFactory { + state: state.clone(), + world: world.clone(), + cookie_secure, + groups_log: groups_log.clone(), + seitan: seitan.clone(), + }; + let routers = securities .into_iter() .zip(surfaces) .map(|(security, surface)| { @@ -583,7 +783,8 @@ pub async fn web_routers( seitan.clone(), ) }) - .collect()) + .collect(); + Ok((routers, surface)) } /// Applies the world/cookie settings and delegates security to the public @@ -1087,3 +1288,47 @@ mod tests { broadcast_chat(&mut program_client, &mut explorer_client, "from-program").await; } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod publication_mounts_tests { + use super::PublicationMounts; + + #[test] + fn lookup_matches_whole_segments_and_prefers_the_longest_mount() { + let mounts = PublicationMounts::new(); + assert_eq!(mounts.lookup("/prog"), None); + mounts.mount("arena", "/prog"); + mounts.mount("deep", "/prog/deep"); + assert_eq!( + mounts.lookup("/prog"), + Some(("/prog".to_owned(), "arena".to_owned())) + ); + assert_eq!( + mounts.lookup("/prog/"), + Some(("/prog".to_owned(), "arena".to_owned())) + ); + assert_eq!( + mounts.lookup("/prog/deep/x"), + Some(("/prog/deep".to_owned(), "deep".to_owned())) + ); + // A merely string-prefixed path is not under the mount. + assert_eq!(mounts.lookup("/program"), None); + assert_eq!(mounts.lookup("/other"), None); + } + + #[test] + fn root_mount_governs_everything_and_unmount_reports_absence() { + let mounts = PublicationMounts::new(); + mounts.mount("arena", "/"); + assert_eq!( + mounts.lookup("/anything/at/all"), + Some(("/".to_owned(), "arena".to_owned())) + ); + mounts.unmount("/").unwrap(); + assert_eq!(mounts.lookup("/anything"), None); + // The MountSink contract: unmounting what is not mounted is + // an error (the route was not removed), never a silent Ok. + assert!(mounts.unmount("/").is_err()); + } +} diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index 6befa080d1..3af0e86f0c 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -661,9 +661,74 @@ fn create_router_inner(state: AppState) -> Router { } None => router.merge(super::world_ws::world_http_routes().with_state(world_state)), }; - router + let router = router .layer(DefaultBodyLimit::max(DEFAULT_BODY_LIMIT)) - .with_state(state) + .with_state(state.clone()); + // #2147 slice 3: dynamic publication mounts intercept here -- + // inside the listener's security guard (applied by the caller + // around this router), above every Explorer route, so a mount + // overrides the Explorer route it shadows and unmounting + // restores it with no router rebuild. + router.layer(axum::middleware::from_fn_with_state( + state, + publication_mount_layer, + )) +} + +/// #2147 slice 3: serve a dynamic publication mount. When the +/// request path falls under a live mount (see +/// [`PublicationMounts::lookup`]), the request is rewritten to the +/// mount-relative path and answered by the mounted world's +/// program-only router (the #2146 phase-2 surface, built on demand +/// over the same shared state); anything else falls through to the +/// Explorer routes unchanged. +/// +/// The listener's own [`WebSecurity`] has already run (this layer +/// sits inside `security::protect`), so the program router is +/// built with the default policy -- re-applying the listener +/// policy here would double-guard the request, not widen it. +/// +/// Known limit: WebSocket upgrades under a mount do not complete, +/// because the on-demand dispatch has no hyper upgrade handle to +/// offer the world bridge; the program page and its HTTP surface +/// serve normally. Dynamic publication *listeners* serve the same +/// router through `axum::serve` directly and have no such limit. +async fn publication_mount_layer( + State(state): State, + req: axum::http::Request, + next: axum::middleware::Next, +) -> Response { + let path = req.uri().path().to_owned(); + let Some((mount, world)) = state.publication_mounts.lookup(&path) else { + return next.run(req).await; + }; + let rest: String = if mount == "/" { + path.clone() + } else if path.len() == mount.len() { + "/".to_owned() + } else { + path[mount.len()..].to_owned() + }; + let path_and_query = match req.uri().query() { + Some(query) => format!("{rest}?{query}"), + None => rest, + }; + let Ok(path_and_query) = path_and_query.parse::() else { + return next.run(req).await; + }; + let mut uri_parts = req.uri().clone().into_parts(); + uri_parts.path_and_query = Some(path_and_query); + let Ok(new_uri) = axum::http::Uri::from_parts(uri_parts) else { + return next.run(req).await; + }; + let (mut parts, body) = req.into_parts(); + parts.uri = new_uri; + let req = axum::http::Request::from_parts(parts, body); + let router = create_program_router(state, &world, WebSecurity::default()); + match tower::ServiceExt::oneshot(router, req).await { + Ok(response) => response, + Err(error) => match error {}, + } } /// The program-only surface's root: the program frontend for the @@ -2320,6 +2385,52 @@ mod upload_router_tests { ) } + #[tokio::test] + async fn publication_mount_overrides_explorer_and_unmount_restores_it() { + let (_, mut state, _dir, _endpoint, _docs) = router_with_state().await; + state.world = Some(hub_with_world("arena", Some("s3cret"))); + let app = create_router(state.clone(), WebSecurity::default()); + + // Before any mount, /prog is not an Explorer route. + let before = app + .clone() + .oneshot(Request::builder().uri("/prog").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(before.status(), StatusCode::NOT_FOUND); + + // Mounting at runtime (no router rebuild) makes /prog serve + // the mounted world's program surface. + state.publication_mounts.mount("arena", "/prog"); + let mounted = app + .clone() + .oneshot(Request::builder().uri("/prog").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(mounted.status(), StatusCode::OK); + let body = to_bytes(mounted.into_body(), usize::MAX).await.unwrap(); + let text = String::from_utf8_lossy(&body); + assert!(text.contains("data-world-program=\"arena\""), "{text}"); + + // The Explorer root is untouched while the mount lives. + let root = app + .clone() + .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(root.status(), StatusCode::OK); + let body = to_bytes(root.into_body(), usize::MAX).await.unwrap(); + assert!(!String::from_utf8_lossy(&body).contains("data-world-program")); + + // Unmounting restores the Explorer answer at /prog. + state.publication_mounts.unmount("/prog").unwrap(); + let after = app + .oneshot(Request::builder().uri("/prog").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(after.status(), StatusCode::NOT_FOUND); + } + #[tokio::test] async fn program_router_serves_only_the_program_surface() { let (_, mut state, _dir, _endpoint, _docs) = router_with_state().await; From c1c9f3ed46ee3cade9cc05e6760d977c3e1a5fe2 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 18:52:32 -0600 Subject: [PATCH 2/3] id(serve): operator publication control + CLI publish/unpublish/publications (#2147 slice 3b) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit id-sync: MetaRequest Publish/Unpublish/ListPublications (appended per the wire append-only rule) + MetaResponse counterparts; PublicationControl trait + handle + shared slot on MetaProtocol. handle() gates publication requests before the store write gate: only the serving node's own authenticated identity is answered, however open the write policy is; an empty slot fails with an explanatory error. id-cli: ServePublicationControl bridges the protocol control to the serve-owned PublicationManager (Arc, registered from cmd_serve after restore); create_local_operator_endpoint presents the node's own key; commands::publish implements the CLI — remote-only, actionable no-serve error, never a local-store fallback. CLI Publish/Unpublish/Publications variants + facade dispatch. Tests: id-sync publication_control_tests 4 pass (postcard roundtrip incl. SocketAddr, operator-only under open writes, empty-slot error, dispatch); id-cli CLI parse tests 3 pass; serve_publications sink tests still pass. --- pkgs/id/crates/id-cli/src/cli/mod.rs | 41 ++ pkgs/id/crates/id-cli/src/cli/tests.rs | 59 +++ pkgs/id/crates/id-cli/src/commands/client.rs | 27 +- pkgs/id/crates/id-cli/src/commands/mod.rs | 4 +- pkgs/id/crates/id-cli/src/commands/publish.rs | 134 ++++++ pkgs/id/crates/id-cli/src/commands/serve.rs | 20 +- .../id-cli/src/commands/serve_publications.rs | 99 ++++- pkgs/id/crates/id-sync/src/protocol.rs | 402 +++++++++++++++++- pkgs/id/src/main.rs | 18 + 9 files changed, 798 insertions(+), 6 deletions(-) create mode 100644 pkgs/id/crates/id-cli/src/commands/publish.rs diff --git a/pkgs/id/crates/id-cli/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs index 14e1f3f45d..2d432cbd30 100644 --- a/pkgs/id/crates/id-cli/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -646,6 +646,47 @@ pub enum Command { /// id serve --replace-defaults /// ``` Serve(ServeArgs), + /// Publish a program (world) on the RUNNING `id serve` (#2147). + /// + /// Drives the serve process's publication manager: the program + /// goes live without restarting the node, and the publication + /// persists across restarts. Exactly one placement is required: + /// `--listen ADDR` for a dedicated listener, or `--path PATH` + /// for a mount on the primary Explorer listener. A path mount + /// that shadows an Explorer route is refused unless + /// `--acknowledge-shadow` is passed. Operator-only: the command + /// connects with the serve node's own key, and fails when no + /// serve is running (it never edits local state directly). + Publish { + /// The world (program) name to publish. + world: String, + /// Publish on a dedicated listener at this address + /// (e.g. `127.0.0.1:8080`; port 0 = OS-assigned). + #[arg(long, conflicts_with = "path")] + listen: Option, + /// Publish as a path mount on the primary Explorer + /// listener (e.g. `/prog`). + #[arg(long)] + path: Option, + /// Acknowledge that a path mount shadows an Explorer + /// route ("I know I'm doing this"). + #[arg(long)] + acknowledge_shadow: bool, + }, + /// Remove a dynamic publication from the RUNNING `id serve` + /// (#2147): the listener closes or the Explorer route is + /// restored, without restarting the node. + Unpublish { + /// Unpublish the dedicated listener at this address. + #[arg(long, conflicts_with = "path")] + listen: Option, + /// Unpublish the path mount at this path. + #[arg(long)] + path: Option, + }, + /// List the RUNNING `id serve`'s dynamic publications (#2147), + /// with live listener addresses. + Publications, /// Start an interactive REPL for issuing commands. /// /// The REPL provides a shell-like interface for executing multiple diff --git a/pkgs/id/crates/id-cli/src/cli/tests.rs b/pkgs/id/crates/id-cli/src/cli/tests.rs index 98db39a5f9..61a03a25c5 100644 --- a/pkgs/id/crates/id-cli/src/cli/tests.rs +++ b/pkgs/id/crates/id-cli/src/cli/tests.rs @@ -665,6 +665,65 @@ fn test_cli_parse_list() { } } +#[test] +fn test_cli_parse_publish_listener() { + let cli = Cli::parse_from(["id", "publish", "arena", "--listen", "127.0.0.1:8080"]); + match cli.command { + Some(Command::Publish { + world, + listen, + path, + acknowledge_shadow, + }) => { + assert_eq!(world, "arena"); + assert_eq!(listen.as_deref(), Some("127.0.0.1:8080")); + assert!(path.is_none()); + assert!(!acknowledge_shadow); + } + _ => panic!("Expected Publish command"), + } +} + +#[test] +fn test_cli_parse_publish_path_with_acknowledgement() { + let cli = Cli::parse_from([ + "id", + "publish", + "arena", + "--path", + "/world", + "--acknowledge-shadow", + ]); + match cli.command { + Some(Command::Publish { + world, + listen, + path, + acknowledge_shadow, + }) => { + assert_eq!(world, "arena"); + assert!(listen.is_none()); + assert_eq!(path.as_deref(), Some("/world")); + assert!(acknowledge_shadow); + } + _ => panic!("Expected Publish command"), + } +} + +#[test] +fn test_cli_parse_unpublish_and_publications() { + let cli = Cli::parse_from(["id", "unpublish", "--path", "/world"]); + match cli.command { + Some(Command::Unpublish { listen, path }) => { + assert!(listen.is_none()); + assert_eq!(path.as_deref(), Some("/world")); + } + _ => panic!("Expected Unpublish command"), + } + let cli = Cli::parse_from(["id", "publications"]); + assert!(matches!(cli.command, Some(Command::Publications))); +} + #[test] fn test_cli_parse_list_remote() { let node_id = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; diff --git a/pkgs/id/crates/id-cli/src/commands/client.rs b/pkgs/id/crates/id-cli/src/commands/client.rs index 029c99bf08..7b1061347f 100644 --- a/pkgs/id/crates/id-cli/src/commands/client.rs +++ b/pkgs/id/crates/id-cli/src/commands/client.rs @@ -25,7 +25,7 @@ use iroh::endpoint::{Endpoint, RelayMode, presets}; use iroh_base::{EndpointAddr, TransportAddr}; use super::serve::ServeInfo; -use crate::{CLIENT_KEY_FILE, load_or_create_keypair}; +use crate::{CLIENT_KEY_FILE, KEY_FILE, load_or_create_keypair}; /// Creates a client endpoint configured to connect to a local serve. /// @@ -65,7 +65,30 @@ use crate::{CLIENT_KEY_FILE, load_or_create_keypair}; pub async fn create_local_client_endpoint( serve_info: &ServeInfo, ) -> Result<(Endpoint, EndpointAddr)> { - let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; + create_local_endpoint_with_key(serve_info, CLIENT_KEY_FILE).await +} + +/// Creates an endpoint that connects to a local serve AS the serve +/// node itself (#2147 operator endpoint). +/// +/// Publication control is operator-only: the serve handler answers +/// publish/unpublish/list requests only from its own authenticated +/// identity, so the local publication CLI presents the node's own +/// keypair (the same `KEY_FILE` serve loaded). Holding that key +/// file is the operator credential -- the design's trade-off, +/// chosen over widening the remote write policy to listener and +/// route changes. +pub async fn create_local_operator_endpoint( + serve_info: &ServeInfo, +) -> Result<(Endpoint, EndpointAddr)> { + create_local_endpoint_with_key(serve_info, KEY_FILE).await +} + +async fn create_local_endpoint_with_key( + serve_info: &ServeInfo, + key_file: &str, +) -> Result<(Endpoint, EndpointAddr)> { + let client_key = load_or_create_keypair(key_file).await?; // The server's loopback addresses come from the lock file, so no relay and // no address lookup (DNS, pkarr, mDNS) are needed. Using the full N0 preset // here made every CLI command probe relays and publish this client's info diff --git a/pkgs/id/crates/id-cli/src/commands/mod.rs b/pkgs/id/crates/id-cli/src/commands/mod.rs index 8086644a05..a1b285921e 100644 --- a/pkgs/id/crates/id-cli/src/commands/mod.rs +++ b/pkgs/id/crates/id-cli/src/commands/mod.rs @@ -67,6 +67,7 @@ pub mod list; #[cfg(feature = "sandbox")] pub mod match_audit; pub mod peers; +pub mod publish; pub mod put; pub mod repl; pub mod send; @@ -80,7 +81,7 @@ pub mod world; pub mod writer_set; pub use claim::cmd_claim; -pub use client::create_local_client_endpoint; +pub use client::{create_local_client_endpoint, create_local_operator_endpoint}; pub use doc::cmd_doc; pub use find::{ PeekOptions, SearchOptions, cmd_find, cmd_find_matches, cmd_peek, cmd_search, cmd_show, @@ -93,6 +94,7 @@ pub use list::{cmd_list, cmd_list_remote}; #[cfg(feature = "sandbox")] pub use match_audit::cmd_match_audit; pub use peers::{PeersOptions, cmd_peers}; +pub use publish::{cmd_publications, cmd_publish, cmd_unpublish}; pub use put::{ cmd_put_hash, cmd_put_local_file, cmd_put_local_stdin, cmd_put_multi, cmd_put_one, cmd_put_one_remote, diff --git a/pkgs/id/crates/id-cli/src/commands/publish.rs b/pkgs/id/crates/id-cli/src/commands/publish.rs new file mode 100644 index 0000000000..c054bb98d5 --- /dev/null +++ b/pkgs/id/crates/id-cli/src/commands/publish.rs @@ -0,0 +1,134 @@ +//! CLI publication commands (#2147 slice 3b): `id publish`, +//! `id unpublish`, `id publications`. +//! +//! These commands drive the publication manager of the RUNNING +//! `id serve` process, through the meta protocol's operator-only +//! publication requests. Two design rules (2026-11-04 decision on +//! #2147) shape everything here: +//! +//! - **Operator-only.** The connection presents the serve node's +//! own keypair ([`create_local_operator_endpoint`]); the handler +//! refuses every other identity, however open the node's write +//! policy is. Holding the node's key file is the credential. +//! - **Never a local fallback.** If no serve is running, the +//! command fails with an actionable error. It does NOT edit the +//! persisted registry itself and does NOT open the local stores: +//! a publication command that reports success without changing +//! the running server is exactly the failure the design forbids. + +use anyhow::{Result, bail}; + +use crate::META_ALPN; +use crate::commands::client::create_local_operator_endpoint; +use crate::commands::serve::get_serve_info; +use crate::meta_client::{expect_ok, request_over}; +use crate::protocol::{MetaRequest, MetaResponse, WirePlacement, WirePublication}; + +/// Publish `world` on the running serve: at `--listen ADDR` (a +/// dedicated listener) or `--path PATH` (a mount on the primary +/// Explorer listener). Exactly one placement is required. +pub async fn cmd_publish( + world: &str, + listen: Option<&str>, + path: Option<&str>, + acknowledge_shadow: bool, +) -> Result<()> { + let placement = placement_from_args(listen, path)?; + let described = describe_placement(&placement); + let publication = WirePublication { + world: world.to_owned(), + placement, + acknowledge_shadow, + }; + match operator_request(MetaRequest::Publish { publication }).await? { + MetaResponse::Published { warning } => { + println!("published {world} at {described}"); + if let Some(warning) = warning { + eprintln!("warning: {warning}"); + } + Ok(()) + } + other => bail!("unexpected response from serve: {other:?}"), + } +} + +/// Remove the publication at `--listen ADDR` or `--path PATH` from +/// the running serve. +pub async fn cmd_unpublish(listen: Option<&str>, path: Option<&str>) -> Result<()> { + let placement = placement_from_args(listen, path)?; + let described = describe_placement(&placement); + match operator_request(MetaRequest::Unpublish { placement }).await? { + MetaResponse::Unpublished { success: true } => { + println!("unpublished {described}"); + Ok(()) + } + other => bail!("unexpected response from serve: {other:?}"), + } +} + +/// List the running serve's live publications. +pub async fn cmd_publications() -> Result<()> { + match operator_request(MetaRequest::ListPublications).await? { + MetaResponse::Publications { items } => { + if items.is_empty() { + println!("no dynamic publications"); + } + for item in &items { + let live = match &item.placement { + WirePlacement::Listener { .. } => match item.actual_addr { + Some(actual) => format!(" (live at {actual})"), + None => " (not live)".to_owned(), + }, + WirePlacement::PathMount { .. } => String::new(), + }; + println!( + "{} at {}{}", + item.world, + describe_placement(&item.placement), + live + ); + } + Ok(()) + } + other => bail!("unexpected response from serve: {other:?}"), + } +} + +fn placement_from_args(listen: Option<&str>, path: Option<&str>) -> Result { + match (listen, path) { + (Some(addr), None) => Ok(WirePlacement::Listener { + addr: addr + .parse() + .map_err(|error| anyhow::anyhow!("invalid --listen address {addr:?}: {error}"))?, + }), + (None, Some(path)) => Ok(WirePlacement::PathMount { + path: path.to_owned(), + }), + _ => bail!("exactly one placement is required: --listen ADDR or --path PATH"), + } +} + +fn describe_placement(placement: &WirePlacement) -> String { + match placement { + WirePlacement::Listener { addr } => format!("listener {addr}"), + WirePlacement::PathMount { path } => format!("path {path}"), + } +} + +/// Send one publication request to the running serve, as the +/// operator. Fails (never falls back) when no serve is running. +async fn operator_request(req: MetaRequest) -> Result { + let Some(info) = get_serve_info().await else { + bail!( + "no `id serve` is running for this data directory — publication \ + commands drive the running serve process and never edit local \ + state directly; start one with `id serve --web` first" + ); + }; + let (endpoint, addr) = create_local_operator_endpoint(&info).await?; + let conn = id_core::connectivity::connect(&endpoint, addr, META_ALPN).await?; + let response = request_over(&conn, &req).await; + conn.close(0u32.into(), b"done"); + endpoint.close().await; + expect_ok(response?) +} diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index b07ce8ea3a..6f736d0b26 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1870,6 +1870,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(all(feature = "world", feature = "ssh"))] let (ssh_tunnel, ssh_tunnel_port) = id_worlds::world_ssh::SshTunnelProtocol::deferred(); + // #2147 slice 3b: a second handle on the meta handler, kept so + // the publication manager built below can register its + // operator control with the already-registered handler. + #[cfg(feature = "web")] + let meta_handle = Arc::clone(&meta); let router_builder = Router::builder(endpoint) .accept(META_ALPN, meta) .accept(BLOBS_ALPN, blobs) @@ -2317,7 +2322,9 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // startup log instead of pretending the set was restored. #[cfg(feature = "web")] let _publication_manager: Option< - crate::commands::serve_publications::ServePublicationManager, + std::sync::Arc< + std::sync::Mutex, + >, > = match publication_surface { Some(surface) => { let has_explorer = web_bindings @@ -2351,6 +2358,17 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { manager.registry().publications.len() ); } + // Slice 3b: share the manager with the meta protocol's + // operator-only publication control, so `id publish` / + // `id unpublish` / `id publications` drive THIS manager + // in the running process. + let manager = std::sync::Arc::new(std::sync::Mutex::new(manager)); + meta_handle.set_publication_control( + crate::commands::serve_publications::ServePublicationControl::new( + std::sync::Arc::clone(&manager), + ) + .handle(), + ); Some(manager) } None => { diff --git a/pkgs/id/crates/id-cli/src/commands/serve_publications.rs b/pkgs/id/crates/id-cli/src/commands/serve_publications.rs index 41ca3de74b..ee50b98f1c 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve_publications.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve_publications.rs @@ -17,11 +17,19 @@ //! Explorer routers consult per request, so a mount takes effect //! -- and reverts -- with no router rebuild. +use std::future::Future; use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; use anyhow::{Context, Result}; -use crate::publications_runtime::{ListenerFactory, LiveListener, MountSink}; +use crate::protocol::{ + PublicationControl, PublicationControlHandle, PublicationOp, PublicationOutcome, WirePlacement, + WirePublicationStatus, +}; +use crate::publications::{Placement, Publication}; +use crate::publications_runtime::{ListenerFactory, LiveListener, MountSink, PublicationStatus}; /// The publication manager as `cmd_serve` instantiates it. pub type ServePublicationManager = @@ -159,3 +167,92 @@ mod tests { sink.mount("arena", "/prog").unwrap(); } } + +/// The meta-protocol publication control over the serve-owned +/// manager (#2147 slice 3b): the bridge the protocol handler's +/// operator gate dispatches to. One control per serve process, +/// registered with the handler once the manager exists. +pub struct ServePublicationControl { + manager: Arc>, +} + +impl ServePublicationControl { + /// A control over the serve process's shared manager. + pub fn new(manager: Arc>) -> Self { + Self { manager } + } + + /// This control as the handle the protocol handler stores. + #[must_use] + pub fn handle(self) -> PublicationControlHandle { + PublicationControlHandle::new(Arc::new(self)) + } +} + +impl PublicationControl for ServePublicationControl { + fn call( + &self, + op: PublicationOp, + ) -> Pin> + Send + '_>> { + Box::pin(async move { + // The manager's operations are synchronous and short + // (validate, bind a socket, save a small JSON registry, + // edit the mount table), so they run under the lock + // directly: the lock is also what serializes operator + // requests against each other, as the design requires + // of the serve-owned manager. + let mut manager = self + .manager + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + match op { + PublicationOp::Publish(wire) => { + let warning = manager + .publish(publication_from_wire(wire)) + .map_err(|error| format!("{error:#}"))?; + Ok(PublicationOutcome::Published { warning }) + } + PublicationOp::Unpublish(wire) => { + manager + .unpublish(&placement_from_wire(&wire)) + .map_err(|error| format!("{error:#}"))?; + Ok(PublicationOutcome::Unpublished) + } + PublicationOp::List => Ok(PublicationOutcome::Listed { + items: manager.list().into_iter().map(status_to_wire).collect(), + }), + } + }) + } +} + +fn publication_from_wire(wire: crate::protocol::WirePublication) -> Publication { + Publication { + world: wire.world, + placement: placement_from_wire(&wire.placement), + acknowledge_shadow: wire.acknowledge_shadow, + } +} + +fn placement_from_wire(wire: &WirePlacement) -> Placement { + match wire { + WirePlacement::Listener { addr } => Placement::Listener { addr: *addr }, + WirePlacement::PathMount { path } => Placement::PathMount { path: path.clone() }, + } +} + +fn placement_to_wire(placement: &Placement) -> WirePlacement { + match placement { + Placement::Listener { addr } => WirePlacement::Listener { addr: *addr }, + Placement::PathMount { path } => WirePlacement::PathMount { path: path.clone() }, + } +} + +fn status_to_wire(status: PublicationStatus) -> WirePublicationStatus { + WirePublicationStatus { + world: status.publication.world.clone(), + placement: placement_to_wire(&status.publication.placement), + acknowledge_shadow: status.publication.acknowledge_shadow, + actual_addr: status.actual_addr, + } +} diff --git a/pkgs/id/crates/id-sync/src/protocol.rs b/pkgs/id/crates/id-sync/src/protocol.rs index 9eab0fd72b..5f05943c0e 100644 --- a/pkgs/id/crates/id-sync/src/protocol.rs +++ b/pkgs/id/crates/id-sync/src/protocol.rs @@ -58,7 +58,7 @@ //! - [`MatchKind::Prefix`]: Name/hash starts with query (good) //! - [`MatchKind::Contains`]: Name/hash contains query anywhere (okay) -use std::{sync::Arc, time::Duration}; +use std::{net::SocketAddr, sync::Arc, time::Duration}; use futures_lite::StreamExt; use iroh::EndpointAddr; @@ -661,6 +661,30 @@ pub enum MetaRequest { /// and replaced. replace: bool, }, + /// Publish a program (world) on the running serve process + /// (#2147 dynamic publications). + /// + /// OPERATOR-ONLY: the handler answers this only when the + /// authenticated caller is the serving node's own identity -- + /// the ordinary write gate is NOT sufficient, and `--open-writes` + /// / `--allow-node` never grant it (changing a node's listeners + /// and routes is an operator act, per the #2147 design decision + /// of 2026-11-04). The local CLI connects with the node's own + /// key to make these requests. + Publish { + /// The publication to apply. + publication: WirePublication, + }, + /// Remove a dynamic publication from the running serve process + /// (#2147). OPERATOR-ONLY, like [`MetaRequest::Publish`]. + Unpublish { + /// The placement to remove. + placement: WirePlacement, + }, + /// List the running serve process's dynamic publications + /// (#2147), with live addresses. OPERATOR-ONLY, like + /// [`MetaRequest::Publish`]: the live set is operator state. + ListPublications, } impl MetaRequest { @@ -676,10 +700,138 @@ impl MetaRequest { | Self::DelTag { .. } | Self::MigrateTags | Self::Send { .. } + | Self::Publish { .. } + | Self::Unpublish { .. } ) } } +/// Where a published program is placed, on the wire (#2147). +/// Mirrors the persisted placement model in `id-cli`'s publications +/// registry; the serve-side control converts between the two. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum WirePlacement { + /// A dedicated listener for this program alone, serving at `/`. + Listener { + /// The listener's socket address (port 0 = OS-assigned). + addr: SocketAddr, + }, + /// A path mount on the node's primary (Explorer) listener. + PathMount { + /// The canonical mount path. + path: String, + }, +} + +/// One published program on the wire (#2147): a world target at one +/// placement. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WirePublication { + /// The world/program name being published. + pub world: String, + /// Where it is published. + pub placement: WirePlacement, + /// The operator's explicit "I know this shadows an Explorer + /// route" acknowledgement for path mounts. + pub acknowledge_shadow: bool, +} + +/// One publication as [`MetaRequest::ListPublications`] reports it: +/// the persisted record plus its live address. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WirePublicationStatus { + /// The world/program name. + pub world: String, + /// Where it is published. + pub placement: WirePlacement, + /// The shadow acknowledgement recorded for the publication. + pub acknowledge_shadow: bool, + /// The live bound address for a listener placement (differs + /// from the requested address when port 0 was requested). + /// `None` for path mounts. + pub actual_addr: Option, +} + +/// A publication operation for a [`PublicationControl`] (#2147). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PublicationOp { + /// Publish this publication. + Publish(WirePublication), + /// Unpublish whatever sits at this placement. + Unpublish(WirePlacement), + /// List the live publications. + List, +} + +/// The outcome of a [`PublicationOp`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PublicationOutcome { + /// Published; carries the loud shadow warning for an + /// acknowledged shadowing mount. + Published { + /// The shadow warning, if the publication shadows an + /// Explorer route with acknowledgement. + warning: Option, + }, + /// Unpublished. + Unpublished, + /// The live publications. + Listed { + /// The live publications. + items: Vec, + }, +} + +/// The serve-side publication control the meta protocol dispatches +/// operator publication requests to (#2147). Implemented by the +/// serve process over its publication manager; kept as a trait +/// here because the manager lives in `id-cli`, which depends on +/// this crate, never the reverse. +pub trait PublicationControl: Send + Sync { + /// Perform one publication operation. + fn call( + &self, + op: PublicationOp, + ) -> std::pin::Pin< + Box> + Send + '_>, + >; +} + +/// A shareable handle to a [`PublicationControl`]. +#[derive(Clone)] +pub struct PublicationControlHandle { + inner: Arc, +} + +impl PublicationControlHandle { + /// Wrap a publication control as a handle. + #[must_use] + pub fn new(control: Arc) -> Self { + Self { inner: control } + } + + /// Perform one publication operation through the handle. + pub async fn call(&self, op: PublicationOp) -> Result { + self.inner.call(op).await + } +} + +impl std::fmt::Debug for PublicationControlHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PublicationControlHandle") + .finish_non_exhaustive() + } +} + +/// The protocol handler's publication control slot (#2147): empty +/// until the serve process has built its publication manager and +/// registered its control, which happens after the handler itself +/// is constructed (the manager needs the web surface, which is +/// built later in startup). Interior mutability is the point: the +/// handler is shared behind an `Arc` from the moment it is +/// registered with the router. +pub type SharedPublicationControl = Arc>>; + /// Responses from a remote node via the meta protocol. /// /// Each variant corresponds to a [`MetaRequest`] variant. Any request may also @@ -814,6 +966,22 @@ pub enum MetaResponse { /// replaced. replaced: bool, }, + /// Response to [`MetaRequest::Publish`] (#2147). + Published { + /// The loud shadow warning for an acknowledged shadowing + /// mount, if the publication shadows an Explorer route. + warning: Option, + }, + /// Response to [`MetaRequest::Unpublish`] (#2147). + Unpublished { + /// Whether a publication was removed. + success: bool, + }, + /// Response to [`MetaRequest::ListPublications`] (#2147). + Publications { + /// The live publications, with live addresses. + items: Vec, + }, } /// One row of [`MetaResponse::AbuseCounters`]: the frame and byte counters @@ -905,6 +1073,13 @@ pub struct MetaProtocol { /// handlers: a `Send` request then fails with an explanatory error /// instead of silently doing nothing. pub endpoint: Option, + /// The #2147 publication control slot: the serve process + /// registers its publication manager's control here once the + /// manager exists (see [`SharedPublicationControl`]). Empty + /// for in-process handlers and during serve startup; operator + /// publication requests against an empty slot fail with an + /// explanatory error, never a silent local success. + pub publications: SharedPublicationControl, } impl MetaProtocol { @@ -928,14 +1103,74 @@ impl MetaProtocol { blob_wait: DEFAULT_BLOB_WAIT, abuse, endpoint: None, + publications: Arc::new(std::sync::Mutex::new(None)), }) } + /// Register the publication control operator requests dispatch + /// to (#2147). Called by the serve process once its publication + /// manager exists; see [`SharedPublicationControl`] for why the + /// slot is filled after construction. + pub fn set_publication_control(&self, control: PublicationControlHandle) { + *self + .publications + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(control); + } + /// Handle one request on behalf of `remote` and produce the response. /// /// This is the whole server-side behaviour of the protocol, independent of /// QUIC, so it can be exercised directly in tests. pub async fn handle(&self, remote: &EndpointId, req: MetaRequest) -> MetaResponse { + // #2147 publication control is OPERATOR-ONLY and is gated + // before (and independently of) the store write gate: only + // the serving node's own authenticated identity may change + // its listeners and routes, no matter how open its write + // policy is. The local publication CLI connects with the + // node's own key (see the #2147 design decision, 2026-11-04). + let publication_op = match &req { + MetaRequest::Publish { publication } => { + Some(PublicationOp::Publish(publication.clone())) + } + MetaRequest::Unpublish { placement } => { + Some(PublicationOp::Unpublish(placement.clone())) + } + MetaRequest::ListPublications => Some(PublicationOp::List), + _ => None, + }; + if let Some(op) = publication_op { + if remote != &self.node_id { + return MetaResponse::Error { + message: format!( + "permission denied: publication control is operator-only \ + (node {remote} is not the serving node); only the serving \ + node's own identity may publish or unpublish, via the \ + local CLI on the serve host" + ), + }; + } + let control = self + .publications + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + let Some(control) = control else { + return MetaResponse::Error { + message: "publication control is not available on this node: \ + no serve-owned publication manager is running here" + .to_owned(), + }; + }; + return match control.call(op).await { + Ok(PublicationOutcome::Published { warning }) => { + MetaResponse::Published { warning } + } + Ok(PublicationOutcome::Unpublished) => MetaResponse::Unpublished { success: true }, + Ok(PublicationOutcome::Listed { items }) => MetaResponse::Publications { items }, + Err(message) => MetaResponse::Error { message }, + }; + } if req.is_write() && !self.access.can_write(remote) { return MetaResponse::Error { message: format!( @@ -1164,6 +1399,16 @@ impl MetaProtocol { } } } + // Publication requests return from the operator gate + // above and never reach this match; the arms exist so + // the match stays exhaustive if that ever changes, and + // they answer with an error rather than falling through + // to any store behaviour. + MetaRequest::Publish { .. } + | MetaRequest::Unpublish { .. } + | MetaRequest::ListPublications => MetaResponse::Error { + message: "publication requests are handled by the operator gate".to_owned(), + }, MetaRequest::Whoami => MetaResponse::Whoami { node_id: self.node_id, version: env!("CARGO_PKG_VERSION").to_owned(), @@ -2121,3 +2366,158 @@ mod tests { assert_eq!(back, tag); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod publication_control_tests { + use std::sync::Arc; + + use id_core::access::AccessPolicy; + use id_store::tags::TagStore; + use iroh::endpoint::{Endpoint, RelayMode, presets}; + use iroh_base::SecretKey; + use iroh_blobs::{api::Store, store::mem::MemStore}; + use iroh_docs::protocol::Docs; + use iroh_gossip::net::Gossip; + + use super::{ + MetaProtocol, MetaRequest, MetaResponse, PublicationControl, PublicationControlHandle, + PublicationOp, PublicationOutcome, WirePlacement, WirePublication, + }; + + struct FakeControl; + + impl PublicationControl for FakeControl { + fn call( + &self, + op: PublicationOp, + ) -> std::pin::Pin< + Box> + Send + '_>, + > { + Box::pin(async move { + match op { + PublicationOp::Publish(_) => { + Ok(PublicationOutcome::Published { warning: None }) + } + PublicationOp::Unpublish(_) => Ok(PublicationOutcome::Unpublished), + PublicationOp::List => Ok(PublicationOutcome::Listed { items: Vec::new() }), + } + }) + } + } + + async fn protocol_with_open_access() -> (Arc, 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, "publication-control-test", dir.path().join("meta")) + .await + .unwrap(), + ); + let protocol = MetaProtocol::new( + &store, + None, + tags, + AccessPolicy::open(), + endpoint.id(), + None, + ); + (protocol, dir) + } + + fn publish_request() -> MetaRequest { + MetaRequest::Publish { + publication: WirePublication { + world: "arena".to_owned(), + placement: WirePlacement::PathMount { + path: "/prog".to_owned(), + }, + acknowledge_shadow: false, + }, + } + } + + #[test] + fn publication_requests_roundtrip_through_postcard() { + // The meta protocol's wire format is postcard; the new + // variants (SocketAddr inside WirePlacement included) must + // survive it, or the CLI and serve would disagree silently. + for req in [ + publish_request(), + MetaRequest::Unpublish { + placement: WirePlacement::Listener { + addr: "127.0.0.1:0".parse().unwrap(), + }, + }, + MetaRequest::ListPublications, + ] { + let bytes = postcard::to_allocvec(&req).unwrap(); + let back: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + assert_eq!(format!("{back:?}"), format!("{req:?}")); + } + } + + #[tokio::test] + async fn publication_requests_are_operator_only_even_with_open_writes() { + let (protocol, _dir) = protocol_with_open_access().await; + protocol.set_publication_control(PublicationControlHandle::new(Arc::new(FakeControl))); + let stranger = SecretKey::from_bytes(&[9; 32]).public(); + // AccessPolicy::open() lets this peer write the store; it + // must still not reach publication control. + let resp = protocol.handle(&stranger, publish_request()).await; + match resp { + MetaResponse::Error { message } => { + assert!(message.contains("operator-only"), "{message}"); + } + other => panic!("expected operator-only error, got {other:?}"), + } + let resp = protocol + .handle(&stranger, MetaRequest::ListPublications) + .await; + assert!(matches!(resp, MetaResponse::Error { .. }), "{resp:?}"); + } + + #[tokio::test] + async fn operator_without_a_registered_control_gets_an_explanatory_error() { + let (protocol, _dir) = protocol_with_open_access().await; + let operator = protocol.node_id; + let resp = protocol + .handle(&operator, MetaRequest::ListPublications) + .await; + match resp { + MetaResponse::Error { message } => { + assert!(message.contains("not available"), "{message}"); + } + other => panic!("expected not-available error, got {other:?}"), + } + } + + #[tokio::test] + async fn operator_requests_dispatch_to_the_registered_control() { + let (protocol, _dir) = protocol_with_open_access().await; + protocol.set_publication_control(PublicationControlHandle::new(Arc::new(FakeControl))); + let operator = protocol.node_id; + let resp = protocol.handle(&operator, publish_request()).await; + assert!( + matches!(resp, MetaResponse::Published { warning: None }), + "{resp:?}" + ); + let resp = protocol + .handle(&operator, MetaRequest::ListPublications) + .await; + match resp { + MetaResponse::Publications { items } => assert!(items.is_empty()), + other => panic!("expected Publications, got {other:?}"), + } + } +} diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index 6bdb707a39..383128378f 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -437,6 +437,24 @@ async fn main() -> Result<()> { Some(Command::WriterSets { json, command }) => { id::commands::cmd_writer_sets(cli.event_store, json, command).await } + Some(Command::Publish { + world, + listen, + path, + acknowledge_shadow, + }) => { + id::commands::cmd_publish( + &world, + listen.as_deref(), + path.as_deref(), + acknowledge_shadow, + ) + .await + } + Some(Command::Unpublish { listen, path }) => { + id::commands::cmd_unpublish(listen.as_deref(), path.as_deref()).await + } + Some(Command::Publications) => id::commands::cmd_publications().await, #[cfg(feature = "sandbox")] Some(Command::MatchAudit(command)) => id::commands::cmd_match_audit(command), #[cfg(feature = "world")] From 4ddc67e65d077a8b71db57e5e0f2186fcbf05ca7 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 19:04:23 -0600 Subject: [PATCH 3/3] =?UTF-8?q?id(serve):=20operator=20is=20the=20designat?= =?UTF-8?q?ed=20local=20client=20identity=20=E2=80=94=20iroh=20cannot=20se?= =?UTF-8?q?lf-connect=20(#2147=20slice=203b=20fix)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The acceptance walk proved the 2026-11-04 transport assumption impossible: an iroh endpoint refuses to connect to itself, so a CLI presenting the serve node's own key can never reach its own serve. Serve now designates this machine's client identity (CLIENT_KEY_FILE, already the access policy's trusted local identity) as the handler's local operator; the gate answers the node itself (in-process) or that identity, and nobody else — --open-writes/--allow-node identities are not operators. Design addendum recorded in the #2147 design record. Acceptance walk (live, this build): publish arena --listen 127.0.0.1:18777 -> program page 200; shadow mount /world refused without ack, warned + overriding with ack; unpublish restores Explorer route and closes listener; restart restores the persisted publication live; no-serve CLI fails actionably with no local fallback. id-sync publication tests 5/5. --- ...6Z_feature_dynamic_publications_runtime.md | 4 ++ pkgs/id/crates/id-cli/src/commands/client.rs | 24 ++++---- pkgs/id/crates/id-cli/src/commands/publish.rs | 7 ++- pkgs/id/crates/id-cli/src/commands/serve.rs | 11 ++++ pkgs/id/crates/id-sync/src/protocol.rs | 60 +++++++++++++++---- 5 files changed, 83 insertions(+), 23 deletions(-) diff --git a/doc/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime.md b/doc/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime.md index cf51239958..d7e6ec070a 100644 --- a/doc/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime.md +++ b/doc/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime/2026-11-04T21-50-26Z_feature_dynamic_publications_runtime.md @@ -55,3 +55,7 @@ These choices fit the current `MetaProtocol`/`AccessPolicy`, `cmd_serve` listene - `pkgs/id/src/publications.rs` - `pkgs/id/src/commands/serve.rs` - `pkgs/id/src/protocol.rs` and `pkgs/id/src/meta_client.rs` + +## 2026-11-14 addendum (slice 3b implementation): operator identity is the local client identity + +The 2026-11-04 decision said publication requests are authorized only when the authenticated caller is the serving node's own identity, with local commands connecting using that identity. The slice-3b acceptance walk showed that transport is impossible: an iroh endpoint refuses to connect to itself ("Connecting to ourself is not supported"), so a CLI presenting the node's own key can never reach its own serve process. Refinement, preserving the decision's security property (only key material on the serve host operates; remote writers never do): serve designates this machine's client identity -- the `CLIENT_KEY_FILE` keypair the access policy already trusts for local CLI/REPL work -- as its local operator, and the handler answers publication requests from the node itself (in-process) or from that designated identity. `--open-writes` and `--allow-node` identities are not operators. Recorded here and in the protocol/CLI code (PR #10410). diff --git a/pkgs/id/crates/id-cli/src/commands/client.rs b/pkgs/id/crates/id-cli/src/commands/client.rs index 7b1061347f..c212a1283c 100644 --- a/pkgs/id/crates/id-cli/src/commands/client.rs +++ b/pkgs/id/crates/id-cli/src/commands/client.rs @@ -25,7 +25,7 @@ use iroh::endpoint::{Endpoint, RelayMode, presets}; use iroh_base::{EndpointAddr, TransportAddr}; use super::serve::ServeInfo; -use crate::{CLIENT_KEY_FILE, KEY_FILE, load_or_create_keypair}; +use crate::{CLIENT_KEY_FILE, load_or_create_keypair}; /// Creates a client endpoint configured to connect to a local serve. /// @@ -68,20 +68,24 @@ pub async fn create_local_client_endpoint( create_local_endpoint_with_key(serve_info, CLIENT_KEY_FILE).await } -/// Creates an endpoint that connects to a local serve AS the serve -/// node itself (#2147 operator endpoint). +/// Creates an endpoint that connects to a local serve as its +/// designated local operator (#2147 operator endpoint). /// /// Publication control is operator-only: the serve handler answers -/// publish/unpublish/list requests only from its own authenticated -/// identity, so the local publication CLI presents the node's own -/// keypair (the same `KEY_FILE` serve loaded). Holding that key -/// file is the operator credential -- the design's trade-off, -/// chosen over widening the remote write policy to listener and -/// route changes. +/// publish/unpublish/list requests only from the serving node +/// itself or the local operator identity serve designated -- this +/// machine's client identity. The local publication CLI therefore +/// presents the client keypair: an iroh endpoint cannot connect to +/// itself ("Connecting to ourself is not supported"), so the +/// node's own key cannot be the transport identity of a local +/// operator connection (learned in the slice-3b acceptance walk, +/// 2026-11-14). Holding either local key file is the operator +/// credential -- the design's trade-off, chosen over widening the +/// remote write policy to listener and route changes. pub async fn create_local_operator_endpoint( serve_info: &ServeInfo, ) -> Result<(Endpoint, EndpointAddr)> { - create_local_endpoint_with_key(serve_info, KEY_FILE).await + create_local_endpoint_with_key(serve_info, CLIENT_KEY_FILE).await } async fn create_local_endpoint_with_key( diff --git a/pkgs/id/crates/id-cli/src/commands/publish.rs b/pkgs/id/crates/id-cli/src/commands/publish.rs index c054bb98d5..04cfac24c3 100644 --- a/pkgs/id/crates/id-cli/src/commands/publish.rs +++ b/pkgs/id/crates/id-cli/src/commands/publish.rs @@ -6,10 +6,11 @@ //! publication requests. Two design rules (2026-11-04 decision on //! #2147) shape everything here: //! -//! - **Operator-only.** The connection presents the serve node's -//! own keypair ([`create_local_operator_endpoint`]); the handler +//! - **Operator-only.** The connection presents this machine's +//! client keypair ([`create_local_operator_endpoint`]), which +//! serve designates as its local operator identity; the handler //! refuses every other identity, however open the node's write -//! policy is. Holding the node's key file is the credential. +//! policy is. Holding a local key file is the credential. //! - **Never a local fallback.** If no serve is running, the //! command fails with an actionable error. It does NOT edit the //! persisted registry itself and does NOT open the local stores: diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 6f736d0b26..fc146feb6d 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1864,8 +1864,19 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); // Server-to-server transfers (#5345) are initiated from this handler // with the server's own endpoint and identity. + // #2147: this machine's client identity is the handler's + // designated local operator for publication control -- the + // local CLI presents that key (an endpoint cannot connect to + // itself, so the node's own key cannot), and holding either + // local key file is the operator credential. Peers granted + // store writes (--allow-node, .iroh-allowed, open writes) are + // NOT operators. + let local_operator = load_or_create_keypair(crate::CLIENT_KEY_FILE) + .await? + .public(); if let Some(inner) = Arc::get_mut(&mut meta) { inner.endpoint = Some(endpoint.clone()); + inner.local_operator = Some(local_operator); } #[cfg(all(feature = "world", feature = "ssh"))] diff --git a/pkgs/id/crates/id-sync/src/protocol.rs b/pkgs/id/crates/id-sync/src/protocol.rs index 5f05943c0e..b77f92e27e 100644 --- a/pkgs/id/crates/id-sync/src/protocol.rs +++ b/pkgs/id/crates/id-sync/src/protocol.rs @@ -665,12 +665,17 @@ pub enum MetaRequest { /// (#2147 dynamic publications). /// /// OPERATOR-ONLY: the handler answers this only when the - /// authenticated caller is the serving node's own identity -- - /// the ordinary write gate is NOT sufficient, and `--open-writes` - /// / `--allow-node` never grant it (changing a node's listeners - /// and routes is an operator act, per the #2147 design decision - /// of 2026-11-04). The local CLI connects with the node's own - /// key to make these requests. + /// authenticated caller is the serving node's own identity or + /// the local operator identity the serve designated (its own + /// machine's client identity -- the two identities whose secret + /// keys live on the serve host). The ordinary write gate is NOT + /// sufficient, and `--open-writes` / `--allow-node` never grant + /// it (changing a node's listeners and routes is an operator + /// act, per the #2147 design decision of 2026-11-04). The local + /// CLI connects with the machine's client key: an iroh endpoint + /// cannot connect to itself, so the node's own key cannot be + /// the transport identity of a local operator connection + /// (learned in the slice-3b acceptance walk, 2026-11-14). Publish { /// The publication to apply. publication: WirePublication, @@ -1080,6 +1085,14 @@ pub struct MetaProtocol { /// publication requests against an empty slot fail with an /// explanatory error, never a silent local success. pub publications: SharedPublicationControl, + /// The designated local operator identity for #2147 + /// publication control: the serve host's own client identity, + /// set by `id serve` (see [`MetaRequest::Publish`]). Callers + /// authenticated as this identity -- or as the node itself -- + /// are operators; nobody else is, whatever the write policy + /// says. `None` (in-process handlers) leaves the node itself + /// as the only operator. + pub local_operator: Option, } impl MetaProtocol { @@ -1104,6 +1117,7 @@ impl MetaProtocol { abuse, endpoint: None, publications: Arc::new(std::sync::Mutex::new(None)), + local_operator: None, }) } @@ -1140,13 +1154,15 @@ impl MetaProtocol { _ => None, }; if let Some(op) = publication_op { - if remote != &self.node_id { + let is_operator = + remote == &self.node_id || self.local_operator.as_ref() == Some(remote); + if !is_operator { return MetaResponse::Error { message: format!( "permission denied: publication control is operator-only \ - (node {remote} is not the serving node); only the serving \ - node's own identity may publish or unpublish, via the \ - local CLI on the serve host" + (node {remote} is neither the serving node nor its \ + designated local operator); publishing and unpublishing \ + happen via the local CLI on the serve host" ), }; } @@ -2487,6 +2503,30 @@ mod publication_control_tests { assert!(matches!(resp, MetaResponse::Error { .. }), "{resp:?}"); } + #[tokio::test] + async fn designated_local_operator_dispatches_but_other_writers_do_not() { + let (protocol, _dir) = protocol_with_open_access().await; + protocol.set_publication_control(PublicationControlHandle::new(Arc::new(FakeControl))); + let client = SecretKey::from_bytes(&[7; 32]).public(); + // The handler is behind an Arc; the test holds the only + // reference, so the designation can be set directly. + let mut protocol = protocol; + Arc::get_mut(&mut protocol).unwrap().local_operator = Some(client); + let resp = protocol + .handle(&client, MetaRequest::ListPublications) + .await; + match resp { + MetaResponse::Publications { items } => assert!(items.is_empty()), + other => panic!("expected Publications for the local operator, got {other:?}"), + } + // A different key is not the operator, even with open writes. + let other_writer = SecretKey::from_bytes(&[8; 32]).public(); + let resp = protocol + .handle(&other_writer, MetaRequest::ListPublications) + .await; + assert!(matches!(resp, MetaResponse::Error { .. }), "{resp:?}"); + } + #[tokio::test] async fn operator_without_a_registered_control_gets_an_explanatory_error() { let (protocol, _dir) = protocol_with_open_access().await;