OXYGENHUB
# f9eab8117787 oxygen / crates / oxy-core / src / repo / identity.rs
20.2 KiB · Rust · last changed Sign in once per hub: oxy auth login, status and logout (closes #47) 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
        crate::durable::write_atomic_private(&path, &sk.encode(&key))?;
69
        write_atomic(
70
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
71
            &id.encode(),
72
        )?;
73
        Ok(key)
74
    }
75
76
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
77
        match scope {
78
            IdentityScope::Repo => {
79
                self.config.set("author.name", &id.name)?;
80
                self.config.set("author.email", &id.email)?;
81
                self.config.set("author.key", &key.to_hex())?;
82
                self.save_config()?;
83
            }
84
            IdentityScope::User => {
85
                Config::set_user(&self.user_config, "author.name", &id.name)?;
86
                Config::set_user(&self.user_config, "author.email", &id.email)?;
87
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
88
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
89
            }
90
        }
91
        Ok(())
92
    }
93
94
    /// The scope that holds the configured author key.
95
    fn author_scope(&self) -> IdentityScope {
96
        if self.config.repo_layer().contains_key("author.key") {
97
            IdentityScope::Repo
98
        } else {
99
            IdentityScope::User
100
        }
101
    }
102
103
    /// Replace the configured identity by `new` signed with `sk`: store it,
104
    /// record a `rotate` attestation signed by the old key, move the old
105
    /// key's policy grants to the new key, and switch the author config.
106
    fn replace_identity(
107
        &mut self,
108
        new: Identity,
109
        sk: SecretKey,
110
        command: &str,
111
    ) -> Result<Rotation> {
112
        let Some((old, old_sk)) = self.secret_key()? else {
113
            return fail("no secret key: run `oxy identity create` first");
114
        };
115
        if new.previous != Some(old) {
116
            return fail("the successor identity must name the current key as previous");
117
        }
118
        let new_key = self.install_key(&new, &sk)?;
119
        let attest = Attest {
120
            repo: self.id()?,
121
            hlc: Hlc::now(),
122
            body: AttestBody::Rotate { new: new_key },
123
        };
124
        let r = self.store.put_attest(&attest)?;
125
        self.store
126
            .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?;
127
        let policy = match self.current_policy()? {
128
            Some((_, sp)) if sp.policy.mentions(&old) => {
129
                let mut p = self.next_policy()?;
130
                p.substitute_key(&old, new.clone());
131
                Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?)
132
            }
133
            _ => None,
134
        };
135
        self.set_author(&new, &new_key, self.author_scope())?;
136
        Ok(Rotation {
137
            old,
138
            new: new_key,
139
            identity: new,
140
            policy,
141
        })
142
    }
143
144
    /// Rotate to a fresh key pair; the new identity names the old one as
145
    /// `previous` and keeps its name, email, delegates, and expiry.
146
    pub fn rotate_identity(&mut self) -> Result<Rotation> {
147
        let Some((old, _)) = self.secret_key()? else {
148
            return fail("no secret key: run `oxy identity create` first");
149
        };
150
        let cur = self.identity(&old)?;
151
        let sk = SecretKey::generate();
152
        let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms);
153
        id.previous = Some(old);
154
        id.delegates = cur.delegates.clone();
155
        id.expires = cur.expires;
156
        self.replace_identity(id, sk, "oxy identity rotate")
157
    }
158
159
    /// Re-issue the identity with the same keys and a new expiry.
160
    pub fn renew_identity(&mut self, expires: Option<u64>) -> Result<Rotation> {
161
        let Some((old, sk)) = self.secret_key()? else {
162
            return fail("no secret key: run `oxy identity create` first");
163
        };
164
        let cur = self.identity(&old)?;
165
        let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms);
166
        self.replace_identity(id, sk, "oxy identity renew")
167
    }
168
169
    /// Let `delegate` sign or seal on this identity's behalf. Delegates are
170
    /// part of the identity object, so this re-issues it with the same keys.
