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