forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

ssh_e2e.rs293 lines, 9.2 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::net::TcpListener as StdListener;
3use std::path::{Path, PathBuf};
4use std::process::Output;
5use std::time::Duration;
6
7use forge_git::GitService;
8use forge_ssh::{GitBackend, LfsOperation, RepoPath, SshConfig};
9use russh::keys::PublicKey;
10use tokio::process::Command;
11
12struct TestBackend {
13 algorithm: String,
14 blob: Vec<u8>,
15 user_id: String,
16 repos: HashMap<String, PathBuf>,
17}
18
19impl GitBackend for TestBackend {
20 async fn authenticate_key(&self, algorithm: &str, key_blob: &[u8]) -> Option<String> {
21 (algorithm == self.algorithm && key_blob == self.blob.as_slice())
22 .then(|| self.user_id.clone())
23 }
24
25 async fn prepare(
26 &self,
27 user_id: &str,
28 service: GitService,
29 repo_path: &RepoPath,
30 _git_protocol: Option<&str>,
31 ) -> Result<Command, String> {
32 if user_id != self.user_id {
33 return Err("forbidden".to_owned());
34 }
35 let repo = self
36 .repos
37 .get(&format!("{}/{}", repo_path.owner, repo_path.name))
38 .ok_or_else(|| "repository not found".to_owned())?;
39 let mut cmd = Command::new("git");
40 cmd.arg(service.name().trim_start_matches("git-")).arg(repo);
41 Ok(cmd)
42 }
43
44 async fn lfs_authenticate(
45 &self,
46 user_id: &str,
47 repo_path: &RepoPath,
48 operation: LfsOperation,
49 ) -> Result<String, String> {
50 let repo = format!("{}/{}", repo_path.owner, repo_path.name);
51 if user_id != self.user_id || !self.repos.contains_key(&repo) {
52 return Err("repository not found".to_owned());
53 }
54 let op = match operation {
55 LfsOperation::Download => "download",
56 LfsOperation::Upload => "upload",
57 };
58 Ok(format!(
59 r#"{{"href":"http://lfs.test/{repo}.git/info/lfs","header":{{"Authorization":"RemoteAuth {op}"}},"expires_in":3600}}"#
60 ))
61 }
62}
63
64fn on_path(tool: &str) -> bool {
65 std::env::var_os("PATH")
66 .map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(tool).is_file()))
67 .unwrap_or(false)
68}
69
70fn free_port() -> u16 {
71 let listener = StdListener::bind("127.0.0.1:0").expect("bind free port");
72 listener.local_addr().expect("local addr").port()
73}
74
75fn ssh_command(key: &Path, port: u16) -> String {
76 format!(
77 "ssh -i {} -p {} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes",
78 key.display(),
79 port
80 )
81}
82
83async fn check(label: &str, cmd: &mut Command) -> Output {
84 let out = cmd
85 .stdin(std::process::Stdio::null())
86 .output()
87 .await
88 .expect("spawn");
89 assert!(
90 out.status.success(),
91 "{label} failed: {}\n{}",
92 String::from_utf8_lossy(&out.stdout),
93 String::from_utf8_lossy(&out.stderr)
94 );
95 out
96}
97
98async fn ssh_exec(key: &Path, port: u16, remote_cmd: &str) -> Output {
99 Command::new("ssh")
100 .args(["-i"])
101 .arg(key)
102 .args(["-p", &port.to_string()])
103 .args([
104 "-o",
105 "StrictHostKeyChecking=no",
106 "-o",
107 "UserKnownHostsFile=/dev/null",
108 "-o",
109 "IdentitiesOnly=yes",
110 ])
111 .arg("git@127.0.0.1")
112 .arg(remote_cmd)
113 .stdin(std::process::Stdio::null())
114 .output()
115 .await
116 .expect("spawn ssh")
117}
118
119async fn ssh_exec_fails(key: &Path, port: u16, remote_cmd: &str) -> Output {
120 let out = ssh_exec(key, port, remote_cmd).await;
121 assert!(!out.status.success(), "expected {remote_cmd:?} to fail");
122 out
123}
124
125async fn wait_for_port(port: u16) {
126 for _ in 0..100 {
127 if tokio::net::TcpStream::connect(("127.0.0.1", port))
128 .await
129 .is_ok()
130 {
131 return;
132 }
133 tokio::time::sleep(Duration::from_millis(50)).await;
134 }
135 panic!("ssh server did not start listening on port {port}");
136}
137
138#[tokio::test(flavor = "multi_thread")]
139async fn clone_push_clone_over_ssh() {
140 for tool in ["ssh", "ssh-keygen", "git"] {
141 if !on_path(tool) {
142 eprintln!("SKIP ssh_e2e: `{tool}` not found on PATH");
143 return;
144 }
145 }
146
147 let tmp = tempfile::tempdir().expect("tempdir");
148 let root = tmp.path();
149
150 let key = root.join("id");
151 let other = root.join("other");
152 for path in [&key, &other] {
153 check(
154 "ssh-keygen",
155 Command::new("ssh-keygen")
156 .args(["-t", "ed25519", "-N", "", "-q", "-f"])
157 .arg(path),
158 )
159 .await;
160 }
161 let pub_line = std::fs::read_to_string(root.join("id.pub")).expect("read pub key");
162 let public = PublicKey::from_openssh(pub_line.trim()).expect("parse pub key");
163 let algorithm = public.algorithm().as_str().to_owned();
164 let blob = public.to_bytes().expect("key blob");
165
166 let bare = root.join("remote").join("test").join("repo.git");
167 std::fs::create_dir_all(bare.parent().expect("parent")).expect("mkdir");
168 check(
169 "git init --bare",
170 Command::new("git")
171 .args(["init", "--bare", "-q", "--initial-branch=main"])
172 .arg(&bare),
173 )
174 .await;
175
176 let backend = TestBackend {
177 algorithm,
178 blob,
179 user_id: "user-1".to_owned(),
180 repos: HashMap::from([("test/repo".to_owned(), bare.clone())]),
181 };
182
183 let port = free_port();
184 let host_key = root.join("state").join("ssh_host_ed25519_key");
185 let config = SshConfig {
186 listen: ([127, 0, 0, 1], port).into(),
187 host_key_path: host_key.clone(),
188 auth_rejection_time: Duration::ZERO,
189 };
190 tokio::spawn(forge_ssh::run(config, std::sync::Arc::new(backend)));
191 wait_for_port(port).await;
192
193 use std::os::unix::fs::PermissionsExt;
194 let mode = std::fs::metadata(&host_key)
195 .expect("host key exists")
196 .permissions()
197 .mode();
198 assert_eq!(mode & 0o777, 0o600, "host key must be 0600");
199
200 let ssh_env = ssh_command(&key, port);
201 let url = format!("ssh://git@127.0.0.1:{port}/test/repo.git");
202
203 let lfs = ssh_exec(&key, port, "git-lfs-authenticate 'test/repo.git' upload").await;
204 assert!(lfs.status.success(), "lfs authenticate failed: {lfs:?}");
205 let reply = String::from_utf8_lossy(&lfs.stdout);
206 assert!(
207 reply.contains("http://lfs.test/test/repo.git/info/lfs")
208 && reply.contains("RemoteAuth upload"),
209 "unexpected reply: {reply}"
210 );
211 ssh_exec_fails(&key, port, "git-lfs-authenticate 'test/missing' download").await;
212 ssh_exec_fails(&key, port, "git-lfs-authenticate '../test/repo' download").await;
213 ssh_exec_fails(&other, port, "git-lfs-authenticate 'test/repo' download").await;
214
215 let clone1 = root.join("clone1");
216 check(
217 "clone",
218 Command::new("git")
219 .env("GIT_SSH_COMMAND", &ssh_env)
220 .arg("clone")
221 .arg(&url)
222 .arg(&clone1),
223 )
224 .await;
225
226 check(
227 "symbolic-ref",
228 Command::new("git")
229 .current_dir(&clone1)
230 .args(["symbolic-ref", "HEAD", "refs/heads/main"]),
231 )
232 .await;
233 std::fs::write(clone1.join("hello.txt"), "hello from forge\n").expect("write file");
234 let git_in = |args: &[&str]| {
235 let mut c = Command::new("git");
236 c.current_dir(&clone1)
237 .env("GIT_SSH_COMMAND", &ssh_env)
238 .env("GIT_AUTHOR_NAME", "test")
239 .env("GIT_AUTHOR_EMAIL", "test@example.invalid")
240 .env("GIT_COMMITTER_NAME", "test")
241 .env("GIT_COMMITTER_EMAIL", "test@example.invalid")
242 .args(args);
243 c
244 };
245 check("add", &mut git_in(&["add", "hello.txt"])).await;
246 check("commit", &mut git_in(&["commit", "-q", "-m", "add hello"])).await;
247 check("push", &mut git_in(&["push", "-q", "origin", "main"])).await;
248
249 let clone2 = root.join("clone2");
250 check(
251 "second clone",
252 Command::new("git")
253 .env("GIT_SSH_COMMAND", &ssh_env)
254 .arg("clone")
255 .arg(&url)
256 .arg(&clone2),
257 )
258 .await;
259 let content = std::fs::read_to_string(clone2.join("hello.txt")).expect("pushed file exists");
260 assert_eq!(content, "hello from forge\n");
261
262 let bad_env = ssh_command(&other, port);
263 let rejected = Command::new("git")
264 .env("GIT_SSH_COMMAND", &bad_env)
265 .arg("clone")
266 .arg(&url)
267 .arg(root.join("clone3"))
268 .stdin(std::process::Stdio::null())
269 .output()
270 .await
271 .expect("spawn git");
272 assert!(!rejected.status.success(), "unknown key must not clone");
273
274 let injections = [
275 "git-upload-pack '--help'",
276 "git-upload-pack '/test/repo'; id",
277 "git-upload-pack '../x/y'",
278 "git-upload-pack 'test/repo/extra'",
279 "git-upload-archive '/test/repo'",
280 ];
281 for cmd in injections {
282 let out = ssh_exec_fails(&key, port, cmd).await;
283 let stderr = String::from_utf8_lossy(&out.stderr);
284 assert!(
285 stderr.contains("malformed repository path") || stderr.contains("unsupported command"),
286 "unexpected rejection for {cmd:?}: {stderr}"
287 );
288 assert!(out.stdout.is_empty(), "no stdout for rejected {cmd:?}");
289 }
290
291 let out = ssh_exec_fails(&key, port, "git-upload-pack '/test/missing.git'").await;
292 assert!(String::from_utf8_lossy(&out.stderr).contains("repository not found"));
293}