ostrya 0.19.1

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
//! The reader of the key groups, `[ex-ostrya key "NAME"]`, and the build of
//! their signing keys.

use std::os::fd::{AsFd, BorrowedFd};
use std::path::Path;

use crate::config::{Key, Section, SectionExt as _, SigningKeyType, key};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::sign::key_text;
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
use crate::verify::read_capped_file_at;
use crate::verify::read_key_file_at;
use crate::verify::trust::valid_group_name;

use super::SigningKey;

/// The name prefix of a key group, before the quoted name.
const KEY_PREFIX: &str = "ex-ostrya key \"";

/// One key group as the check of its keys reads it.
pub(crate) enum KeySpec {
    Ed25519 {
        file: String,
    },
    #[cfg(feature = "sign-spki")]
    Spki {
        file: String,
        /// The `certificate-chain-file`, if the group sets it.
        chain: Option<String>,
        /// The `crl-file`, if the group sets it.
        crl: Option<String>,
    },
    #[cfg(feature = "sign-gpg")]
    Gpg {
        key: String,
        homedir: Option<String>,
    },
}

impl SigningKey {
    /// Builds the signing keys of the key group `[ex-ostrya key "NAME"]` of
    /// the config of `repo`, where `NAME` is `name`.
    ///
    /// The call reads the group from [`Repo::config`]. It checks and builds
    /// that group alone. It reads no client group, no server group, no trust
    /// group, and no other key group, so a malformed group that `name` does
    /// not name does not stop the call. `ostrya serve` and `ostrya receive`
    /// read the same groups, so one group holds one key for each of them.
    ///
    /// The group takes the keys of [`config::key`](crate::config::key): `type`,
    /// which is `ed25519`, `spki`, or `gpg`. An `ed25519` or `spki` group
    /// takes `secret-key-file`. An `spki` group also takes
    /// `certificate-chain-file` and `crl-file` as options. A `gpg` group
    /// takes `gpg-key`, and `gpg-homedir` as an option.
    ///
    /// An `ed25519` group and a `gpg` group give one key. The
    /// `secret-key-file` of an `ed25519` group holds one base64 key on one
    /// line. The `secret-key-file` of an `spki` group holds PEM
    /// `PRIVATE KEY` blocks, as `spki_secret_keys` of the `spki` module reads
    /// them. Each block gives one key, in the order of the file. The list
    /// that the call returns is never empty.
    ///
    /// # X.509 chains
    ///
    /// The `certificate-chain-file` of an `spki` group holds PEM
    /// `CERTIFICATE` blocks of one chain, the leaf certificate first, as
    /// `X509Chain::from_pem` of the `spki` module reads them. The key of the
    /// leaf certificate must be the key of one `PRIVATE KEY` block of
    /// `secret-key-file`. The `crl-file` holds PEM `X509 CRL` blocks, as
    /// `x509_crls` of the `spki` module reads them. The group can set
    /// `crl-file` with no `certificate-chain-file`. The signer of the key of
    /// the leaf certificate carries the chain, and the signer of each key of
    /// the group carries the CRLs, through [`Signer::x509_attachments`]. The
    /// writers that the docs of the `sign` module list append them, and so
    /// the summaries that the key groups of `sign-summary` of
    /// `[ex-ostrya server]` sign carry them. A commit signature that the
    /// receive endpoint makes with a key group, for a pushed commit or a
    /// server commit, carries them too. The call
    /// validates no chain and no CRL beyond the form of each file. The chain
    /// file has a ceiling of [`MAX_KEY_FILE`](crate::sign::MAX_KEY_FILE)
    /// bytes, and the CRL file a ceiling of
    /// [`MAX_X509_CRL_FILE`](crate::sign::MAX_X509_CRL_FILE) bytes.
    ///
    /// [`Signer::x509_attachments`]: crate::sign::Signer::x509_attachments
    ///
    /// # Files
    ///
    /// A relative `secret-key-file`, `certificate-chain-file`, or `crl-file`
    /// is relative to the root of `repo`. The call reads each file on the
    /// blocking pool. The value of `gpg-homedir`
    /// goes to GnuPG unchanged, so a relative value is relative to the
    /// current directory of the process. A `gpg` group runs `gpg` at most
    /// two times: the listing of the secret key and the export of its public
    /// certificate.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `name` is empty or holds a `"` or a
    ///   control character. The message is
    ///   `malformed key group name '<name>': the name is not empty, and holds
    ///   no '"' and no control character`.
    /// - [`Error::InvalidInput`] if the config has no such group. The message
    ///   is `the config has no [ex-ostrya key "<name>"] group`.
    /// - [`Error::InvalidFormat`] if the group holds a key that it does not
    ///   take, has no `type`, has an unknown `type` or the type `dummy`, has
    ///   no value or an empty value for a required key, has an empty
    ///   `certificate-chain-file` or `crl-file`, or has a relative path with a
    ///   `..` component. The message names the group. The message of a key of
    ///   another type is `[ex-ostrya key "<name>"] holds '<key>', which a key
    ///   of type <type> does not take`. The message of an unknown `type` and
    ///   of `dummy` is
    ///   `malformed [ex-ostrya key "<name>"] type value '<type>': <reason>`.
    /// - [`Error::Unsupported`] if the group is an `spki` group in a build
    ///   with no `sign-spki` feature, an `spki` group with
    ///   `certificate-chain-file` or `crl-file` in a build with no
    ///   `sign-x509` feature, or a `gpg` group in a build with no `sign-gpg`
    ///   feature.
    /// - [`Error::Signature`] if:
    ///   - the secret key file does not exist, cannot be opened or read, is
    ///     not a regular file, or is larger than
    ///     [`MAX_KEY_FILE`](crate::sign::MAX_KEY_FILE)
    ///   - the secret key file holds no key, or holds more than one key (an
    ///     `ed25519` group)
    ///   - `spki_secret_keys` refuses the secret key file of an `spki` group
    ///   - the chain file or the CRL file does not exist, cannot be opened or
    ///     read, is not a regular file, or is over its ceiling
    ///   - `X509Chain::from_pem` refuses the chain file, or `x509_crls`
    ///     refuses the CRL file
    ///   - the key of the leaf certificate is not the key of a `PRIVATE KEY`
    ///     block of the secret key file. The message is
    ///     `[ex-ostrya key "<name>"]: the certificate chain file '<path>':
    ///     the key of the first certificate is not the key of a PRIVATE KEY
    ///     block of the group`
    ///   - an engine refuses a key
    ///   - the GPG selector names no secret key or more than one
    ///   - `gpg` cannot start, a read of its output or the wait for it fails,
    ///     or `gpg` fails.
    ///
    ///   The message starts with `[ex-ostrya key "<name>"]: `.
    /// - [`Error::Core`] if a value holds a malformed escape sequence, or if
    ///   the key line of an `ed25519` secret key file is not valid base64.
    ///   The message does not name the group.
    ///
    /// # Examples
    ///
    /// Sign a commit with the keys of the group `release`, and skip each key
    /// that signed the commit before:
    ///
    /// ```no_run
    /// use ostrya::sign::SigningKey;
    /// use ostrya::{Checksum, Repo};
    ///
    /// # async fn run(commit: Checksum) -> ostrya::Result<()> {
    /// let repo = Repo::open("/srv/repo".as_ref()).await?;
    /// for key in SigningKey::from_key_group(&repo, "release").await? {
    ///     if !repo.has_signed_commit(&commit, &key).await? {
    ///         repo.sign_commit(&commit, key.signer()).await?;
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn from_key_group(repo: &Repo, name: &str) -> Result<Vec<SigningKey>> {
        if !valid_group_name(name) {
            return Err(Error::InvalidInput(format!(
                "malformed key group name '{name}': the name is not empty, and holds no '\"' \
                 and no control character"
            )));
        }
        let Some(section) = repo.config().section::<key::Group>(name) else {
            return Err(Error::InvalidInput(format!(
                "the config has no [{KEY_PREFIX}{name}\"] group"
            )));
        };
        let spec = parse_key(&section)?;
        build_signers(repo, name, &spec).await
    }
}

