fluidattacks-core-git 0.68.0

Fluid Attacks Core Git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
pub mod codecommit;
pub mod https;
pub mod ssh;

pub(crate) mod reason;

pub use https::build_https_config_args;
pub use https::format_https_url;
pub use reason::hide;
pub use ssh::setup_ssh_env;

use anyhow::{bail, Context, Result};
use serde_json::json;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use tokio::process::Command;
use tracing::{info, warn};

use crate::errors::{CloneError, FileError, HttpsAccessError};
use crate::types::{CredentialKind, Credentials, GitRoot};
use https::HttpsAccess;

/// Which refs a clone takes, and what it leaves on disk.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CloneShape {
    /// The named branch and only it, with a working tree.
    SingleBranch,
    /// Every ref the remote advertises, as a bare mirror.
    Mirror,
    /// Every branch head — `refs/heads/*` plus `HEAD` — as a bare repo:
    /// no tags, no hidden refs, no mirror config remnants.
    BareHeads,
}

pub struct CloneOpts {
    pub group_name: String,
    pub nickname: String,
    pub repo_url: String,
    pub branch: String,
    pub credentials: Option<Credentials>,
    pub follow_redirects: bool,
    pub skip_existing: bool,
    pub shape: CloneShape,
}

impl CloneOpts {
    #[must_use]
    pub fn from_root(
        group: &str,
        root: &GitRoot,
        credentials: Option<Credentials>,
        skip_existing: bool,
        shape: CloneShape,
    ) -> Self {
        Self {
            group_name: group.to_owned(),
            nickname: root.nickname.clone(),
            repo_url: root.url.clone(),
            branch: root.branch.clone(),
            credentials,
            follow_redirects: root.follow_redirects(),
            skip_existing,
            shape,
        }
    }
}

async fn dispatch_clone(opts: &CloneOpts, dest: &Path) -> Result<()> {
    match &opts.credentials {
        Some(Credentials {
            kind: CredentialKind::Ssh { .. },
        }) => ssh::clone_ssh(opts, dest).await,
        Some(Credentials {
            kind: CredentialKind::Https { .. },
        }) => https::clone_https(opts, dest).await,
        Some(Credentials {
            kind: CredentialKind::Token { .. },
        }) => https::clone_https_token(opts, dest).await,
        Some(Credentials {
            kind: CredentialKind::AwsRole { .. },
        }) => codecommit::clone_codecommit(opts, dest).await,
        None if opts.repo_url.starts_with("http") => https::clone_https_public(opts, dest).await,
        _ => bail!("no suitable credentials found for root {:?}", opts.nickname),
    }
}

pub async fn clone_root(opts: &CloneOpts) -> Result<()> {
    let repo_dir = PathBuf::from("groups")
        .join(&opts.group_name)
        .join(&opts.nickname);

    if opts.skip_existing {
        if let Ok(entries) = fs::read_dir(&repo_dir) {
            if entries.count() > 0 {
                info!(nickname = opts.nickname, "skipping existing repo");
                return Ok(());
            }
        }
    }

    // Use tempdir_in targeting repo_dir's parent to avoid cross-filesystem rename (EXDEV)
    let tmp_parent = repo_dir.parent().unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(tmp_parent)
        .with_context(|| format!("creating parent dir {}", tmp_parent.display()))?;
    let tmp_dir = tempfile::tempdir_in(tmp_parent).context("creating temp dir")?;
    let clone_dest = tmp_dir.path().join(&opts.nickname);

    dispatch_clone(opts, &clone_dest)
        .await
        .with_context(|| format!("cloning {:?}", opts.nickname))?;

    if opts.shape == CloneShape::Mirror {
        convert_bare_to_worktree(&clone_dest)
            .await
            .with_context(|| format!("converting mirror to worktree for {:?}", opts.nickname))?;
    }

    if repo_dir.exists() {
        fs::remove_dir_all(&repo_dir)
            .with_context(|| format!("removing old repo dir {}", repo_dir.display()))?;
    }
    fs::rename(&clone_dest, &repo_dir)
        .with_context(|| format!("moving cloned repo to {}", repo_dir.display()))?;

    log_clone_result(&repo_dir, opts).await;

    if opts.shape == CloneShape::Mirror {
        if let Err(e) = write_mirror_info(&repo_dir, opts) {
            warn!(error = %e, "failed to write .info.json");
        }
    }

    Ok(())
}

