Repository navigation
feat(minimald): handle git pushes natively #347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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" | ||
| ;; | ||
| '') | ||
| exit 0 | ||
| ;; | ||
| esac | ||
| done | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
|
@@ -30,7 +31,7 @@ use tokio::{ | |
| }; | ||
|
|
||
| use crate::{ | ||
| MINIMAL_SESSION_ID_ENV, | ||
| ChannelConfig, MINIMAL_SESSION_ID_ENV, | ||
| connection::{ConnectionError, ConnectionHandle}, | ||
| server::ServerStateHandle, | ||
| session::SessionHandle, | ||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. PTY validation is bypassed for 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 |
||
|
|
||
| if config.pty.is_some() { | ||
| tracing::warn!("channel {id}: pty requested but not yet supported",); | ||
| session.channel_failure(id)?; | ||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handle At Line 770, 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 |
||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't These 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 🤖 Prompt for AI Agents |
||
| 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 | ||
|
|
@@ -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"); | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
🤖 Prompt for AI Agents