diff --git a/Cargo.lock b/Cargo.lock index 89cb439e22..9fd33172dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3600,6 +3600,7 @@ version = "0.0.1" dependencies = [ "chrono", "constcat", + "paths", "serde", "serde_json", "sessions", diff --git a/crates/minimal2/src/main.rs b/crates/minimal2/src/main.rs index f4cbb761d3..797b1030f1 100644 --- a/crates/minimal2/src/main.rs +++ b/crates/minimal2/src/main.rs @@ -445,10 +445,6 @@ async fn cmd_activate(global: &GlobalArgs, args: ActivateArgs) -> Result<(), ()> let abs_path = paths::HostAbsPath::try_new(utf8_path) .map_err(|e| eprintln!("Invalid project path: {e}"))?; - let username = std::env::var("USER") - .or_else(|_| std::env::var("LOGNAME")) - .ok(); - let mut port_mappings = Vec::with_capacity(args.ingress.len()); for spec in &args.ingress { match parse_ingress_mapping(spec) { @@ -467,21 +463,23 @@ async fn cmd_activate(global: &GlobalArgs, args: ActivateArgs) -> Result<(), ()> }), }; - let record = sessions::Record { - id: sessions::SessionId::nil(), + // The daemon sources `username` from the authenticated SSH + // connection context; the client doesn't send it. + let config = minimald_rpc::SessionConfig { name: args.name.clone(), - username, project_path: abs_path, network: args.network.into(), policy, - status: Default::default(), attrs: Default::default(), }; let mut client = connect_daemon(global).await?; use minimald_rpc::{CreateSession, CreateSessionRequest}; - let req = CreateSessionRequest { record }; + let req = CreateSessionRequest { + config, + contribution: Default::default(), + }; let resp = client .oneshot_rpc::(req) .await @@ -497,13 +495,26 @@ async fn cmd_activate(global: &GlobalArgs, args: ActivateArgs) -> Result<(), ()> return Err(()); } }; + // Today the daemon only ever produces `Ready` (the empty- + // contribution fast path). `Pending` lights up when Phase 2 + // routing lands. + let id = match created { + minimald_rpc::CreateSessionResponse::Ready { id } => id, + minimald_rpc::CreateSessionResponse::Pending { .. } => { + eprintln!( + "CreateSession returned Pending, but the composition pipeline \ + is not wired in this client yet", + ); + return Err(()); + } + }; - println!("{}", created.id); + println!("{id}"); if args.attach { // Chain into attach. let attach_args = AttachArgs { - session: created.id.to_string(), + session: id.to_string(), command: None, }; return cmd_attach(global, attach_args).await; diff --git a/crates/minimald-rpc/Cargo.toml b/crates/minimald-rpc/Cargo.toml index 452c5c925b..3846dd504e 100644 --- a/crates/minimald-rpc/Cargo.toml +++ b/crates/minimald-rpc/Cargo.toml @@ -7,6 +7,7 @@ publish.workspace = true [dependencies] constcat.workspace = true chrono.workspace = true +paths.workspace = true serde.workspace = true sessions.workspace = true diff --git a/crates/minimald-rpc/src/lib.rs b/crates/minimald-rpc/src/lib.rs index a7f062c545..62cdd5a6a3 100644 --- a/crates/minimald-rpc/src/lib.rs +++ b/crates/minimald-rpc/src/lib.rs @@ -172,19 +172,81 @@ impl OneshotSshRpc for GetSessionRecord { type Response = GetSessionRecordResponse; } -/// An RPC to create a new session based on the given record. +/// An RPC to create a new session. +/// +/// Carries two parts: a [`SessionConfig`] (everything that doesn't +/// fit in a [`WireContribution`] — name, network, policy, attrs) +/// plus the client's Phase 1 [`WireContribution`]. Callers that +/// don't go through the composition pipeline (sftp / exec / +/// session-recovery) send `WireContribution::default()`. pub struct CreateSession; +/// Session configuration that lives outside the composable +/// [`WireContribution`] — the user-supplied `name`, the project +/// path the session is built from, the network isolation mode, the +/// per-session networking policy, and free-form attrs. +/// +/// `username` is deliberately *not* here: it comes from the SSH +/// connection context on the daemon side, never from the caller. +/// `id` and `status` are also out: id is allocated by the store, +/// status is managed by the manager actor. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SessionConfig { + /// User-supplied name. `None` is anonymous; the daemon may render + /// a short display name (e.g. `--`). + pub name: Option, + /// Absolute host path the session is built from. + pub project_path: paths::HostAbsPath, + /// Network isolation mode. + #[serde(default)] + pub network: NetworkMode, + /// Per-session networking policy (egress + ingress). + #[serde(default)] + pub policy: SessionPolicy, + /// Free-form attributes (typed by the caller). + #[serde(default)] + pub attrs: std::collections::BTreeMap, +} + /// The request for a [`CreateSession`] RPC. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateSessionRequest { - pub record: sessions::Record, + /// Out-of-band session config. + pub config: SessionConfig, + /// Client-side Phase 1 contribution. Defaulted (empty) by + /// internal callers that aren't composing a session — e.g. sftp, + /// exec, session-recovery — so the daemon takes the empty- + /// contribution fast path and returns [`CreateSessionResponse::Ready`] + /// immediately. + #[serde(default)] + pub contribution: sessions::wire::request::WireContribution, } /// The response for a [`CreateSession`] RPC. +/// +/// `Ready` is the only variant exercised today; `Pending` is +/// reserved for when daemon-side Phase 2 routing lands and the +/// daemon can ask the client to gate items that need approval. +/// Defining both up front locks the wire shape so adding the +/// Pending path later doesn't break callers. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CreateSessionResponse { - pub id: SessionId, +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum CreateSessionResponse { + /// No items need user gating. The session id is the finalized + /// session — callers can immediately use it. + Ready { + /// Daemon-assigned session id. + id: SessionId, + }, + /// Items need client-side gating. The session id is allocated + /// and the session is persisted (status reflects "in flight"). + /// Client follows up with `SubmitVerdict` carrying the same id. + Pending { + /// Daemon-assigned session id; also embedded in `response`. + id: SessionId, + /// Pending items the client must gate. + response: sessions::wire::request::ContributionResponse, + }, } impl OneshotSshRpc for CreateSession { @@ -480,6 +542,7 @@ impl OneshotSshRpc for GetMeshStatus { #[cfg(test)] mod tests { use super::*; + use sessions::wire::request::{ContributionResponse, WireContribution}; #[test] fn policy_types_are_present_and_serializable() { @@ -520,4 +583,72 @@ mod tests { "got: {json}" ); } + + fn round_trip(value: &T) -> T + where + T: serde::Serialize + serde::de::DeserializeOwned, + { + let json = serde_json::to_string(value).expect("serialize"); + serde_json::from_str(&json).expect("deserialize") + } + + #[test] + fn create_session_request_round_trips_with_explicit_contribution() { + let req = CreateSessionRequest { + config: SessionConfig { + name: Some("my-session".into()), + project_path: paths::HostAbsPath::try_new("/home/u/proj").unwrap(), + network: NetworkMode::OwnIp, + policy: SessionPolicy::default(), + attrs: [("color".to_string(), "blue".to_string())] + .into_iter() + .collect(), + }, + contribution: WireContribution::default(), + }; + assert_eq!(round_trip(&req), req); + } + + #[test] + fn create_session_request_accepts_missing_contribution_field() { + // Wire payload from an internal caller that doesn't know about + // the composition pipeline: only `config` is set. + let raw = serde_json::json!({ + "config": { + "name": null, + "project_path": "/proj", + "network": "host_net", + "policy": { "egress": null, "ingress": null }, + "attrs": {}, + }, + }); + let req: CreateSessionRequest = serde_json::from_value(raw).expect("deserialize"); + assert_eq!(req.contribution, WireContribution::default()); + } + + #[test] + fn create_session_response_ready_round_trips() { + let id = SessionId::parse_str("00000000-0000-0000-0000-000000000001").unwrap(); + let resp = CreateSessionResponse::Ready { id }; + assert_eq!(round_trip(&resp), resp); + let json = serde_json::to_string(&resp).unwrap(); + assert!(json.contains(r#""kind":"ready""#), "got: {json}"); + } + + #[test] + fn create_session_response_pending_round_trips() { + let id = SessionId::parse_str("00000000-0000-0000-0000-000000000001").unwrap(); + let resp = CreateSessionResponse::Pending { + id, + response: ContributionResponse { + session_id: id, + vars: vec![], + patches: vec![], + lifecycle_hooks: vec![], + }, + }; + assert_eq!(round_trip(&resp), resp); + let json = serde_json::to_string(&resp).unwrap(); + assert!(json.contains(r#""kind":"pending""#), "got: {json}"); + } } diff --git a/crates/minimald/src/exec.rs b/crates/minimald/src/exec.rs index 031b1bd7d1..9fb1832bb2 100644 --- a/crates/minimald/src/exec.rs +++ b/crates/minimald/src/exec.rs @@ -1220,35 +1220,24 @@ mod tests { //! Tests that exercise the full ssh-exec stack against a real //! `TestServer`: russh transport, `ConnectionHandler` dispatch, //! `handle_exec`, and a real `/bin/sh -c` child. - use paths::HostAbsPath; use sessions::SessionId; - use minimald_rpc::{CreateSession, CreateSessionRequest}; + use minimald_rpc::CreateSession; use crate::MINIMAL_SESSION_ID_ENV; use crate::sessions::SessionKeyPredicate; - use crate::test_harness::{TestClient, TestServer}; + use crate::test_harness::{TestClient, TestServer, create_session_req, unwrap_ready}; /// Creates a fresh session through the public CreateSession RPC /// and returns its id, mirroring how a real client sets up state /// before running commands against the session. async fn fresh_session(client: &mut TestClient) -> SessionId { - client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("exec-test".to_string()), - username: None, - project_path: HostAbsPath::try_new("/tmp").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap() - .id + unwrap_ready( + client + .call::(&create_session_req("exec-test", "/tmp")) + .await + .unwrap(), + ) } #[tokio::test] diff --git a/crates/minimald/src/rpc.rs b/crates/minimald/src/rpc.rs index 7bc11b7bbd..eeff7c350e 100644 --- a/crates/minimald/src/rpc.rs +++ b/crates/minimald/src/rpc.rs @@ -1,11 +1,11 @@ #[cfg(feature = "networking-proxy")] use minimald_rpc::IssueClientCertResponse; use minimald_rpc::{ - CreateSession, CreateSessionResponse, DestroySession, DestroySessionResponse, Errorable, - GetMeshStatus, GetSessionPolicy, GetSessionPolicyRequest, GetSessionRecord, - GetSessionRecordRequest, GetSessionRecordResponse, GetVersion, GetVersionResponse, - IssueClientCert, IssueClientCertRequest, ListSessions, ListSessionsEntry, ListSessionsResponse, - OneshotSshRpc, RPC_SUBSYSTEM_PREFIX, RenameSession, RenameSessionResponse, + CreateSession, DestroySession, DestroySessionResponse, Errorable, GetMeshStatus, + GetSessionPolicy, GetSessionPolicyRequest, GetSessionRecord, GetSessionRecordRequest, + GetSessionRecordResponse, GetVersion, GetVersionResponse, IssueClientCert, + IssueClientCertRequest, ListSessions, ListSessionsEntry, ListSessionsResponse, OneshotSshRpc, + RPC_SUBSYSTEM_PREFIX, RenameSession, RenameSessionResponse, }; use russh::{ Channel as RuChannel, ChannelId, @@ -136,24 +136,33 @@ async fn serve_get_session_record(s: ServerStateHandle, c: RuChannel) { } } -async fn serve_create_session(s: ServerStateHandle, c: RuChannel) { +async fn serve_create_session( + s: ServerStateHandle, + c: RuChannel, + ssh_username: Option, +) { let res = CreateSession .handle_channel(c, async |req| { let mngr = s.sessions_manager().await; - Ok(match mngr.create_session(req.record).await { - Ok(id) => Errorable::Ok(CreateSessionResponse { id }), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Errorable::Err { - error: "A session with that name already exists".to_string(), - }, - // R2.1: a policy/network-mode mismatch is rejected at - // declaration time and surfaced as a clean typed error rather - // than a transport failure. - Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => Errorable::Err { - error: e.to_string(), + Ok( + match mngr + .create_session(req.config, ssh_username, req.contribution) + .await + { + Ok(resp) => Errorable::Ok(resp), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Errorable::Err { + error: "A session with that name already exists".to_string(), + }, + // R2.1: a policy/network-mode mismatch is rejected at + // declaration time and surfaced as a clean typed error rather + // than a transport failure. + Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => Errorable::Err { + error: e.to_string(), + }, + Err(e) => return Err(ConnectionError::Internal(e.to_string())), }, - Err(e) => return Err(ConnectionError::Internal(e.to_string())), - }) + ) }) .await; if let Err(e) = res { @@ -347,6 +356,9 @@ pub async fn handle_ssh_rpc( session: &mut Session, ) -> Result<(), ConnectionError> { // Take the channel from connection state if its a known RPC. + // `ssh_username` is read out under the same lock so `serve_*` + // handlers that need the authenticated user (CreateSession) don't + // have to re-lock. let res = match name { GetVersion::NAME | ListSessions::NAME @@ -366,17 +378,18 @@ pub async fn handle_ssh_rpc( } Some((channel, config)) => (channel, config), }; + let ssh_username = conn_lock.ssh_username.clone(); drop(conn_lock); session.channel_success(id)?; - Some(c_hnd) + Some((c_hnd, ssh_username)) } _ => { session.channel_failure(id)?; None } }; - let (channel, config) = match res { - Some((channel, config)) => (channel, config), + let ((channel, config), ssh_username) = match res { + Some(v) => v, None => return Ok(()), }; @@ -385,7 +398,7 @@ pub async fn handle_ssh_rpc( GetVersion::NAME => drop(spawn(serve_get_version(channel))), ListSessions::NAME => drop(spawn(serve_list_sessions(s, channel))), GetSessionRecord::NAME => drop(spawn(serve_get_session_record(s, channel))), - CreateSession::NAME => drop(spawn(serve_create_session(s, channel))), + CreateSession::NAME => drop(spawn(serve_create_session(s, channel, ssh_username))), RenameSession::NAME => drop(spawn(serve_rename_session(s, channel))), DestroySession::NAME => drop(spawn(serve_destroy_session(s, channel))), GetSessionPolicy::NAME => drop(spawn(serve_get_session_policy(s, channel))), @@ -444,24 +457,16 @@ mod tests { encoder.into_inner() } + use crate::test_harness::{create_session_req as req, unwrap_ready}; + /// Creates a session through the public RPC and returns its id. async fn fresh_session(client: &mut TestClient) -> SessionId { - client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("stream-test".to_string()), - username: None, - project_path: HostAbsPath::try_new("/tmp").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap() - .id + unwrap_ready( + client + .call::(&req("stream-test", "/tmp")) + .await + .unwrap(), + ) } #[tokio::test] @@ -612,28 +617,18 @@ mod tests { let server = TestServer::new().await; let mut client = server.connect().await; - let create_session = client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("my session".to_string()), - username: None, - project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap(); - - assert!(create_session.id != SessionId::nil()); + let id = unwrap_ready( + client + .call::(&req("my session", "/uwu")) + .await + .unwrap(), + ); + assert!(id != SessionId::nil()); let get_session = client - .call::(&GetSessionRecordRequest::Id(create_session.id)) + .call::(&GetSessionRecordRequest::Id(id)) .await; - assert_eq!(get_session.record.as_ref().unwrap().id, create_session.id); + assert_eq!(get_session.record.as_ref().unwrap().id, id); assert_eq!( get_session.record.as_ref().unwrap().name, Some("my session".to_string()) @@ -647,7 +642,7 @@ mod tests { assert_eq!( list_sessions.sessions, vec![ListSessionsEntry { - id: create_session.id, + id, name: Some("my session".to_string()), attrs: None, }] @@ -667,24 +662,24 @@ mod tests { allow_dns_hosts: None, allow_protocols: None, }; - let created = client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("policy-session".to_string()), - username: None, - project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: NetworkMode::OwnIp, - policy: SessionPolicy::new(Some(egress.clone()), None), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap(); + let created_id = unwrap_ready( + client + .call::(&CreateSessionRequest { + config: minimald_rpc::SessionConfig { + name: Some("policy-session".to_string()), + project_path: HostAbsPath::try_new("/uwu").unwrap(), + network: NetworkMode::OwnIp, + policy: SessionPolicy::new(Some(egress.clone()), None), + attrs: Default::default(), + }, + contribution: Default::default(), + }) + .await + .unwrap(), + ); let policy = client - .call::(&GetSessionPolicyRequest::Id(created.id)) + .call::(&GetSessionPolicyRequest::Id(created_id)) .await .unwrap(); assert_eq!(policy.egress, Some(egress)); @@ -698,38 +693,17 @@ mod tests { let server = TestServer::new().await; let mut client = server.connect().await; - let create_session = client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("my session".to_string()), - username: None, - project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap(); - - assert!(create_session.id != SessionId::nil()); + let id = unwrap_ready( + client + .call::(&req("my session", "/uwu")) + .await + .unwrap(), + ); + assert!(id != SessionId::nil()); assert_eq!( client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("my session".to_string()), - username: None, - project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) + .call::(&req("my session", "/uwu")) .await, Errorable::Err { error: "A session with that name already exists".to_string() @@ -751,16 +725,14 @@ mod tests { }; let resp = client .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), + config: minimald_rpc::SessionConfig { name: Some("bad-policy".to_string()), - username: None, project_path: HostAbsPath::try_new("/uwu").unwrap(), network: NetworkMode::HostNet, policy: SessionPolicy::new(Some(egress), None), - status: Default::default(), attrs: Default::default(), }, + contribution: Default::default(), }) .await; assert_eq!( diff --git a/crates/minimald/src/session.rs b/crates/minimald/src/session.rs index b5202ce80d..eaecf09e86 100644 --- a/crates/minimald/src/session.rs +++ b/crates/minimald/src/session.rs @@ -457,32 +457,21 @@ impl SessionHandle { mod tests { use std::time::Duration; - use paths::HostAbsPath; use russh::ChannelMsg; use sessions::SessionId; - use minimald_rpc::{CreateSession, CreateSessionRequest}; + use minimald_rpc::CreateSession; - use crate::test_harness::{TestClient, TestServer}; + use crate::test_harness::{TestClient, TestServer, create_session_req, unwrap_ready}; /// Creates a fresh session on the server and returns its id. async fn create_session(client: &mut TestClient) -> SessionId { - client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("shell-test".to_string()), - username: None, - project_path: HostAbsPath::try_new("/uwu").unwrap(), - network: Default::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap() - .id + unwrap_ready( + client + .call::(&create_session_req("shell-test", "/uwu")) + .await + .unwrap(), + ) } /// Drives the full SSH path into the session host with the mock launcher: diff --git a/crates/minimald/src/sessions.rs b/crates/minimald/src/sessions.rs index f38530f070..82c690dab7 100644 --- a/crates/minimald/src/sessions.rs +++ b/crates/minimald/src/sessions.rs @@ -8,6 +8,7 @@ use paths::DaemonAbsPath; use sessions::{ SessionId, store::{DiskLoader, Loader, SessionKey, SessionObject}, + wire::request::WireContribution, }; use std::sync::Arc; #[cfg(target_os = "linux")] @@ -48,6 +49,7 @@ fn registry_name(record: &sessions::Record) -> String { } /// Encapsulates the return channel for messages back from the actor. +#[derive(Debug)] struct Responder(oneshot::Sender>); impl Responder { @@ -66,11 +68,28 @@ impl Responder { } } +/// CreateSession payload — boxed so it doesn't dominate +/// `ManagerMessage`'s size (the variant carries a full session +/// config + an optional contribution; other variants are just a +/// few words). +#[derive(Debug)] +struct CreateSessionMsg { + config: minimald_rpc::SessionConfig, + /// Authenticated SSH username, supplied by the RPC handler from + /// the SSH connection context (never the client). + username: Option, + /// Client-side Phase 1 contribution. Today the handler rejects + /// anything other than the default; the composition pipeline will + /// consume it when Phase 2 lands. + contribution: WireContribution, + responder: Responder, +} + enum ManagerMessage { List(Responder>), GetRecord(SessionKeyPredicate, Responder>), GetSession(SessionKeyPredicate, Responder>), - CreateSession(sessions::Record, Responder), + CreateSession(Box), RenameSession(SessionId, String, Responder<()>), DestroySession(SessionId, Responder<()>), } @@ -242,20 +261,62 @@ impl Manager { }) .await; } - // Creates a session using the given record. - ManagerMessage::CreateSession(record, r) => { - r.handle(async { - // R2.1: reject a policy incompatible with the network mode - // (e.g. egress on a non-`OwnIp` PTask) at declaration time, - // so an invalid session is never written to the store - // rather than only failing when a client later attaches. - record - .validate_policy() - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; - let k = self.store.create(record)?; - Ok(*k.id()) - }) - .await; + // Creates a session from a config + (optional) client wire + // contribution. + ManagerMessage::CreateSession(msg) => { + let CreateSessionMsg { + config, + username, + contribution, + responder, + } = *msg; + responder + .handle(async { + // Until daemon-side Phase 2 routing lands, the only + // valid contribution is the empty default. Silently + // dropping a non-empty contribution would let clients + // believe their composed vars/patches/packages/hooks + // were honored — they would not be. Reject explicitly + // so the failure surfaces at the call site instead + // of as missing items in the assembled session. + // + // TODO(composition): when Phase 2 lands, the + // composition pipeline consumes this field instead. + // The seam is here: replace this check with the + // partition + ContributionResponse flow. + if contribution != WireContribution::default() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "non-empty WireContribution is not supported \ + by this daemon — daemon-side composition \ + (Phase 2) is not wired yet", + )); + } + // Assemble the on-disk Record from out-of-band config + // + the SSH-supplied username. Persists `Active` + // immediately on the empty-contribution fast path. + let record = sessions::Record { + id: SessionId::nil(), + name: config.name, + username, + project_path: config.project_path, + network: config.network, + policy: config.policy, + status: sessions::SessionStatus::Active, + attrs: config.attrs, + }; + // R2.1: reject a policy incompatible with the network + // mode (e.g. egress on a non-`OwnIp` PTask) at + // declaration time, so an invalid session is never + // written to the store rather than only failing when + // a client later attaches. + record.validate_policy().map_err(|e| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, e) + })?; + let k = self.store.create(record)?; + Ok(minimald_rpc::CreateSessionResponse::Ready { id: *k.id() }) + }) + .await; } // Renames an existing session with the given ID. ManagerMessage::RenameSession(id, new_name, r) => { @@ -387,16 +448,26 @@ impl ManagerHandle { recv.await.expect("corresponding sessions manager is dead") } - /// Creates a session based on the given record. + /// Creates a session from the given config + client wire + /// contribution. `username` is the authenticated SSH user from + /// the connection context; pass `None` for non-SSH callers (e.g. + /// in-process daemon callers and tests). pub async fn create_session( &self, - record: sessions::Record, - ) -> Result { + config: minimald_rpc::SessionConfig, + username: Option, + contribution: WireContribution, + ) -> Result { let (send, recv) = Responder::channel(); // Ignore send errors - the recv will also fail. let _ = self .sender - .send(ManagerMessage::CreateSession(record, send)) + .send(ManagerMessage::CreateSession(Box::new(CreateSessionMsg { + config, + username, + contribution, + responder: send, + }))) .await; recv.await.expect("corresponding sessions manager is dead") } @@ -456,19 +527,26 @@ mod tests { DaemonAbsPath::try_new(tmp.path().to_str().unwrap()).unwrap() } - fn sample_record() -> sessions::Record { - sessions::Record { - id: SessionId::nil(), + fn sample_config() -> minimald_rpc::SessionConfig { + minimald_rpc::SessionConfig { name: Some("doomed".to_string()), - username: None, project_path: HostAbsPath::try_new("/proj").unwrap(), network: sessions::NetworkMode::default(), policy: Default::default(), - status: Default::default(), attrs: Default::default(), } } + /// Test helper: send via the in-process manager actor (not RPC), + /// then unwrap the `Ready` arm via the shared test_harness helper. + async fn create_and_unwrap_id(mngr: &ManagerHandle) -> SessionId { + crate::test_harness::unwrap_ready( + mngr.create_session(sample_config(), None, WireContribution::default()) + .await + .unwrap(), + ) + } + async fn manager() -> (TempDir, TempDir, ManagerHandle) { let state = TempDir::new().unwrap(); let cache = TempDir::new().unwrap(); @@ -490,7 +568,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn destroy_removes_a_non_running_session() { let (_state, _cache, mngr) = manager().await; - let id = mngr.create_session(sample_record()).await.unwrap(); + let id = create_and_unwrap_id(&mngr).await; mngr.destroy_session(id).await.unwrap(); @@ -503,7 +581,7 @@ mod tests { ); assert!(mngr.list().await.unwrap().is_empty()); // The name index entry was dropped, so the name can be taken again. - mngr.create_session(sample_record()).await.unwrap(); + let _ = create_and_unwrap_id(&mngr).await; } /// Destroying a session that has been brought up (its actor is running, but @@ -511,7 +589,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn destroy_tears_down_a_running_session() { let (_state, _cache, mngr) = manager().await; - let id = mngr.create_session(sample_record()).await.unwrap(); + let id = create_and_unwrap_id(&mngr).await; // Bring the session actor up (populating the running map) without // attaching a host. @@ -551,4 +629,32 @@ mod tests { .expect_err("destroying an unknown id should error"); assert_eq!(err.kind(), ErrorKind::NotFound); } + + /// A non-empty `WireContribution` must be refused with + /// `InvalidInput` until daemon-side Phase 2 routing lands. + /// Silently dropping it would let clients believe their + /// composed items were honored. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn create_session_rejects_non_empty_contribution() { + use sessions::core::source::Source; + use sessions::wire::primitives::{WireResolvedVar, WireSessionVar, WireSource}; + + let (_state, _cache, mngr) = manager().await; + let mut contribution = WireContribution::default(); + contribution.vars.push(WireSessionVar { + var: WireResolvedVar { + name: "EDITOR".into(), + value: "hx".into(), + }, + source: WireSource::from(Source::UserLoadout { + name: "test".into(), + }), + }); + + let err = mngr + .create_session(sample_config(), None, contribution) + .await + .expect_err("non-empty contribution must be rejected today"); + assert_eq!(err.kind(), ErrorKind::InvalidInput); + } } diff --git a/crates/minimald/src/sftp.rs b/crates/minimald/src/sftp.rs index 151722a327..6f16448ca9 100644 --- a/crates/minimald/src/sftp.rs +++ b/crates/minimald/src/sftp.rs @@ -461,13 +461,12 @@ pub(crate) async fn handle_sftp_subsystem( #[cfg(test)] mod tests { - use paths::HostAbsPath; use russh_sftp::client::error::Error as SftpClientError; use russh_sftp::protocol::{OpenFlags, StatusCode}; use sessions::SessionId; use tokio::io::AsyncWriteExt; - use minimald_rpc::{CreateSession, CreateSessionRequest}; + use minimald_rpc::CreateSession; use crate::test_harness::TestServer; @@ -475,22 +474,13 @@ mod tests { /// returns its uuid, mirroring how a real client would set things up /// before opening an SFTP channel. async fn fresh_session(client: &mut crate::test_harness::TestClient) -> SessionId { - client - .call::(&CreateSessionRequest { - record: sessions::Record { - id: SessionId::nil(), - name: Some("sftp-test".to_string()), - username: None, - project_path: HostAbsPath::try_new("/tmp").unwrap(), - network: sessions::NetworkMode::default(), - policy: Default::default(), - status: Default::default(), - attrs: Default::default(), - }, - }) - .await - .unwrap() - .id + use crate::test_harness::{create_session_req, unwrap_ready}; + unwrap_ready( + client + .call::(&create_session_req("sftp-test", "/tmp")) + .await + .unwrap(), + ) } #[tokio::test] diff --git a/crates/minimald/src/test_harness.rs b/crates/minimald/src/test_harness.rs index 0156344c30..42cb402c99 100644 --- a/crates/minimald/src/test_harness.rs +++ b/crates/minimald/src/test_harness.rs @@ -324,3 +324,36 @@ impl russh::client::Handler for TestClientHandler { Ok(true) } } + +// --------------------------------------------------------------------------- +// CreateSession test helpers +// --------------------------------------------------------------------------- + +/// Build a `CreateSessionRequest` with sensible defaults for tests +/// that only care about `name` and `project_path`. +pub(crate) fn create_session_req(name: &str, project: &str) -> minimald_rpc::CreateSessionRequest { + minimald_rpc::CreateSessionRequest { + config: minimald_rpc::SessionConfig { + name: Some(name.to_string()), + project_path: paths::HostAbsPath::try_new(project).unwrap(), + network: sessions::NetworkMode::default(), + policy: Default::default(), + attrs: Default::default(), + }, + contribution: Default::default(), + } +} + +/// Unwrap the `Ready` arm of a [`minimald_rpc::CreateSessionResponse`]. +/// The only arm reachable in tests today — `Pending` is unreachable +/// until daemon Phase 2 routing lands. Avoids dumping the full +/// `Pending` payload in the panic message so test output stays focused +/// on the variant mismatch. +pub(crate) fn unwrap_ready(resp: minimald_rpc::CreateSessionResponse) -> sessions::SessionId { + match resp { + minimald_rpc::CreateSessionResponse::Ready { id } => id, + minimald_rpc::CreateSessionResponse::Pending { .. } => { + panic!("expected Ready variant, got Pending") + } + } +} diff --git a/crates/minvmd/examples/exec.rs b/crates/minvmd/examples/exec.rs index b7128cb27a..9b9b4d2d37 100644 --- a/crates/minvmd/examples/exec.rs +++ b/crates/minvmd/examples/exec.rs @@ -27,22 +27,14 @@ use std::time::Duration; use russh::ChannelMsg; use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use minimald_rpc::{CreateSessionRequest, CreateSessionResponse, SessionConfig}; + /// SSH subsystem for the CreateSession RPC (mirrors minimald's /// `RPC_SUBSYSTEM_PREFIX` + "CreateSession"). const CREATE_SESSION_SUBSYSTEM: &str = "minimald-v1-CreateSession"; /// Env var minimald reads to scope an exec to a session. const MINIMAL_SESSION_ID_ENV: &str = "MINIMAL_SESSION_ID"; -#[derive(serde::Serialize)] -struct CreateSessionRequest { - record: sessions::Record, -} - -#[derive(serde::Deserialize)] -struct CreateSessionResponse { - id: sessions::SessionId, -} - /// russh client handler: accept the guest's ephemeral host key. struct ClientHandler; @@ -164,17 +156,15 @@ async fn run_session_exec( .map(|d| d.as_nanos()) .unwrap_or(0); let req = CreateSessionRequest { - record: sessions::Record { - id: sessions::SessionId::nil(), + config: SessionConfig { name: Some(format!("minvmd-demo-{uniq:x}")), - username: None, project_path: paths::HostAbsPath::try_new("/tmp") .map_err(|e| format!("project_path: {e}"))?, network: sessions::NetworkMode::default(), policy: Default::default(), - status: Default::default(), attrs: Default::default(), }, + contribution: Default::default(), }; let body = serde_json::to_vec(&req).map_err(|e| format!("serialize request: {e}"))?; @@ -191,7 +181,14 @@ async fn run_session_exec( .map_err(|e| format!("read response: {e}"))?; let resp: CreateSessionResponse = serde_json::from_slice(&resp_buf).map_err(|e| format!("decode response: {e}"))?; - resp.id + match resp { + CreateSessionResponse::Ready { id } => id, + CreateSessionResponse::Pending { .. } => { + return Err("CreateSession returned Pending; \ + this example only handles Ready" + .to_string()); + } + } }; // Exec the command in that session. diff --git a/crates/minvmd/tests/minimald_session_e2e.rs b/crates/minvmd/tests/minimald_session_e2e.rs index dc924000b5..510196cf86 100644 --- a/crates/minvmd/tests/minimald_session_e2e.rs +++ b/crates/minvmd/tests/minimald_session_e2e.rs @@ -225,17 +225,15 @@ async fn run_session_exec( .map_err(|e| format!("request_subsystem: {e}"))?; let req = CreateSessionRequest { - record: sessions::Record { - id: sessions::SessionId::nil(), + config: minimald_rpc::SessionConfig { name: Some("minvmd-e2e".to_string()), - username: None, project_path: paths::HostAbsPath::try_new("/tmp") .map_err(|e| format!("project_path: {e}"))?, network: sessions::NetworkMode::default(), policy: Default::default(), - status: Default::default(), attrs: Default::default(), }, + contribution: Default::default(), }; let body = serde_json::to_vec(&req).map_err(|e| format!("serialize request: {e}"))?; @@ -252,9 +250,17 @@ async fn run_session_exec( .map_err(|e| format!("read response: {e}"))?; let resp: ::Response = serde_json::from_slice(&resp_buf).map_err(|e| format!("decode response: {e}"))?; - resp.ok() - .ok_or_else(|| "CreateSession returned an error".to_string())? - .id + let created = resp + .ok() + .ok_or_else(|| "CreateSession returned an error".to_string())?; + match created { + minimald_rpc::CreateSessionResponse::Ready { id } => id, + minimald_rpc::CreateSessionResponse::Pending { .. } => { + return Err("CreateSession returned Pending; \ + e2e test only handles Ready" + .to_string()); + } + } }; // Exec the command in that session. diff --git a/crates/sessions/docs/COMPOSITION.md b/crates/sessions/docs/COMPOSITION.md index 74c11c9dee..48d38e301f 100644 --- a/crates/sessions/docs/COMPOSITION.md +++ b/crates/sessions/docs/COMPOSITION.md @@ -62,7 +62,13 @@ runs the **shared client-side gate pipeline** (described below). User-origin items auto-pass the `allow` step but still hit `deny` and `ignore`, so the gate completes without prompts (every outcome is decidable). The output is a `WireContribution`, shipped to the -daemon inside a `SessionCreateRequest`. +daemon inside `minimald_rpc::CreateSessionRequest { config, +contribution }`. The `config` half carries the out-of-band session +fields (`name`, `project_path`, `network`, `policy`, `attrs`); +internal callers that don't go through the composition pipeline +(sftp, exec, session-recovery) supply `WireContribution::default()` +for the contribution half and the daemon takes the empty- +contribution fast path described in Phase 4. ### Phase 2 — Daemon collects and emits pending items @@ -107,6 +113,25 @@ declares `EDITOR=vim`) surfaces here as the apply layer, which builds the sandbox, materializes vars, copies patched files, and installs lifecycle hooks. +**Response shape.** The daemon returns +`CreateSessionResponse::Ready { id }` when no items need user +gating (today's only path, including the empty-contribution fast +path used by internal callers) or +`CreateSessionResponse::Pending { id, response }` when items need +user-side gating. The `id` is allocated before the response +returns, so file uploads (when that subsystem lands) can target +the session as soon as the client receives either variant. Today +only `Ready` is reachable; `Pending` is wire-defined for the +daemon-side Phase 2 routing that will land in a future change. + +**Empty-contribution fast path.** When the client sends +`WireContribution::default()` the daemon skips Phase 2 entirely: +no project/package contributions are collected, no pending items +are emitted, no `Composition::extend_from_wire` merge runs. The +record is persisted as `Active` and returned via `Ready` in one +round-trip. This is the only path exercised by internal callers +today (sftp, exec, session-recovery). + `Composition`'s fields: `vars: Vec`, `patches: Vec`, `packages: Vec`, `lifecycle_hooks: Vec`. Vars and patches are diff --git a/crates/sessions/src/lib.rs b/crates/sessions/src/lib.rs index b74ab0f1f9..2a11d03cb1 100644 --- a/crates/sessions/src/lib.rs +++ b/crates/sessions/src/lib.rs @@ -279,6 +279,16 @@ impl fmt::Display for SessionId { /// records the status verbatim. State-machine rules (e.g. "only /// the composition pipeline can promote `Draft` → `Active`") live /// in the manager actor. +/// +/// **Forward compatibility.** This enum is binary today but will +/// grow at least one intermediate variant when file uploads land — +/// uploads need a "session id is valid, uploads are accepted, but +/// the session isn't user-connectable yet" state. Code branching on +/// status should prefer `match` arms over `status == Active` +/// equality so the compiler points at every site when the new +/// variant arrives. `#[non_exhaustive]` will be added at the same +/// time; we omit it today because every match site is in-tree and +/// the extra noise buys nothing yet. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "snake_case")] pub enum SessionStatus {