mkit-cli 0.4.2

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
//! `mkit trust` — manage the commit-history allowed-signers file that
//! `mkit verify --trusted` cross-checks a commit/remix/tag's `signer`
//! against.
//!
//! ```text
//! mkit trust add <keyid> <pubkey-hex> [--kind ed25519|p256-sec1|secp256k1|bls12381-thr]
//!                [--trust-roots <path>] [--force]
//! mkit trust list [--trust-roots <path>] [--json]
//! mkit trust remove <keyid> [--trust-roots <path>] --yes
//! ```
//!
//! The file is the same `[[trust_root]]` TOML format `mkit
//! verify-attest --trust-roots` already reads (see
//! `commands/trust_roots.rs`) — one registry, shared by DSSE
//! attestation verification and commit/remix/tag signer verification,
//! keyed by the `TrustRoot` type `mkit-attest` already exposes. Path
//! defaults to the user-scoped `$XDG_CONFIG_HOME/mkit/trust-roots.toml`;
//! an in-repo path is refused unless passed explicitly via
//! `--trust-roots` (same hostile-clone defense as `verify-attest`, see
//! `docs/THREAT-MODEL.md` §5).

use std::io::Write as _;
use std::path::PathBuf;

use clap::{Parser, Subcommand};

use super::trust_roots::{
    self, TrustEntry, default_trust_roots_path, keyid_matches_pubkey, warn_if_unsafe_trust_roots,
};
use crate::clap_shim;
use crate::exit;

#[derive(Debug, Parser)]
#[command(
    name = "mkit trust",
    about = "Manage the commit-history trust-roots file."
)]
struct TrustOpts {
    #[command(subcommand)]
    command: TrustCommand,
}

#[derive(Debug, Subcommand)]
enum TrustCommand {
    /// Add (or replace) a trusted signer.
    Add(AddOpts),
    /// List trusted signers.
    List(ListOpts),
    /// Remove a trusted signer.
    Remove(RemoveOpts),
}

#[derive(Debug, Parser)]
struct AddOpts {
    /// Identifier for this trust root, e.g. `ed25519:<hex-pubkey>` or a
    /// human label like `alice-laptop`. Free-form, but see `kind` for
    /// the canonical `<algorithm>:<hex-pubkey>` shape.
    keyid: String,
    /// Public key, lowercase hex. Ed25519 is 32 bytes; P-256/secp256k1
    /// SEC1 are 33 (compressed) or 65 (uncompressed) bytes; the
    /// BLS12-381 threshold cohort key (`bls-threshold` feature) is 96
    /// bytes.
    pubkey_hex: String,
    /// Trust-root kind. Commit/remix/tag signing is Ed25519-only
    /// today, so this defaults to `ed25519`; other kinds only matter
    /// for `mkit verify-attest`.
    #[arg(long, value_name = "KIND", default_value = "ed25519")]
    kind: String,
    #[arg(long, value_name = "PATH")]
    trust_roots: Option<String>,
    /// Overwrite an existing entry for this keyid.
    #[arg(long)]
    force: bool,
}

#[derive(Debug, Parser)]
struct ListOpts {
    #[arg(long, value_name = "PATH")]
    trust_roots: Option<String>,
    #[arg(long)]
    json: bool,
}

#[derive(Debug, Parser)]
struct RemoveOpts {
    keyid: String,
    #[arg(long, value_name = "PATH")]
    trust_roots: Option<String>,
    #[arg(long)]
    yes: bool,
}

#[must_use]
pub fn run(args: &[String]) -> u8 {
    let opts = match clap_shim::parse::<TrustOpts>("mkit trust", args) {
        Ok(opts) => opts,
        Err(code) => return code,
    };
    match opts.command {
        TrustCommand::Add(opts) => add(&opts),
        TrustCommand::List(opts) => list(&opts),
        TrustCommand::Remove(opts) => remove(&opts),
    }
}

