8000 feat(minimald): scaffolding for the attachable session process by twitchyliquid64 · Pull Request #375 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
5 changes: 4 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ google-cloud-gax = "1.13"
google-cloud-auth = "1.5"
google-cloud-storage = "1.7"
# Revert back to crates.io dep once new version is released.
hakoniwa = { git = "https://github.com/souk4711/hakoniwa.git", rev = "65d12eaae6786cd312aa74784514eb3a072dfe38", features = ["cgroups"] }
hakoniwa = { git = "https://github.com/souk4711/hakoniwa.git", rev = "41ce36e087fa1fcf28d17123042d150e71c09705", features = ["cgroups"] }
http-body = "1"
hex = "0.4"
indicatif = "0.18"
Expand Down Expand Up @@ -116,6 +116,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
thiserror = "2"
url = "2" # keep in sync with reqwest
uuid = { version = "1.23", features = ["v4", "v7", "serde"] }
vt100-ctt = "0.17"
zstd = "0.13"

moka = { version = "0.12", default-features = false, features = ["sync"] }
Expand Down
3 changes: 3 additions & 0 deletions crates/minimald/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ edition.workspace = true
publish.workspace = true

[dependencies]
bytes.workspace = true
camino.workspace = true
clap.workspace = true
clap_complete.workspace = true
constcat.workspace = true
dirs.workspace = true
either.workspace = true
futures.workspace = true
hakoniwa.workspace = true
libc.workspace = true
Expand All @@ -19,6 +21,7 @@ path-absolutize.workspace = true
serde.workspace = true
serde_json.workspace = true
tempfile.workspace = true
vt100-ctt.workspace = true

tokio.workspace = true
tracing.workspace = true
Expand Down
51 changes: 50 additions & 1 deletion crates/minimald/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use russh::{
Channel as RuChannel, ChannelId,
server::{Config as RuConfig, Msg, RunningSession, Session},
};
use sessions::SessionId;
use std::{
collections::BTreeMap,
fmt,
Expand All @@ -17,6 +18,7 @@ use crate::{
ChannelConfig, RequestedPty, exec,
rpc::{self},
server::ServerStateHandle,
sessions::SessionKeyPredicate,
sftp,
};

Expand Down Expand Up @@ -369,7 +371,54 @@ impl russh::server::Handler for ConnectionHandler {
session: &mut Session,
) -> Result<(), Self::Error> {
protocol_trace!("Got shell_request on channel {id}");
session.channel_failure(id)?; // TODO: handle shell request

let conn = self.0.clone();
let serv = conn.0.lock().await.serv.clone();
let mut conn_lock = conn.lock().await;
let Some((channel, config)) = conn_lock.take(id) else {
session.channel_failure(id)?;
return Ok(());
};
drop(conn_lock);
if config.pty.is_none() {
tracing::warn!("channel {id}: pty not requested for shell session",);
session.channel_failure(id)?;
return Ok(());
}

let Some(session_id_str) = config.env_vars.get(crate::MINIMAL_SESSION_ID_ENV) else {
tracing::warn!("shell request rejected on channel {id}: missing MINIMAL_SESSION_ID",);
session.channel_failure(id)?;
return Ok(());
};
let Ok(session_id) = SessionId::parse_str(session_id_str) else {
tracing::warn!(
value = %session_id_str,
"shell request rejected on channel {id}: not a uuid",
);
session.channel_failure(id)?;
return Ok(());
};

let mngr = serv.sessions_manager().await;
let session_handle = match mngr.get_session(SessionKeyPredicate::Id(session_id)).await {
Ok(Some(h)) => h,
Ok(None) => {
tracing::warn!(%session_id, "shell request rejected: unknown session");
session.channel_failure(id)?;
return Ok(());
}
Err(e) => {
tracing::warn!(%session_id, error = %e, "shell request rejected: lookup failed");
session.channel_failure(id)?;
return Ok(());
}
};
Comment on lines +375 to +416
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Delay take(id) until the shell request is fully validated.

This consumes the channel before the PTY check, MINIMAL_SESSION_ID parsing, and session lookup. On any rejection path, the channel stays in Taken, so the client cannot retry or fall back to another request on the same channel even though initiation never succeeded.

Suggested direction

Validate against the pending config first, then call take(id) only once the code is ready to attach:

-        let mut conn_lock = conn.lock().await;
-        let Some((channel, config)) = conn_lock.take(id) else {
+        let config = {
+            let conn_lock = conn.lock().await;
+            let Some(channel) = conn_lock.channels.get(&id) else {
+                session.channel_failure(id)?;
+                return Ok(());
+            };
+            let ChannelInner::Pending(_, config) = &channel.inner else {
+                session.channel_failure(id)?;
+                return Ok(());
+            };
+            config.clone()
+        };
+
+        let Some((channel, config)) = conn.lock().await.take(id) else {
             session.channel_failure(id)?;
             return Ok(());
         };
-        drop(conn_lock);

If ChannelConfig is not Clone, an immutable accessor for just the needed fields would avoid freezing the channel early.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/minimald/src/connection.rs` around lines 358 - 399, The code currently
calls conn_lock.take(id) early which consumes the pending channel; instead,
inspect the pending ChannelConfig immutably (avoid take) to validate pty, check
MINIMAL_SESSION_ID_ENV and parse SessionId and perform the session lookup (using
SessionId::parse_str, crate::MINIMAL_SESSION_ID_ENV, mngr =
serv.sessions_manager(), mngr.get_session(...)) while leaving the channel in
place; only after all validations succeed call conn_lock.take(id) and proceed to
attach; if ChannelConfig is not Clone add a small immutable accessor to read the
needed fields (pty, env_vars) so the channel isn't marked Taken on rejection
paths.


session.channel_success(id)?;
tokio::spawn(async move {
session_handle.attach(channel, config).await;
});
Ok(())
}

Expand Down
1 change: 1 addition & 0 deletions crates/minimald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod guest;
pub mod rpc;
pub mod server;
mod session;
pub mod session_host;
mod sessions;
mod sftp;
#[cfg(test)]
Expand Down
15 changes: 12 additions & 3 deletions crates/minimald/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use camino::Utf8PathBuf;
use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use paths::{CwdRelative, Daemon, DaemonAbsPath, DaemonRelPath, sub_path};
use tokio::net::UnixListener;
use tokio::{net::UnixListener, runtime::Builder};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};

use minimald::server::{Config, HostKey, Server};
Expand Down Expand Up @@ -126,8 +126,17 @@ pub enum MainError {
IO(std::io::Error, &'static str),
}

#[tokio::main]
async fn main() -> Result<(), MainError> {
fn main() -> Result<(), MainError> {
let runtime = Builder::new_multi_thread()
.thread_name("minimald-worker")
.thread_stack_size(8 * 1024 * 1024)
.enable_all()
.build()
.unwrap();
runtime.block_on(async_main())
}

async fn async_main() -> Result<(), MainError> {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| {
EnvFilter::new("info")
.add_directive("topiary=off".parse().unwrap())
Expand Down
Loading
Loading
0