monochromatic-git-policy-cli 0.4.6

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! Controls for the manual-push probe against real repositories and bare remotes.
//! The TypeScript corpus is `src/policy-engine/manual-push.integration.unit.test.ts` (probe and ls-remote cases)
//! and `src/policy-engine/manual-push-scope.unit.test.ts`; the update-discovery cases are reproduced here.

use super::*;
use crate::auto_push_single_flight::PushGit;
use crate::test_support::{fixture, git, remove};

/// Environment every Git child of these fixtures runs with.
fn fixture_environment() -> Vec<(OsString, OsString)> {
    return [
        ("PATH", "/usr/bin:/bin"),
        ("GIT_CONFIG_NOSYSTEM", "1"),
        ("GIT_CONFIG_GLOBAL", "/nonexistent-global-config"),
        ("GIT_AUTHOR_NAME", "Fixture"),
        ("GIT_AUTHOR_EMAIL", "fixture@example.invalid"),
        ("GIT_COMMITTER_NAME", "Fixture"),
        ("GIT_COMMITTER_EMAIL", "fixture@example.invalid"),
    ]
    .iter()
    .map(|(name, value)| {
        return (OsString::from(name), OsString::from(value));
    })
    .collect();
}

/// The home directory of a fixture repository at `root`, beside it, where the per-user scratch directory is made.
fn home_beside(root: &Path) -> PathBuf {
    return root.parent().expect("fixture root").join("home");
}

/// Coordinator Git for a fixture repository at `root`, with a home beside the repository.
fn git_for(root: &Path) -> PushGit {
    let mut environment = fixture_environment();
    environment.push((OsString::from("HOME"), home_beside(root).into_os_string()));
    return PushGit {
        real_git: PathBuf::from("/usr/bin/git"),
        cwd: root.to_path_buf(),
        environment,
        lfs_pre_push: None,
    };
}

/// A repository with one commit on `main` and a bare origin that holds the same commit.
fn repository_with_origin(name: &str) -> (PathBuf, PathBuf, String) {
    let root = fixture(name);
    let origin = root.join("origin.git");
    let repo = root.join("repo");
    git(
        &root,
        &["init", "--quiet", "--bare", origin.to_str().expect("utf-8")],
    );
    std::fs::create_dir_all(&repo).expect("repo");
    git(&repo, &["init", "--quiet", "--initial-branch=main"]);
    git(
        &repo,
        &["commit", "--quiet", "--allow-empty", "--message=base"],
    );
    git(
        &repo,
        &["remote", "add", "origin", origin.to_str().expect("utf-8")],
    );
    git(
        &repo,
        &["push", "--quiet", "origin", "HEAD:refs/heads/main"],
    );
    let base = head_of(&repo);
    return (repo, origin, base);
}

/// The commit `HEAD` names.
fn head_of(repo: &Path) -> String {
    return String::from_utf8_lossy(&git(repo, &["rev-parse", "HEAD"]).stdout)
        .trim()
        .to_owned();
}

/// The object a ref names in a bare remote, or nothing.
fn remote_value(origin: &Path, reference: &str) -> Option<String> {
    let output = std::process::Command::new("/usr/bin/git")
        .current_dir(origin)
        .env_clear()
        .envs(fixture_environment())
        .args(["rev-parse", "--verify", "--quiet", reference])
        .output()
        .expect("rev-parse");
    if !output.status.success() {
        return None;
    }
    return Some(String::from_utf8_lossy(&output.stdout).trim().to_owned());
}

/// Post-subcommand arguments as owned strings.
fn post(arguments: &[&str]) -> Vec<OsString> {
    return arguments.iter().map(OsString::from).collect();
}

/// Pure parsing: four fields per record, empty lines ignored, other shapes refused.
#[test]
fn update_records_have_four_fields_and_other_shapes_are_refused() {
    let parsed = parse_update_records(
        "refs/heads/main abc refs/heads/main def\n\nrefs/heads/x 111 refs/heads/x 000\n",
        "origin",
        "/remote",
    )
    .expect("parses");
    assert_eq!(parsed.len(), 2);
    assert_eq!(parsed[0].remote_name, "origin");
    assert_eq!(parsed[0].remote_location, "/remote");
    assert_eq!(parsed[0].remote_ref, "refs/heads/main");
    assert_eq!(parsed[0].advertised_remote_oid, "def");
    assert!(parse_update_records("refs/heads/main abc refs/heads/main\n", "o", "l").is_err());
    assert!(parse_update_records("a b c d e\n", "o", "l").is_err());
    assert_eq!(
        parse_update_records("", "o", "l").expect("empty"),
        Vec::new()
    );
}

