OXYGENHUB
◆ show-stat oxygen / src / cli / identity.rs
31.2 KiB · Rust · last changed Policies grant subjects an issuer certifies (keyless step 4a) 18 days ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Identity, verification, and configuration commands.
2
3
use super::format::{short_id, signature_line, when};
75167672 Andy McCall 4
use super::json;
fce44ae9 Andy McCall ↶ 5
use super::open;
135212de Andy McCall ↶ 6
use super::ui;
fce44ae9 Andy McCall ↶ 7
use anyhow::Result;
8
use oxy_core::hash::ChangeHash;
75167672 Andy McCall 9
use oxy_core::hash::KeyId;
7ba155f2 Andy McCall ↶ 10
use oxy_core::identity::{Delegate, Identity, Scope};
28fc23d7 Andy McCall ↶ 11
use oxy_core::objects::Hlc;
12
use oxy_core::protocol::SignedPolicy;
c6aa5bd9 Andy McCall ↶ 13
use oxy_core::repo::{self, IdentityScope, PolicyUpdate, Repo, Rotation, SignatureStatus};
83e0677b Andy McCall ↶ 14
use std::path::{Path, PathBuf};
fce44ae9 Andy McCall ↶ 15
28fc23d7 Andy McCall ↶ 16
const DAY_MS: u64 = 24 * 60 * 60 * 1000;
17
18
fn expiry_from_days(days: u64) -> Option<u64> {
19
    (days > 0).then(|| Hlc::now().wall_ms + days * DAY_MS)
20
}
21
7ba155f2 Andy McCall ↶ 22
/// `30m`, `8h`, `7d`, or a bare number of days, as a wall time from now.
23
fn expiry_from_duration(s: &str) -> Result<u64> {
24
    let s = s.trim();
25
    let (n, unit) = match s.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
26
        Some((i, _)) => (&s[..i], &s[i..]),
27
        None => (s, "d"),
28
    };
29
    let n: u64 = n.parse().map_err(|_| {
30
        anyhow::anyhow!("--expires takes 30m, 8h, 7d or a number of days, not {s:?}")
31
    })?;
32
    let ms = match unit {
33
        "m" => 60_000,
34
        "h" => 3_600_000,
35
        "d" => DAY_MS,
36
        _ => anyhow::bail!("--expires takes 30m, 8h, 7d or a number of days, not {s:?}"),
37
    };
38
    if n == 0 {
39
        anyhow::bail!("--expires needs a length of time; leave it out for no expiry");
40
    }
41
    Ok(Hlc::now().wall_ms + n * ms)
