ostrya 0.19.0

Pure-Rust async reimplementation of the ostree repository 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
//! The X.509 CRL cache of a repository: `extensions/ostrya/x509-crl/`.
//!
//! Each CRL is one file `<issuer>/<number>`. `<issuer>` is the SHA-256 of
//! the DER of the issuer name of the CRL followed by the DER of the
//! SubjectPublicKeyInfo of the trusted signer whose key verifies the CRL, in
//! 64 lowercase hex digits. `<number>` is the `cRLNumber` in lowercase hex,
//! padded with zeros to 40 digits, so the order of the names is the order of
//! the numbers. `ostrya_sign::x509_crl_cache_name` gives the two names.
//!
//! A reader takes the file with the highest number of each issuer directory
//! that a verifier names. A writer writes a file with an atomic link, and
//! keeps a file that exists with the same name. Then it removes the files of
//! the issuer directory with a lower number. It never removes a file with a
//! higher number, so concurrent writers keep the CRL with the highest number
//! with no lock.

use ostrya_core::{Type, Value};

use crate::config::repo;
use crate::error::Result;
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, Publish, RepoDir, RepoLayout};
use crate::sign::{MAX_X509_CRL, MAX_X509_CRLS, Verifier, X509_CRLS_KEY, X509KeptCrl};

/// The cache directory, below `extensions`.
const CACHE_SUBDIR: &str = "ostrya/x509-crl";

/// The number of hex digits of the name of an issuer directory.
const ISSUER_DIGITS: usize = 64;

/// The number of hex digits of the name of a CRL file.
const NUMBER_DIGITS: usize = 40;

/// Returns `name` as text if it is `digits` lowercase hex digits.
fn hex_name(name: &[u8], digits: usize) -> Option<&str> {
    (name.len() == digits && name.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
        .then(|| std::str::from_utf8(name).ok())
        .flatten()
}

/// Returns the highest CRL file name of the issuer directory `dir`, or
/// `None` if it holds no such name. Each other name is ignored.
fn highest(dir: &RepoDir) -> Result<Option<String>> {
    Ok(dir
        .list()?
        .iter()
        .filter_map(|entry| hex_name(&entry.name, NUMBER_DIGITS))
        .max()
        .map(str::to_owned))
}

/// Returns the issuer directories of the cache that a verify of the
/// signature dict `dict` with `verifiers` can use, each one time, as
/// [`Verifier::x509_crl_cache_dirs`] gives them.
pub(crate) fn cache_dirs<'a>(
    verifiers: impl IntoIterator<Item = &'a dyn Verifier>,
    dict: Option<&Value>,
) -> Vec<String> {
    let mut dirs: Vec<String> = Vec::new();
    for verifier in verifiers {
        for dir in verifier.x509_crl_cache_dirs(dict) {
            if !dirs.contains(&dir) {
                dirs.push(dir);
            }
        }
    }
    dirs
}

/// Reads the CRL with the highest number of each issuer directory of `dirs`
/// in the cache below the repository root `root`, in the order of the
/// directory names. The read opens no other directory of the cache. A
/// repository with no cache, and a directory that is absent, give no CRL.
///
/// A name of `dirs` that is not 64 lowercase hex digits, and a file name that
/// is not 40 lowercase hex digits, are ignored. A symlink, an entry of
/// another type, a CRL file larger than [`MAX_X509_CRL`] bytes, and an I/O
/// error fail the read. If a writer removes the file after the listing of its
/// directory, the read lists the directory again: a writer removes a file
/// only after it writes a file with a higher number.
pub(crate) fn read(root: &RepoDir, dirs: &[String]) -> Result<Vec<Vec<u8>>> {
    let mut issuers: Vec<&str> = dirs
        .iter()
        .filter_map(|dir| hex_name(dir.as_bytes(), ISSUER_DIGITS))
        .collect();
    if issuers.is_empty() {
        return Ok(Vec::new());
    }
    issuers.sort_unstable();
    issuers.dedup();
    let Some(extensions) = root.open_layout(RepoLayout::Extensions).optional()? else {
        return Ok(Vec::new());
    };
    let Some(cache) = extensions.open_dir(CACHE_SUBDIR).optional()? else {
        return Ok(Vec::new());
    };
    let mut crls = Vec::with_capacity(issuers.len());
    for issuer in issuers {
        let Some(dir) = cache.open_dir(issuer).optional()? else {
            continue;
        };
        while let Some(number) = highest(&dir)? {
            match dir.read_capped(&number, MAX_X509_CRL as u64) {
                Ok(crl) => {
                    crls.push(crl);
                    break;
                }
                Err(FsError::Absent { .. }) => continue,
                Err(err) => return Err(err.into()),
            }
        }
    }
    Ok(crls)
}

