OXYGENHUB
# 5d695d869fbf spectra / src / cli / identity.rs
7.3 KiB · Rust · last changed The command line in oxy's style: ticks and verbs, key-value rows, sections, hints, spinners; plain when piped 2 days ago source blame history raw
1
//! `spectra init` and `spectra identity`: the owner and the instance
2
//! (spec §8.3, §9.5). The owner proves possession of their identity by
3
//! signing with it; Spectra never holds the owner's secret key.
4
5
use super::{ui, Ctx};
6
use anyhow::{bail, Context, Result};
7
use oxy_core::identity::Identity;
8
use spectra_core::keys::KeyPair;
9
use spectra_core::ledger::Ledger;
10
use spectra_core::principals::{identity_payload, signed_event, Principals};
11
use std::path::{Path, PathBuf};
12
13
/// The owner's `OXY_HOME`: `--owner-home`, else `[owner] home` in
14
/// spectra.toml, else oxy's own default.
15
pub fn owner_home(ctx: &Ctx, flag: Option<PathBuf>) -> PathBuf {
16
    flag.or_else(|| ctx.config_owner_home()).unwrap_or_else(oxy_core::repo::default_home)
17
}
18
19
pub async fn init(ctx: &Ctx, owner_home_flag: Option<PathBuf>, name: Option<String>) -> Result<i32> {
20
    let data = &ctx.data;
21
    let db = data.join("spectra.db");
22
    if db.exists() {
23
        bail!("{} already holds a Spectra (spectra identity show)", data.display());
24
    }
25
    let home = owner_home(ctx, owner_home_flag);
26
    let owner = KeyPair::load_home(&home).with_context(|| {
27
        format!("the owner signs with their own identity: none usable in {} (oxy identity create, or --owner-home)", home.display())
28
    })?;
29
    std::fs::create_dir_all(data)?;
30
    #[cfg(unix)]
31
    {
32
        use std::os::unix::fs::PermissionsExt;
33
        std::fs::set_permissions(data, std::fs::Permissions::from_mode(0o700))?;
34
    }
35
    let name = name.unwrap_or_else(hostname);
36
    let instance = KeyPair::instance(data, &name)?;
37
    let ledger = Ledger::open(&db, Some(instance.clone())).await?;
38
    ledger
39
        .append(vec![
40
            signed_event(&owner, "human", "identity.owner", identity_payload(&owner.identity)),
41
            signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity)),
42
        ])
43
        .await?;
44
    ledger.checkpoint().await?;
45
    let home_s = home.display().to_string();
46
    std::fs::write(
47
        data.join("spectra.toml"),
48
        format!("# Spectra's configuration (spec §22.1).\n\n[owner]\nkey = \"{}\"\nhome = {}\n", owner.key.to_hex(), toml_str(&home_s)),
49
    )?;
50
    println!("{} {}  {}", ui::done("Initialised"), ui::subject("Spectra"), ui::path(data.display()));
51
    println!("{}", ui::kv("owner", format!("{}{}{}", ui::author(&owner.identity.name), ui::sep(), ui::hash(owner.key.short(12)))));
52
    println!("{}", ui::kv("instance", format!("{}{}{}", name, ui::sep(), ui::hash(instance.key.short(12)))));
53
    println!("{}", ui::kv("ledger", format!("{}{}", ui::path(db.display()), ui::dim(" (verified with spectra admin verify)"))));
54
    println!();
55
    println!("  {} {}", ui::note(), ui::dim("so that checkpoints are verifiably from your machine, delegate to the instance key:"));
56
    println!(
57
        "    {}",
58
        ui::id(format!("oxy identity delegate add {} --scope changes", data.join("keys").join("instance.identity").display()))
59
    );
60
    println!(
61
        "  {} {} {}",
62
        ui::note(),
63
        ui::dim("then add agents with"),
64
        ui::id("spectra agent add NAME --kind KIND --project PROJECT --home DIR")
65
    );
66
    Ok(0)