async fn convert_bare_to_worktree(clone_dest: &Path) -> Result<()> {
    let bare_tmp = clone_dest.with_extension("bare");
    fs::rename(clone_dest, &bare_tmp)
        .with_context(|| format!("renaming bare repo to {}", bare_tmp.display()))?;
    fs::create_dir_all(clone_dest)
        .with_context(|| format!("creating worktree dir {}", clone_dest.display()))?;
    let git_dir = clone_dest.join(".git");
    fs::rename(&bare_tmp, &git_dir)
        .with_context(|| format!("moving bare contents to {}", git_dir.display()))?;

    let dest_str = clone_dest.to_string_lossy().to_string();

    let config_out = Command::new("git")
        .args(["-C", &dest_str, "config", "core.bare", "false"])
        .output()
        .await
        .context("running git config core.bare false")?;
    if !config_out.status.success() {
        bail!(
            "git config core.bare false failed: {}",
            String::from_utf8_lossy(&config_out.stderr)
        );
    }

    let reset_out = Command::new("git")
        .args(["-C", &dest_str, "reset", "--hard", "HEAD"])
        .output()
        .await
        .context("running git reset --hard HEAD")?;
    if !reset_out.status.success() {
        bail!(
            "git reset --hard HEAD failed: {}",
            String::from_utf8_lossy(&reset_out.stderr)
        );
    }

    Ok(())
}

async fn log_clone_result(repo_dir: &Path, opts: &CloneOpts) {
    let label = match opts.shape {
        CloneShape::Mirror => "cloned (mirror)",
        CloneShape::BareHeads => "cloned (bare heads)",
        CloneShape::SingleBranch => "cloned",
    };
    let repo_dir_str = repo_dir.to_string_lossy().to_string();
    match Command::new("git")
        .args(["-C", &repo_dir_str, "log", "-1", "--format=%H %ai"])
        .output()
        .await
    {
        Ok(output) if output.status.success() => {
            let head = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            info!(nickname = opts.nickname, head = head, label);
        }
        _ => {
            info!(nickname = opts.nickname, dir = %repo_dir.display(), label);
        }
    }
}

fn write_mirror_info(repo_dir: &Path, opts: &CloneOpts) -> Result<(), FileError> {
    let info = json!({
        "fluid_branch": opts.branch,
        "repo": opts.repo_url,
    });
    let path = repo_dir.join(".info.json");
    fs::write(&path, format!("{info:#}")).map_err(|source| FileError {
        action: "writing",
        path,
        source,
    })
}

/// git creates whatever part of `temp_dir` is missing.
#[expect(
    clippy::too_many_arguments,
    reason = "what the python https_clone, ssh_clone and call_codecommit_clone take, the credential in one"
)]
pub async fn clone_to_temp(
    temp_dir: &Path,
    url: &str,
    branch: &str,
    credential: Option<&CredentialKind>,
    follow_redirects: bool,
    mirror: bool,
) -> Result<PathBuf, CloneError> {
    let nickname = uuid::Uuid::new_v4().to_string();
    let dest = temp_dir.join(&nickname);
    let opts = CloneOpts {
        group_name: String::new(),
        nickname,
        repo_url: url.to_owned(),
        branch: branch.to_owned(),
        credentials: None,
        follow_redirects,
        skip_existing: false,
        shape: if mirror {
            CloneShape::Mirror
        } else {
            CloneShape::SingleBranch
        },
    };
    let cloned = match credential {
        Some(CredentialKind::Ssh { key }) => ssh::run_git_clone(&opts, &dest, key).await,
        Some(CredentialKind::AwsRole {
            arn,
            external_id,
            via,
        }) => codecommit::run_git_clone(&opts, &dest, arn, external_id, via.as_deref()).await,
        // git takes any url, an scp-like one over ssh with whatever keys this machine has.
        None if !has_http_scheme(url) => return Err(HttpsAccessError::NotHttp.into()),
        _ => {
            let access = HttpsAccess::new(url, credential)?;
            Ok(https::run_git_clone(&opts, &dest, &access).await?)
        }
    };
    cloned.inspect_err(|_| {
        let _ = fs::remove_dir_all(&dest);
    })?;
    log_clone_result(&dest, &opts).await;
    if mirror {
        keep_with_info(&dest, &opts)?;
    }
    Ok(dest)
}

