mkit-cli 0.5.0

The mkit command-line tool: a content-addressed VCS with native attestation support
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! `mkit serve`'s own code: repo resolution, the stdio adapter and its idle
//! timeout, the session cap flag and the startup sweep. The session's
//! frame-level behavior is tested in `mkit-server` (`ssh::tests`); the
//! golden sessions run through the real binary in `tests/serve_golden.rs`.

use std::fs;
use std::io::{self, Cursor, Read};
use std::path::Path;
use std::time::{Duration, Instant};

use mkit_core::hash::hash;
use mkit_core::protocol::{PackKey, RefWriteCondition, Transport as _};
use mkit_rpc::mkit::rpc::v1::ssh::{
    Close, Hello, HelloResponse, PackChunk, SshFrame, UploadPack, ssh_frame,
};
use mkit_rpc::mkit::rpc::v1::{ErrorCode, ProtocolVersion};
use mkit_transport_file::FileTransport;

use super::*;
use crate::exit;

const GOLDEN_IN: &[u8] = include_bytes!("../../../../../tests/golden/ssh-serve/session-1.in.bin");
const GOLDEN_OUT: &[u8] = include_bytes!("../../../../../tests/golden/ssh-serve/session-1.bin");
/// The `server_id` the golden sessions were captured with.
const GOLDEN_SERVER_ID: &str = "mkit serve/0.4.2";

type Body = ssh_frame::Body;

// ---------------------------------------------------------------- helpers

fn repo_root() -> tempfile::TempDir {
    let td = tempfile::tempdir().unwrap();
    fs::create_dir_all(td.path().join(".mkit")).unwrap();
    td
}

fn frame(body: Body) -> SshFrame {
    SshFrame {
        body: Some(body),
        ..Default::default()
    }
}

fn hello() -> Body {
    Body::Hello(Box::new(
        Hello::default().with_proto(ProtocolVersion::ProtocolVersion1),
    ))
}

fn close() -> Body {
    Body::Close(Box::<Close>::default())
}

fn encode(bodies: impl IntoIterator<Item = Body>) -> Vec<u8> {
    let mut out = Vec::new();
    for body in bodies {
        mkit_rpc::write_frame(&mut out, &frame(body)).unwrap();
    }
    out
}

fn decode(mut bytes: &[u8]) -> Vec<SshFrame> {
    let mut out = Vec::new();
    while !bytes.is_empty() {
        out.push(mkit_rpc::read_frame::<_, SshFrame>(&mut bytes).unwrap());
    }
    out
}

fn assert_error(f: &SshFrame, code: ErrorCode, message: &str) {
    let Some(Body::Error(e)) = &f.body else {
        panic!("expected Error, got {:?}", f.body);
    };
    assert!(e.code.is_some_and(|c| c == code), "code of {e:?}");
    assert_eq!(e.message.as_deref(), Some(message));
}

/// The plain-mode target `mkit serve <path>` serves.
fn plain_target(root: &Path) -> ServeTarget {
    ServeTarget {
        root: root.to_path_buf(),
        repo: repo_id(),
        write_policy: WritePolicy::Open,
        principal: Principal::SshForcedCommand { key: None },
    }
}

/// `serve_stdio` over in-memory streams, with the output bytes.
fn serve(root: &Path, input: impl Read + Send + 'static, idle: Option<Duration>) -> (u8, Vec<u8>) {
    let mut out = Vec::new();
    let code = serve_stdio(&plain_target(root), input, &mut out, idle, false);
    (code, out)
}

/// The golden patterned pack bytes (`mkit-server`'s `ssh::tests`).
fn pack_bytes(len: usize, seed: u8) -> Vec<u8> {
    #[allow(clippy::cast_possible_truncation)]
    (0..len)
        .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
        .collect()
}

/// `golden` with its `HelloResponse` (the first frame) re-encoded with
/// this build's `server_id`, so the pin survives a version bump; the rest
/// is compared byte for byte.
fn with_current_server_id(golden: &[u8]) -> Vec<u8> {
    let mut tail = golden;
    let first: SshFrame = mkit_rpc::read_frame(&mut tail).unwrap();
    let resp = HelloResponse {
        proto: Some(ProtocolVersion::ProtocolVersion1.into()),
        server_id: Some(GOLDEN_SERVER_ID.to_owned()),
        ..Default::default()
    };
    assert_eq!(first, frame(Body::HelloResponse(Box::new(resp.clone()))));
    let current = HelloResponse {
        server_id: Some(format!("mkit serve/{CLI_VERSION}")),
        ..resp
    };
    let mut out = Vec::new();
    mkit_rpc::write_frame(&mut out, &frame(Body::HelloResponse(Box::new(current)))).unwrap();
    out.extend_from_slice(tail);
    out
}

