OXYGENHUB

Coverage / src/cli/identity.rs 26.3%

210 of 798 lines run, 17 of 153 functions · run #348 on paths-for-resolutions-and-amend · run missed

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
180×
fn expiry_from_days(days: u64) -> Option<u64> {
190×
    (days > 0).then(|| Hlc::now().wall_ms + days * DAY_MS)
200×
}
21
22
/// `30m`, `8h`, `7d`, or a bare number of days, as a wall time from now.
230×
fn expiry_from_duration(s: &str) -> Result<u64> {
240×
    let s = s.trim();
250×
    let (n, unit) = match s.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
260×
        Some((i, _)) => (&s[..i], &s[i..]),
270×
        None => (s, "d"),
28
    };
290×
    let n: u64 = n.parse().map_err(|_| {
300×
        anyhow::anyhow!("--expires takes 30m, 8h, 7d or a number of days, not {s:?}")
310×
    })?;
320×
    let ms = match unit {
330×
        "m" => 60_000,
340×
        "h" => 3_600_000,
350×
        "d" => DAY_MS,
360×
        _ => anyhow::bail!("--expires takes 30m, 8h, 7d or a number of days, not {s:?}"),
37
    };
380×
    if n == 0 {
390×
        anyhow::bail!("--expires needs a length of time; leave it out for no expiry");
400×
    }
410×
    Ok(Hlc::now().wall_ms + n * ms)
