monochromatic-git-policy-cli 0.5.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
//! Controls for the deadline-bound push runner:
//!  real child processes that finish, fail, stall, ignore the stop request or flood their output,
//!  and the limits derived from the environment.

use super::*;
use crate::test_support::scratch_environment;
use std::ffi::OsStr;

/// An environment holding the given pairs.
fn environment(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
    let mut built: Vec<(OsString, OsString)> = Vec::new();
    for (name, value) in pairs {
        built.push((OsString::from(name), OsString::from(value)));
    }
    return built;
}

/// A shell command running `script`.
#[cfg(unix)]
fn shell(script: &str) -> Command {
    let mut command: Command = Command::new("sh");
    command.arg("-c").arg(script);
    return command;
}

/// The deadline is the default without the variable and the variable's whole seconds with it,
///  and the last of repeated entries wins.
#[test]
fn the_deadline_comes_from_the_variable_or_the_default() {
    assert_eq!(push_deadline(&[]), DEFAULT_PUSH_DEADLINE);
    // The default only has to bound the push: a zero default would stop every push at once.
    assert!(DEFAULT_PUSH_DEADLINE > Duration::ZERO);
    assert_eq!(
        push_deadline(&environment(&[(PUSH_DEADLINE_VARIABLE, "45")])),
        Duration::from_secs(45)
    );
    assert_eq!(
        push_deadline(&environment(&[(PUSH_DEADLINE_VARIABLE, " 7 ")])),
        Duration::from_secs(7)
    );
    assert_eq!(
        push_deadline(&environment(&[
            (PUSH_DEADLINE_VARIABLE, "10"),
            ("OTHER", "99"),
            (PUSH_DEADLINE_VARIABLE, "20"),
        ])),
        Duration::from_secs(20)
    );
}

/// A zero, negative, fractional, empty or non-numeric value never means "no deadline".
#[test]
fn an_unusable_deadline_falls_back_to_the_default() {
    for value in ["0", "-5", "1.5", "", "soon", "10s"] {
        assert_eq!(
            push_deadline(&environment(&[(PUSH_DEADLINE_VARIABLE, value)])),
            DEFAULT_PUSH_DEADLINE,
            "{value:?}"
        );
    }
}

/// A value that is not valid text is unusable too.
#[cfg(unix)]
#[test]
fn a_non_text_deadline_falls_back_to_the_default() {
    use std::os::unix::ffi::OsStringExt;
    let pairs: Vec<(OsString, OsString)> = vec![(
        OsString::from(PUSH_DEADLINE_VARIABLE),
        OsString::from_vec(vec![0xff, 0xfe]),
    )];
    assert_eq!(push_deadline(&pairs), DEFAULT_PUSH_DEADLINE);
}

/// The lock wait outlasts the holder's whole push,
///  its stop grace and the margin,
///  and a huge deadline saturates instead of overflowing.
#[test]
fn the_lock_wait_outlasts_the_holders_whole_push() {
    let derived = |deadline: Duration| -> Duration {
        return deadline * HOLDER_BUDGET_DEADLINES + STOP_GRACE * 2 + LOCK_WAIT_MARGIN;
    };
    assert_eq!(lock_wait_limit(&[]), derived(DEFAULT_PUSH_DEADLINE));
    let hundred: Duration = Duration::from_secs(100);
    assert_eq!(lock_wait_limit(&environment(&[(PUSH_DEADLINE_VARIABLE, "100")])), derived(hundred));
    assert!(lock_wait_limit(&[]) > holder_budget(&[]) + STOP_GRACE, "the waiter outlasts a holder that uses its whole budget");
    assert_eq!(
        lock_wait_limit(&environment(&[(PUSH_DEADLINE_VARIABLE, "18446744073709551615")])),
        Duration::MAX
    );
}

/// The lock wait variable replaces the derived limit,
///  and an unusable value is ignored.
#[test]
fn the_lock_wait_variable_replaces_the_derived_limit() {
    assert_eq!(
        lock_wait_limit(&environment(&[
            (PUSH_DEADLINE_VARIABLE, "100"),
            (LOCK_WAIT_VARIABLE, "7"),
        ])),
        Duration::from_secs(7)
    );
    for value in ["0", "", "later", "-1"] {
        assert_eq!(
            lock_wait_limit(&environment(&[(LOCK_WAIT_VARIABLE, value)])),
            lock_wait_limit(&[]),
            "{value:?}"
        );
    }
}