/// Only the all-zero spelling is an absent object name.
#[test]
fn only_all_zero_names_are_absent() {
    assert!(is_zero_oid("0000000000000000000000000000000000000000"));
    assert!(!is_zero_oid("0000000000000000000000000000000000000001"));
    assert!(!is_zero_oid(""));
}

/// The probe inserts its hook override and `--dry-run --verify` before a `--` terminator, after the global options.
#[test]
fn probe_arguments_keep_git_options_before_the_terminator() {
    let arguments = probe_arguments(
        &post(&["-C", "/repo"]),
        &post(&["origin", "main", "--", "tail"]),
        Path::new("/hooks"),
    );
    let text: Vec<String> = arguments
        .iter()
        .map(|argument| {
            return argument.to_string_lossy().into_owned();
        })
        .collect();
    assert_eq!(
        text,
        vec![
            "-C",
            "/repo",
            "-c",
            "core.hooksPath=/hooks",
            "-c",
            "hook.pre-push.enabled=false",
            "push",
            "origin",
            "main",
            "--dry-run",
            "--verify",
            "--",
            "tail"
        ]
    );
}

/// The recording hook refuses to overwrite a capture and limits its input.
#[test]
fn the_hook_writes_an_exclusive_capture_of_bounded_input() {
    let source = hook_source();
    assert!(source.starts_with("#!/bin/sh\n"), "{source}");
    assert!(source.contains("set -C"), "{source}");
    assert!(
        source.contains("$CLI_GIT_PUSH_FACTS_DIRECTORY/$$.capture"),
        "{source}"
    );
    assert!(
        source.contains(&format!("head -c {}", MAX_HOOK_INPUT_BYTES + 1)),
        "{source}"
    );
}

/// The limit itself is complete input; the one extra byte the hook reads is proof that input was cut short.
#[test]
fn only_input_past_the_limit_exceeds_the_capture_limit() {
    let limit = usize::try_from(MAX_HOOK_INPUT_BYTES).expect("the limit fits in memory");
    assert!(!exceeds_capture_limit(0));
    assert!(!exceeds_capture_limit(limit - 1));
    assert!(!exceeds_capture_limit(limit));
    assert!(exceeds_capture_limit(limit + 1));
}

/// A new branch pushed by the probe is one update: a local object, no remote object, the named remote.
#[test]
fn a_new_branch_is_one_update_with_no_remote_object() {
    let (repo, origin, _base) = repository_with_origin("mp-probe-new");
    git(&repo, &["checkout", "--quiet", "-b", "feature"]);
    let landed = head_of(&repo);
    git(
        &repo,
        &["commit", "--quiet", "--allow-empty", "--message=feature"],
    );
    let tip = head_of(&repo);
    let updates = probe_manual_push_updates(&git_for(&repo), &[], &post(&["origin", "feature"]))
        .expect("probes");
    assert_eq!(
        updates,
        vec![PushUpdate {
            local_oid: Some(tip.clone()),
            remote_oid: None,
            remote_name: "origin".to_owned(),
            remote_ref: "refs/heads/feature".to_owned(),
        }]
    );
    assert_eq!(
        remote_value(&origin, "refs/heads/feature"),
        None,
        "the probe must not publish"
    );
    assert_ne!(landed, tip);
    remove(repo.parent().expect("root"));
}

/// A fast-forward names the remote's current object as the prior value.
#[test]
fn a_fast_forward_names_the_prior_remote_value() {
    let (repo, origin, base) = repository_with_origin("mp-probe-ff");
    git(
        &repo,
        &["commit", "--quiet", "--allow-empty", "--message=next"],
    );
    let tip = head_of(&repo);
    let updates = probe_manual_push_updates(&git_for(&repo), &[], &post(&["origin", "main"]))
        .expect("probes");
    assert_eq!(updates.len(), 1);
    assert_eq!(updates[0].local_oid.as_deref(), Some(tip.as_str()));
    assert_eq!(updates[0].remote_oid.as_deref(), Some(base.as_str()));
    assert_eq!(
        remote_value(&origin, "refs/heads/main").as_deref(),
        Some(base.as_str())
    );
    remove(repo.parent().expect("root"));
}

