Skip to main content

adk_kernel/control/
server.rs

1//! The control plane's listeners (spec 3.2 §7.11).
2
3use std::collections::HashMap;
4use std::fmt;
5use std::net::SocketAddr;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::time::Duration;
9
10use adk_core::RequestContext;
11use adk_server::approvals::{ApprovalEndpoints, approvals_router};
12use adk_server::auth_bridge::{RequestContextError, RequestContextExtractor};
13use axum::Router;
14use axum::body::Body;
15use axum::extract::ConnectInfo;
16use axum::http::Request;
17use axum::middleware::{self, Next};
18use axum::response::{IntoResponse, Response};
19use tokio::task::JoinHandle;
20use tokio_util::sync::CancellationToken;
21
22use super::routes::{ControlBackend, OPERATOR_SCOPE, routes};
23use super::{ControlPlaneConfig, ControlTransport, paths};
24use crate::error::{KernelError, Result};
25use crate::kernel::Kernel;
26
27/// How long [`ControlPlane::shutdown`] lets requests in flight finish; an event stream
28/// never does, so it is cut after this.
29const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
30
31/// The running listeners of a kernel's control plane (spec 3.2 §7.11): the Unix socket, or
32/// on Windows the named pipe [`ControlPlaneConfig::pipe_name`] names (§10 W2), and, when
33/// [`ControlPlaneConfig::http`](super::ControlPlaneConfig::http) is set, an HTTP bind, all
34/// serving [`router`](super::router) under `/api`, with the approvals inbox beside it when
35/// the kernel has an approval service.
36///
37/// The socket is created owner-only and admits only peers running as its owner, each as
38/// the OS user with the `operator` scope. The pipe carries a protected DACL that admits its
39/// owner, the user the kernel runs as, alone (§10 W4), and admits a connection only when the
40/// token the client opened it with is that user's. HTTP requests carry the configured
41/// extractor's subject, or, on a loopback bind without one, loopback peers as the OS user
42/// (K-I16). A non-loopback bind without an extractor is refused (K-I18). On a platform with
43/// neither, `start` with a socket configured answers [`KernelError::ControlPlane`].
44/// [`Kernel::start`] starts it and [`Kernel::stop`] shuts it down.
45///
46/// # Example
47///
48/// ```rust,no_run
49/// use adk_kernel::control::ControlPlane;
50///
51/// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
52/// let plane = ControlPlane::start(&kernel).await?;
53/// println!("listening on {:?}", plane.socket_path());
54/// plane.shutdown().await?;
55/// # Ok(())
56/// # }
57/// ```
58pub struct ControlPlane {
59    socket: Option<PathBuf>,
60    /// The directory of its own a socket too long for the home sits in (spec 3.3 G18).
61    socket_dir: Option<PathBuf>,
62    pipe: Option<String>,
63    http: Option<SocketAddr>,
64    tasks: Vec<JoinHandle<()>>,
65    stop: CancellationToken,
66}
67
68impl fmt::Debug for ControlPlane {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("ControlPlane")
71            .field("socket", &self.socket)
72            .field("pipe", &self.pipe)
73            .field("http", &self.http)
74            .finish_non_exhaustive()
75    }
76}
77
78impl ControlPlane {
79    /// Serves `kernel`'s control plane as its configuration says.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`KernelError::Config`] for a refused configuration (K-I18) and
84    /// [`KernelError::ControlPlane`] when the socket path, pipe or bind is taken, or when a
85    /// socket is configured on a platform with neither Unix sockets nor named pipes.
86    pub async fn start(kernel: &Kernel) -> Result<Self> {
87        let config = kernel.config();
88        Self::serve(Arc::new(kernel.clone()), &config.control, &config.home).await
89    }
90
91    /// Serves `backend` as `config` says, the socket path relative to `home`.
92    pub(crate) async fn serve(
93        backend: Arc<dyn ControlBackend>,
94        config: &ControlPlaneConfig,
95        home: &Path,
96    ) -> Result<Self> {
97        config.validate()?;
98        let mut plane = Self {
99            socket: None,
100            socket_dir: None,
101            pipe: None,
102            http: None,
103            tasks: Vec::new(),
104            stop: CancellationToken::new(),
105        };
106        let api = api(&backend);
107        #[cfg(windows)]
108        if let Some(name) = config.pipe_name(home) {
109            plane.tasks.push(super::pipe::serve(&name, api.clone(), plane.stop.clone()).await?);
110            plane.pipe = Some(name);
111        }
112        #[cfg(not(windows))]
113        if let (Some(socket), Some(path)) = (&config.socket, config.socket_path(home)) {
114            let configured = home.join(socket);
115            // A failure drops `plane`, which stops whatever already listens.
116            plane
117                .tasks
118                .push(serve_socket(&path, &configured, api.clone(), plane.stop.clone()).await?);
119            if path != configured {
120                plane.socket_dir = path.parent().map(Path::to_path_buf);
121            }
122            plane.socket = Some(path);
123        }
124        if let Some(addr) = config.http {
125            let (local, task) =
126                serve_http(addr, api, &backend, config.extractor.clone(), plane.stop.clone())
127                    .await?;
128            plane.tasks.push(task);
129            plane.http = Some(local);
130        }
131        tracing::info!(
132            control.socket = ?plane.socket,
133            control.pipe = ?plane.pipe,
134            control.http = ?plane.http,
135            "kernel control plane listening"
136        );
137        Ok(plane)
138    }
139
140    /// The socket's path, when one is served.
141    pub fn socket_path(&self) -> Option<&Path> {
142        self.socket.as_deref()
143    }
144
145    /// The named pipe's name, when one is served (Windows; spec 3.2 §10 W2).
146    pub fn pipe_name(&self) -> Option<&str> {
147        self.pipe.as_deref()
148    }
149
150    /// The HTTP address, when one is served: the bound address, so a configured port 0
151    /// reads as the port the system chose.
152    pub fn http_addr(&self) -> Option<SocketAddr> {
153        self.http
154    }
155
156    /// Stops accepting, finishes the requests in flight and removes the socket.
157    ///
158    /// # Errors
159    ///
160    /// Returns [`KernelError::Io`] when the socket cannot be removed.
161    pub async fn shutdown(mut self) -> Result<()> {
162        self.stop.cancel();
163        for task in std::mem::take(&mut self.tasks) {
164            let abort = task.abort_handle();
165            if tokio::time::timeout(SHUTDOWN_GRACE, task).await.is_err() {
166                abort.abort();
167            }
168        }
169        match self.socket.take() {
170            Some(path) => remove_socket(&path),
171            None => Ok(()),
172        }
173    }
174}
175
176impl Drop for ControlPlane {
177    fn drop(&mut self) {
178        self.stop.cancel();
179        for task in &self.tasks {
180            task.abort();
181        }
182        if let Some(path) = self.socket.take()
183            && let Err(error) = remove_socket(&path)
184        {
185            tracing::warn!(error = %error, socket.path = %path.display(), "could not remove the kernel socket");
186        }
187        // Kept when anything besides the socket is in it.
188        if let Some(dir) = self.socket_dir.take()
189            && let Err(error) = std::fs::remove_dir(&dir)
190        {
191            tracing::debug!(error = %error, socket.dir = %dir.display(), "kept the kernel socket directory");
192        }
193    }
194}
195
196fn remove_socket(path: &Path) -> Result<()> {
197    match std::fs::remove_file(path) {
198        Ok(()) => Ok(()),
199        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
200        Err(error) => Err(error.into()),
201    }
202}
203
204/// The kernel routes under `/api`, with the approvals inbox when the backend has an
205/// approval service, its decisions checked by the kernel's decide guard.
206pub(super) fn api(backend: &Arc<dyn ControlBackend>) -> Router {
207    let mut routes = routes(backend.clone());
208    if let Some(service) = backend.approvals() {
209        // Each decision is answered under spec 3.3 §7.2 for the surface this transport is.
210        let guard = Arc::new(super::decide::KernelDecideGuard::new(backend.clone()));
211        let endpoints = ApprovalEndpoints::new(service.clone()).with_decide_guard(guard);
212        routes = routes.merge(approvals_router(endpoints));
213    }
214    Router::new().nest(paths::API_PREFIX, routes)
215}
216
217/// The OS user the kernel runs as, the subject of the socket and of loopback peers.
218pub(crate) fn os_user() -> String {
219    ["USER", "USERNAME"]
220        .into_iter()
221        .filter_map(|name| std::env::var(name).ok())
222        .find(|user| !user.trim().is_empty())
223        .unwrap_or_else(|| "user".to_string())
224}
225
226pub(super) fn operator(user_id: &str) -> RequestContext {
227    RequestContext {
228        user_id: user_id.to_string(),
229        scopes: vec![OPERATOR_SCOPE.to_string()],
230        metadata: HashMap::new(),
231    }
232}
233
234/// Marks a request authenticated as `context` over `transport`, as the server's auth
235/// middleware marks one, and runs it.
236pub(super) async fn admit(
237    mut request: Request<Body>,
238    next: Next,
239    context: RequestContext,
240    transport: ControlTransport,
241) -> Response {
242    request.extensions_mut().insert(Some(context));
243    request.extensions_mut().insert(transport);
244    next.run(request).await
245}
246
247/// The uid of a socket peer, and its process when the OS says, from its credentials.
248#[cfg(unix)]
249#[derive(Debug, Clone, Copy)]
250struct PeerUid(Option<u32>, Option<u32>);
251
252/// The process that sent a request on the socket, when the OS says (spec 3.3 §5.2): the
253/// command routes record it.
254#[derive(Debug, Clone, Copy)]
255pub(super) struct PeerProcess(pub(super) u32);
256
257#[cfg(unix)]
258impl
259    axum::extract::connect_info::Connected<
260        axum::serve::IncomingStream<'_, tokio::net::UnixListener>,
261    > for PeerUid
262{
263    fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
264        let credentials = stream.io().peer_cred().ok();
265        let pid = credentials.and_then(|credentials| credentials.pid());
266        Self(
267            credentials.map(|credentials| credentials.uid()),
268            pid.and_then(|pid| u32::try_from(pid).ok()),
269        )
270    }
271}
272
273/// The subject of a socket peer of uid `peer` on a socket `owner` owns: the OS user `user`
274/// with the `operator` scope when the uids match, else refused.
275#[cfg(unix)]
276pub(crate) fn socket_subject(peer: Option<u32>, owner: u32, user: &str) -> Result<RequestContext> {
277    match peer {
278        Some(uid) if uid == owner => Ok(operator(user)),
279        _ => Err(KernelError::Unauthorized {
280            reason: "the kernel socket admits only the OS user that runs the kernel".into(),
281        }),
282    }
283}
284
285/// Serves `api` on a socket at `path`, created owner-only, admitting peers of its owner's
286/// uid as the OS user. `configured` is the path under the kernel home; a `path` other than it
287/// stands in for one too long for a socket, in a directory of its own (spec 3.3 G18).
288#[cfg(unix)]
289async fn serve_socket(
290    path: &Path,
291    configured: &Path,
292    api: Router,
293    stop: CancellationToken,
294) -> Result<JoinHandle<()>> {
295    use std::os::unix::fs::{MetadataExt, PermissionsExt};
296
297    if !super::socket::fits(path) {
298        return Err(KernelError::ControlPlane {
299            reason: format!(
300                "the kernel socket path {} is {} bytes and its short stand-in {} is {} bytes, \
301                 both over the {max}-byte limit of a Unix socket path on this system; start the \
302                 kernel with a shorter --home (or socket name), so the socket path in the home \
303                 is at most {max} bytes",
304                configured.display(),
305                configured.as_os_str().len(),
306                path.display(),
307                path.as_os_str().len(),
308                max = super::socket::MAX_LEN,
309            ),
310        });
311    }
312    match path.parent() {
313        Some(dir) if path != configured => super::socket::prepare_dir(dir)?,
314        Some(dir) => tokio::fs::create_dir_all(dir).await?,
315        None => {}
316    }
317    prepare_socket_path(path).await?;
318    let listener =
319        tokio::net::UnixListener::bind(path).map_err(|error| KernelError::ControlPlane {
320            reason: format!("could not listen on {}: {error}", path.display()),
321        })?;
322    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
323    // The kernel created the socket, so its owner is the uid the kernel runs as.
324    let owner = std::fs::metadata(path)?.uid();
325    let user = os_user();
326    let app = api.layer(middleware::from_fn(move |mut request: Request<Body>, next: Next| {
327        let user = user.clone();
328        async move {
329            let (peer, pid) = request
330                .extensions()
331                .get::<ConnectInfo<PeerUid>>()
332                .map_or((None, None), |ConnectInfo(PeerUid(uid, pid))| (*uid, *pid));
333            if let Some(pid) = pid {
334                request.extensions_mut().insert(PeerProcess(pid));
335            }
336            match socket_subject(peer, owner, &user) {
337                Ok(context) => admit(request, next, context, ControlTransport::Socket).await,
338                Err(error) => error.into_response(),
339            }
340        }
341    }));
342    let service = app.into_make_service_with_connect_info::<PeerUid>();
343    Ok(tokio::spawn(async move {
344        if let Err(error) =
345            axum::serve(listener, service).with_graceful_shutdown(stop.cancelled_owned()).await
346        {
347            tracing::error!(error = %error, "the kernel control socket stopped");
348        }
349    }))
350}
351
352/// Clears a stale socket left by a kernel that did not stop cleanly, and refuses a path
353/// another kernel answers on or that is not a socket.
354#[cfg(unix)]
355async fn prepare_socket_path(path: &Path) -> Result<()> {
356    use std::os::unix::fs::FileTypeExt;
357
358    let metadata = match tokio::fs::symlink_metadata(path).await {
359        Ok(metadata) => metadata,
360        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
361        Err(error) => return Err(error.into()),
362    };
363    if !metadata.file_type().is_socket() {
364        return Err(KernelError::ControlPlane {
365            reason: format!(
366                "{} exists and is not a socket; move it away, or give the kernel another home",
367                path.display()
368            ),
369        });
370    }
371    match tokio::net::UnixStream::connect(path).await {
372        Ok(_) => Err(KernelError::ControlPlane {
373            reason: format!(
374                "a kernel already listens on {}: attach to it with `adk-rust attach`, or stop \
375                 it before starting another with the same home",
376                path.display()
377            ),
378        }),
379        Err(error)
380            if matches!(
381                error.kind(),
382                std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
383            ) =>
384        {
385            tracing::info!(socket.path = %path.display(), "removing a stale kernel socket");
386            remove_socket(path)
387        }
388        Err(error) => Err(KernelError::ControlPlane {
389            reason: format!("could not check the kernel socket {}: {error}", path.display()),
390        }),
391    }
392}
393
394#[cfg(not(any(unix, windows)))]
395async fn serve_socket(
396    path: &Path,
397    _configured: &Path,
398    _api: Router,
399    _stop: CancellationToken,
400) -> Result<JoinHandle<()>> {
401    Err(KernelError::ControlPlane {
402        reason: format!(
403            "the local control socket {} needs Unix sockets or Windows named pipes. Serve the \
404             control plane over HTTP without a socket (ControlPlaneConfig::without_socket and \
405             with_http, or `adk-rust up --bind`)",
406            path.display()
407        ),
408    })
409}
410
411/// Serves `api` over HTTP on `addr`, authenticating with `extractor`, or admitting loopback
412/// peers as the OS user when there is none (a non-loopback bind without one never gets
413/// here: `ControlPlaneConfig::validate` refuses it). A request carrying a paired device's
414/// token is that device whatever else would admit it (spec 3.3 §10 K2), and the pairing
415/// claim route needs no caller.
416async fn serve_http(
417    addr: SocketAddr,
418    api: Router,
419    backend: &Arc<dyn ControlBackend>,
420    extractor: Option<Arc<dyn RequestContextExtractor>>,
421    stop: CancellationToken,
422) -> Result<(SocketAddr, JoinHandle<()>)> {
423    let listener = tokio::net::TcpListener::bind(addr).await.map_err(|error| {
424        KernelError::ControlPlane { reason: format!("could not listen on {addr}: {error}") }
425    })?;
426    let local = listener.local_addr()?;
427    let user = os_user();
428    let devices = backend.clone();
429    let app = api.layer(middleware::from_fn(move |request: Request<Body>, next: Next| {
430        let extractor = extractor.clone();
431        let user = user.clone();
432        let backend = devices.clone();
433        async move {
434            let (parts, body) = request.into_parts();
435            if let Some(pairing) = backend.pairing()
436                && let Some(token) = crate::pairing::device_token(&parts.headers)
437            {
438                let (token, path) = (token.to_string(), parts.uri.path().to_string());
439                let (request, answer) =
440                    match super::pairing::read_answer(Request::from_parts(parts, body)).await {
441                        Ok(read) => read,
442                        Err(response) => return response,
443                    };
444                let (parts, body) = request.into_parts();
445                return match super::pairing::admit_device(
446                    backend.as_ref(),
447                    &pairing,
448                    &token,
449                    &parts.method,
450                    &path,
451                    answer.as_deref(),
452                )
453                .await
454                {
455                    Ok(context) => {
456                        let request = Request::from_parts(parts, body);
457                        admit(request, next, context, ControlTransport::Http).await
458                    }
459                    Err(response) => response,
460                };
461            }
462            let context = match &extractor {
463                Some(extractor) => match extractor.extract(&parts).await {
464                    Ok(context) => context,
465                    Err(error @ RequestContextError::ExtractionFailed(_)) => {
466                        return KernelError::ControlPlane { reason: error.to_string() }
467                            .into_response();
468                    }
469                    Err(error) => {
470                        return KernelError::Unauthorized { reason: error.to_string() }
471                            .into_response();
472                    }
473                },
474                None => {
475                    let loopback = parts
476                        .extensions
477                        .get::<ConnectInfo<SocketAddr>>()
478                        .is_some_and(|ConnectInfo(peer)| peer.ip().is_loopback());
479                    if !loopback {
480                        return KernelError::Unauthorized {
481                            reason: "only loopback peers are admitted without a bearer token \
482                                     or SSO"
483                                .into(),
484                        }
485                        .into_response();
486                    }
487                    operator(&user)
488                }
489            };
490            admit(Request::from_parts(parts, body), next, context, ControlTransport::Http).await
491        }
492    }));
493    let app = match backend.pairing() {
494        Some(_) => app.merge(super::pairing::claim_routes(backend.clone())),
495        None => app,
496    };
497    let service = app.into_make_service_with_connect_info::<SocketAddr>();
498    let task = tokio::spawn(async move {
499        if let Err(error) =
500            axum::serve(listener, service).with_graceful_shutdown(stop.cancelled_owned()).await
501        {
502            tracing::error!(error = %error, "the kernel control plane's HTTP listener stopped");
503        }
504    });
505    Ok((local, task))
506}