/// The low-speed defaults are added when absent and each is left alone when the person set it.
#[test]
fn low_speed_defaults_never_override_the_environment() {
    let mut bare: Command = Command::new("git");
    apply_low_speed_defaults(&mut bare, &[]);
    let added: Vec<(&OsStr, Option<&OsStr>)> = bare.get_envs().collect();
    assert_eq!(
        added,
        vec![
            (
                OsStr::new("GIT_HTTP_LOW_SPEED_LIMIT"),
                Some(OsStr::new(LOW_SPEED_LIMIT))
            ),
            (
                OsStr::new("GIT_HTTP_LOW_SPEED_TIME"),
                Some(OsStr::new(LOW_SPEED_TIME))
            ),
        ]
    );
    let mut limited: Command = Command::new("git");
    apply_low_speed_defaults(
        &mut limited,
        &environment(&[("GIT_HTTP_LOW_SPEED_LIMIT", "1")]),
    );
    let only_time: Vec<(&OsStr, Option<&OsStr>)> = limited.get_envs().collect();
    assert_eq!(
        only_time,
        vec![(
            OsStr::new("GIT_HTTP_LOW_SPEED_TIME"),
            Some(OsStr::new(LOW_SPEED_TIME))
        )]
    );
    let mut both: Command = Command::new("git");
    apply_low_speed_defaults(
        &mut both,
        &environment(&[
            ("GIT_HTTP_LOW_SPEED_LIMIT", "1"),
            ("GIT_HTTP_LOW_SPEED_TIME", "2"),
        ]),
    );
    assert_eq!(both.get_envs().count(), 0);
    let mut only_limit: Command = Command::new("git");
    apply_low_speed_defaults(
        &mut only_limit,
        &environment(&[("GIT_HTTP_LOW_SPEED_TIME", "2")]),
    );
    let remaining: Vec<(&OsStr, Option<&OsStr>)> = only_limit.get_envs().collect();
    assert_eq!(
        remaining,
        vec![(
            OsStr::new("GIT_HTTP_LOW_SPEED_LIMIT"),
            Some(OsStr::new(LOW_SPEED_LIMIT))
        )]
    );
}

/// Exactly one trailing line break goes, of either kind.
#[test]
fn one_trailing_line_break_is_removed() {
    assert_eq!(strip_one_line_break("a\n"), "a");
    assert_eq!(strip_one_line_break("a\r\n"), "a");
    assert_eq!(strip_one_line_break("a\n\n"), "a\n");
    assert_eq!(strip_one_line_break("a"), "a");
    assert_eq!(strip_one_line_break("a\r"), "a\r");
    assert_eq!(strip_one_line_break(""), "");
}