/// A reader that serves `bytes` in `piece`-byte reads, sleeping `gap`
/// before each (and `first_gap` before the first).
struct Trickle {
    bytes: Cursor<Vec<u8>>,
    piece: usize,
    first_gap: Duration,
    gap: Duration,
    started: bool,
}

impl Read for Trickle {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let gap = if self.started {
            self.gap
        } else {
            self.first_gap
        };
        self.started = true;
        std::thread::sleep(gap);
        let n = buf.len().min(self.piece);
        self.bytes.read(&mut buf[..n])
    }
}

// ------------------------------------------------------------- resolution

#[test]
fn resolve_repo_path_rejects_missing_path() {
    let err = resolve_repo_path("/definitely/does/not/exist/xyzzy").unwrap_err();
    assert_eq!(err, exit::NOINPUT);
}

// ------------------------------------------------- --principal (Test 5)

/// A namespace every root-mode fixture uses: `ed25519-<64 lowercase hex>`.
const NS: &str = "ed25519-abababababababababababababababababababababababababababababababab";

fn parse_opts(a: &[&str]) -> Result<ServeOpts, u8> {
    let args = a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
    clap_shim::parse::<ServeOpts>("mkit serve", &args)
}

/// `--principal` accepts only the raw 32-byte key as 64 lowercase hex.
#[test]
fn principal_flag_accepts_raw_hex_only() {
    let hex = "ab".repeat(32);
    let opts = parse_opts(&["repo", "--principal", &hex]).unwrap();
    assert_eq!(opts.principal, Some([0xab; 32]));
    let zero = "00".repeat(32);
    assert_eq!(
        parse_opts(&["repo", "--principal", &zero])
            .unwrap()
            .principal,
        Some([0; 32])
    );
    for bad in [
        "ABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABABAB", // uppercase
        &"ab".repeat(31)[..62],                                             // too short
        &"ab".repeat(33),                                                   // too long
        &format!("ed25519-{hex}"),                                          // prefixed
        &format!("0x{}", &hex[..62]),                                       // 0x
        &format!("{}gg", "ab".repeat(31)),                                  // non-hex
        "",
    ] {
        // Clap's value parser refuses the flag before any frame is read;
        // `InvalidValue` maps to DATAERR like `--commit not-a-hash`.
        assert_eq!(
            parse_opts(&["repo", "--principal", bad]).unwrap_err(),
            exit::DATAERR,
            "{bad:?} must be refused before any frame is read"
        );
    }
}

// -------------------------------------------- SSH_ORIGINAL_COMMAND (Test 7)

#[test]
fn original_command_accepts_exactly_mkit_serve_path() {
    let path = format!("{NS}/room-a");
    let command = format!("mkit serve {path}");
    assert_eq!(parse_original_command(&command), Some(path.as_str()));
    // A path with every permitted byte class.
    assert_eq!(
        parse_original_command("mkit serve a-b_c.d/e"),
        Some("a-b_c.d/e")
    );
    for bad in [
        "mkit serve",             // no path
        "mkit serve a b",         // extra argument
        "mkit serve  a",          // double space
        "mkit  serve a",          // double space
        " mkit serve a",          // leading space
        "mkit serve a ",          // trailing space
        "mkit serve\ta",          // tab
        "mkit serve a\n",         // LF
        "mkit serve a\r\n",       // CRLF
        "mkit serve 'a'",         // quotes
        "mkit serve \"a\"",       // double quotes
        "mkit serve a; rm -rf /", // shell metachar
        "mkit serve $(id)",       // command substitution
        "mkit serve `id`",        // backticks
        "mkit serve a\0b",        // NUL
        "sh -c mkit serve a",     // a wrapper
        "mkit serve --root /srv", // smuggled flag (3+ tokens)
        "mkit serve --principal", // flag as path
        "mkit serve -a",          // flag as path
        "mkit serve --",          // flag as path
        "mkit update-ref a",      // another verb
        "MKIT serve a",           // case
        "mkit serve a>b",         // redirect
        "mkit serve a|b",         // pipe
    ] {
        assert_eq!(parse_original_command(bad), None, "{bad:?}");
    }
    // `parse_original_command` checks only the command's shape: a path the
    // identity grammar will refuse still comes back, to fail downstream.
    assert_eq!(parse_original_command("mkit serve /a/"), Some("/a/"));
}