42
}
43
5cde7882 Andy McCall ↶ 44
/// Print the delegates, one per line: who, their key, what they may do
45
/// and until when, so an agent's name is seen, not only its key.
46
fn print_delegates(repo: &Repo, delegates: &[Delegate]) {
47
    if delegates.is_empty() {
48
        return;
49
    }
50
    println!("{}", ui::kv("delegates", delegates.len().to_string()));
51
    let now = Hlc::now().wall_ms;
52
    for d in delegates {
53
        let who = repo
54
            .identity(&d.key)
55
            .map(|i| format!("{} <{}>", i.name, i.email))
56
            .unwrap_or_else(|_| "(unknown identity)".into());
57
        let until = match d.expires {
58
            Some(e) if now > e => ui::err(format!("expired {}", ui::ago(e))),
59
            Some(e) => ui::dim(format!("until {}", when(e))),
60
            None => String::new(),
61
        };
62
        println!(
63
            "    {}  {}  {} {}",
64
            ui::author(who),
65
            ui::hash(d.key.short(12)),
66
            ui::dim(d.scope.to_string()),
67
            until
68
        );
69
    }
7ba155f2 Andy McCall ↶ 70
}
71
28fc23d7 Andy McCall ↶ 72
/// Resolve a KeyId prefix among the identities the repository knows.
73
fn resolve_key(repo: &Repo, prefix: &str) -> Result<KeyId> {
74
    if let Some(k) = KeyId::from_hex(prefix) {
75
        return Ok(k);
76
    }
77
    let mut candidates: Vec<KeyId> = Vec::new();
78
    if let Some((_, sp)) = repo.current_policy()? {
79
        candidates.extend(sp.policy.identities.iter().map(|i| i.hash()));
80
        candidates.extend(sp.policy.revoked.iter().copied());
81
    }
82
    if let Some(own) = repo.config.author_key {
83
        candidates.push(own);
84
        if let Ok(id) = repo.identity(&own) {
7ba155f2 Andy McCall ↶ 85
            candidates.extend(id.delegates.iter().map(|d| d.key));
28fc23d7 Andy McCall ↶ 86
        }
87
    }
88
    candidates.sort();
89
    candidates.dedup();
75167672 Andy McCall 90
    let matches: Vec<_> = candidates
91
        .into_iter()
92
        .filter(|k| k.starts_with_hex(prefix))
93
        .collect();
28fc23d7 Andy McCall ↶ 94
    match matches.len() {
95
        1 => Ok(matches[0]),
96
        0 => anyhow::bail!("no known key starts with {prefix:?}"),
97
        _ => anyhow::bail!("{prefix:?} is ambiguous"),
98
    }
99
}
100
101
/// Report a policy update: applied, or written out as a proposal that
102
/// other root holders sign with `oxy policy sign`.
103
fn report_update(u: &PolicyUpdate, out: Option<PathBuf>) -> Result<()> {
104
    if u.applied {
75167672 Andy McCall 105
        println!(
106
            "{} policy serial {} {}",
107
            ui::done("Applied"),
108
            u.policy.serial,
109
            ui::dim("(push to publish it)")
110
        );
28fc23d7 Andy McCall ↶ 111
        return Ok(());
112
    }
113
    let path = out.unwrap_or_else(|| PathBuf::from(format!("policy-{}.proposal", u.policy.serial)));
114
    std::fs::write(&path, u.signed().encode())?;
115
    println!(
116
        "{} policy serial {} needs {} of {} root signatures; has {}. Wrote {} for another root to run {}",
117
        ui::caution(),
118
        u.policy.serial,
119
        u.policy.root_threshold,
120
        u.policy.roots.len(),
121
        u.sigs.len(),
122
        ui::path(path.display()),
123
        ui::dim(format!("oxy policy sign {}", path.display()))
124
    );
125
    Ok(())
126
}
127
5cde7882 Andy McCall ↶ 128
fn report_rotation(repo: &Repo, r: &Rotation, verb: &str) -> Result<()> {
75167672 Andy McCall 129
    println!(
130
        "{} identity {} <{}>",
131
        ui::done(verb),
132
        ui::author(&r.identity.name),
133
        r.identity.email
134
    );
28fc23d7 Andy McCall ↶ 135
    println!("{}", ui::kv("old key", ui::dim(r.old.to_hex())));
136
    println!("{}", ui::kv("new key", r.new.to_hex()));
5cde7882 Andy McCall ↶ 137
    print_delegates(repo, &r.identity.delegates);
28fc23d7 Andy McCall ↶ 138
    if let Some(e) = r.identity.expires {
139
        println!("{}", ui::kv("expires", when(e)));
140
    }
141
    match &r.policy {
142
        Some(u) => report_update(u, None)?,
75167672 Andy McCall 143
        None => println!(
144
            "  {} {}",
145
            ui::note(),
146
            ui::dim("no policy names the old key; export the new identity for policy holders")
147
        ),
28fc23d7 Andy McCall ↶ 148
    }
149
    Ok(())
150
}
151
75167672 Andy McCall 152
pub fn create(
153
    name: Option<String>,
154
    email: Option<String>,
155
    local: bool,
156
    expires: Option<u64>,
157
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 158
    let mut repo = open()?;
159
    let name = name.unwrap_or_else(|| repo.config.author_name.clone());
160
    let email = email.unwrap_or_else(|| repo.config.author_email.clone());
75167672 Andy McCall 161
    let scope = if local {
162
        IdentityScope::Repo
163
    } else {
164
        IdentityScope::User
165
    };
166
    let (key, _) =
167
        repo.create_identity_with(&name, &email, scope, expires.and_then(expiry_from_days))?;
168
    println!(
169
        "{} identity {} <{email}>",
170
        ui::done("Created"),
171
        ui::author(&name)
172
    );
94084087 Andy McCall ↶ 173
    println!("{}", ui::kv("key", key));
75167672 Andy McCall 174
    println!(
175
        "{}",
176
        ui::kv("secret", ui::path(repo::default_keys_dir().display()))
177
    );
fce44ae9 Andy McCall ↶ 178
    match scope {
75167672 Andy McCall 179
        IdentityScope::User => println!(
180
            "{}",
181
            ui::kv(
182
                "scope",
183
                format!(
184
                    "default author in {}",
185
                    ui::path(repo.user_config_path().display())
186
                )
187
            )
188
        ),
189
        IdentityScope::Repo => {
190
            println!("{}", ui::kv("scope", "this repository's .oxy/config only"))
191
        }
fce44ae9 Andy McCall ↶ 192
    }
193
    if !repo.config.sign_changes {
94084087 Andy McCall ↶ 194
        println!("  {} {}", ui::note(), ui::dim("changes will carry this author; run oxy config --user core.sign change to sign each commit"));
fce44ae9 Andy McCall ↶ 195
    }
196
    Ok(0)
197
}
198
199
pub fn show() -> Result<i32> {
200
    let repo = open()?;
201
    let Some(key) = repo.config.author_key else {
202
        println!("No identity configured; run `oxy identity create`.");
203
        return Ok(0);
204
    };
205
    let id = repo.identity(&key)?;
75167672 Andy McCall 206
    println!(
207
        "{} {} <{}>",
208
        ui::section("identity"),
209
        ui::author(&id.name),
210
        id.email
211
    );
94084087 Andy McCall ↶ 212
    println!("{}", ui::kv("key", key));
75167672 Andy McCall 213
    println!(
214
        "{}",
215
        ui::kv(
216
            "created",
217
            format!(
218
                "{} {}",
219
                when(id.created),
220
                ui::dim(format!("({})", ui::ago(id.created)))
221
            )
222
        )
223
    );
28fc23d7 Andy McCall ↶ 224
    if let Some(e) = id.expires {
225
        let expired = id.is_expired_at(Hlc::now().wall_ms);
75167672 Andy McCall 226
        println!(
227
            "{}",
228
            ui::kv(
229
                "expires",
230
                if expired {
231
                    ui::err(format!("{} EXPIRED", when(e)))
232
                } else {
233
                    when(e)
234
                }
235
            )
236
        );
28fc23d7 Andy McCall ↶ 237
    }
238
    if let Some(p) = id.previous {
239
        println!("{}", ui::kv("previous", ui::dim(p.short(12))));
240
    }
614f55e1 Andy McCall ↶ 241
    // A repository that pins one key while the user file names another is
242
    // how checkouts drift apart after a rotation (oxygen#69).
243
    if let Some(pinned) = repo
244
        .config
245
        .repo_layer()
246
        .get("author.key")
247
        .and_then(|k| oxy_core::hash::KeyId::from_hex(k))
248
    {
249
        let user_key = repo::read_config_file(&repo::default_user_config())
250
            .ok()
251
            .and_then(|m| {
252
                m.get("author.key")
253
                    .and_then(|k| oxy_core::hash::KeyId::from_hex(k))
254
            });
255
        if let Some(u) = user_key.filter(|u| *u != pinned) {
256
            let related = |from: oxy_core::hash::KeyId, to: oxy_core::hash::KeyId| {
257
                let mut cur = Some(from);
258
                for _ in 0..64 {
259
                    match cur {
260
                        Some(k) if k == to => return true,
261
                        Some(k) => cur = repo.identity(&k).ok().and_then(|i| i.previous),
262
                        None => break,
263
                    }
264
                }
265
                false
266
            };
267
            let how = if related(pinned, u) {
268
                "an older key of this identity"
269
            } else if related(u, pinned) {
270
                "a newer key of this identity"
271
            } else {
272
                "another key"
273
            };
274
            println!(
275
                "  {} {}",
276
                ui::caution(),
277
                ui::dim(format!(
278
                    "this repository pins author.key {}; your user config names {how}, {}. Other checkouts follow the user config: `oxy config --unset author.key` here, or `oxy config --user author.key {}`",
279
                    pinned.short(12),
280
                    u.short(12),
281
                    pinned.to_hex()
282
                ))
283
            );
284
        }
285
    }
5cde7882 Andy McCall ↶ 286
    print_delegates(&repo, &id.delegates);
28fc23d7 Andy McCall ↶ 287
    if repo.is_revoked(&key)? {
75167672 Andy McCall 288
        println!(
289
            "{}",
290
            ui::kv(
291
                "status",
292
                ui::err(format!("{} REVOKED", ui::glyph("✖", "x")))
293
            )
294
        );
28fc23d7 Andy McCall ↶ 295
    }
75167672 Andy McCall 296
    println!(
297
        "{}",
298
        ui::kv(
299
            "secret",
300
            if repo.secret_key()?.is_some() {
301
                ui::ok(format!("{} available", ui::glyph("✔", "*")))
302
            } else {
303
                ui::err(format!(
304
                    "{} not found in the key directory",
305
                    ui::glyph("✖", "x")
306
                ))
307
            }
308
        )
309
    );
310
    println!(
311
        "{}",
312
        ui::kv(
313
            "signing",
314
            if repo.config.sign_changes {
315
                "every change (core.sign = change)"
316
            } else {
317
                "at push via seals (core.sign = seal)"
318
            }
319
        )
320
    );
fce44ae9 Andy McCall ↶ 321
    Ok(0)
322
}
323
2c9ddac3 Andy McCall ↶ 324
pub fn verify(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 325
    let repo = open()?;
2c9ddac3 Andy McCall ↶ 326
    let hashes: Vec<ChangeHash> = match (change, revset) {
327
        (_, Some(r)) => {
328
            let wc = repo.working_copy().ok().map(|(h, _)| h);
329
            repo.revset(r)?
330
                .hashes
331
                .into_iter()
332
                .filter(|h| Some(*h) != wc)
333
                .collect()
334
        }
335
        (Some(c), None) => vec![repo.resolve_change(c)?],
336
        (None, None) => repo
75167672 Andy McCall 337
            .log()?
338
            .into_iter()
339
            .filter(|e| !e.is_working_copy)
340
            .map(|e| e.hash)
341
            .collect(),
fce44ae9 Andy McCall ↶ 342
    };
343
    let mut bad = 0;
c6aa5bd9 Andy McCall ↶ 344
    if as_json {
345
        let mut items = Vec::new();
346
        for h in &hashes {
75167672 Andy McCall 347
            let Ok(c) = repo.store().get_change(h) else {
348
                continue;
349
            };
c6aa5bd9 Andy McCall ↶ 350
            let (status, key, name, revoked, reason) = match repo.authenticate_change(h)? {
351
                SignatureStatus::Unsigned => ("unsigned", None, None, false, None),
75167672 Andy McCall 352
                SignatureStatus::Valid {
353
                    key,
354
                    name,
355
                    sealed,
356
                    revoked,
357
                    ..
358
                } => (
359
                    if sealed { "sealed" } else { "signed" },
360
                    Some(key.to_hex()),
361
                    Some(name),
362
                    revoked,
363
                    None,
364
                ),
c6aa5bd9 Andy McCall ↶ 365
                SignatureStatus::Invalid(why) => {
366
                    bad += 1;
367
                    ("invalid", None, None, false, Some(why))
368
                }
369
            };
370
            items.push(json::obj([
371
                ("hash", json::s(&h.to_hex())),
372
                ("change_id", json::s(&c.change_id.to_hex())),
373
                ("status", json::s(status)),
374
                ("key", json::opt(key.as_deref(), json::s)),
375
                ("name", json::opt(name.as_deref(), json::s)),
376
                ("revoked", json::b(revoked)),
377
                ("reason", json::opt(reason.as_deref(), json::s)),
378
            ]));
379
        }
380
        println!("{}", json::arr(items));
381
        return Ok(if bad > 0 { 1 } else { 0 });
382
    }
fce44ae9 Andy McCall ↶ 383
    for h in hashes {
2863456a Andy McCall ↶ 384
        let Ok(c) = repo.store().get_change(&h) else {
75167672 Andy McCall 385
            println!(
386
                "{}  {}",
387
                ui::hash(format!("#{}", h.short(12))),
388
                ui::dim("not present (shallow)")
389
            );
2863456a Andy McCall ↶ 390
            continue;
391
        };
fce44ae9 Andy McCall ↶ 392
        let line = signature_line(&repo, &h)?;
135212de Andy McCall ↶ 393
        let styled = if line.starts_with("INVALID") {
fce44ae9 Andy McCall ↶ 394
            bad += 1;
94084087 Andy McCall ↶ 395
            ui::err(format!("{} {line}", ui::glyph("✖", "x")))
135212de Andy McCall ↶ 396
        } else if line == "unsigned" {
94084087 Andy McCall ↶ 397
            ui::dim(format!("{} {line}", ui::glyph("·", "-")))
135212de Andy McCall ↶ 398
        } else {
94084087 Andy McCall ↶ 399
            ui::ok(format!("{} {line}", ui::glyph("✔", "v")))
135212de Andy McCall ↶ 400
        };
75167672 Andy McCall 401
        println!(
402
            "{} {}  {styled}",
403
            ui::id(short_id(&c)),
404
            ui::hash(format!("#{}", h.short(12)))
405
        );
fce44ae9 Andy McCall ↶ 406
    }
407
    Ok(if bad > 0 { 1 } else { 0 })
408
}
409
8e9c64d1 Andy McCall ↶ 410
/// Whether a configuration key holds a secret, never to be printed.
411
fn secret_key(key: &str) -> bool {
412
    let k = key.to_ascii_lowercase();
413
    k.ends_with(".token") || k.contains("secret") || k.contains("password")
414
}
415
416
/// A secret as a confirmation may show it (oxygen#113): enough of its start
417
/// to tell which one it is, never the rest.
418
fn mask(value: &str) -> String {
419
    let shown: String = value.chars().take(10).collect();
420
    let rest = value.chars().count().saturating_sub(10);
421
    if rest == 0 {
422
        "…".to_string()
423
    } else {
424
        format!("{shown}…({rest} more)")
425
    }
426
}
427
614f55e1 Andy McCall ↶ 428
pub fn config(key: &str, value: &str, user: bool, unset: bool) -> Result<i32> {
429
    // An empty value removes the key, which is what --unset says plainly.
8e9c64d1 Andy McCall ↶ 430
    // `-` reads the value from standard input, so a token never sits in
431
    // the shell's history (oxygen#113).
432
    let read;
433
    let value = if unset {
434
        ""
435
    } else if value == "-" {
436
        let mut line = String::new();
437
        std::io::stdin().read_line(&mut line)?;
438
        read = line.trim().to_string();
439
        read.as_str()
440
    } else {
441
        value
442
    };
614f55e1 Andy McCall ↶ 443
    let said = if unset {
444
        format!("{} {key}", ui::done("Unset"))
8e9c64d1 Andy McCall ↶ 445
    } else if secret_key(key) {
446
        format!("{} {key} = {}", ui::done("Set"), mask(value))
614f55e1 Andy McCall ↶ 447
    } else {
448
        format!("{} {key} = {value}", ui::done("Set"))
449
    };
fce44ae9 Andy McCall ↶ 450
    if user {
451
        let path = repo::default_user_config();
452
        repo::Config::set_user(&path, key, value)?;
614f55e1 Andy McCall ↶ 453
        println!("{said} {}", ui::dim(format!("(in {})", path.display())));
fce44ae9 Andy McCall ↶ 454
    } else {
455
        let mut repo = open()?;
456
        repo.config.set(key, value)?;
457
        repo.save_config()?;
614f55e1 Andy McCall ↶ 458
        println!("{said} {}", ui::dim("(in this repository)"));
fce44ae9 Andy McCall ↶ 459
    }
460
    Ok(0)
461
}
83e0677b Andy McCall ↶ 462
a39754d0 Andy McCall ↶ 463
pub fn export(path: Option<PathBuf>, pem: bool) -> Result<i32> {
83e0677b Andy McCall ↶ 464
    let repo = open()?;
a39754d0 Andy McCall ↶ 465
    // The PEM is for checking what this home signs, so it is the signing
466
    // key's: a delegate's when `author.signer` names one.
467
    let key = if pem {
468
        repo.signing_key()
469
    } else {
470
        repo.config.author_key
471
    };
472
    let Some(key) = key else {
83e0677b Andy McCall ↶ 473
        anyhow::bail!("no identity configured; run `oxy identity create`");
474
    };
475
    let id = repo.identity(&key)?;
a39754d0 Andy McCall ↶ 476
    let ext = if pem { "pem" } else { "identity" };
477
    let path = path.unwrap_or_else(|| PathBuf::from(format!("{}.{ext}", key.short(16))));
478
    if pem {
479
        std::fs::write(&path, oxy_core::dsse::public_pem(&id))?;
480
    } else {
481
        std::fs::write(&path, id.encode())?;
482
    }
75167672 Andy McCall 483
    println!(
a39754d0 Andy McCall ↶ 484
        "{} {} {} <{}> ({}) to {}",
75167672 Andy McCall 485
        ui::done("Wrote"),
a39754d0 Andy McCall ↶ 486
        if pem { "the public key of" } else { "identity" },
75167672 Andy McCall 487
        ui::author(&id.name),
488
        id.email,
489
        key.short(12),
490
        ui::path(path.display())
491
    );
83e0677b Andy McCall ↶ 492
    Ok(0)
493
}
494
28fc23d7 Andy McCall ↶ 495
pub fn rotate() -> Result<i32> {
496
    let mut repo = open()?;
497
    let r = repo.rotate_identity()?;
5cde7882 Andy McCall ↶ 498
    report_rotation(&repo, &r, "Rotated")?;
28fc23d7 Andy McCall ↶ 499
    Ok(0)
500
}
501
502
pub fn renew(expires: u64) -> Result<i32> {
503
    let mut repo = open()?;
504
    let r = repo.renew_identity(expiry_from_days(expires))?;
5cde7882 Andy McCall ↶ 505
    report_rotation(&repo, &r, "Renewed")?;
28fc23d7 Andy McCall ↶ 506
    Ok(0)
507
}
508
509
pub fn revoke(key: Option<&str>, reason: &str) -> Result<i32> {
510
    let repo = open()?;
511
    let key = match key {
512
        Some(k) => resolve_key(&repo, k)?,
75167672 Andy McCall 513
        None => repo
514
            .config
515
            .author_key
516
            .ok_or_else(|| anyhow::anyhow!("no identity configured"))?,
28fc23d7 Andy McCall ↶ 517
    };
518
    let update = repo.revoke_identity(&key, reason)?;
75167672 Andy McCall 519
    println!(
520
        "{} key {}{}",
521
        ui::done("Revoked"),
522
        ui::hash(key.short(12)),
523
        if reason.is_empty() {
524
            String::new()
525
        } else {
526
            format!(": {reason}")
527
        }
528
    );
28fc23d7 Andy McCall ↶ 529
    match update {
530
        Some(u) => report_update(&u, None)?,
75167672 Andy McCall 531
        None => println!(
532
            "  {} {}",
533
            ui::note(),
534
            ui::dim("recorded locally; no policy named the key")
535
        ),
28fc23d7 Andy McCall ↶ 536
    }
7ba155f2 Andy McCall ↶ 537
    // A revoked delegate comes off the identity too, so the successor no
538
    // longer names it (spec §14.2).
539
    let own = repo.config.author_key;
540
    let delegated = own.is_some_and(|o| {
541
        repo.identity(&o)
542
            .is_ok_and(|id| id.delegate(&key).is_some())
543
    });
544
    if delegated {
545
        let mut repo = repo;
546
        let r = repo.delegate_remove(&key)?;
5cde7882 Andy McCall ↶ 547
        report_rotation(&repo, &r, "Undelegated")?;
7ba155f2 Andy McCall ↶ 548
        return Ok(0);
549
    }
28fc23d7 Andy McCall ↶ 550
    if repo.config.author_key == Some(key) {
75167672 Andy McCall 551
        println!(
552
            "  {} {}",
553
            ui::caution(),
554
            ui::warn("this was your configured key; run oxy identity create or rotate")
555
        );
28fc23d7 Andy McCall ↶ 556
    }
557
    Ok(0)
558
}
559
614f55e1 Andy McCall ↶ 560
pub fn delegate_add(identity_files: &[PathBuf], scope: &str, expires: Option<&str>) -> Result<i32> {
28fc23d7 Andy McCall ↶ 561
    let mut repo = open()?;
614f55e1 Andy McCall ↶ 562
    let ids = identity_files
563
        .iter()
564
        .map(|f| {
565
            Identity::decode(
566
                &std::fs::read(f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?,
567
            )
568
            .map_err(Into::into)
569
        })
570
        .collect::<Result<Vec<_>>>()?;
7ba155f2 Andy McCall ↶ 571
    let scope = Scope::parse(scope).map_err(|e| anyhow::anyhow!("{e}"))?;
572
    let expires = expires.map(expiry_from_duration).transpose()?;
614f55e1 Andy McCall ↶ 573
    let r = repo.delegate_add_many(ids, scope, expires)?;
5cde7882 Andy McCall ↶ 574
    report_rotation(&repo, &r, "Delegated")?;
614f55e1 Andy McCall ↶ 575
    println!(
576
        "  {} {}",
577
        ui::note(),
578
        ui::dim("an agent configured with your author.key needs the new key: oxy config --user author.key NEW in its home")
579
    );
7ba155f2 Andy McCall ↶ 580
    if !scope.has(Scope::REFS) {
581
        println!(
582
            "  {} {}",
583
            ui::note(),
584
            ui::dim("it may not move references: a push or tag it attests is refused")
585
        );
586
    }
28fc23d7 Andy McCall ↶ 587
    Ok(0)
588
}
589
590
pub fn delegate_remove(key: &str) -> Result<i32> {
591
    let mut repo = open()?;
592
    let k = resolve_key(&repo, key)?;
593
    let r = repo.delegate_remove(&k)?;
5cde7882 Andy McCall ↶ 594
    report_rotation(&repo, &r, "Undelegated")?;
28fc23d7 Andy McCall ↶ 595
    Ok(0)
596
}
597
598
pub fn delegate_list() -> Result<i32> {
599
    let repo = open()?;
600
    let Some(key) = repo.config.author_key else {
601
        println!("No identity configured; run `oxy identity create`.");
602
        return Ok(0);
603
    };
604
    let id = repo.identity(&key)?;
605
    if id.delegates.is_empty() {
606
        println!("{}", ui::dim("No delegates."));
607
    }
7ba155f2 Andy McCall ↶ 608
    let now = Hlc::now().wall_ms;
28fc23d7 Andy McCall ↶ 609
    for d in &id.delegates {
75167672 Andy McCall 610
        let who = repo
7ba155f2 Andy McCall ↶ 611
            .identity(&d.key)
75167672 Andy McCall 612
            .map(|i| format!("{} <{}>", i.name, i.email))
613
            .unwrap_or_else(|_| "(unknown identity)".into());
7ba155f2 Andy McCall ↶ 614
        let until = match d.expires {
615
            Some(e) if now > e => ui::err(format!("expired {}", ui::ago(e))),
616
            Some(e) => ui::dim(format!("until {}", when(e))),
617
            None => String::new(),
618
        };
75167672 Andy McCall 619
        println!(
7ba155f2 Andy McCall ↶ 620
            "  {} {}  {}  {} {}",
75167672 Andy McCall 621
            ui::ok(ui::glyph("🔑", "*")),
7ba155f2 Andy McCall ↶ 622
            ui::hash(d.key.short(12)),
623
            ui::author(who),
624
            ui::dim(d.scope.to_string()),
625
            until
75167672 Andy McCall 626
        );
28fc23d7 Andy McCall ↶ 627
    }
628
    Ok(0)
629
}
630
631
pub fn policy_root_add(identity_file: &Path, out: Option<PathBuf>) -> Result<i32> {
632
    let repo = open()?;
633
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
634
    let key = id.hash();
635
    let u = repo.policy_root_add(id.clone())?;
75167672 Andy McCall 636
    println!(
637
        "{} root {} <{}> ({})",
638
        ui::done("Added"),
639
        ui::author(&id.name),
640
        id.email,
641
        key.short(12)
642
    );
28fc23d7 Andy McCall ↶ 643
    report_update(&u, out)?;
644
    Ok(0)
645
}
646
647
pub fn policy_root_remove(key: &str, out: Option<PathBuf>) -> Result<i32> {
648
    let repo = open()?;
649
    let k = resolve_key(&repo, key)?;
650
    let u = repo.policy_root_remove(&k)?;
651
    println!("{} root {}", ui::done("Removed"), ui::hash(k.short(12)));
652
    report_update(&u, out)?;
653
    Ok(0)
654
}
655
656
pub fn policy_threshold(n: u32, out: Option<PathBuf>) -> Result<i32> {
657
    let repo = open()?;
658
    let u = repo.policy_set_threshold(n)?;
659
    println!("{} root threshold to {n}", ui::done("Set"));
660
    report_update(&u, out)?;
661
    Ok(0)
662
}
663
664
pub fn policy_sign(proposal: &Path, out: Option<PathBuf>) -> Result<i32> {
665
    let repo = open()?;
666
    let sp = SignedPolicy::decode(&std::fs::read(proposal)?)?;
667
    let u = repo.policy_sign(sp)?;
668
    println!("{} policy serial {}", ui::done("Signed"), u.policy.serial);
669
    report_update(&u, Some(out.unwrap_or_else(|| proposal.to_path_buf())))?;
670
    Ok(0)
671
}
672
83e0677b Andy McCall ↶ 673
pub fn policy_init() -> Result<i32> {
674
    let repo = open()?;
675
    let sp = repo.policy_init()?;
75167672 Andy McCall 676
    println!(
677
        "{} policy with root key {}",
678
        ui::done("Created"),
679
        sp.policy.roots[0].short(12)
680
    );
28fc23d7 Andy McCall ↶ 681
    report_update(&sp, None)?;
83e0677b Andy McCall ↶ 682
    Ok(0)
683
}
684
c6aa5bd9 Andy McCall ↶ 685
pub fn policy_show(as_json: bool) -> Result<i32> {
83e0677b Andy McCall ↶ 686
    let repo = open()?;
687
    let Some((r, sp)) = repo.current_policy()? else {
c6aa5bd9 Andy McCall ↶ 688
        if as_json {
689
            println!("null");
690
        } else {
75167672 Andy McCall 691
            println!(
692
                "No policy: this repository is unverified. Run `oxy policy init` to create one."
693
            );
c6aa5bd9 Andy McCall ↶ 694
        }
83e0677b Andy McCall ↶ 695
        return Ok(0);
696
    };
697
    let p = &sp.policy;
c6aa5bd9 Andy McCall ↶ 698
    if as_json {
699
        let ident = |k: &oxy_core::hash::KeyId| {
75167672 Andy McCall 700
            let (name, email) = p
701
                .identity(k)
702
                .map(|i| (i.name.clone(), i.email.clone()))
703
                .unwrap_or_default();
704
            json::obj([
705
                ("key", json::s(&k.to_hex())),
706
                ("name", json::s(&name)),
707
                ("email", json::s(&email)),
708
            ])
c6aa5bd9 Andy McCall ↶ 709
        };
710
        println!(
711
            "{}",
712
            json::obj([
713
                ("hash", json::s(&r.to_hex())),
714
                ("serial", json::n(p.serial)),
715
                ("expires_ms", json::n(p.expires)),
75167672 Andy McCall 716
                (
717
                    "expired",
718
                    json::b(p.is_expired(oxy_core::objects::Hlc::now().wall_ms))
719
                ),
c6aa5bd9 Andy McCall ↶ 720
                ("root_threshold", json::n(p.root_threshold)),
721
                ("roots", json::arr(p.roots.iter().map(ident))),
722
                (
723
                    "rules",
724
                    json::arr(p.rules.iter().map(|rule| {
725
                        json::obj([
726
                            ("pattern", json::s(&rule.pattern)),
727
                            ("keys", json::arr(rule.keys.iter().map(ident))),
728
                            ("threshold", json::n(rule.threshold)),
729
                            ("require", json::s(rule.require.name())),
730
                            ("allow_conflicts", json::b(rule.allow_conflicts)),
3a6effc7 Andy McCall ↶ 731
                            (
732
                                "subjects",
733
                                json::arr(rule.subjects.iter().map(|g| {
734
                                    json::obj([
735
                                        ("subject", json::s(&g.pattern)),
736
                                        ("issuer", ident(&g.issuer)),
737
                                        ("scope", json::s(&g.scope.to_string())),
738
                                    ])
739
                                })),
740
                            ),
c6aa5bd9 Andy McCall ↶ 741
                        ])
742
                    })),
743
                ),
744
                ("revoked", json::arr(p.revoked.iter().map(ident))),
745
            ])
746
        );
747
        return Ok(0);
748
    }
75167672 Andy McCall 749
    let name = |k: &oxy_core::hash::KeyId| {
750
        p.identity(k)
751
            .map(|i| format!("{} <{}>", i.name, i.email))
752
            .unwrap_or_else(|| "(unknown identity)".into())
753
    };
94084087 Andy McCall ↶ 754
    let expired = p.is_expired(oxy_core::objects::Hlc::now().wall_ms);
75167672 Andy McCall 755
    println!(
756
        "{} {}{}serial {}{}expires {}{}",
757
        ui::section("policy"),
758
        ui::hash(format!("#{}", r.short(12))),
759
        ui::sep(),
760
        p.serial,
761
        ui::sep(),
762
        when(p.expires),
763
        if expired {
764
            ui::err(format!("  {} EXPIRED", ui::glyph("✖", "x")))
765
        } else {
766
            String::new()
767
        }
768
    );
769
    println!(
770
        "{}",
771
        ui::section(format!(
772
            "roots {}",
773
            ui::dim(format!("(threshold {})", p.root_threshold))
774
        ))
775
    );
83e0677b Andy McCall ↶ 776
    for k in &p.roots {
75167672 Andy McCall 777
        println!(
778
            "  {} {}  {}",
779
            ui::ok(ui::glyph("🔑", "*")),
780
            ui::hash(k.short(12)),
781
            ui::author(name(k))
782
        );
83e0677b Andy McCall ↶ 783
    }
94084087 Andy McCall ↶ 784
    println!("{}", ui::section("rules"));
83e0677b Andy McCall ↶ 785
    for rule in &p.rules {
75167672 Andy McCall 786
        println!(
787
            "  {} {:12} {}",
788
            ui::ok(ui::glyph("▸", ">")),
789
            ui::bookmark(&rule.pattern),
790
            ui::dim(format!(
791
                "threshold {}, require {}, conflicts {}",
792
                rule.threshold,
793
                rule.require.name(),
794
                if rule.allow_conflicts {
795
                    "allowed"
796
                } else {
797
                    "refused"
798
                }
799
            ))
800
        );
83e0677b Andy McCall ↶ 801
        for k in &rule.keys {
94084087 Andy McCall ↶ 802
            println!("      {}  {}", ui::hash(k.short(12)), ui::author(name(k)));
83e0677b Andy McCall ↶ 803
        }
3a6effc7 Andy McCall ↶ 804
        for g in &rule.subjects {
805
            println!(
806
                "      {}  {} {}",
807
                ui::author(&g.pattern),
808
                ui::dim(format!(
809
                    "certified by {} ({}),",
810
                    name(&g.issuer),
811
                    g.issuer.short(12)
812
                )),
813
                ui::dim(format!("scope {}", g.scope))
814
            );
815
        }
83e0677b Andy McCall ↶ 816
    }
817
    if !p.revoked.is_empty() {
94084087 Andy McCall ↶ 818
        println!("{}", ui::section("revoked"));
83e0677b Andy McCall ↶ 819
        for k in &p.revoked {
75167672 Andy McCall 820
            println!(
821
                "  {} {}  {}",
822
                ui::err(ui::glyph("✖", "x")),
823
                ui::hash(k.short(12)),
824
                ui::author(name(k))
825
            );
83e0677b Andy McCall ↶ 826
        }
827
    }
828
    Ok(0)
829
}
830
75167672 Andy McCall 831
pub fn policy_grant(
832
    identity_file: &Path,
833
    pattern: Option<&str>,
834
    out: Option<PathBuf>,
835
) -> Result<i32> {
83e0677b Andy McCall ↶ 836
    let repo = open()?;
837
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
838
    let key = id.hash();
28fc23d7 Andy McCall ↶ 839
    let u = repo.policy_grant(id.clone(), pattern)?;
75167672 Andy McCall 840
    println!(
841
        "{} {} <{}> ({}) on {}",
842
        ui::done("Granted"),
843
        ui::author(&id.name),
844
        id.email,
845
        key.short(12),
846
        ui::bookmark(pattern.unwrap_or("*"))
3a6effc7 Andy McCall ↶ 847
    );
848
    report_update(&u, out)?;
849
    Ok(0)
850
}
851
852
pub fn policy_grant_subject(
853
    subject: &str,
854
    issuer_file: &Path,
855
    scope: &str,
856
    pattern: Option<&str>,
857
    out: Option<PathBuf>,
858
) -> Result<i32> {
859
    let repo = open()?;
860
    let issuer = Identity::decode(&std::fs::read(issuer_file)?)
861
        .map_err(|e| anyhow::anyhow!("{}: not an identity file: {e}", issuer_file.display()))?;
862
    let scope = oxy_core::identity::Scope::parse(scope).map_err(|e| anyhow::anyhow!(e))?;
863
    let key = issuer.hash();
864
    let u = repo.policy_grant_subject(subject, issuer.clone(), scope, pattern)?;
865
    println!(
866
        "{} {} certified by {} ({}) on {}, scope {}",
867
        ui::done("Granted"),
868
        ui::author(subject),
869
        issuer.name,
870
        key.short(12),
871
        ui::bookmark(pattern.unwrap_or("*")),
872
        scope
75167672 Andy McCall 873
    );
28fc23d7 Andy McCall ↶ 874
    report_update(&u, out)?;
83e0677b Andy McCall ↶ 875
    Ok(0)
876
}
877
28fc23d7 Andy McCall ↶ 878
pub fn policy_revoke(key: &str, out: Option<PathBuf>) -> Result<i32> {
83e0677b Andy McCall ↶ 879
    let repo = open()?;
28fc23d7 Andy McCall ↶ 880
    if repo.current_policy()?.is_none() {
83e0677b Andy McCall ↶ 881
        anyhow::bail!("this repository has no policy");
28fc23d7 Andy McCall ↶ 882
    }
883
    let full = resolve_key(&repo, key)?;
884
    let u = repo.policy_revoke(&full)?;
885
    println!("{} {}", ui::done("Revoked"), ui::hash(full.short(12)));
886
    report_update(&u, out)?;
83e0677b Andy McCall ↶ 887
    Ok(0)
888
}
05e71ed6 Andy McCall ↶ 889
890
/// `oxy seal [CHANGE..]`: seal the named changes, or every sealable one.
891
pub fn seal(specs: &[String], as_json: bool) -> Result<i32> {
892
    let repo = Repo::open(&std::env::current_dir()?)?;
893
    let hashes: Vec<_> = if specs.is_empty() {
894
        repo.sealable()?
895
    } else {
b0e64e81 Andy McCall ↶ 896
        specs
897
            .iter()
898
            .map(|s| repo.resolve_change(s))
899
            .collect::<std::result::Result<_, _>>()?
05e71ed6 Andy McCall ↶ 900
    };
901
    if hashes.is_empty() {
902
        if as_json {
903
            println!("{{\"sealed\":[]}}");
904
        } else {
b0e64e81 Andy McCall ↶ 905
            println!(
906
                "{} nothing to seal: every change you can authenticate already is",
907
                ui::done("Sealed")
908
            );
05e71ed6 Andy McCall ↶ 909
        }
910
        return Ok(0);
911
    }
912
    let mut refs = Vec::new();
913
    for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) {
914
        refs.push(repo.seal(chunk)?);
915
    }
916
    if as_json {
b0e64e81 Andy McCall ↶ 917
        let list: Vec<String> = hashes
918
            .iter()
919
            .map(|h| format!("\"{}\"", h.to_hex()))
920
            .collect();
05e71ed6 Andy McCall ↶ 921
        let seals: Vec<String> = refs.iter().map(|r| format!("\"{}\"", r.to_hex())).collect();
b0e64e81 Andy McCall ↶ 922
        println!(
923
            "{{\"sealed\":[{}],\"seals\":[{}]}}",
924
            list.join(","),
925
            seals.join(",")
926
        );
05e71ed6 Andy McCall ↶ 927
    } else {
b0e64e81 Andy McCall ↶ 928
        println!(
929
            "{} {} change{} in {} seal{}; they travel with your next push",
930
            ui::done("Sealed"),
931
            hashes.len(),
932
            if hashes.len() == 1 { "" } else { "s" },
933
            refs.len(),
934
            if refs.len() == 1 { "" } else { "s" }
935
        );
05e71ed6 Andy McCall ↶ 936
        for h in &hashes {
b0e64e81 Andy McCall ↶ 937
            let title = repo
938
                .store()
939
                .get_change(h)
940
                .map(|c| c.message.lines().next().unwrap_or("").to_string())
941
                .unwrap_or_default();
05e71ed6 Andy McCall ↶ 942
            println!("  {} {}", ui::hash(h.short(12)), title);
943
        }
944
    }
945
    Ok(0)
946
}
7aa2dc93 Andy McCall ↶ 947
948
/// `oxy identity sign-challenge HEX`: the composite signature over a
949
/// host's challenge, as hex of the CBOR signature (hub spec §5.3).
950
pub fn sign_challenge(challenge_hex: &str, as_json: bool) -> Result<i32> {
951
    let repo = open()?;
952
    let Some((key, sk)) = repo.secret_key()? else {
953
        anyhow::bail!("no secret key: run `oxy identity create` first");
954
    };
119bbf50 Andy McCall ↶ 955
    let challenge = hex_bytes(challenge_hex.trim())
956
        .ok_or_else(|| anyhow::anyhow!("the challenge must be hex"))?;
957
    let sig = sk
958
        .sign_challenge(&key, &challenge)
959
        .map_err(|e| anyhow::anyhow!("{e}"))?;
7aa2dc93 Andy McCall ↶ 960
    let encoded = hex_string(&oxy_core::identity::Signature::encode_list(&[sig]));
961
    if as_json {
119bbf50 Andy McCall ↶ 962
        println!(
963
            "{{\"key\":\"{}\",\"signature\":\"{}\"}}",
964
            key.to_hex(),
965
            encoded
966
        );
7aa2dc93 Andy McCall ↶ 967
    } else {
968
        println!("{encoded}");
969
    }
970
    Ok(0)
971
}
972
973
fn hex_bytes(s: &str) -> Option<Vec<u8>> {
974
    if !s.len().is_multiple_of(2) {
975
        return None;
976
    }
119bbf50 Andy McCall ↶ 977
    (0..s.len())
978
        .step_by(2)
979
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
980
        .collect()
7aa2dc93 Andy McCall ↶ 981
}
982
983
fn hex_string(b: &[u8]) -> String {
984
    b.iter().map(|x| format!("{x:02x}")).collect()
8e9c64d1 Andy McCall ↶ 985
}
986
987
#[cfg(test)]
988
mod tests {
989
    #[test]
990
    fn secrets_are_never_printed_whole() {
991
        assert!(
992
            super::secret_key("remote.earth.token")
993
                && super::secret_key("auth.secret")
994
                && !super::secret_key("remote.earth.url")
995
        );
996
        assert_eq!(
997
            super::mask("oxyhub_6b7dce13409b634d"),
998
            "oxyhub_6b7…(13 more)"
999
        );
1000
        assert_eq!(super::mask("short"), "…");
1001
    }
7aa2dc93 Andy McCall ↶ 1002
}