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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! End-to-end coverage for the `mkit+ssh://` transport and the issue
//! #389 trust-pinning wiring.
//!
//! ## What this proves
//!
//! 1. A full `mkit clone mkit+ssh://…` moves real data through the SSH
//!    transport: the `Hello` handshake, ref negotiation, and upload-pack
//!    all run against a real `mkit serve` on the far side. The cloned
//!    repo's HEAD ref and object content MATCH the source.
//!
//! 2. The per-repo `ssh.*` trust-pinning config keys
//!    (`ssh.strict_host_key_checking`, `ssh.user_known_hosts_file`,
//!    `ssh.identity_file`) actually reach the spawned `ssh` program as
//!    `-o StrictHostKeyChecking=…`, `-o UserKnownHostsFile=…`, and
//!    `-i …`. Before the #389 fix these keys were parsed into `Config`
//!    but never threaded into `SshOptions`, so the recorded argv would
//!    lack them — this test FAILS on the pre-fix code and PASSES after.
//!
//! ## How it stays hermetic
//!
//! `build_ssh_command` honours `MKIT_SSH_PROGRAM` (the testability seam
//! added for #389). We point it at a generated `/bin/sh` wrapper that:
//!
//!   (a) appends its entire argv to `$MKIT_SSH_ARGV_LOG`, then
//!   (b) finds the `mkit` token in that argv and `exec`s
//!       `$MKIT_SSH_TARGET_BIN serve <path>` locally with inherited
//!       stdin/stdout — i.e. it replaces the network hop with a local
//!       `mkit serve`, while still exercising the real wire protocol.
//!
//! Both env vars are set on the `mkit clone` process and inherited by the
//! spawned wrapper, so the script body stays fully static (no path is
//! interpolated into shell source).
//!
//! No sshd, no network, no `ssh` binary required. The higher-fidelity
//! real-`ssh(1)` variant lives in `ssh_e2e_real.rs` and is `#[ignore]`d.
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::{Command, Output, Stdio};

use mkit_core::layout::RepoLayout;
use mkit_core::ops::reachable_objects;
use mkit_core::refs;
use mkit_core::store::ObjectStore;

fn mkit_bin() -> &'static str {
    env!("CARGO_BIN_EXE_mkit")
}

/// Drive the real `mkit` binary, fully isolated from the developer's
/// environment. `extra_env` lets a test add the `MKIT_SSH_*` vars.
fn run_in(cwd: &Path, xdg: &Path, args: &[&str], extra_env: &[(&str, &str)]) -> Output {
    let mut cmd = Command::new(mkit_bin());
    cmd.args(args)
        .current_dir(cwd)
        .env("XDG_CONFIG_HOME", xdg)
        .env("HOME", xdg)
        .env("EDITOR", "true")
        .env("VISUAL", "true")
        .stdin(Stdio::null());
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.output().expect("spawn mkit")
}

/// Write the hermetic ssh-wrapper script and `chmod +x` it. The script
/// records its argv and execs `$MKIT_SSH_TARGET_BIN serve <path>`.
///
/// All dynamic inputs (the argv log path, the target binary) arrive via
/// the environment, so the script body is fully static — no path is
/// interpolated into shell source, leaving no injection surface. The
/// caller sets `MKIT_SSH_ARGV_LOG` and `MKIT_SSH_TARGET_BIN` on the
/// `mkit clone` process; `build_ssh_command` spawns this wrapper without
/// clearing the environment, so both vars reach it.
fn write_ssh_wrapper(dir: &Path) -> std::path::PathBuf {
    let wrapper = dir.join("fake_ssh.sh");
    // `set -eu`: fail loud on any error and on a missing MKIT_SSH_* var
    // rather than silently logging to nowhere or exec'ing an empty path.
    let script = r#"#!/bin/sh
set -eu

# Record the full argv this wrapper was invoked with, one token per line,
# framed by a record separator so the test can scan a single invocation.
{
  echo "=== ssh invocation ==="
  for a in "$@"; do
    printf '%s\n' "$a"
  done
} >> "$MKIT_SSH_ARGV_LOG"

# Find the `mkit serve <path>` triple at the tail of the argv and exec it
# locally. We walk forward to the literal `mkit` token; everything after
# `mkit serve` is the path.
found=0
path=""
for a in "$@"; do
  if [ "$found" = 2 ]; then
    path="$a"
    break
  fi
  if [ "$found" = 1 ] && [ "$a" = serve ]; then
    found=2
    continue
  fi
  if [ "$a" = mkit ]; then
    found=1
  fi
done

if [ -z "$path" ]; then
  echo "fake_ssh: could not locate 'mkit serve <path>' in argv" >&2
  exit 64
fi

exec "$MKIT_SSH_TARGET_BIN" serve "$path"
"#;
    fs::write(&wrapper, script).expect("write wrapper");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&wrapper).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&wrapper, perms).unwrap();
    }
    wrapper
}