171
    pub fn delegate_add(&mut self, delegate: Identity) -> Result<Rotation> {
172
        let Some((old, sk)) = self.secret_key()? else {
173
            return fail("no secret key: run `oxy identity create` first");
174
        };
175
        let dk = self.store.put_identity(&delegate)?;
176
        if dk == old {
177
            return fail("an identity cannot delegate to itself");
178
        }
179
        let cur = self.identity(&old)?;
180
        if cur.delegates.contains(&dk) {
181
            return fail(format!("{} is already a delegate", dk.short(12)));
182
        }
183
        let mut delegates = cur.delegates.clone();
184
        delegates.push(dk);
185
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
186
        self.replace_identity(
187
            id,
188
            sk,
189
            &format!("oxy identity delegate add {}", dk.short(12)),
190
        )
191
    }
192
193
    /// Withdraw a delegation; re-issues the identity with the same keys.
194
    pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result<Rotation> {
195
        let Some((old, sk)) = self.secret_key()? else {
196
            return fail("no secret key: run `oxy identity create` first");
197
        };
198
        let cur = self.identity(&old)?;
199
        if !cur.delegates.contains(delegate) {
200
            return fail(format!("{} is not a delegate", delegate.short(12)));
201
        }
202
        let delegates = cur
203
            .delegates
204
            .iter()
205
            .copied()
206
            .filter(|d| d != delegate)
207
            .collect();
208
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
209
        self.replace_identity(
210
            id,
211
            sk,
212
            &format!("oxy identity delegate remove {}", delegate.short(12)),
213
        )
214
    }
215
216
    /// Revoke `key` (your own, or any key when you hold a policy root):
217
    /// record a signed `revoke` attestation and a local marker, and drop
218
    /// the key from the policy where it has one.
219
    pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result<Option<PolicyUpdate>> {
220
        let Some((own, sk)) = self.secret_key()? else {
221
            return fail("no secret key: run `oxy identity create` first");
222
        };
223
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
224
        let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own));
225
        if *key != own && !is_root {
226
            return fail("only the key's holder or a policy root can revoke it");
227
        }
228
        let attest = Attest {
229
            repo: self.id()?,
230
            hlc: Hlc::now(),
231
            body: AttestBody::Revoke {
232
                key: *key,
233
                reason: reason.into(),
234
            },
235
        };
236
        let r = self.store.put_attest(&attest)?;
237
        self.store
238
            .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?;
239
        let dir = self.oxy.join("revoked");
240
        fs::create_dir_all(&dir)?;
241
        write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?;
242
        match policy {
243
            Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)),
244
            _ => Ok(None),
245
        }
246
    }
247
248
    /// Whether `key` is revoked by the policy or by a recorded revocation.
249
    pub fn is_revoked(&self, key: &KeyId) -> Result<bool> {
250
        if self.oxy.join("revoked").join(key.to_hex()).exists() {
251
            return Ok(true);
252
        }
253
        Ok(self
254
            .current_policy()?
255
            .is_some_and(|(_, sp)| sp.policy.is_revoked(key)))
256
    }
257
258
    /// The secret key for `author.key`, if configured and present on disk.
259
    /// The identity object is kept beside the secret so a repository that has
260
    /// never seen it (a fresh clone) can store it when it first signs.
261
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
262
        let Some(key) = self.config.author_key else {
263
            return Ok(None);
264
        };
265
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
266
        match fs::read(&path) {
267
            Ok(b) => {
268
                let (k, sk) = SecretKey::decode(&b)?;
269
                if k != key {
270
                    return fail(format!(
271
                        "{} holds a different key than its name",
272
                        path.display()
273
                    ));
274
                }
275
                if !self.store.has(&key) {
276
                    let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
277
                    if let Ok(bytes) = fs::read(&id_path) {
278
                        let id = Identity::decode(&bytes)?;
279
                        if id.hash() == key {
280
                            self.store.put_identity(&id)?;
281
                        }
282
                    }
283
                }
284
                Ok(Some((k, sk)))
285
            }
286
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
287
            Err(e) => Err(e.into()),
288
        }
289
    }
290
291
    /// An identity: from this repository's store, or else from the key
292
    /// directory, where `oxy identity create` keeps the user's own (a new
293
    /// repository has not stored it yet). The file must hash to `key`.
