Skip to main content

mur_common/identity/
human.rs

1//! Where the human owner's identity lives (at-mention phase 2, D-1, D-8).
2//!
3//! Split in two on purpose, like an agent's:
4//!
5//! - `<mur_home>/identity/` holds the PUBLIC half (`identity.pub`,
6//!   `rotations.jsonl`). Every agent may read it — verifying a human-signed
7//!   event needs it — and no agent may write it: the rotation chain there
8//!   decides which key speaks for the human.
9//! - `<mur_home>/keys/.human/` holds the private key. It sits under `keys/`,
10//!   which the sandbox already denies for read and write as a subtree, and
11//!   `.human` can never collide with an agent because `.` is not a valid
12//!   agent-name character (`agent_name::validate_agent_name`).
13
14use std::fs;
15use std::io;
16use std::path::{Path, PathBuf};
17
18use super::{
19    ChainError, ChainOptions, ChainOutcome, RotationAttestation, decode_pubkey, verify_chain,
20};
21
22/// Directory under `<mur_home>` holding the human's public key material.
23pub const HUMAN_IDENTITY_DIR: &str = "identity";
24
25/// Directory under `<mur_home>/keys` holding the human's private key.
26pub const HUMAN_KEY_DIR: &str = ".human";
27
28/// Directory under `<mur_home>` that holds every private signing key.
29pub const KEYS_DIR: &str = "keys";
30
31/// `<mur_home>/identity` — public, agent-readable, never agent-writable.
32pub fn human_identity_dir(mur_home: &Path) -> PathBuf {
33    mur_home.join(HUMAN_IDENTITY_DIR)
34}
35
36/// `<mur_home>/keys/.human` — private, denied to every agent.
37pub fn human_key_dir(mur_home: &Path) -> PathBuf {
38    mur_home.join(KEYS_DIR).join(HUMAN_KEY_DIR)
39}
40
41/// File name of the public key, inside [`human_identity_dir`].
42pub const HUMAN_PUBKEY_FILE: &str = "identity.pub";
43
44/// File name of the rotation chain, inside [`human_identity_dir`].
45pub const HUMAN_ROTATIONS_FILE: &str = "rotations.jsonl";
46
47/// File name of the private key, inside [`human_key_dir`].
48pub const HUMAN_PRIVATE_KEY_FILE: &str = "identity.key";
49
50/// Why the human's public identity could not be read.
51///
52/// `NotEnrolled` and `Unreadable` are separate on purpose (#1010): a sandbox
53/// deny must never look like "no human yet", or a caller that enrolls on
54/// absence would mint a second key over a perfectly good one.
55#[derive(Debug, thiserror::Error)]
56pub enum HumanIdentityError {
57    #[error("no human identity enrolled ({path} is absent)")]
58    NotEnrolled { path: PathBuf },
59    #[error("human identity at {path} exists but is not readable: {source}")]
60    Unreadable {
61        path: PathBuf,
62        #[source]
63        source: io::Error,
64    },
65    #[error("human identity at {path} is invalid: {detail}")]
66    Invalid { path: PathBuf, detail: String },
67}
68
69/// The human's rotation chain, already checked by [`verify_chain`] and
70/// matched against `identity.pub`. Holding one means both checks passed —
71/// there is no constructor that skips them.
72#[derive(Debug, Clone)]
73pub struct RotationChain {
74    entries: Vec<RotationAttestation>,
75    head: ChainOutcome,
76    head_pubkey: [u8; 32],
77}
78
79impl RotationChain {
80    /// Every attestation, bootstrap first.
81    pub fn entries(&self) -> &[RotationAttestation] {
82        &self.entries
83    }
84
85    /// The current key. The only key that carries authority (D-9).
86    pub fn head_pubkey(&self) -> [u8; 32] {
87        self.head_pubkey
88    }
89
90    pub fn head_key_version(&self) -> u32 {
91        self.head.head_key_version
92    }
93}
94
95/// `<mur_home>/identity/identity.pub`
96pub fn human_pubkey_path(mur_home: &Path) -> PathBuf {
97    human_identity_dir(mur_home).join(HUMAN_PUBKEY_FILE)
98}
99
100/// `<mur_home>/identity/rotations.jsonl`
101pub fn human_rotations_path(mur_home: &Path) -> PathBuf {
102    human_identity_dir(mur_home).join(HUMAN_ROTATIONS_FILE)
103}
104
105/// `<mur_home>/keys/.human/identity.key`
106pub fn human_private_key_path(mur_home: &Path) -> PathBuf {
107    human_key_dir(mur_home).join(HUMAN_PRIVATE_KEY_FILE)
108}
109
110/// Read a file, keeping "absent" and "may not read" apart. `fs::metadata`
111/// first because `Path::exists` folds every stat failure into `false`.
112fn read_public(path: &Path) -> Result<String, HumanIdentityError> {
113    let unreadable = |source| HumanIdentityError::Unreadable {
114        path: path.to_path_buf(),
115        source,
116    };
117    match fs::metadata(path) {
118        Ok(_) => {}
119        Err(e) if e.kind() == io::ErrorKind::NotFound => {
120            return Err(HumanIdentityError::NotEnrolled {
121                path: path.to_path_buf(),
122            });
123        }
124        Err(e) => return Err(unreadable(e)),
125    }
126    fs::read_to_string(path).map_err(unreadable)
127}
128
129fn invalid(path: &Path, detail: impl ToString) -> HumanIdentityError {
130    HumanIdentityError::Invalid {
131        path: path.to_path_buf(),
132        detail: detail.to_string(),
133    }
134}
135
136/// The human's current public key, from `identity/identity.pub`.
137///
138/// Reads `identity/` only — never `keys/`, which every agent is denied. This
139/// is what lets a sandboxed verifier check a human signature.
140pub fn load_pubkey(mur_home: &Path) -> Result<[u8; 32], HumanIdentityError> {
141    let path = human_pubkey_path(mur_home);
142    let text = read_public(&path)?;
143    decode_pubkey(text.trim()).map_err(|e| invalid(&path, e))
144}
145
146/// The human's rotation chain, verified, with its head matched against
147/// `identity.pub`.
148///
149/// Fails closed: a line that does not parse, a chain that does not verify, or
150/// a head that disagrees with `identity.pub` is `Invalid` — never "skip the
151/// bad line" (that is how a planted line would get through) and never "fall
152/// back to identity.pub" (that is the single-host shortcut D-10 rules out).
153pub fn rotation_chain(mur_home: &Path) -> Result<RotationChain, HumanIdentityError> {
154    let path = human_rotations_path(mur_home);
155    let text = read_public(&path)?;
156    let entries = text
157        .lines()
158        .filter(|l| !l.trim().is_empty())
159        .map(serde_json::from_str::<RotationAttestation>)
160        .collect::<Result<Vec<_>, _>>()
161        .map_err(|e| invalid(&path, e))?;
162    let head = verify_chain(
163        &entries,
164        ChainOptions {
165            allow_emergency: false,
166        },
167    )
168    .map_err(|e: ChainError| invalid(&path, e))?;
169    let head_pubkey = decode_pubkey(&head.head_pubkey).map_err(|e| invalid(&path, e))?;
170    let current = load_pubkey(mur_home)?;
171    if current != head_pubkey {
172        return Err(invalid(
173            &path,
174            format!(
175                "chain head (key_version {}) is not the key in {HUMAN_PUBKEY_FILE}",
176                head.head_key_version
177            ),
178        ));
179    }
180    Ok(RotationChain {
181        entries,
182        head,
183        head_pubkey,
184    })
185}
186
187#[cfg(test)]
188#[path = "human_tests.rs"]
189mod human_tests;
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn the_key_dir_name_is_not_a_valid_agent_name() {
197        assert!(crate::agent_name::validate_agent_name(HUMAN_KEY_DIR).is_err());
198    }
199
200    #[test]
201    fn the_two_halves_never_share_a_directory() {
202        let home = Path::new("/m");
203        let public = human_identity_dir(home);
204        let private = human_key_dir(home);
205        assert!(!private.starts_with(&public) && !public.starts_with(&private));
206    }
207}