/// Build `root/source` as a repo with real committed content. Returns
/// its path.
fn build_source(root: &Path, xdg: &Path) -> std::path::PathBuf {
    let source = root.join("source");
    fs::create_dir_all(&source).unwrap();
    assert!(
        run_in(&source, xdg, &["init"], &[]).status.success(),
        "init source"
    );
    assert!(
        run_in(&source, xdg, &["keygen"], &[]).status.success(),
        "keygen source"
    );
    fs::write(source.join("README.md"), b"# e2e ssh project\n").unwrap();
    fs::create_dir_all(source.join("src")).unwrap();
    fs::write(
        source.join("src/main.rs"),
        b"fn main() { println!(\"hi\"); }\n",
    )
    .unwrap();
    assert!(
        run_in(&source, xdg, &["add", "."], &[]).status.success(),
        "add source"
    );
    let commit = run_in(&source, xdg, &["commit", "-m", "e2e-1"], &[]);
    assert!(
        commit.status.success(),
        "commit source: {}",
        String::from_utf8_lossy(&commit.stderr)
    );
    source
}

/// Build a source repo with real committed content, then push it to a
/// freshly-initialised `remote` repo so the remote carries the packmap
/// refs that `clone` reconstructs from. Returns the served `remote`
/// repo path.
///
/// mkit's transfer dialect is packmap-only: a branch tip is only
/// fetchable once a push has advertised `refs/mkit/packmap/<branch>`. A
/// repo that was merely committed-to (never pushed) advertises no
/// packmap, so cloning it yields zero refs. We therefore serve a
/// push-populated remote, exactly as a real deployment would.
fn build_and_push_source(root: &Path, xdg: &Path) -> std::path::PathBuf {
    let source = build_source(root, xdg);

    let remote = root.join("remote");
    fs::create_dir_all(&remote).unwrap();
    assert!(
        run_in(&remote, xdg, &["init"], &[]).status.success(),
        "init remote"
    );
    let remote_url = format!("mkit+file://{}", remote.display());
    assert!(
        run_in(&source, xdg, &["remote", "add", "origin", &remote_url], &[])
            .status
            .success(),
        "remote add"
    );
    let push = run_in(&source, xdg, &["push", "origin"], &[]);
    assert!(
        push.status.success(),
        "push source -> remote: {}",
        String::from_utf8_lossy(&push.stderr)
    );
    remote
}

