OXYGENHUB
# 58dfe0e134eb oxygen / crates / oxy-core / src / repo / identity.rs
15.9 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
1
//! Identities, signing, and signature verification (spec §14).
2
3
use super::*;
4
5
/// Outcome of verifying the signatures on a change (spec §14.3, §14.4).
6
#[derive(Clone, Debug, PartialEq, Eq)]
7
pub enum SignatureStatus {
8
    Unsigned,
9
    /// `revoked` marks a signature that verifies but whose key has since
10
    /// been revoked by policy or by a revocation this repository recorded.
11
    Valid {
12
        key: KeyId,
13
        name: String,
14
        email: String,
15
        sealed: bool,
16
        revoked: bool,
17
    },
18
    Invalid(String),
19
}
20
21
/// The outcome of replacing the configured identity (spec §14.2).
22
#[derive(Clone, Debug)]
23
pub struct Rotation {
24
    pub old: KeyId,
25
    pub new: KeyId,
26
    pub identity: Identity,
27
    /// The policy update that moved the old key's grants to the new key,
28
    /// when the repository has a policy naming the old key.
29
    pub policy: Option<PolicyUpdate>,
30
}
31
32
impl Repo {
33
    // ------------------------------------------------------------ identity
34
35
    /// Generate a composite key pair, store its identity object, keep the
36
    /// secret in the key directory, and record the author at `scope`.
37
    pub fn create_identity(
38
        &mut self,
39
        name: &str,
40
        email: &str,
41
        scope: IdentityScope,
42
    ) -> Result<(KeyId, Identity)> {
43
        self.create_identity_with(name, email, scope, None)
44
    }
45
46
    /// `create_identity` with an expiry (milliseconds since the epoch).
47
    pub fn create_identity_with(
48
        &mut self,
49
        name: &str,
50
        email: &str,
51
        scope: IdentityScope,
52
        expires: Option<u64>,
53
    ) -> Result<(KeyId, Identity)> {
54
        let sk = SecretKey::generate();
55
        let mut id = sk.identity(name, email, Hlc::now().wall_ms);
56
        id.expires = expires;
57
        let key = self.install_key(&id, &sk)?;
58
        self.set_author(&id, &key, scope)?;
59
        Ok((key, id))
60
    }
61
62
    /// Store an identity and keep its secret (and a copy of the identity)
63
    /// in the key directory.
64
    fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> {
65
        let key = self.store.put_identity(id)?;
66
        fs::create_dir_all(&self.keys_dir)?;
67
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
68
        write_atomic(&path, &sk.encode(&key))?;
69
        write_atomic(
70
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
71
            &id.encode(),
72
        )?;
73
        #[cfg(unix)]
74
        {
75
            use std::os::unix::fs::PermissionsExt;
76
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
77
        }
78
        Ok(key)
79
    }
80
81
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
82
        match scope {
83
            IdentityScope::Repo => {
84
                self.config.set("author.name", &id.name)?;
85
                self.config.set("author.email", &id.email)?;
86
                self.config.set("author.key", &key.to_hex())?;
87
                self.save_config()?;
88
            }
89
            IdentityScope::User => {
90
                Config::set_user(&self.user_config, "author.name", &id.name)?;
91
                Config::set_user(&self.user_config, "author.email", &id.email)?;
92
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
93
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
94
            }
95
        }
96
        Ok(())
97
    }
98
99
    /// The scope that holds the configured author key.
100
    fn author_scope(&self) -> IdentityScope {
101
        if self.config.repo_layer().contains_key("author.key") {
102
            IdentityScope::Repo
103
        } else {
104
            IdentityScope::User
105
        }
106
    }
107
108
    /// Replace the configured identity by `new` signed with `sk`: store it,
109
    /// record a `rotate` attestation signed by the old key, move the old
110
    /// key's policy grants to the new key, and switch the author config.
111
    fn replace_identity(
112
        &mut self,
113
        new: Identity,
114
        sk: SecretKey,
115
        command: &str,
116
    ) -> Result<Rotation> {
117
        let Some((old, old_sk)) = self.secret_key()? else {
118
            return fail("no secret key: run `oxy identity create` first");
119
        };
120
        if new.previous != Some(old) {
121
            return fail("the successor identity must name the current key as previous");
122
        }
123
        let new_key = self.install_key(&new, &sk)?;
124
        let attest = Attest {
125
            repo: self.id()?,
126
            hlc: Hlc::now(),
127
            body: AttestBody::Rotate { new: new_key },
128
        };
129
        let r = self.store.put_attest(&attest)?;
130
        self.store
131
            .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?;
132
        let policy = match self.current_policy()? {
133
            Some((_, sp)) if sp.policy.mentions(&old) => {
134
                let mut p = self.next_policy()?;
135
                p.substitute_key(&old, new.clone());
136
                Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?)
137
            }
138
            _ => None,
139
        };
140
        self.set_author(&new, &new_key, self.author_scope())?;
