OXYGENHUB
# 01320eefd505 spectra / crates / spectra-core / src / keys.rs
7.5 KiB · Rust · last changed The ledger: hash-chained events in the frozen envelope, signed checkpoints, admin verify, check and rebuild (#3) 2 days ago source blame history raw
1
//! Keys and identities on disk, laid out exactly as `oxy` lays them out
2
//! (spec §8.1, §21.3): an `OXY_HOME` holds `keys/<KEYID>.secret` (private),
3
//! `keys/<KEYID>.identity` and `config.toml` naming the key as `author.key`.
4
//! Spectra writes them with `oxy-core`'s own functions, so `oxy` reads what
5
//! Spectra made and the other way round.
6
//!
7
//! The instance key (spec §9.5) is kept in the data directory instead, at
8
//! `keys/instance.secret` and `keys/instance.identity`.
9
10
use anyhow::{bail, Context, Result};
11
use oxy_core::durable::{write_atomic, write_atomic_private};
12
use oxy_core::hash::KeyId;
13
use oxy_core::identity::{Identity, SecretKey, Signature};
14
use std::fs;
15
use std::path::{Path, PathBuf};
16
17
/// A key pair with its identity: the instance, an agent, or the owner.
18
#[derive(Clone, Debug)]
19
pub struct KeyPair {
20
    pub key: KeyId,
21
    pub identity: Identity,
22
    secret: SecretKey,
23
}
24
25
impl KeyPair {
26
    /// A fresh key pair named `name`, made now.
27
    pub fn generate(name: &str, email: &str) -> KeyPair {
28
        let secret = SecretKey::generate();
29
        let identity = secret.identity(name, email, crate::ids::now_ms());
30
        KeyPair { key: identity.hash(), identity, secret }
31
    }
32
33
    /// Sign `message` (a Spectra domain-prefixed byte string, at least 16
34
    /// bytes) through Oxygen's challenge signing: the target is
35
    /// `BLAKE3("oxy1 challenge " || message)`, so a Spectra signature can
36
    /// never be taken for a change, an attestation or a policy.
37
    pub fn sign(&self, message: &[u8]) -> Signature {
38
        self.secret.sign_challenge(&self.key, message).expect("Spectra messages are longer than 16 bytes")
39
    }
40
41
    /// Make a key pair in an `OXY_HOME` laid out as `oxy identity create`
42
    /// lays one out, and name it the home's author.
43
    pub fn create_home(home: &Path, name: &str, email: &str) -> Result<KeyPair> {
44
        let pair = KeyPair::generate(name, email);
45
        let keys = home.join("keys");
46
        fs::create_dir_all(&keys).with_context(|| format!("creating {}", keys.display()))?;
47
        #[cfg(unix)]
48
        {
49
            use std::os::unix::fs::PermissionsExt;
50
            fs::set_permissions(home, fs::Permissions::from_mode(0o700))?;
51
        }
52
        write_atomic_private(&keys.join(format!("{}.secret", pair.key.to_hex())), &pair.secret.encode(&pair.key))?;
53
        write_atomic(&keys.join(format!("{}.identity", pair.key.to_hex())), &pair.identity.encode())?;
54
        let config = home.join("config.toml");
55
        oxy_core::repo::Config::set_user(&config, "author.name", name)?;
56
        oxy_core::repo::Config::set_user(&config, "author.email", email)?;
57
        oxy_core::repo::Config::set_user(&config, "author.key", &pair.key.to_hex())?;
58
        Ok(pair)
59
    }
60
61
    /// The key pair an `OXY_HOME` signs with: `author.key` from its
62
    /// `config.toml`, else its only secret key.
63
    pub fn load_home(home: &Path) -> Result<KeyPair> {
64
        let keys = home.join("keys");
65
        let key = match author_key(home)? {
66
            Some(k) => k,
67
            None => {
68
                let secrets: Vec<PathBuf> = fs::read_dir(&keys)
69
                    .with_context(|| format!("reading {}", keys.display()))?
70
                    .filter_map(|e| e.ok().map(|e| e.path()))
71
                    .filter(|p| p.extension().is_some_and(|x| x == "secret"))
72
                    .collect();
73
                match secrets.as_slice() {
74
                    [one] => KeyId::from_hex(one.file_stem().and_then(|s| s.to_str()).unwrap_or(""))
75
                        .context("a secret key file is not named by its key")?,
76
                    [] => bail!("{} holds no secret key: an agent home is made by `spectra agent add`", home.display()),
77
                    _ => bail!("{} holds several keys and its config.toml names none (author.key)", home.display()),
78
                }
79
            }
80
        };
81
        KeyPair::load(&keys.join(format!("{}.secret", key.to_hex())), &keys.join(format!("{}.identity", key.to_hex())))
82
    }
83
84
    /// Read a secret and its identity, checking that they belong together.
85
    pub fn load(secret: &Path, identity: &Path) -> Result<KeyPair> {
86
        let (key, secret_key) = SecretKey::decode(&fs::read(secret).with_context(|| format!("reading {}", secret.display()))?)
87
            .map_err(|e| anyhow::anyhow!("{}: {e}", secret.display()))?;
88
        let identity = Identity::decode(&fs::read(identity).with_context(|| format!("reading {}", identity.display()))?)
89
            .map_err(|e| anyhow::anyhow!("{}: {e}", identity.display()))?;
90
        if identity.hash() != key {
91
            bail!("{} is not the identity of {}", identity.name, secret.display());
92
        }
93
        if secret_key.identity(&identity.name, &identity.email, identity.created).ed25519_pk != identity.ed25519_pk {
94
            bail!("the secret key in {} does not match its identity", secret.display());
95
        }
96
        Ok(KeyPair { key, identity, secret: secret_key })
97
    }
98
99
    /// The data directory's instance key, made on first use (spec §9.5).
100
    pub fn instance(data: &Path, name: &str) -> Result<KeyPair> {
101
        let keys = data.join("keys");
102
        let (secret, identity) = (keys.join("instance.secret"), keys.join("instance.identity"));
103
        if secret.exists() {
104
            return KeyPair::load(&secret, &identity);
105
        }
106
        fs::create_dir_all(&keys)?;
107
        let pair = KeyPair::generate(name, "");
108
        write_atomic_private(&secret, &pair.secret.encode(&pair.key))?;
109
        write_atomic(&identity, &pair.identity.encode())?;
110
        Ok(pair)
111
    }
112
}
113
114
/// The identity an `OXY_HOME` names as its author (`oxy identity export`
115
/// without the CLI): for reading the owner's identity at `spectra init`.
116
pub fn home_identity(home: &Path) -> Result<Identity> {
117
    let key = author_key(home)?.with_context(|| format!("{} names no identity (author.key in config.toml)", home.display()))?;
118
    let path = home.join("keys").join(format!("{}.identity", key.to_hex()));
119
    Identity::decode(&fs::read(&path).with_context(|| format!("reading {}", path.display()))?)
120
        .map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))