#[test]
fn ssh_clone_moves_data_and_delivers_pinned_options() {
    // Skip cleanly on non-unix where the /bin/sh wrapper can't run.
    if cfg!(not(unix)) {
        eprintln!("ssh_e2e: skipped (requires a POSIX shell)");
        return;
    }

    let work = tempfile::tempdir().expect("work tempdir");
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let root = work.path();

    // --- Source repo with real content, pushed to a served remote -------
    let remote = build_and_push_source(root, xdg.path());
    let source = root.join("source");
    let source_tip = refs::read_ref(&RepoLayout::single(&source), "main")
        .unwrap()
        .expect("source has refs/heads/main");

    // --- Pinned trust options: real files on disk -----------------------
    let known_hosts = root.join("project.known_hosts");
    fs::write(&known_hosts, b"# pinned known hosts for e2e\n").unwrap();
    let identity = root.join("id_ed25519_e2e");
    fs::write(&identity, b"-----BEGIN OPENSSH PRIVATE KEY-----\nfake\n").unwrap();
    // Must NOT be "accept-new": `build_ssh_command` emits
    // `StrictHostKeyChecking=accept-new` as its default baseline whenever
    // the configured value is empty, so an `accept-new` pin would pass the
    // assertion below even on pre-fix code. "yes" is only ever produced by
    // the live Config→SshOptions wiring, making the assertion discriminating.
    // The hermetic `fake_ssh.sh` shim ignores all `-o` options, so the
    // clone still succeeds regardless of the value.
    let strict_value = "yes";

    // Set the three ssh.* keys in the USER-scoped config (they are
    // REPO_FORBIDDEN_KEYS, so only user scope may set them). `mkit
    // config <key> <val>` writes to $XDG_CONFIG_HOME/mkit/config.
    for (key, val) in [
        ("ssh.strict_host_key_checking", strict_value),
        ("ssh.user_known_hosts_file", known_hosts.to_str().unwrap()),
        ("ssh.identity_file", identity.to_str().unwrap()),
    ] {
        let out = run_in(root, xdg.path(), &["config", key, val], &[]);
        assert!(
            out.status.success(),
            "set {key}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    // --- Hermetic ssh wrapper -------------------------------------------
    let argv_log = root.join("ssh_argv.log");
    let wrapper = write_ssh_wrapper(root);

    // --- Clone over mkit+ssh:// -----------------------------------------
    // We serve the push-populated `remote` repo (it carries the packmap
    // refs `clone` reconstructs from). The path must satisfy the strict
    // ssh-path charset (`[A-Za-z0-9._-/]`); tempdir paths qualify.
    let remote_path = remote.to_str().unwrap();
    let url = format!("mkit+ssh://e2euser@localhost{remote_path}");
    let dest = root.join("dest");
    let dest_str = dest.to_str().unwrap();

    let clone = run_in(
        root,
        xdg.path(),
        &["clone", &url, dest_str],
        &[
            ("MKIT_SSH_PROGRAM", wrapper.to_str().unwrap()),
            ("MKIT_SSH_ARGV_LOG", argv_log.to_str().unwrap()),
            ("MKIT_SSH_TARGET_BIN", mkit_bin()),
        ],
    );
    assert!(
        clone.status.success(),
        "clone over ssh must succeed; stderr:\n{}",
        String::from_utf8_lossy(&clone.stderr)
    );

    // --- (b) HEAD ref + object closure MATCH the source -----------------
    let dest_tip = refs::read_ref(&RepoLayout::single(&dest), "main")
        .unwrap()
        .expect("cloned repo has refs/heads/main");
    assert_eq!(
        source_tip, dest_tip,
        "cloned HEAD must equal source HEAD (real ref negotiation)"
    );

    let source_store = ObjectStore::open(&RepoLayout::single(&source)).unwrap();
    let dest_store = ObjectStore::open(&RepoLayout::single(&dest)).unwrap();
    let source_set: HashSet<_> = reachable_objects(&source_store, &source_tip)
        .unwrap()
        .into_iter()
        .collect();
    let dest_set: HashSet<_> = reachable_objects(&dest_store, &dest_tip)
        .unwrap()
        .into_iter()
        .collect();
    assert_eq!(
        source_set, dest_set,
        "object closures must match — proves real data moved through the transport"
    );
    assert!(
        source_set.len() >= 4,
        "closure must include >= commit + tree + 2 blobs"
    );

    // --- (c) The pinned options reached the spawned program -------------
    let log = fs::read_to_string(&argv_log).expect("argv log written by wrapper");
    // argv is logged one token per line; assert the consecutive
    // `-o <val>` / `-i <val>` pairs are present.
    let lines: Vec<&str> = log.lines().collect();
    assert!(
        has_pair(
            &lines,
            "-o",
            &format!("StrictHostKeyChecking={strict_value}")
        ),
        "ssh argv missing StrictHostKeyChecking; log:\n{log}"
    );
    assert!(
        has_pair(
            &lines,
            "-o",
            &format!("UserKnownHostsFile={}", known_hosts.display())
        ),
        "ssh argv missing UserKnownHostsFile; log:\n{log}"
    );
    assert!(
        has_pair(&lines, "-i", &identity.display().to_string()),
        "ssh argv missing identity file; log:\n{log}"
    );
}

/// True when `lines` contains `flag` immediately followed by `value`.
fn has_pair(lines: &[&str], flag: &str, value: &str) -> bool {
    lines.windows(2).any(|w| w[0] == flag && w[1] == value)
}

// ------------------------------------------------- WP-1.15 root mode
//
// `mkit serve --root <dir> [--principal <hex>]` serves the repositories
// under `<dir>` addressed by `<namespace>/<name>`; only the namespace's
// owner may write. The wrapper stands in for sshd's forced command: it
// finds the client's `mkit serve <path>` in argv (the same scan as
// `fake_ssh.sh`) and execs `mkit serve --root` locally — handing the
// path over argv, or over `SSH_ORIGINAL_COMMAND` the way sshd does when
// `MKIT_SSH_SERVE_ENV` is set. The asserted principal arrives via
// `MKIT_SSH_PRINCIPAL` (absent → no `--principal`, as a forced command
// that asserts none).

/// A hex string as a `&'static str` for `run_in`'s env table.
fn hex(byte: char) -> String {
    std::iter::repeat_n(byte, 64).collect()
}

/// `ed25519-<64 hex>` — a self-certifying namespace's canonical form.
fn ns(byte: char) -> String {
    format!("ed25519-{}", hex(byte))
}

/// Write the root-mode ssh wrapper (see the header above).
fn write_root_ssh_wrapper(dir: &Path) -> std::path::PathBuf {
    let wrapper = dir.join("fake_ssh_root.sh");
    let script = r#"#!/bin/sh
set -eu

{ echo "=== ssh invocation ==="; for a in "$@"; do printf '%s\n' "$a"; done; } >> "$MKIT_SSH_ARGV_LOG"

found=0
path=""
for a in "$@"; do
  if [ "$found" = 2 ]; then
    path="$a"
    break
  fi
  if [ "$found" = 1 ] && [ "$a" = serve ]; then
    found=2
    continue
  fi
  if [ "$a" = mkit ]; then
    found=1
  fi
done

if [ -z "$path" ]; then
  echo "fake_ssh_root: could not locate 'mkit serve <path>' in argv" >&2
  exit 64
fi

# `MKIT_SSH_SERVE_ENV=1`: hand the path over SSH_ORIGINAL_COMMAND the way
# sshd does, instead of as a positional argument.
serve_env=${MKIT_SSH_SERVE_ENV:-}
if [ -n "$serve_env" ]; then
  SSH_ORIGINAL_COMMAND="mkit serve $path"
  export SSH_ORIGINAL_COMMAND
  path=""
fi

if [ -n "${MKIT_SSH_PRINCIPAL:-}" ]; then
  if [ -n "$path" ]; then
    exec "$MKIT_SSH_TARGET_BIN" serve --root "$MKIT_SSH_ROOT" --principal "$MKIT_SSH_PRINCIPAL" "$path"
  fi
  exec "$MKIT_SSH_TARGET_BIN" serve --root "$MKIT_SSH_ROOT" --principal "$MKIT_SSH_PRINCIPAL"
elif [ -n "$path" ]; then
  exec "$MKIT_SSH_TARGET_BIN" serve --root "$MKIT_SSH_ROOT" "$path"
else
  exec "$MKIT_SSH_TARGET_BIN" serve --root "$MKIT_SSH_ROOT"
fi
"#;
    fs::write(&wrapper, script).expect("write root wrapper");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&wrapper).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&wrapper, perms).unwrap();
    }
    wrapper
}