294
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
295
        match self.store.get_identity(key) {
296
            Ok(id) => Ok(id),
297
            Err(e) => {
298
                let path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
299
                match fs::read(&path) {
300
                    Ok(bytes) => {
301
                        let id = Identity::decode(&bytes)?;
302
                        if id.hash() != *key {
303
                            return fail(format!(
304
                                "{} does not hold identity {}",
305
                                path.display(),
306
                                key.short(12)
307
                            ));
308
                        }
309
                        Ok(id)
310
                    }
311
                    Err(_) => Err(e.into()),
312
                }
313
            }
314
        }
315
    }
316
317
    /// Sign a stored change with the configured secret key.
318
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
319
        let Some((key, sk)) = self.secret_key()? else {
320
            return fail("no secret key: run `oxy identity create` first");
321
        };
322
        let sig = sk.sign(Domain::Change, &key, hash);
323
        self.store.put_signature(hash, &sig)?;
324
        Ok(sig)
325
    }
326
327
    /// Check the signatures on a change against the author-or-delegate rule.
328
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
329
        self.verify_change_known(hash, None)
330
    }
331
332
    /// `verify_change`, with the change's metadata when the caller has it
333
    /// (a change object can be as large as the tree it adds). Signatures
334
    /// are looked up first: an unsigned change needs no metadata.
335
    fn verify_change_known(
336
        &self,
337
        hash: &ChangeHash,
338
        known: Option<&crate::state::ChangeMeta>,
339
    ) -> Result<SignatureStatus> {
340
        let sigs = self.store.signatures(hash)?;
341
        if sigs.is_empty() {
342
            return Ok(SignatureStatus::Unsigned);
343
        }
344
        let read;
345
        let change = match known {
346
            Some(m) => m,
347
            None => {
348
                read = self.store.get_change_meta(hash)?;
349
                &read
350
            }
351
        };
352
        let mut last_err = String::new();
353
        for sig in &sigs {
354
            match self.check_signer(change, sig, Domain::Change, hash) {
355
                Ok(id) => {
356
                    return Ok(SignatureStatus::Valid {
357
                        key: sig.key,
358
                        name: id.name,
359
                        email: id.email,
360
                        sealed: false,
361
                        revoked: self.is_revoked(&sig.key)?,
362
                    })
363
                }
364
                Err(e) => last_err = e,
365
            }
366
        }
367
        Ok(SignatureStatus::Invalid(last_err))
368
    }
369
370
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
371
    fn check_signer(
372
        &self,
373
        change: &crate::state::ChangeMeta,
374
        sig: &Signature,
375
        domain: Domain,
376
        target: &ObjectRef,
377
    ) -> std::result::Result<Identity, String> {
378
        let id = self
379
            .store
380
            .get_identity(&sig.key)
381
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
382
        // The author-or-delegate rule (spec §14.4). A change whose author is
383
        // the zero key names nobody (Git imports, history from before an
384
        // identity existed), so any key may adopt it with a seal; policy
385
        // then authorises that key for the reference as usual.
386
        let authorised = change.author.is_zero()
387
            || sig.key == change.author
388
            || self
389
                .store
390
                .get_identity(&change.author)
391
                .map(|a| a.delegates.contains(&sig.key))
392
                .unwrap_or(false);
393
        if !authorised {
394
            return Err(format!(
395
                "key {} is neither the author nor a delegate",
396
                sig.key.short(12)
397
            ));
398
        }
399
        if id.is_expired_at(change.hlc.wall_ms) {
400
            return Err(format!(
401
                "key {} had expired when the change was made",
402
                sig.key.short(12)
403
            ));
404
        }
405
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
406
        Ok(id)
407
    }
408
409
    /// Like `verify_change`, but a change with no valid individual signature
410
    /// is also authenticated by a valid seal covering it (spec §14.4).
411
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
412
        self.authenticate_change_known(hash, None)
413
    }
414
415
    /// `authenticate_change`, with the change's metadata when the caller
416
    /// has it (from a log, say), so the change itself need not be read.
