8000 feat(minimald): handle git pushes natively by twitchyliquid64 · Pull Request #347 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .minimal/minimal.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ locked_commit = "0da02c7fe4cff292388c1b9ebd611feceabb22fe"

[harness]
use = "rust"
runtime_packages = ["socat"]

[defaults]
profile = "dev"
Expand Down
4 changes: 1 addition & 3 deletions crates/minimald/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ russh-sftp.workspace = true
path-absolutize.workspace = true
serde.workspace = true
serde_json.workspace = true
tempfile.workspace = true

tokio.workspace = true
tracing.workspace = true
Expand All @@ -31,6 +32,3 @@ ot.workspace = true
paths.workspace = true
sessions.workspace = true
stdlib.workspace = true

[dev-dependencies]
tempfile.workspace = true
20 changes: 20 additions & 0 deletions crates/minimald/git-remote-min
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/sh
# git-remote-min <remote-name> <url>

while read -r cmd arg; do
case "$cmd" in
capabilities)
echo connect
echo # blank line ends the capabilities list
;;
connect)
echo # blank line: connection established
exec ssh -o ProxyCommand="socat - UNIX-CONNECT:$HOME/.local/state/minimal/providers/local-0/ssh.sock" \
-o 'StrictHostKeyChecking=no' -o 'UserKnownHostsFile=/dev/null' \
local "$arg" "$2"
Comment on lines +13 to +14
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 | 🟠 Major | ⚡ Quick win

Re-enable SSH host key verification for push transport.

Line 13 turns off host verification and disables known_hosts persistence, so a spoofed local endpoint can silently impersonate the server and receive pushed data. Please use host key pinning (or at least a dedicated known_hosts file with strict checking) instead of disabling verification.

Suggested hardening
-        exec ssh -o ProxyCommand="socat - UNIX-CONNECT:$HOME/.local/state/minimal/providers/local-0/ssh.sock" \
-		 -o 'StrictHostKeyChecking=no' -o 'UserKnownHostsFile=/dev/null' \
+        exec ssh -o ProxyCommand="socat - UNIX-CONNECT:$HOME/.local/state/minimal/providers/local-0/ssh.sock" \
+		 -o 'StrictHostKeyChecking=yes' -o "UserKnownHostsFile=$HOME/.local/state/minimal/known_hosts" \
 		 local "$arg" "$2"
