OXYGENHUB
# a269bee11bb2 oxygen / src / cli / identity.rs
5.8 KiB · Rust · last changed Trust policy: policy objects, init/grant/revoke, enforcement on push and fetch, propagation with downgrade protection (spec 0.6) 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Identity, verification, and configuration commands.
2
3
use super::format::{short_id, signature_line, when};
4
use super::open;
5
use anyhow::Result;
6
use oxy_core::hash::ChangeHash;
83e0677b Andy McCall ↶ 7
use oxy_core::identity::Identity;
fce44ae9 Andy McCall ↶ 8
use oxy_core::repo::{self, IdentityScope};
83e0677b Andy McCall ↶ 9
use std::path::{Path, PathBuf};
fce44ae9 Andy McCall ↶ 10
11
pub fn create(name: Option<String>, email: Option<String>, local: bool) -> Result<i32> {
12
    let mut repo = open()?;
13
    let name = name.unwrap_or_else(|| repo.config.author_name.clone());
14
    let email = email.unwrap_or_else(|| repo.config.author_email.clone());
15
    let scope = if local { IdentityScope::Repo } else { IdentityScope::User };
16
    let (key, _) = repo.create_identity(&name, &email, scope)?;
17
    println!("Created identity {name} <{email}>");
18
    println!("KeyId: {key}");
19
    println!("Secret key stored under {}", repo::default_keys_dir().display());
20
    match scope {
21
        IdentityScope::User => println!("Recorded as your default author in {}", repo.user_config_path().display()),
22
        IdentityScope::Repo => println!("Recorded in this repository's .oxy/config only"),
23
    }
24
    if !repo.config.sign_changes {
25
        println!("Changes will carry this author; run `oxy config --user core.sign change` to sign each commit.");
26
    }
27
    Ok(0)
28
}
29
30
pub fn show() -> Result<i32> {
31
    let repo = open()?;
32
    let Some(key) = repo.config.author_key else {
33
        println!("No identity configured; run `oxy identity create`.");
34
        return Ok(0);
35
    };
36
    let id = repo.identity(&key)?;
37
    println!("{} <{}>", id.name, id.email);
38
    println!("KeyId:   {key}");
39
    println!("Created: {}", when(id.created));
40
    println!("Secret:  {}", if repo.secret_key()?.is_some() { "available" } else { "NOT FOUND in key directory" });
41
    println!("Signing: {}", if repo.config.sign_changes { "every change (core.sign = change)" } else { "at push via seals (core.sign = seal)" });
42
    Ok(0)
43
}
44
45
pub fn verify(change: Option<&str>) -> Result<i32> {
46
    let repo = open()?;
47
    let hashes: Vec<ChangeHash> = match change {
48
        Some(c) => vec![repo.resolve_change(c)?],
49
        None => repo.log()?.into_iter().filter(|e| !e.is_working_copy).map(|e| e.hash).collect(),
50
    };
51
    let mut bad = 0;
52
    for h in hashes {
53
        let c = repo.store().get_change(&h)?;
54
        let line = signature_line(&repo, &h)?;
55
        if line.starts_with("INVALID") {
56
            bad += 1;
57
        }
58
        println!("{} #{}  {line}", short_id(&c), h.short(12));
59
    }
60
    Ok(if bad > 0 { 1 } else { 0 })
61
}
62
63
pub fn config(key: &str, value: &str, user: bool) -> Result<i32> {
64
    if user {
65
        let path = repo::default_user_config();
66
        repo::Config::set_user(&path, key, value)?;
67
        println!("{key} = {value} (in {})", path.display());
68
    } else {
69
        let mut repo = open()?;
70
        repo.config.set(key, value)?;
71
        repo.save_config()?;
72
        println!("{key} = {value} (in this repository)");
73
    }
74
    Ok(0)
75
}
83e0677b Andy McCall ↶ 76
77
pub fn export(path: Option<PathBuf>) -> Result<i32> {
78
    let repo = open()?;
79
    let Some(key) = repo.config.author_key else {
80
        anyhow::bail!("no identity configured; run `oxy identity create`");
81
    };
82
    let id = repo.identity(&key)?;
83
    let path = path.unwrap_or_else(|| PathBuf::from(format!("{}.identity", key.short(16))));
84
    std::fs::write(&path, id.encode())?;
85
    println!("Wrote identity {} <{}> ({}) to {}", id.name, id.email, key.short(12), path.display());
86
    Ok(0)
87
}
88
89
pub fn policy_init() -> Result<i32> {
90
    let repo = open()?;
91
    let sp = repo.policy_init()?;
92
    println!("Created policy serial {} with root key {}; push to publish it.", sp.policy.serial, sp.policy.roots[0].short(12));
93
    Ok(0)
94
}
95
96
pub fn policy_show() -> Result<i32> {
97
    let repo = open()?;
98
    let Some((r, sp)) = repo.current_policy()? else {
99
        println!("No policy: this repository is unverified. Run `oxy policy init` to create one.");
100
        return Ok(0);
101
    };
102
    let p = &sp.policy;
103
    let name = |k: &oxy_core::hash::KeyId| p.identity(k).map(|i| format!("{} <{}>", i.name, i.email)).unwrap_or_else(|| "(unknown identity)".into());
104
    println!("policy #{} serial {} expires {}{}", r.short(12), p.serial, when(p.expires), if p.is_expired(oxy_core::objects::Hlc::now().wall_ms) { "  EXPIRED" } else { "" });
105
    println!("roots (threshold {}):", p.root_threshold);
106
    for k in &p.roots {
107
        println!("  {}  {}", k.short(12), name(k));
108
    }
109
    println!("rules:");
110
    for rule in &p.rules {
111
        println!("  {:12} threshold {} require {} conflicts {}", rule.pattern, rule.threshold, rule.require.name(), if rule.allow_conflicts { "allowed" } else { "refused" });
112
        for k in &rule.keys {
113
            println!("      {}  {}", k.short(12), name(k));
114
        }
115
    }
116
    if !p.revoked.is_empty() {
117
        println!("revoked:");
118
        for k in &p.revoked {
119
            println!("  {}  {}", k.short(12), name(k));
120
        }
121
    }
122
    Ok(0)
123
}
124
125
pub fn policy_grant(identity_file: &Path, pattern: Option<&str>) -> Result<i32> {
126
    let repo = open()?;
127
    let id = Identity::decode(&std::fs::read(identity_file)?)?;
128
    let key = id.hash();
129
    let sp = repo.policy_grant(id.clone(), pattern)?;
130
    println!("Granted {} <{}> ({}) on {}; policy serial {}. Push to publish.", id.name, id.email, key.short(12), pattern.unwrap_or("*"), sp.policy.serial);
131
    Ok(0)
132
}
133
134
pub fn policy_revoke(key: &str) -> Result<i32> {
135
    let repo = open()?;
136
    let Some((_, sp)) = repo.current_policy()? else {
137
        anyhow::bail!("this repository has no policy");
138
    };
139
    let matches: Vec<_> = sp.policy.identities.iter().map(|i| i.hash()).filter(|k| k.starts_with_hex(key)).collect();
140
    let full = match matches.len() {
141
        1 => matches[0],
142
        0 => anyhow::bail!("no key in the policy starts with {key:?}"),
143
        _ => anyhow::bail!("{key:?} is ambiguous"),
144
    };
145
    let sp = repo.policy_revoke(&full)?;
146
    println!("Revoked {}; policy serial {}. Push to publish.", full.short(12), sp.policy.serial);
147
    Ok(0)
148
}