/// Reads the key group `section`.
///
/// The checks come in this order: a key that the group does not list, the
/// type, and a key that the type does not take. Then the keys of the type,
/// one key at a time, in the order `secret-key-file`,
/// `certificate-chain-file`, `crl-file`, `gpg-key`: a relative path with a
/// `..` component, an absent or empty key that the type needs, and an empty
/// `certificate-chain-file` or `crl-file`. Last, a type that the build cannot
/// sign with, and a `certificate-chain-file` or a `crl-file` in a build
/// without `sign-x509`.
pub(crate) fn parse_key(section: &Section<'_, key::Group>) -> Result<KeySpec> {
    section.refuse_unknown_keys()?;
    let group = section.header();
    let Some(kind) = section.file_value::<key::Type>()? else {
        return Err(Error::InvalidFormat(format!(
            "[{group}] needs type: ed25519, spki, or gpg"
        )));
    };
    // A key of another type, in the order of the keys of the group.
    let foreign = |held: Option<&str>| -> Result<()> {
        match held {
            Some(name) => Err(Error::InvalidFormat(format!(
                "[{group}] holds '{name}', which a key of type {} does not take",
                kind.as_str()
            ))),
            None => Ok(()),
        }
    };
    let needs = |name: &str| Error::InvalidFormat(format!("[{group}] needs {name}"));
    // A relative path of the secret key file is relative to the repository
    // root, and the value type refuses a `..` component.
    let key_file = || -> Result<String> {
        match section.file_value::<key::SecretKeyFile>()? {
            Some(path) if !path.as_str().is_empty() => Ok(path.into_string()),
            _ => Err(needs(<key::SecretKeyFile as Key<key::Group>>::NAME)),
        }
    };
    let gpg_keys = || held::<key::GpgKey>(section).or_else(|| held::<key::GpgHomedir>(section));
    let x509_keys =
        || held::<key::CertificateChainFile>(section).or_else(|| held::<key::CrlFile>(section));
    // An optional path of an spki key group. The value type refuses a `..`
    // component, and an empty value names no file.
    let x509_file = |path: Option<crate::config::ConfigPath>, name: &str| -> Result<_> {
        match path {
            Some(path) if path.as_str().is_empty() => {
                Err(Error::InvalidFormat(format!("[{group}] {name} is empty")))
            }
            other => Ok(other.map(crate::config::ConfigPath::into_string)),
        }
    };
    match kind {
        SigningKeyType::Ed25519 => {
            foreign(x509_keys().or_else(gpg_keys))?;
            Ok(KeySpec::Ed25519 { file: key_file()? })
        }
        SigningKeyType::Spki => {
            foreign(gpg_keys())?;
            let file = key_file()?;
            let chain = x509_file(
                section.file_value::<key::CertificateChainFile>()?,
                <key::CertificateChainFile as Key<key::Group>>::NAME,
            )?;
            let crl = x509_file(
                section.file_value::<key::CrlFile>()?,
                <key::CrlFile as Key<key::Group>>::NAME,
            )?;
            spki_key(group, file, chain, crl)
        }
        SigningKeyType::Gpg => {
            foreign(held::<key::SecretKeyFile>(section).or_else(x509_keys))?;
            let selector = match section.file_value::<key::GpgKey>()? {
                Some(value) if !value.is_empty() => value,
                _ => return Err(needs(<key::GpgKey as Key<key::Group>>::NAME)),
            };
            gpg_key(group, selector, section.file_value::<key::GpgHomedir>()?)
        }
    }
}

