OXYGENHUB
# c3d2ef6104c2 oxygen / crates / oxy-core / src / repo / identity.rs
20.3 KiB · Rust · last changed Log from the state index, signature marks without reading changes (refs #41) 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
    /// An identity: from this repository's store, or else from the key
297
    /// directory, where `oxy identity create` keeps the user's own (a new
298
    /// repository has not stored it yet). The file must hash to `key`.
299
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
300
        match self.store.get_identity(key) {
301
            Ok(id) => Ok(id),
302
            Err(e) => {
303
                let path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
304
                match fs::read(&path) {
305
                    Ok(bytes) => {
306
                        let id = Identity::decode(&bytes)?;
307
                        if id.hash() != *key {
308
                            return fail(format!(
309
                                "{} does not hold identity {}",
310
                                path.display(),
311
                                key.short(12)
312
                            ));
313
                        }
314
                        Ok(id)
315
                    }
316
                    Err(_) => Err(e.into()),
317
                }
318
            }
319
        }
320
    }
321
322
    /// Sign a stored change with the configured secret key.
323
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
324
        let Some((key, sk)) = self.secret_key()? else {
325
            return fail("no secret key: run `oxy identity create` first");
326
        };
327
        let sig = sk.sign(Domain::Change, &key, hash);
328
        self.store.put_signature(hash, &sig)?;
329
        Ok(sig)
330
    }
331
332
    /// Check the signatures on a change against the author-or-delegate rule.
333
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
334
        self.verify_change_known(hash, None)
335
    }
336
337
    /// `verify_change`, with the change's metadata when the caller has it
338
    /// (a change object can be as large as the tree it adds). Signatures
339
    /// are looked up first: an unsigned change needs no metadata.
340
    fn verify_change_known(
341
        &self,
342
        hash: &ChangeHash,
343
        known: Option<&crate::state::ChangeMeta>,
344
    ) -> Result<SignatureStatus> {
345
        let sigs = self.store.signatures(hash)?;
346
        if sigs.is_empty() {
347
            return Ok(SignatureStatus::Unsigned);
348
        }
349
        let read;
350
        let change = match known {
351
            Some(m) => m,
352
            None => {
353
                read = self.store.get_change_meta(hash)?;
354
                &read
355
            }
356
        };
357
        let mut last_err = String::new();
358
        for sig in &sigs {
359
            match self.check_signer(change, sig, Domain::Change, hash) {
360
                Ok(id) => {
361
                    return Ok(SignatureStatus::Valid {
362
                        key: sig.key,
363
                        name: id.name,
364
                        email: id.email,
365
                        sealed: false,
366
                        revoked: self.is_revoked(&sig.key)?,
367
                    })
368
                }
369
                Err(e) => last_err = e,
370
            }
371
        }
372
        Ok(SignatureStatus::Invalid(last_err))
373
    }
374
375
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
376
    fn check_signer(
377
        &self,
378
        change: &crate::state::ChangeMeta,
379
        sig: &Signature,
380
        domain: Domain,
381
        target: &ObjectRef,
382
    ) -> std::result::Result<Identity, String> {
383
        let id = self
384
            .store
385
            .get_identity(&sig.key)
386
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
387
        // The author-or-delegate rule (spec §14.4). A change whose author is
388
        // the zero key names nobody (Git imports, history from before an
389
        // identity existed), so any key may adopt it with a seal; policy
390
        // then authorises that key for the reference as usual.
391
        let authorised = change.author.is_zero()
392
            || sig.key == change.author
393
            || self
394
                .store
395
                .get_identity(&change.author)
396
                .map(|a| a.delegates.contains(&sig.key))
397
                .unwrap_or(false);
398
        if !authorised {
399
            return Err(format!(
400
                "key {} is neither the author nor a delegate",
401
                sig.key.short(12)
402
            ));
403
        }
404
        if id.is_expired_at(change.hlc.wall_ms) {
405
            return Err(format!(
406
                "key {} had expired when the change was made",
407
                sig.key.short(12)
408
            ));
409
        }
410
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
411
        Ok(id)
412
    }
413
414
    /// Like `verify_change`, but a change with no valid individual signature
415
    /// is also authenticated by a valid seal covering it (spec §14.4).
416
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
417
        self.authenticate_change_known(hash, None)
418
    }