pub(crate) fn has_http_scheme(url: &str) -> bool {
    url.split_once("://")
        .is_some_and(|(scheme, _)| matches!(scheme, "http" | "https"))
}

fn keep_with_info(dest: &Path, opts: &CloneOpts) -> Result<(), CloneError> {
    // On an error the caller never gets the path, so nobody would remove this clone.
    write_mirror_info(dest, opts).map_err(|error| {
        let _ = fs::remove_dir_all(dest);
        error.into()
    })
}

#[must_use]
pub fn build_clone_args(
    opts: &CloneOpts,
    repo_url: &str,
    dest: &Path,
    extra_config: &[String],
) -> Vec<OsString> {
    let mut args = vec!["-c".to_owned(), "core.symlinks=false".to_owned()];

    args.extend(extra_config.iter().cloned());

    args.push("clone".to_owned());

    match opts.shape {
        CloneShape::Mirror => args.push("--mirror".to_owned()),
        // Every branch head and nothing else: unlike --mirror this skips
        // refs/pull, refs/merge-requests and keep-around refs, and writes no
        // mirror refspec into the clone's config.
        CloneShape::BareHeads => args.extend(["--bare".to_owned(), "--no-tags".to_owned()]),
        // An empty branch is passed on for git to refuse, not read as the default one.
        CloneShape::SingleBranch => args.extend([
            "--branch".to_owned(),
            opts.branch.clone(),
            "--single-branch".to_owned(),
        ]),
    }

    args.extend(["--".to_owned(), repo_url.to_owned()]);

    let mut args: Vec<OsString> = args.into_iter().map(OsString::from).collect();
    // A path need not be UTF-8, so git gets its bytes.
    args.push(dest.as_os_str().to_owned());
    args
}

pub(crate) fn redirect_config(follow_redirects: bool) -> [String; 2] {
    [
        "-c".to_owned(),
        format!("http.followRedirects={follow_redirects}"),
    ]
}

pub(crate) fn stall_config() -> [String; 4] {
    [
        "-c".to_owned(),
        "http.lowSpeedLimit=1000".to_owned(),
        "-c".to_owned(),
        "http.lowSpeedTime=600".to_owned(),
    ]
}

#[cfg(test)]
mod tests {
    use std::ffi::{OsStr, OsString};
    use std::io::{BufRead, BufReader, Write};
    use std::net::TcpListener;
    use std::os::unix::ffi::OsStrExt;
    use std::path::Path;
    use std::process::Command;

    use super::{build_clone_args, clone_to_temp, keep_with_info, CloneOpts, CloneShape};
    use crate::errors::{CloneError, HttpsAccessError};

    pub(super) fn opts(shape: CloneShape) -> CloneOpts {
        CloneOpts {
            group_name: "a-group".to_owned(),
            nickname: "a_root".to_owned(),
            repo_url: "https://gitlab.com/org/repo".to_owned(),
            branch: "trunk".to_owned(),
            credentials: None,
            follow_redirects: false,
            skip_existing: false,
            shape,
        }
    }