/// A `--root` deployment at `work/serve-root` with each of `rooms`
/// `mkit init`ed under `ed25519-<owner>`. Returns the root's path.
fn serve_root_with_rooms(
    work: &Path,
    xdg: &Path,
    owner_ns: &str,
    rooms: &[&str],
) -> std::path::PathBuf {
    let serve_root = work.join("serve-root");
    for room in rooms {
        let dir = serve_root.join(owner_ns).join(room);
        fs::create_dir_all(&dir).unwrap();
        let out = run_in(&dir, xdg, &["init"], &[]);
        assert!(
            out.status.success(),
            "init {room}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
    serve_root
}

/// The environment `run_in` needs so the spawned `mkit` reaches the
/// root-mode wrapper: `MKIT_SSH_PROGRAM` picks the wrapper itself, the
/// rest it inherits. `principal` is the asserted `--principal` key
/// (`None` → the forced command asserts none); `env_path` hands the
/// path via `SSH_ORIGINAL_COMMAND` instead of argv.
fn root_env(
    wrapper: &Path,
    serve_root: &Path,
    principal: Option<&str>,
    env_path: bool,
) -> Vec<(String, String)> {
    let mut env = vec![
        (
            "MKIT_SSH_PROGRAM".to_owned(),
            wrapper.to_str().unwrap().to_owned(),
        ),
        (
            "MKIT_SSH_ARGV_LOG".to_owned(),
            wrapper
                .parent()
                .unwrap()
                .join("ssh_argv.log")
                .to_str()
                .unwrap()
                .to_owned(),
        ),
        ("MKIT_SSH_TARGET_BIN".to_owned(), mkit_bin().to_owned()),
        (
            "MKIT_SSH_ROOT".to_owned(),
            serve_root.to_str().unwrap().to_owned(),
        ),
    ];
    if let Some(key) = principal {
        env.push(("MKIT_SSH_PRINCIPAL".to_owned(), key.to_owned()));
    }
    if env_path {
        env.push(("MKIT_SSH_SERVE_ENV".to_owned(), "1".to_owned()));
    }
    env
}

/// `mkit remote add origin <url>` on `source`, then `push origin` with
/// `env`; returns the push's output.
fn push_over_ssh(source: &Path, xdg: &Path, url: &str, env: &[(String, String)]) -> Output {
    let env: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    let add = run_in(source, xdg, &["remote", "add", "origin", url], &env);
    assert!(
        add.status.success(),
        "remote add: {}",
        String::from_utf8_lossy(&add.stderr)
    );
    run_in(source, xdg, &["push", "origin"], &env)
}

/// The owner pushes over `mkit+ssh://` — sshd's forced command asserting
/// the principal over `SSH_ORIGINAL_COMMAND` — and a clone of the same
/// `<namespace>/<name>` address reconstructs the repo.
#[test]
fn ssh_root_mode_owner_pushes_and_clones() {
    if cfg!(not(unix)) {
        eprintln!("ssh_root_mode: skipped (requires a POSIX shell)");
        return;
    }
    let work = tempfile::tempdir().expect("work tempdir");
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let root = work.path();

    let owner_ns = ns('a');
    let serve_root = serve_root_with_rooms(root, xdg.path(), &owner_ns, &["room-a"]);
    let source = build_source(root, xdg.path());
    let wrapper = write_root_ssh_wrapper(root);
    let env = root_env(&wrapper, &serve_root, Some(&hex('a')), true);
    let url = format!("mkit+ssh://e2euser@localhost/{owner_ns}/room-a");

    let push = push_over_ssh(&source, xdg.path(), &url, &env);
    assert!(
        push.status.success(),
        "owner push must succeed; stderr:\n{}",
        String::from_utf8_lossy(&push.stderr)
    );

    let dest = root.join("dest");
    let clone = run_in(
        root,
        xdg.path(),
        &["clone", &url, dest.to_str().unwrap()],
        &env.iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect::<Vec<_>>(),
    );
    assert!(
        clone.status.success(),
        "clone over ssh must succeed; stderr:\n{}",
        String::from_utf8_lossy(&clone.stderr)
    );
    let source_tip = refs::read_ref(&RepoLayout::single(&source), "main")
        .unwrap()
        .expect("source has refs/heads/main");
    let dest_tip = refs::read_ref(&RepoLayout::single(&dest), "main")
        .unwrap()
        .expect("cloned repo has refs/heads/main");
    assert_eq!(source_tip, dest_tip, "clone must reconstruct the push");
}

/// A principal that is not the namespace's key is denied: the push fails
/// and the error the client surfaces is the pinned
/// `write not permitted` (B11's `INVALID_REQUEST` frame).
#[test]
fn ssh_root_mode_non_owner_push_is_refused() {
    if cfg!(not(unix)) {
        eprintln!("ssh_root_mode: skipped (requires a POSIX shell)");
        return;
    }
    let work = tempfile::tempdir().expect("work tempdir");
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let root = work.path();

    let owner_ns = ns('a');
    let serve_root = serve_root_with_rooms(root, xdg.path(), &owner_ns, &["room-a"]);
    let source = build_source(root, xdg.path());
    let wrapper = write_root_ssh_wrapper(root);
    // 'b' is not 'a': the forced command asserts a non-owner key.
    let env = root_env(&wrapper, &serve_root, Some(&hex('b')), false);
    let url = format!("mkit+ssh://e2euser@localhost/{owner_ns}/room-a");

    let push = push_over_ssh(&source, xdg.path(), &url, &env);
    assert!(!push.status.success(), "non-owner push must fail: {push:?}");
    let stderr = String::from_utf8_lossy(&push.stderr);
    assert!(
        stderr.contains("write not permitted"),
        "the pinned refusal reaches the client: {stderr}"
    );
    // The refused push wrote nothing: the repo still advertises no refs.
    let dest = root.join("dest");
    let clone = run_in(
        root,
        xdg.path(),
        &["clone", &url, dest.to_str().unwrap()],
        &env.iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect::<Vec<_>>(),
    );
    assert!(clone.status.success(), "{clone:?}");
    assert!(
        refs::read_ref(&RepoLayout::single(&dest), "main")
            .unwrap()
            .is_none(),
        "a denied push leaves the repo with no refs"
    );
}

/// No `--principal` asserted at all: reads work, every write is denied.
#[test]
fn ssh_root_mode_without_principal_reads_but_cannot_write() {
    if cfg!(not(unix)) {
        eprintln!("ssh_root_mode: skipped (requires a POSIX shell)");
        return;
    }
    let work = tempfile::tempdir().expect("work tempdir");
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let root = work.path();

    let owner_ns = ns('a');
    let serve_root = serve_root_with_rooms(root, xdg.path(), &owner_ns, &["room-a"]);
    let source = build_source(root, xdg.path());
    let wrapper = write_root_ssh_wrapper(root);
    let url = format!("mkit+ssh://e2euser@localhost/{owner_ns}/room-a");

    // Seed the repo as the owner so the read side has content.
    let owner_env = root_env(&wrapper, &serve_root, Some(&hex('a')), false);
    let push = push_over_ssh(&source, xdg.path(), &url, &owner_env);
    assert!(
        push.status.success(),
        "owner push: {}",
        String::from_utf8_lossy(&push.stderr)
    );

    // The same forced command with no --principal: clone works, push fails.
    let anon_env = root_env(&wrapper, &serve_root, None, false);
    let anon: Vec<(&str, &str)> = anon_env
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    let dest = root.join("dest");
    let clone = run_in(
        root,
        xdg.path(),
        &["clone", &url, dest.to_str().unwrap()],
        &anon,
    );
    assert!(
        clone.status.success(),
        "a keyless principal may read: {}",
        String::from_utf8_lossy(&clone.stderr)
    );
    let second = root.join("source2");
    fs::create_dir_all(&second).unwrap();
    assert!(run_in(&second, xdg.path(), &["init"], &[]).status.success());
    assert!(
        run_in(&second, xdg.path(), &["keygen"], &[])
            .status
            .success()
    );
    fs::write(second.join("f.txt"), b"nope\n").unwrap();
    assert!(
        run_in(&second, xdg.path(), &["add", "."], &[])
            .status
            .success()
    );
    assert!(
        run_in(&second, xdg.path(), &["commit", "-m", "x"], &[])
            .status
            .success()
    );
    let push = push_over_ssh(&second, xdg.path(), &url, &anon_env);
    assert!(!push.status.success(), "a keyless push must fail: {push:?}");
    assert!(
        String::from_utf8_lossy(&push.stderr).contains("write not permitted"),
        "{}",
        String::from_utf8_lossy(&push.stderr)
    );
}

/// Two repositories under one root are isolated: pushing to
/// `ed25519-<a>/room-a` leaves `ed25519-<a>/room-b` empty.
#[test]
fn ssh_root_mode_isolates_repositories() {
    if cfg!(not(unix)) {
        eprintln!("ssh_root_mode: skipped (requires a POSIX shell)");
        return;
    }
    let work = tempfile::tempdir().expect("work tempdir");
    let xdg = tempfile::tempdir().expect("xdg tempdir");
    let root = work.path();

    let owner_ns = ns('a');
    let serve_root = serve_root_with_rooms(root, xdg.path(), &owner_ns, &["room-a", "room-b"]);
    let source = build_source(root, xdg.path());
    let wrapper = write_root_ssh_wrapper(root);
    let env = root_env(&wrapper, &serve_root, Some(&hex('a')), false);
    let url_a = format!("mkit+ssh://e2euser@localhost/{owner_ns}/room-a");
    let url_b = format!("mkit+ssh://e2euser@localhost/{owner_ns}/room-b");
    let env_refs: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();

    let push = push_over_ssh(&source, xdg.path(), &url_a, &env);
    assert!(
        push.status.success(),
        "push to room-a: {}",
        String::from_utf8_lossy(&push.stderr)
    );

    // room-b reconstructs nothing of room-a's push.
    let dest_b = root.join("dest-b");
    let clone = run_in(
        root,
        xdg.path(),
        &["clone", &url_b, dest_b.to_str().unwrap()],
        &env_refs,
    );
    assert!(
        clone.status.success(),
        "clone room-b: {}",
        String::from_utf8_lossy(&clone.stderr)
    );
    assert!(
        refs::read_ref(&RepoLayout::single(&dest_b), "main")
            .unwrap()
            .is_none(),
        "room-b must not see room-a's refs/heads/main"
    );
    // And the pack the push stored in room-a is not visible through
    // room-b's repo either: cloning it yields zero refs (the ssh-session
    // tests cover `PackExists`/`DownloadPack` at frame level).
}