/// Returns the CRLs `crls` as context dicts of a verifier: dicts with the
/// key [`X509_CRLS_KEY`] alone, each with at most [`MAX_X509_CRLS`] CRLs.
/// The dicts take the CRLs with no copy.
pub(crate) fn dicts(crls: Vec<Vec<u8>>) -> Vec<Value> {
    let ty = Type::array(Type::array(Type::Byte));
    let mut crls = crls.into_iter();
    let mut dicts = Vec::new();
    loop {
        let chunk: Vec<Value> = crls
            .by_ref()
            .take(MAX_X509_CRLS)
            .map(Value::Bytes)
            .collect();
        if chunk.is_empty() {
            return dicts;
        }
        dicts.push(Value::Array(vec![Value::Tuple(vec![
            Value::Str(X509_CRLS_KEY.to_owned()),
            Value::variant(ty.clone(), Value::Array(chunk)),
        ])]));
    }
}

/// Returns the directory `path` below `extensions` of the root `root` if it
/// exists. The call creates no directory.
fn existing_dir(root: &RepoDir, path: &str) -> Result<Option<RepoDir>> {
    let Some(extensions) = root.open_layout(RepoLayout::Extensions).optional()? else {
        return Ok(None);
    };
    Ok(extensions.open_dir(path).optional()?)
}

/// Writes each CRL of `crls` to the cache below the repository root `root`.
///
/// A writer skips a CRL whose issuer directory holds a file with the same
/// number or a higher number, and a CRL that the path check does not use. It
/// reads the names of a CRL before it reads the rest of the CRL, so the skip
/// of a CRL that the cache holds parses no CRL and creates no directory. Else
/// it writes the file with an atomic link, and then removes each file of the
/// issuer directory with a lower number. With `fsync`, the writes and the
/// removals are synced.
pub(crate) fn write(root: &RepoDir, crls: &[X509KeptCrl], fsync: bool) -> Result<()> {
    for crl in crls {
        let Some((issuer, number)) = ostrya_sign::x509_crl_cache_name(crl) else {
            continue;
        };
        let path = format!("{CACHE_SUBDIR}/{issuer}");
        let existing = existing_dir(root, &path)?;
        if let Some(dir) = &existing
            && highest(dir)?.is_some_and(|held| held >= number)
        {
            continue;
        }
        if !ostrya_sign::x509_crl_usable(&crl.der) {
            continue;
        }
        let dir = match existing {
            Some(dir) => dir,
            None => root
                .ensure_layout(RepoLayout::Extensions, fsync)?
                .ensure_dir(&path, fsync)?,
        };
        dir.write_atomic(&number, &crl.der, Publish::KeepExisting, fsync)?;
        let lower: Vec<String> = dir
            .list()?
            .iter()
            .filter_map(|entry| hex_name(&entry.name, NUMBER_DIGITS))
            .filter(|name| *name < number.as_str())
            .map(str::to_owned)
            .collect();
        for name in lower {
            dir.remove_file(&name, fsync)?;
        }
    }
    Ok(())
}