420×
}
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.
460×
fn print_delegates(repo: &Repo, delegates: &[Delegate]) {
470×
    if delegates.is_empty() {
480×
        return;
490×
    }
500×
    println!("{}", ui::kv("delegates", delegates.len().to_string()));
510×
    let now = Hlc::now().wall_ms;
520×
    for d in delegates {
530×
        let who = repo
540×
            .identity(&d.key)
550×
            .map(|i| format!("{} <{}>", i.name, i.email))
560×
            .unwrap_or_else(|_| "(unknown identity)".into());
570×
        let until = match d.expires {
580×
            Some(e) if now > e => ui::err(format!("expired {}", ui::ago(e))),
590×
            Some(e) => ui::dim(format!("until {}", when(e))),
600×
            None => String::new(),
61
        };
620×
        println!(
63
            "    {}  {}  {} {}",
640×
            ui::author(who),
650×
            ui::hash(d.key.short(12)),
660×
            ui::dim(d.scope.to_string()),
67
            until
68
        );
69
    }
700×
}
71
72
/// Resolve a KeyId prefix among the identities the repository knows.
730×
fn resolve_key(repo: &Repo, prefix: &str) -> Result<KeyId> {
740×
    if let Some(k) = KeyId::from_hex(prefix) {
750×
        return Ok(k);
760×
    }
770×
    let mut candidates: Vec<KeyId> = Vec::new();
780×
    if let Some((_, sp)) = repo.current_policy()? {
790×
        candidates.extend(sp.policy.identities.iter().map(|i| i.hash()));
800×
        candidates.extend(sp.policy.revoked.iter().copied());
810×
    }
820×
    if let Some(own) = repo.config.author_key {
830×
        candidates.push(own);
840×
        if let Ok(id) = repo.identity(&own) {
850×
            candidates.extend(id.delegates.iter().map(|d| d.key));
860×
        }
870×
    }
880×
    candidates.sort();
890×
    candidates.dedup();
900×
    let matches: Vec<_> = candidates
910×
        .into_iter()
920×
        .filter(|k| k.starts_with_hex(prefix))
930×
        .collect();
940×
    match matches.len() {
950×
        1 => Ok(matches[0]),
960×
        0 => anyhow::bail!("no known key starts with {prefix:?}"),
970×
        _ => anyhow::bail!("{prefix:?} is ambiguous"),
98
    }
990×
}
100
101
/// Report a policy update: applied, or written out as a proposal that
102
/// other root holders sign with `oxy policy sign`.
1032×
fn report_update(u: &PolicyUpdate, out: Option<PathBuf>) -> Result<()> {
1042×
    if u.applied {
1052×
        println!(
106
            "{} policy serial {} {}",
1072×
            ui::done("Applied"),
108
            u.policy.serial,
1092×
            ui::dim("(push to publish it)")
110
        );
1112×
        return Ok(());
1120×
    }
1130×
    let path = out.unwrap_or_else(|| PathBuf::from(format!("policy-{}.proposal", u.policy.serial)));
1140×
    std::fs::write(&path, u.signed().encode())?;
1150×
    println!(
116
        "{} policy serial {} needs {} of {} root signatures; has {}. Wrote {} for another root to run {}",
1170×
        ui::caution(),
118
        u.policy.serial,
119
        u.policy.root_threshold,
1200×
        u.policy.roots.len(),
1210×
        u.sigs.len(),
1220×
        ui::path(path.display()),
1230×
        ui::dim(format!("oxy policy sign {}", path.display()))
124
    );
1250×
    Ok(())
1262×
}
127
1280×
fn report_rotation(repo: &Repo, r: &Rotation, verb: &str) -> Result<()> {
1290×
    println!(
130
        "{} identity {} <{}>",
1310×
        ui::done(verb),
1320×
        ui::author(&r.identity.name),
133
        r.identity.email
134
    );
1350×
    println!("{}", ui::kv("old key", ui::dim(r.old.to_hex())));
1360×
    println!("{}", ui::kv("new key", r.new.to_hex()));
1370×
    print_delegates(repo, &r.identity.delegates);
1380×
    if let Some(e) = r.identity.expires {
1390×
        println!("{}", ui::kv("expires", when(e)));
1400×
    }
1410×
    match &r.policy {
1420×
        Some(u) => report_update(u, None)?,
1430×
        None => println!(
144
            "  {} {}",
1450×
            ui::note(),
1460×
            ui::dim("no policy names the old key; export the new identity for policy holders")
147
        ),
148
    }
1490×
    Ok(())
1500×
}
151
1522×
pub fn create(
1532×
    name: Option<String>,
1542×
    email: Option<String>,
1552×
    local: bool,
1562×
    expires: Option<u64>,
1572×
) -> Result<i32> {
1582×
    let mut repo = open()?;
1592×
    let name = name.unwrap_or_else(|| repo.config.author_name.clone());
1602×
    let email = email.unwrap_or_else(|| repo.config.author_email.clone());
1612×
    let scope = if local {
1620×
        IdentityScope::Repo
163
    } else {
1642×
        IdentityScope::User
165
    };
1662×
    let (key, _) =
1672×
        repo.create_identity_with(&name, &email, scope, expires.and_then(expiry_from_days))?;
1682×
    println!(
169
        "{} identity {} <{email}>",
1702×
        ui::done("Created"),
1712×
        ui::author(&name)
172
    );
1732×
    println!("{}", ui::kv("key", key));
1742×
    println!(
175
        "{}",
1762×
        ui::kv("secret", ui::path(repo::default_keys_dir().display()))
177
    );
1782×
    match scope {
1792×
        IdentityScope::User => println!(
180
            "{}",
1812×
            ui::kv(
1822×
                "scope",
1832×
                format!(
184
                    "default author in {}",
1852×
                    ui::path(repo.user_config_path().display())
186
                )
187
            )
188
        ),
189
        IdentityScope::Repo => {
1900×
            println!("{}", ui::kv("scope", "this repository's .oxy/config only"))
191
        }
192
    }
1932×
    if !repo.config.sign_changes {
1942×
        println!("  {} {}", ui::note(), ui::dim("changes will carry this author; run oxy config --user core.sign change to sign each commit"));
1952×
    }
1962×
    Ok(0)
1972×
}
198
1990×
pub fn show() -> Result<i32> {
2000×
    let repo = open()?;
2010×
    let Some(key) = repo.config.author_key else {
2020×
        println!("No identity configured; run `oxy identity create`.");
2030×
        return Ok(0);
204
    };
2050×
    let id = repo.identity(&key)?;
2060×
    println!(
207
        "{} {} <{}>",
2080×
        ui::section("identity"),
2090×
        ui::author(&id.name),
210
        id.email
211
    );
2120×
    println!("{}", ui::kv("key", key));
2130×
    println!(
214
        "{}",
2150×
        ui::kv(
2160×
            "created",
2170×
            format!(
218
                "{} {}",
2190×
                when(id.created),
2200×
                ui::dim(format!("({})", ui::ago(id.created)))
221
            )
222
        )
223
    );
2240×
    if let Some(e) = id.expires {
2250×
        let expired = id.is_expired_at(Hlc::now().wall_ms);
2260×
        println!(
227
            "{}",
2280×
            ui::kv(
2290×
                "expires",
2300×
                if expired {
2310×
                    ui::err(format!("{} EXPIRED", when(e)))
232
                } else {
2330×
                    when(e)
234
                }
235
            )
236
        );
2370×
    }
2380×
    if let Some(p) = id.previous {
2390×
        println!("{}", ui::kv("previous", ui::dim(p.short(12))));
2400×
    }
241
    // A repository that pins one key while the user file names another is
242
    // how checkouts drift apart after a rotation (oxygen#69).
2430×
    if let Some(pinned) = repo
2440×
        .config
2450×
        .repo_layer()
2460×
        .get("author.key")
2470×
        .and_then(|k| oxy_core::hash::KeyId::from_hex(k))
248
    {
2490×
        let user_key = repo::read_config_file(&repo::default_user_config())
2500×
            .ok()
2510×
            .and_then(|m| {
2520×
                m.get("author.key")
2530×
                    .and_then(|k| oxy_core::hash::KeyId::from_hex(k))
2540×
            });
2550×
        if let Some(u) = user_key.filter(|u| *u != pinned) {
2560×
            let related = |from: oxy_core::hash::KeyId, to: oxy_core::hash::KeyId| {
2570×
                let mut cur = Some(from);
2580×
                for _ in 0..64 {
2590×
                    match cur {
2600×
                        Some(k) if k == to => return true,
2610×
                        Some(k) => cur = repo.identity(&k).ok().and_then(|i| i.previous),
2620×
                        None => break,
263
                    }
264
                }
2650×
                false
2660×
            };
2670×
            let how = if related(pinned, u) {
2680×
                "an older key of this identity"
2690×
            } else if related(u, pinned) {
2700×
                "a newer key of this identity"
271
            } else {
2720×
                "another key"
273
            };
2740×
            println!(
275
                "  {} {}",
2760×
                ui::caution(),
2770×
                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 {}`",
2790×
                    pinned.short(12),
2800×
                    u.short(12),
2810×
                    pinned.to_hex()
282
                ))
283
            );
2840×
        }
2850×
    }
2860×
    print_delegates(&repo, &id.delegates);
2870×
    if repo.is_revoked(&key)? {
2880×
        println!(
2890×
            "{}",
2900×
            ui::kv(
2910×
                "status",
2920×
                ui::err(format!("{} REVOKED", ui::glyph("✖", "x")))
2930×
            )
2940×
        );
2950×
    }
2960×
    println!(
297
        "{}",
2980×
        ui::kv(
2990×
            "secret",
3000×
            if repo.secret_key()?.is_some() {
3010×
                ui::ok(format!("{} available", ui::glyph("✔", "*")))
302
            } else {
3030×
                ui::err(format!(
304
                    "{} not found in the key directory",
3050×
                    ui::glyph("✖", "x")
306
                ))
307
            }
308
        )
309
    );
3100×
    println!(
311
        "{}",
3120×
        ui::kv(
3130×
            "signing",
3140×
            if repo.config.sign_changes {
3150×
                "every change (core.sign = change)"
316
            } else {
3170×
                "at push via seals (core.sign = seal)"
318
            }
319
        )
320
    );
3210×
    Ok(0)
3220×
}
323
3241×
pub fn verify(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
3251×
    let repo = open()?;
3261×
    let hashes: Vec<ChangeHash> = match (change, revset) {
3270×
        (_, Some(r)) => {
3280×
            let wc = repo.working_copy().ok().map(|(h, _)| h);
3290×
            repo.revset(r)?
330
                .hashes
3310×
                .into_iter()
3320×
                .filter(|h| Some(*h) != wc)
3330×
                .collect()
334
        }
3350×
        (Some(c), None) => vec![repo.resolve_change(c)?],
3361×
        (None, None) => repo
3371×
            .log()?
3381×
            .into_iter()
3393×
            .filter(|e| !e.is_working_copy)
3401×
            .map(|e| e.hash)
3411×
            .collect(),
342
    };
3431×
    let mut bad = 0;
3441×
    if as_json {
3451×
        let mut items = Vec::new();
3462×
        for h in &hashes {
3472×
            let Ok(c) = repo.store().get_change(h) else {
3480×
                continue;
349
            };
3502×
            let (status, key, name, revoked, reason) = match repo.authenticate_change(h)? {
3510×
                SignatureStatus::Unsigned => ("unsigned", None, None, false, None),
352
                SignatureStatus::Valid {
3532×
                    key,
3542×
                    name,
3552×
                    sealed,
3562×
                    revoked,
357
                    ..
358
                } => (
3592×
                    if sealed { "sealed" } else { "signed" },
3602×
                    Some(key.to_hex()),
3612×
                    Some(name),
3622×
                    revoked,
3632×
                    None,
364
                ),
3650×
                SignatureStatus::Invalid(why) => {
3660×
                    bad += 1;
3670×
                    ("invalid", None, None, false, Some(why))
368
                }
369
            };
3702×
            items.push(json::obj([
3712×
                ("hash", json::s(&h.to_hex())),
3722×
                ("change_id", json::s(&c.change_id.to_hex())),
3732×
                ("status", json::s(status)),
3742×
                ("key", json::opt(key.as_deref(), json::s)),
3752×
                ("name", json::opt(name.as_deref(), json::s)),
3762×
                ("revoked", json::b(revoked)),
3772×
                ("reason", json::opt(reason.as_deref(), json::s)),
3782×
            ]));
379
        }
3801×
        println!("{}", json::arr(items));
3811×
        return Ok(if bad > 0 { 1 } else { 0 });
3820×
    }
3830×
    for h in hashes {
3840×
        let Ok(c) = repo.store().get_change(&h) else {
3850×
            println!(
386
                "{}  {}",
3870×
                ui::hash(format!("#{}", h.short(12))),
3880×
                ui::dim("not present (shallow)")
389
            );
3900×
            continue;
391
        };
3920×
        let line = signature_line(&repo, &h)?;
3930×
        let styled = if line.starts_with("INVALID") {
3940×
            bad += 1;
3950×
            ui::err(format!("{} {line}", ui::glyph("✖", "x")))
3960×
        } else if line == "unsigned" {
3970×
            ui::dim(format!("{} {line}", ui::glyph("·", "-")))
398
        } else {
3990×
            ui::ok(format!("{} {line}", ui::glyph("✔", "v")))
400
        };
4010×
        println!(
402
            "{} {}  {styled}",
4030×
            ui::id(short_id(&c)),
4040×
            ui::hash(format!("#{}", h.short(12)))
405
        );
406
    }
4070×
    Ok(if bad > 0 { 1 } else { 0 })
4081×
}
409
410
/// Whether a configuration key holds a secret, never to be printed.
4114×
fn secret_key(key: &str) -> bool {
4124×
    let k = key.to_ascii_lowercase();
4134×
    k.ends_with(".token") || k.contains("secret") || k.contains("password")
4144×
}
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.
4182×
fn mask(value: &str) -> String {
4192×
    let shown: String = value.chars().take(10).collect();
4202×
    let rest = value.chars().count().saturating_sub(10);
4212×
    if rest == 0 {
4221×
        "…".to_string()
423
    } else {
4241×
        format!("{shown}…({rest} more)")
425
    }
4262×
}
427
4281×
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;
4331×
    let value = if unset {
4340×
        ""
4351×
    } else if value == "-" {
4360×
        let mut line = String::new();
4370×
        std::io::stdin().read_line(&mut line)?;
4380×
        read = line.trim().to_string();
4390×
        read.as_str()
440
    } else {
4411×
        value
442
    };
4431×
    let said = if unset {
4440×
        format!("{} {key}", ui::done("Unset"))
4451×
    } else if secret_key(key) {
4460×
        format!("{} {key} = {}", ui::done("Set"), mask(value))
447
    } else {
4481×
        format!("{} {key} = {value}", ui::done("Set"))
449
    };
4501×
    if user {
4511×
        let path = repo::default_user_config();
4521×
        repo::Config::set_user(&path, key, value)?;
4531×
        println!("{said} {}", ui::dim(format!("(in {})", path.display())));
454
    } else {
4550×
        let mut repo = open()?;
4560×
        repo.config.set(key, value)?;
4570×
        repo.save_config()?;
4580×
        println!("{said} {}", ui::dim("(in this repository)"));
459
    }
4601×
    Ok(0)
4611×
}
462
4631×
pub fn export(path: Option<PathBuf>, pem: bool) -> Result<i32> {
4641×
    let repo = open()?;
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.
4671×
    let key = if pem {
4681×
        repo.signing_key()
469
    } else {
4700×
        repo.config.author_key
471
    };
4721×
    let Some(key) = key else {
4730×
        anyhow::bail!("no identity configured; run `oxy identity create`");
474
    };
4751×
    let id = repo.identity(&key)?;
4761×
    let ext = if pem { "pem" } else { "identity" };
4771×
    let path = path.unwrap_or_else(|| PathBuf::from(format!("{}.{ext}", key.short(16))));
4781×
    if pem {
4791×
        std::fs::write(&path, oxy_core::dsse::public_pem(&id))?;
480
    } else {
4810×
        std::fs::write(&path, id.encode())?;
482
    }
4831×
    println!(
484
        "{} {} {} <{}> ({}) to {}",
4851×
        ui::done("Wrote"),
4861×
        if pem { "the public key of" } else { "identity" },
4871×
        ui::author(&id.name),
488
        id.email,
4891×
        key.short(12),
4901×
        ui::path(path.display())
491
    );
4921×
    Ok(0)
4931×
}
494
4950×
pub fn rotate() -> Result<i32> {
4960×
    let mut repo = open()?;
4970×
    let r = repo.rotate_identity()?;
4980×
    report_rotation(&repo, &r, "Rotated")?;
4990×
    Ok(0)
5000×
}
501
5020×
pub fn renew(expires: u64) -> Result<i32> {
5030×
    let mut repo = open()?;
5040×
    let r = repo.renew_identity(expiry_from_days(expires))?;
5050×
    report_rotation(&repo, &r, "Renewed")?;
5060×
    Ok(0)
5070×
}
508
5090×
pub fn revoke(key: Option<&str>, reason: &str) -> Result<i32> {
5100×
    let repo = open()?;
5110×
    let key = match key {
5120×
        Some(k) => resolve_key(&repo, k)?,
5130×
        None => repo
5140×
            .config
5150×
            .author_key
5160×
            .ok_or_else(|| anyhow::anyhow!("no identity configured"))?,
517
    };
5180×
    let update = repo.revoke_identity(&key, reason)?;
5190×
    println!(
520
        "{} key {}{}",
5210×
        ui::done("Revoked"),
5220×
        ui::hash(key.short(12)),
5230×
        if reason.is_empty() {
5240×
            String::new()
525
        } else {
5260×
            format!(": {reason}")
527
        }
528
    );
5290×
    match update {
5300×
        Some(u) => report_update(&u, None)?,
5310×
        None => println!(
532
            "  {} {}",
5330×
            ui::note(),
5340×
            ui::dim("recorded locally; no policy named the key")
535
        ),
536
    }
537
    // A revoked delegate comes off the identity too, so the successor no
538
    // longer names it (spec §14.2).
5390×
    let own = repo.config.author_key;
5400×
    let delegated = own.is_some_and(|o| {
5410×
        repo.identity(&o)
5420×
            .is_ok_and(|id| id.delegate(&key).is_some())
5430×
    });
5440×
    if delegated {
5450×
        let mut repo = repo;
5460×
        let r = repo.delegate_remove(&key)?;
5470×
        report_rotation(&repo, &r, "Undelegated")?;
5480×
        return Ok(0);
5490×
    }
5500×
    if repo.config.author_key == Some(key) {
5510×
        println!(
5520×
            "  {} {}",
5530×
            ui::caution(),
5540×
            ui::warn("this was your configured key; run oxy identity create or rotate")
5550×
        );
5560×
    }
5570×
    Ok(0)
5580×
}
559
5600×
pub fn delegate_add(identity_files: &[PathBuf], scope: &str, expires: Option<&str>) -> Result<i32> {
5610×
    let mut repo = open()?;
5620×
    let ids = identity_files
5630×
        .iter()
5640×
        .map(|f| {
5650×
            Identity::decode(
5660×
                &std::fs::read(f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?,
567
            )
5680×
            .map_err(Into::into)
5690×
        })
5700×
        .collect::<Result<Vec<_>>>()?;
5710×
    let scope = Scope::parse(scope).map_err(|e| anyhow::anyhow!("{e}"))?;
5720×
    let expires = expires.map(expiry_from_duration).transpose()?;
5730×
    let r = repo.delegate_add_many(ids, scope, expires)?;
5740×
    report_rotation(&repo, &r, "Delegated")?;
5750×
    println!(
576
        "  {} {}",
5770×
        ui::note(),
5780×
        ui::dim("an agent configured with your author.key needs the new key: oxy config --user author.key NEW in its home")
579
    );
5800×
    if !scope.has(Scope::REFS) {
5810×
        println!(
5820×
            "  {} {}",
5830×
            ui::note(),
5840×
            ui::dim("it may not move references: a push or tag it attests is refused")
5850×
        );
5860×
    }
5870×
    Ok(0)
5880×
}
589
5900×
pub fn delegate_remove(key: &str) -> Result<i32> {
5910×
    let mut repo = open()?;
5920×
    let k = resolve_key(&repo, key)?;
5930×
    let r = repo.delegate_remove(&k)?;
5940×
    report_rotation(&repo, &r, "Undelegated")?;
5950×
    Ok(0)
5960×
}
597
5980×
pub fn delegate_list() -> Result<i32> {
5990×
    let repo = open()?;
6000×
    let Some(key) = repo.config.author_key else {
6010×
        println!("No identity configured; run `oxy identity create`.");
6020×
        return Ok(0);
603
    };
6040×
    let id = repo.identity(&key)?;
6050×
    if id.delegates.is_empty() {
6060×
        println!("{}", ui::dim("No delegates."));
6070×
    }
6080×
    let now = Hlc::now().wall_ms;
6090×
    for d in &id.delegates {
6100×
        let who = repo
6110×
            .identity(&d.key)
6120×
            .map(|i| format!("{} <{}>", i.name, i.email))
6130×
            .unwrap_or_else(|_| "(unknown identity)".into());
6140×
        let until = match d.expires {
6150×
            Some(e) if now > e => ui::err(format!("expired {}", ui::ago(e))),
6160×
            Some(e) => ui::dim(format!("until {}", when(e))),
6170×
            None => String::new(),
618
        };
6190×
        println!(
620
            "  {} {}  {}  {} {}",
6210×
            ui::ok(ui::glyph("🔑", "*")),
6220×
            ui::hash(d.key.short(12)),
6230×
            ui::author(who),
6240×
            ui::dim(d.scope.to_string()),
625
            until
626
        );
627
    }
6280×
    Ok(0)
6290×
}
630
6310×
pub fn policy_root_add(identity_file: &Path, out: Option<PathBuf>) -> Result<i32> {
6320×
    let repo = open()?;
6330×
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
6340×
    let key = id.hash();
6350×
    let u = repo.policy_root_add(id.clone())?;
6360×
    println!(
637
        "{} root {} <{}> ({})",
6380×
        ui::done("Added"),
6390×
        ui::author(&id.name),
640
        id.email,
6410×
        key.short(12)
642
    );
6430×
    report_update(&u, out)?;
6440×
    Ok(0)
6450×
}
646
6470×
pub fn policy_root_remove(key: &str, out: Option<PathBuf>) -> Result<i32> {
6480×
    let repo = open()?;
6490×
    let k = resolve_key(&repo, key)?;
6500×
    let u = repo.policy_root_remove(&k)?;
6510×
    println!("{} root {}", ui::done("Removed"), ui::hash(k.short(12)));
6520×
    report_update(&u, out)?;
6530×
    Ok(0)
6540×
}
655
6560×
pub fn policy_threshold(n: u32, out: Option<PathBuf>) -> Result<i32> {
6570×
    let repo = open()?;
6580×
    let u = repo.policy_set_threshold(n)?;
6590×
    println!("{} root threshold to {n}", ui::done("Set"));
6600×
    report_update(&u, out)?;
6610×
    Ok(0)
6620×
}
663
6640×
pub fn policy_sign(proposal: &Path, out: Option<PathBuf>) -> Result<i32> {
6650×
    let repo = open()?;
6660×
    let sp = SignedPolicy::decode(&std::fs::read(proposal)?)?;
6670×
    let u = repo.policy_sign(sp)?;
6680×
    println!("{} policy serial {}", ui::done("Signed"), u.policy.serial);
6690×
    report_update(&u, Some(out.unwrap_or_else(|| proposal.to_path_buf())))?;
6700×
    Ok(0)
6710×
}
672
6731×
pub fn policy_init() -> Result<i32> {
6741×
    let repo = open()?;
6751×
    let sp = repo.policy_init()?;
6761×
    println!(
677
        "{} policy with root key {}",
6781×
        ui::done("Created"),
6791×
        sp.policy.roots[0].short(12)
680
    );
6811×
    report_update(&sp, None)?;
6821×
    Ok(0)
6831×
}
684
6853×
pub fn policy_show(as_json: bool) -> Result<i32> {
6863×
    let repo = open()?;
6873×
    let Some((r, sp)) = repo.current_policy()? else {
6881×
        if as_json {
6891×
            println!("null");
6901×
        } else {
6910×
            println!(
6920×
                "No policy: this repository is unverified. Run `oxy policy init` to create one."
6930×
            );
6940×
        }
6951×
        return Ok(0);
696
    };
6972×
    let p = &sp.policy;
6982×
    if as_json {
6995×
        let ident = |k: &oxy_core::hash::KeyId| {
7005×
            let (name, email) = p
7015×
                .identity(k)
7025×
                .map(|i| (i.name.clone(), i.email.clone()))
7035×
                .unwrap_or_default();
7045×
            json::obj([
7055×
                ("key", json::s(&k.to_hex())),
7065×
                ("name", json::s(&name)),
7075×
                ("email", json::s(&email)),
7085×
            ])
7095×
        };
7102×
        println!(
711
            "{}",
7122×
            json::obj([
7132×
                ("hash", json::s(&r.to_hex())),
7142×
                ("serial", json::n(p.serial)),
7152×
                ("expires_ms", json::n(p.expires)),
7162×
                (
7172×
                    "expired",
7182×
                    json::b(p.is_expired(oxy_core::objects::Hlc::now().wall_ms))
7192×
                ),
7202×
                ("root_threshold", json::n(p.root_threshold)),
7212×
                ("roots", json::arr(p.roots.iter().map(ident))),
722
                (
7232×
                    "rules",
7242×
                    json::arr(p.rules.iter().map(|rule| {
7252×
                        json::obj([
7262×
                            ("pattern", json::s(&rule.pattern)),
7272×
                            ("keys", json::arr(rule.keys.iter().map(ident))),
7282×
                            ("threshold", json::n(rule.threshold)),
7292×
                            ("require", json::s(rule.require.name())),
7302×
                            ("allow_conflicts", json::b(rule.allow_conflicts)),
731
                            (
7322×
                                "subjects",
7332×
                                json::arr(rule.subjects.iter().map(|g| {
7341×
                                    json::obj([
7351×
                                        ("subject", json::s(&g.pattern)),
7361×
                                        ("issuer", ident(&g.issuer)),
7371×
                                        ("scope", json::s(&g.scope.to_string())),
7381×
                                    ])
7391×
                                })),
740
                            ),
741
                        ])
7422×
                    })),
743
                ),
7442×
                ("revoked", json::arr(p.revoked.iter().map(ident))),
745
            ])
746
        );
7472×
        return Ok(0);
7480×
    }
7490×
    let name = |k: &oxy_core::hash::KeyId| {
7500×
        p.identity(k)
7510×
            .map(|i| format!("{} <{}>", i.name, i.email))
7520×
            .unwrap_or_else(|| "(unknown identity)".into())
7530×
    };
7540×
    let expired = p.is_expired(oxy_core::objects::Hlc::now().wall_ms);
7550×
    println!(
756
        "{} {}{}serial {}{}expires {}{}",
7570×
        ui::section("policy"),
7580×
        ui::hash(format!("#{}", r.short(12))),
7590×
        ui::sep(),
760
        p.serial,
7610×
        ui::sep(),
7620×
        when(p.expires),
7630×
        if expired {
7640×
            ui::err(format!("  {} EXPIRED", ui::glyph("✖", "x")))
765
        } else {
7660×
            String::new()
767
        }
768
    );
7690×
    println!(
770
        "{}",
7710×
        ui::section(format!(
772
            "roots {}",
7730×
            ui::dim(format!("(threshold {})", p.root_threshold))
774
        ))
775
    );
7760×
    for k in &p.roots {
7770×
        println!(
7780×
            "  {} {}  {}",
7790×
            ui::ok(ui::glyph("🔑", "*")),
7800×
            ui::hash(k.short(12)),
7810×
            ui::author(name(k))
7820×
        );
7830×
    }
7840×
    println!("{}", ui::section("rules"));
7850×
    for rule in &p.rules {
7860×
        println!(
787
            "  {} {:12} {}",
7880×
            ui::ok(ui::glyph("▸", ">")),
7890×
            ui::bookmark(&rule.pattern),
7900×
            ui::dim(format!(
791
                "threshold {}, require {}, conflicts {}",
792
                rule.threshold,
7930×
                rule.require.name(),
7940×
                if rule.allow_conflicts {
7950×
                    "allowed"
796
                } else {
7970×
                    "refused"
798
                }
799
            ))
800
        );
8010×
        for k in &rule.keys {
8020×
            println!("      {}  {}", ui::hash(k.short(12)), ui::author(name(k)));
8030×
        }
8040×
        for g in &rule.subjects {
8050×
            println!(
8060×
                "      {}  {} {}",
8070×
                ui::author(&g.pattern),
8080×
                ui::dim(format!(
8090×
                    "certified by {} ({}),",
8100×
                    name(&g.issuer),
8110×
                    g.issuer.short(12)
8120×
                )),
8130×
                ui::dim(format!("scope {}", g.scope))
8140×
            );
8150×
        }
816
    }
8170×
    if !p.revoked.is_empty() {
8180×
        println!("{}", ui::section("revoked"));
8190×
        for k in &p.revoked {
8200×
            println!(
8210×
                "  {} {}  {}",
8220×
                ui::err(ui::glyph("✖", "x")),
8230×
                ui::hash(k.short(12)),
8240×
                ui::author(name(k))
8250×
            );
8260×
        }
8270×
    }
8280×
    Ok(0)
8293×
}
830
8310×
pub fn policy_grant(
8320×
    identity_file: &Path,
8330×
    pattern: Option<&str>,
8340×
    out: Option<PathBuf>,
8350×
) -> Result<i32> {
8360×
    let repo = open()?;
8370×
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
8380×
    let key = id.hash();
8390×
    let u = repo.policy_grant(id.clone(), pattern)?;
8400×
    println!(
841
        "{} {} <{}> ({}) on {}",
8420×
        ui::done("Granted"),
8430×
        ui::author(&id.name),
844
        id.email,
8450×
        key.short(12),
8460×
        ui::bookmark(pattern.unwrap_or("*"))
847
    );
8480×
    report_update(&u, out)?;
8490×
    Ok(0)
8500×
}
851
8521×
pub fn policy_grant_subject(
8531×
    subject: &str,
8541×
    issuer_file: &Path,
8551×
    scope: &str,
8561×
    pattern: Option<&str>,
8571×
    out: Option<PathBuf>,
8581×
) -> Result<i32> {
8591×
    let repo = open()?;
8601×
    let issuer = Identity::decode(&std::fs::read(issuer_file)?)
8611×
        .map_err(|e| anyhow::anyhow!("{}: not an identity file: {e}", issuer_file.display()))?;
8621×
    let scope = oxy_core::identity::Scope::parse(scope).map_err(|e| anyhow::anyhow!(e))?;
8631×
    let key = issuer.hash();
8641×
    let u = repo.policy_grant_subject(subject, issuer.clone(), scope, pattern)?;
8651×
    println!(
866
        "{} {} certified by {} ({}) on {}, scope {}",
8671×
        ui::done("Granted"),
8681×
        ui::author(subject),
869
        issuer.name,
8701×
        key.short(12),
8711×
        ui::bookmark(pattern.unwrap_or("*")),
872
        scope
873
    );
8741×
    report_update(&u, out)?;
8751×
    Ok(0)
8761×
}
877
8780×
pub fn policy_revoke(key: &str, out: Option<PathBuf>) -> Result<i32> {
8790×
    let repo = open()?;
8800×
    if repo.current_policy()?.is_none() {
8810×
        anyhow::bail!("this repository has no policy");
8820×
    }
8830×
    let full = resolve_key(&repo, key)?;
8840×
    let u = repo.policy_revoke(&full)?;
8850×
    println!("{} {}", ui::done("Revoked"), ui::hash(full.short(12)));
8860×
    report_update(&u, out)?;
8870×
    Ok(0)
8880×
}
889
890
/// `oxy seal [CHANGE..]`: seal the named changes, or every sealable one.
8910×
pub fn seal(specs: &[String], as_json: bool) -> Result<i32> {
8920×
    let repo = Repo::open(&std::env::current_dir()?)?;
8930×
    let hashes: Vec<_> = if specs.is_empty() {
8940×
        repo.sealable()?
895
    } else {
8960×
        specs
8970×
            .iter()
8980×
            .map(|s| repo.resolve_change(s))
8990×
            .collect::<std::result::Result<_, _>>()?
900
    };
9010×
    if hashes.is_empty() {
9020×
        if as_json {
9030×
            println!("{{\"sealed\":[]}}");
9040×
        } else {
9050×
            println!(
9060×
                "{} nothing to seal: every change you can authenticate already is",
9070×
                ui::done("Sealed")
9080×
            );
9090×
        }
9100×
        return Ok(0);
9110×
    }
9120×
    let mut refs = Vec::new();
9130×
    for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) {
9140×
        refs.push(repo.seal(chunk)?);
915
    }
9160×
    if as_json {
9170×
        let list: Vec<String> = hashes
9180×
            .iter()
9190×
            .map(|h| format!("\"{}\"", h.to_hex()))
9200×
            .collect();
9210×
        let seals: Vec<String> = refs.iter().map(|r| format!("\"{}\"", r.to_hex())).collect();
9220×
        println!(
923
            "{{\"sealed\":[{}],\"seals\":[{}]}}",
9240×
            list.join(","),
9250×
            seals.join(",")
926
        );
927
    } else {
9280×
        println!(
929
            "{} {} change{} in {} seal{}; they travel with your next push",
9300×
            ui::done("Sealed"),
9310×
            hashes.len(),
9320×
            if hashes.len() == 1 { "" } else { "s" },
9330×
            refs.len(),
9340×
            if refs.len() == 1 { "" } else { "s" }
935
        );
9360×
        for h in &hashes {
9370×
            let title = repo
9380×
                .store()
9390×
                .get_change(h)
9400×
                .map(|c| c.message.lines().next().unwrap_or("").to_string())
9410×
                .unwrap_or_default();
9420×
            println!("  {} {}", ui::hash(h.short(12)), title);
943
        }
944
    }
9450×
    Ok(0)
9460×
}
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).
9500×
pub fn sign_challenge(challenge_hex: &str, as_json: bool) -> Result<i32> {
9510×
    let repo = open()?;
9520×
    let Some((key, sk)) = repo.secret_key()? else {
9530×
        anyhow::bail!("no secret key: run `oxy identity create` first");
954
    };
9550×
    let challenge = hex_bytes(challenge_hex.trim())
9560×
        .ok_or_else(|| anyhow::anyhow!("the challenge must be hex"))?;
9570×
    let sig = sk
9580×
        .sign_challenge(&key, &challenge)
9590×
        .map_err(|e| anyhow::anyhow!("{e}"))?;
9600×
    let encoded = hex_string(&oxy_core::identity::Signature::encode_list(&[sig]));
9610×
    if as_json {
9620×
        println!(
9630×
            "{{\"key\":\"{}\",\"signature\":\"{}\"}}",
9640×
            key.to_hex(),
9650×
            encoded
9660×
        );
9670×
    } else {
9680×
        println!("{encoded}");
9690×
    }
9700×
    Ok(0)
9710×
}
972
9730×
fn hex_bytes(s: &str) -> Option<Vec<u8>> {
9740×
    if !s.len().is_multiple_of(2) {
9750×
        return None;
9760×
    }
9770×
    (0..s.len())
9780×
        .step_by(2)
9790×
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
9800×
        .collect()
9810×
}
982
9830×
fn hex_string(b: &[u8]) -> String {
9840×
    b.iter().map(|x| format!("{x:02x}")).collect()
9850×
}
986
987
#[cfg(test)]
988
mod tests {
989
    #[test]
9901×
    fn secrets_are_never_printed_whole() {
9911×
        assert!(
9921×
            super::secret_key("remote.earth.token")
9931×
                && super::secret_key("auth.secret")
9941×
                && !super::secret_key("remote.earth.url")
995
        );
9961×
        assert_eq!(
9971×
            super::mask("oxyhub_6b7dce13409b634d"),
998
            "oxyhub_6b7…(13 more)"
999
        );
10001×
        assert_eq!(super::mask("short"), "…");
10011×
    }
1002
}