🤖 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/git-remote-min` around lines 13 - 14, The current SSH
invocation disables host key verification via the flags '-o
'StrictHostKeyChecking=no'' and '-o 'UserKnownHostsFile=/dev/null''; remove
these insecure options and instead enable strict checking and use a dedicated
known_hosts file for this transport. Replace the two flags with something like
'-o StrictHostKeyChecking=yes -o
UserKnownHostsFile=/path/to/transport_known_hosts' (or '-o
StrictHostKeyChecking=accept-new' if you need first-time acceptance), ensure the
code that runs the command (the invocation containing local "$arg" "$2")
creates/populates that known_hosts file or pins the server key before
connecting, and update any helper functions that build SSH options to reference
the new flags and file path.

;;
'')
exit 0
;;
esac
done
221 changes: 220 additions & 1 deletion crates/minimald/src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use russh::{
server::{Msg, Session},
};
use sessions::SessionId;
use tempfile::TempDir;
use tokio::net::unix::pipe;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
Expand All @@ -30,7 +31,7 @@ use tokio::{
};

use crate::{
MINIMAL_SESSION_ID_ENV,
ChannelConfig, MINIMAL_SESSION_ID_ENV,
connection::{ConnectionError, ConnectionHandle},
server::ServerStateHandle,
session::SessionHandle,
Expand Down Expand Up @@ -642,6 +643,10 @@ pub(crate) async fn handle_exec(
};
drop(conn_lock);

if let Some(ident) = argv.strip_prefix("git-receive-pack min://") {
return handle_git_receive(ident, serv, conn, id, session, channel, config).await;
}
Comment on lines +646 to +648
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 | 🟠 Major | ⚡ Quick win

PTY validation is bypassed for git-receive-pack requests.

At Line 645, the early return routes git requests before the PTY rejection at Line 649, so unsupported PTY configs can slip through this path. Keep the same PTY guard for git as normal exec handling.

Suggested fix
 if let Some(ident) = argv.strip_prefix("git-receive-pack min://") {
+    if config.pty.is_some() {
+        tracing::warn!("channel {id}: pty requested but not yet supported");
+        session.channel_failure(id)?;
+        return Ok(());
+    }
     return handle_git_receive(ident, serv, conn, id, session, channel, config).await;
 }
🤖 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/exec.rs` around lines 645 - 647, The git-receive-pack
branch (argv.strip_prefix(...) calling handle_git_receive) returns before the
PTY validation and therefore bypasses the PTY guard; move or duplicate the PTY
validation so that the same PTY rejection logic that runs later is applied
before invoking handle_git_receive. Concretely, ensure the PTY check (the
existing PTY guard logic used for normal exec handling) runs prior to the early
return from the git branch (or insert the same validation immediately before
calling handle_git_receive), referencing argv.strip_prefix("git-receive-pack
min://") and handle_git_receive(...) so the git path follows the same PTY
accept/reject flow as other execs.


if config.pty.is_some() {
tracing::warn!("channel {id}: pty requested but not yet supported",);
session.channel_failure(id)?;
Expand Down Expand Up @@ -714,6 +719,122 @@ pub(crate) async fn handle_exec(
Ok(())
}

async fn handle_git_receive(
ident: &str,
serv: ServerStateHandle,
conn: ConnectionHandle,
id: ChannelId,
session: &mut Session,
channel: Channel<Msg>,
config: ChannelConfig,
) -> Result<(), ConnectionError> {
let session_pred = {
match config.env_vars.get(MINIMAL_SESSION_ID_ENV) {
Some(id_str) => match SessionId::parse_str(id_str) {
Ok(id) => SessionKeyPredicate::Id(id),
Err(_e) => {
tracing::warn!(
value = %id_str,
"git-receive-pack rejected on channel {id}: {MINIMAL_SESSION_ID_ENV} is not a uuid",
);
session.channel_failure(id)?;
return Ok(());
}
},
None => match SessionId::parse_str(ident) {
Ok(id) => SessionKeyPredicate::Id(id),
Err(_e) => SessionKeyPredicate::Name(ident.to_string()),
},
}
};

let mngr = serv.sessions_manager().await;
let session_handle = match mngr.get_session(session_pred).await {
Ok(Some(h)) => h,
Ok(None) => {
tracing::warn!("git-receive-pack rejected: unknown session");
session.channel_failure(id)?;
return Ok(());
}
Err(e) => {
tracing::warn!(error = %e, "git-receive-pack rejected: lookup failed");
session.channel_failure(id)?;
return Ok(());
}
};
session.channel_success(id)?;

spawn(async move {
let workspace = session_handle.workspace_path().await;

let dotgit_dir = workspace.as_utf8_path().join(".git");
if let Ok(false) = tokio::fs::try_exists(&dotgit_dir).await {
// No .git directory exists, so this is likely
// the first push to populate. Create an empty git
// repo, and make sure its configured to checkout
// the ref it recieves.
let res = tokio::process::Command::new("git")
.arg("init")
.current_dir(workspace.as_utf8_path())
.output()
.await;
if let Err(e) = res {
tracing::warn!(error = %e, "git init failed");
channel.close().await.unwrap();
return;
}
}
Comment on lines +771 to +786
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 | 🟠 Major | ⚡ Quick win

Handle .git probe/init failures explicitly before continuing.

At Line 770, try_exists errors are ignored; at Line 776, only execution errors are handled, while non-zero git init exit status still falls through to receive-pack. This can continue with an invalid repo state. Also avoid unwrap() on channel close (Line 778) in this error path.

Suggested fix
-        if let Ok(false) = tokio::fs::try_exists(&dotgit_dir).await {
-            let res = tokio::process::Command::new("git")
-                .arg("init")
-                .current_dir(workspace.as_utf8_path())
-                .output()
-                .await;
-            if let Err(e) = res {
-                tracing::warn!(error = %e, "git init failed");
-                channel.close().await.unwrap();
-                return;
-            }
-        }
+        match tokio::fs::try_exists(&dotgit_dir).await {
+            Ok(false) => {
+                match tokio::process::Command::new("git")
+                    .arg("init")
+                    .current_dir(workspace.as_utf8_path())
+                    .output()
+                    .await
+                {
+                    Ok(out) if out.status.success() => {}
+                    Ok(out) => {
+                        tracing::warn!(status = %out.status, "git init failed with non-zero status");
+                        let _ = channel.close().await;
+                        return;
+                    }
+                    Err(e) => {
+                        tracing::warn!(error = %e, "git init failed");
+                        let _ = channel.close().await;
+                        return;
+                    }
+                }
+            }
+            Ok(true) => {}
+            Err(e) => {
+                tracing::warn!(error = %e, "failed to check .git existence");
+                let _ = channel.close().await;
+                return;
+            }
+        }
🤖 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/exec.rs` around lines 770 - 781, The code ignores errors
from tokio::fs::try_exists(&dotgit_dir), doesn't check git init's exit status,
and unwraps channel.close().await; update the block around try_exists/dotgit_dir
and the Command::new("git") invocation so that: 1) if try_exists returns Err(e)
you log/tracing::warn the error and close the channel (handle close errors
instead of unwrap) then return; 2) after awaiting .output(), check
output.status.success() and if false log the stdout/stderr and close the channel
(again handling close errors) and return; reference the dotgit_dir probe, the
Command::new("git")/.output() result and channel.close().await to locate and fix
the logic before proceeding to receive-pack.

let hooks_tmp = TempDir::new().unwrap();
tokio::fs::OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o755)
.open(hooks_tmp.path().join("post-receive"))
.await
.unwrap()
.write_all(
r#"#!/bin/sh
GIT_DIR_ABS=$(pwd -P)
WORK_TREE=$(dirname "$GIT_DIR_ABS")
unset GIT_DIR GIT_WORK_TREE GIT_QUARANTINE_PATH
g() { git --git-dir="$GIT_DIR_ABS" --work-tree="$WORK_TREE" "$@"; }

while read -r old new ref; do
case "$ref" in refs/heads/*) ;; *) continue ;; esac
branch=${ref#refs/heads/}

if ! g diff --quiet || ! g diff --cached --quiet; then
echo "remote worktree has uncommitted changes; skipping checkout of $branch" >&2
continue
fi
g checkout -f "$branch"
done"#
.as_bytes(),
)
.await
.unwrap();

let exec_task = ExecTask {
conn,
serv,
session: session_handle,
channel_id: id,
exec: TokioExec {
argv: format!(
"git -c core.hooksPath={} receive-pack .",
hooks_tmp.path().to_str().unwrap()
),
Comment on lines +787 to +826
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 | 🟠 Major | ⚡ Quick win

Don't unwrap() hook setup after channel_success.

These unwrap()s run inside the detached git task after the exec request has already been accepted. Any tempdir/fs failure — or a non-UTF-8 temp path at to_str().unwrap() — turns the push into a panic and dropped channel instead of a controlled git failure.

Suggested fix
-        let hooks_tmp = TempDir::new().unwrap();
+        let hooks_tmp = match TempDir::new() {
+            Ok(dir) => dir,
+            Err(e) => {
+                tracing::warn!(error = %e, "failed to create git hooks dir");
+                let _ = channel.close().await;
+                return;
+            }
+        };

Apply the same pattern to the open(...), write_all(...), and to_str() sites before constructing TokioExec.

🤖 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/exec.rs` around lines 787 - 825, The detached git task
currently uses unwrap() when creating/writing the temporary hook file and
calling hooks_tmp.path().to_str().unwrap(), which can panic after
channel_success; change the hook setup in the block that builds
ExecTask/TokioExec to handle and propagate IO/UTF-8 errors instead of
unwrapping: perform fallible operations for TempDir::new,
tokio::fs::OpenOptions::open, file.write_all, and hooks_tmp.path().to_str() with
proper error handling (return Result or send a controlled git failure), e.g.,
capture the error, log it and convert it into a failed exec result that the git
subprocess will see; update the code around hooks_tmp, OpenOptions::open,
write_all, and the construction of TokioExec/argv to use these fallible paths
rather than unwrap().

cwd: workspace,
env: BTreeMap::new(),
},
};
exec_task.run(channel).await;
drop(hooks_tmp);
});

Ok(())
}