/// Returns the name of the key `K` if the section `section` holds it.
fn held<K: Key<key::Group>>(section: &Section<'_, key::Group>) -> Option<&'static str> {
    section.contains::<K>().then_some(K::NAME)
}

/// Returns the spec of an spki key group whose keys passed their checks.
///
/// A build without the feature `sign-x509` cannot read a chain file or a CRL
/// file, so it refuses a group that names one with [`Error::Unsupported`].
#[cfg(feature = "sign-spki")]
fn spki_key(
    group: &str,
    file: String,
    chain: Option<String>,
    crl: Option<String>,
) -> Result<KeySpec> {
    #[cfg(not(feature = "sign-x509"))]
    if chain.is_some() || crl.is_some() {
        let name = if chain.is_some() {
            "certificate-chain-file"
        } else {
            "crl-file"
        };
        return Err(Error::Unsupported(format!(
            "[{group}] holds '{name}', which this build cannot read; build with the sign-x509 \
             feature"
        )));
    }
    #[cfg(feature = "sign-x509")]
    let _ = group;
    Ok(KeySpec::Spki { file, chain, crl })
}

/// Refuses an spki key group with [`Error::Unsupported`] in a build without
/// the spki engine.
///
/// The build cannot sign with the key, so the refusal stops the build of the
/// key group before a caller signs with the key.
#[cfg(not(feature = "sign-spki"))]
fn spki_key(
    group: &str,
    _file: String,
    _chain: Option<String>,
    _crl: Option<String>,
) -> Result<KeySpec> {
    Err(Error::Unsupported(format!(
        "[{group}] is an spki key, which this build cannot sign with; build with \
         the sign-spki feature"
    )))
}

/// Returns the spec of a GPG key group whose keys passed their checks.
#[cfg(feature = "sign-gpg")]
fn gpg_key(_group: &str, key: String, homedir: Option<String>) -> Result<KeySpec> {
    Ok(KeySpec::Gpg { key, homedir })
}

/// Refuses a GPG key group with [`Error::Unsupported`] in a build without
/// GPG signing.
///
/// The build cannot sign with the key, so the refusal stops the build of the
/// key group before a caller signs with the key.
#[cfg(not(feature = "sign-gpg"))]
fn gpg_key(group: &str, _key: String, _homedir: Option<String>) -> Result<KeySpec> {
    Err(Error::Unsupported(format!(
        "[{group}] is a GPG key, which this build cannot sign with; build with the \
         sign-gpg feature"
    )))
}

/// Builds the signers of the key group `name`.
///
/// An ed25519 or GPG key group gives one signer. An spki key group gives one
/// signer for each `PRIVATE KEY` block of its secret key file, in the order of
/// the file. A relative path of the secret key file is relative to the root of
/// `repo`.
pub(crate) async fn build_signers(
    repo: &Repo,
    name: &str,
    spec: &KeySpec,
) -> Result<Vec<SigningKey>> {
    let label = format!("[{KEY_PREFIX}{name}\"]");
    let in_group = |e: Error| match e {
        Error::Signature(message) => Error::Signature(format!("{label}: {message}")),
        other => other,
    };
    match spec {
        KeySpec::Ed25519 { file } => {
            let line = secret_key_line(repo, file).await.map_err(in_group)?;
            let signer =
                SigningKey::ed25519(&ostrya_core::base64::decode(&line)?).map_err(in_group)?;
            Ok(vec![signer])
        }
        #[cfg(feature = "sign-spki")]
        KeySpec::Spki { file, chain, crl } => {
            let signers = secret_key_blocks(repo, file).await.map_err(in_group)?;
            #[cfg(feature = "sign-x509")]
            if chain.is_some() || crl.is_some() {
                return x509_signers(repo, signers, chain.as_deref(), crl.as_deref())
                    .await
                    .map_err(in_group);
            }
            #[cfg(not(feature = "sign-x509"))]
            let _ = (chain, crl);
            signers
                .into_iter()
                .map(|signer| SigningKey::spki(signer).map_err(in_group))
                .collect()
        }
        #[cfg(feature = "sign-gpg")]
        KeySpec::Gpg { key, homedir } => {
            let mut signer = crate::gpg::GpgSigner::new(key.as_str());
            if let Some(dir) = homedir {
                signer = signer.with_homedir(dir);
            }
            Ok(vec![SigningKey::gpg(signer).await.map_err(in_group)?])
        }
    }
}

/// Returns the one secret key that the file at `path` holds, as its base64
/// line. A relative `path` is relative to the root of `repo`.
///
/// The read runs on the blocking pool.
async fn secret_key_line(repo: &Repo, path: &str) -> Result<String> {
    let repo = repo.clone();
    let path = path.to_owned();
    ostrya_rt::unblock(move || read_secret_key_line(repo.root_dir().as_fd(), &path)).await
}

/// Reads the one secret key line of the file at `path` relative to `root`,
/// the blocking half of `secret_key_line`.
///
/// The read obeys the rule of every key source: a regular file alone, of at
/// most [`MAX_KEY_FILE`](crate::sign::MAX_KEY_FILE) bytes. The function
/// skips blank lines. The file must hold exactly one other line.
fn read_secret_key_line(root: BorrowedFd<'_>, path: &str) -> Result<String> {
    let subject = format!("the secret key file '{path}'");
    let bytes = read_key_file_at(root, Path::new(path), &subject)?;
    let text = key_text(bytes, &subject)?;
    let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty());
    match (lines.next(), lines.next()) {
        (Some(line), None) => Ok(line.to_owned()),
        (None, _) => Err(Error::Signature(format!("{subject} holds no key"))),
        (Some(_), Some(_)) => Err(Error::Signature(format!(
            "{subject} holds more than one key"
        ))),
    }
}