/// Resolve the trust-roots path from an optional CLI flag, honoring
/// the same repo-local path-fencing every trust-consuming command
/// applies.
fn resolve_path(flag: Option<&str>) -> Result<PathBuf, u8> {
    let path = flag.map_or_else(default_trust_roots_path, PathBuf::from);
    // `mkit trust` has no repo context of its own (unlike `verify` /
    // `verify-attest`, which resolve a `.mkit` dir to fence against) —
    // it only needs to refuse an explicit-looking-but-actually-default
    // in-repo path when the CWD happens to be a repo. Fence against
    // `.mkit` under the current directory if one exists; otherwise
    // there is nothing to fence.
    let cwd = std::env::current_dir().unwrap_or_default();
    let mkit_dir = cwd.join(".mkit");
    warn_if_unsafe_trust_roots(&path, &mkit_dir, flag.is_some())?;
    Ok(path)
}

fn add(opts: &AddOpts) -> u8 {
    let path = match resolve_path(opts.trust_roots.as_deref()) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let Some(pk_bytes) = trust_roots::hex_decode(&opts.pubkey_hex) else {
        return emit_err(
            &format!("bad --pubkey-hex '{}': not valid hex", opts.pubkey_hex),
            exit::USAGE,
        );
    };
    if let Some(expected_len) = expected_pubkey_len(&opts.kind)
        && pk_bytes.len() != expected_len
    {
        return emit_err(
            &format!(
                "bad pubkey length for kind '{}': expected {expected_len} bytes, got {}",
                opts.kind,
                pk_bytes.len()
            ),
            exit::USAGE,
        );
    }
    if !keyid_matches_pubkey(&opts.keyid, &pk_bytes) {
        return emit_err(
            &format!(
                "keyid '{}' does not match the given pubkey — a `<algorithm>:<hex>` keyid must \
                 embed the same hex as --pubkey-hex (or the blake3 digest of it)",
                opts.keyid
            ),
            exit::USAGE,
        );
    }
    let mut entries = match trust_roots::load_entries(&path) {
        Ok(e) => e,
        Err((msg, code)) => return emit_err(&msg, code),
    };
    if let Some(existing) = entries.iter().position(|e| e.keyid == opts.keyid) {
        if !opts.force {
            return emit_err(
                &format!(
                    "a trust root for keyid '{}' already exists — pass --force to replace it",
                    opts.keyid
                ),
                exit::USAGE,
            );
        }
        entries.remove(existing);
    }
    entries.push(TrustEntry {
        keyid: opts.keyid.clone(),
        kind: opts.kind.clone(),
        pubkey_hex: opts.pubkey_hex.to_ascii_lowercase(),
    });
    if let Err((msg, code)) = trust_roots::save(&path, &entries) {
        return emit_err(&msg, code);
    }
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(
        stdout,
        "added {} ({}) to {}",
        opts.keyid,
        opts.kind,
        path.display()
    );
    exit::OK
}

fn list(opts: &ListOpts) -> u8 {
    let path = match resolve_path(opts.trust_roots.as_deref()) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let entries = match trust_roots::load_entries(&path) {
        Ok(e) => e,
        Err((msg, code)) => return emit_err(&msg, code),
    };
    let mut stdout = std::io::stdout().lock();
    if opts.json {
        use std::fmt::Write as _;
        let mut out = String::from("[");
        for (i, e) in entries.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            let _ = write!(
                out,
                "{{\"keyid\":{:?},\"kind\":{:?},\"pubkey_hex\":{:?}}}",
                e.keyid, e.kind, e.pubkey_hex
            );
        }
        out.push(']');
        let _ = writeln!(stdout, "{out}");
    } else if entries.is_empty() {
        let _ = writeln!(stdout, "no trust roots in {}", path.display());
    } else {
        for e in &entries {
            let _ = writeln!(stdout, "{}  [{}]  {}", e.keyid, e.kind, e.pubkey_hex);
        }
    }
    exit::OK
}

fn remove(opts: &RemoveOpts) -> u8 {
    if !opts.yes {
        return emit_err("mkit trust remove requires --yes", exit::USAGE);
    }
    let path = match resolve_path(opts.trust_roots.as_deref()) {
        Ok(p) => p,
        Err(code) => return code,
    };
    let mut entries = match trust_roots::load_entries(&path) {
        Ok(e) => e,
        Err((msg, code)) => return emit_err(&msg, code),
    };
    let Some(pos) = entries.iter().position(|e| e.keyid == opts.keyid) else {
        return emit_err(
            &format!("no trust root registered for keyid '{}'", opts.keyid),
            exit::GENERAL_ERROR,
        );
    };
    entries.remove(pos);
    if let Err((msg, code)) = trust_roots::save(&path, &entries) {
        return emit_err(&msg, code);
    }
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(stdout, "removed {} from {}", opts.keyid, path.display());
    exit::OK
}