/// Deleting a remote branch is an update with no local object.
#[test]
fn a_deletion_has_no_local_object() {
    let (repo, _origin, base) = repository_with_origin("mp-probe-delete");
    let updates = probe_manual_push_updates(&git_for(&repo), &[], &post(&["origin", ":main"]))
        .expect("probes");
    assert_eq!(
        updates,
        vec![PushUpdate {
            local_oid: None,
            remote_oid: Some(base),
            remote_name: "origin".to_owned(),
            remote_ref: "refs/heads/main".to_owned(),
        }]
    );
    remove(repo.parent().expect("root"));
}

/// A push with nothing to send has no updates to scan.
#[test]
fn an_up_to_date_push_has_no_updates() {
    let (repo, _origin, _base) = repository_with_origin("mp-probe-noop");
    let updates = probe_manual_push_updates(&git_for(&repo), &[], &post(&["origin", "main"]))
        .expect("probes");
    assert_eq!(updates, Vec::new());
    remove(repo.parent().expect("root"));
}

/// A destination Git cannot reach yields no capture, so the probe fails instead of reporting no updates.
#[test]
fn an_unreachable_destination_fails_the_probe() {
    let (repo, _origin, _base) = repository_with_origin("mp-probe-unreachable");
    git(
        &repo,
        &["commit", "--quiet", "--allow-empty", "--message=next"],
    );
    let missing = repo.parent().expect("root").join("missing.git");
    let result = probe_manual_push_updates(
        &git_for(&repo),
        &[],
        &post(&[missing.to_str().expect("utf-8"), "main"]),
    );
    assert!(result.is_err());
    remove(repo.parent().expect("root"));
}

/// Confirmation refuses a destination whose value differs from the negotiated one.
#[test]
fn confirmation_refuses_a_remote_ref_that_changed_after_negotiation() {
    let (repo, origin, base) = repository_with_origin("mp-confirm-changed");
    let changed = ProbedUpdate {
        local_ref: "refs/heads/main".to_owned(),
        local_oid: head_of(&repo),
        remote_name: "origin".to_owned(),
        remote_location: origin.to_str().expect("utf-8").to_owned(),
        remote_ref: "refs/heads/main".to_owned(),
        advertised_remote_oid: "1".repeat(40),
    };
    assert!(confirm_group(&git_for(&repo), origin.to_str().expect("utf-8"), &[changed]).is_err());
    let matching = ProbedUpdate {
        local_ref: "refs/heads/main".to_owned(),
        local_oid: head_of(&repo),
        remote_name: "origin".to_owned(),
        remote_location: origin.to_str().expect("utf-8").to_owned(),
        remote_ref: "refs/heads/main".to_owned(),
        advertised_remote_oid: base.clone(),
    };
    let confirmed = confirm_group(
        &git_for(&repo),
        origin.to_str().expect("utf-8"),
        &[matching],
    )
    .expect("confirms");
    assert_eq!(confirmed[0].remote_oid.as_deref(), Some(base.as_str()));
    remove(repo.parent().expect("root"));
}

/// A remote ref deleted after negotiation is refused: the advertised tip no longer exists.
#[test]
fn confirmation_refuses_a_remote_ref_deleted_after_negotiation() {
    let (repo, origin, base) = repository_with_origin("mp-confirm-deleted");
    let deleted = ProbedUpdate {
        local_ref: "refs/heads/main".to_owned(),
        local_oid: head_of(&repo),
        remote_name: "origin".to_owned(),
        remote_location: origin.to_str().expect("utf-8").to_owned(),
        remote_ref: "refs/heads/gone".to_owned(),
        advertised_remote_oid: base,
    };
    assert!(confirm_group(&git_for(&repo), origin.to_str().expect("utf-8"), &[deleted]).is_err());
    remove(repo.parent().expect("root"));
}

/// The scratch guard removes its directory when it is dropped, on every path.
#[test]
fn the_scratch_guard_removes_the_probe_directory() {
    let root = fixture("mp-scratch-guard");
    let scratch = root.join("probe");
    std::fs::create_dir_all(scratch.join("captures")).expect("scratch");
    drop(ScratchGuard(scratch.clone()));
    assert!(!scratch.exists());
    remove(&root);
}

