OXYGENHUB

Coverage / src/cli/identity.rs 54.8%

86 of 157 lines run, 14 of 48 functions · run #9 on main · run missed

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.
1538×
pub fn owner_home(ctx: &Ctx, flag: Option<PathBuf>) -> PathBuf {
1638×
    flag.or_else(|| ctx.config_owner_home()).unwrap_or_else(oxy_core::repo::default_home)
1738×
}
18
1913×
pub async fn init(ctx: &Ctx, owner_home_flag: Option<PathBuf>, name: Option<String>) -> Result<i32> {
2013×
    let data = &ctx.data;
2113×
    let db = data.join("spectra.db");
2213×
    if db.exists() {
231×
        bail!("{} already holds a Spectra (spectra identity show)", data.display());
2412×
    }
2512×
    let home = owner_home(ctx, owner_home_flag);
2612×
    let owner = KeyPair::load_home(&home).with_context(|| {
271×
        format!("the owner signs with their own identity: none usable in {} (oxy identity create, or --owner-home)", home.display())
281×
    })?;
2911×
    std::fs::create_dir_all(data)?;
30
    #[cfg(unix)]
31
    {
32
        use std::os::unix::fs::PermissionsExt;
3311×
        std::fs::set_permissions(data, std::fs::Permissions::from_mode(0o700))?;
34
    }
3511×
    let name = name.unwrap_or_else(hostname);
3611×
    let instance = KeyPair::instance(data, &name)?;
3711×
    let ledger = Ledger::open(&db, Some(instance.clone())).await?;
3811×
    let mut first = vec![
3911×
        signed_event(&owner, "human", "identity.owner", identity_payload(&owner.identity)),
4011×
        signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity)),
41
    ];
4211×
    first.extend(spectra_core::conversation::default_channel_events());
4311×
    ledger.append(first).await?;
4411×
    ledger.checkpoint().await?;
4511×
    let home_s = home.display().to_string();
4611×
    std::fs::write(
4711×
        data.join("spectra.toml"),
4811×
        format!("# Spectra's configuration (spec §22.1).\n\n[owner]\nkey = \"{}\"\nhome = {}\n", owner.key.to_hex(), toml_str(&home_s)),
490×
    )?;
5011×
    println!("{} {}  {}", ui::done("Initialised"), ui::subject("Spectra"), ui::path(data.display()));
5111×
    println!("{}", ui::kv("owner", format!("{}{}{}", ui::author(&owner.identity.name), ui::sep(), ui::hash(owner.key.short(12)))));
5211×
    println!("{}", ui::kv("instance", format!("{}{}{}", name, ui::sep(), ui::hash(instance.key.short(12)))));
5311×
    println!("{}", ui::kv("ledger", format!("{}{}", ui::path(db.display()), ui::dim(" (verified with spectra admin verify)"))));
5411×
    println!();
5511×
    println!("  {} {}", ui::note(), ui::dim("so that checkpoints are verifiably from your machine, delegate to the instance key:"));
5611×
    println!(
57
        "    {}",
5811×
        ui::id(format!("oxy identity delegate add {} --scope changes", data.join("keys").join("instance.identity").display()))
59
    );
6011×
    println!(
61
        "  {} {} {}",
6211×
        ui::note(),
6311×
        ui::dim("then add agents with"),
6411×
        ui::id("spectra agent add NAME --kind KIND --project PROJECT --home DIR")
65
    );
6611×
    Ok(0)
