feat(maestro): registry HTTP API, cookie auth, JWT issuance, events WS
ci / rust (push) Successful in 48s
ci / rust (push) Successful in 48s
Adds the client-facing surface on the registry (NAP-215). Endpoints:
- GET /api/daemons — list connected daemons (with daemon_url)
- GET /api/sessions — flat session catalog
- POST /api/sessions — forwards CreateSession to chosen daemon, 504 on
10s daemon timeout
- DELETE /api/sessions/:id — forwards KillSession
- GET /api/sessions/:id/connect-info — returns {daemon_url, jwt} with a
5min HS256-signed attach JWT
- WS /api/events — snapshot + delta broadcast of catalog and presence
- GET / placeholder served until NAP-218 web bundle lands
Cookie auth middleware mints a long-lived httpOnly JWT cookie on first
request and reissues silently on missing/tampered cookies. Per spec the
perimeter is the operator's network — the cookie is a second factor.
Protocol additions: daemon_url on Hello, DaemonInfo, ConnectInfo,
RegistryEvent. Daemon config + RegistryClient now carry daemon_url.
Registry state now exposes an event broadcast channel (subscribe gives
a snapshot + tokio::sync::broadcast::Receiver) and helper lookups
daemon_for_session / daemon_url.
Tests: 11 reqwest-driven HTTP integration tests cover every endpoint,
the cookie flow, 504 timeout path, worktree forwarding, and events WS
propagation.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
//! Cookie-based auth for the client-facing HTTP/WS surface.
|
||||
//!
|
||||
//! On the first request the registry sets an httpOnly cookie whose value is a
|
||||
//! JWT signed with the shared `MAESTRO_TOKEN` (HS256). Subsequent requests
|
||||
//! must present a cookie whose signature verifies; missing or tampered
|
||||
//! cookies get a fresh cookie issued (effectively re-bootstrapping a
|
||||
//! first-time client) and are still allowed through. The cookie is the second
|
||||
//! factor against anyone routing to the bind address; per spec §Auth the
|
||||
//! perimeter is the operator's network.
|
||||
//!
|
||||
//! Implementation notes:
|
||||
//!
|
||||
//! - We reuse `jsonwebtoken` so we don't pull in a cookie/HMAC crate just for
|
||||
//! this one signature.
|
||||
//! - The middleware passes the inbound `Cookie` header through to the inner
|
||||
//! handler unchanged, and adds a `Set-Cookie` response header if the inbound
|
||||
//! cookie was missing or invalid.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::State;
|
||||
use axum::http::{header, HeaderValue, Request, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use chrono::{Duration, Utc};
|
||||
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Name of the auth cookie surfaced to web clients.
|
||||
pub const COOKIE_NAME: &str = "maestro_session";
|
||||
|
||||
/// 30 days. Cookie is the second factor — long enough not to log users out;
|
||||
/// short enough to bound the blast radius if the secret rotates.
|
||||
const COOKIE_TTL_DAYS: i64 = 30;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct CookieClaims {
|
||||
/// Subject — currently always `"client"` because this is single-user.
|
||||
sub: String,
|
||||
exp: i64,
|
||||
iat: i64,
|
||||
}
|
||||
|
||||
/// Issue a fresh cookie value (a JWT) signed with `secret`.
|
||||
pub fn issue_cookie(secret: &str) -> String {
|
||||
let now = Utc::now();
|
||||
let claims = CookieClaims {
|
||||
sub: "client".into(),
|
||||
iat: now.timestamp(),
|
||||
exp: (now + Duration::days(COOKIE_TTL_DAYS)).timestamp(),
|
||||
};
|
||||
let header = Header::new(Algorithm::HS256);
|
||||
let key = EncodingKey::from_secret(secret.as_bytes());
|
||||
encode(&header, &claims, &key).expect("encode auth cookie")
|
||||
}
|
||||
|
||||
/// Returns true if `value` is a JWT validly signed by `secret`.
|
||||
pub fn verify_cookie(secret: &str, value: &str) -> bool {
|
||||
let key = DecodingKey::from_secret(secret.as_bytes());
|
||||
let validation = Validation::new(Algorithm::HS256);
|
||||
decode::<CookieClaims>(value, &key, &validation).is_ok()
|
||||
}
|
||||
|
||||
/// Format the full `Set-Cookie` header value.
|
||||
fn set_cookie_header(value: &str) -> String {
|
||||
format!(
|
||||
"{name}={value}; HttpOnly; SameSite=Strict; Path=/; Max-Age={age}",
|
||||
name = COOKIE_NAME,
|
||||
age = COOKIE_TTL_DAYS * 24 * 60 * 60,
|
||||
)
|
||||
}
|
||||
|
||||
/// Find our cookie inside an inbound `Cookie:` header. Header may contain
|
||||
/// many `name=value` pairs separated by `;`.
|
||||
pub fn extract_cookie<'a>(header_value: &'a str, name: &str) -> Option<&'a str> {
|
||||
for part in header_value.split(';') {
|
||||
let part = part.trim();
|
||||
if let Some(eq) = part.find('=') {
|
||||
let (k, v) = part.split_at(eq);
|
||||
if k == name {
|
||||
return Some(&v[1..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Shared state for the auth middleware: just the signing secret.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthState {
|
||||
pub token: Arc<String>,
|
||||
}
|
||||
|
||||
/// Axum middleware that enforces / bootstraps the client auth cookie.
|
||||
///
|
||||
/// - Valid cookie present → pass through, no `Set-Cookie`.
|
||||
/// - Cookie missing → issue a fresh one and pass through.
|
||||
/// - Cookie present but tampered/expired → issue a fresh one and pass through.
|
||||
/// (Spec is intentionally lenient — perimeter is the operator's network.)
|
||||
pub async fn cookie_middleware(
|
||||
State(state): State<AuthState>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let token = state.token.clone();
|
||||
let inbound_cookie = request
|
||||
.headers()
|
||||
.get(header::COOKIE)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.and_then(|v| extract_cookie(v, COOKIE_NAME).map(|s| s.to_string()));
|
||||
|
||||
let needs_new_cookie = match &inbound_cookie {
|
||||
Some(value) => !verify_cookie(token.as_str(), value),
|
||||
None => true,
|
||||
};
|
||||
|
||||
let mut response = next.run(request).await;
|
||||
|
||||
if needs_new_cookie {
|
||||
let fresh = issue_cookie(token.as_str());
|
||||
match HeaderValue::from_str(&set_cookie_header(&fresh)) {
|
||||
Ok(hv) => {
|
||||
response.headers_mut().append(header::SET_COOKIE, hv);
|
||||
}
|
||||
Err(_) => {
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, "cookie encode failed").into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trip() {
|
||||
let token = "shared-secret-aaaa";
|
||||
let value = issue_cookie(token);
|
||||
assert!(verify_cookie(token, &value));
|
||||
assert!(!verify_cookie("different-secret", &value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_cookie_finds_named_value() {
|
||||
let h = "foo=1; maestro_session=abc.def.ghi; bar=2";
|
||||
assert_eq!(extract_cookie(h, "maestro_session"), Some("abc.def.ghi"));
|
||||
assert_eq!(extract_cookie(h, "foo"), Some("1"));
|
||||
assert_eq!(extract_cookie(h, "missing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cookie_header_includes_attributes() {
|
||||
let h = set_cookie_header("abc");
|
||||
assert!(h.contains("HttpOnly"));
|
||||
assert!(h.contains("SameSite=Strict"));
|
||||
assert!(h.contains("Path=/"));
|
||||
assert!(h.starts_with("maestro_session=abc;"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Client-facing HTTP API routes (NAP-215).
|
||||
//!
|
||||
//! Mounts under the same router as the daemon-facing `WS /daemon`. The cookie
|
||||
//! middleware in [`crate::auth`] gates everything except the WS upgrade for
|
||||
//! `/daemon` (daemons authenticate via the shared token in `Hello`).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{ws::WebSocketUpgrade, Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{any, get};
|
||||
use axum::{Json, Router};
|
||||
use maestro_protocol::{ConnectInfo, CreateSessionRequest, DaemonInfo, Session};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::events::events_ws;
|
||||
use crate::jwt::issue_attach_jwt;
|
||||
use crate::state::{Registry, RegistryError, RPC_TIMEOUT};
|
||||
|
||||
/// Shared state plumbed into client-facing handlers.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClientApiState {
|
||||
pub registry: Registry,
|
||||
pub token: Arc<String>,
|
||||
pub rpc_timeout: Duration,
|
||||
}
|
||||
|
||||
/// Mount client-facing routes on the given router. Caller is responsible for
|
||||
/// applying the cookie middleware (we do that in [`crate::server::router`]).
|
||||
pub fn routes(state: ClientApiState) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/api/daemons", get(list_daemons))
|
||||
.route("/api/sessions", get(list_sessions).post(create_session))
|
||||
.route("/api/sessions/:id", axum::routing::delete(delete_session))
|
||||
.route("/api/sessions/:id/connect-info", get(session_connect_info))
|
||||
.route("/api/events", any(events_ws_handler))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn index() -> impl IntoResponse {
|
||||
// Placeholder until the real web bundle lands in NAP-218.
|
||||
(
|
||||
[("content-type", "text/html; charset=utf-8")],
|
||||
"<!doctype html><title>maestro</title><h1>maestro registry</h1>\
|
||||
<p>The web client is not bundled yet — see NAP-218.</p>",
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_daemons(State(s): State<ClientApiState>) -> Json<Vec<DaemonInfo>> {
|
||||
let infos: Vec<DaemonInfo> = s
|
||||
.registry
|
||||
.daemons()
|
||||
.await
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
Json(infos)
|
||||
}
|
||||
|
||||
async fn list_sessions(State(s): State<ClientApiState>) -> Json<Vec<Session>> {
|
||||
Json(s.registry.sessions().await)
|
||||
}
|
||||
|
||||
async fn create_session(
|
||||
State(s): State<ClientApiState>,
|
||||
Json(body): Json<CreateSessionRequest>,
|
||||
) -> Response {
|
||||
let daemon = body.daemon_id.clone();
|
||||
let outcome =
|
||||
tokio::time::timeout(s.rpc_timeout, s.registry.create_session(&daemon, body)).await;
|
||||
match outcome {
|
||||
Err(_) => (
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
Json(error_body("timeout", "daemon did not reply in time")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(RegistryError::DaemonNotConnected(_))) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(error_body("unknown_daemon", "daemon is not connected")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(RegistryError::Timeout(_))) => (
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
Json(error_body("timeout", "daemon did not reply in time")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(e)) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(error_body("transport", &e.to_string())),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Ok(Err(rpc_err))) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(error_body(&rpc_err.0.code, &rpc_err.0.message)),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Ok(Ok(session))) => (StatusCode::CREATED, Json(session)).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn delete_session(State(s): State<ClientApiState>, Path(id): Path<Uuid>) -> Response {
|
||||
let Some(daemon) = s.registry.daemon_for_session(id).await else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(error_body("unknown_session", "no such session")),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
|
||||
let outcome = tokio::time::timeout(s.rpc_timeout, s.registry.kill_session(&daemon, id)).await;
|
||||
match outcome {
|
||||
Err(_) => (
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
Json(error_body("timeout", "daemon did not reply in time")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(RegistryError::DaemonNotConnected(_))) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(error_body("unknown_daemon", "daemon is not connected")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(RegistryError::Timeout(_))) => (
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
Json(error_body("timeout", "daemon did not reply in time")),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Err(e)) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(error_body("transport", &e.to_string())),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Ok(Err(rpc_err))) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(error_body(&rpc_err.0.code, &rpc_err.0.message)),
|
||||
)
|
||||
.into_response(),
|
||||
Ok(Ok(Ok(()))) => StatusCode::NO_CONTENT.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn session_connect_info(State(s): State<ClientApiState>, Path(id): Path<Uuid>) -> Response {
|
||||
let Some(daemon) = s.registry.daemon_for_session(id).await else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(error_body("unknown_session", "no such session")),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
let Some(daemon_url) = s.registry.daemon_url(&daemon).await else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(error_body("unknown_daemon", "owning daemon is offline")),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
let jwt = match issue_attach_jwt(s.token.as_str(), &daemon, id) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(error_body("jwt_failed", &e.to_string())),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
Json(ConnectInfo { daemon_url, jwt }).into_response()
|
||||
}
|
||||
|
||||
async fn events_ws_handler(
|
||||
State(s): State<ClientApiState>,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> impl IntoResponse {
|
||||
let registry = s.registry.clone();
|
||||
ws.on_upgrade(move |socket| async move {
|
||||
let _ = events_ws(socket, registry).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn error_body(code: &str, message: &str) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Convenience: produce a `ClientApiState` from a `Registry` and shared token.
|
||||
/// Uses the production [`RPC_TIMEOUT`].
|
||||
pub fn state_for(registry: Registry, token: String) -> ClientApiState {
|
||||
ClientApiState {
|
||||
registry,
|
||||
token: Arc::new(token),
|
||||
rpc_timeout: RPC_TIMEOUT,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! `WS /api/events` — registry-side fan-out of catalog + presence deltas.
|
||||
//!
|
||||
//! On connect we immediately push a [`RegistryEvent::Snapshot`] of the current
|
||||
//! state, then forward every broadcast event until the client disconnects.
|
||||
//! Lagged subscribers receive a [`RegistryEvent::Lagged`] notice with the
|
||||
//! count of dropped frames — the convention is for the client to re-fetch
|
||||
//! `GET /api/sessions` on receipt.
|
||||
|
||||
use axum::extract::ws::{Message, WebSocket};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use maestro_protocol::RegistryEvent;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
|
||||
use crate::state::Registry;
|
||||
|
||||
pub async fn events_ws(socket: WebSocket, registry: Registry) -> Result<(), axum::Error> {
|
||||
let (mut sink, mut stream) = socket.split();
|
||||
|
||||
let (snapshot, mut rx) = registry.subscribe().await;
|
||||
sink.send(Message::Text(
|
||||
serde_json::to_string(&snapshot).expect("snapshot"),
|
||||
))
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
ev = rx.recv() => {
|
||||
match ev {
|
||||
Ok(event) => {
|
||||
let text = serde_json::to_string(&event).expect("event encode");
|
||||
if sink.send(Message::Text(text)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvError::Lagged(n)) => {
|
||||
let text = serde_json::to_string(&RegistryEvent::Lagged { skipped: n })
|
||||
.expect("lagged encode");
|
||||
if sink.send(Message::Text(text)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
client_frame = stream.next() => {
|
||||
// Treat anything from the client as either a close or a ping
|
||||
// we don't care about; the events WS is server-push only.
|
||||
match client_frame {
|
||||
None => break,
|
||||
Some(Err(_)) => break,
|
||||
Some(Ok(Message::Close(_))) => break,
|
||||
Some(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -37,13 +37,14 @@ pub async fn handle_socket(
|
||||
None => return None,
|
||||
};
|
||||
|
||||
let (daemon_id, hostname, version, token) = match hello {
|
||||
let (daemon_id, hostname, version, token, daemon_url) = match hello {
|
||||
DaemonOutbound::Hello {
|
||||
daemon_id,
|
||||
hostname,
|
||||
version,
|
||||
token,
|
||||
} => (daemon_id, hostname, version, token),
|
||||
daemon_url,
|
||||
} => (daemon_id, hostname, version, token, daemon_url),
|
||||
_ => {
|
||||
let _ = send_error(&mut sink, "expected_hello", "first message must be Hello").await;
|
||||
return None;
|
||||
@@ -57,7 +58,7 @@ pub async fn handle_socket(
|
||||
|
||||
let (out_tx, mut out_rx) = mpsc::channel::<DaemonInbound>(OUTBOUND_BUFFER);
|
||||
registry
|
||||
.register(daemon_id.clone(), hostname, version, out_tx)
|
||||
.register(daemon_id.clone(), hostname, version, daemon_url, out_tx)
|
||||
.await;
|
||||
|
||||
let _ = sink
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Registry-side JWT issuance for the per-session attach endpoint.
|
||||
//!
|
||||
//! The daemon validates these tokens locally with the same shared secret —
|
||||
//! the registry doesn't see any callback on the attach hot path.
|
||||
//! Spec §Auth, §"Wire protocol (Client↔Daemon)".
|
||||
|
||||
use chrono::{Duration, Utc};
|
||||
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
|
||||
use maestro_protocol::JwtClaims;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Spec §Auth: ~5 minutes.
|
||||
pub const ATTACH_JWT_TTL: Duration = Duration::minutes(5);
|
||||
|
||||
/// Mint a short-lived attach JWT for `(daemon_id, session_id)`.
|
||||
pub fn issue_attach_jwt(
|
||||
secret: &str,
|
||||
daemon_id: &str,
|
||||
session_id: Uuid,
|
||||
) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
let now = Utc::now();
|
||||
let claims = JwtClaims {
|
||||
session_id,
|
||||
daemon_id: daemon_id.to_string(),
|
||||
exp: (now + ATTACH_JWT_TTL).timestamp(),
|
||||
iat: Some(now.timestamp()),
|
||||
};
|
||||
let header = Header::new(Algorithm::HS256);
|
||||
let key = EncodingKey::from_secret(secret.as_bytes());
|
||||
encode(&header, &claims, &key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use jsonwebtoken::{decode, DecodingKey, Validation};
|
||||
|
||||
#[test]
|
||||
fn issued_token_verifies_with_shared_secret() {
|
||||
let secret = "shared-secret";
|
||||
let daemon = "laptop";
|
||||
let session = Uuid::new_v4();
|
||||
let token = issue_attach_jwt(secret, daemon, session).unwrap();
|
||||
let decoded = decode::<JwtClaims>(
|
||||
&token,
|
||||
&DecodingKey::from_secret(secret.as_bytes()),
|
||||
&Validation::new(Algorithm::HS256),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(decoded.claims.daemon_id, daemon);
|
||||
assert_eq!(decoded.claims.session_id, session);
|
||||
assert!(decoded.claims.exp > Utc::now().timestamp());
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,28 @@
|
||||
//! The always-on Maestro registry.
|
||||
//!
|
||||
//! This crate covers the daemon-facing surface only — there is no client HTTP
|
||||
//! API in NAP-213. See `docs/superpowers/specs/2026-05-24-maestro-design.md`
|
||||
//! §Registry and §"Wire protocol (D↔R)".
|
||||
//! Covers two surfaces:
|
||||
//!
|
||||
//! - Daemon-facing `WS /daemon` (NAP-213): presence + session catalog.
|
||||
//! - Client-facing HTTP/WS API (NAP-215): list daemons/sessions, spawn/kill
|
||||
//! sessions (forwarded to the owning daemon via WS), issue per-session
|
||||
//! attach JWTs, and broadcast catalog deltas over `WS /api/events`.
|
||||
//!
|
||||
//! See `docs/superpowers/specs/2026-05-24-maestro-design.md` §Registry,
|
||||
//! §"Wire protocol", and §Auth.
|
||||
|
||||
#![deny(missing_debug_implementations)]
|
||||
|
||||
pub mod auth;
|
||||
pub mod client_api;
|
||||
pub mod events;
|
||||
pub mod handler;
|
||||
pub mod jwt;
|
||||
pub mod server;
|
||||
pub mod state;
|
||||
pub mod token;
|
||||
|
||||
pub use server::{router, router_with_timeout, RegistryServer};
|
||||
pub use auth::{issue_cookie, verify_cookie, COOKIE_NAME};
|
||||
pub use jwt::{issue_attach_jwt, ATTACH_JWT_TTL};
|
||||
pub use server::{router, router_full, router_with_timeout, RegistryServer};
|
||||
pub use state::{DaemonView, Registry, RegistryError, RpcError, HEARTBEAT_TIMEOUT, RPC_TIMEOUT};
|
||||
pub use token::{ensure_token, RegistryConfig, TokenError};
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! axum router + listener for the daemon-facing WS endpoint.
|
||||
//!
|
||||
//! The router exposes only `WS /daemon` in NAP-213. Client-facing HTTP arrives
|
||||
//! in NAP-215.
|
||||
//! axum router + listener for the registry, including both the daemon-facing
|
||||
//! `WS /daemon` endpoint (NAP-213) and the client-facing HTTP API (NAP-215).
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
@@ -11,41 +9,70 @@ use axum::extract::ws::WebSocketUpgrade;
|
||||
use axum::extract::State;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::any;
|
||||
use axum::Router;
|
||||
use axum::{middleware, Router};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use crate::auth::{cookie_middleware, AuthState};
|
||||
use crate::client_api::{routes as client_routes, ClientApiState};
|
||||
use crate::handler::handle_socket;
|
||||
use crate::state::{Registry, HEARTBEAT_TIMEOUT};
|
||||
use crate::state::{Registry, HEARTBEAT_TIMEOUT, RPC_TIMEOUT};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct AppState {
|
||||
struct DaemonAppState {
|
||||
registry: Registry,
|
||||
token: Arc<String>,
|
||||
heartbeat_timeout: Duration,
|
||||
}
|
||||
|
||||
/// Build the daemon-facing router with the production heartbeat timeout.
|
||||
/// Build the production router (daemon WS + client HTTP API) with default
|
||||
/// timeouts.
|
||||
pub fn router(registry: Registry, token: String) -> Router {
|
||||
router_with_timeout(registry, token, HEARTBEAT_TIMEOUT)
|
||||
router_full(registry, token, HEARTBEAT_TIMEOUT, RPC_TIMEOUT)
|
||||
}
|
||||
|
||||
/// Build the daemon-facing router with a custom heartbeat timeout. Mainly for
|
||||
/// integration tests that want to verify the timeout path without waiting 30s.
|
||||
/// Variant for integration tests that want a short heartbeat. Keeps the
|
||||
/// existing 4-arg call sites in `daemon_ws.rs` working.
|
||||
pub fn router_with_timeout(
|
||||
registry: Registry,
|
||||
token: String,
|
||||
heartbeat_timeout: Duration,
|
||||
) -> Router {
|
||||
Router::new()
|
||||
.route("/daemon", any(daemon_ws))
|
||||
.with_state(AppState {
|
||||
registry,
|
||||
token: Arc::new(token),
|
||||
heartbeat_timeout,
|
||||
})
|
||||
router_full(registry, token, heartbeat_timeout, RPC_TIMEOUT)
|
||||
}
|
||||
|
||||
async fn daemon_ws(State(state): State<AppState>, ws: WebSocketUpgrade) -> impl IntoResponse {
|
||||
/// Full builder; lets tests override every knob.
|
||||
pub fn router_full(
|
||||
registry: Registry,
|
||||
token: String,
|
||||
heartbeat_timeout: Duration,
|
||||
rpc_timeout: Duration,
|
||||
) -> Router {
|
||||
let token_arc = Arc::new(token.clone());
|
||||
|
||||
let daemon_router = Router::new()
|
||||
.route("/daemon", any(daemon_ws))
|
||||
.with_state(DaemonAppState {
|
||||
registry: registry.clone(),
|
||||
token: token_arc.clone(),
|
||||
heartbeat_timeout,
|
||||
});
|
||||
|
||||
let client_router = client_routes(ClientApiState {
|
||||
registry,
|
||||
token: token_arc.clone(),
|
||||
rpc_timeout,
|
||||
})
|
||||
.layer(middleware::from_fn_with_state(
|
||||
AuthState {
|
||||
token: token_arc.clone(),
|
||||
},
|
||||
cookie_middleware,
|
||||
));
|
||||
|
||||
Router::new().merge(daemon_router).merge(client_router)
|
||||
}
|
||||
|
||||
async fn daemon_ws(State(state): State<DaemonAppState>, ws: WebSocketUpgrade) -> impl IntoResponse {
|
||||
let registry = state.registry.clone();
|
||||
let token = state.token.clone();
|
||||
let timeout = state.heartbeat_timeout;
|
||||
|
||||
@@ -14,11 +14,17 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use maestro_protocol::{
|
||||
CreateSessionRequest, DaemonInbound, ErrorInfo, ReplyTo, RpcResult, Session,
|
||||
CreateSessionRequest, DaemonInbound, DaemonInfo, ErrorInfo, RegistryEvent, ReplyTo, RpcResult,
|
||||
Session,
|
||||
};
|
||||
use tokio::sync::{mpsc, oneshot, Mutex};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, Mutex};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Capacity of the registry-wide broadcast channel that feeds
|
||||
/// `WS /api/events` subscribers. Subscribers that fall this far behind get a
|
||||
/// `Lagged` event and are expected to resync via `GET /api/sessions`.
|
||||
const EVENT_CHANNEL_CAPACITY: usize = 256;
|
||||
|
||||
/// How long a daemon can go without sending us *any* message before it is
|
||||
/// considered offline and its sessions are dropped from the catalog.
|
||||
pub const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -46,18 +52,32 @@ pub enum RegistryError {
|
||||
#[error("daemon rpc failed: {0:?}")]
|
||||
pub struct RpcError(pub ErrorInfo);
|
||||
|
||||
/// Public, read-only view of a single connected daemon.
|
||||
/// Public, read-only view of a single connected daemon. Convertible to the
|
||||
/// protocol-level `DaemonInfo` for inclusion in HTTP responses and events.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DaemonView {
|
||||
pub daemon_id: String,
|
||||
pub hostname: String,
|
||||
pub version: String,
|
||||
pub daemon_url: String,
|
||||
}
|
||||
|
||||
impl From<DaemonView> for DaemonInfo {
|
||||
fn from(v: DaemonView) -> Self {
|
||||
Self {
|
||||
daemon_id: v.daemon_id,
|
||||
hostname: v.hostname,
|
||||
version: v.version,
|
||||
daemon_url: v.daemon_url,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared, cloneable registry handle.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Registry {
|
||||
inner: Arc<Mutex<State>>,
|
||||
events: broadcast::Sender<RegistryEvent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -73,16 +93,52 @@ struct State {
|
||||
struct DaemonEntry {
|
||||
hostname: String,
|
||||
version: String,
|
||||
daemon_url: String,
|
||||
outbound: mpsc::Sender<DaemonInbound>,
|
||||
}
|
||||
|
||||
impl DaemonEntry {
|
||||
fn to_view(&self, daemon_id: &str) -> DaemonView {
|
||||
DaemonView {
|
||||
daemon_id: daemon_id.to_string(),
|
||||
hostname: self.hostname.clone(),
|
||||
version: self.version.clone(),
|
||||
daemon_url: self.daemon_url.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn new() -> Self {
|
||||
let (events, _) = broadcast::channel(EVENT_CHANNEL_CAPACITY);
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(State::default())),
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to the registry's broadcast event stream. The subscriber gets
|
||||
/// a one-shot `Snapshot` of the current catalog first, then live deltas.
|
||||
pub async fn subscribe(&self) -> (RegistryEvent, broadcast::Receiver<RegistryEvent>) {
|
||||
let state = self.inner.lock().await;
|
||||
let snapshot = RegistryEvent::Snapshot {
|
||||
daemons: state
|
||||
.daemons
|
||||
.iter()
|
||||
.map(|(id, e)| e.to_view(id).into())
|
||||
.collect(),
|
||||
sessions: state.sessions.values().cloned().collect(),
|
||||
};
|
||||
let rx = self.events.subscribe();
|
||||
(snapshot, rx)
|
||||
}
|
||||
|
||||
fn broadcast(&self, event: RegistryEvent) {
|
||||
// Send returns Err only when there are no subscribers; that's not a
|
||||
// bug, so swallow.
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Connection lifecycle
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -95,26 +151,58 @@ impl Registry {
|
||||
daemon_id: String,
|
||||
hostname: String,
|
||||
version: String,
|
||||
daemon_url: String,
|
||||
outbound: mpsc::Sender<DaemonInbound>,
|
||||
) {
|
||||
let mut state = self.inner.lock().await;
|
||||
state.drop_daemon_sessions(&daemon_id);
|
||||
let removed_sessions = state.drop_daemon_sessions(&daemon_id);
|
||||
state.daemons.insert(
|
||||
daemon_id,
|
||||
daemon_id.clone(),
|
||||
DaemonEntry {
|
||||
hostname,
|
||||
version,
|
||||
hostname: hostname.clone(),
|
||||
version: version.clone(),
|
||||
daemon_url: daemon_url.clone(),
|
||||
outbound,
|
||||
},
|
||||
);
|
||||
drop(state);
|
||||
for id in removed_sessions {
|
||||
self.broadcast(RegistryEvent::SessionRemoved {
|
||||
daemon_id: daemon_id.clone(),
|
||||
id,
|
||||
});
|
||||
}
|
||||
self.broadcast(RegistryEvent::DaemonAdded {
|
||||
daemon: DaemonInfo {
|
||||
daemon_id,
|
||||
hostname,
|
||||
version,
|
||||
daemon_url,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove the daemon and any sessions it owned. Also fails any pending
|
||||
/// RPCs that were sent to it.
|
||||
pub async fn deregister(&self, daemon_id: &str) {
|
||||
let mut state = self.inner.lock().await;
|
||||
state.daemons.remove(daemon_id);
|
||||
state.drop_daemon_sessions(daemon_id);
|
||||
let removed_sessions;
|
||||
let had_daemon;
|
||||
{
|
||||
let mut state = self.inner.lock().await;
|
||||
had_daemon = state.daemons.remove(daemon_id).is_some();
|
||||
removed_sessions = state.drop_daemon_sessions(daemon_id);
|
||||
}
|
||||
for id in removed_sessions {
|
||||
self.broadcast(RegistryEvent::SessionRemoved {
|
||||
daemon_id: daemon_id.to_string(),
|
||||
id,
|
||||
});
|
||||
}
|
||||
if had_daemon {
|
||||
self.broadcast(RegistryEvent::DaemonRemoved {
|
||||
daemon_id: daemon_id.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -122,30 +210,75 @@ impl Registry {
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
pub async fn apply_snapshot(&self, daemon_id: &str, sessions: Vec<Session>) {
|
||||
let mut state = self.inner.lock().await;
|
||||
state.drop_daemon_sessions(daemon_id);
|
||||
for s in sessions {
|
||||
state.sessions.insert((daemon_id.to_string(), s.id), s);
|
||||
let (removed, added) = {
|
||||
let mut state = self.inner.lock().await;
|
||||
let removed = state.drop_daemon_sessions(daemon_id);
|
||||
let mut added = Vec::with_capacity(sessions.len());
|
||||
for s in sessions {
|
||||
added.push(s.clone());
|
||||
state.sessions.insert((daemon_id.to_string(), s.id), s);
|
||||
}
|
||||
(removed, added)
|
||||
};
|
||||
for id in removed {
|
||||
self.broadcast(RegistryEvent::SessionRemoved {
|
||||
daemon_id: daemon_id.to_string(),
|
||||
id,
|
||||
});
|
||||
}
|
||||
for s in added {
|
||||
self.broadcast(RegistryEvent::SessionAdded { session: s });
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add_session(&self, daemon_id: &str, session: Session) {
|
||||
let mut state = self.inner.lock().await;
|
||||
state
|
||||
.sessions
|
||||
.insert((daemon_id.to_string(), session.id), session);
|
||||
{
|
||||
let mut state = self.inner.lock().await;
|
||||
state
|
||||
.sessions
|
||||
.insert((daemon_id.to_string(), session.id), session.clone());
|
||||
}
|
||||
self.broadcast(RegistryEvent::SessionAdded { session });
|
||||
}
|
||||
|
||||
pub async fn remove_session(&self, daemon_id: &str, id: Uuid) {
|
||||
let mut state = self.inner.lock().await;
|
||||
state.sessions.remove(&(daemon_id.to_string(), id));
|
||||
let removed = {
|
||||
let mut state = self.inner.lock().await;
|
||||
state.sessions.remove(&(daemon_id.to_string(), id))
|
||||
};
|
||||
if removed.is_some() {
|
||||
self.broadcast(RegistryEvent::SessionRemoved {
|
||||
daemon_id: daemon_id.to_string(),
|
||||
id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_session(&self, daemon_id: &str, session: Session) {
|
||||
let mut state = self.inner.lock().await;
|
||||
{
|
||||
let mut state = self.inner.lock().await;
|
||||
state
|
||||
.sessions
|
||||
.insert((daemon_id.to_string(), session.id), session.clone());
|
||||
}
|
||||
self.broadcast(RegistryEvent::SessionUpdated { session });
|
||||
}
|
||||
|
||||
/// Look up the daemon that owns the given session id.
|
||||
pub async fn daemon_for_session(&self, session_id: Uuid) -> Option<String> {
|
||||
let state = self.inner.lock().await;
|
||||
state
|
||||
.sessions
|
||||
.insert((daemon_id.to_string(), session.id), session);
|
||||
.iter()
|
||||
.find(|((_, id), _)| *id == session_id)
|
||||
.map(|((d, _), _)| d.clone())
|
||||
}
|
||||
|
||||
/// Resolve a daemon's connect URL (the operator-advertised value from its
|
||||
/// Hello frame).
|
||||
pub async fn daemon_url(&self, daemon_id: &str) -> Option<String> {
|
||||
let state = self.inner.lock().await;
|
||||
state.daemons.get(daemon_id).map(|e| e.daemon_url.clone())
|
||||
}
|
||||
|
||||
/// Resolve a CreateSession RPC reply. Returns true if a waiter was found.
|
||||
@@ -238,15 +371,7 @@ impl Registry {
|
||||
|
||||
pub async fn daemons(&self) -> Vec<DaemonView> {
|
||||
let state = self.inner.lock().await;
|
||||
state
|
||||
.daemons
|
||||
.iter()
|
||||
.map(|(id, e)| DaemonView {
|
||||
daemon_id: id.clone(),
|
||||
hostname: e.hostname.clone(),
|
||||
version: e.version.clone(),
|
||||
})
|
||||
.collect()
|
||||
state.daemons.iter().map(|(id, e)| e.to_view(id)).collect()
|
||||
}
|
||||
|
||||
pub async fn sessions(&self) -> Vec<Session> {
|
||||
@@ -272,8 +397,19 @@ impl Default for Registry {
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn drop_daemon_sessions(&mut self, daemon_id: &str) {
|
||||
self.sessions.retain(|(d, _), _| d.as_str() != daemon_id);
|
||||
/// Removes every session belonging to `daemon_id`, returning their ids so
|
||||
/// the caller can emit `SessionRemoved` events outside the lock.
|
||||
fn drop_daemon_sessions(&mut self, daemon_id: &str) -> Vec<Uuid> {
|
||||
let mut removed = Vec::new();
|
||||
self.sessions.retain(|(d, id), _| {
|
||||
if d.as_str() == daemon_id {
|
||||
removed.push(*id);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
removed
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user