OXYGENHUB
# eca5af92279b spectra / src / cli / identity.rs
10.7 KiB · Rust · last changed spectra connect: trust a server through the owner's delegation, pin it, claim it (#21) 1 day 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
    let mut first = vec![
39
        signed_event(&owner, "human", "identity.owner", identity_payload(&owner.identity)),
40
        signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity)),
41
    ];
42
    first.extend(spectra_core::conversation::default_channel_events());
43
    ledger.append(first).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 home = owner_home(ctx, owner_home_flag);
112
    let w = ctx.owner_writer(&home).await?;
113
    let rotated = refresh_event(w.ledger(), &home).await?;
114
    let outcome = rotated.as_ref().map(|_| KeyPair::load_home(&home).map(|p| p.identity)).transpose()?;
115
    if let Some(e) = rotated {
116
        w.append(vec![e]).await?;
117
    }
118
    match outcome {
119
        Some(id) => println!(
120
            "{} {}{}{}",
121
            ui::done("Recorded"),
122
            ui::subject("the owner's current identity"),
123
            ui::sep(),
124
            ui::hash(id.hash().short(12))
125
        ),
126
        None => println!("{} {}", ui::done("Current"), ui::subject("the owner's identity has not moved")),
127
    }
128
    Ok(0)
129
}
130
131
/// If the owner's home names a successor of the recorded owner, the event
132
/// that records it, signed with it, with the identities between. Callers
133
/// append it in the same batch as whatever needs it.
134
pub async fn refresh_event(ledger: &Ledger, home: &Path) -> Result<Option<spectra_core::event::NewEvent>> {
135
    let p = Principals::load(ledger).await?;
136
    let recorded = p.owner().context("no owner is recorded (spectra init)")?.clone();
137
    rotation(&recorded, home)
138
}
139
140
/// The `identity.rotated` that takes `recorded` to the owner's current
141
/// identity in `home`, with the identities between, or none if it is
142
/// current.
143
pub fn rotation(recorded: &Identity, home: &Path) -> Result<Option<spectra_core::event::NewEvent>> {
144
    let pair = KeyPair::load_home(home)?;
145
    if pair.key == recorded.hash() {
146
        return Ok(None);
147
    }
148
    let mut chain = Vec::new();
149
    let mut at = pair.identity.clone();
150
    while let Some(prev) = at.previous {
151
        if prev == recorded.hash() {
152
            break;
153
        }
154
        let file = home.join("keys").join(format!("{}.identity", prev.to_hex()));
155
        at = Identity::decode(
156
            &std::fs::read(&file).with_context(|| format!("{} is not a successor of the recorded owner", pair.identity.name))?,
157
        )
158
        .map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?;
159
        chain.push(hex::encode(at.encode()));
160
        if chain.len() > 1000 {
161
            bail!("the owner's identity chain is too long to follow");
162
        }
163
    }
164
    if at.previous != Some(recorded.hash()) && pair.identity.previous != Some(recorded.hash()) {
165
        bail!("{} in {} is not a successor of the recorded owner {}", pair.identity.name, home.display(), recorded.hash().short(12));
166
    }
167
    let mut payload = identity_payload(&pair.identity);
168
    payload["chain"] = chain.into();
169
    Ok(Some(signed_event(&pair, "human", "identity.rotated", payload)))
170
}
171
172
/// The key pair of the owner identity the ledger already records, from the
173
/// owner's home: what a request to the daemon is signed with, since the
174
/// daemon may not know a newer one yet.
175
pub async fn recorded_owner(ledger: &Ledger, home: &Path) -> Result<KeyPair> {
176
    let p = Principals::load(ledger).await?;
177
    let recorded = p.owner().context("no owner is recorded (spectra init)")?.hash();
178
    let keys = home.join("keys");
179
    KeyPair::load(&keys.join(format!("{}.secret", recorded.to_hex())), &keys.join(format!("{}.identity", recorded.to_hex())))
180
        .with_context(|| format!("the recorded owner's key is not in {}", home.display()))
181
}
182
183
/// `spectra init --owner KEYID` (spec §8.6): a server's instance key and
184
/// ledger, with the owner named but not yet recorded; the owner claims it
185
/// from their own machine, so their secret key never comes here.
186
pub async fn init_for(ctx: &Ctx, owner_key: &str, name: Option<String>) -> Result<i32> {
187
    let key = owner_key.trim().to_ascii_lowercase();
188
    if key.len() != 64 || hex::decode(&key).is_err() {
189
        bail!("{owner_key} is not a KeyId (64 hex digits; the owner's `oxy identity show` prints it)");
190
    }
191
    let data = &ctx.data;
192
    let db = data.join("spectra.db");
193
    if db.exists() {
194
        bail!("{} already holds a Spectra (spectra identity show)", data.display());
195
    }
196
    std::fs::create_dir_all(data)?;
197
    #[cfg(unix)]
198
    {
199
        use std::os::unix::fs::PermissionsExt;
200
        std::fs::set_permissions(data, std::fs::Permissions::from_mode(0o700))?;
201
    }
202
    let name = name.unwrap_or_else(hostname);
203
    let instance = KeyPair::instance(data, &name)?;
204
    let ledger = Ledger::open(&db, Some(instance.clone())).await?;
205
    let mut first = vec![signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity))];
206
    first.extend(spectra_core::conversation::default_channel_events());
207
    ledger.append(first).await?;
208
    ledger.checkpoint().await?;
209
    std::fs::write(
210
        data.join("spectra.toml"),
211
        format!(
212
            "# Spectra's configuration (spec §22.1).\n\n[owner]\nkey = \"{key}\"     # claimed from the owner's machine with `spectra connect`\n\n[server]\n# bind = \"[::]:7350\"   # serve other machines over TLS (spec §8.6)\n"
213
        ),
214
    )?;
215
    println!("{} {}  {}", ui::done("Initialised"), ui::subject("Spectra"), ui::path(data.display()));
216
    println!("{}", ui::kv("owner", format!("{}{}", ui::hash(&key[..12]), ui::dim(" (named; not yet claimed)"))));
217
    println!("{}", ui::kv("instance", format!("{}{}{}", name, ui::sep(), ui::hash(instance.key.short(12)))));
218
    println!();
219
    println!("  {} {}", ui::note(), ui::dim("serve it to other machines: set [server] bind in spectra.toml, then spectra serve"));
220
    println!("  {} {}", ui::note(), ui::dim("then, on the owner's machine:"));
221
    println!("    {}", ui::id("spectra connect https://HOST:7350"));
222
    Ok(0)
223
}
224
225
fn hostname() -> String {
226
    std::fs::read_to_string("/etc/hostname")
227
        .ok()
228
        .map(|h| h.trim().to_string())
229
        .filter(|h| !h.is_empty())
230
        .unwrap_or_else(|| "spectra".into())
231
}
232
233
fn toml_str(s: &str) -> String {
234
    serde_json::to_string(s).unwrap_or_default()
235
}