/// A probe that fails before or after Git ran leaves no scratch directory: the captures name unpublished refs.
#[test]
fn a_failed_probe_removes_its_scratch_directory() {
    let root = fixture("mp-scratch-failure");
    let (repo, _origin, _base) = repository_with_origin("mp-scratch-failure-repo");
    // Git cannot start.
    let missing = PushGit {
        real_git: PathBuf::from("/nonexistent/git"),
        cwd: repo.clone(),
        environment: fixture_environment(),
        lfs_pre_push: None,
    };
    let not_started = root.join("not-started");
    assert!(capture_probed_updates(&missing, &[], &[], &not_started).is_err());
    assert!(!not_started.exists(), "the scratch directory of a probe that could not start remains");
    // Git runs, and the hook captures nothing because the remote cannot be reached.
    let nothing_captured = root.join("nothing-captured");
    let unreachable = post(&["/nonexistent-remote-for-the-probe", "main"]);
    assert!(capture_probed_updates(&git_for(&repo), &[], &unreachable, &nothing_captured).is_err());
    assert!(!nothing_captured.exists(), "the scratch directory of a probe with no capture remains");
    // A scratch path that exists already is not adopted and not removed.
    let present = root.join("present");
    std::fs::create_dir_all(&present).expect("present");
    assert!(capture_probed_updates(&git_for(&repo), &[], &[], &present).is_err());
    assert!(present.exists(), "a directory the probe did not create was removed");
    remove(repo.parent().expect("root"));
    remove(&root);
}

/// The probe makes its private directory in the per-user scratch directory of the push's environment, never in the
/// system temporary directory (the environment's `TMPDIR` names a path that does not exist), and leaves nothing there.
#[test]
fn the_probe_scratch_lives_in_the_per_user_scratch_directory_and_is_removed() {
    let (repo, _origin, _base) = repository_with_origin("mp-scratch-location");
    git(&repo, &["commit", "--quiet", "--allow-empty", "--message=next"]);
    let unusable = home_beside(&repo).join("no-such-tmpdir");
    let mut pushing = git_for(&repo);
    pushing.environment.push((OsString::from("TMPDIR"), unusable.clone().into_os_string()));
    let updates = probe_manual_push_updates(&pushing, &[], &post(&["origin", "main"])).expect("probes");
    assert_eq!(updates.len(), 1);
    let scratch = home_beside(&repo).join(".local/state/cli-git/scratch");
    let left: Vec<OsString> = fs::read_dir(&scratch)
        .expect("the per-user scratch directory exists")
        .map(|entry| { return entry.expect("entry").file_name(); })
        .collect();
    assert!(left.is_empty(), "nothing is left in {}: {left:?}", scratch.display());
    assert!(!unusable.exists(), "nothing created the unusable temporary directory");
    remove(repo.parent().expect("root"));
}

/// A push environment with no state directory and no home fails the probe naming the variables, and the system
/// temporary directory is not a fallback.
#[test]
fn the_probe_without_a_home_fails_naming_the_variables() {
    let (repo, _origin, _base) = repository_with_origin("mp-scratch-no-home");
    let homeless = PushGit {
        real_git: PathBuf::from("/usr/bin/git"),
        cwd: repo.clone(),
        environment: fixture_environment(),
        lfs_pre_push: None,
    };
    let error = probe_manual_push_updates(&homeless, &[], &post(&["origin", "main"])).expect_err("no home");
    assert!(error.message.contains("XDG_STATE_HOME") && error.message.contains("HOME"), "{}", error.message);
    remove(repo.parent().expect("root"));
}

/// The probe error prints as its diagnostic, so a refused push names what could not be established.
#[test]
fn the_probe_error_displays_its_message() {
    let error = ManualPushProbeError {
        message: String::from("the probe could not run"),
    };
    assert_eq!(error.to_string(), "the probe could not run");
}

/// The recording hook accepts exactly 16 MiB of standard input, the incumbent's limit.
#[test]
fn the_hook_input_limit_is_sixteen_mebibytes() {
    assert_eq!(MAX_HOOK_INPUT_BYTES, 16_777_216);
}