141
        Ok(Rotation {
142
            old,
143
            new: new_key,
144
            identity: new,
145
            policy,
146
        })
147
    }
148
149
    /// Rotate to a fresh key pair; the new identity names the old one as
150
    /// `previous` and keeps its name, email, delegates, and expiry.
151
    pub fn rotate_identity(&mut self) -> Result<Rotation> {
152
        let Some((old, _)) = self.secret_key()? else {
153
            return fail("no secret key: run `oxy identity create` first");
154
        };
155
        let cur = self.identity(&old)?;
156
        let sk = SecretKey::generate();
157
        let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms);
158
        id.previous = Some(old);
159
        id.delegates = cur.delegates.clone();
160
        id.expires = cur.expires;
161
        self.replace_identity(id, sk, "oxy identity rotate")
162
    }
163
164
    /// Re-issue the identity with the same keys and a new expiry.
165
    pub fn renew_identity(&mut self, expires: Option<u64>) -> Result<Rotation> {
166
        let Some((old, sk)) = self.secret_key()? else {
167
            return fail("no secret key: run `oxy identity create` first");
168
        };
169
        let cur = self.identity(&old)?;
170
        let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms);
171
        self.replace_identity(id, sk, "oxy identity renew")
172
    }
173
174
    /// Let `delegate` sign or seal on this identity's behalf. Delegates are
175
    /// part of the identity object, so this re-issues it with the same keys.
176
    pub fn delegate_add(&mut self, delegate: Identity) -> Result<Rotation> {
177
        let Some((old, sk)) = self.secret_key()? else {
178
            return fail("no secret key: run `oxy identity create` first");
179
        };
180
        let dk = self.store.put_identity(&delegate)?;
181
        if dk == old {
182
            return fail("an identity cannot delegate to itself");
183
        }
184
        let cur = self.identity(&old)?;
185
        if cur.delegates.contains(&dk) {
186
            return fail(format!("{} is already a delegate", dk.short(12)));
187
        }
188
        let mut delegates = cur.delegates.clone();
189
        delegates.push(dk);
190
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
191
        self.replace_identity(
192
            id,
193
            sk,
194
            &format!("oxy identity delegate add {}", dk.short(12)),
195
        )
196
    }
197
198
    /// Withdraw a delegation; re-issues the identity with the same keys.
199
    pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result<Rotation> {
200
        let Some((old, sk)) = self.secret_key()? else {
201
            return fail("no secret key: run `oxy identity create` first");
202
        };
203
        let cur = self.identity(&old)?;
204
        if !cur.delegates.contains(delegate) {
205
            return fail(format!("{} is not a delegate", delegate.short(12)));
206
        }
207
        let delegates = cur
208
            .delegates
209
            .iter()
210
            .copied()
211
            .filter(|d| d != delegate)
212
            .collect();
213
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
214
        self.replace_identity(
215
            id,
216
            sk,
217
            &format!("oxy identity delegate remove {}", delegate.short(12)),
218
        )
219
    }
220
221
    /// Revoke `key` (your own, or any key when you hold a policy root):
222
    /// record a signed `revoke` attestation and a local marker, and drop
223
    /// the key from the policy where it has one.
224
    pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result<Option<PolicyUpdate>> {
225
        let Some((own, sk)) = self.secret_key()? else {
226
            return fail("no secret key: run `oxy identity create` first");
227
        };
228
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
229
        let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own));
230
        if *key != own && !is_root {
231
            return fail("only the key's holder or a policy root can revoke it");
232
        }
233
        let attest = Attest {
234
            repo: self.id()?,
235
            hlc: Hlc::now(),
236
            body: AttestBody::Revoke {
237
                key: *key,
238
                reason: reason.into(),
239
            },
240
        };
241
        let r = self.store.put_attest(&attest)?;
242
        self.store
243
            .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?;
244
        let dir = self.oxy.join("revoked");
245
        fs::create_dir_all(&dir)?;
246
        write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?;
247
        match policy {
248
            Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)),
249
            _ => Ok(None),
250
        }
251
    }
252
253
    /// Whether `key` is revoked by the policy or by a recorded revocation.
254
    pub fn is_revoked(&self, key: &KeyId) -> Result<bool> {
255
        if self.oxy.join("revoked").join(key.to_hex()).exists() {
256
            return Ok(true);
257
        }
258
        Ok(self
259
            .current_policy()?
260
            .is_some_and(|(_, sp)| sp.policy.is_revoked(key)))
261
    }
262
263
    /// The secret key for `author.key`, if configured and present on disk.
264
    /// The identity object is kept beside the secret so a repository that has
265
    /// never seen it (a fresh clone) can store it when it first signs.
266
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
267
        let Some(key) = self.config.author_key else {
268
            return Ok(None);
269
        };