// -------------------------------------------------- --root resolution (Test 6)

/// A root holding `<ns>/<name>` repository dirs, canonicalized.
fn root_mode_root(names: &[(&str, &str)]) -> (tempfile::TempDir, std::path::PathBuf) {
    let td = tempfile::tempdir().unwrap();
    for (ns, name) in names {
        fs::create_dir_all(td.path().join(ns).join(name).join(".mkit")).unwrap();
    }
    let root = fs::canonicalize(td.path()).unwrap();
    (td, root)
}

#[test]
fn root_repo_resolves_namespaced_path() {
    let (_td, root) = root_mode_root(&[(NS, "room-a"), (NS, "room-b")]);
    for path in [
        format!("{NS}/room-a"),
        format!("/{NS}/room-a"),
        format!("{NS}/room-a/"),
        format!("/{NS}/room-a/"),
    ] {
        let (dir, repo) = resolve_root_repo(&root, &path).unwrap();
        assert_eq!(dir, root.join(NS).join("room-a"));
        assert_eq!(repo.name.as_str(), "room-a");
        assert_eq!(repo.namespace.as_str(), NS);
    }
    // The other repository resolves to its own dir.
    let (dir, repo) = resolve_root_repo(&root, &format!("{NS}/room-b")).unwrap();
    assert_eq!(dir, root.join(NS).join("room-b"));
    assert_eq!(repo.name.as_str(), "room-b");
}

#[test]
fn root_repo_refuses_bad_identities() {
    let (_td, root) = root_mode_root(&[(NS, "room-a")]);
    for (path, code) in [
        ("room-a", exit::USAGE),                                 // bare name
        (&format!("{NS}/room-a/x")[..], exit::USAGE),            // extra component
        (&format!("{}/room-a", NS.to_uppercase()), exit::USAGE), // uppercase
        (&format!("{NS}/../room-a"), exit::USAGE),               // dotdot
        (&format!("{NS}/room-a/../room-b"), exit::USAGE),
        ("", exit::USAGE),
        ("/", exit::USAGE),
    ] {
        assert_eq!(resolve_root_repo(&root, path).unwrap_err(), code, "{path}");
    }
    // A 0x namespace is a valid identity but its directory must exist.
    let addr = format!("0x{}", "ab".repeat(20));
    assert_eq!(
        resolve_root_repo(&root, &format!("{addr}/room-a")).unwrap_err(),
        exit::NOINPUT
    );
}

#[test]
fn root_repo_refuses_symlinked_components() {
    let (_td, root) = root_mode_root(&[(NS, "room-a")]);
    let target = tempfile::tempdir().unwrap();
    // A repository dir outside the root, linked from `<root>/<ns2>`: the
    // addressed path resolves through the link but its canonical form
    // differs from `<root>/<ns2>/room-a`.
    fs::create_dir_all(target.path().join("room-a/.mkit")).unwrap();
    let ns2 = format!("ed25519-{}", "cd".repeat(32));
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target.path(), root.join(&ns2)).unwrap();
        assert_eq!(
            resolve_root_repo(&root, &format!("{ns2}/room-a")).unwrap_err(),
            exit::NOPERM,
            "a symlinked namespace dir must not alias another repository"
        );
        // Even a symlink inside the root aliasing a real dir: canonical
        // must equal the addressed path exactly.
        let ns3 = format!("ed25519-{}", "ef".repeat(32));
        fs::create_dir_all(root.join("real/repo/.mkit")).unwrap();
        std::os::unix::fs::symlink(root.join("real"), root.join(&ns3)).unwrap();
        assert_eq!(
            resolve_root_repo(&root, &format!("{ns3}/repo")).unwrap_err(),
            exit::NOPERM
        );
        // The repository dir itself is a symlink into another repo.
        let ns4 = format!("ed25519-{}", "12".repeat(32));
        fs::create_dir(root.join(&ns4)).unwrap();
        std::os::unix::fs::symlink(root.join(NS).join("room-a"), root.join(&ns4).join("room-a"))
            .unwrap();
        assert_eq!(
            resolve_root_repo(&root, &format!("{ns4}/room-a")).unwrap_err(),
            exit::NOPERM
        );
    }
}

