radicle 0.23.0

Radicle standard library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
pub mod error;

mod iter;

#[cfg(test)]
mod test;

use std::collections::{BTreeMap, HashMap};
use std::num::NonZeroUsize;
use std::path::Path;

use crypto::{signature, PublicKey};
use nonempty::NonEmpty;
use radicle_core::{NodeId, RepoId};
use radicle_git_metadata::commit::CommitData;
use radicle_oid::Oid;

use crate::git;
use crate::identity::doc;
use crate::storage::refs::sigrefs::git::{object, reference};
use crate::storage::refs::{
    FeatureLevel, Refs, SignedRefs, IDENTITY_ROOT, REFS_BLOB_PATH, SIGNATURE_BLOB_PATH,
    SIGREFS_BRANCH,
};

/// A `rad/sigrefs` that has passed the following verification checks:
///
/// - Has a valid `/signature` blob, which is verified by the signing key.
/// - Contains the `refs/rad/root` entry under `/refs`, which matches the
///   [`RepoId`] of the local repository.
/// - The `refs/rad/sigrefs-parent` entry matches the commit's parent, if the
///   entry exists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerifiedCommit {
    /// The commit that was verified.
    commit: Commit,
    /// The feature level that was recognized for the commit that was verified.
    level: FeatureLevel,
}

impl VerifiedCommit {
    /// Borrow the [`Commit`] that was verified.
    pub(super) fn commit(&self) -> &Commit {
        &self.commit
    }

    // The [`FeatureLevel`] of the refs in this commit.
    #[cfg(test)]
    pub(super) fn level(&self) -> FeatureLevel {
        self.level
    }

    pub(crate) fn into_sigrefs_at(self, id: PublicKey) -> SignedRefs {
        SignedRefs {
            refs: self.commit.refs,
            signature: self.commit.signature,
            id,
            level: self.level,
            parent: self.commit.parent,
            at: self.commit.oid,
        }
    }
}

/// A [`SignedRefsReader`] reads and verifies a commit chain for a `rad/sigrefs`
/// entry.
///
/// To create a new reader, use [`SignedRefsReader::new`].
///
/// The construction expects:
/// - A [`RepoId`] which is the repository identifier of the Radicle repository.
/// - A [`Tip`] which describes where and how to start the verification.
/// - A `repository` which is the Git repository that is being used for the reading.
/// - A `verifier` which is the entity that verifies the cryptographic signatures.
pub struct SignedRefsReader<'a, R, V> {
    rid: RepoId,
    tip: Tip,
    repository: &'a R,
    verifier: &'a V,
}

/// Describe where to start a [`SignedRefsReader`]'s commit chain.
pub enum Tip {
    /// Use the namespace of the given [`NodeId`], resolving their `rad/sigrefs`
    /// to its commit [`Oid`].
    Reference(NodeId),
    /// Use the supplied commit [`Oid`].
    Commit(Oid),
}

/// Describes the feature levels of a history of commits.
#[derive(Debug, PartialEq)]
pub struct FeatureLevels(BTreeMap<FeatureLevel, Oid>);

impl FeatureLevels {
    fn new() -> Self {
        Self(BTreeMap::new())
    }

    pub fn max(&self) -> FeatureLevel {
        self.0.last_key_value().map(|(k, _)| *k).unwrap_or_default()
    }

    fn insert(&mut self, verified: &VerifiedCommit) {
        if verified.level != FeatureLevel::None {
            self.0.entry(verified.level).or_insert(verified.commit.oid);
        }
    }

    #[cfg(any(test, feature = "test"))]
    pub fn test(from: impl IntoIterator<Item = (FeatureLevel, Oid)>) -> Self {
        Self(BTreeMap::from_iter(from))
    }
}

impl std::fmt::Display for FeatureLevels {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(
            &self
                .0
                .iter()
                .map(|(level, at)| format!("{level}@{at}"))
                .collect::<Vec<_>>()
                .join(", "),
        )
    }
}