270
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
271
        match fs::read(&path) {
272
            Ok(b) => {
273
                let (k, sk) = SecretKey::decode(&b)?;
274
                if k != key {
275
                    return fail(format!(
276
                        "{} holds a different key than its name",
277
                        path.display()
278
                    ));
279
                }
280
                if !self.store.has(&key) {
281
                    let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
282
                    if let Ok(bytes) = fs::read(&id_path) {
283
                        let id = Identity::decode(&bytes)?;
284
                        if id.hash() == key {
285
                            self.store.put_identity(&id)?;
286
                        }
287
                    }
288
                }
289
                Ok(Some((k, sk)))
290
            }
291
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
292
            Err(e) => Err(e.into()),
293
        }
294
    }
295
296
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
297
        Ok(self.store.get_identity(key)?)
298
    }
299
300
    /// Sign a stored change with the configured secret key.
301
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
302
        let Some((key, sk)) = self.secret_key()? else {
303
            return fail("no secret key: run `oxy identity create` first");
304
        };
305
        let sig = sk.sign(Domain::Change, &key, hash);
306
        self.store.put_signature(hash, &sig)?;
307
        Ok(sig)
308
    }
309
310
    /// Check the signatures on a change against the author-or-delegate rule.
311
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
312
        let change = self.store.get_change(hash)?;
313
        let sigs = self.store.signatures(hash)?;
314
        if sigs.is_empty() {
315
            return Ok(SignatureStatus::Unsigned);
316
        }
317
        let mut last_err = String::new();
318
        for sig in &sigs {
319
            match self.check_signer(&change, sig, Domain::Change, hash) {
320
                Ok(id) => {
321
                    return Ok(SignatureStatus::Valid {
322
                        key: sig.key,
323
                        name: id.name,
324
                        email: id.email,
325
                        sealed: false,
326
                        revoked: self.is_revoked(&sig.key)?,
327
                    })
328
                }
329
                Err(e) => last_err = e,
330
            }
331
        }
332
        Ok(SignatureStatus::Invalid(last_err))
333
    }
334
335
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
336
    fn check_signer(
337
        &self,
338
        change: &Change,
339
        sig: &Signature,
340
        domain: Domain,
341
        target: &ObjectRef,
342
    ) -> std::result::Result<Identity, String> {
343
        let id = self
344
            .store
345
            .get_identity(&sig.key)
346
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
347
        let authorised = sig.key == change.author
348
            || self
349
                .store
350
                .get_identity(&change.author)
351
                .map(|a| a.delegates.contains(&sig.key))
352
                .unwrap_or(false);
353
        if !authorised {
354
            return Err(format!(
355
                "key {} is neither the author nor a delegate",
356
                sig.key.short(12)
357
            ));
358
        }
359
        if id.is_expired_at(change.hlc.wall_ms) {
360
            return Err(format!(
361
                "key {} had expired when the change was made",
362
                sig.key.short(12)
363
            ));
364
        }
365
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
366
        Ok(id)
367
    }
368
369
    /// Like `verify_change`, but a change with no valid individual signature
370
    /// is also authenticated by a valid seal covering it (spec §14.4).
371
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
372
        let direct = self.verify_change(hash)?;
373
        if matches!(direct, SignatureStatus::Valid { .. }) {
374
            return Ok(direct);
375
        }
376
        let change = self.store.get_change(hash)?;
377
        let mut last_err = match &direct {
378
            SignatureStatus::Invalid(e) => e.clone(),
379
            _ => String::new(),
380
        };
381
        for seal_ref in self.store.seals_for(hash)? {
382
            let attest = self.store.get_attest(&seal_ref)?;
383
            let AttestBody::Seal { hashes } = &attest.body else {
384
                continue;
385
            };
386
            if !hashes.contains(hash) {
387
                continue;
388
            }
389
            for sig in self.store.signatures(&seal_ref)? {
390
                match self.check_signer(&change, &sig, Domain::Attest, &seal_ref) {
391
                    Ok(id) => {
392
                        return Ok(SignatureStatus::Valid {
393
                            key: sig.key,
394
                            name: id.name,
395
                            email: id.email,
396
                            sealed: true,
397
                            revoked: self.is_revoked(&sig.key)?,
398
                        })
399
                    }
400
                    Err(e) => last_err = e,
401
                }
402
            }
403
        }
404
        if last_err.is_empty() {
405
            Ok(SignatureStatus::Unsigned)
406
        } else {
407
            Ok(SignatureStatus::Invalid(last_err))
408
        }
409
    }
410
411
    /// Store and sign an attestation with the configured key.
412
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
413
        let Some((key, sk)) = self.secret_key()? else {
414
            return fail("no secret key: run `oxy identity create` first");
415
        };
416
        let r = self.store.put_attest(attest)?;
417
        let sig = sk.sign(Domain::Attest, &key, &r);
418
        self.store.put_signature(&r, &sig)?;
419
        if let AttestBody::Seal { hashes } = &attest.body {
420
            for h in hashes {
421
                self.store.index_seal(h, &r)?;
422
            }
423
        }
424
        Ok(SignedAttest {
425
            attest: attest.clone(),
426
            sigs: vec![sig],
427
        })
428
    }
429
}