interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-git / tests / h1_hostile_repo.rs

360 lines · 13530 bytes Raw Blame History
1//! ADR 0003 step H1 (issue #48): a crafted repository must not hang the native reader, make
2//! it read outside the repository, or make it allocate without bound (review of PR #90,
3//! findings B1 and B2). Every case calls only `GitRepository::open` and `full_history`, the
4//! import entry points. The system `git` builds ordinary fixture history; the hostile parts
5//! (a pipe, links, a delta bomb pack) are made by hand.
6//!
7//! A case that would block (a pipe) runs in a thread with a deadline, so a regression fails
8//! the test instead of hanging the test runner.
9
10use sha1::{Digest, Sha1};
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14use std::sync::mpsc;
15use std::time::Duration;
16use synapse_core::{GitOid, RefusalCode, SynapseResult};
17use synapse_git::pack::{crc32, write_idx, PackIndexEntry};
18use synapse_git::{zlib_compress_store, GitRepository};
19
20fn temp_dir(label: &str) -> PathBuf {
21 let dir = std::env::temp_dir().join(format!(
22 "synapse-h1-hostile-{label}-{}-{}",
23 std::process::id(),
24 std::time::SystemTime::now()
25 .duration_since(std::time::UNIX_EPOCH)
26 .unwrap()
27 .as_nanos()
28 ));
29 fs::create_dir_all(&dir).unwrap();
30 dir
31}
32
33fn git(dir: &Path, args: &[&str]) -> String {
34 let out = Command::new("git")
35 .arg("-C")
36 .arg(dir)
37 .args(args)
38 .env("GIT_CONFIG_NOSYSTEM", "1")
39 .env("GIT_CONFIG_GLOBAL", "/dev/null")
40 .env("GIT_AUTHOR_NAME", "Fixture Author")
41 .env("GIT_AUTHOR_EMAIL", "author@fixture.invalid")
42 .env("GIT_AUTHOR_DATE", "1700000000 +0000")
43 .env("GIT_COMMITTER_NAME", "Fixture Committer")
44 .env("GIT_COMMITTER_EMAIL", "committer@fixture.invalid")
45 .env("GIT_COMMITTER_DATE", "1700000000 +0000")
46 .output()
47 .unwrap();
48 assert!(
49 out.status.success(),
50 "git {args:?} failed: {}",
51 String::from_utf8_lossy(&out.stderr)
52 );
53 String::from_utf8(out.stdout).unwrap().trim().to_string()
54}
55
56/// A small repository with two commits on `main`; returns its `.git` directory and the tip.
57fn small_repo(label: &str) -> (PathBuf, PathBuf, String) {
58 let root = temp_dir(label);
59 let work = root.join("work");
60 fs::create_dir_all(&work).unwrap();
61 git(&work, &["init", "-q", "-b", "main"]);
62 fs::write(work.join("a.txt"), b"one\n").unwrap();
63 git(&work, &["add", "-A"]);
64 git(&work, &["commit", "-q", "-m", "one"]);
65 fs::write(work.join("a.txt"), b"two\n").unwrap();
66 git(&work, &["add", "-A"]);
67 git(&work, &["commit", "-q", "-m", "two"]);
68 let tip = git(&work, &["rev-parse", "HEAD"]);
69 (root, work.join(".git"), tip)
70}
71
72fn read_history(git_dir: &Path) -> SynapseResult<usize> {
73 let mut repo = GitRepository::open(git_dir)?;
74 Ok(repo.full_history()?.objects.len())
75}
76
77fn assert_refused(result: SynapseResult<usize>, code: RefusalCode, case: &str) {
78 match result {
79 Err(e) => assert_eq!(e.code, code, "{case}: refused with the wrong code: {e}"),
80 Ok(n) => panic!("{case}: read {n} objects instead of refusing"),
81 }
82}
83
84/// Run `full_history` on `git_dir` in a thread. If it has not returned within `deadline`,
85/// open `pipe` for writing (which releases a reader blocked opening it) and fail.
86fn read_history_with_deadline(git_dir: &Path, pipe: &Path, case: &str) -> SynapseResult<usize> {
87 let (tx, rx) = mpsc::channel();
88 let dir = git_dir.to_path_buf();
89 let handle = std::thread::spawn(move || {
90 let _ = tx.send(read_history(&dir));
91 });
92 match rx.recv_timeout(Duration::from_secs(10)) {
93 Ok(result) => {
94 handle.join().unwrap();
95 result
96 }
97 Err(_) => {
98 // Release the blocked open so the thread ends, then fail.
99 drop(fs::OpenOptions::new().write(true).open(pipe));
100 let _ = rx.recv_timeout(Duration::from_secs(10));
101 panic!("{case}: full_history blocked on a pipe for more than 10 s");
102 }
103 }
104}
105
106fn mkfifo(path: &Path) {
107 let status = Command::new("mkfifo").arg(path).status().unwrap();
108 assert!(status.success(), "mkfifo {}", path.display());
109}
110
111#[test]
112fn h1_hostile_fifo_reference_is_refused_without_blocking() {
113 let (_root, git_dir, _) = small_repo("fifo-ref");
114 let pipe = git_dir.join("refs/heads/pipe");
115 mkfifo(&pipe);
116 let result = read_history_with_deadline(&git_dir, &pipe, "FIFO ref");
117 assert_refused(result, RefusalCode::PathInvalid, "FIFO ref");
118}
119
120#[test]
121fn h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking() {
122 for name in ["packed-refs", "HEAD"] {
123 let (_root, git_dir, _) = small_repo("fifo-file");
124 let pipe = git_dir.join(name);
125 let _ = fs::remove_file(&pipe);
126 mkfifo(&pipe);
127 let result = read_history_with_deadline(&git_dir, &pipe, name);
128 assert_refused(result, RefusalCode::PathInvalid, name);
129 }
130}
131
132#[test]
133fn h1_hostile_fifo_loose_object_is_refused_without_blocking() {
134 let (_root, git_dir, tip) = small_repo("fifo-object");
135 let path = git_dir.join("objects").join(&tip[..2]).join(&tip[2..]);
136 fs::remove_file(&path).unwrap();
137 mkfifo(&path);
138 let result = read_history_with_deadline(&git_dir, &path, "FIFO loose object");
139 assert_refused(result, RefusalCode::PathInvalid, "FIFO loose object");
140}
141
142#[test]
143fn h1_hostile_reference_linked_to_dev_zero_is_refused() {
144 let (_root, git_dir, _) = small_repo("dev-zero");
145 std::os::unix::fs::symlink("/dev/zero", git_dir.join("refs/heads/zero")).unwrap();
146 assert_refused(
147 read_history(&git_dir),
148 RefusalCode::PathInvalid,
149 "ref -> /dev/zero",
150 );
151}
152
153#[test]
154fn h1_hostile_reference_linked_outside_the_repository_is_refused() {
155 let (root, git_dir, tip) = small_repo("outside-link");
156 // A file outside the repository that holds a valid object ID: following the link would
157 // read it as a reference.
158 let outside = root.join("outside-ref");
159 fs::write(&outside, format!("{tip}\n")).unwrap();
160 std::os::unix::fs::symlink(&outside, git_dir.join("refs/heads/out")).unwrap();
161 assert_refused(
162 read_history(&git_dir),
163 RefusalCode::PathInvalid,
164 "ref -> file outside",
165 );
166 // A linked directory under refs/ is refused the same way (no walk into the host tree).
167 let (_root2, git_dir2, _) = small_repo("outside-dir");
168 std::os::unix::fs::symlink("/dev", git_dir2.join("refs/dev")).unwrap();
169 assert_refused(
170 read_history(&git_dir2),
171 RefusalCode::PathInvalid,
172 "refs/dev -> /dev",
173 );
174}
175
176#[test]
177fn h1_hostile_linked_object_fanout_directory_is_refused() {
178 // Re-review of PR #90, N1: `objects/ab` replaced by a link to a directory outside the
179 // repository that holds the very same object file. Following the link would read it.
180 let (root, git_dir, tip) = small_repo("fanout-link");
181 let fanout = git_dir.join("objects").join(&tip[..2]);
182 let outside = root.join("outside-fanout");
183 fs::rename(&fanout, &outside).unwrap();
184 std::os::unix::fs::symlink(&outside, &fanout).unwrap();
185 assert_refused(
186 read_history(&git_dir),
187 RefusalCode::PathInvalid,
188 "objects/xx -> directory outside",
189 );
190}
191
192#[test]
193fn h1_hostile_oversized_reference_file_is_refused() {
194 let (_root, git_dir, tip) = small_repo("big-ref");
195 let mut text = format!("{tip}\n");
196 text.push_str(&" ".repeat(1 << 20));
197 fs::write(git_dir.join("refs/heads/big"), text).unwrap();
198 assert_refused(
199 read_history(&git_dir),
200 RefusalCode::QuotaPayloadTooLarge,
201 "1 MiB ref",
202 );
203}
204
205#[test]
206fn h1_detached_head_commit_is_collected() {
207 let (_root, git_dir, _) = small_repo("detached");
208 let work = git_dir.parent().unwrap();
209 git(work, &["checkout", "-q", "--detach"]);
210 fs::write(work.join("a.txt"), b"detached\n").unwrap();
211 git(work, &["add", "-A"]);
212 git(work, &["commit", "-q", "-m", "only on a detached HEAD"]);
213 let detached = GitOid::from_hex(&git(work, &["rev-parse", "HEAD"])).unwrap();
214 let mut repo = GitRepository::open(&git_dir).unwrap();
215 let history = repo.full_history().unwrap();
216 assert!(
217 history.objects.contains_key(&detached),
218 "a commit reachable only from a detached HEAD was dropped"
219 );
220 // Git's own view of everything reachable includes it.
221 let all = git(work, &["rev-list", "--all", "--objects"]);
222 assert_eq!(all.lines().count(), history.objects.len());
223}
224
225/// The Git blob ID of `base` repeated `copies` times then the byte `tail`, from the system
226/// `git hash-object` (the oracle; hashing 256 MiB natively in a debug test build is slow).
227fn git_hash_blob(base: &[u8], copies: u64, tail: u8) -> GitOid {
228 use std::io::Write;
229 let mut child = Command::new("git")
230 .args(["hash-object", "--stdin"])
231 .env("GIT_CONFIG_NOSYSTEM", "1")
232 .env("GIT_CONFIG_GLOBAL", "/dev/null")
233 .stdin(std::process::Stdio::piped())
234 .stdout(std::process::Stdio::piped())
235 .spawn()
236 .unwrap();
237 {
238 let mut stdin = child.stdin.take().unwrap();
239 for _ in 0..copies {
240 stdin.write_all(base).unwrap();
241 }
242 stdin.write_all(&[tail]).unwrap();
243 }
244 let out = child.wait_with_output().unwrap();
245 assert!(out.status.success());
246 GitOid::from_hex(String::from_utf8(out.stdout).unwrap().trim()).unwrap()
247}
248
249fn entry_header(pack_type: u8, size: u64) -> Vec<u8> {
250 let mut out = vec![(pack_type << 4) | (size & 0x0f) as u8];
251 let mut rest = size >> 4;
252 while rest != 0 {
253 *out.last_mut().unwrap() |= 0x80;
254 out.push((rest & 0x7f) as u8);
255 rest >>= 7;
256 }
257 out
258}
259
260fn size_varint(mut n: u64, out: &mut Vec<u8>) {
261 loop {
262 let byte = (n & 0x7f) as u8;
263 n >>= 7;
264 if n == 0 {
265 out.push(byte);
266 return;
267 }
268 out.push(byte | 0x80);
269 }
270}
271
272fn ofs_back(back: u64) -> Vec<u8> {
273 let mut n = back;
274 let mut out = vec![(n & 0x7f) as u8];
275 n >>= 7;
276 while n != 0 {
277 n -= 1;
278 out.push(0x80 | (n & 0x7f) as u8);
279 n >>= 7;
280 }
281 out.reverse();
282 out
283}
284
285/// A bare repository whose one pack holds a 64 KiB blob and `deltas` offset deltas against it,
286/// each about 4 KiB long and resolving to 256 MiB plus one distinguishing byte, each named by
287/// a tag. Returns the repository and the pack's size in bytes.
288fn delta_bomb(label: &str, deltas: u8) -> (PathBuf, usize) {
289 let dir = temp_dir(label);
290 let base: Vec<u8> = (0..65_536u32).map(|i| (i * 7 % 251) as u8).collect();
291 let copies = 4096u64;
292 let result_size = copies * base.len() as u64 + 1;
293 let mut pack = b"PACK".to_vec();
294 pack.extend_from_slice(&2u32.to_be_bytes());
295 pack.extend_from_slice(&(1 + u32::from(deltas)).to_be_bytes());
296 let mut entries = Vec::new();
297
298 let start = pack.len();
299 pack.extend_from_slice(&entry_header(3, base.len() as u64));
300 pack.extend_from_slice(&zlib_compress_store(&base));
301 entries.push(PackIndexEntry {
302 oid: GitOid::compute_git_object("blob", &base),
303 offset: start as u64,
304 crc32: crc32(&pack[start..]),
305 });
306 let mut refs = Vec::new();
307 for i in 0..deltas {
308 let mut delta = Vec::new();
309 size_varint(base.len() as u64, &mut delta);
310 size_varint(result_size, &mut delta);
311 // Copy op with no offset or size bytes: copy 0x10000 bytes from offset 0.
312 delta.extend(std::iter::repeat_n(0x80u8, copies as usize));
313 delta.extend_from_slice(&[1, i]);
314 let at = pack.len();
315 pack.extend_from_slice(&entry_header(6, delta.len() as u64));
316 pack.extend_from_slice(&ofs_back((at - start) as u64));
317 pack.extend_from_slice(&zlib_compress_store(&delta));
318 let oid = git_hash_blob(&base, copies, i);
319 entries.push(PackIndexEntry {
320 oid,
321 offset: at as u64,
322 crc32: crc32(&pack[at..]),
323 });
324 refs.push((format!("refs/tags/t{i}"), oid));
325 }
326 let checksum: [u8; 20] = Sha1::digest(&pack).into();
327 pack.extend_from_slice(&checksum);
328 let idx = write_idx(&entries, GitOid(checksum));
329 let pack_dir = dir.join("objects/pack");
330 fs::create_dir_all(&pack_dir).unwrap();
331 fs::create_dir_all(dir.join("refs/tags")).unwrap();
332 let name = format!("pack-{}", GitOid(checksum).to_hex());
333 fs::write(pack_dir.join(format!("{name}.pack")), &pack).unwrap();
334 fs::write(pack_dir.join(format!("{name}.idx")), &idx).unwrap();
335 for (name, oid) in refs {
336 fs::write(dir.join(name), format!("{}\n", oid.to_hex())).unwrap();
337 }
338 fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
339 (dir, pack.len())
340}
341
342#[test]
343fn h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved() {
344 // Five deltas of 256 MiB each from a pack under 100 KB: 1.25 GiB declared, over the
345 // default 1 GiB budget. The refusal must come from the declared sizes, before anything
346 // is resolved, so this test allocates almost nothing.
347 let (dir, pack_bytes) = delta_bomb("delta-bomb", 5);
348 assert!(pack_bytes < 100_000, "bomb pack is {pack_bytes} bytes");
349 let started = std::time::Instant::now();
350 assert_refused(
351 read_history(&dir),
352 RefusalCode::QuotaPayloadTooLarge,
353 "delta bomb",
354 );
355 assert!(
356 started.elapsed() < Duration::from_secs(5),
357 "refusal took {:?}; it must not resolve the deltas",
358 started.elapsed()
359 );
360}