/// The X.509 CRL cache of a repository.
impl Repo {
    /// Returns the CRLs of the X.509 CRL cache of this repository for a
    /// verify of the signature dict `dict` with `verifiers`, as context dicts
    /// of [`Verifier::verify_metadata`].
    ///
    /// The cache is `extensions/ostrya/x509-crl/` in the repository. A pull,
    /// a local pull, a media import, the receive endpoint, and the one-way
    /// receive write to it the CRLs that the X.509 check of the spki engine
    /// selects at the admission of an object. The call reads only the issuer
    /// directories of the candidate CRL signers of the verify, which
    /// [`Verifier::x509_crl_cache_dirs`] of each verifier gives, and the CRL
    /// with the highest `cRLNumber` of each. Each dict holds the key
    /// [`X509_CRLS_KEY`] alone, with at most [`MAX_X509_CRLS`] CRLs. A
    /// repository with no cache, and a verify with no candidate signer, give
    /// no dict.
    ///
    /// A caller gives the dicts to a verify of an object that is in the
    /// repository, for example to [`verify_all`](crate::sign::verify_all),
    /// so the verify knows each CRL that an admission learned. A CRL can
    /// only make a check fail. The verifier checks the signature of each CRL
    /// of the cache again.
    ///
    /// The read runs on the blocking pool.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`](crate::Error::InvalidFormat) if a
    ///   directory or a file of the cache whose name is 64 or 40 lowercase
    ///   hex digits is a symlink or of another type, or if a CRL file is
    ///   larger than [`MAX_X509_CRL`] bytes. The cache ignores each other
    ///   name.
    /// - [`Error::Io`](crate::Error::Io) if a file system operation fails.
    pub async fn x509_crl_context(
        &self,
        verifiers: &[&dyn Verifier],
        dict: Option<&Value>,
    ) -> Result<Vec<Value>> {
        let dirs = cache_dirs(verifiers.iter().copied(), dict);
        if dirs.is_empty() {
            return Ok(Vec::new());
        }
        let repo = self.clone();
        ostrya_rt::unblock(move || read(repo.root_dir(), &dirs).map(dicts)).await
    }

    /// Writes the X.509 CRLs `crls` to the X.509 CRL cache of this
    /// repository.
    ///
    /// Each item is a CRL with the key of its signer, for example from
    /// [`VerifyOutcome::crls`](crate::sign::VerifyOutcome::crls) of a
    /// verify at the admission of an object. The issuer directory of a CRL is
    /// the directory of its issuer and its signer, so the CRLs of two CA keys
    /// with one name do not replace each other. The call skips a CRL whose
    /// issuer directory holds a CRL with the same `cRLNumber` or a higher
    /// one, and a CRL that the path check of the spki engine does not use. It
    /// writes each other CRL with an atomic link, and then removes each CRL
    /// of the issuer directory with a lower number. It takes no lock:
    /// concurrent writers keep the CRL with the highest number. The writes
    /// follow `[core] fsync`.
    ///
    /// The call does not check the signature of a CRL. A reader of the cache
    /// checks it at each verify.
    ///
    /// The write runs on the blocking pool.
    ///
    /// # Errors
    ///
    /// - [`Error::Core`](crate::Error::Core) if `[core] fsync` is not a
    ///   boolean.
    /// - [`Error::InvalidFormat`](crate::Error::InvalidFormat) if a
    ///   directory of the cache is a symlink or of another type.
    /// - [`Error::Io`](crate::Error::Io) if a file system operation fails,
    ///   for example on a full file system.
    pub async fn cache_x509_crls(&self, crls: &[X509KeptCrl]) -> Result<()> {
        if crls.is_empty() {
            return Ok(());
        }
        let fsync = self.config().get::<repo::Fsync>()?;
        let repo = self.clone();
        let crls = crls.to_vec();
        ostrya_rt::unblock(move || write(repo.root_dir(), &crls, fsync)).await
    }
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::*;
    use crate::{CreateOptions, RepoMode};

    /// The signer key of the test CRLs. The cache takes the key into the name
    /// of a directory alone, so these bytes stand for a SubjectPublicKeyInfo.
    const SIGNER: &[u8] = b"the key of the intermediate";

    /// The key of another CA whose intermediate has the same name.
    const OTHER_SIGNER: &[u8] = b"the key of another intermediate";

    /// Returns the DER of the CRL of the X.509 fixture file `name`.
    fn fixture(name: &str) -> Vec<u8> {
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/x509")
            .join(name);
        crate::spki::x509_crls(&std::fs::read(path).unwrap(), name)
            .unwrap()
            .remove(0)
    }

    /// Returns the CRL of the fixture file `name` with the signer `signer`.
    fn kept(name: &str, signer: &[u8]) -> X509KeptCrl {
        X509KeptCrl {
            der: fixture(name),
            signer: signer.to_vec(),
        }
    }

    /// The CRLs of the intermediate of the fixtures, with the numbers 1, 2,
    /// and 3, each with the signer `signer`.
    fn numbered(signer: &[u8]) -> [X509KeptCrl; 3] {
        [
            kept("intermediate.crl.pem", signer),
            kept("intermediate-2.crl.pem", signer),
            kept("intermediate-stale.crl.pem", signer),
        ]
    }