#[cfg(test)]
pub(crate) mod testing {
//! Mock `Process` for testing the exec bridge without spawning a
Expand Down Expand Up @@ -1192,5 +1313,103 @@ mod tests {
let observed = std::path::PathBuf::from(observed.trim_end());
assert_eq!(observed, expected);
}

/// End-to-end: `git push min://<session-id>` driven by an
/// OpenSSH process going through a modified `git-remote-min`
/// helper lands the pushed commit in the session workspace, with
/// the post-receive hook checking out the branch on disk.
#[ignore]
#[tokio::test]
async fn git_receive_pack_lands_pushed_commit_in_workspace() {
use std::os::unix::fs::PermissionsExt;

use tempfile::TempDir;
use tokio::process::Command;

async fn run_git(cwd: &std::path::Path, args: &[&str]) {
let out = Command::new("git")
.current_dir(cwd)
.args(args)
.output()
.await
.expect("git should be invocable");
assert!(
out.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr),
);
}

let server = TestServer::new().await;
let sock_dir = TempDir::new().unwrap();
let sock_path = sock_dir.path().join("ssh.sock");
server.listen_on_uds(&sock_path).await;

let mut client = server.connect().await;
let session_id = fresh_session(&mut client).await;

// Drop a `git-remote-min` into a tempdir and prepend that
// tempdir to PATH so `git push min://…` resolves to it. The
// script is the production one with its hard-coded socket
// path swapped for the test server's UDS.
let helpers_dir = TempDir::new().unwrap();
let helper_path = helpers_dir.path().join("git-remote-min");
let template = include_str!("../git-remote-min");
let script = template.replace(
"$HOME/.local/state/minimal/providers/local-0/ssh.sock",
sock_path.to_str().unwrap(),
);
tokio::fs::write(&helper_path, script).await.unwrap();
tokio::fs::set_permissions(&helper_path, std::fs::Permissions::from_mode(0o755))
.await
.unwrap();

// Source repo with a single commit on `main`. Local
// user.email/user.name to keep the test independent of any
// global git config.
let src_dir = TempDir::new().unwrap();
let src_path = src_dir.path();
run_git(src_path, &["init", "-q", "-b", "main"]).await;
run_git(src_path, &["config", "user.email", "t@example.com"]).await;
run_git(src_path, &["config", "user.name", "Test"]).await;
tokio::fs::write(src_path.join("hello.txt"), b"hi there\n")
.await
.unwrap();
run_git(src_path, &["add", "hello.txt"]).await;
run_git(src_path, &["commit", "-q", "-m", "first commit"]).await;

let inherited_path = std::env::var("PATH").unwrap_or_default();
let path_with_helper = format!("{}:{}", helpers_dir.path().display(), inherited_path);
let url = format!("min://{session_id}");
let push = Command::new("git")
.current_dir(src_path)
.env("PATH", &path_with_helper)
.args(["push", &url, "main"])
.output()
.await
.expect("git push should run");
assert!(
push.status.success(),
"git push failed: stdout={} stderr={}",
String::from_utf8_lossy(&push.stdout),
String::from_utf8_lossy(&push.stderr),
);

// The post-receive hook checks out `refs/heads/main` into
// the worktree, so the pushed file should be readable from
// the session workspace.
let mngr = server.state.sessions_manager().await;
let session_handle = mngr
.get_session(SessionKeyPredicate::Id(session_id))
.await
.unwrap()
.expect("session should be retrievable");
let workspace = session_handle.workspace_path().await;
let pushed = workspace.as_utf8_path().join("hello.txt");
let contents = tokio::fs::read(&pushed)
.await
.unwrap_or_else(|e| panic!("reading pushed file {pushed} failed: {e}"));
assert_eq!(contents, b"hi there\n");
}
}
}
24 changes: 23 additions & 1 deletion crates/minimald/src/test_harness.rs
7923
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#![cfg(test)]

