Skip to main content

fluidattacks_core_git/
download.rs

1use rustix::fs::{renameat_with, RenameFlags, CWD};
2use std::io;
3use std::num::NonZeroUsize;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6use tokio::io::{AsyncWriteExt, BufWriter};
7use tracing::warn;
8
9use crate::errors::{DownloadError, ExtractError, FetchError, PruneError};
10
11const TIMEOUTS: Timeouts = Timeouts {
12    connect: Duration::from_secs(30),
13    total: Duration::from_hours(1),
14};
15const DEFAULT_DOWNLOAD_BUFFER_SIZE: usize = 64 * 1024;
16const MAX_DOWNLOAD_BUFFER_SIZE: usize = 16 * 1024 * 1024;
17const WORK_PREFIX: &str = ".fluidattacks_";
18const ARCHIVE_NAME: &str = "repo.tar.gz";
19const EXTRACTED_NAME: &str = "extracted";
20const GIT_DIR_DATA: [&str; 6] = ["HEAD", "index", "objects", "packed-refs", "refs", "shallow"];
21// Inside `objects/`, these point git at object stores elsewhere on disk.
22const OBJECT_STORE_POINTERS: [&str; 2] = ["alternates", "http-alternates"];
23const TRUSTED_CONFIG: &str = "[core]\nrepositoryformatversion = 0\nbare = false\n";
24
25struct Timeouts {
26    connect: Duration,
27    total: Duration,
28}
29
30fn resolve_buffer_size(buffer_size: Option<NonZeroUsize>) -> usize {
31    buffer_size.map_or(DEFAULT_DOWNLOAD_BUFFER_SIZE, |size| {
32        size.get().min(MAX_DOWNLOAD_BUFFER_SIZE)
33    })
34}
35
36fn parse_url(url: &str) -> Result<url::Url, FetchError> {
37    let parsed = url::Url::parse(url).map_err(|error| FetchError::InvalidUrl {
38        url: url.to_owned(),
39        reason: error.to_string(),
40    })?;
41    if !matches!(parsed.scheme(), "http" | "https") {
42        return Err(FetchError::NonHttpUrl(url.to_owned()));
43    }
44    Ok(parsed)
45}
46
47// A presigned url carries its signature in the query, so no error keeps it.
48fn request_error(error: reqwest::Error) -> FetchError {
49    let error = error.without_url();
50    if error.is_connect() {
51        return if error.is_timeout() {
52            FetchError::ConnectTimeout(error)
53        } else {
54            FetchError::Connect(error)
55        };
56    }
57    if error.is_timeout() {
58        return FetchError::Timeout(error);
59    }
60    let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(&error);
61    let mut socket = None;
62    while let Some(current) = cause {
63        if let Some(hyper) = current.downcast_ref::<hyper::Error>() {
64            if hyper.is_incomplete_message() {
65                return FetchError::Disconnected(error);
66            }
67            if hyper.is_parse() {
68                return FetchError::Malformed(error);
69            }
70        }
71        if let Some(io) = current.downcast_ref::<io::Error>() {
72            socket = Some(io);
73        }
74        cause = current.source();
75    }
76    match socket {
77        Some(io) => FetchError::Socket {
78            reset: io.kind() == io::ErrorKind::ConnectionReset,
79            errno: io.raw_os_error(),
80            source: error,
81        },
82        None => FetchError::Other(error),
83    }
84}
85
86fn body_error(error: reqwest::Error) -> FetchError {
87    let error = error.without_url();
88    if error.is_timeout() {
89        FetchError::BodyTimeout(error)
90    } else {
91        FetchError::BodyCut(error)
92    }
93}
94
95async fn fetch_to(
96    url: &str,
97    path: &Path,
98    buffer_size: usize,
99    timeouts: Timeouts,
100) -> Result<(), DownloadError> {
101    let url = parse_url(url)?;
102    // As the python's aiohttp, the environment's proxy is ignored.
103    let client = reqwest::Client::builder()
104        .no_proxy()
105        .timeout(timeouts.total)
106        .connect_timeout(timeouts.connect)
107        .build()
108        .map_err(FetchError::Other)?;
109    let mut response = client.get(url).send().await.map_err(request_error)?;
110    let status = response.status();
111    if status != reqwest::StatusCode::OK {
112        return Err(FetchError::Status(status).into());
113    }
114
115    let file = tokio::fs::File::create(path)
116        .await
117        .map_err(DownloadError::Write)?;
118    let mut writer = BufWriter::with_capacity(buffer_size, file);
119    while let Some(chunk) = response.chunk().await.map_err(body_error)? {
120        for slice in chunk.chunks(buffer_size) {
121            writer
122                .write_all(slice)
123                .await
124                .map_err(DownloadError::Write)?;
125        }
126    }
127    writer.flush().await.map_err(DownloadError::Write)?;
128    Ok(())
129}
130
131async fn extracted_dir(extracted: &Path) -> Result<PathBuf, ExtractError> {
132    let mut entries = tokio::fs::read_dir(extracted)
133        .await
134        .map_err(ExtractError::Io)?;
135    let mut dirs = Vec::new();
136    while let Some(entry) = entries.next_entry().await.map_err(ExtractError::Io)? {
137        if entry.file_type().await.is_ok_and(|kind| kind.is_dir()) {
138            dirs.push(entry.path());
139        }
140    }
141    // The producers pack a single top-level directory.
142    dirs.sort();
143
144    if dirs.len() > 1 {
145        warn!(
146            count = dirs.len(),
147            "multiple directories found in archive, using the first one"
148        );
149    }
150    dirs.into_iter().next().ok_or_else(|| {
151        ExtractError::NoRepository("no directory found in the extracted archive".to_owned())
152    })
153}
154
155// A `.git` file or link would redirect git to a repository outside the archive.
156async fn keep_only_history(repo: &Path) -> Result<(), ExtractError> {
157    let git_dir = repo.join(".git");
158    let is_dir = tokio::fs::symlink_metadata(&git_dir)
159        .await
160        .is_ok_and(|meta| meta.is_dir());
161    if !is_dir {
162        return Err(ExtractError::NoRepository(
163            "no .git directory found in the extracted archive".to_owned(),
164        ));
165    }
166
167    let mut entries = tokio::fs::read_dir(&git_dir)
168        .await
169        .map_err(ExtractError::Io)?;
170    while let Some(entry) = entries.next_entry().await.map_err(ExtractError::Io)? {
171        if GIT_DIR_DATA.iter().any(|kept| entry.file_name() == *kept) {
172            continue;
173        }
174        let path = entry.path();
175        let removed = if entry.file_type().await.is_ok_and(|kind| kind.is_dir()) {
176            tokio::fs::remove_dir_all(&path).await
177        } else {
178            tokio::fs::remove_file(&path).await
179        };
180        removed.map_err(ExtractError::Io)?;
181    }
182    for pointer in OBJECT_STORE_POINTERS {
183        match tokio::fs::remove_file(git_dir.join("objects/info").join(pointer)).await {
184            Err(error) if error.kind() != io::ErrorKind::NotFound => {
185                return Err(ExtractError::Io(error));
186            }
187            _ => {}
188        }
189    }
190
191    tokio::fs::write(git_dir.join("config"), TRUSTED_CONFIG)
192        .await
193        .map_err(ExtractError::Io)
194}
195
196fn prune(repo: &Path, git_ignore: &[String]) -> Result<(), DownloadError> {
197    super::fs::remove_symlinks(repo).map_err(PruneError::from)?;
198    super::fs::delete_gitignored_files(repo, git_ignore)?;
199    Ok(())
200}
201
202// One swap with no await inside, so `dest` holds the previous tree or the
203// new one, never neither.
204fn place(repo: &Path, dest: &Path) -> Result<(), DownloadError> {
205    match std::fs::symlink_metadata(dest) {
206        Ok(meta) if meta.is_dir() => renameat_with(CWD, repo, CWD, dest, RenameFlags::EXCHANGE)
207            .map_err(|errno| DownloadError::Place(errno.into())),
208        // As the python, which could not remove a file or a link there.
209        Ok(_) => Err(DownloadError::Place(io::Error::from(
210            io::ErrorKind::NotADirectory,
211        ))),
212        Err(error) if error.kind() == io::ErrorKind::NotFound => {
213            std::fs::rename(repo, dest).map_err(DownloadError::Place)
214        }
215        Err(error) => Err(DownloadError::Place(error)),
216    }
217}
218
219// What `download_and_extract_repo` was asked for, with the buffer size resolved.
220struct Request<'a> {
221    url: &'a str,
222    git_ignore: &'a [String],
223    buffer_size: usize,
224    checkout: bool,
225    timeouts: Timeouts,
226}
227
228async fn build_repo(request: Request<'_>, work: &Path) -> Result<PathBuf, DownloadError> {
229    let archive = work.join(ARCHIVE_NAME);
230    fetch_to(request.url, &archive, request.buffer_size, request.timeouts).await?;
231
232    let extracted = work.join(EXTRACTED_NAME);
233    tokio::fs::create_dir(&extracted)
234        .await
235        .map_err(ExtractError::Io)?;
236    let file = tokio::fs::File::open(&archive)
237        .await
238        .map_err(ExtractError::Io)?;
239    super::tar::extract(file, &extracted).await?;
240    let _ = tokio::fs::remove_file(&archive).await;
241
242    let repo = extracted_dir(&extracted).await?;
243    keep_only_history(&repo).await?;
244    if request.checkout {
245        super::cli::reset_hard(&repo).await?;
246        prune(&repo, request.git_ignore)?;
247    }
248    Ok(repo)
249}
250
251async fn download_with(request: Request<'_>, dest: &Path) -> Result<(), DownloadError> {
252    let dest = &std::path::absolute(dest).map_err(DownloadError::Write)?;
253    let parent = dest.parent().ok_or_else(|| {
254        DownloadError::Write(io::Error::new(
255            io::ErrorKind::InvalidInput,
256            "the destination has no parent directory",
257        ))
258    })?;
259    tokio::fs::create_dir_all(parent)
260        .await
261        .map_err(DownloadError::Write)?;
262    // Beside the destination, so the repository swaps into place, and
263    // whatever fails or is cancelled leaves the destination as it was. A
264    // parent that refuses it would refuse the repository too.
265    let work = tempfile::Builder::new()
266        .prefix(WORK_PREFIX)
267        .tempdir_in(parent)
268        .map_err(DownloadError::Place)?;
269
270    let repo = build_repo(request, work.path()).await?;
271    place(&repo, dest)
272}
273
274/// Leaves the repository archived at `url` at `dest`, replacing what was there.
275///
276/// The archive holds only `.git`, so the working tree is restored with a
277/// `git reset --hard`. Pass `checkout = false` to keep just the history: peak
278/// disk stays at the size of the archive plus `.git`, which is what a consumer
279/// that walks commits needs. `git_ignore` prunes working-tree files and has no
280/// effect on a history-only download. `buffer_size` bounds a single write of
281/// the archive to disk; `None` takes 64 KiB, and anything above 16 MiB is
282/// taken as 16 MiB.
283///
284/// The archive is untrusted, so only its history is kept and its config is
285/// replaced. Everything is built in a directory beside `dest`, so a failed or
286/// cancelled call leaves `dest` as it was. Nothing is retried. A relative
287/// `dest` is resolved against the working directory once, when the call
288/// starts, and the working directory is never changed.
289pub async fn download_and_extract_repo(
290    url: &str,
291    dest: &Path,
292    git_ignore: &[String],
293    buffer_size: Option<NonZeroUsize>,
294    checkout: bool,
295) -> Result<(), DownloadError> {
296    let request = Request {
297        url,
298        git_ignore,
299        buffer_size: resolve_buffer_size(buffer_size),
300        checkout,
301        timeouts: TIMEOUTS,
302    };
303    download_with(request, dest).await
304}
305
306#[cfg(test)]
307mod tests {
308    use super::{
309        download_and_extract_repo, extracted_dir, fetch_to, place, resolve_buffer_size, Timeouts,
310        DEFAULT_DOWNLOAD_BUFFER_SIZE, MAX_DOWNLOAD_BUFFER_SIZE, TRUSTED_CONFIG,
311    };
312    use crate::errors::{DownloadError, ExtractError, FetchError};
313    use flate2::write::GzEncoder;
314    use flate2::Compression;
315    use std::num::NonZeroUsize;
316    use std::path::{Path, PathBuf};
317    use std::time::Duration;
318    use tokio::io::{AsyncReadExt, AsyncWriteExt};
319    use tokio::net::TcpListener;
320
321    // Answers every request with `archive`, as a bucket would.
322    async fn serve(archive: Vec<u8>) -> String {
323        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
324        let address = listener.local_addr().unwrap();
325        tokio::spawn(async move {
326            while let Ok((mut stream, _)) = listener.accept().await {
327                let mut request = [0u8; 1024];
328                let _ = stream.read(&mut request).await;
329                let head = format!(
330                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
331                    archive.len()
332                );
333                let _ = stream.write_all(head.as_bytes()).await;
334                let _ = stream.write_all(&archive).await;
335            }
336        });
337        format!("http://{address}/repo.tar.gz")
338    }
339
340    async fn download(archive: Vec<u8>, dest: &Path, checkout: bool) -> Result<(), DownloadError> {
341        let url = serve(archive).await;
342        download_and_extract_repo(&url, dest, &[], None, checkout).await
343    }
344
345    fn tar_gz(name: &str, contents: &[u8]) -> Vec<u8> {
346        let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
347        let mut header = tar::Header::new_gnu();
348        header.set_size(u64::try_from(contents.len()).unwrap());
349        header.set_mode(0o644);
350        builder.append_data(&mut header, name, contents).unwrap();
351        builder.into_inner().unwrap().finish().unwrap()
352    }
353
354    #[tokio::test]
355    async fn the_archive_replaces_an_existing_destination_and_leaves_nothing_beside_it() {
356        let tmp = tempfile::tempdir().unwrap();
357        let dest = tmp.path().join("dest");
358        std::fs::create_dir_all(&dest).unwrap();
359        std::fs::write(dest.join("stale"), b"old").unwrap();
360
361        download(
362            tar_gz("repo/.git/HEAD", b"ref: refs/heads/trunk\n"),
363            &dest,
364            false,
365        )
366        .await
367        .unwrap();
368
369        assert_eq!(
370            std::fs::read_to_string(dest.join(".git/HEAD")).unwrap(),
371            "ref: refs/heads/trunk\n"
372        );
373        assert!(!dest.join("stale").exists());
374        assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 1);
375    }
376
377    #[tokio::test]
378    async fn an_archive_without_a_directory_is_rejected() {
379        let tmp = tempfile::tempdir().unwrap();
380        let dest = tmp.path().join("dest");
381
382        let outcome = download(tar_gz("HEAD", b"ref: refs/heads/trunk\n"), &dest, false).await;
383
384        assert!(
385            matches!(
386                outcome,
387                Err(DownloadError::Extract(ExtractError::NoRepository(_)))
388            ),
389            "{outcome:?}"
390        );
391        assert!(!dest.exists());
392    }
393
394    const SHORT: Duration = Duration::from_secs(1);
395    const LONG: Duration = Duration::from_secs(30);
396
397    async fn answer_and_stall(mut stream: tokio::net::TcpStream, raw: &'static [u8]) {
398        let mut request = [0u8; 1024];
399        let _ = stream.read(&mut request).await;
400        let _ = stream.write_all(raw).await;
401        while stream.read(&mut request).await.is_ok_and(|read| read > 0) {}
402    }
403
404    // Answers every connection with `raw` and keeps it open, so only a
405    // timeout of the client ends the request.
406    async fn serve_and_stall(raw: &'static [u8]) -> String {
407        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
408        let address = listener.local_addr().unwrap();
409        tokio::spawn(async move {
410            while let Ok((stream, _)) = listener.accept().await {
411                tokio::spawn(answer_and_stall(stream, raw));
412            }
413        });
414        format!("http://{address}/repo.tar.gz")
415    }
416
417    async fn fetch_with(url: &str, timeouts: Timeouts) -> Result<(), DownloadError> {
418        let dir = tempfile::tempdir().unwrap();
419        fetch_to(
420            url,
421            &dir.path().join("repo.tar.gz"),
422            DEFAULT_DOWNLOAD_BUFFER_SIZE,
423            timeouts,
424        )
425        .await
426    }
427
428    #[tokio::test]
429    async fn a_connect_that_never_completes_is_a_connect_timeout() {
430        // The connect covers the TLS handshake, which this server never answers.
431        let url = serve_and_stall(b"")
432            .await
433            .replacen("http://", "https://", 1);
434
435        let outcome = fetch_with(
436            &url,
437            Timeouts {
438                connect: SHORT,
439                total: LONG,
440            },
441        )
442        .await;
443
444        assert!(
445            matches!(
446                outcome,
447                Err(DownloadError::Fetch(FetchError::ConnectTimeout(_)))
448            ),
449            "{outcome:?}"
450        );
451    }
452
453    #[tokio::test]
454    async fn a_response_that_never_starts_is_a_timeout_before_the_headers() {
455        let url = serve_and_stall(b"").await;
456
457        let outcome = fetch_with(
458            &url,
459            Timeouts {
460                connect: LONG,
461                total: SHORT,
462            },
463        )
464        .await;
465
466        assert!(
467            matches!(outcome, Err(DownloadError::Fetch(FetchError::Timeout(_)))),
468            "{outcome:?}"
469        );
470    }
471
472    #[tokio::test]
473    async fn a_body_that_stops_arriving_is_a_timeout_reading_the_body() {
474        let url =
475            serve_and_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n\x1f\x8b\x08\x00")
476                .await;
477
478        let outcome = fetch_with(
479            &url,
480            Timeouts {
481                connect: LONG,
482                total: SHORT,
483            },
484        )
485        .await;
486
487        assert!(
488            matches!(
489                outcome,
490                Err(DownloadError::Fetch(FetchError::BodyTimeout(_)))
491            ),
492            "{outcome:?}"
493        );
494    }
495
496    #[tokio::test]
497    async fn a_failed_fetch_never_carries_the_query_of_the_url() {
498        let refused = {
499            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
500            format!("http://{}/repo.tar.gz", listener.local_addr().unwrap())
501        };
502        let silent = serve_and_stall(b"").await;
503        let cut = serve_and_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\nx").await;
504
505        for url in [refused, silent, cut] {
506            let outcome = fetch_with(
507                &format!("{url}?X-Amz-Signature=secret"),
508                Timeouts {
509                    connect: SHORT,
510                    total: SHORT,
511                },
512            )
513            .await;
514
515            assert!(!format!("{outcome:?}").contains("secret"), "{outcome:?}");
516            let error = outcome.unwrap_err();
517            assert!(!error.to_string().contains("secret"), "{error}");
518        }
519    }
520
521    #[test]
522    fn an_absent_buffer_size_takes_the_default_of_the_python() {
523        assert_eq!(resolve_buffer_size(None), DEFAULT_DOWNLOAD_BUFFER_SIZE);
524        assert_eq!(resolve_buffer_size(NonZeroUsize::new(8 * 1024)), 8 * 1024);
525    }
526
527    #[test]
528    fn a_buffer_size_above_the_maximum_is_clamped() {
529        assert_eq!(
530            resolve_buffer_size(NonZeroUsize::new(MAX_DOWNLOAD_BUFFER_SIZE + 1)),
531            MAX_DOWNLOAD_BUFFER_SIZE
532        );
533    }
534
535    fn git(repo: &Path, args: &[&str]) {
536        let status = std::process::Command::new("git")
537            .arg("-C")
538            .arg(repo)
539            .args([
540                "-c",
541                "user.email=dev@fluidattacks.com",
542                "-c",
543                "user.name=dev",
544            ])
545            .args(args)
546            .status()
547            .unwrap();
548        assert!(status.success());
549    }
550
551    fn hostile_archive(dir: &Path, key: &str) -> (Vec<u8>, PathBuf) {
552        let marker = dir.join("pwned");
553        let payload = dir.join("payload.sh");
554        std::fs::write(
555            &payload,
556            format!("#!/bin/sh\ntouch {}\ncat\n", marker.display()),
557        )
558        .unwrap();
559        #[cfg(unix)]
560        {
561            use std::os::unix::fs::PermissionsExt;
562            std::fs::set_permissions(&payload, std::fs::Permissions::from_mode(0o755)).unwrap();
563        }
564
565        let source = dir.join("source");
566        std::fs::create_dir_all(&source).unwrap();
567        git(&source, &["init", "-q"]);
568        std::fs::write(source.join(".gitattributes"), b"* filter=pwn\n").unwrap();
569        std::fs::write(source.join("tracked.txt"), b"content\n").unwrap();
570        git(&source, &["add", "-A"]);
571        git(&source, &["commit", "-q", "-m", "add tracked file"]);
572        git(&source, &["config", key, &payload.to_string_lossy()]);
573        std::fs::create_dir_all(source.join(".git/objects/info")).unwrap();
574        std::fs::write(
575            source.join(".git/objects/info/alternates"),
576            format!("{}\n", dir.display()),
577        )
578        .unwrap();
579
580        let mut builder = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
581        builder
582            .append_dir_all("source/.git", source.join(".git"))
583            .unwrap();
584        let archive = builder.into_inner().unwrap().finish().unwrap();
585        std::fs::remove_dir_all(&source).unwrap();
586        (archive, marker)
587    }
588
589    #[tokio::test]
590    async fn a_restored_archive_runs_nothing_it_configures() {
591        for key in ["filter.pwn.smudge", "filter.pwn.process", "core.fsmonitor"] {
592            let tmp = tempfile::tempdir().unwrap();
593            let (archive, marker) = hostile_archive(tmp.path(), key);
594            let dest = tmp.path().join("dest");
595
596            download(archive, &dest, true).await.unwrap();
597
598            assert!(!marker.exists(), "{key} ran");
599            assert_eq!(
600                std::fs::read_to_string(dest.join("tracked.txt")).unwrap(),
601                "content\n"
602            );
603        }
604    }
605
606    #[tokio::test]
607    async fn only_the_history_of_the_archive_is_kept() {
608        let tmp = tempfile::tempdir().unwrap();
609        let (archive, _) = hostile_archive(tmp.path(), "core.fsmonitor");
610        let dest = tmp.path().join("dest");
611
612        download(archive, &dest, false).await.unwrap();
613
614        let git_dir = dest.join(".git");
615        assert_eq!(
616            std::fs::read_to_string(git_dir.join("config")).unwrap(),
617            TRUSTED_CONFIG
618        );
619        assert!(!git_dir.join("hooks").exists());
620        assert!(!git_dir.join("objects/info/alternates").exists());
621        assert!(git_dir.join("HEAD").is_file());
622    }
623
624    #[tokio::test]
625    async fn a_git_file_in_the_archive_is_rejected() {
626        let tmp = tempfile::tempdir().unwrap();
627        let dest = tmp.path().join("dest");
628
629        let outcome = download(
630            tar_gz("repo/.git", b"gitdir: /elsewhere/.git\n"),
631            &dest,
632            false,
633        )
634        .await;
635
636        assert!(
637            matches!(
638                outcome,
639                Err(DownloadError::Extract(ExtractError::NoRepository(_)))
640            ),
641            "{outcome:?}"
642        );
643        assert!(!dest.exists());
644    }
645
646    #[tokio::test]
647    async fn a_failed_reset_keeps_the_previous_destination() {
648        let tmp = tempfile::tempdir().unwrap();
649        let dest = tmp.path().join("dest");
650        std::fs::create_dir_all(&dest).unwrap();
651        std::fs::write(dest.join("previous"), b"old").unwrap();
652
653        // A HEAD with no objects behind it, which git cannot reset to.
654        let outcome = download(
655            tar_gz("repo/.git/HEAD", b"ref: refs/heads/trunk\n"),
656            &dest,
657            true,
658        )
659        .await;
660
661        assert!(
662            matches!(outcome, Err(DownloadError::Reset(_))),
663            "{outcome:?}"
664        );
665        assert_eq!(std::fs::read(dest.join("previous")).unwrap(), b"old");
666        assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 1);
667    }
668
669    #[test]
670    fn a_failed_swap_keeps_the_previous_destination() {
671        let tmp = tempfile::tempdir().unwrap();
672        let dest = tmp.path().join("dest");
673        std::fs::create_dir_all(&dest).unwrap();
674        std::fs::write(dest.join("previous"), b"old").unwrap();
675
676        let outcome = place(&tmp.path().join("missing"), &dest);
677
678        assert!(
679            matches!(outcome, Err(DownloadError::Place(_))),
680            "{outcome:?}"
681        );
682        assert_eq!(std::fs::read(dest.join("previous")).unwrap(), b"old");
683    }
684
685    #[tokio::test]
686    async fn a_work_directory_that_cannot_be_made_is_a_place_failure() {
687        use std::os::unix::fs::PermissionsExt;
688        let tmp = tempfile::tempdir().unwrap();
689        let parent = tmp.path().join("read-only");
690        std::fs::create_dir(&parent).unwrap();
691        std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o500)).unwrap();
692        // Root writes in a read-only directory, so there is nothing to refuse.
693        if std::fs::create_dir(parent.join("probe")).is_ok() {
694            return;
695        }
696
697        let outcome =
698            download_and_extract_repo("http://127.0.0.1:9/", &parent.join("root"), &[], None, true)
699                .await;
700
701        std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o700)).unwrap();
702        assert!(
703            matches!(outcome, Err(DownloadError::Place(_))),
704            "{outcome:?}"
705        );
706    }
707
708    #[tokio::test]
709    async fn the_first_directory_is_taken_in_a_stable_order() {
710        let tmp = tempfile::tempdir().unwrap();
711        std::fs::write(tmp.path().join("stray"), b"").unwrap();
712        std::fs::create_dir_all(tmp.path().join("b_repo")).unwrap();
713        std::fs::create_dir_all(tmp.path().join("a_repo")).unwrap();
714
715        assert_eq!(
716            extracted_dir(tmp.path()).await.unwrap(),
717            tmp.path().join("a_repo")
718        );
719    }
720}