OXYGENHUB
# 8e9c64d16ded oxygen / src / cli / identity.rs
29.1 KiB · Rust · last changed oxy config never prints a secret whole 20 days ago source blame history raw
1
//! Identity, verification, and configuration commands.
2
3
use super::format::{short_id, signature_line, when};
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::Result;
8
use oxy_core::hash::ChangeHash;
9
use oxy_core::hash::KeyId;
10
use oxy_core::identity::{Delegate, Identity, Scope};
11
use oxy_core::objects::Hlc;
12
use oxy_core::protocol::SignedPolicy;
13
use oxy_core::repo::{self, IdentityScope, PolicyUpdate, Repo, Rotation, SignatureStatus};
14
use std::path::{Path, PathBuf};
15
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
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
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
    }
70
}
71
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) {
85
            candidates.extend(id.delegates.iter().map(|d| d.key));
86
        }
87
    }
88
    candidates.sort();
89
    candidates.dedup();
90
    let matches: Vec<_> = candidates
91
        .into_iter()
92
        .filter(|k| k.starts_with_hex(prefix))
93
        .collect();
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 {
105
        println!(
106
            "{} policy serial {} {}",
107
            ui::done("Applied"),
108
            u.policy.serial,
109
            ui::dim("(push to publish it)")
110
        );
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
128
fn report_rotation(repo: &Repo, r: &Rotation, verb: &str) -> Result<()> {
129
    println!(
130
        "{} identity {} <{}>",
131
        ui::done(verb),
132
        ui::author(&r.identity.name),
133
        r.identity.email
134
    );
135
    println!("{}", ui::kv("old key", ui::dim(r.old.to_hex())));
136
    println!("{}", ui::kv("new key", r.new.to_hex()));
137
    print_delegates(repo, &r.identity.delegates);
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)?,
143
        None => println!(
144
            "  {} {}",
145
            ui::note(),
146
            ui::dim("no policy names the old key; export the new identity for policy holders")
147
        ),
148
    }
149
    Ok(())
150
}
151
152
pub fn create(
153
    name: Option<String>,
154
    email: Option<String>,
155
    local: bool,
156
    expires: Option<u64>,
157
) -> Result<i32> {
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());
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
    );
173
    println!("{}", ui::kv("key", key));
174
    println!(
175
        "{}",
176
        ui::kv("secret", ui::path(repo::default_keys_dir().display()))
177
    );
178
    match scope {
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
        }
192
    }
193
    if !repo.config.sign_changes {
194
        println!("  {} {}", ui::note(), ui::dim("changes will carry this author; run oxy config --user core.sign change to sign each commit"));
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)?;
206
    println!(
207
        "{} {} <{}>",
208
        ui::section("identity"),
209
        ui::author(&id.name),
210
        id.email
211
    );
212
    println!("{}", ui::kv("key", key));
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
    );
224
    if let Some(e) = id.expires {
225
        let expired = id.is_expired_at(Hlc::now().wall_ms);
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
        );
237
    }
238
    if let Some(p) = id.previous {
239
        println!("{}", ui::kv("previous", ui::dim(p.short(12))));
240
    }
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
    }
286
    print_delegates(&repo, &id.delegates);
287
    if repo.is_revoked(&key)? {
288
        println!(
289
            "{}",
290
            ui::kv(
291
                "status",
292
                ui::err(format!("{} REVOKED", ui::glyph("✖", "x")))
293
            )
294
        );
295
    }
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
    );
321
    Ok(0)
322
}
323
324
pub fn verify(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
325
    let repo = open()?;
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
337
            .log()?
338
            .into_iter()
339
            .filter(|e| !e.is_working_copy)
340
            .map(|e| e.hash)
341
            .collect(),
342
    };
343
    let mut bad = 0;