419
420
    /// `authenticate_change`, with the change's metadata when the caller
421
    /// has it (from a log, say), so the change itself need not be read.
422
    pub fn authenticate_change_known(
423
        &self,
424
        hash: &ChangeHash,
425
        known: Option<&crate::state::ChangeMeta>,
426
    ) -> Result<SignatureStatus> {
427
        let direct = self.verify_change_known(hash, known)?;
428
        if matches!(direct, SignatureStatus::Valid { .. }) {
429
            return Ok(direct);
430
        }
431
        let mut last_err = match &direct {
432
            SignatureStatus::Invalid(e) => e.clone(),
433
            _ => String::new(),
434
        };
435
        let seals = self.store.seals_for(hash)?;
436
        if seals.is_empty() {
437
            return Ok(match last_err.is_empty() {
438
                true => SignatureStatus::Unsigned,
439
                false => SignatureStatus::Invalid(last_err),
440
            });
441
        }
442
        let read;
443
        let change = match known {
444
            Some(m) => m,
445
            None => {
446
                read = self.store.get_change_meta(hash)?;
447
                &read
448
            }
449
        };
450
        for seal_ref in seals {
451
            let attest = self.store.get_attest(&seal_ref)?;
452
            let AttestBody::Seal { hashes } = &attest.body else {
453
                continue;
454
            };
455
            if !hashes.contains(hash) {
456
                continue;
457
            }
458
            for sig in self.store.signatures(&seal_ref)? {
459
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
460
                    Ok(id) => {
461
                        return Ok(SignatureStatus::Valid {
462
                            key: sig.key,
463
                            name: id.name,
464
                            email: id.email,
465
                            sealed: true,
466
                            revoked: self.is_revoked(&sig.key)?,
467
                        })
468
                    }
469
                    Err(e) => last_err = e,
470
                }
471
            }
472
        }
473
        if last_err.is_empty() {
474
            Ok(SignatureStatus::Unsigned)
475
        } else {
476
            Ok(SignatureStatus::Invalid(last_err))
477
        }
478
    }
479
480
    /// Store and sign an attestation with the configured key.
481
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
482
    /// seal attestation over `hashes`, pushed with the next push. Returns
483
    /// the attestation's reference.
484
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
485
        if hashes.is_empty() {
486
            return fail("nothing to seal");
487
        }
488
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
489
            return fail(format!(
490
                "a seal covers at most {} changes",
491
                crate::attest::MAX_SEAL_HASHES
492
            ));
493
        }
494
        for h in hashes {
495
            if !self.store.has(h) {
496
                return fail(format!("unknown change {}", h.short(12)));
497
            }
498
        }
499
        let mut sorted = hashes.to_vec();
500
        sorted.sort();
501
        sorted.dedup();
502
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
503
        let r = self.store.put_attest(&sa.attest)?;
504
        for sig in &sa.sigs {
505
            self.store.put_signature(&r, sig)?;
506
        }
507
        for h in &sorted {
508
            self.store.index_seal(h, &r)?;
509
        }
510
        Ok(r)
511
    }
512
513
    /// The changes of the current bookmark this identity can authenticate
514
    /// but has not: its own unsigned ones and anonymous ones.
515
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
516
        let Some((key, _)) = self.secret_key()? else {
517
            return fail("no identity: run oxy identity create");
518
        };
519
        let heads = self.bookmark_heads()?;
520
        let state = self.load_state(&heads)?;
521
        let mut out = Vec::new();
522
        for (h, meta) in state.changes() {
523
            if (meta.author == key || meta.author.is_zero())
524
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
525
            {
526
                out.push(*h);
527
            }
528
        }
529
        out.sort();
530
        Ok(out)
531
    }
532
533
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
534
        let Some((key, sk)) = self.secret_key()? else {
535
            return fail("no secret key: run `oxy identity create` first");
536
        };
537
        let r = self.store.put_attest(attest)?;
538
        let sig = sk.sign(Domain::Attest, &key, &r);
539
        self.store.put_signature(&r, &sig)?;
540
        if let AttestBody::Seal { hashes } = &attest.body {
541
            for h in hashes {
542
                self.store.index_seal(h, &r)?;
543
            }
544
        }
545
        Ok(SignedAttest {
546
            attest: attest.clone(),
547
            sigs: vec![sig],
548
        })
549
    }
550
}