67
}
68
69
pub async fn show(ctx: &Ctx, json: bool) -> Result<i32> {
70
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
71
    let p = Principals::load(&ledger).await?;
72
    let owner = p.owner().context("no owner is recorded")?;
73
    let instance = p.instance();
74
    let delegated =
75
        instance.is_some_and(|i| owner.delegates_to(&i.hash(), spectra_core::principals::DELEGATION_SCOPE, spectra_core::ids::now_ms()));
76
    if json {
77
        println!(
78
            "{}",
79
            serde_json::json!({
80
                "owner": { "name": owner.name, "key": owner.hash().to_hex() },
81
                "instance": instance.map(|i| serde_json::json!({ "name": i.name, "key": i.hash().to_hex(), "delegated": delegated })),
82
            })
83
        );
84
        return Ok(0);
85
    }
86
    println!("{}", ui::section("Owner"));
87
    println!("{}", ui::kv("name", ui::author(format!("{} <{}>", owner.name, owner.email))));
88
    println!("{}", ui::kv("key", ui::hash(owner.hash().to_hex())));
89
    println!("{}", ui::kv("delegates", owner.delegates.len()));
90
    if let Some(i) = instance {
91
        println!("{}", ui::section("Instance"));
92
        println!("{}", ui::kv("name", &i.name));
93
        println!("{}", ui::kv("key", ui::hash(i.hash().to_hex())));
94
        if delegated {
95
            println!("{}", ui::kv("status", ui::ok("delegated by the owner: checkpoints are verifiably yours")));
96
        } else {
97
            println!("{}", ui::kv("status", ui::warn("not delegated by the owner yet")));
98
            println!(
99
                "  {} {}",
100
                ui::note(),
101
                ui::id(format!("oxy identity delegate add {} --scope changes", ctx.data.join("keys").join("instance.identity").display()))
102
            );
103
        }
104
    }
105
    Ok(0)
106
}
107
108
/// Record the owner's current identity when it has moved on (a delegation
109
/// added or removed): `spectra identity refresh`.
110
pub async fn refresh(ctx: &Ctx, owner_home_flag: Option<PathBuf>) -> Result<i32> {
111
    let ledger = ctx.writer().await?;
112
    let outcome = refresh_owner(&ledger, &owner_home(ctx, owner_home_flag)).await?;
113
    ledger.checkpoint().await?;
114
    match outcome {
115
        Some(id) => println!(
116
            "{} {}{}{}",
117
            ui::done("Recorded"),
118
            ui::subject("the owner's current identity"),
119
            ui::sep(),
120
            ui::hash(id.hash().short(12))
121
        ),
122
        None => println!("{} {}", ui::done("Current"), ui::subject("the owner's identity has not moved")),
123
    }
124
    Ok(0)
125
}
126
127
/// If the owner's home names a successor of the recorded owner, record it,
128
/// signed with it, with the identities between. Returns the new identity.
129
pub async fn refresh_owner(ledger: &Ledger, home: &Path) -> Result<Option<Identity>> {
130
    let p = Principals::load(ledger).await?;
131
    let recorded = p.owner().context("no owner is recorded (spectra init)")?.clone();
132
    let pair = KeyPair::load_home(home)?;
133
    if pair.key == recorded.hash() {
134
        return Ok(None);
135
    }
136
    let mut chain = Vec::new();
137
    let mut at = pair.identity.clone();
138
    while let Some(prev) = at.previous {
139
        if prev == recorded.hash() {
140
            break;
141
        }
142
        let file = home.join("keys").join(format!("{}.identity", prev.to_hex()));
143
        at = Identity::decode(
144
            &std::fs::read(&file).with_context(|| format!("{} is not a successor of the recorded owner", pair.identity.name))?,
145
        )
146
        .map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?;
147
        chain.push(hex::encode(at.encode()));
148
        if chain.len() > 1000 {
149
            bail!("the owner's identity chain is too long to follow");
150
        }
151
    }
152
    if at.previous != Some(recorded.hash()) && pair.identity.previous != Some(recorded.hash()) {
153
        bail!("{} in {} is not a successor of the recorded owner {}", pair.identity.name, home.display(), recorded.hash().short(12));
154
    }
155
    let mut payload = identity_payload(&pair.identity);
156
    payload["chain"] = chain.into();
157
    ledger.append_one(signed_event(&pair, "human", "identity.rotated", payload)).await?;
158
    Ok(Some(pair.identity))
159
}
160
161
fn hostname() -> String {
162
    std::fs::read_to_string("/etc/hostname")
163
        .ok()
164
        .map(|h| h.trim().to_string())
165
        .filter(|h| !h.is_empty())
166
        .unwrap_or_else(|| "spectra".into())
167
}
168
169
fn toml_str(s: &str) -> String {
170
    serde_json::to_string(s).unwrap_or_default()
171
}