返回 CodeWhale
daemon_socket.rs
根目录 / crates / app-server / src / daemon_socket.rs
1 //! Authenticated local daemon transport: Unix socket and Windows named pipe.
2 //!
3 //! The desktop shell attaches to a long-lived `codewhale app-server --socket`
4 //! daemon over a local socket instead of a TCP port: local multi-client,
5 //! peer-credential auth, nothing to firewall (CORE-PROTOCOL spec §5). The
6 //! wire carries RPC objects in WebSocket text messages; process stdio uses
7 //! JSONL. Both use `crate::stdio::run_stdio_loop` after the private channel's
8 //! WebSocket upgrade and `daemon/attach` handshake establish the connection
9 //! and whether this client owns the daemon.
10 //!
11 //! Windows derives a local named-pipe endpoint from the selected home and
12 //! current principal. It shares the same dispatcher and ownership handshake;
13 //! no supported platform falls back to TCP. Windows runtime proof is separate.
14 //!
15 //! # Ownership
16 //!
17 //! Hermes' claim model, server-side: a client attaches with `mode: "claim"`
18 //! (it spawned the daemon and will manage its lifetime) or `mode: "attach"`
19 //! (it found a healthy daemon and is a guest). Only the current owner may
20 //! `shutdown` the daemon; guests get `not_daemon_owner`. When the owner
21 //! disconnects the slot frees, so a relaunched shell can re-claim the daemon
22 //! it left running — sessions survive UI restarts because the daemon does.
23
24 use std::path::PathBuf;
25
26 use codewhale_protocol::RuntimeOwnerReceipt;
27 use serde::{Deserialize, Serialize};
28
29 pub use codewhale_paths::daemon_socket::{
30 DAEMON_SOCKET_FILE_NAME, DaemonSocketError, MAX_SOCKET_PATH_BYTES, SocketPathInputs,
31 WINDOWS_NAMED_PIPE, resolve_socket_path,
32 };
33 #[cfg(unix)]
34 pub use codewhale_paths::daemon_socket::{default_socket_path, store_selected_socket_path};
35
36 /// JSON-RPC method a client must send first on a daemon-socket connection.
37 pub const ATTACH_METHOD: &str = "daemon/attach";
38
39 /// How to start the daemon socket transport.
40 #[derive(Debug, Clone, Default)]
41 pub struct DaemonSocketOptions {
42 /// Explicit socket path; `None` resolves the platform default.
43 pub socket_path: Option<PathBuf>,
44 /// Explicit config file, like `app-server --config`.
45 pub config_path: Option<PathBuf>,
46 }
47
48 /// The socket path this host would use with no explicit override.
49 #[cfg(not(any(unix, windows)))]
50 pub fn default_socket_path() -> Result<PathBuf, DaemonSocketError> {
51 Err(unsupported_platform())
52 }
53
54 /// Who is on the other end of a daemon-socket connection.
55 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56 pub struct ClientIdentity {
57 /// Product name of the client, e.g. `codewhale-desktop`.
58 pub name: String,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub version: Option<String>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub pid: Option<u32>,
63 }
64
65 /// Ownership intent carried by `daemon/attach`.
66 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
67 #[serde(rename_all = "snake_case")]
68 pub enum AttachMode {
69 /// A guest: use the daemon, never stop it.
70 #[default]
71 Attach,
72 /// The daemon's owner: may `shutdown`. Fails if a live owner exists.
73 Claim,
74 }
75
76 /// Role granted by a successful attach.
77 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78 #[serde(rename_all = "snake_case")]
79 pub enum AttachRole {
80 Owner,
81 Attached,
82 }
83
84 /// `daemon/attach` params.
85 #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
86 #[serde(rename_all = "snake_case")]
87 pub enum AttachFrontend {
88 #[default]
89 Control,
90 Acp,
91 Listener,
92 }
93
94 #[derive(Debug, Clone, Deserialize)]
95 pub struct AttachParams {
96 #[serde(default)]
97 pub native_runtime: Option<crate::native_runtime::NativeSelection>,
98 #[serde(default)]
99 pub frontend: AttachFrontend,
100 #[serde(default)]
101 pub listener: Option<crate::RuntimeListenerSelection>,
102 #[serde(default)]
103 pub scope: Option<crate::RuntimeFrontendScope>,
104 #[serde(default)]
105 pub acp_model: Option<String>,
106 pub client: ClientIdentity,
107 #[serde(default)]
108 pub mode: AttachMode,
109 /// Bundle-skew guard: when set, the daemon refuses the attach unless its
110 /// own version string matches exactly.
111 #[serde(default)]
112 pub expect_daemon_version: Option<String>,
113 #[serde(default)]
114 pub expect_owner: Option<RuntimeOwnerReceipt>,
115 #[serde(default)]
116 pub desktop_browser_owner: Option<String>,
117 }
118
119 /// The typed refusal every non-unix entry point returns. Unused in the unix
120 /// library build by construction; the tests pin its wording on every host.
121 #[cfg(any(test, not(any(unix, windows))))]
122 fn unsupported_platform() -> DaemonSocketError {
123 DaemonSocketError::UnsupportedPlatform {
124 platform: std::env::consts::OS,
125 planned_endpoint: WINDOWS_NAMED_PIPE,
126 }
127 }
128
129 #[cfg(any(unix, windows))]
130 use codewhale_runtime::runtime_control::owner_work;
131
132 // Blocking endpoint mutations retain the actual captured manager through
133 // its existing frontend, even after cancellation of the async caller.
134 #[cfg(any(unix, windows))]
135 pub(crate) async fn socket_owner_work<T, F>(owner_state: Option<AppState>, work: F) -> Result<T>
136 where
137 T: Send + 'static,
138 F: FnOnce() -> Result<T> + Send + 'static,
139 {
140 owner_work(move || {
141 let _held_owner = owner_state;
142 work()
143 })
144 .await
145 }
146
147 use crate::stdio::{
148 ParsedStdioLine, dispatch_stdio_request_with_writer, parse_stdio_line, run_stdio_loop,
149 write_stdio_line,
150 };
151 use crate::{
152 AppState, AppTransport, DispatchError, ShutdownAuthority, StdioLoopExit, StdioLoopPolicy,
153 jsonrpc_error, jsonrpc_result, params_or_object, parse_params,
154 };
155 use anyhow::Result;
156 use serde_json::{Value, json};
157 use std::collections::HashMap;
158 use std::sync::{Arc, Mutex};
159 use std::time::{Duration, Instant};
160 use tokio::io::{AsyncBufRead, AsyncWrite, AsyncWriteExt as _, BufReader};
161 use tokio::sync::watch;
162 use tokio::task::JoinSet;
163
164 /// Facts about this daemon, reported in every attach reply.
165 #[derive(Debug)]
166 struct DaemonInfo {
167 pid: u32,
168 version: &'static str,
169 /// Independent effective principal captured from this process.
170 #[cfg(unix)]
171 uid: u32,
172 socket_path: PathBuf,
173 started_at: Instant,
174 }
175
176 #[derive(Debug, Default)]
177 struct ConnectionRegistry {
178 next_id: u64,
179 connections: HashMap<u64, ClientIdentity>,
180 owner: Option<u64>,
181 }
182
183 impl ConnectionRegistry {
184 fn register(&mut self, client: ClientIdentity) -> u64 {
185 self.next_id += 1;
186 let id = self.next_id;
187 self.connections.insert(id, client);
188 id
189 }
190
191 /// Take the owner slot, or report who holds it.
192 fn claim(&mut self, id: u64) -> Result<(), ClientIdentity> {
193 if let Some(owner_id) = self.owner
194 && owner_id != id
195 && let Some(owner) = self.connections.get(&owner_id)
196 {
197 return Err(owner.clone());
198 }
199 self.owner = Some(id);
200 Ok(())
201 }
202
203 fn owner(&self) -> Option<ClientIdentity> {
204 self.owner.and_then(|id| self.connections.get(&id)).cloned()
205 }
206
207 fn remove(&mut self, id: u64) {
208 self.connections.remove(&id);
209 if self.owner == Some(id) {
210 self.owner = None;
211 }
212 }
213 }
214
215 /// Releases the registry slot (and the owner claim) on drop, whichever
216 /// way the connection ends.
217 struct ConnectionGuard {
218 native_runtime: Option<crate::native_runtime::NativeSelection>,
219 frontend: AttachFrontend,
220 listener: Option<crate::RuntimeListenerSelection>,
221 scope: Option<crate::RuntimeFrontendScope>,
222 acp_model: Option<String>,
223 registry: Arc<Mutex<ConnectionRegistry>>,
224 id: u64,
225 role: AttachRole,
226 }
227
228 impl Drop for ConnectionGuard {
229 fn drop(&mut self) {
230 if let Ok(mut registry) = self.registry.lock() {
231 registry.remove(self.id);
232 }
233 }
234 }
235
236 /// Asks a running [`DaemonSocket::serve`] to stop.
237 #[derive(Debug, Clone)]
238 pub struct DaemonShutdownHandle(pub(crate) Arc<watch::Sender<bool>>);
239
240 impl DaemonShutdownHandle {
241 /// Idempotent; safe to call from any task or signal handler.
242 pub fn trigger(&self) {
243 self.0.send_replace(true);
244 }
245 }
246
247 #[derive(Clone)]
248 pub(crate) struct ConnectionContext {
249 state: AppState,
250 registry: Arc<Mutex<ConnectionRegistry>>,
251 info: Arc<DaemonInfo>,
252 shutdown: DaemonShutdownHandle,
253 owner: Option<RuntimeOwnerReceipt>,
254 }
255
256 /// The daemon's connection tasks. A `JoinSet` keeps every finished task
257 /// until it is joined, so a long-lived daemon used to retain one task per
258 /// past client (health polls, re-attaches) for its whole lifetime.
259 /// [`Self::spawn`] is the only way in and reaps finished tasks first, so
260 /// the set is bounded by the live connections plus those that ended since
261 /// the last accept. A panicked connection is logged, not fatal.
262 #[derive(Default)]
263 pub(crate) struct ConnectionTasks(JoinSet<()>);
264
265 impl ConnectionTasks {
266 pub(crate) async fn shutdown(&mut self) {
267 self.0.shutdown().await;
268 }
269 pub(crate) fn at_capacity(&mut self) -> bool {
270 while let Some(joined) = self.0.try_join_next() {
271 if let Err(err) = joined
272 && err.is_panic()
273 {
274 tracing::warn!(error = %err, "daemon connection task panicked");
275 }
276 }
277 self.0.len() >= 64
278 }
279 pub(crate) fn spawn(&mut self, task: impl std::future::Future<Output = ()> + Send + 'static) {
280 if !self.at_capacity() {
281 self.0.spawn(task);
282 } else {
283 tracing::debug!("local control connection ceiling reached; refusing before admission");
284 }
285 }
286 }
287
288 /// Serve `healthz` and wait for `daemon/attach`; everything else is
289 /// refused with `attach_required` until the client attaches.
290 async fn handshake<R, W>(
291 context: &ConnectionContext,
292 lines: &mut crate::stdio::BoundedLines<R>,
293 writer: &mut W,
294 ) -> Result<Option<ConnectionGuard>>
295 where
296 R: AsyncBufRead + Unpin,
297 W: AsyncWrite + Unpin,
298 {
299 loop {
300 let Some(line) = lines.next_line().await? else {
301 return Ok(None);
302 };
303 let request = match parse_stdio_line(&line) {
304 ParsedStdioLine::Blank => continue,
305 ParsedStdioLine::Ignored | ParsedStdioLine::Response(_) => continue,
306 ParsedStdioLine::Request(request) => request,
307 };
308 let Some(id) = request.id.clone() else {
309 continue;
310 };
311 match request.method.as_str() {
312 "healthz" | "app/healthz" => {
313 let response = match dispatch_stdio_request_with_writer(
314 &context.state,
315 writer,
316 &request.method,
317 request.params,
318 AppTransport::Socket,
319 None,
320 None,
321 )
322 .await
323 {
324 Ok(dispatch) => jsonrpc_result(id, dispatch.result),
325 Err(err) => jsonrpc_error(id, err),
326 };
327 write_stdio_line(writer, &response).await?;
328 }
329 ATTACH_METHOD => match attach(context, request.params).await {
330 Ok((result, guard)) => {
331 write_stdio_line(writer, &jsonrpc_result(id, result)).await?;
332 return Ok(Some(guard));
333 }
334 Err(err) => write_stdio_line(writer, &jsonrpc_error(id, err)).await?,
335 },
336 other => {
337 write_stdio_line(
338 writer,
339 &jsonrpc_error(id, DispatchError::attach_required(other)),
340 )
341 .await?;
342 }
343 }
344 }
345 }
346
347 async fn attach(
348 context: &ConnectionContext,
349 params: Value,
350 ) -> Result<(Value, ConnectionGuard), DispatchError> {
351 let mut params: AttachParams = parse_params(params_or_object(params))?;
352 if params.desktop_browser_owner.is_some() && params.frontend != AttachFrontend::Listener {
353 return Err(DispatchError::invalid_params(
354 "desktop browser owner requires listener frontend",
355 ));
356 }
357 if params.frontend == AttachFrontend::Acp
358 && (context.state.owner_frontend.is_none()
359 || !context
360 .state
361 .captured_routing
362 .as_ref()
363 .is_some_and(|routing| routing.acp))
364 {
365 return Err(DispatchError::invalid_params(
366 "held owner has no narrowed ACP projection; cross-profile attachment refused",
367 ));
368 }
369 if (params.frontend == AttachFrontend::Listener) != params.listener.is_some() {
370 return Err(DispatchError::invalid_params(
371 "listener selection does not match frontend",
372 ));
373 }
374 if let Some(listener) = params.listener.as_mut() {
375 if let Some(owner) = params.desktop_browser_owner.take() {
376 listener.desktop_browser_owner = Some(owner);
377 }
378 listener.validate_bounds().map_err(|_| {
379 DispatchError::invalid_params("selected frontend input exceeds its bounds")
380 })?;
381 if context.state.owner_frontend.is_none() {
382 return Err(DispatchError::invalid_params(
383 "held owner has no selected listener projection",
384 ));
385 }
386 }
387 if params.scope.is_some()
388 && (params.frontend == AttachFrontend::Listener || context.state.owner_frontend.is_none())
389 || params.acp_model.is_some() && params.frontend != AttachFrontend::Acp
390 {
391 return Err(DispatchError::invalid_params(
392 "selected scope does not match captured frontend",
393 ));
394 }
395 if let Some(scope) = params.scope.as_ref() {
396 scope.validate_bounds().map_err(|_| {
397 DispatchError::invalid_params("selected frontend scope exceeds its bounds")
398 })?;
399 }
400 if params
401 .acp_model
402 .as_ref()
403 .is_some_and(|model| model.trim().is_empty() || model.len() > 1024)
404 {
405 return Err(DispatchError::invalid_params("invalid selected ACP model"));
406 }
407 if let Some(owner) = context.owner.as_ref() {
408 if params.expect_owner.as_ref() != Some(owner) {
409 return Err(DispatchError::invalid_params(
410 "captured owner generation or store does not match",
411 ));
412 }
413 if params.mode == AttachMode::Claim {
414 return Err(DispatchError::not_daemon_owner());
415 }
416 }
417 if params.client.name.trim().is_empty() {
418 return Err(DispatchError::invalid_params(
419 "client.name must not be empty",
420 ));
421 }
422 if let Some(expected) = params.expect_daemon_version.as_deref()
423 && expected != context.info.version
424 {
425 return Err(DispatchError::daemon_version_skew(
426 expected,
427 context.info.version,
428 ));
429 }
430
431 if let Some(native) = params.native_runtime.as_ref() {
432 native
433 .validate()
434 .map_err(|_| DispatchError::invalid_params("invalid native capability selection"))?;
435 if params.frontend != AttachFrontend::Control
436 || params.mode != AttachMode::Attach
437 || params.scope.is_some()
438 || params.listener.is_some()
439 || params.acp_model.is_some()
440 || context.owner.is_none()
441 {
442 return Err(DispatchError::invalid_params(
443 "native Runtime requires captured attach-only Control",
444 ));
445 }
446 let frontend = context
447 .state
448 .owner_frontend
449 .as_ref()
450 .ok_or_else(|| DispatchError::invalid_params("captured Runtime unavailable"))?;
451 frontend
452 .execute(crate::RuntimeOwnerRequest::Native {
453 workspace: native.workspace.clone(),
454 request: codewhale_app_server_protocol::runtime::NativeRuntimeRequest::Capabilities(
455 codewhale_app_server_protocol::runtime::NativeEmpty {},
456 ),
457 })
458 .await
459 .map_err(|_| DispatchError::invalid_params("native workspace refused"))?;
460 }
461 if let Some(frontend) = context.state.owner_frontend.as_ref() {
462 let selection = match params.frontend {
463 AttachFrontend::Listener => Some(crate::RuntimeOwnerFrontendSelection::Listener(
464 params.listener.clone().expect("validated listener"),
465 )),
466 AttachFrontend::Acp => Some(crate::RuntimeOwnerFrontendSelection::Acp {
467 scope: params.scope.clone(),
468 model: params.acp_model.clone(),
469 }),
470 AttachFrontend::Control => params
471 .scope
472 .clone()
473 .map(crate::RuntimeOwnerFrontendSelection::Control),
474 };
475 if let Some(selection) = selection {
476 frontend
477 .validate_selection(&selection)
478 .await
479 .map_err(|error| DispatchError::invalid_params(error.to_string()))?;
480 }
481 }
482 let mut registry = context
483 .registry
484 .lock()
485 .map_err(|_| DispatchError::internal("daemon connection registry poisoned"))?;
486 let id = registry.register(params.client.clone());
487 let role = match params.mode {
488 AttachMode::Attach => AttachRole::Attached,
489 AttachMode::Claim => match registry.claim(id) {
490 Ok(()) => AttachRole::Owner,
491 Err(owner) => {
492 registry.remove(id);
493 let owner = serde_json::to_value(owner)
494 .map_err(|err| DispatchError::internal(err.to_string()))?;
495 return Err(DispatchError::daemon_already_claimed(&owner));
496 }
497 },
498 };
499 let owner = registry.owner();
500 let connections = registry.connections.len();
501 drop(registry);
502
503 let info = &context.info;
504 let result = json!({
505 "attached": true,
506 "connection_id": id,
507 "role": role,
508 "transport": AppTransport::Socket.label(),
509 "daemon": {
510 "service": crate::legacy_deepseek_compat::SERVICE_NAME,
511 "pid": info.pid,
512 "version": info.version,
513 "socket_path": info.socket_path.display().to_string(),
514 "uptime_ms": u64::try_from(info.started_at.elapsed().as_millis()).unwrap_or(u64::MAX),
515 },
516 "owner": owner,
517 "connections": connections,
518 "owner_receipt": context.owner,
519 "runtime_routing": context.state.captured_routing,
520 "native_runtime": params.native_runtime,
521 });
522 Ok((
523 result,
524 ConnectionGuard {
525 native_runtime: params.native_runtime,
526 frontend: params.frontend,
527 listener: params.listener,
528 scope: params.scope,
529 acp_model: params.acp_model,
530 registry: Arc::clone(&context.registry),
531 id,
532 role,
533 },
534 ))
535 }
536
537 pub(crate) struct AuthorizedPeer {
538 pub(crate) pid: u32,
539 pub(crate) start: String,
540 #[cfg(windows)]
541 pub(crate) process: codewhale_config::windows_identity::WindowsPeerProcess,
542 }
543
544 impl AuthorizedPeer {
545 pub(crate) fn check(&self) -> Result<()> {
546 #[cfg(unix)]
547 anyhow::ensure!(
548 codewhale_config::private_directory::unix_process_start(self.pid)? == self.start,
549 "local control peer generation changed"
550 );
551 #[cfg(windows)]
552 {
553 self.process.check_current_user()?;
554 anyhow::ensure!(
555 self.process.pid() == self.pid,
556 "Windows kernel peer PID changed"
557 );
558 anyhow::ensure!(
559 self.process.start() == self.start,
560 "local control peer generation changed"
561 );
562 }
563 Ok(())
564 }
565 }
566
567 pub(crate) async fn connection_context(
568 state: AppState,
569 path: PathBuf,
570 shutdown: DaemonShutdownHandle,
571 owner: Option<RuntimeOwnerReceipt>,
572 ) -> Result<ConnectionContext> {
573 Ok(ConnectionContext {
574 state,
575 registry: Arc::new(Mutex::new(ConnectionRegistry::default())),
576 info: Arc::new(DaemonInfo {
577 pid: std::process::id(),
578 version: env!("CARGO_PKG_VERSION"),
579 #[cfg(unix)]
580 uid: codewhale_config::private_directory::PrivateDirectory::current_user_id(),
581 socket_path: path,
582 started_at: Instant::now(),
583 }),
584 shutdown,
585 owner,
586 })
587 }
588
589 pub(crate) async fn run_authorized_connection<R, W>(
590 context: ConnectionContext,
591 read: R,
592 writer: W,
593 peer: AuthorizedPeer,
594 ) where
595 R: tokio::io::AsyncRead + Unpin + Send + 'static,
596 W: AsyncWrite + Unpin + Send + 'static,
597 {
598 let peer = Arc::new(peer);
599 let check = peer.clone();
600 if owner_work(move || check.check()).await.is_err() {
601 return;
602 }
603 let transport = match crate::websocket::accept(read, writer).await {
604 Ok(transport) => transport,
605 Err(error) => {
606 tracing::debug!(%error, "private WebSocket upgrade refused");
607 return;
608 }
609 };
610 let (read, mut writer) = tokio::io::split(transport);
611 let mut lines = crate::stdio::BoundedLines::new(BufReader::new(read));
612 let guard = match tokio::time::timeout(
613 Duration::from_secs(5),
614 handshake(&context, &mut lines, &mut writer),
615 )
616 .await
617 {
618 Err(_) => return,
619 Ok(result) => match result {
620 Ok(Some(guard)) => guard,
621 Ok(None) => return,
622 Err(error) => {
623 tracing::debug!(%error,"local control handshake ended");
624 return;
625 }
626 },
627 };
628 let check = peer.clone();
629 if owner_work(move || check.check()).await.is_err() {
630 return;
631 }
632 if let Some(native) = guard.native_runtime.as_ref() {
633 let Some(frontend) = context.state.owner_frontend.clone() else {
634 return;
635 };
636 let _ = crate::native_runtime::serve(
637 frontend,
638 native.workspace.clone(),
639 lines,
640 &mut writer,
641 peer.clone(),
642 )
643 .await;
644 return;
645 }
646 if guard.frontend != AttachFrontend::Control || guard.scope.is_some() {
647 let Some(frontend) = context.state.owner_frontend.as_ref() else {
648 return;
649 };
650 let selection = match guard.frontend {
651 AttachFrontend::Listener => crate::RuntimeOwnerFrontendSelection::Listener(
652 guard.listener.clone().expect("admitted listener"),
653 ),
654 AttachFrontend::Acp => crate::RuntimeOwnerFrontendSelection::Acp {
655 scope: guard.scope.clone(),
656 model: guard.acp_model.clone(),
657 },
658 AttachFrontend::Control => crate::RuntimeOwnerFrontendSelection::Control(
659 guard.scope.clone().expect("admitted scope"),
660 ),
661 };
662 let _claim = (guard, peer);
663 if let Err(error) = frontend
664 .serve(
665 selection,
666 context.state.clone(),
667 Box::new(lines.into_inner()),
668 Box::new(&mut writer),
669 )
670 .await
671 {
672 tracing::debug!(%error,"captured frontend connection ended");
673 }
674 let _ = tokio::time::timeout(Duration::from_secs(5), writer.shutdown()).await;
675 return;
676 }
677 let policy = StdioLoopPolicy {
678 transport: AppTransport::Socket,
679 shutdown: match guard.role {
680 AttachRole::Owner => ShutdownAuthority::Granted,
681 AttachRole::Attached => ShutdownAuthority::Denied,
682 },
683 };
684 let result = run_stdio_loop(
685 &context.state,
686 lines,
687 &mut writer,
688 policy,
689 Some((guard, peer)),
690 )
691 .await;
692 let _ = tokio::time::timeout(Duration::from_secs(5), writer.shutdown()).await;
693 match result {
694 Ok(StdioLoopExit::Shutdown) => context.shutdown.trigger(),
695 Ok(StdioLoopExit::InputClosed) => {}
696 Err(error) => tracing::debug!(%error,"local control connection ended"),
697 }
698 }
699
700 #[cfg(unix)]
701 mod platform {
702 use std::fs::File;
703 use std::path::{Path, PathBuf};
704 use std::sync::Arc;
705 use std::time::Duration;
706
707 use anyhow::Result;
708 use codewhale_config::private_directory::{PrivateDirectory, PrivateSocketIdentity};
709 use codewhale_paths::daemon_socket::{SocketPathInputs, resolve_socket_path};
710 use tokio::net::{UnixListener, UnixStream};
711 use tokio::sync::watch;
712
713 #[cfg(test)]
714 use super::{ClientIdentity, ConnectionRegistry};
715 use super::{
716 ConnectionContext, ConnectionTasks, DaemonShutdownHandle, DaemonSocketError,
717 DaemonSocketOptions, socket_owner_work,
718 };
719 use crate::{AppState, AppTransport, build_state_off_runtime};
720
721 /// How long the stale-socket probe waits for a connect to resolve.
722 const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
723
724 #[cfg(test)]
725 type BeforeOwnerRebind = Box<dyn FnOnce(&Path)>;
726 #[cfg(test)]
727 thread_local! {
728 static BEFORE_OWNER_REBIND: std::cell::RefCell<Option<BeforeOwnerRebind>> = const { std::cell::RefCell::new(None) };
729 }
730
731 /// Removes the socket file when the server stops, however it stops.
732 struct SocketFileGuard {
733 parent: Arc<PrivateDirectory>,
734 name: String,
735 identity: PrivateSocketIdentity,
736 receipt: Option<(String, File)>,
737 owner_state: Option<AppState>,
738 retired: bool,
739 }
740
741 impl SocketFileGuard {
742 fn retirement(&mut self) -> Option<impl FnOnce() -> Result<()> + Send + 'static> {
743 if self.retired {
744 return None;
745 }
746 self.retired = true;
747 let parent = self.parent.clone();
748 let name = self.name.clone();
749 let identity = self.identity;
750 let receipt = self.receipt.take();
751 let owner_state = self.owner_state.take();
752 Some(move || {
753 let _held_owner = owner_state;
754 if let Some((name, file)) = receipt {
755 parent.retire_private_receipt(&name, &file)?;
756 }
757 parent.retire_socket(&name, identity)?;
758 Ok(())
759 })
760 }
761
762 async fn retire(&mut self) -> Result<()> {
763 if let Some(retire) = self.retirement() {
764 tokio::spawn(async move { super::owner_work(retire).await })
765 .await
766 .map_err(anyhow::Error::from)??;
767 }
768 Ok(())
769 }
770 }
771
772 impl Drop for SocketFileGuard {
773 fn drop(&mut self) {
774 let Some(retire) = self.retirement() else {
775 return;
776 };
777 if let Ok(handle) = tokio::runtime::Handle::try_current() {
778 handle.spawn(async move {
779 if let Err(error) = super::owner_work(retire).await {
780 tracing::warn!(%error, "private endpoint retirement is uncertain; retaining it");
781 }
782 });
783 } else if let Err(error) = retire() {
784 tracing::warn!(%error, "private endpoint retirement is uncertain; retaining it");
785 }
786 }
787 }
788
789 /// A bound, not yet serving, daemon socket.
790 pub struct DaemonSocket {
791 listener: UnixListener,
792 path: PathBuf,
793 state: AppState,
794 shutdown: Arc<watch::Sender<bool>>,
795 socket_file: SocketFileGuard,
796 owner: Option<super::RuntimeOwnerReceipt>,
797 }
798
799 impl DaemonSocket {
800 /// Where clients connect.
801 #[must_use]
802 pub fn local_path(&self) -> &Path {
803 &self.path
804 }
805
806 /// A handle that stops [`Self::serve`] from outside (signals, tests).
807 #[must_use]
808 pub fn shutdown_handle(&self) -> DaemonShutdownHandle {
809 DaemonShutdownHandle(Arc::clone(&self.shutdown))
810 }
811
812 /// Accept clients until the owner sends `shutdown` or the handle is
813 /// triggered. Removes the socket file on the way out.
814 pub async fn serve(self) -> Result<(), DaemonSocketError> {
815 let Self {
816 listener,
817 path,
818 state,
819 shutdown,
820 socket_file,
821 owner,
822 } = self;
823 let mut socket_file = socket_file;
824 let context = super::connection_context(
825 state,
826 path.clone(),
827 DaemonShutdownHandle(Arc::clone(&shutdown)),
828 owner,
829 )
830 .await
831 .map_err(DaemonSocketError::State)?;
832 let mut shutdown_rx = shutdown.subscribe();
833 let mut connections = ConnectionTasks::default();
834
835 loop {
836 if *shutdown_rx.borrow() {
837 break;
838 }
839 tokio::select! {
840 accepted = listener.accept() => match accepted {
841 Ok((stream, _)) => {
842 connections.spawn(handle_connection(context.clone(), stream));
843 }
844 Err(err) => {
845 tracing::warn!(error = %err, "daemon socket accept failed");
846 tokio::time::sleep(Duration::from_millis(50)).await;
847 }
848 },
849 changed = shutdown_rx.changed() => {
850 if changed.is_err() || *shutdown_rx.borrow() {
851 break;
852 }
853 }
854 }
855 }
856
857 // The owner's `shutdown` reply was flushed before its loop
858 // returned, so aborting what is left loses nothing a client
859 // still needs.
860 connections.shutdown().await;
861 drop(listener);
862 socket_file
863 .retire()
864 .await
865 .map_err(DaemonSocketError::State)?;
866 Ok(())
867 }
868 }
869
870 /// Resolve the path, clear a stale socket, bind with `0600`, and build
871 /// the shared app state. Does not accept anything until
872 /// [`DaemonSocket::serve`].
873 pub async fn bind_daemon_socket(
874 options: DaemonSocketOptions,
875 ) -> Result<DaemonSocket, DaemonSocketError> {
876 // A daemon-only run has nothing else to serve with, so a mount that
877 // cannot carry the endpoint is a failure here rather than a degraded
878 // start. `bind_with_owner` reports it as such when `degrade` is false.
879 match bind_with_owner(options, None, None, false).await? {
880 Some(socket) => Ok(socket),
881 // A non-degrading bind reports a mount it cannot use as an error,
882 // so this is an internal invariant rather than a runtime state.
883 None => Err(DaemonSocketError::State(anyhow::anyhow!(
884 "a bind that cannot degrade returned no endpoint"
885 ))),
886 }
887 }
888
889 /// Bind the control endpoint for an owner that also has an HTTP frontend.
890 ///
891 /// `None` means this filesystem cannot hold a private endpoint directory.
892 /// The owner still serves HTTP, which is what its clients connect to; what
893 /// it loses is the socket a second client would use to discover it. The
894 /// store owner lock still keeps a second engine out of the same store, so
895 /// this degrades discovery, not mutual exclusion.
896 pub(crate) async fn bind_captured_owner(
897 state: AppState,
898 owner: super::RuntimeOwnerReceipt,
899 recovery: Option<Arc<crate::daemon_client::UnavailablePublication>>,
900 ) -> Result<Option<DaemonSocket>, DaemonSocketError> {
901 let options = DaemonSocketOptions {
902 socket_path: Some(owner.socket_path.clone()),
903 config_path: None,
904 };
905 bind_with_owner(options, Some((state, owner)), recovery, true).await
906 }
907
908 async fn bind_with_owner(
909 options: DaemonSocketOptions,
910 captured: Option<(AppState, super::RuntimeOwnerReceipt)>,
911 recovery: Option<Arc<crate::daemon_client::UnavailablePublication>>,
912 degrade: bool,
913 ) -> Result<Option<DaemonSocket>, DaemonSocketError> {
914 let owner_state = captured.as_ref().map(|(state, _)| state.clone());
915 let path = resolve_socket_path(&SocketPathInputs::from_environment(options.socket_path)?)?;
916 let parent_path = path
917 .parent()
918 .filter(|parent| !parent.as_os_str().is_empty())
919 .ok_or(DaemonSocketError::RuntimeDirUnavailable)?
920 .to_path_buf();
921 let parent = if let Some(previous) = recovery.as_ref() {
922 let owner = &captured
923 .as_ref()
924 .ok_or_else(|| {
925 DaemonSocketError::State(anyhow::anyhow!(
926 "stale publication requires the actual captured Runtime owner"
927 ))
928 })?
929 .1;
930 previous
931 .require_same_selection(owner, &path)
932 .map_err(DaemonSocketError::State)?;
933 if !previous
934 .revalidate()
935 .await
936 .map_err(DaemonSocketError::State)?
937 {
938 return Err(DaemonSocketError::State(anyhow::anyhow!(
939 "captured stale owner changed before bind"
940 )));
941 }
942 previous.publication.parent.clone()
943 } else {
944 // The strict admission first: on a filesystem that stores owner and
945 // mode it succeeds and nothing here costs anything extra. Only a
946 // failure asks the mount what it can express, which is what turns
947 // the opaque "failed to build daemon state" into either a reason to
948 // continue without the endpoint or a named refusal.
949 let admitted = socket_owner_work(owner_state.clone(), {
950 let parent_path = parent_path.clone();
951 move || PrivateDirectory::admit(&parent_path)
952 })
953 .await;
954 match admitted {
955 Ok(directory) => Arc::new(directory),
956 Err(error) => {
957 if let codewhale_config::private_directory::PrivateFooting::Synthesised {
958 observed_uid,
959 observed_mode,
960 } = socket_owner_work(owner_state.clone(), {
961 let parent_path = parent_path.clone();
962 move || {
963 Ok(codewhale_config::private_directory::mount_footing(
964 &parent_path,
965 ))
966 }
967 })
968 .await
969 .map_err(DaemonSocketError::State)?
970 {
971 if degrade {
972 tracing::warn!(
973 endpoint = %path.display(),
974 "{} cannot provide workspace control-socket discovery: the \
975 filesystem reports uid {observed_uid} and mode \
976 {observed_mode:o} for objects created on it, so a private \
977 endpoint directory cannot be verified here; serving the control \
978 API over HTTP only",
979 parent_path.display()
980 );
981 return Ok(None);
982 }
983 return Err(DaemonSocketError::EndpointDirectoryUnsupported {
984 path: parent_path.clone(),
985 reason: format!(
986 "the filesystem reports uid {observed_uid} and mode \
987 {observed_mode:o} for objects created on it, so a private \
988 endpoint directory cannot be verified there"
989 ),
990 });
991 }
992 return Err(DaemonSocketError::State(error));
993 }
994 }
995 };
996 let name = path
997 .file_name()
998 .and_then(|name| name.to_str())
999 .ok_or(DaemonSocketError::RuntimeDirUnavailable)?
1000 .to_string();
1001 clear_stale_socket(
1002 &path,
1003 &parent,
1004 &name,
1005 recovery.clone(),
1006 captured.is_some() && recovery.is_none(),
1007 owner_state.clone(),
1008 )
1009 .await?;
1010 let check_parent = parent.clone();
1011 if !super::owner_work(move || check_parent.is_at_selected_path())
1012 .await
1013 .map_err(DaemonSocketError::State)?
1014 {
1015 return Err(DaemonSocketError::State(anyhow::anyhow!(
1016 "private endpoint parent changed"
1017 )));
1018 }
1019
1020 // Withdraw the exact dead publication before a new PID can answer on
1021 // its endpoint. Contenders then re-observe absence and the held lease.
1022 if let Some(previous) = recovery.as_ref() {
1023 let previous = previous.clone();
1024 let parent = parent.clone();
1025 socket_owner_work(owner_state.clone(), move || {
1026 anyhow::ensure!(
1027 previous.revalidate_receipt()?,
1028 "captured stale owner receipt changed before retirement"
1029 );
1030 anyhow::ensure!(
1031 parent.retire_private_receipt(
1032 &previous.publication.receipt_name,
1033 &previous.publication.file
1034 )?,
1035 "captured stale owner receipt changed during retirement"
1036 );
1037 Ok(())
1038 })
1039 .await
1040 .map_err(DaemonSocketError::State)?;
1041 }
1042
1043 #[cfg(test)]
1044 BEFORE_OWNER_REBIND.with(|slot| {
1045 if let Some(observe) = slot.borrow_mut().take() {
1046 observe(&path);
1047 }
1048 });
1049 let listener = UnixListener::bind(&path).map_err(|source| DaemonSocketError::Io {
1050 context: "failed to bind the daemon socket",
1051 path: path.clone(),
1052 source,
1053 })?;
1054 let inspect_parent = parent.clone();
1055 let inspect_name = name.clone();
1056 let identity = super::owner_work(move || inspect_parent.socket_identity(&inspect_name))
1057 .await
1058 .map_err(DaemonSocketError::State)?
1059 .ok_or_else(|| {
1060 DaemonSocketError::State(anyhow::anyhow!("bound socket identity is unavailable"))
1061 })?;
1062 let socket_file = SocketFileGuard {
1063 parent: parent.clone(),
1064 name,
1065 identity,
1066 receipt: None,
1067 owner_state: owner_state.clone(),
1068 retired: false,
1069 };
1070 let protect_parent = parent.clone();
1071 let protect_name = socket_file.name.clone();
1072 socket_owner_work(owner_state.clone(), move || {
1073 anyhow::ensure!(
1074 protect_parent.is_at_selected_path()?,
1075 "private endpoint parent changed during bind"
1076 );
1077 protect_parent.protect_socket(&protect_name, identity)
1078 })
1079 .await
1080 .map_err(DaemonSocketError::State)?;
1081
1082 let (state, owner) = match captured {
1083 Some((state, owner)) => (state, Some(owner)),
1084 None => (
1085 build_state_off_runtime(options.config_path, None, AppTransport::Socket)
1086 .await
1087 .map_err(DaemonSocketError::State)?,
1088 None,
1089 ),
1090 };
1091 let mut socket_file = socket_file;
1092 if let Some(owner) = owner.as_ref() {
1093 let receipt_name = format!("{}.owner.json", socket_file.name);
1094 let bytes = serde_json::to_vec(owner)
1095 .map_err(|error| DaemonSocketError::State(error.into()))?;
1096 if bytes.len() > 16384 {
1097 return Err(DaemonSocketError::State(anyhow::anyhow!(
1098 "owner receipt exceeds private publication limit"
1099 )));
1100 }
1101 let parent = parent.clone();
1102 let name = receipt_name.clone();
1103 let guard = socket_file;
1104 socket_file = socket_owner_work(owner_state, move || {
1105 let mut guard = guard;
1106 anyhow::ensure!(
1107 parent.is_at_selected_path()?,
1108 "private owner parent changed before publication"
1109 );
1110 anyhow::ensure!(
1111 parent.read_private_receipt(&name, 16384)?.is_none(),
1112 "owner publication appeared during bootstrap; refusing replacement"
1113 );
1114 parent.write_owned_file(&name, &bytes, false)?;
1115 let (_, file) = parent
1116 .read_private_receipt(&name, 16384)?
1117 .ok_or_else(|| anyhow::anyhow!("published owner receipt unavailable"))?;
1118 guard.receipt = Some((name, file));
1119 anyhow::ensure!(
1120 parent.is_at_selected_path()?,
1121 "private owner parent changed during publication; retaining uncertain receipt"
1122 );
1123 Ok(guard)
1124 })
1125 .await
1126 .map_err(DaemonSocketError::State)?;
1127 }
1128 let (shutdown, _) = watch::channel(false);
1129 Ok(Some(DaemonSocket {
1130 listener,
1131 path,
1132 state,
1133 shutdown: Arc::new(shutdown),
1134 socket_file,
1135 owner,
1136 }))
1137 }
1138
1139 /// Only a definite refusal permits exact captured endpoint retirement.
1140 async fn clear_stale_socket(
1141 path: &Path,
1142 parent: &Arc<PrivateDirectory>,
1143 name: &str,
1144 recovery: Option<Arc<crate::daemon_client::UnavailablePublication>>,
1145 expect_no_receipt: bool,
1146 owner_state: Option<AppState>,
1147 ) -> Result<(), DaemonSocketError> {
1148 let inspect_parent = parent.clone();
1149 let inspect_name = name.to_string();
1150 let expected = recovery.clone();
1151 let Some(identity) = super::owner_work(move || {
1152 if let Some(previous) = expected.as_ref() {
1153 anyhow::ensure!(
1154 previous.revalidate_all()?,
1155 "captured stale owner/socket changed before retirement"
1156 );
1157 return Ok(previous.publication.socket_identity);
1158 }
1159 if expect_no_receipt {
1160 anyhow::ensure!(
1161 inspect_parent
1162 .read_private_receipt(&format!("{inspect_name}.owner.json"), 16384)?
1163 .is_none(),
1164 "owner publication appeared before fresh endpoint bind; refusing replacement"
1165 );
1166 }
1167 inspect_parent.socket_identity(&inspect_name)
1168 })
1169 .await
1170 .map_err(|error| {
1171 if error
1172 .downcast_ref::<std::io::Error>()
1173 .is_some_and(|error| error.kind() == std::io::ErrorKind::InvalidInput)
1174 {
1175 DaemonSocketError::NotASocket {
1176 path: path.to_path_buf(),
1177 }
1178 } else {
1179 DaemonSocketError::State(error)
1180 }
1181 })?
1182 else {
1183 return Ok(());
1184 };
1185 match tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(path)).await {
1186 Ok(Ok(_live)) => Err(DaemonSocketError::AlreadyRunning {
1187 path: path.to_path_buf(),
1188 }),
1189 Ok(Err(error)) if error.kind() == std::io::ErrorKind::ConnectionRefused => {
1190 let retire_parent = parent.clone();
1191 let retire_name = name.to_string();
1192 if socket_owner_work(owner_state, move || {
1193 if let Some(previous) = recovery.as_ref() {
1194 anyhow::ensure!(previous.revalidate_all()?, "captured stale owner/socket changed before retirement");
1195 } else if expect_no_receipt {
1196 anyhow::ensure!(retire_parent.read_private_receipt(&format!("{retire_name}.owner.json"), 16384)?.is_none(),
1197 "owner publication appeared before fresh endpoint retirement; refusing replacement");
1198 }
1199 retire_parent.retire_socket(&retire_name, identity)
1200 })
1201 .await
1202 .map_err(DaemonSocketError::State)?
1203 {
1204 Ok(())
1205 } else {
1206 Err(DaemonSocketError::State(anyhow::anyhow!(
1207 "stale endpoint changed; refusing replacement"
1208 )))
1209 }
1210 }
1211 Ok(Err(source)) => Err(DaemonSocketError::Io {
1212 context: "uncertain daemon endpoint probe; refusing replacement",
1213 path: path.to_path_buf(),
1214 source,
1215 }),
1216 Err(_) => Err(DaemonSocketError::ProbeTimedOut {
1217 path: path.to_path_buf(),
1218 }),
1219 }
1220 }
1221
1222 async fn handle_connection(context: ConnectionContext, stream: UnixStream) {
1223 let credential = match stream.peer_cred() {
1224 Ok(peer) if peer.uid() == context.info.uid => peer,
1225 _ => return,
1226 };
1227 let Some(pid) = credential.pid().and_then(|pid| u32::try_from(pid).ok()) else {
1228 return;
1229 };
1230 let start = match super::owner_work(move || {
1231 codewhale_config::private_directory::unix_process_start(pid)
1232 })
1233 .await
1234 {
1235 Ok(start) => start,
1236 Err(_) => return,
1237 };
1238 let (read, write) = stream.into_split();
1239 super::run_authorized_connection(
1240 context,
1241 read,
1242 write,
1243 super::AuthorizedPeer { pid, start },
1244 )
1245 .await;
1246 }
1247
1248 #[cfg(test)]
1249 mod tests {
1250 use super::*;
1251 use anyhow::Context as _;
1252
1253 struct FrontendLifetime {
1254 _held: Arc<()>,
1255 }
1256 impl crate::RuntimeOwnerFrontend for FrontendLifetime {
1257 fn execute(
1258 &self,
1259 _request: crate::RuntimeOwnerRequest,
1260 ) -> std::pin::Pin<
1261 Box<
1262 dyn std::future::Future<Output = anyhow::Result<serde_json::Value>> + Send + '_,
1263 >,
1264 > {
1265 Box::pin(async {
1266 anyhow::bail!("this captured frontend admits no ordinary native service")
1267 })
1268 }
1269 fn events(
1270 &self,
1271 _thread_id: String,
1272 _since_seq: u64,
1273 ) -> std::pin::Pin<
1274 Box<
1275 dyn std::future::Future<Output = anyhow::Result<crate::RuntimeOwnerEventStream>>
1276 + Send
1277 + '_,
1278 >,
1279 > {
1280 Box::pin(async {
1281 anyhow::bail!("this captured frontend admits no ordinary native observation")
1282 })
1283 }
1284 fn validate_selection<'a>(
1285 &'a self,
1286 _selection: &'a crate::RuntimeOwnerFrontendSelection,
1287 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>
1288 {
1289 Box::pin(async { anyhow::bail!("lifetime-only frontend cannot admit a command") })
1290 }
1291 fn serve<'a>(
1292 &'a self,
1293 _selection: crate::RuntimeOwnerFrontendSelection,
1294 _compatibility: AppState,
1295 _input: Box<dyn tokio::io::AsyncBufRead + Send + Unpin>,
1296 _output: Box<dyn tokio::io::AsyncWrite + Send + Unpin + 'a>,
1297 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>
1298 {
1299 Box::pin(async { anyhow::bail!("lifetime-only frontend cannot serve a command") })
1300 }
1301 }
1302
1303 #[tokio::test]
1304 async fn owner_bootstrap_cancelled_mutations_and_retirement_retain_captured_frontend()
1305 -> Result<()> {
1306 // Proves transport custody. The TUI bootstrap tests separately
1307 // prove the captured manager retains its real store lease.
1308 let temporary = tempfile::Builder::new()
1309 .prefix("cw-ob-cancel-")
1310 .tempdir_in("/tmp")?;
1311 let root = temporary.path().canonicalize()?;
1312 let config = root.join("config.toml");
1313 std::fs::write(&config, "")?;
1314 for retirement in [false, true] {
1315 let mut state =
1316 build_state_off_runtime(Some(config.clone()), None, AppTransport::Socket)
1317 .await?;
1318 let held = Arc::new(());
1319 let observed_owner = Arc::downgrade(&held);
1320 state.owner_frontend = Some(Arc::new(FrontendLifetime { _held: held }));
1321 let parent_path = root.join(if retirement { "retirement" } else { "mutation" });
1322 let parent = Arc::new(PrivateDirectory::admit(&parent_path)?);
1323 let path = parent_path.join("daemon.sock");
1324 let socket = std::os::unix::net::UnixListener::bind(&path)?;
1325 let identity = parent
1326 .socket_identity("daemon.sock")?
1327 .context("socket identity")?;
1328 parent.protect_socket("daemon.sock", identity)?;
1329 drop(socket);
1330 parent.write_owned_file("daemon.sock.owner.json", b"{}", false)?;
1331 let (_, receipt_file) = parent
1332 .read_private_receipt("daemon.sock.owner.json", 16384)?
1333 .context("receipt")?;
1334 let (release, released) = std::sync::mpsc::channel();
1335 let (started, observed_start) = tokio::sync::oneshot::channel();
1336 let (finished, observed_finish) = tokio::sync::oneshot::channel();
1337 let worker = if retirement {
1338 let mut guard = SocketFileGuard {
1339 parent,
1340 name: "daemon.sock".into(),
1341 identity,
1342 receipt: Some(("daemon.sock.owner.json".into(), receipt_file)),
1343 owner_state: Some(state.clone()),
1344 retired: false,
1345 };
1346 let retire = guard.retirement().context("first retirement")?;
1347 drop(guard);
1348 tokio::spawn(super::super::owner_work(move || {
1349 let _ = started.send(());
1350 let _ = released.recv();
1351 let result = retire();
1352 let _ = finished.send(());
1353 result
1354 }))
1355 } else {
1356 tokio::spawn(socket_owner_work(Some(state.clone()), move || {
1357 let _ = started.send(());
1358 let _ = released.recv();
1359 parent.protect_socket("daemon.sock", identity)?;
1360 let _ = finished.send(());
1361 Ok(())
1362 }))
1363 };
1364 drop(state);
1365 tokio::time::timeout(Duration::from_secs(5), observed_start).await??;
1366 worker.abort();
1367 let _ = worker.await;
1368 assert!(
1369 observed_owner.upgrade().is_some(),
1370 "running filesystem mutation retains captured owner after waiter cancellation"
1371 );
1372 release.send(())?;
1373 tokio::time::timeout(Duration::from_secs(5), observed_finish).await??;
1374 tokio::time::timeout(Duration::from_secs(5), async {
1375 while observed_owner.upgrade().is_some() {
1376 tokio::task::yield_now().await;
1377 }
1378 })
1379 .await?;
1380 if retirement {
1381 assert!(!path.exists());
1382 assert!(!path.with_file_name("daemon.sock.owner.json").exists());
1383 } else {
1384 assert!(path.exists(), "protection alone preserves publication");
1385 assert!(path.with_file_name("daemon.sock.owner.json").exists());
1386 }
1387 }
1388 Ok(())
1389 }
1390
1391 #[tokio::test(flavor = "current_thread")]
1392 async fn owner_bootstrap_withdraws_dead_receipt_before_replacement_listener_can_answer()
1393 -> Result<()> {
1394 struct OwnedChild(std::process::Child);
1395 impl Drop for OwnedChild {
1396 fn drop(&mut self) {
1397 if self.0.try_wait().ok().flatten().is_none() {
1398 let _ = self.0.kill();
1399 }
1400 let _ = self.0.wait();
1401 }
1402 }
1403 let temporary = tempfile::Builder::new()
1404 .prefix("cw-ob-order-")
1405 .tempdir_in("/tmp")?;
1406 let root = temporary.path().canonicalize()?;
1407 let path = root.join("run/daemon.sock");
1408 let config = root.join("config.toml");
1409 std::fs::write(&config, "")?;
1410 let parent = PrivateDirectory::admit(path.parent().unwrap())?;
1411 std::fs::create_dir_all(root.join("runtime"))?;
1412 let stale = std::os::unix::net::UnixListener::bind(&path)?;
1413 let identity = parent.socket_identity("daemon.sock")?.unwrap();
1414 parent.protect_socket("daemon.sock", identity)?;
1415 drop(stale);
1416 let mut child = OwnedChild(
1417 std::process::Command::new("/bin/sleep")
1418 .arg("60")
1419 .stdin(std::process::Stdio::null())
1420 .stdout(std::process::Stdio::null())
1421 .stderr(std::process::Stdio::null())
1422 .spawn()?,
1423 );
1424 let mut owner = codewhale_protocol::RuntimeOwnerReceipt {
1425 version: 1,
1426 data_dir: root.join("runtime"),
1427 execution_scope: "ordering-store".into(),
1428 lease_generation: "ordering-old".into(),
1429 pid: child.0.id(),
1430 process_start: super::super::capture_process_start(child.0.id()).await?,
1431 principal: PrivateDirectory::current_user_id().to_string(),
1432 socket_path: path.clone(),
1433 config_path: Some(config.clone()),
1434 };
1435 child.0.kill()?;
1436 child.0.wait()?;
1437 parent.write_owned_file(
1438 "daemon.sock.owner.json",
1439 &serde_json::to_vec(&owner)?,
1440 false,
1441 )?;
1442 let crate::daemon_client::HostOwnerProbe::Unavailable(captured) =
1443 crate::daemon_client::probe_owner_for_host_startup(
1444 Some(config.clone()),
1445 Some(path.clone()),
1446 &owner.data_dir,
1447 )
1448 .await?
1449 else {
1450 anyhow::bail!("dead owner must be captured")
1451 };
1452 let observed = Arc::new(std::sync::atomic::AtomicBool::new(false));
1453 let observed_hook = observed.clone();
1454 let selected = path.clone();
1455 let selected_config = config.clone();
1456 let selected_store = owner.data_dir.clone();
1457 let stale_capture = captured.clone();
1458 BEFORE_OWNER_REBIND.with(|slot| {
1459 *slot.borrow_mut() = Some(Box::new(move |endpoint| {
1460 assert_eq!(endpoint, selected);
1461 assert!(!selected.with_file_name("daemon.sock.owner.json").exists());
1462 let endpoint = selected.clone();
1463 std::thread::spawn(move || {
1464 tokio::runtime::Builder::new_current_thread()
1465 .enable_all()
1466 .build()
1467 .unwrap()
1468 .block_on(async {
1469 assert!(
1470 !stale_capture.revalidate().await.unwrap(),
1471 "withdrawn capture must never authorize a replacement"
1472 );
1473 assert!(matches!(
1474 crate::daemon_client::probe_owner_for_host_startup(
1475 Some(selected_config),
1476 Some(endpoint),
1477 &selected_store,
1478 )
1479 .await
1480 .unwrap(),
1481 crate::daemon_client::HostOwnerProbe::Absent
1482 ));
1483 });
1484 })
1485 .join()
1486 .unwrap();
1487 // Force bind failure after the exact observation point;
1488 // the product must preserve this task-owned replacement.
1489 drop(std::os::unix::net::UnixListener::bind(&selected).unwrap());
1490 observed_hook.store(true, std::sync::atomic::Ordering::SeqCst);
1491 }));
1492 });
1493 owner.pid = std::process::id();
1494 owner.process_start = super::super::capture_process_start(owner.pid).await?;
1495 owner.lease_generation = "ordering-new".into();
1496 let result = crate::bind_runtime_frontends(
1497 Some(config),
1498 None,
1499 owner,
1500 crate::RuntimeOwnerRouting {
1501 endpoint: "127.0.0.1:1".parse()?,
1502 workspace: None,
1503 workers: None,
1504 mobile: false,
1505 web: false,
1506 acp: false,
1507 acp_only: false,
1508 },
1509 None,
1510 Some(captured),
1511 )
1512 .await;
1513 assert!(result.is_err(), "injected replacement prevents new bind");
1514 assert!(observed.load(std::sync::atomic::Ordering::SeqCst));
1515 assert!(
1516 parent.socket_identity("daemon.sock")?.is_some(),
1517 "replacement endpoint preserved"
1518 );
1519 assert!(!path.with_file_name("daemon.sock.owner.json").exists());
1520 Ok(())
1521 }
1522
1523 fn client(name: &str) -> ClientIdentity {
1524 ClientIdentity {
1525 name: name.to_string(),
1526 version: None,
1527 pid: None,
1528 }
1529 }
1530
1531 #[tokio::test]
1532 async fn finished_connection_tasks_are_reaped() {
1533 let mut connections = ConnectionTasks::default();
1534 let mut handles = Vec::new();
1535 for _ in 0..3 {
1536 handles.push(connections.0.spawn(async {}));
1537 }
1538 handles.push(
1539 connections
1540 .0
1541 .spawn(async { panic!("fixture connection panic") }),
1542 );
1543 tokio::time::timeout(Duration::from_secs(5), async {
1544 while !handles.iter().all(tokio::task::AbortHandle::is_finished) {
1545 tokio::task::yield_now().await;
1546 }
1547 })
1548 .await
1549 .expect("fixture connections finish");
1550
1551 // Accepting the next client reaps every finished connection,
1552 // including the panicked one, and keeps only the new live one.
1553 connections.spawn(std::future::pending::<()>());
1554 assert_eq!(connections.0.len(), 1, "only the live connection is kept");
1555 connections.0.abort_all();
1556 }
1557
1558 #[tokio::test]
1559 async fn cancelled_owner_waiter_retains_worker_capacity_until_real_completion() {
1560 let (started, mut observed) = tokio::sync::mpsc::unbounded_channel();
1561 let mut releases = Vec::new();
1562 let mut waiters = Vec::new();
1563 for _ in 0..4 {
1564 let (release, released) = std::sync::mpsc::channel();
1565 releases.push(release);
1566 let started = started.clone();
1567 waiters.push(tokio::spawn(super::super::owner_work(move || {
1568 started.send(()).unwrap();
1569 let _ = released.recv();
1570 Ok(())
1571 })));
1572 }
1573 for _ in 0..4 {
1574 tokio::time::timeout(Duration::from_secs(5), observed.recv())
1575 .await
1576 .unwrap()
1577 .unwrap();
1578 }
1579 waiters[0].abort();
1580 let _ = (&mut waiters[0]).await;
1581 let (next_started, mut next_observed) = tokio::sync::mpsc::unbounded_channel();
1582 let next = tokio::spawn(super::super::owner_work(move || {
1583 next_started.send(()).unwrap();
1584 Ok(())
1585 }));
1586 tokio::task::yield_now().await;
1587 assert!(matches!(
1588 next_observed.try_recv(),
1589 Err(tokio::sync::mpsc::error::TryRecvError::Empty)
1590 ));
1591 releases.remove(0).send(()).unwrap();
1592 tokio::time::timeout(Duration::from_secs(5), next_observed.recv())
1593 .await
1594 .unwrap()
1595 .unwrap();
1596 for release in releases {
1597 release.send(()).unwrap();
1598 }
1599 for waiter in waiters.into_iter().skip(1) {
1600 waiter.await.unwrap().unwrap();
1601 }
1602 next.await.unwrap().unwrap();
1603 }
1604
1605 #[test]
1606 fn registry_claim_is_exclusive_until_the_owner_leaves() {
1607 let mut registry = ConnectionRegistry::default();
1608 let first = registry.register(client("desktop-a"));
1609 let second = registry.register(client("desktop-b"));
1610
1611 assert!(registry.claim(first).is_ok());
1612 assert_eq!(registry.claim(second), Err(client("desktop-a")));
1613 assert!(
1614 registry.claim(first).is_ok(),
1615 "re-claim by the owner is idempotent"
1616 );
1617
1618 registry.remove(first);
1619 assert_eq!(registry.owner(), None);
1620 assert!(registry.claim(second).is_ok());
1621 assert_eq!(registry.owner(), Some(client("desktop-b")));
1622 }
1623
1624 #[test]
1625 fn removing_a_guest_keeps_the_owner() {
1626 let mut registry = ConnectionRegistry::default();
1627 let owner = registry.register(client("owner"));
1628 let guest = registry.register(client("guest"));
1629 registry.claim(owner).expect("claim");
1630 registry.remove(guest);
1631 assert_eq!(registry.owner(), Some(client("owner")));
1632 assert_eq!(registry.connections.len(), 1);
1633 }
1634 }
1635 }
1636
1637 #[cfg(not(any(unix, windows)))]
1638 mod platform {
1639 use std::path::Path;
1640
1641 use super::{
1642 DaemonShutdownHandle, DaemonSocketError, DaemonSocketOptions, unsupported_platform,
1643 };
1644
1645 /// Placeholder until the Windows named pipe lands; cannot be constructed.
1646 pub struct DaemonSocket {
1647 never: std::convert::Infallible,
1648 }
1649
1650 impl DaemonSocket {
1651 #[must_use]
1652 pub fn local_path(&self) -> &Path {
1653 match self.never {}
1654 }
1655
1656 #[must_use]
1657 pub fn shutdown_handle(&self) -> DaemonShutdownHandle {
1658 match self.never {}
1659 }
1660
1661 pub async fn serve(self) -> Result<(), DaemonSocketError> {
1662 match self.never {}
1663 }
1664 }
1665
1666 /// Always [`DaemonSocketError::UnsupportedPlatform`] here.
1667 pub async fn bind_daemon_socket(
1668 _options: DaemonSocketOptions,
1669 ) -> Result<DaemonSocket, DaemonSocketError> {
1670 Err(unsupported_platform())
1671 }
1672 }
1673
1674 #[cfg(windows)]
1675 use crate::daemon_windows as platform;
1676 pub use platform::{DaemonSocket, bind_daemon_socket};
1677
1678 #[cfg(any(unix, windows))]
1679 pub(crate) use platform::bind_captured_owner;
1680
1681 #[cfg(unix)]
1682 pub async fn capture_process_start(pid: u32) -> anyhow::Result<String> {
1683 owner_work(move || codewhale_config::private_directory::unix_process_start(pid)).await
1684 }
1685
1686 #[cfg(windows)]
1687 pub fn default_socket_path() -> Result<PathBuf, DaemonSocketError> {
1688 crate::daemon_windows::selected_pipe_path(None).map_err(DaemonSocketError::State)
1689 }
1690
1691 #[cfg(windows)]
1692 pub async fn capture_process_start(pid: u32) -> anyhow::Result<String> {
1693 owner_work(move || {
1694 Ok(
1695 codewhale_config::windows_identity::WindowsPeerProcess::open_current_user(pid)?
1696 .start()
1697 .to_string(),
1698 )
1699 })
1700 .await
1701 }
1702
1703 #[cfg(test)]
1704 mod tests {
1705 use super::*;
1706 #[cfg(unix)]
1707 use std::path::Path;
1708
1709 fn inputs() -> SocketPathInputs {
1710 SocketPathInputs {
1711 explicit: None,
1712 codewhale_home_override: None,
1713 xdg_runtime_dir: None,
1714 user_home: Some(PathBuf::from("/cw-test-home/whale")),
1715 macos: false,
1716 }
1717 }
1718
1719 #[test]
1720 fn explicit_path_wins() {
1721 let resolved = resolve_socket_path(&SocketPathInputs {
1722 explicit: Some(PathBuf::from("/tmp/x.sock")),
1723 codewhale_home_override: Some(PathBuf::from("/iso")),
1724 xdg_runtime_dir: Some(PathBuf::from("/run/user/1000")),
1725 ..inputs()
1726 })
1727 .expect("resolve");
1728 assert_eq!(resolved, PathBuf::from("/tmp/x.sock"));
1729 }
1730
1731 #[test]
1732 fn explicit_codewhale_home_isolates_the_daemon() {
1733 let resolved = resolve_socket_path(&SocketPathInputs {
1734 codewhale_home_override: Some(PathBuf::from("/iso/home")),
1735 xdg_runtime_dir: Some(PathBuf::from("/run/user/1000")),
1736 ..inputs()
1737 })
1738 .expect("resolve");
1739 assert_eq!(resolved, PathBuf::from("/iso/home/run/daemon.sock"));
1740 }
1741
1742 #[test]
1743 fn xdg_runtime_dir_beats_home_layouts() {
1744 let resolved = resolve_socket_path(&SocketPathInputs {
1745 xdg_runtime_dir: Some(PathBuf::from("/run/user/1000")),
1746 macos: true,
1747 ..inputs()
1748 })
1749 .expect("resolve");
1750 assert_eq!(
1751 resolved,
1752 PathBuf::from("/run/user/1000/codewhale/daemon.sock")
1753 );
1754 }
1755
1756 #[test]
1757 fn macos_defaults_to_application_support() {
1758 let resolved = resolve_socket_path(&SocketPathInputs {
1759 macos: true,
1760 user_home: Some(PathBuf::from("/Users/whale")),
1761 ..inputs()
1762 })
1763 .expect("resolve");
1764 assert_eq!(
1765 resolved,
1766 PathBuf::from("/Users/whale/Library/Application Support/codewhale/daemon.sock")
1767 );
1768 }
1769
1770 #[test]
1771 fn linux_defaults_to_dot_codewhale_run() {
1772 let resolved = resolve_socket_path(&inputs()).expect("resolve");
1773 assert_eq!(
1774 resolved,
1775 PathBuf::from("/cw-test-home/whale/.codewhale/run/daemon.sock")
1776 );
1777 }
1778
1779 #[cfg(unix)]
1780 #[test]
1781 fn default_store_keeps_the_well_known_socket() {
1782 let resolved = store_selected_socket_path(None, &inputs()).expect("resolve");
1783 assert_eq!(
1784 resolved,
1785 PathBuf::from("/cw-test-home/whale/.codewhale/run/daemon.sock")
1786 );
1787 }
1788
1789 #[cfg(unix)]
1790 #[test]
1791 fn distinct_stores_derive_distinct_sibling_sockets() {
1792 let one = store_selected_socket_path(
1793 Some(Path::new("/cw-test-home/whale/.local/state/one/runtime")),
1794 &inputs(),
1795 )
1796 .expect("resolve");
1797 let two = store_selected_socket_path(
1798 Some(Path::new("/cw-test-home/whale/.local/state/two/runtime")),
1799 &inputs(),
1800 )
1801 .expect("resolve");
1802 assert_eq!(
1803 one.parent().unwrap(),
1804 Path::new("/cw-test-home/whale/.codewhale/run")
1805 );
1806 assert_eq!(one.parent().unwrap(), two.parent().unwrap());
1807 assert_ne!(one, two);
1808 let name = one.file_name().unwrap().to_str().unwrap();
1809 assert!(name.starts_with("store-"), "derived name: {name}");
1810 assert!(name.ends_with(".sock"), "derived name: {name}");
1811 assert_eq!(name.len(), 23, "derived name: {name}");
1812 }
1813
1814 #[cfg(unix)]
1815 #[test]
1816 fn the_derived_socket_is_a_pure_function_of_the_store_root() {
1817 let store = Path::new("/cw-test-home/whale/.local/state/one/runtime");
1818 let first = store_selected_socket_path(Some(store), &inputs()).expect("resolve");
1819 let second = store_selected_socket_path(Some(store), &inputs()).expect("resolve");
1820 assert_eq!(first, second);
1821 }
1822
1823 #[cfg(unix)]
1824 #[test]
1825 fn store_sockets_stay_within_the_kernel_path_budget() {
1826 // The longest realistic parent (macOS app support) plus a long store
1827 // path must still resolve: the derived name is a fixed 23 bytes.
1828 let macos = SocketPathInputs {
1829 user_home: Some(PathBuf::from("/Users/whale")),
1830 macos: true,
1831 ..inputs()
1832 };
1833 let store = PathBuf::from(format!(
1834 "/Users/whale/Library/Application Support/Code/User/globalStorage/ext/runtime/ws-{}",
1835 "a".repeat(16)
1836 ));
1837 let resolved = store_selected_socket_path(Some(&store), &macos).expect("resolve");
1838 assert!(resolved.as_os_str().len() <= MAX_SOCKET_PATH_BYTES);
1839 }
1840
1841 #[test]
1842 fn no_home_is_a_typed_error() {
1843 let err = resolve_socket_path(&SocketPathInputs {
1844 user_home: None,
1845 ..inputs()
1846 })
1847 .expect_err("must fail");
1848 assert!(
1849 matches!(err, DaemonSocketError::RuntimeDirUnavailable),
1850 "{err}"
1851 );
1852 }
1853
1854 #[test]
1855 fn over_long_paths_are_refused_before_bind() {
1856 let long = PathBuf::from(format!(
1857 "/{}/daemon.sock",
1858 "d".repeat(MAX_SOCKET_PATH_BYTES)
1859 ));
1860 let err = resolve_socket_path(&SocketPathInputs {
1861 explicit: Some(long.clone()),
1862 ..inputs()
1863 })
1864 .expect_err("must fail");
1865 match err {
1866 DaemonSocketError::PathTooLong { path, len, max } => {
1867 assert_eq!(path, long);
1868 assert!(len > max);
1869 assert_eq!(max, MAX_SOCKET_PATH_BYTES);
1870 }
1871 other => panic!("unexpected error: {other}"),
1872 }
1873 }
1874
1875 #[test]
1876 fn unsupported_platform_error_names_the_named_pipe() {
1877 let err = unsupported_platform();
1878 let text = err.to_string();
1879 assert!(text.contains(WINDOWS_NAMED_PIPE), "{text}");
1880 assert!(text.contains("not implemented"), "{text}");
1881 }
1882
1883 #[test]
1884 fn attach_mode_defaults_to_guest() {
1885 let params: AttachParams =
1886 serde_json::from_value(serde_json::json!({ "client": { "name": "x" } }))
1887 .expect("parse");
1888 assert_eq!(params.mode, AttachMode::Attach);
1889 assert_eq!(params.expect_daemon_version, None);
1890 }
1891 }
1892
1892 lines RUST