344
    if as_json {
345
        let mut items = Vec::new();
346
        for h in &hashes {
347
            let Ok(c) = repo.store().get_change(h) else {
348
                continue;
349
            };
350
            let (status, key, name, revoked, reason) = match repo.authenticate_change(h)? {
351
                SignatureStatus::Unsigned => ("unsigned", None, None, false, None),
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
                ),
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
    }
383
    for h in hashes {
384
        let Ok(c) = repo.store().get_change(&h) else {
385
            println!(
386
                "{}  {}",
387
                ui::hash(format!("#{}", h.short(12))),
388
                ui::dim("not present (shallow)")
389
            );
390
            continue;
391
        };
392
        let line = signature_line(&repo, &h)?;
393
        let styled = if line.starts_with("INVALID") {
394
            bad += 1;
395
            ui::err(format!("{} {line}", ui::glyph("✖", "x")))
396
        } else if line == "unsigned" {
397
            ui::dim(format!("{} {line}", ui::glyph("·", "-")))
398
        } else {
399
            ui::ok(format!("{} {line}", ui::glyph("✔", "v")))
400
        };
401
        println!(
402
            "{} {}  {styled}",
403
            ui::id(short_id(&c)),
404
            ui::hash(format!("#{}", h.short(12)))
405
        );
406
    }
407
    Ok(if bad > 0 { 1 } else { 0 })
408
}
409
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
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.
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
    };
443
    let said = if unset {
444
        format!("{} {key}", ui::done("Unset"))
445
    } else if secret_key(key) {
446
        format!("{} {key} = {}", ui::done("Set"), mask(value))
447
    } else {
448
        format!("{} {key} = {value}", ui::done("Set"))
449
    };
450
    if user {
451
        let path = repo::default_user_config();
452
        repo::Config::set_user(&path, key, value)?;
453
        println!("{said} {}", ui::dim(format!("(in {})", path.display())));
454
    } else {
455
        let mut repo = open()?;
456
        repo.config.set(key, value)?;
457
        repo.save_config()?;
458
        println!("{said} {}", ui::dim("(in this repository)"));
459
    }
460
    Ok(0)