121
}
122
123
fn author_key(home: &Path) -> Result<Option<KeyId>> {
124
    let config = home.join("config.toml");
125
    let Ok(text) = fs::read_to_string(&config) else { return Ok(None) };
126
    let table: toml::Table = text.parse().with_context(|| format!("reading {}", config.display()))?;
127
    let found = table.get("author").and_then(|a| a.get("key")).or_else(|| table.get("author.key")).and_then(|v| v.as_str());
128
    Ok(match found {
129
        Some(hex) => Some(KeyId::from_hex(hex).with_context(|| format!("{}: author.key is not a key", config.display()))?),
130
        None => None,
131
    })
132
}
133
134
#[cfg(test)]
135
mod tests {
136
    use super::*;
137
138
    #[test]
139
    fn a_home_made_here_reads_back_and_signs_verifiably() {
140
        let dir = tempfile::tempdir().unwrap();
141
        let made = KeyPair::create_home(dir.path(), "claude-oxygen", "").unwrap();
142
        let read = KeyPair::load_home(dir.path()).unwrap();
143
        assert_eq!(made.key, read.key);
144
        assert_eq!(home_identity(dir.path()).unwrap().hash(), made.key);
145
        let msg = b"spectra1 test message of some length";
146
        let sig = read.sign(msg);
147
        oxy_core::identity::verify_challenge(&made.identity, &sig, msg).unwrap();
148
        assert!(oxy_core::identity::verify_challenge(&made.identity, &sig, b"spectra1 another message entirely").is_err());
149
    }
150
151
    #[test]
152
    fn the_instance_key_is_made_once() {
153
        let dir = tempfile::tempdir().unwrap();
154
        let a = KeyPair::instance(dir.path(), "laptop").unwrap();
155
        let b = KeyPair::instance(dir.path(), "laptop").unwrap();
156
        assert_eq!(a.key, b.key);
157
    }
158
}