#[test]
fn root_repo_requires_a_repo_dir() {
    let td = tempfile::tempdir().unwrap();
    let root = fs::canonicalize(td.path()).unwrap();
    // Missing entirely.
    assert_eq!(
        resolve_root_repo(&root, &format!("{NS}/gone")).unwrap_err(),
        exit::NOINPUT
    );
    // Present but no `.mkit`.
    fs::create_dir_all(root.join(NS).join("plain")).unwrap();
    assert_eq!(
        resolve_root_repo(&root, &format!("{NS}/plain")).unwrap_err(),
        exit::DATAERR
    );
    // A file, not a dir: canonicalize succeeds on a file, so DATAERR.
    fs::write(root.join(NS).join("file"), b"x").unwrap();
    assert_eq!(
        resolve_root_repo(&root, &format!("{NS}/file")).unwrap_err(),
        exit::DATAERR
    );
}

#[test]
fn resolve_repo_path_rejects_non_repo_dir() {
    let td = tempfile::tempdir().unwrap();
    let err = resolve_repo_path(td.path().to_str().unwrap()).unwrap_err();
    assert_eq!(err, exit::DATAERR);
}

#[test]
fn resolve_repo_path_accepts_repo_dir() {
    let td = repo_root();
    let resolved = resolve_repo_path(td.path().to_str().unwrap()).unwrap();
    assert!(resolved.join(".mkit").is_dir());
}

#[test]
fn removed_listener_flag_names_the_first_removed_flag() {
    let args = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
    assert_eq!(
        removed_listener_flag(&args(&["repo", "--http", "127.0.0.1:0"])),
        Some("--http")
    );
    assert_eq!(
        removed_listener_flag(&args(&["--enc-idle-timeout-secs=5", "--listen-enc", "x"])),
        Some("--enc-idle-timeout-secs")
    );
    // Not a removed flag, a prefix of one, anything after `--`, or the
    // idle timeout `mkit serve` does take.
    assert_eq!(removed_listener_flag(&args(&["repo", "--bogus"])), None);
    assert_eq!(removed_listener_flag(&args(&["--htt", "repo"])), None);
    assert_eq!(removed_listener_flag(&args(&["--", "--http"])), None);
    assert_eq!(
        removed_listener_flag(&args(&["repo", "--idle-timeout-secs", "5"])),
        None
    );
}

/// Both timeout flags are bounded at 7 days; past that clap refuses the
/// value (no `Instant` overflow can follow from a huge one).
#[test]
fn timeout_flags_are_bounded() {
    let parse = |a: &[&str]| {
        let args = a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
        clap_shim::parse::<ServeOpts>("mkit serve", &args)
    };
    let week = MAX_TIMEOUT_SECS.to_string();
    let over = (MAX_TIMEOUT_SECS + 1).to_string();
    for flag in ["--idle-timeout-secs", "--max-session-secs"] {
        assert!(parse(&["repo", flag, &week]).is_ok(), "{flag}");
        assert_eq!(
            parse(&["repo", flag, &over]).unwrap_err(),
            exit::DATAERR,
            "{flag}"
        );
        let max = u64::MAX.to_string();
        assert_eq!(
            parse(&["repo", flag, &max]).unwrap_err(),
            exit::DATAERR,
            "{flag}"
        );
    }
    let opts = parse(&["repo"]).unwrap();
    assert_eq!(
        opts.max_session_secs, 0,
        "the session cap is off by default"
    );
    assert_eq!(
        parse(&["repo", "--max-session-secs", "30"])
            .unwrap()
            .max_session_secs,
        30
    );
}