417
    pub fn authenticate_change_known(
418
        &self,
419
        hash: &ChangeHash,
420
        known: Option<&crate::state::ChangeMeta>,
421
    ) -> Result<SignatureStatus> {
422
        let direct = self.verify_change_known(hash, known)?;
423
        if matches!(direct, SignatureStatus::Valid { .. }) {
424
            return Ok(direct);
425
        }
426
        let mut last_err = match &direct {
427
            SignatureStatus::Invalid(e) => e.clone(),
428
            _ => String::new(),
429
        };
430
        let seals = self.store.seals_for(hash)?;
431
        if seals.is_empty() {
432
            return Ok(match last_err.is_empty() {
433
                true => SignatureStatus::Unsigned,
434
                false => SignatureStatus::Invalid(last_err),
435
            });
436
        }
437
        let read;
438
        let change = match known {
439
            Some(m) => m,
440
            None => {
441
                read = self.store.get_change_meta(hash)?;
442
                &read
443
            }
444
        };
445
        for seal_ref in seals {
446
            let attest = self.store.get_attest(&seal_ref)?;
447
            let AttestBody::Seal { hashes } = &attest.body else {
448
                continue;
449
            };
450
            if !hashes.contains(hash) {
451
                continue;
452
            }
453
            for sig in self.store.signatures(&seal_ref)? {
454
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
455
                    Ok(id) => {
456
                        return Ok(SignatureStatus::Valid {
457
                            key: sig.key,
458
                            name: id.name,
459
                            email: id.email,
460
                            sealed: true,
461
                            revoked: self.is_revoked(&sig.key)?,
462
                        })
463
                    }
464
                    Err(e) => last_err = e,
465
                }
466
            }
467
        }
468
        if last_err.is_empty() {
469
            Ok(SignatureStatus::Unsigned)
470
        } else {
471
            Ok(SignatureStatus::Invalid(last_err))
472
        }
473
    }
474
475
    /// Store and sign an attestation with the configured key.
476
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
477
    /// seal attestation over `hashes`, pushed with the next push. Returns
478
    /// the attestation's reference.
479
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
480
        if hashes.is_empty() {
481
            return fail("nothing to seal");
482
        }
483
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
484
            return fail(format!(
485
                "a seal covers at most {} changes",
486
                crate::attest::MAX_SEAL_HASHES
487
            ));
488
        }
489
        for h in hashes {
490
            if !self.store.has(h) {
491
                return fail(format!("unknown change {}", h.short(12)));
492
            }
493
        }
494
        let mut sorted = hashes.to_vec();
495
        sorted.sort();
496
        sorted.dedup();
497
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
498
        let r = self.store.put_attest(&sa.attest)?;
499
        for sig in &sa.sigs {
500
            self.store.put_signature(&r, sig)?;
501
        }
502
        for h in &sorted {
503
            self.store.index_seal(h, &r)?;
504
        }
505
        Ok(r)
506
    }
507
508
    /// The changes of the current bookmark this identity can authenticate
509
    /// but has not: its own unsigned ones and anonymous ones.
510
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
511
        let Some((key, _)) = self.secret_key()? else {
512
            return fail("no identity: run oxy identity create");
513
        };
514
        let heads = self.bookmark_heads()?;
515
        let state = self.load_state_history(&heads)?;
516
        let mut out = Vec::new();
517
        for (h, meta) in state.changes() {
518
            if (meta.author == key || meta.author.is_zero())
519
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
520
            {
521
                out.push(*h);
522
            }
523
        }
524
        out.sort();
525
        Ok(out)
526
    }
527
528
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
529
        let Some((key, sk)) = self.secret_key()? else {
530
            return fail("no secret key: run `oxy identity create` first");
531
        };
532
        let r = self.store.put_attest(attest)?;
533
        let sig = sk.sign(Domain::Attest, &key, &r);
534
        self.store.put_signature(&r, &sig)?;
535
        if let AttestBody::Seal { hashes } = &attest.body {
536
            for h in hashes {
537
                self.store.index_seal(h, &r)?;
538
            }
539
        }
540
        Ok(SignedAttest {
541
            attest: attest.clone(),
542
            sigs: vec![sig],
543
        })
544
    }
545
}