    fn shape_args(shape: CloneShape) -> Vec<OsString> {
        let opts = opts(shape);

        // Between "clone" and "--" sits exactly the shape.
        build_clone_args(&opts, &opts.repo_url, Path::new("/tmp/a_root"), &[])
            .iter()
            .skip_while(|arg| *arg != "clone")
            .skip(1)
            .take_while(|arg| *arg != "--")
            .cloned()
            .collect()
    }

    fn run_git(dir: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .arg("-C")
            .arg(dir)
            .args([
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=Test",
                "-c",
                "commit.gpgsign=false",
                "-c",
                "tag.gpgsign=false",
            ])
            .args(args)
            .output()
            .expect("git runs");
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_owned()
    }

    #[test]
    fn a_clone_never_writes_a_symbolic_link() {
        let opts = opts(CloneShape::SingleBranch);
        let args = build_clone_args(&opts, &opts.repo_url, Path::new("/tmp/a_root"), &[]);

        assert!(args
            .windows(2)
            .any(|pair| pair == ["-c", "core.symlinks=false"]));
    }

    #[test]
    fn a_destination_that_is_not_utf8_reaches_git_as_its_bytes() {
        let opts = opts(CloneShape::SingleBranch);
        let dest = Path::new(OsStr::from_bytes(b"/tmp/caf\xe9"));

        let args = build_clone_args(&opts, &opts.repo_url, dest, &[]);

        assert_eq!(args.last().map(OsString::as_os_str), Some(dest.as_os_str()));
    }

    #[test]
    fn a_branch_clone_is_single_branch() {
        assert_eq!(
            shape_args(CloneShape::SingleBranch),
            ["--branch", "trunk", "--single-branch"]
        );
    }

    #[test]
    fn an_empty_branch_is_asked_for_instead_of_the_default_one() {
        let opts = CloneOpts {
            branch: String::new(),
            ..opts(CloneShape::SingleBranch)
        };
        let args = build_clone_args(&opts, &opts.repo_url, Path::new("/tmp/a_root"), &[]);

        assert!(args.windows(2).any(|pair| pair == ["--branch", ""]));
    }

    #[test]
    fn a_mirror_clone_takes_every_ref() {
        assert_eq!(shape_args(CloneShape::Mirror), ["--mirror"]);
    }

    #[test]
    fn a_bare_heads_clone_takes_heads_without_tags() {
        assert_eq!(shape_args(CloneShape::BareHeads), ["--bare", "--no-tags"]);
    }

    #[test]
    fn a_bare_heads_clone_holds_exactly_the_branch_heads() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let source = tmp.path().join("source");
        std::fs::create_dir(&source).expect("mkdir");
        run_git(&source, &["init", "--initial-branch=main"]);
        std::fs::write(source.join("file.txt"), "content\n").expect("write");
        run_git(&source, &["add", "file.txt"]);
        run_git(&source, &["commit", "-m", "first"]);
        run_git(&source, &["branch", "feature"]);
        run_git(&source, &["tag", "v1"]);
        // The kind of hidden ref --mirror would drag in.
        run_git(&source, &["update-ref", "refs/pull/1/head", "HEAD"]);

        let dest = tmp.path().join("dest");
        let opts = opts(CloneShape::BareHeads);
        let args = build_clone_args(&opts, &source.to_string_lossy(), &dest, &[]);
        let clone = Command::new("git").args(&args).output().expect("git runs");
        assert!(
            clone.status.success(),
            "clone failed: {}",
            String::from_utf8_lossy(&clone.stderr)
        );