/// An idle timeout whose deadline an `Instant` cannot hold waits forever
/// instead of panicking.
#[test]
fn a_huge_idle_timeout_does_not_overflow() {
    let td = repo_root();
    let input = Cursor::new(encode([hello(), close()]));
    let (code, out) = serve(td.path(), input, Some(Duration::from_secs(u64::MAX)));
    assert_eq!(code, exit::OK);
    assert!(matches!(decode(&out)[0].body, Some(Body::HelloResponse(_))));
}

#[test]
fn idle_timeout_flag_defaults_to_60_and_takes_zero() {
    let parse = |a: &[&str]| {
        let args = a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
        clap_shim::parse::<ServeOpts>("mkit serve", &args).unwrap()
    };
    assert_eq!(parse(&["repo"]).idle_timeout_secs, 60);
    assert_eq!(
        parse(&["repo", "--idle-timeout-secs", "0"]).idle_timeout_secs,
        0
    );
    assert_eq!(
        parse(&["--idle-timeout-secs=5", "repo"]).idle_timeout_secs,
        5
    );
}

// ---------------------------------------------------------------- session

/// The M0-12 golden session through `serve_stdio`, over the `.mkit`
/// layout seeded as it was captured: refs `main`, `dev`, `tags/v1` and one
/// 1000-byte pack.
#[test]
fn serve_stdio_matches_golden_session() {
    let td = repo_root();
    let tx = FileTransport::new(td.path());
    for (name, id) in [
        ("refs/heads/main", [0x11; 32]),
        ("refs/heads/dev", [0x22; 32]),
        ("refs/tags/v1", [0x33; 32]),
    ] {
        tx.update_ref(name, RefWriteCondition::Any, &id).unwrap();
    }
    let seeded = pack_bytes(1000, 7);
    tx.upload_pack(&seeded, &PackKey::new(hash(&seeded)))
        .unwrap();

    let (code, out) = serve(
        td.path(),
        Cursor::new(GOLDEN_IN),
        Some(Duration::from_mins(1)),
    );
    assert_eq!(code, exit::OK);
    let want = with_current_server_id(GOLDEN_OUT);
    let (got_frames, want_frames) = (decode(&out), decode(&want));
    for (i, (g, w)) in got_frames.iter().zip(&want_frames).enumerate() {
        assert_eq!(g, w, "frame {i}");
    }
    assert_eq!(out, want);
    // The refs the session left are `FileTransport`'s files.
    assert_eq!(tx.read_ref("refs/heads/main").unwrap(), Some([0x44; 32]));
}

#[test]
fn idle_timeout_ends_session_with_protocol_error() {
    let td = repo_root();
    // A client that connects and sends nothing: the pipe's writer stays
    // open until the test ends.
    let (reader, _writer) = io::pipe().unwrap();
    let started = Instant::now();
    let (code, out) = serve(td.path(), reader, Some(Duration::from_millis(100)));
    assert!(
        started.elapsed() < Duration::from_secs(1),
        "{:?}",
        started.elapsed()
    );
    assert_eq!(code, exit::PROTOCOL_ERROR);
    let frames = decode(&out);
    assert_eq!(frames.len(), 1, "{frames:?}");
    assert_error(&frames[0], ErrorCode::InvalidRequest, "idle timeout");
}

#[test]
fn zero_disables_timeout() {
    let td = repo_root();
    let slow = Trickle {
        bytes: Cursor::new(encode([hello(), close()])),
        piece: usize::MAX,
        first_gap: Duration::from_millis(300),
        gap: Duration::ZERO,
        started: false,
    };
    let (code, out) = serve(td.path(), slow, None);
    assert_eq!(code, exit::OK);
    let frames = decode(&out);
    assert!(matches!(frames[0].body, Some(Body::HelloResponse(_))));
    // The same client against a 100 ms timeout is cut off before `Hello`.
    let slow = Trickle {
        bytes: Cursor::new(encode([hello(), close()])),
        piece: usize::MAX,
        first_gap: Duration::from_millis(300),
        gap: Duration::ZERO,
        started: false,
    };
    let (code, _) = serve(td.path(), slow, Some(Duration::from_millis(100)));
    assert_eq!(code, exit::PROTOCOL_ERROR);
}

