1use 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
27const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
30
31pub struct ControlPlane {
59 socket: Option<PathBuf>,
60 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 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 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 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 pub fn socket_path(&self) -> Option<&Path> {
142 self.socket.as_deref()
143 }
144
145 pub fn pipe_name(&self) -> Option<&str> {
147 self.pipe.as_deref()
148 }
149
150 pub fn http_addr(&self) -> Option<SocketAddr> {
153 self.http
154 }
155
156 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 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
204pub(super) fn api(backend: &Arc<dyn ControlBackend>) -> Router {
207 let mut routes = routes(backend.clone());
208 if let Some(service) = backend.approvals() {
209 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
217pub(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
234pub(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#[cfg(unix)]
249#[derive(Debug, Clone, Copy)]
250struct PeerUid(Option<u32>, Option<u32>);
251
252#[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#[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#[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 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#[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
411async 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}