use std::path::Path;
use std::sync::Arc;

use camino::Utf8PathBuf;
Expand All @@ -25,7 +26,7 @@ use russh::keys::ssh_key;
use sessions::SessionId;
use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::net::{UnixListener, UnixStream};

use crate::connection::Connection;
use crate::rpc::OneshotSshRpc;
Expand Down Expand Up @@ -106,6 +107,27 @@ impl TestServer {

TestClient { handle }
}

/// Binds a `UnixListener` at `sock` and spawns an accept loop wired
/// through the same russh stack `connect()` uses, so external clients
/// (e.g. an OpenSSH process driven by `git push`) can dial the test
/// server over a real UDS rather than the in-memory pair.
pub(crate) async fn listen_on_uds(&self, sock: &Path) {
let listener = UnixListener::bind(sock).unwrap();
let russh_config = self.russh_config.clone();
let state = self.state.clone();
tokio::spawn(async move {
while let Ok((socket, _)) = listener.accept().await {
let russh_config = russh_config.clone();
let state = state.clone();
tokio::spawn(async move {
let (_conn, session_fut) =
Connection::from_socket(socket, russh_config, state, true).await;
let _ = session_fut.await;
});
}
});
}
}

/// An authenticated client connection against a [`TestServer`].
Expand Down
0