/// An upload that keeps sending never trips the timeout, even though one
/// chunk frame takes several timeouts to arrive; a client that stops in
/// the middle of one does, and the upload is discarded.
#[test]
fn idle_timeout_counts_bytes_not_frames() {
    let pack = pack_bytes(4000, 3);
    let id = hash(&pack).to_vec();
    let header = Body::UploadPack(Box::new(UploadPack {
        pack_id: Some(id.clone()),
        total_bytes: Some(pack.len() as u64),
        ..Default::default()
    }));
    let chunk = Body::PackChunk(Box::new(PackChunk {
        pack_id: Some(id.clone()),
        offset: Some(0),
        data: Some(pack.clone()),
        last: Some(true),
        ..Default::default()
    }));
    let input = encode([hello(), header.clone(), chunk, close()]);

    // ~4 KiB at 400 bytes per 40 ms: about 400 ms, 4x the timeout.
    let td = repo_root();
    let trickle = Trickle {
        bytes: Cursor::new(input),
        piece: 400,
        first_gap: Duration::ZERO,
        gap: Duration::from_millis(40),
        started: false,
    };
    let (code, out) = serve(td.path(), trickle, Some(Duration::from_millis(100)));
    assert_eq!(code, exit::OK);
    let frames = decode(&out);
    assert!(
        matches!(frames[1].body, Some(Body::UploadPackResponse(_))),
        "{frames:?}"
    );
    let key = PackKey::new(hash(&pack));
    assert!(FileTransport::new(td.path()).pack_exists(&key).unwrap());

    // The header, then silence.
    let td = repo_root();
    let (reader, mut writer) = io::pipe().unwrap();
    io::Write::write_all(&mut writer, &encode([hello(), header])).unwrap();
    let (code, out) = serve(td.path(), reader, Some(Duration::from_millis(100)));
    assert_eq!(code, exit::PROTOCOL_ERROR);
    let frames = decode(&out);
    assert_error(&frames[1], ErrorCode::InvalidRequest, "idle timeout");
    assert!(!FileTransport::new(td.path()).pack_exists(&key).unwrap());
    let packs = td.path().join("packs");
    let left = fs::read_dir(&packs).map_or(0, Iterator::count);
    assert_eq!(left, 0, "the upload's temp file is removed");
    drop(writer);
}

#[test]
fn a_root_whose_refs_live_in_sqlite_is_refused() {
    let td = repo_root();
    fs::write(td.path().join(".mkit/server-meta"), b"sqlite").unwrap();
    let (code, out) = serve(td.path(), Cursor::new(encode([hello()])), None);
    assert_eq!(code, exit::CONFIG_ERROR);
    assert!(out.is_empty());
}

#[test]
fn stop_after_hello_ends_cleanly_after_the_handshake() {
    let td = repo_root();
    let input = Cursor::new(encode([hello(), close()]));
    let mut out = Vec::new();
    let code = serve_stdio(&plain_target(td.path()), input, &mut out, None, true);
    assert_eq!(code, exit::OK);
    let frames = decode(&out);
    assert_eq!(frames.len(), 1);
    assert!(matches!(frames[0].body, Some(Body::HelloResponse(_))));
}

// ------------------------------------------------------- startup upkeep

#[test]
fn startup_sweeps_crashed_uploads_only_when_no_server_holds_the_lock() {
    let td = repo_root();
    let packs = td.path().join("packs");
    fs::create_dir_all(&packs).unwrap();
    let stale = packs.join(format!(".{}.tmp.4242.0", "ab".repeat(32)));
    fs::write(&stale, b"partial").unwrap();
    let old = std::time::SystemTime::now() - Duration::from_hours(2);
    fs::File::options()
        .write(true)
        .open(&stale)
        .unwrap()
        .set_modified(old)
        .unwrap();

    // Another server is up (it holds `serve.lock` shared): no sweep.
    let dot_mkit = td.path().join(".mkit");
    let other = repo_lock::acquire_shared(
        &dot_mkit,
        crate::commands::SERVE_LOCK,
        repo_lock::DEFAULT_TIMEOUT,
    )
    .unwrap();
    let ours = lock_and_sweep(td.path()).unwrap();
    assert!(stale.exists(), "swept while another server was up");
    drop((ours, other));

    // Alone: swept, and the shared lock is held afterwards.
    let ours = lock_and_sweep(td.path()).unwrap();
    assert!(!stale.exists());
    assert!(!repo_lock::probe_exclusive(&dot_mkit, crate::commands::SERVE_LOCK).unwrap());
    drop(ours);
}