/// Returns the signing keys of the spki signers `signers` with the chain of
/// the file at `chain` and the CRLs of the file at `crl`. A relative path is
/// relative to the root of `repo`.
///
/// The key of the leaf certificate of the chain must be the key of a signer
/// of `signers`. The signer of that key carries the chain, and each signer
/// carries the CRLs. The reads run on the blocking pool.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
async fn x509_signers(
    repo: &Repo,
    signers: Vec<crate::spki::SpkiSigner>,
    chain: Option<&str>,
    crl: Option<&str>,
) -> Result<Vec<SigningKey>> {
    use crate::spki::{X509Chain, x509_crls};

    let repo = repo.clone();
    let (chain, crl) = (chain.map(str::to_owned), crl.map(str::to_owned));
    let (chain, crls) = ostrya_rt::unblock(move || -> Result<_> {
        let root = repo.root_dir().as_fd();
        let chain = match &chain {
            Some(path) => {
                let subject = format!("the certificate chain file '{path}'");
                let bytes = read_key_file_at(root, Path::new(path), &subject)?;
                let chain = X509Chain::from_pem(&bytes, &subject)?;
                Some((chain, subject))
            }
            None => None,
        };
        let crls = match &crl {
            Some(path) => {
                let subject = format!("the CRL file '{path}'");
                let bytes = read_capped_file_at(
                    root,
                    Path::new(path),
                    &subject,
                    crate::sign::MAX_X509_CRL_FILE,
                )?;
                x509_crls(&bytes, &subject)?
            }
            None => Vec::new(),
        };
        Ok((chain, crls))
    })
    .await?;
    if let Some((chain, subject)) = &chain
        && !signers.iter().any(|signer| chain.is_key_of(signer))
    {
        return Err(Error::Signature(format!(
            "{subject}: the key of the first certificate is not the key of a PRIVATE KEY block \
             of the group"
        )));
    }
    signers
        .into_iter()
        .map(|signer| {
            let chains = chain
                .iter()
                .filter(|(chain, _)| chain.is_key_of(&signer))
                .map(|(chain, _)| chain.clone())
                .collect();
            SigningKey::spki_x509(signer.with_x509(chains, crls.clone())?)
        })
        .collect()
}