/// A push that ends in time reports its exit code and both streams in the order written.
#[cfg(unix)]
#[test]
fn a_finished_push_keeps_the_interleaved_output_and_exit_code() {
    let attempt: PushAttempt = run_bounded_push(
        shell("echo one; echo two >&2; echo three; exit 3"),
        Duration::from_secs(60),
        Duration::from_secs(1),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, 3);
    assert_eq!(attempt.output, "one\ntwo\nthree");
    let clean: PushAttempt = run_bounded_push(
        shell("echo remote: done"),
        Duration::from_secs(60),
        Duration::from_secs(1),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(clean.exit_code, 0);
    assert_eq!(clean.output, "remote: done");
}

/// A push ended by a signal has no exit code and reports one,
///  and it is not mistaken for a stopped push.
#[cfg(unix)]
#[test]
fn a_push_ended_by_a_signal_reports_one() {
    let attempt: PushAttempt = run_bounded_push(
        shell("echo before; kill -9 $$"),
        Duration::from_secs(60),
        Duration::from_secs(1),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, 1);
    assert_eq!(attempt.output, "before");
}

/// A stalled push is stopped at its deadline and becomes a failed attempt that says why,
///  keeping what it printed first.
#[cfg(unix)]
#[test]
fn a_stalled_push_is_stopped_at_its_deadline() {
    let deadline: Duration = Duration::from_millis(300);
    let started: Instant = Instant::now();
    let attempt: PushAttempt = run_bounded_push(
        shell("echo started; exec sleep 8"),
        deadline,
        Duration::from_secs(10),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    let elapsed: Duration = started.elapsed();
    assert!(elapsed >= deadline, "{elapsed:?}");
    assert!(elapsed < Duration::from_secs(20), "{elapsed:?}");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(
        attempt.output.starts_with("started\n"),
        "{}",
        attempt.output
    );
    assert!(
        attempt.output.contains(
            format!(
                "did not finish within {} seconds and was stopped",
                deadline.as_secs()
            )
            .as_str()
        ),
        "{}",
        attempt.output
    );
    assert!(
        attempt.output.contains(PUSH_DEADLINE_VARIABLE),
        "{}",
        attempt.output
    );
}

/// A stalled push that printed nothing reports only the reason.
#[cfg(unix)]
#[test]
fn a_silent_stalled_push_reports_only_the_reason() {
    let attempt: PushAttempt = run_bounded_push(
        shell("exec sleep 8"),
        Duration::from_millis(200),
        Duration::from_secs(10),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(
        attempt
            .output
            .starts_with("cli-git: git push did not finish"),
        "{}",
        attempt.output
    );
}

/// A push that ignores the stop request is killed once the grace passes.
#[cfg(unix)]
#[test]
fn a_push_that_ignores_the_stop_request_is_killed_after_the_grace() {
    let deadline: Duration = Duration::from_millis(200);
    let grace: Duration = Duration::from_millis(400);
    let started: Instant = Instant::now();
    let attempt: PushAttempt = run_bounded_push(
        shell("trap '' TERM; echo up; exec sleep 8"),
        deadline,
        grace,
        scratch_environment().as_slice(),
    )
    .expect("runs");
    let elapsed: Duration = started.elapsed();
    assert!(elapsed >= deadline + grace, "{elapsed:?}");
    assert!(elapsed < Duration::from_secs(20), "{elapsed:?}");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(attempt.output.starts_with("up\n"), "{}", attempt.output);
}

/// A push that honors the stop request is asked first:
///  it sees the request and ends by itself before the grace is used up.
#[cfg(unix)]
#[test]
fn a_push_that_honors_the_stop_request_ends_within_the_grace() {
    let attempt: PushAttempt = run_bounded_push(
        shell("trap 'echo got-the-request; exit 0' TERM; echo up; while :; do sleep 0.05; done"),
        Duration::from_millis(200),
        Duration::from_secs(3),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(
        attempt.output.contains("got-the-request\n"),
        "{}",
        attempt.output
    );
}

/// The grace is over exactly when the time since the request reaches it.
#[test]
fn the_grace_is_over_at_its_length_exactly() {
    let grace: Duration = Duration::from_millis(400);
    assert!(grace_remains(Duration::from_millis(399), grace));
    assert!(!grace_remains(grace, grace));
    assert!(!grace_remains(Duration::from_millis(401), grace));
}

/// An output is a flood only when it is larger than the cap.
#[test]
fn an_output_is_a_flood_only_past_the_cap() {
    assert!(!is_flood(MAX_PUSH_OUTPUT - 1));
    assert!(!is_flood(MAX_PUSH_OUTPUT));
    assert!(is_flood(MAX_PUSH_OUTPUT + 1));
}

/// A push that floods its output is stopped,
///  and only the capped part is kept.
#[cfg(unix)]
#[test]
fn a_flooding_push_is_stopped_and_its_output_capped() {
    // The producer writes twice the cap, so the case holds for any cap the constant takes.
    let flood: String = format!("head -c {} /dev/zero; exec sleep 8", MAX_PUSH_OUTPUT * 2);
    let attempt: PushAttempt = run_bounded_push(
        shell(flood.as_str()),
        Duration::from_secs(60),
        Duration::from_secs(10),
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(
        attempt.output.contains("bytes of output and was stopped. Hint: if a hook or the remote prints this much"),
        "{}",
        &attempt.output[attempt.output.len().saturating_sub(120)..]
    );
    assert!(
        attempt.output.len() < 2 * MAX_PUSH_OUTPUT as usize,
        "{}",
        attempt.output.len()
    );
}

/// A program that cannot start is a start failure, not a push result.
#[test]
fn a_program_that_cannot_start_is_a_start_failure() {
    let failure: SingleFlightError = run_bounded_push(
        Command::new("/nonexistent/cli-git-push-fixture"),
        Duration::from_secs(5),
        Duration::from_secs(1),
        scratch_environment().as_slice(),
    )
    .expect_err("no such program");
    assert!(matches!(failure, SingleFlightError::Start(_)), "{failure}");
}

/// A step that comes after the holder's time budget is spent is not started at all: the program named here does not
///  exist, so a start would be an error, and the answer is the stopped status with the budget's words.
#[test]
fn a_step_after_the_budget_is_spent_is_not_started() {
    let _budget = crate::holder_budget::enter(Duration::ZERO);
    let attempt: PushAttempt = run_bounded_push(
        Command::new("/nonexistent/never-started"),
        DEFAULT_PUSH_DEADLINE,
        STOP_GRACE,
        scratch_environment().as_slice(),
    )
    .expect("no start was attempted");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert_eq!(attempt.output, budget_spent_message());
}

/// A step under a budget is stopped at what is left of it, not at its own longer deadline.
#[cfg(unix)]
#[test]
fn a_step_under_a_budget_is_stopped_when_the_budget_runs_out() {
    let left: Duration = Duration::from_millis(300);
    let _budget = crate::holder_budget::enter(left);
    let started: Instant = Instant::now();
    let attempt: PushAttempt = run_bounded_push(
        shell("exec sleep 3000"),
        DEFAULT_PUSH_DEADLINE,
        STOP_GRACE,
        scratch_environment().as_slice(),
    )
    .expect("runs");
    assert_eq!(attempt.exit_code, STOPPED_EXIT_CODE);
    assert!(started.elapsed() < DEFAULT_PUSH_DEADLINE, "stopped by the budget, not by its own deadline");
}