fn expected_pubkey_len(kind: &str) -> Option<usize> {
    match kind {
        "ed25519" => Some(32),
        #[cfg(feature = "bls-threshold")]
        "bls12381-thr" => Some(mkit_attest::BLS_THRESHOLD_PUBLIC_KEY_SIZE),
        // SEC1 p256/secp256k1 accept both 33 (compressed) and 65
        // (uncompressed) — length-checked by mkit-attest at verify
        // time instead of here.
        _ => None,
    }
}

use super::error as emit_err;

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    fn parse_args(args: &[String]) -> Result<TrustOpts, clap::Error> {
        let mut full: Vec<String> = vec!["mkit trust".into()];
        full.extend_from_slice(args);
        TrustOpts::try_parse_from(full)
    }

    #[test]
    fn parse_add_defaults_kind_to_ed25519() {
        let args = vec!["add".into(), "keyid".into(), "aa".into()];
        let TrustCommand::Add(opts) = parse_args(&args).unwrap().command else {
            panic!("expected Add");
        };
        assert_eq!(opts.kind, "ed25519");
        assert!(!opts.force);
    }

    #[test]
    fn parse_remove_requires_yes_flag_at_runtime_not_parse_time() {
        let args = vec!["remove".into(), "keyid".into()];
        let TrustCommand::Remove(opts) = parse_args(&args).unwrap().command else {
            panic!("expected Remove");
        };
        assert!(!opts.yes);
    }

    #[test]
    fn add_list_remove_round_trip() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let hex = "11".repeat(32);
        let keyid = format!("ed25519:{hex}");

        let rc = add(&AddOpts {
            keyid: keyid.clone(),
            pubkey_hex: hex.clone(),
            kind: "ed25519".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            force: false,
        });
        assert_eq!(rc, exit::OK);

        let entries = trust_roots::load_entries(&path).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].keyid, keyid);

        let rc = remove(&RemoveOpts {
            keyid: keyid.clone(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            yes: true,
        });
        assert_eq!(rc, exit::OK);
        assert!(trust_roots::load_entries(&path).unwrap().is_empty());
        let _ = fs::remove_dir_all(td.path());
    }

    #[test]
    fn add_rejects_keyid_pubkey_mismatch() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let hex = "22".repeat(32);
        let rc = add(&AddOpts {
            keyid: format!("ed25519:{}", "ff".repeat(32)),
            pubkey_hex: hex,
            kind: "ed25519".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            force: false,
        });
        assert_eq!(rc, exit::USAGE);
    }

    #[test]
    fn add_without_force_refuses_duplicate_keyid() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let hex = "33".repeat(32);
        let keyid = format!("ed25519:{hex}");
        let make = || AddOpts {
            keyid: keyid.clone(),
            pubkey_hex: hex.clone(),
            kind: "ed25519".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            force: false,
        };
        assert_eq!(add(&make()), exit::OK);
        assert_eq!(add(&make()), exit::USAGE);
        let mut forced = make();
        forced.force = true;
        assert_eq!(add(&forced), exit::OK);
        assert_eq!(trust_roots::load_entries(&path).unwrap().len(), 1);
    }

    #[test]
    fn remove_without_yes_is_refused() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let rc = remove(&RemoveOpts {
            keyid: "anything".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            yes: false,
        });
        assert_eq!(rc, exit::USAGE);
    }

    #[test]
    fn remove_unknown_keyid_is_an_error() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let rc = remove(&RemoveOpts {
            keyid: "nope".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            yes: true,
        });
        assert_eq!(rc, exit::GENERAL_ERROR);
    }

    #[test]
    fn list_json_emits_valid_array_shape() {
        let td = tempfile::tempdir().unwrap();
        let path = td.path().join("trust-roots.toml");
        let hex = "44".repeat(32);
        let keyid = format!("ed25519:{hex}");
        add(&AddOpts {
            keyid,
            pubkey_hex: hex,
            kind: "ed25519".into(),
            trust_roots: Some(path.to_string_lossy().into_owned()),
            force: false,
        });
        let rc = list(&ListOpts {
            trust_roots: Some(path.to_string_lossy().into_owned()),
            json: true,
        });
        assert_eq!(rc, exit::OK);
    }
}