461
}
462
463
pub fn export(path: Option<PathBuf>) -> Result<i32> {
464
    let repo = open()?;
465
    let Some(key) = repo.config.author_key else {
466
        anyhow::bail!("no identity configured; run `oxy identity create`");
467
    };
468
    let id = repo.identity(&key)?;
469
    let path = path.unwrap_or_else(|| PathBuf::from(format!("{}.identity", key.short(16))));
470
    std::fs::write(&path, id.encode())?;
471
    println!(
472
        "{} identity {} <{}> ({}) to {}",
473
        ui::done("Wrote"),
474
        ui::author(&id.name),
475
        id.email,
476
        key.short(12),
477
        ui::path(path.display())
478
    );
479
    Ok(0)
480
}
481
482
pub fn rotate() -> Result<i32> {
483
    let mut repo = open()?;
484
    let r = repo.rotate_identity()?;
485
    report_rotation(&repo, &r, "Rotated")?;
486
    Ok(0)
487
}
488
489
pub fn renew(expires: u64) -> Result<i32> {
490
    let mut repo = open()?;
491
    let r = repo.renew_identity(expiry_from_days(expires))?;
492
    report_rotation(&repo, &r, "Renewed")?;
493
    Ok(0)
494
}
495
496
pub fn revoke(key: Option<&str>, reason: &str) -> Result<i32> {
497
    let repo = open()?;
498
    let key = match key {
499
        Some(k) => resolve_key(&repo, k)?,
500
        None => repo
501
            .config
502
            .author_key
503
            .ok_or_else(|| anyhow::anyhow!("no identity configured"))?,
504
    };
505
    let update = repo.revoke_identity(&key, reason)?;
506
    println!(
507
        "{} key {}{}",
508
        ui::done("Revoked"),
509
        ui::hash(key.short(12)),
510
        if reason.is_empty() {
511
            String::new()
512
        } else {
513
            format!(": {reason}")
514
        }
515
    );
516
    match update {
517
        Some(u) => report_update(&u, None)?,
518
        None => println!(
519
            "  {} {}",
520
            ui::note(),
521
            ui::dim("recorded locally; no policy named the key")
522
        ),
523
    }
524
    // A revoked delegate comes off the identity too, so the successor no
525
    // longer names it (spec §14.2).
526
    let own = repo.config.author_key;
527
    let delegated = own.is_some_and(|o| {
528
        repo.identity(&o)
529
            .is_ok_and(|id| id.delegate(&key).is_some())
530
    });
531
    if delegated {
532
        let mut repo = repo;
533
        let r = repo.delegate_remove(&key)?;
534
        report_rotation(&repo, &r, "Undelegated")?;
535
        return Ok(0);
536
    }
537
    if repo.config.author_key == Some(key) {
538
        println!(
539
            "  {} {}",
540
            ui::caution(),
541
            ui::warn("this was your configured key; run oxy identity create or rotate")
542
        );
543
    }
544
    Ok(0)
545
}
546
547
pub fn delegate_add(identity_files: &[PathBuf], scope: &str, expires: Option<&str>) -> Result<i32> {
548
    let mut repo = open()?;
549
    let ids = identity_files
550
        .iter()
551
        .map(|f| {
552
            Identity::decode(
553
                &std::fs::read(f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?,
554
            )
555
            .map_err(Into::into)
556
        })
557
        .collect::<Result<Vec<_>>>()?;
558
    let scope = Scope::parse(scope).map_err(|e| anyhow::anyhow!("{e}"))?;
559
    let expires = expires.map(expiry_from_duration).transpose()?;
560
    let r = repo.delegate_add_many(ids, scope, expires)?;
561
    report_rotation(&repo, &r, "Delegated")?;
562
    println!(
563
        "  {} {}",
564
        ui::note(),
565
        ui::dim("an agent configured with your author.key needs the new key: oxy config --user author.key NEW in its home")
566
    );
567
    if !scope.has(Scope::REFS) {
568
        println!(
569
            "  {} {}",
570
            ui::note(),
571
            ui::dim("it may not move references: a push or tag it attests is refused")
572
        );
573
    }
574
    Ok(0)
575
}
576
577
pub fn delegate_remove(key: &str) -> Result<i32> {
578
    let mut repo = open()?;
579
    let k = resolve_key(&repo, key)?;
580
    let r = repo.delegate_remove(&k)?;
581
    report_rotation(&repo, &r, "Undelegated")?;
582
    Ok(0)
583
}
584
585
pub fn delegate_list() -> Result<i32> {
586
    let repo = open()?;
587
    let Some(key) = repo.config.author_key else {
588
        println!("No identity configured; run `oxy identity create`.");
589
        return Ok(0);
590
    };
591
    let id = repo.identity(&key)?;
592
    if id.delegates.is_empty() {
593
        println!("{}", ui::dim("No delegates."));
594
    }
595
    let now = Hlc::now().wall_ms;
596
    for d in &id.delegates {
597
        let who = repo
598
            .identity(&d.key)
599
            .map(|i| format!("{} <{}>", i.name, i.email))
600
            .unwrap_or_else(|_| "(unknown identity)".into());
601
        let until = match d.expires {
602
            Some(e) if now > e => ui::err(format!("expired {}", ui::ago(e))),
603
            Some(e) => ui::dim(format!("until {}", when(e))),
604
            None => String::new(),
605
        };
606
        println!(
607
            "  {} {}  {}  {} {}",
608
            ui::ok(ui::glyph("🔑", "*")),
609
            ui::hash(d.key.short(12)),
610
            ui::author(who),
611
            ui::dim(d.scope.to_string()),
612
            until
613
        );
614
    }
615
    Ok(0)
616
}
617
618
pub fn policy_root_add(identity_file: &Path, out: Option<PathBuf>) -> Result<i32> {
619
    let repo = open()?;
620
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
621
    let key = id.hash();
622
    let u = repo.policy_root_add(id.clone())?;
623
    println!(
624
        "{} root {} <{}> ({})",
625
        ui::done("Added"),
626
        ui::author(&id.name),
627
        id.email,
628
        key.short(12)
629
    );
630
    report_update(&u, out)?;
631
    Ok(0)
632
}
633
634
pub fn policy_root_remove(key: &str, out: Option<PathBuf>) -> Result<i32> {
635
    let repo = open()?;
636
    let k = resolve_key(&repo, key)?;
637
    let u = repo.policy_root_remove(&k)?;
638
    println!("{} root {}", ui::done("Removed"), ui::hash(k.short(12)));
639
    report_update(&u, out)?;
640
    Ok(0)
641
}
642
643
pub fn policy_threshold(n: u32, out: Option<PathBuf>) -> Result<i32> {
644
    let repo = open()?;
645
    let u = repo.policy_set_threshold(n)?;
646
    println!("{} root threshold to {n}", ui::done("Set"));
647
    report_update(&u, out)?;
648
    Ok(0)
649
}
650
651
pub fn policy_sign(proposal: &Path, out: Option<PathBuf>) -> Result<i32> {
652
    let repo = open()?;
653
    let sp = SignedPolicy::decode(&std::fs::read(proposal)?)?;
654
    let u = repo.policy_sign(sp)?;
655
    println!("{} policy serial {}", ui::done("Signed"), u.policy.serial);
656
    report_update(&u, Some(out.unwrap_or_else(|| proposal.to_path_buf())))?;
657
    Ok(0)
658
}
659
660
pub fn policy_init() -> Result<i32> {
661
    let repo = open()?;
662
    let sp = repo.policy_init()?;
663
    println!(
664
        "{} policy with root key {}",
665
        ui::done("Created"),
666
        sp.policy.roots[0].short(12)
667
    );
668
    report_update(&sp, None)?;
669
    Ok(0)
670
}
671
672
pub fn policy_show(as_json: bool) -> Result<i32> {
673
    let repo = open()?;
674
    let Some((r, sp)) = repo.current_policy()? else {
675
        if as_json {
676
            println!("null");
677
        } else {
678
            println!(
679
                "No policy: this repository is unverified. Run `oxy policy init` to create one."
680
            );
681
        }
682
        return Ok(0);
683
    };
684
    let p = &sp.policy;
685
    if as_json {
686
        let ident = |k: &oxy_core::hash::KeyId| {
687
            let (name, email) = p
688
                .identity(k)
689
                .map(|i| (i.name.clone(), i.email.clone()))
690
                .unwrap_or_default();
691
            json::obj([
692
                ("key", json::s(&k.to_hex())),
693
                ("name", json::s(&name)),
694
                ("email", json::s(&email)),
695
            ])
696
        };
697
        println!(
698
            "{}",
699
            json::obj([
700
                ("hash", json::s(&r.to_hex())),
701
                ("serial", json::n(p.serial)),
702
                ("expires_ms", json::n(p.expires)),
703
                (
704
                    "expired",
705
                    json::b(p.is_expired(oxy_core::objects::Hlc::now().wall_ms))
706
                ),
707
                ("root_threshold", json::n(p.root_threshold)),
708
                ("roots", json::arr(p.roots.iter().map(ident))),
709
                (
710
                    "rules",
711
                    json::arr(p.rules.iter().map(|rule| {
712
                        json::obj([
713
                            ("pattern", json::s(&rule.pattern)),
714
                            ("keys", json::arr(rule.keys.iter().map(ident))),
715
                            ("threshold", json::n(rule.threshold)),
716
                            ("require", json::s(rule.require.name())),
717
                            ("allow_conflicts", json::b(rule.allow_conflicts)),
718
                        ])
719
                    })),
720
                ),
721
                ("revoked", json::arr(p.revoked.iter().map(ident))),
722
            ])
723
        );
724
        return Ok(0);
725
    }
726
    let name = |k: &oxy_core::hash::KeyId| {
727
        p.identity(k)
728
            .map(|i| format!("{} <{}>", i.name, i.email))
729
            .unwrap_or_else(|| "(unknown identity)".into())
730
    };
731
    let expired = p.is_expired(oxy_core::objects::Hlc::now().wall_ms);
732
    println!(
733
        "{} {}{}serial {}{}expires {}{}",
734
        ui::section("policy"),
735
        ui::hash(format!("#{}", r.short(12))),
736
        ui::sep(),
737
        p.serial,
738
        ui::sep(),
739
        when(p.expires),
740
        if expired {
741
            ui::err(format!("  {} EXPIRED", ui::glyph("✖", "x")))
742
        } else {
743
            String::new()
744
        }
745
    );
746
    println!(
747
        "{}",
748
        ui::section(format!(
749
            "roots {}",
750
            ui::dim(format!("(threshold {})", p.root_threshold))
751
        ))
752
    );
753
    for k in &p.roots {
754
        println!(
755
            "  {} {}  {}",
756
            ui::ok(ui::glyph("🔑", "*")),
757
            ui::hash(k.short(12)),
758
            ui::author(name(k))
759
        );
760
    }
761
    println!("{}", ui::section("rules"));
762
    for rule in &p.rules {
763
        println!(
764
            "  {} {:12} {}",
765
            ui::ok(ui::glyph("▸", ">")),
766
            ui::bookmark(&rule.pattern),
767
            ui::dim(format!(
768
                "threshold {}, require {}, conflicts {}",
769
                rule.threshold,
770
                rule.require.name(),
771
                if rule.allow_conflicts {
772
                    "allowed"
773
                } else {
774
                    "refused"
775
                }
776
            ))
777
        );
778
        for k in &rule.keys {
779
            println!("      {}  {}", ui::hash(k.short(12)), ui::author(name(k)));
780
        }
781
    }
782
    if !p.revoked.is_empty() {
783
        println!("{}", ui::section("revoked"));
784
        for k in &p.revoked {
785
            println!(
786
                "  {} {}  {}",
787
                ui::err(ui::glyph("✖", "x")),
788
                ui::hash(k.short(12)),
789
                ui::author(name(k))
790
            );
791
        }
792
    }
793
    Ok(0)
794
}
795
796
pub fn policy_grant(
797
    identity_file: &Path,
798
    pattern: Option<&str>,
799
    out: Option<PathBuf>,
800
) -> Result<i32> {
801
    let repo = open()?;
802
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
803
    let key = id.hash();
804
    let u = repo.policy_grant(id.clone(), pattern)?;
805
    println!(
806
        "{} {} <{}> ({}) on {}",
807
        ui::done("Granted"),
808
        ui::author(&id.name),
809
        id.email,
810
        key.short(12),
811
        ui::bookmark(pattern.unwrap_or("*"))
812
    );
813
    report_update(&u, out)?;
814
    Ok(0)
815
}
816
817
pub fn policy_revoke(key: &str, out: Option<PathBuf>) -> Result<i32> {
818
    let repo = open()?;
819
    if repo.current_policy()?.is_none() {
820
        anyhow::bail!("this repository has no policy");
821
    }
822
    let full = resolve_key(&repo, key)?;
823
    let u = repo.policy_revoke(&full)?;
824
    println!("{} {}", ui::done("Revoked"), ui::hash(full.short(12)));
825
    report_update(&u, out)?;
826
    Ok(0)
827
}
828
829
/// `oxy seal [CHANGE..]`: seal the named changes, or every sealable one.
830
pub fn seal(specs: &[String], as_json: bool) -> Result<i32> {
831
    let repo = Repo::open(&std::env::current_dir()?)?;
832
    let hashes: Vec<_> = if specs.is_empty() {
833
        repo.sealable()?
834
    } else {
835
        specs
836
            .iter()
837
            .map(|s| repo.resolve_change(s))
838
            .collect::<std::result::Result<_, _>>()?
839
    };
840
    if hashes.is_empty() {
841
        if as_json {
842
            println!("{{\"sealed\":[]}}");
843
        } else {
844
            println!(
845
                "{} nothing to seal: every change you can authenticate already is",
846
                ui::done("Sealed")
847
            );
848
        }
849
        return Ok(0);
850
    }
851
    let mut refs = Vec::new();
852
    for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) {
853
        refs.push(repo.seal(chunk)?);
854
    }
855
    if as_json {
856
        let list: Vec<String> = hashes
857
            .iter()
858
            .map(|h| format!("\"{}\"", h.to_hex()))
859
            .collect();
860
        let seals: Vec<String> = refs.iter().map(|r| format!("\"{}\"", r.to_hex())).collect();
861
        println!(
862
            "{{\"sealed\":[{}],\"seals\":[{}]}}",
863
            list.join(","),
864
            seals.join(",")
865
        );
866
    } else {
867
        println!(
868
            "{} {} change{} in {} seal{}; they travel with your next push",
869
            ui::done("Sealed"),
870
            hashes.len(),
871
            if hashes.len() == 1 { "" } else { "s" },
872
            refs.len(),
873
            if refs.len() == 1 { "" } else { "s" }
874
        );
875
        for h in &hashes {
876
            let title = repo
877
                .store()
878
                .get_change(h)
879
                .map(|c| c.message.lines().next().unwrap_or("").to_string())
880
                .unwrap_or_default();
881
            println!("  {} {}", ui::hash(h.short(12)), title);
882
        }
883
    }
884
    Ok(0)
885
}
886
887
/// `oxy identity sign-challenge HEX`: the composite signature over a
888
/// host's challenge, as hex of the CBOR signature (hub spec §5.3).
889
pub fn sign_challenge(challenge_hex: &str, as_json: bool) -> Result<i32> {
890
    let repo = open()?;
891
    let Some((key, sk)) = repo.secret_key()? else {
892
        anyhow::bail!("no secret key: run `oxy identity create` first");
893
    };
894
    let challenge = hex_bytes(challenge_hex.trim())
895
        .ok_or_else(|| anyhow::anyhow!("the challenge must be hex"))?;
896
    let sig = sk
897
        .sign_challenge(&key, &challenge)
898
        .map_err(|e| anyhow::anyhow!("{e}"))?;
899
    let encoded = hex_string(&oxy_core::identity::Signature::encode_list(&[sig]));
900
    if as_json {
901
        println!(
902
            "{{\"key\":\"{}\",\"signature\":\"{}\"}}",
903
            key.to_hex(),
904
            encoded
905
        );
906
    } else {
907
        println!("{encoded}");
908
    }
909
    Ok(0)
910
}
911
912
fn hex_bytes(s: &str) -> Option<Vec<u8>> {
913
    if !s.len().is_multiple_of(2) {
914
        return None;
915
    }
916
    (0..s.len())
917
        .step_by(2)
918
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
919
        .collect()
920
}
921
922
fn hex_string(b: &[u8]) -> String {
923
    b.iter().map(|x| format!("{x:02x}")).collect()
924
}
925
926
#[cfg(test)]
927
mod tests {
928
    #[test]
929
    fn secrets_are_never_printed_whole() {
930
        assert!(
931
            super::secret_key("remote.earth.token")
932
                && super::secret_key("auth.secret")
933
                && !super::secret_key("remote.earth.url")
934
        );
935
        assert_eq!(
936
            super::mask("oxyhub_6b7dce13409b634d"),
937
            "oxyhub_6b7…(13 more)"
938
        );
939
        assert_eq!(super::mask("short"), "…");
940
    }
941
}