use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use adk_core::RequestContext;
use adk_server::approvals::{ApprovalEndpoints, approvals_router};
use adk_server::auth_bridge::{RequestContextError, RequestContextExtractor};
use axum::Router;
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::Request;
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use super::routes::{ControlBackend, OPERATOR_SCOPE, routes};
use super::{ControlPlaneConfig, ControlTransport, paths};
use crate::error::{KernelError, Result};
use crate::kernel::Kernel;
const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
pub struct ControlPlane {
socket: Option<PathBuf>,
socket_dir: Option<PathBuf>,
pipe: Option<String>,
http: Option<SocketAddr>,
tasks: Vec<JoinHandle<()>>,
stop: CancellationToken,
}
impl fmt::Debug for ControlPlane {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ControlPlane")
.field("socket", &self.socket)
.field("pipe", &self.pipe)
.field("http", &self.http)
.finish_non_exhaustive()
}
}
impl ControlPlane {
pub async fn start(kernel: &Kernel) -> Result<Self> {
let config = kernel.config();
Self::serve(Arc::new(kernel.clone()), &config.control, &config.home).await
}
pub(crate) async fn serve(
backend: Arc<dyn ControlBackend>,
config: &ControlPlaneConfig,
home: &Path,
) -> Result<Self> {
config.validate()?;
let mut plane = Self {
socket: None,
socket_dir: None,
pipe: None,
http: None,
tasks: Vec::new(),
stop: CancellationToken::new(),
};
let api = api(&backend);
#[cfg(windows)]
if let Some(name) = config.pipe_name(home) {
plane.tasks.push(super::pipe::serve(&name, api.clone(), plane.stop.clone()).await?);
plane.pipe = Some(name);
}
#[cfg(not(windows))]
if let (Some(socket), Some(path)) = (&config.socket, config.socket_path(home)) {
let configured = home.join(socket);
plane
.tasks
.push(serve_socket(&path, &configured, api.clone(), plane.stop.clone()).await?);
if path != configured {
plane.socket_dir = path.parent().map(Path::to_path_buf);
}
plane.socket = Some(path);
}
if let Some(addr) = config.http {
let (local, task) =
serve_http(addr, api, &backend, config.extractor.clone(), plane.stop.clone())
.await?;
plane.tasks.push(task);
plane.http = Some(local);
}
tracing::info!(
control.socket = ?plane.socket,
control.pipe = ?plane.pipe,
control.http = ?plane.http,
"kernel control plane listening"
);
Ok(plane)
}
pub fn socket_path(&self) -> Option<&Path> {
self.socket.as_deref()
}
pub fn pipe_name(&self) -> Option<&str> {
self.pipe.as_deref()
}
pub fn http_addr(&self) -> Option<SocketAddr> {
self.http
}
pub async fn shutdown(mut self) -> Result<()> {
self.stop.cancel();
for task in std::mem::take(&mut self.tasks) {
let abort = task.abort_handle();
if tokio::time::timeout(SHUTDOWN_GRACE, task).await.is_err() {
abort.abort();
}
}
match self.socket.take() {
Some(path) => remove_socket(&path),
None => Ok(()),
}
}
}
impl Drop for ControlPlane {
fn drop(&mut self) {
self.stop.cancel();
for task in &self.tasks {
task.abort();
}
if let Some(path) = self.socket.take()
&& let Err(error) = remove_socket(&path)
{
tracing::warn!(error = %error, socket.path = %path.display(), "could not remove the kernel socket");
}
if let Some(dir) = self.socket_dir.take()
&& let Err(error) = std::fs::remove_dir(&dir)
{
tracing::debug!(error = %error, socket.dir = %dir.display(), "kept the kernel socket directory");
}
}
}
fn remove_socket(path: &Path) -> Result<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
pub(super) fn api(backend: &Arc<dyn ControlBackend>) -> Router {
let mut routes = routes(backend.clone());
if let Some(service) = backend.approvals() {
let guard = Arc::new(super::decide::KernelDecideGuard::new(backend.clone()));
let endpoints = ApprovalEndpoints::new(service.clone()).with_decide_guard(guard);
routes = routes.merge(approvals_router(endpoints));
}
Router::new().nest(paths::API_PREFIX, routes)
}
pub(crate) fn os_user() -> String {
["USER", "USERNAME"]
.into_iter()
.filter_map(|name| std::env::var(name).ok())
.find(|user| !user.trim().is_empty())
.unwrap_or_else(|| "user".to_string())
}
pub(super) fn operator(user_id: &str) -> RequestContext {
RequestContext {
user_id: user_id.to_string(),
scopes: vec![OPERATOR_SCOPE.to_string()],
metadata: HashMap::new(),
}
}
pub(super) async fn admit(
mut request: Request<Body>,
next: Next,
context: RequestContext,
transport: ControlTransport,
) -> Response {
request.extensions_mut().insert(Some(context));
request.extensions_mut().insert(transport);
next.run(request).await
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
struct PeerUid(Option<u32>, Option<u32>);
#[derive(Debug, Clone, Copy)]
pub(super) struct PeerProcess(pub(super) u32);
#[cfg(unix)]
impl
axum::extract::connect_info::Connected<
axum::serve::IncomingStream<'_, tokio::net::UnixListener>,
> for PeerUid
{
fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
let credentials = stream.io().peer_cred().ok();
let pid = credentials.and_then(|credentials| credentials.pid());
Self(
credentials.map(|credentials| credentials.uid()),
pid.and_then(|pid| u32::try_from(pid).ok()),
)
}
}
#[cfg(unix)]
pub(crate) fn socket_subject(peer: Option<u32>, owner: u32, user: &str) -> Result<RequestContext> {
match peer {
Some(uid) if uid == owner => Ok(operator(user)),
_ => Err(KernelError::Unauthorized {
reason: "the kernel socket admits only the OS user that runs the kernel".into(),
}),
}
}
#[cfg(unix)]
async fn serve_socket(
path: &Path,
configured: &Path,
api: Router,
stop: CancellationToken,
) -> Result<JoinHandle<()>> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
if !super::socket::fits(path) {
return Err(KernelError::ControlPlane {
reason: format!(
"the kernel socket path {} is {} bytes and its short stand-in {} is {} bytes, \
both over the {max}-byte limit of a Unix socket path on this system; start the \
kernel with a shorter --home (or socket name), so the socket path in the home \
is at most {max} bytes",
configured.display(),
configured.as_os_str().len(),
path.display(),
path.as_os_str().len(),
max = super::socket::MAX_LEN,
),
});
}
match path.parent() {
Some(dir) if path != configured => super::socket::prepare_dir(dir)?,
Some(dir) => tokio::fs::create_dir_all(dir).await?,
None => {}
}
prepare_socket_path(path).await?;
let listener =
tokio::net::UnixListener::bind(path).map_err(|error| KernelError::ControlPlane {
reason: format!("could not listen on {}: {error}", path.display()),
})?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
let owner = std::fs::metadata(path)?.uid();
let user = os_user();
let app = api.layer(middleware::from_fn(move |mut request: Request<Body>, next: Next| {
let user = user.clone();
async move {
let (peer, pid) = request
.extensions()
.get::<ConnectInfo<PeerUid>>()
.map_or((None, None), |ConnectInfo(PeerUid(uid, pid))| (*uid, *pid));
if let Some(pid) = pid {
request.extensions_mut().insert(PeerProcess(pid));
}
match socket_subject(peer, owner, &user) {
Ok(context) => admit(request, next, context, ControlTransport::Socket).await,
Err(error) => error.into_response(),
}
}
}));
let service = app.into_make_service_with_connect_info::<PeerUid>();
Ok(tokio::spawn(async move {
if let Err(error) =
axum::serve(listener, service).with_graceful_shutdown(stop.cancelled_owned()).await
{
tracing::error!(error = %error, "the kernel control socket stopped");
}
}))
}
#[cfg(unix)]
async fn prepare_socket_path(path: &Path) -> Result<()> {
use std::os::unix::fs::FileTypeExt;
let metadata = match tokio::fs::symlink_metadata(path).await {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
};
if !metadata.file_type().is_socket() {
return Err(KernelError::ControlPlane {
reason: format!(
"{} exists and is not a socket; move it away, or give the kernel another home",
path.display()
),
});
}
match tokio::net::UnixStream::connect(path).await {
Ok(_) => Err(KernelError::ControlPlane {
reason: format!(
"a kernel already listens on {}: attach to it with `adk-rust attach`, or stop \
it before starting another with the same home",
path.display()
),
}),
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
) =>
{
tracing::info!(socket.path = %path.display(), "removing a stale kernel socket");
remove_socket(path)
}
Err(error) => Err(KernelError::ControlPlane {
reason: format!("could not check the kernel socket {}: {error}", path.display()),
}),
}
}
#[cfg(not(any(unix, windows)))]
async fn serve_socket(
path: &Path,
_configured: &Path,
_api: Router,
_stop: CancellationToken,
) -> Result<JoinHandle<()>> {
Err(KernelError::ControlPlane {
reason: format!(
"the local control socket {} needs Unix sockets or Windows named pipes. Serve the \
control plane over HTTP without a socket (ControlPlaneConfig::without_socket and \
with_http, or `adk-rust up --bind`)",
path.display()
),
})
}
async fn serve_http(
addr: SocketAddr,
api: Router,
backend: &Arc<dyn ControlBackend>,
extractor: Option<Arc<dyn RequestContextExtractor>>,
stop: CancellationToken,
) -> Result<(SocketAddr, JoinHandle<()>)> {
let listener = tokio::net::TcpListener::bind(addr).await.map_err(|error| {
KernelError::ControlPlane { reason: format!("could not listen on {addr}: {error}") }
})?;
let local = listener.local_addr()?;
let user = os_user();
let devices = backend.clone();
let app = api.layer(middleware::from_fn(move |request: Request<Body>, next: Next| {
let extractor = extractor.clone();
let user = user.clone();
let backend = devices.clone();
async move {
let (parts, body) = request.into_parts();
if let Some(pairing) = backend.pairing()
&& let Some(token) = crate::pairing::device_token(&parts.headers)
{
let (token, path) = (token.to_string(), parts.uri.path().to_string());
let (request, answer) =
match super::pairing::read_answer(Request::from_parts(parts, body)).await {
Ok(read) => read,
Err(response) => return response,
};
let (parts, body) = request.into_parts();
return match super::pairing::admit_device(
backend.as_ref(),
&pairing,
&token,
&parts.method,
&path,
answer.as_deref(),
)
.await
{
Ok(context) => {
let request = Request::from_parts(parts, body);
admit(request, next, context, ControlTransport::Http).await
}
Err(response) => response,
};
}
let context = match &extractor {
Some(extractor) => match extractor.extract(&parts).await {
Ok(context) => context,
Err(error @ RequestContextError::ExtractionFailed(_)) => {
return KernelError::ControlPlane { reason: error.to_string() }
.into_response();
}
Err(error) => {
return KernelError::Unauthorized { reason: error.to_string() }
.into_response();
}
},
None => {
let loopback = parts
.extensions
.get::<ConnectInfo<SocketAddr>>()
.is_some_and(|ConnectInfo(peer)| peer.ip().is_loopback());
if !loopback {
return KernelError::Unauthorized {
reason: "only loopback peers are admitted without a bearer token \
or SSO"
.into(),
}
.into_response();
}
operator(&user)
}
};
admit(Request::from_parts(parts, body), next, context, ControlTransport::Http).await
}
}));
let app = match backend.pairing() {
Some(_) => app.merge(super::pairing::claim_routes(backend.clone())),
None => app,
};
let service = app.into_make_service_with_connect_info::<SocketAddr>();
let task = tokio::spawn(async move {
if let Err(error) =
axum::serve(listener, service).with_graceful_shutdown(stop.cancelled_owned()).await
{
tracing::error!(error = %error, "the kernel control plane's HTTP listener stopped");
}
});
Ok((local, task))
}