        let refs = run_git(&dest, &["for-each-ref", "--format=%(refname)"]);
        let mut held: Vec<&str> = refs.lines().collect();
        held.sort_unstable();
        assert_eq!(held, ["refs/heads/feature", "refs/heads/main"]);
        assert_eq!(run_git(&dest, &["symbolic-ref", "HEAD"]), "refs/heads/main");
        assert_eq!(run_git(&dest, &["config", "core.bare"]), "true");
        // No mirror remnants: neither the flag nor a fetch refspec.
        for key in ["remote.origin.mirror", "remote.origin.fetch"] {
            let lookup = Command::new("git")
                .args(["-C", &dest.to_string_lossy(), "config", "--get", key])
                .output()
                .expect("git runs");
            assert!(!lookup.status.success(), "{key} is set");
        }
    }

    pub(super) fn source(tmp: &Path) -> String {
        let work = tmp.join("work");
        std::fs::create_dir(&work).unwrap();
        run_git(&work, &["init", "--quiet", "--initial-branch=main"]);
        run_git(&work, &["commit", "--quiet", "--allow-empty", "-m", "one"]);
        format!("file://{}", work.display())
    }

    // `source` over git's dumb http protocol: a static file server on a bare copy.
    fn served(tmp: &Path) -> String {
        let bare = tmp.join("served.git");
        let cloned = Command::new("git")
            .args(["clone", "--quiet", "--bare", &source(tmp)])
            .arg(&bare)
            .status()
            .unwrap();
        assert!(cloned.success());
        run_git(&bare, &["update-server-info"]);
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for mut stream in listener.incoming().flatten() {
                let mut lines = BufReader::new(&stream).lines();
                let request = lines.next().and_then(Result::ok).unwrap_or_default();
                // Unread headers left behind make the close a reset that git may see first.
                lines
                    .map_while(Result::ok)
                    .take_while(|line| !line.is_empty())
                    .for_each(drop);
                let _ = stream.write_all(&file_answer(&bare, &request));
            }
        });
        format!("http://127.0.0.1:{port}/")
    }

    // The file a request line asks for under `root`, query left out, or a 404.
    fn file_answer(root: &Path, request: &str) -> Vec<u8> {
        let path = request.split(' ').nth(1).unwrap_or_default();
        let file = path.split('?').next().unwrap_or_default();
        std::fs::read(root.join(file.trim_start_matches('/'))).map_or_else(
            |_| {
                b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec()
            },
            |body| {
                let head = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                [head.into_bytes(), body].concat()
            },
        )
    }

    #[tokio::test]
    async fn git_creates_a_missing_temp_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let url = served(tmp.path());
        let temp_dir = tmp.path().join("missing/clones");

        let folder = clone_to_temp(&temp_dir, &url, "main", None, false, false)
            .await
            .unwrap();

        assert_eq!(folder.parent(), Some(temp_dir.as_path()));
    }

    #[tokio::test]
    async fn a_url_without_a_credential_goes_to_git_as_given() {
        let tmp = tempfile::tempdir().unwrap();
        let url = served(tmp.path());

        let folder = clone_to_temp(tmp.path(), &url, "main", None, false, false)
            .await
            .unwrap();

        assert!(folder.join(".git").is_dir());
    }

    #[tokio::test]
    async fn a_url_that_is_not_http_reaches_no_git_without_a_credential() {
        let tmp = tempfile::tempdir().unwrap();
        // git would clone this one.
        let url = source(tmp.path());
        let temp_dir = tmp.path().join("clones");

        let outcome = clone_to_temp(&temp_dir, &url, "main", None, false, false).await;

        assert!(
            matches!(outcome, Err(CloneError::Access(HttpsAccessError::NotHttp))),
            "{outcome:?}"
        );
        assert!(!temp_dir.exists());
    }

    #[test]
    fn a_mirror_whose_info_cannot_be_written_is_removed() {
        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().join("mirror");
        // A directory where the file goes makes the write fail.
        std::fs::create_dir_all(dest.join(".info.json")).unwrap();

        let outcome = keep_with_info(&dest, &opts(CloneShape::Mirror));

        assert!(matches!(outcome, Err(CloneError::Info(_))), "{outcome:?}");
        assert!(!dest.exists());
    }
}