6713×
}
68
690×
pub async fn show(ctx: &Ctx, json: bool) -> Result<i32> {
700×
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
710×
    let p = Principals::load(&ledger).await?;
720×
    let owner = p.owner().context("no owner is recorded")?;
730×
    let instance = p.instance();
740×
    let delegated =
750×
        instance.is_some_and(|i| owner.delegates_to(&i.hash(), spectra_core::principals::DELEGATION_SCOPE, spectra_core::ids::now_ms()));
760×
    if json {
770×
        println!(
78
            "{}",
790×
            serde_json::json!({
800×
                "owner": { "name": owner.name, "key": owner.hash().to_hex() },
810×
                "instance": instance.map(|i| serde_json::json!({ "name": i.name, "key": i.hash().to_hex(), "delegated": delegated })),
82
            })
83
        );
840×
        return Ok(0);
850×
    }
860×
    println!("{}", ui::section("Owner"));
870×
    println!("{}", ui::kv("name", ui::author(format!("{} <{}>", owner.name, owner.email))));
880×
    println!("{}", ui::kv("key", ui::hash(owner.hash().to_hex())));
890×
    println!("{}", ui::kv("delegates", owner.delegates.len()));
900×
    if let Some(i) = instance {
910×
        println!("{}", ui::section("Instance"));
920×
        println!("{}", ui::kv("name", &i.name));
930×
        println!("{}", ui::kv("key", ui::hash(i.hash().to_hex())));
940×
        if delegated {
950×
            println!("{}", ui::kv("status", ui::ok("delegated by the owner: checkpoints are verifiably yours")));
960×
        } else {
970×
            println!("{}", ui::kv("status", ui::warn("not delegated by the owner yet")));
980×
            println!(
990×
                "  {} {}",
1000×
                ui::note(),
1010×
                ui::id(format!("oxy identity delegate add {} --scope changes", ctx.data.join("keys").join("instance.identity").display()))
1020×
            );
1030×
        }
1040×
    }
1050×
    Ok(0)
1060×
}
107
108
/// Record the owner's current identity when it has moved on (a delegation
109
/// added or removed): `spectra identity refresh`.
1100×
pub async fn refresh(ctx: &Ctx, owner_home_flag: Option<PathBuf>) -> Result<i32> {
1110×
    let home = owner_home(ctx, owner_home_flag);
1120×
    let w = ctx.owner_writer(&home).await?;
1130×
    let rotated = refresh_event(w.ledger(), &home).await?;
1140×
    let outcome = rotated.as_ref().map(|_| KeyPair::load_home(&home).map(|p| p.identity)).transpose()?;
1150×
    if let Some(e) = rotated {
1160×
        w.append(vec![e]).await?;
1170×
    }
1180×
    match outcome {
1190×
        Some(id) => println!(
120
            "{} {}{}{}",
1210×
            ui::done("Recorded"),
1220×
            ui::subject("the owner's current identity"),
1230×
            ui::sep(),
1240×
            ui::hash(id.hash().short(12))
125
        ),
1260×
        None => println!("{} {}", ui::done("Current"), ui::subject("the owner's identity has not moved")),
127
    }
1280×
    Ok(0)
1290×
}
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.
13423×
pub async fn refresh_event(ledger: &Ledger, home: &Path) -> Result<Option<spectra_core::event::NewEvent>> {
13523×
    let p = Principals::load(ledger).await?;
13623×
    let recorded = p.owner().context("no owner is recorded (spectra init)")?.clone();
13723×
    let pair = KeyPair::load_home(home)?;
13823×
    if pair.key == recorded.hash() {
13914×
        return Ok(None);
1409×
    }
1419×
    let mut chain = Vec::new();
1429×
    let mut at = pair.identity.clone();
1439×
    while let Some(prev) = at.previous {
1449×
        if prev == recorded.hash() {
1459×
            break;
1460×
        }
1470×
        let file = home.join("keys").join(format!("{}.identity", prev.to_hex()));
1480×
        at = Identity::decode(
1490×
            &std::fs::read(&file).with_context(|| format!("{} is not a successor of the recorded owner", pair.identity.name))?,
150
        )
1510×
        .map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?;
1520×
        chain.push(hex::encode(at.encode()));
1530×
        if chain.len() > 1000 {
1540×
            bail!("the owner's identity chain is too long to follow");
1550×
        }
156
    }
1579×
    if at.previous != Some(recorded.hash()) && pair.identity.previous != Some(recorded.hash()) {
1580×
        bail!("{} in {} is not a successor of the recorded owner {}", pair.identity.name, home.display(), recorded.hash().short(12));
1599×
    }
1609×
    let mut payload = identity_payload(&pair.identity);
1619×
    payload["chain"] = chain.into();
1629×
    Ok(Some(signed_event(&pair, "human", "identity.rotated", payload)))
16323×
}
164
165
/// The key pair of the owner identity the ledger already records, from the
166
/// owner's home: what a request to the daemon is signed with, since the
167
/// daemon may not know a newer one yet.
1682×
pub async fn recorded_owner(ledger: &Ledger, home: &Path) -> Result<KeyPair> {
1692×
    let p = Principals::load(ledger).await?;
1702×
    let recorded = p.owner().context("no owner is recorded (spectra init)")?.hash();
1712×
    let keys = home.join("keys");
1722×
    KeyPair::load(&keys.join(format!("{}.secret", recorded.to_hex())), &keys.join(format!("{}.identity", recorded.to_hex())))
1732×
        .with_context(|| format!("the recorded owner's key is not in {}", home.display()))
1742×
}
175
17610×
fn hostname() -> String {
17710×
    std::fs::read_to_string("/etc/hostname")
17810×
        .ok()
17910×
        .map(|h| h.trim().to_string())
18010×
        .filter(|h| !h.is_empty())
18110×
        .unwrap_or_else(|| "spectra".into())
18210×
}
183
18411×
fn toml_str(s: &str) -> String {
18511×
    serde_json::to_string(s).unwrap_or_default()
18611×
}