/// Returns the signers of the spki secret key file at `path`, one for each
/// `PRIVATE KEY` block, in the order of the file. A relative `path` is
/// relative to the root of `repo`.
///
/// The read runs on the blocking pool.
#[cfg(feature = "sign-spki")]
async fn secret_key_blocks(repo: &Repo, path: &str) -> Result<Vec<crate::spki::SpkiSigner>> {
    let repo = repo.clone();
    let path = path.to_owned();
    ostrya_rt::unblock(move || read_secret_key_blocks(repo.root_dir().as_fd(), &path)).await
}

/// Reads the signers of the spki secret key file at `path` relative to
/// `root`, the blocking half of `secret_key_blocks`.
///
/// The read obeys the rule of every key source: a regular file alone, of at
/// most [`MAX_KEY_FILE`](crate::sign::MAX_KEY_FILE) bytes.
/// `spki_secret_keys` reads the blocks and states the rules of the file.
#[cfg(feature = "sign-spki")]
fn read_secret_key_blocks(
    root: BorrowedFd<'_>,
    path: &str,
) -> Result<Vec<crate::spki::SpkiSigner>> {
    let subject = format!("the secret key file '{path}'");
    let bytes = read_key_file_at(root, Path::new(path), &subject)?;
    Ok(crate::spki::spki_secret_keys(bytes, &subject)?)
}