    /// Returns the issuer directory name of `crl`.
    fn dir_of(crl: &X509KeptCrl) -> String {
        ostrya_sign::x509_crl_cache_name(crl).unwrap().0
    }

    /// Returns the cache name of the number of `crl`.
    fn number_of(crl: &X509KeptCrl) -> String {
        ostrya_sign::x509_crl_cache_name(crl).unwrap().1
    }

    /// A scratch directory with an archive repository. The guard removes the
    /// directory when it drops.
    struct Scratch {
        dir: PathBuf,
        repo: Repo,
    }

    impl Scratch {
        fn new(name: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "ostrya-crl-cache-{name}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            let repo = ostrya_rt::block_on(Repo::create(
                &dir.join("repo"),
                CreateOptions::new(RepoMode::Archive),
            ))
            .unwrap();
            Scratch { dir, repo }
        }

        /// Returns the cache directory.
        fn cache(&self) -> PathBuf {
            self.dir.join("repo/extensions").join(CACHE_SUBDIR)
        }

        /// Returns the issuer directory of `crl` in the cache.
        fn issuer_dir(&self, crl: &X509KeptCrl) -> PathBuf {
            self.cache().join(dir_of(crl))
        }

        /// Returns the names of the files of the issuer directory of `crl`,
        /// sorted.
        fn names(&self, crl: &X509KeptCrl) -> Vec<String> {
            let mut names: Vec<String> = std::fs::read_dir(self.issuer_dir(crl))
                .unwrap()
                .map(|e| e.unwrap().file_name().into_string().unwrap())
                .collect();
            names.sort();
            names
        }

        /// Writes `crls` to the cache.
        fn write(&self, crls: &[X509KeptCrl]) {
            write(self.repo.root_dir(), crls, false).unwrap();
        }

        /// Reads the issuer directories of `crls` of the cache.
        fn read(&self, crls: &[&X509KeptCrl]) -> Result<Vec<Vec<u8>>> {
            let dirs: Vec<String> = crls.iter().map(|crl| dir_of(crl)).collect();
            read(self.repo.root_dir(), &dirs)
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }

    #[test]
    fn the_cache_keeps_the_highest_number_of_each_issuer() {
        let scratch = Scratch::new("highest");
        let [one, two, _] = numbered(SIGNER);
        let root = kept("root.crl.pem", b"the key of the root");
        assert!(scratch.read(&[&one, &root]).unwrap().is_empty());
        scratch.write(std::slice::from_ref(&one));
        scratch.write(&[two.clone(), root.clone()]);
        assert_eq!(scratch.names(&two), [number_of(&two)]);
        // A lower number is skipped.
        scratch.write(std::slice::from_ref(&one));
        assert_eq!(scratch.names(&two), [number_of(&two)]);
        let mut held = scratch.read(&[&two, &root]).unwrap();
        held.sort();
        let mut expected = vec![two.der.clone(), root.der.clone()];
        expected.sort();
        assert_eq!(held, expected);
        assert_eq!(dicts(held).len(), 1);
        // The read opens the named directories alone.
        assert_eq!(scratch.read(&[&root]).unwrap(), [root.der]);
        assert!(read(scratch.repo.root_dir(), &[]).unwrap().is_empty());
    }

    #[test]
    fn a_crl_of_another_signer_with_the_same_issuer_name_evicts_and_blocks_nothing() {
        let scratch = Scratch::new("signers");
        let [one, two, _] = numbered(SIGNER);
        let [_, _, foreign] = numbered(OTHER_SIGNER);
        scratch.write(std::slice::from_ref(&one));
        // Another CA keeps a CRL of an issuer of the same name with a higher
        // number.
        scratch.write(std::slice::from_ref(&foreign));
        assert_ne!(dir_of(&one), dir_of(&foreign));
        assert_eq!(scratch.names(&one), [number_of(&one)]);
        assert_eq!(
            scratch.read(&[&one]).unwrap(),
            std::slice::from_ref(&one.der)
        );
        // A later CRL of the first CA is written, and replaces its own lower
        // number alone.
        scratch.write(std::slice::from_ref(&two));
        assert_eq!(scratch.names(&two), [number_of(&two)]);
        assert_eq!(scratch.names(&foreign), [number_of(&foreign)]);
        assert_eq!(scratch.read(&[&two]).unwrap(), [two.der]);
        assert_eq!(scratch.read(&[&foreign]).unwrap(), [foreign.der]);
    }

    #[test]
    fn a_writer_with_a_lower_number_removes_nothing_above_it() {
        let scratch = Scratch::new("lower");
        let [one, two, three] = numbered(SIGNER);
        scratch.write(std::slice::from_ref(&one));
        // Another writer put a higher number in place after the listing of
        // a writer of the number 2.
        std::fs::write(scratch.issuer_dir(&one).join(number_of(&three)), &three.der).unwrap();
        scratch.write(std::slice::from_ref(&two));
        assert_eq!(scratch.names(&one), [number_of(&one), number_of(&three)]);
        assert_eq!(scratch.read(&[&one]).unwrap(), [three.der]);
    }

    #[test]
    fn two_writers_at_once_keep_the_highest_number() {
        let crls = numbered(SIGNER);
        for round in 0..16 {
            let scratch = Scratch::new("race");
            let path = scratch.dir.join("repo");
            // Odd rounds write through a second handle of the repository.
            let other = if round % 2 == 1 {
                ostrya_rt::block_on(Repo::open(&path)).unwrap()
            } else {
                scratch.repo.clone()
            };
            let mut order = [0usize, 1, 2];
            order.rotate_left(round % 3);
            if round % 4 >= 2 {
                order.reverse();
            }
            std::thread::scope(|s| {
                for (n, index) in order.into_iter().enumerate() {
                    let repo = if n % 2 == 0 { &scratch.repo } else { &other };
                    let crl = &crls[index];
                    s.spawn(move || {
                        write(repo.root_dir(), std::slice::from_ref(crl), false).unwrap();
                    });
                }
            });
            // A lower number can stay after a race: a later writer removes
            // it. The highest number stays, and the reader takes it.
            let names = scratch.names(&crls[2]);
            assert_eq!(names.last(), Some(&number_of(&crls[2])), "{order:?}");
            assert_eq!(scratch.read(&[&crls[2]]).unwrap(), [crls[2].der.clone()]);
        }
    }

    #[test]
    fn other_names_are_ignored_and_a_symlink_fails_the_read() {
        let scratch = Scratch::new("names");
        let [one, two, _] = numbered(SIGNER);
        scratch.write(std::slice::from_ref(&one));
        std::fs::write(scratch.cache().join("README"), b"x").unwrap();
        std::fs::write(scratch.issuer_dir(&one).join("NOTES"), b"x").unwrap();
        std::fs::write(
            scratch
                .issuer_dir(&one)
                .join(number_of(&one).to_uppercase() + "f"),
            b"x",
        )
        .unwrap();
        let dirs = [dir_of(&one), "README".to_owned(), "../x".to_owned()];
        assert_eq!(
            read(scratch.repo.root_dir(), &dirs).unwrap(),
            std::slice::from_ref(&one.der)
        );
        // A symlink with the name of a number fails the read.
        std::os::unix::fs::symlink(
            number_of(&one),
            scratch.issuer_dir(&one).join(number_of(&two)),
        )
        .unwrap();
        let err = scratch.read(&[&one]).unwrap_err();
        assert!(
            matches!(&err, crate::Error::InvalidFormat(m) if m.contains("symlink")),
            "{err:?}"
        );
    }

    #[test]
    fn a_crl_that_the_check_does_not_use_is_not_written() {
        let scratch = Scratch::new("unused");
        scratch.write(&[kept("crl-no-number.pem", SIGNER)]);
        assert!(!scratch.cache().exists());
    }

    #[test]
    fn the_cache_is_given_in_dicts_of_at_most_16_crls() {
        let crl = fixture("intermediate.crl.pem");
        let held = dicts(vec![crl.clone(); MAX_X509_CRLS + 1]);
        assert_eq!(held.len(), 2);
        assert_eq!(ostrya_sign::x509_crls_in(&held[0]).len(), MAX_X509_CRLS);
        assert_eq!(ostrya_sign::x509_crls_in(&held[1]), [&crl[..]]);
        assert!(dicts(Vec::new()).is_empty());
    }
}