impl<'a, R, V> SignedRefsReader<'a, R, V>
where
    R: object::Reader + reference::Reader,
    V: signature::Verifier<crypto::Signature>,
{
    /// Construct a new [`SignedRefsReader`].
    pub fn new(rid: RepoId, tip: Tip, repository: &'a R, verifier: &'a V) -> Self {
        Self {
            rid,
            tip,
            repository,
            verifier,
        }
    }

    /// Read a [`VerifiedCommit`] using the [`SignedRefsReader`], from a
    /// linear history.
    ///
    /// The [`VerifiedCommit`] will be the latest commit, if the commit verifies
    /// and contains its parent in its [`Refs`] entry.
    ///
    /// If the commit does not contain a parent, but its signature is not
    /// repeated, then it is still returned.
    ///
    /// Otherwise, the latest commit that has no duplicate signatures in its
    /// ancestry is returned.
    ///
    /// # Replay Attacks
    ///
    /// The [`SignedRefsReader`] prevents replay attacks via two mechanisms:
    /// - The first is recording the parent commit in the `/refs` blob. This
    ///   prevents a replay by not allowing the same signature payload to be
    ///   used in a new commit, since the parents would not match. Note that
    ///   this does not detect replays by older clients, since they will not
    ///   include this entry in `/refs`.
    /// - The second mechanism uses the fact that a replay will give duplicate
    ///   signatures. This means that any repeated signatures will be skipped,
    ///   and the commit returned will be the first valid commit, that was not a
    ///   replay.
    pub fn read(self) -> Result<VerifiedCommit, error::Read> {
        const ONE: NonZeroUsize = NonZeroUsize::new(1).expect("one is non-zero");
        const SIGNATURES_COLLECTED: &str = "all signatures were collected";

        let mut head = CommitReader::new(self.resolve_tip()?, self.repository)
            .read()
            .map_err(error::Read::Commit)?
            .verify(self.rid, self.verifier)
            .map_err(error::Read::Verify)?;

        if head.commit.parent.is_none() && head.level == FeatureLevel::Root {
            head.level = FeatureLevel::Parent;
        }

        let head = head;

        if head.level >= FeatureLevel::Parent {
            // `head` is verified, thus we know that if the parent reference
            // exists, its target actually matches the parent OID.
            // The fact that the parent OID is a hash over all previous history
            // makes it *incredibly unlikely* or rather *practically impossible*
            // that the same `/refs` blob re-appears in previous history.
            // Thus, we can spare oureselves walking the history.
            return Ok(head);
        }

        // `seen` maps from signatures to the `NonEmpty` of commits they were
        // seen in. Note that for all sets of commits which share the same
        // signature, the `NonEmpty` in `seen` will be in reverse order of the
        // walk.  That is, the latest commit in the set will be at the first
        // position, and the earliest commit will be at the last position.
        //
        // `level` is the feature level of the history, which is
        // the maximum feature level over all commits in the history.
        let (seen, levels) = iter::Walk::new(head.commit.oid, self.repository).try_fold(
            (
                HashMap::<crypto::Signature, NonEmpty<Oid>>::new(),
                FeatureLevels::new(),
            ),
            |(mut seen, mut levels), commit| {
                let commit = commit.map_err(error::Read::Commit)?;

                seen.entry(commit.signature)
                    .and_modify(|value| value.push(commit.oid))
                    .or_insert_with(|| NonEmpty::new(commit.oid));

                // Before `commit` can be interpreted for feature detection,
                // it must be verified. In particular, we do not want to
                // detect features on commits that have an invalid signature.
                // However, if we have already reached the maximum level,
                // this is not required anymore, since it cannot increase any
                // further.
                if levels.max() < FeatureLevel::LATEST {
                    let commit = commit
                        .verify(self.rid, self.verifier)
                        .map_err(error::Read::Verify)?;

                    if commit.level > FeatureLevel::None {
                        levels.insert(&commit);
                    }
                }

                Ok((seen, levels))
            },
        )?;

        let level = levels.max();

        if head.level < level {
            return Err(error::Read::Downgrade {
                levels,
                actual: head.level,
                commit: head.commit.oid,
            });
        }

        if seen
            .get(&head.commit.signature)
            .expect(SIGNATURES_COLLECTED)
            .len_nonzero()
            == ONE
        {
            // `head` has a verified, non-repeated signature, but does not
            // include the parent reference in the `/refs` blob. Maintains
            // backwards-compatibility.
            return Ok(head);
        }

        // If the signature in `head` was seen twice, then
        // `head` must have a parent.
        let parent = head.commit.parent.expect("parent must exist");

        // The second walk can start from the parent of `head`. We do not need to
        // verify `head` twice, and we already know that the parent exists.
        for commit in iter::Walk::new(parent, self.repository) {
            let verified = commit
                .map_err(error::Read::Commit)?
                .verify(self.rid, self.verifier)
                .map_err(error::Read::Verify)?;

            if verified.level < level {
                // To avoid downgrade attacks, we skip `commit`.
                continue;
            }

            let commit = verified.commit();

            let commits = seen.get(&commit.signature).expect(SIGNATURES_COLLECTED);
            if commits.len_nonzero() == ONE {
                return Ok(verified);
            }

            let id = &commit.oid;
            if id == commits.last() {
                // If this commit is the last element of `commits`,
                // then this means it is the earliest of all that share
                // its signature. It thus cannot have been replayed.
                return Ok(verified);
            }

            if id == commits.first() {
                // We only log one warning per set of duplicates, and that is
                // when we reach the first element of `commits`, which is the
                // latest in the history.
                log::warn!("Duplicate signature found in commits {commits:?}");
            }
        }

        unreachable!()
    }

    fn resolve_tip(&self) -> Result<Oid, error::Read> {
        match self.tip {
            Tip::Commit(oid) => Ok(oid),
            Tip::Reference(namespace) => {
                let reference =
                    SIGREFS_BRANCH.with_namespace(git::fmt::Component::from(&namespace));
                let head = self
                    .repository
                    .find_reference(&reference)
                    .map_err(error::Read::FindReference)?
                    .ok_or_else(|| error::Read::MissingSigrefs { namespace })?;
                Ok(head)
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Commit {
    oid: Oid,
    parent: Option<Oid>,
    refs: Refs,
    signature: crypto::Signature,
    identity_root: Option<IdentityRoot>,
}

impl Commit {
    /// The [`Oid`] of this commit.
    pub(super) fn oid(&self) -> &Oid {
        &self.oid
    }

    /// The parent [`Oid`] of the commit, unless it is the root commit.
    #[cfg(test)]
    pub(super) fn parent(&self) -> Option<&Oid> {
        self.parent.as_ref()
    }

    /// The [`Refs`] found in the blob at `/refs` in in the tree of this commit.
    pub(super) fn refs(&self) -> &Refs {
        &self.refs
    }

    /// The [`crypto::Signature`] found in blob at `/signature` in the tree of the commit.
    #[cfg(test)]
    pub(super) fn signature(&self) -> &crypto::Signature {
        &self.signature
    }

    pub(super) fn verify<V>(
        mut self,
        expected: RepoId,
        verifier: &V,
    ) -> Result<VerifiedCommit, error::Verify>
    where
        V: signature::Verifier<crypto::Signature>,
    {
        verifier
            .verify(&self.refs.canonical(), &self.signature)
            .map_err(error::Verify::Signature)?;

        let level = if let Some(IdentityRoot {
            commit: identity_commit,
            rid,
        }) = self.identity_root
        {
            if rid != expected {
                return Err(error::Verify::MismatchedIdentity {
                    identity_commit,
                    sigrefs_commit: self.oid,
                    expected,
                    found: rid,
                });
            } else {
                FeatureLevel::Root
            }
        } else {
            FeatureLevel::None
        };

        self.refs.remove_sigrefs();

        let level = match (self.parent, self.refs.remove_parent()) {
            (None, None) | (Some(_), None) => {
                // Pattern 1:
                // We are looking at a root commit.
                // This is a special case, as there is no good value
                // for `rad/refs/sigrefs-parent` to target. The zero OID would
                // be a candidate, but it is filtered out in [`Refs`].
                // Upgrading to `FeatureLevel::Parent` is not a good idea
                // either, otherwise any history containing this commit
                // would be at that level from the root onwards.

                // Pattern 2:
                // The ref `refs/rad/sigrefs-parent` is simply absent,
                // we remain on the same feature level.

                level
            }
            (None, Some(actual)) => {
                // We are looking at a root commit.
                // Any target OID is treated as dangling.
                return Err(error::Verify::DanglingParent {
                    sigrefs_commit: self.oid,
                    actual,
                });
            }
            (Some(expected), Some(actual)) if expected == actual => {
                // We have a good value for `refs/rad/sigrefs-parent`, however,
                // as feature levels are monotonic, we also make sure that the
                // earlier check of `refs/rad/root` was positive.
                // In case the prior feature level was not `FeatureLevel::Root`,
                // we can even error early.
                if level == FeatureLevel::Root {
                    FeatureLevel::Parent
                } else {
                    return Err(error::Verify::IdentityRootDowngrade {
                        sigrefs_commit: self.oid,
                    });
                }
            }
            (Some(expected), Some(actual)) => {
                return Err(error::Verify::MismatchedParent {
                    sigrefs_commit: self.oid,
                    expected,
                    actual,
                })
            }
        };

        Ok(VerifiedCommit {
            commit: self,
            level,
        })
    }
}

pub(super) struct CommitReader<'a, R> {
    commit: Oid,
    repository: &'a R,
}

impl<'a, R> CommitReader<'a, R>
where
    R: object::Reader,
{
    pub(super) fn new(commit: Oid, repository: &'a R) -> Self {
        Self { commit, repository }
    }

    pub(super) fn read(self) -> Result<Commit, error::Commit> {
        let commit = self.read_commit_data()?;
        let Tree { refs, signature } = TreeReader::new(self.commit, self.repository)
            .read()
            .map_err(error::Commit::Tree)?;
        let identity_root = IdentityRootReader::new(&refs, self.repository)
            .read()
            .map_err(error::Commit::IdentityRoot)?;
        let parent = Self::get_parent(&commit).transpose()?;

        Ok(Commit {
            oid: self.commit,
            parent,
            refs,
            signature,
            identity_root,
        })
    }

    fn read_commit_data(&self) -> Result<CommitData<Oid, Oid>, error::Commit> {
        let bytes = self
            .repository
            .read_commit(&self.commit)
            .map_err(error::Commit::Read)?
            .ok_or(error::Commit::Missing { oid: self.commit })?;
        CommitData::from_bytes(&bytes).map_err(|err| error::Commit::Parse {
            oid: self.commit,
            source: err,
        })
    }

    /// Extract the single parent [`Oid`] from a [`CommitData`], if any.
    ///
    /// Returns `None` if the commit has no parents (i.e. it is a root commit).
    /// Returns an error if the commit has more than one parent, since the
    /// transparency log is a linear chain.
    fn get_parent(commit: &CommitData<Oid, Oid>) -> Option<Result<Oid, error::Commit>> {
        let NonEmpty {
            head: parent,
            tail: mut rest,
        } = NonEmpty::collect(commit.parents())?;
        if rest.is_empty() {
            Some(Ok(parent))
        } else {
            rest.insert(0, parent);
            let err = error::Commit::TooManyParents(error::Parent { parents: rest });
            Some(Err(err))
        }
    }
}

struct Tree {
    refs: Refs,
    signature: crypto::Signature,
}

struct TreeReader<'a, R> {
    commit: Oid,
    repository: &'a R,
}

impl<'a, R> TreeReader<'a, R>
where
    R: object::Reader,
{
    fn new(commit: Oid, repository: &'a R) -> Self {
        Self { commit, repository }
    }

    fn read(self) -> Result<Tree, error::Tree> {
        let (refs, signature) = self.try_handle_blobs()?;
        let refs = Refs::from_canonical(&refs.bytes).map_err(error::Tree::ParseRefs)?;
        let signature = crypto::Signature::try_from(signature.bytes.as_slice())
            .map_err(error::Tree::ParseSignature)?;
        Ok(Tree { refs, signature })
    }

    /// Fetch the refs blob and signature blob from the repository, returning a
    /// descriptive error if either or both are missing.
    fn try_handle_blobs(&self) -> Result<(object::Blob, object::Blob), error::Tree> {
        let commit = &self.commit;
        let refs_path = Path::new(REFS_BLOB_PATH);
        let sig_path = Path::new(SIGNATURE_BLOB_PATH);

        let refs_bytes = self
            .repository
            .read_blob(commit, refs_path)
            .map_err(error::Tree::Refs)?;
        let sig_bytes = self
            .repository
            .read_blob(commit, sig_path)
            .map_err(error::Tree::Signature)?;

        let result = match (refs_bytes, sig_bytes) {
            (None, None) => Err(error::MissingBlobs::Both {
                commit: *commit,
                refs: refs_path.to_path_buf(),
                signature: sig_path.to_path_buf(),
            }),
            (None, Some(_)) => Err(error::MissingBlobs::Signature {
                commit: *commit,
                path: sig_path.to_path_buf(),
            }),
            (Some(_), None) => Err(error::MissingBlobs::Refs {
                commit: *commit,
                path: refs_path.to_path_buf(),
            }),
            (Some(refs), Some(sig)) => Ok((refs, sig)),
        };

        result.map_err(error::Tree::from)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct IdentityRoot {
    commit: Oid,
    rid: RepoId,
}

struct IdentityRootReader<'a, 'b, R> {
    refs: &'a Refs,
    repository: &'b R,
}

impl<'a, 'b, R> IdentityRootReader<'a, 'b, R>
where
    R: object::Reader,
{
    fn new(refs: &'a Refs, repository: &'b R) -> Self {
        Self { refs, repository }
    }

    fn read(self) -> Result<Option<IdentityRoot>, error::IdentityRoot> {
        match self.refs.get(&IDENTITY_ROOT) {
            Some(commit) => self
                .read_blob(&commit)
                .map(|rid| Some(IdentityRoot { commit, rid })),
            None => Ok(None),
        }
    }

    fn read_blob(&self, commit: &Oid) -> Result<RepoId, error::IdentityRoot> {
        let path = Path::new("embeds").join(*doc::PATH);
        let object::Blob { oid, .. } = self
            .repository
            .read_blob(commit, &path)
            .map_err(error::IdentityRoot::Blob)?
            .ok_or_else(|| error::IdentityRoot::MissingIdentity { commit: *commit })?;
        Ok(RepoId::from(oid))
    }
}