ostrya 0.14.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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! The receive policy of a client group, and the policies of the client
//! groups of a repository.

use std::sync::Arc;

use ostrya_core::Ref;

use crate::access::{AccessModes, AuthItem, ClientAccess, ClientGroup, Namespace, NamespaceRules};
use crate::error::Result;
use crate::remote::{self, RefUpdate};
use crate::repo::Repo;
use crate::sign::SigningKey;

use super::reader;
use super::session::Failure;
use super::{StreamPolicy, TrustedKeys};

/// The rules of one client group for a push session.
///
/// The policy states which refs a session can read and change, how the
/// server verifies the commits of the client, and which keys sign them. It
/// also states the steps after an accepted session: the server signatures of
/// the summary and the summary regeneration.
///
/// [`ReceivePolicies::from_config`] builds one policy for each client group
/// of a repository. A caller can also build a policy in code.
///
/// The [`Default`] policy has no allow item. It opens no push session, so
/// each `Hello` gets `ref-denied`.
///
/// # Rights
///
/// [`rights`](ReceivePolicy::rights) gives the effective rights of a ref in
/// its namespace. A plain `NAME` and `@ID:NAME` with `ID` the collection id
/// of the repository are in the local refs. `@ID:NAME` with each other `ID`
/// is in the namespace of the collection `ID`. A session applies the rights
/// in this way:
///
/// - Each ref of `Hello` needs `r` in its namespace. A remote ref
///   `REMOTE:NAME` has no right, so a push session never reads or writes
///   one.
/// - A session opens only if an allow item of a namespace has `w`, `c`, `t`,
///   or `d`.
/// - An update that writes a commit needs `w` or `t`. With `t` and no `w`,
///   the update can create the ref and cannot write to a ref that exists,
///   also when the commit is the current one.
/// - An update with `w` is a fast-forward. With `w`, `d`, and `force` in the
///   request, it can also be a non-fast-forward update.
/// - A delete of a ref that exists needs `d`. A delete of an absent ref
///   changes nothing.
/// - A server commit needs `c` on its branch. With `orphan` on a branch that
///   exists, it needs `c` and `d`. Each tag of a server commit needs `t` or
///   `w` in the namespace of the tag, and the tag must not exist, also with
///   `w`. A bound name of a server commit gets no ref and needs no right.
#[derive(Debug, Clone, Default)]
pub struct ReceivePolicy {
    /// The allow items and the deny items of the group, for each namespace.
    pub rules: NamespaceRules,
    /// The signatures that a new commit must carry.
    ///
    /// The verification applies to each new commit of a ref update that a
    /// client builds and pushes. A server commit gets no verification. A
    /// commit that no update names gets no verification, a staged parent and
    /// an attachment included. The checksum of an attachment is in field 2 of
    /// a commit. A new commit is that commit, or binds it through the parent
    /// checksums of its history, and the signatures of the new commit cover
    /// these checksums.
    pub verify: ReceiveVerify,
    /// The switch that accepts a new commit with no signature.
    ///
    /// The switch applies only with [`ReceiveVerify::Keys`], and only to a
    /// new commit that the client built, which
    /// [`verify`](ReceivePolicy::verify) applies to. A commit has no
    /// signature if its detached metadata holds no blob under
    /// `ostree.gpgsigs`, `ostree.sign.ed25519`, `ostree.sign.spki`, and
    /// `ostree.sign.dummy`. A commit with a blob under one of these keys must
    /// pass the verification on each axis of the keys, also when the switch
    /// is `true`.
    pub allow_unsigned: bool,
    /// The keys that the server signs each new commit with, in order.
    ///
    /// An spki key group gives one key for each block of its secret key file,
    /// so the list can hold more keys than the client group names groups.
    ///
    /// A new commit is a commit that becomes the new value of a ref. A server
    /// commit is a new commit too. The server signs no other commit, a staged
    /// parent and an attachment included. The server signature on a new
    /// commit covers its field 2 and its parent checksum.
    pub signers: Vec<Arc<SigningKey>>,
    /// The switch that accepts privileged content in a `bare` repository.
    ///
    /// Privileged content is a setuid or setgid mode bit, or the
    /// `security.capability` or `security.selinux` extended attribute.
    pub allow_privileged: bool,
    /// The switch that skips the check of `ostree.ref-binding` of each new
    /// commit that the client built.
    ///
    /// With `true`, the name of a ref update need not be in the
    /// `ostree.ref-binding` of its new commit. The check of
    /// `ostree.collection-binding` stays on. A server commit gets the
    /// bindings of the server, so the switch does not apply to it.
    pub disable_verify_bindings: bool,
    /// The keys that the server signs each regenerated summary with, in
    /// order. An spki key group gives one key for each block of its secret
    /// key file.
    pub summary_signers: Vec<Arc<SigningKey>>,
    /// The switch that regenerates the summary of each auth item, as
    /// [`Repo::regenerate_summaries`](crate::Repo::regenerate_summaries)
    /// writes them, after a session that writes a ref.
    pub update_summary: bool,
    /// The name of the client group of the policy.
    ///
    /// [`ReceivePolicies::from_config`] sets the name of each group. A policy
    /// built in code can have `None`. A session copies the name into
    /// [`ReceiveReport::group`](super::ReceiveReport::group).
    pub group: Option<String>,
}

/// The signatures that a received commit must carry.
#[derive(Debug, Clone, Default)]
pub enum ReceiveVerify {
    /// No signature verification.
    #[default]
    Off,
    /// A valid signature on each axis of the trusted keys.
    ///
    /// # Trust groups
    ///
    /// A trust group, `[ex-ostrya trust "NAME"]`, uses the key names of a
    /// remote section:
    ///
    /// - `gpgkeypath` for the GPG axis
    /// - `verification-<engine>-key` and `verification-<engine>-file` for the
    ///   sign-api axis
    ///
    /// `gpg-verify` and `sign-verify` turn on the axes. In a trust group,
    /// `gpg-verify` has the default `false`.
    ///
    /// A trust group trusts these keys alone. It reads no system key store, no
    /// revoked set, no per-remote keyring, and no global trusted directory. A
    /// server verifies a commit against the keys that the group names, and
    /// against no other key.
    Keys(Arc<TrustedKeys>),
}

impl ReceivePolicy {
    /// Returns the effective rights of the ref `r`.
    ///
    /// For a local ref `NAME`, the result is [`NamespaceRules::rights`] of
    /// `NAME` in [`Namespace::Local`]. For a collection ref `@ID:NAME`, it is
    /// the rights of `NAME` in the collection `ID`. A remote ref
    /// `REMOTE:NAME` has no right, because a push session does not write
    /// remote refs.
    ///
    /// The call reads `r` as it is. A session maps `@ID:NAME` with `ID` the
    /// collection id of the repository to the local ref `NAME` before it
    /// calls it.
    pub fn rights(&self, r: &Ref) -> AccessModes {
        match r {
            Ref::Local { name } => self.rules.rights(&Namespace::Local, name),
            Ref::Collection { id, name } => {
                self.rules.rights(&Namespace::Collection(id.clone()), name)
            }
            Ref::Remote { .. } => AccessModes::NONE,
        }
    }
}

/// The receive policy of each client group of a repository.
///
/// [`from_config`](ReceivePolicies::from_config) builds the value.
#[derive(Debug, Clone)]
pub struct ReceivePolicies {
    access: Arc<ClientAccess>,
    /// The policy of each group of `access`, in the same order.
    policies: Vec<Arc<ReceivePolicy>>,
}

impl ReceivePolicies {
    /// Reads the client groups of the configuration of `repo` and builds the
    /// receive policy of each group.
    ///
    /// [`ClientAccess::from_config`] reads the client groups and
    /// `[ex-ostrya server]`. A config with no client group has the implicit
    /// group, and it gets a policy. Then the call reads each
    /// `[ex-ostrya trust "NAME"]` and each `[ex-ostrya key "NAME"]` group,
    /// and builds each one once, in file order, also a group that no client
    /// group names. So a key source that the policies cannot use fails the
    /// call.
    ///
    /// The policy of a group takes these values:
    ///
    /// - [`rules`](ReceivePolicy::rules) from `allow` and `deny`
    /// - [`verify`](ReceivePolicy::verify) from `verify`, with the keys of the
    ///   trust group
    /// - [`allow_unsigned`](ReceivePolicy::allow_unsigned) from
    ///   `allow-unsigned`, or its default
    /// - [`signers`](ReceivePolicy::signers) from `sign`
    /// - [`allow_privileged`](ReceivePolicy::allow_privileged) from
    ///   `allow-privileged`
    /// - [`disable_verify_bindings`](ReceivePolicy::disable_verify_bindings)
    ///   from `disable-verify-bindings`
    /// - [`summary_signers`](ReceivePolicy::summary_signers) from
    ///   `sign-summary` of `[ex-ostrya server]`
    /// - [`update_summary`](ReceivePolicy::update_summary) from
    ///   `[core] auto-update-summary` and its alias, as
    ///   [`auto_update_summary`](crate::RepoConfig::auto_update_summary) reads
    ///   them.
    ///
    /// # Trust groups and key groups
    ///
    /// A trust group takes `gpg-verify`, `gpgkeypath`, `sign-verify`,
    /// `verification-ENGINE-key`, and `verification-ENGINE-file`, in the value
    /// forms of a remote section.
    ///
    /// A key group takes `type`, which is `ed25519`, `spki`, or `gpg`. An
    /// `ed25519` or `spki` key group takes `secret-key-file`. A `gpg` key group
    /// takes `gpg-key`, and `gpg-homedir` as an option.
    ///
    /// The `secret-key-file` of an `ed25519` key group holds one base64 key on
    /// one line. The `secret-key-file` of an `spki` key group holds PEM
    /// `PRIVATE KEY` blocks, as `spki_secret_keys` of the `spki` module reads
    /// them. Each block gives one key.
    ///
    /// # Errors
    ///
    /// - Each error of [`ClientAccess::from_config`].
    /// - [`Error::InvalidFormat`](crate::Error::InvalidFormat) if:
    ///   - a trust group or a key group holds a key that it does not take
    ///   - a key has no effect
    ///   - a trust group turns on no signature verification
    ///   - a trust group names an engine other than `ed25519` or `spki`, or
    ///     sets `gpg-verify=true` and its `gpgkeypath` names no keyring or
    ///     holds an empty entry
    ///   - a key group has no `type`, an unknown `type`, the type `dummy`, or
    ///     no value for a required key.
    /// - [`Error::Unsupported`](crate::Error::Unsupported) if a group names a
    ///   signing or verification engine that this build does not have.
    /// - [`Error::Signature`](crate::Error::Signature) if:
    ///   - a key source cannot be read
    ///   - a secret key file does not exist
    ///   - a secret key file holds no key, or holds more than one key (an
    ///     `ed25519` key group)
    ///   - `spki_secret_keys` refuses the secret key file of an `spki` key
    ///     group
    ///   - an engine refuses a key
    ///   - a GPG selector names no secret key or more than one, or `gpg` fails
    ///   - an engine that `sign-verify` names has no trusted key, or no engine
    ///     has a trusted key
    ///   - the keyrings that a trust group names hold no certificate.
    /// - [`Error::Core`](crate::Error::Core) if a boolean value is malformed,
    ///   a string value holds a malformed escape sequence, or a key is not
    ///   valid base64.
    /// - [`Error::Io`](crate::Error::Io) if a directory of keys cannot be
    ///   listed, or if the read of the output of `gpg` or the wait for `gpg`
    ///   fails.
    pub async fn from_config(repo: &Repo) -> Result<ReceivePolicies> {
        let (access, policies) = reader::read(repo).await?;
        Ok(ReceivePolicies {
            access: Arc::new(access),
            policies,
        })
    }

    /// Returns the client groups and the server settings that the policies
    /// come from. A clone of the `Arc` shares them.
    pub fn access(&self) -> &Arc<ClientAccess> {
        &self.access
    }

    /// Returns the policy of the client group `group`, or `None` if no group
    /// has this name.
    ///
    /// `group` is the quoted part of the group name, as
    /// [`ClientGroup::name`](crate::access::ClientGroup::name) returns it.
    pub fn get(&self, group: &str) -> Option<&Arc<ReceivePolicy>> {
        self.access
            .groups()
            .iter()
            .position(|held| held.name() == group)
            .map(|i| &self.policies[i])
    }

    /// Returns the client group that carries `item`, with its policy, or
    /// `None`.
    ///
    /// [`ClientAccess::select`] states the selection.
    pub fn select(&self, item: &AuthItem) -> Option<(&ClientGroup, &Arc<ReceivePolicy>)> {
        self.access
            .select_index(item)
            .map(|i| (&self.access.groups()[i], &self.policies[i]))
    }
}

/// The rule that the commit of a session applies to one ref update.
pub(super) struct UpdateRule<'a> {
    /// `true` if the update can create its ref and cannot write a commit to
    /// a ref that exists.
    pub(super) create_only: bool,
    /// `true` if the update can delete a ref that exists.
    pub(super) allow_delete: bool,
    /// `true` if the update can be a non-fast-forward update, when the client
    /// asks for one.
    pub(super) allow_non_fast_forward: bool,
    /// The signatures that the new commit must carry.
    pub(super) verify: &'a ReceiveVerify,
    /// `true` if a new commit with no signature passes the verification of
    /// `verify`.
    pub(super) allow_unsigned: bool,
    /// The keys that the server signs the new commit with.
    pub(super) signers: &'a [Arc<SigningKey>],
}

/// The rule that the commit of a session applies to a server commit.
pub(super) struct ServerCommitRule<'a> {
    /// `true` if an `orphan` server commit can replace a branch that exists.
    pub(super) allow_orphan_over_branch: bool,
    /// The keys that the server signs the commit with.
    pub(super) signers: &'a [Arc<SigningKey>],
}

/// The rules that a session applies: the policy of a client group, or the
/// policy of a one-way stream.
pub(super) trait SessionPolicy: Send + Sync {
    /// Returns `true` if the session accepts privileged content in a `bare`
    /// repository.
    fn privileged_allowed(&self) -> bool;

    /// Checks the refs of `Hello`, each in its canonical form, before the
    /// session opens, with no I/O.
    fn check_hello(&self, refs: &[Ref]) -> std::result::Result<(), Failure>;

    /// Returns the rule of `update` of the ref `name`, in its canonical form
    /// in a repository whose `[core] collection-id` is `own`, or the
    /// `ref-denied` refusal of the update.
    fn rule(
        &self,
        name: &Ref,
        update: &RefUpdate,
        own: Option<&str>,
    ) -> std::result::Result<UpdateRule<'_>, Failure>;

    /// Returns the rule of a server commit on `branch` that creates `tags`,
    /// each in its canonical form, or the `ref-denied` refusal of the server
    /// commit.
    fn server_commit_rule(
        &self,
        branch: &Ref,
        tags: &[Ref],
    ) -> std::result::Result<ServerCommitRule<'_>, Failure>;

    /// Returns `true` if the session checks the `ostree.ref-binding` of each
    /// new commit that the client built.
    fn verifies_ref_bindings(&self) -> bool;

    /// Returns `true` if the session regenerates the summary after it writes
    /// a ref.
    fn regenerates_summary(&self) -> bool;

    /// Returns the keys that sign each regenerated summary.
    fn summary_keys(&self) -> &[Arc<SigningKey>];

    /// Returns the name of the client group of the session, for the report.
    fn group(&self) -> Option<&str>;
}

fn ref_denied(message: String) -> Failure {
    Failure::Wire(remote::Error::RefDenied(message))
}

impl SessionPolicy for ReceivePolicy {
    fn privileged_allowed(&self) -> bool {
        self.allow_privileged
    }

    /// Refuses a policy that opens no push session, and a ref without `r`
    /// in its namespace.
    fn check_hello(&self, refs: &[Ref]) -> std::result::Result<(), Failure> {
        if !self.rules.opens_push_session() {
            return Err(ref_denied(
                "the policy of the session opens no push session: no allow item has the \
                 mode w, c, t, or d"
                    .into(),
            ));
        }
        for name in refs {
            if let Ref::Remote { .. } = name {
                return Err(ref_denied(format!(
                    "ref '{name}' is a remote ref, which a push session does not read or write"
                )));
            }
            if !self.rights(name).contains(AccessModes::READ) {
                return Err(ref_denied(format!("the policy gives no r on ref '{name}'")));
            }
        }
        Ok(())
    }

    /// Refuses a remote ref, and a write of a commit without `w` or `t`. The
    /// rule of a delete comes from `d`, under the update lock. The rules of
    /// the policy already read `@OWN:` as the local refs, so the call does
    /// not use `own`.
    fn rule(
        &self,
        name: &Ref,
        update: &RefUpdate,
        _own: Option<&str>,
    ) -> std::result::Result<UpdateRule<'_>, Failure> {
        if let Ref::Remote { .. } = name {
            return Err(ref_denied(format!(
                "ref '{name}' is a remote ref, which a push session does not write"
            )));
        }
        let rights = self.rights(name);
        let write = rights.contains(AccessModes::WRITE);
        let tag = rights.contains(AccessModes::TAG);
        if update.new.is_some() && !write && !tag {
            return Err(ref_denied(format!(
                "the policy gives no w or t on ref '{name}'"
            )));
        }
        let delete = rights.contains(AccessModes::DELETE);
        Ok(UpdateRule {
            create_only: tag && !write,
            allow_delete: delete,
            allow_non_fast_forward: write && delete,
            verify: &self.verify,
            allow_unsigned: self.allow_unsigned,
            signers: &self.signers,
        })
    }

    /// Refuses a remote ref, a branch without `c`, and a tag without `t` or
    /// `w`. The rule of `orphan` on a branch that exists comes from `d`,
    /// under the update lock.
    fn server_commit_rule(
        &self,
        branch: &Ref,
        tags: &[Ref],
    ) -> std::result::Result<ServerCommitRule<'_>, Failure> {
        for name in std::iter::once(branch).chain(tags) {
            if let Ref::Remote { .. } = name {
                return Err(ref_denied(format!(
                    "ref '{name}' is a remote ref, which a push session does not write"
                )));
            }
        }
        let rights = self.rights(branch);
        if !rights.contains(AccessModes::COMMIT) {
            return Err(ref_denied(format!(
                "the policy gives no c on ref '{branch}'"
            )));
        }
        for tag in tags {
            let tag_rights = self.rights(tag);
            if !tag_rights.contains(AccessModes::TAG) && !tag_rights.contains(AccessModes::WRITE) {
                return Err(ref_denied(format!(
                    "the policy gives no t or w on ref '{tag}'"
                )));
            }
        }
        Ok(ServerCommitRule {
            allow_orphan_over_branch: rights.contains(AccessModes::DELETE),
            signers: &self.signers,
        })
    }

    fn verifies_ref_bindings(&self) -> bool {
        !self.disable_verify_bindings
    }

    fn regenerates_summary(&self) -> bool {
        self.update_summary
    }

    fn summary_keys(&self) -> &[Arc<SigningKey>] {
        &self.summary_signers
    }

    fn group(&self) -> Option<&str> {
        self.group.as_deref()
    }
}

impl SessionPolicy for StreamPolicy {
    fn privileged_allowed(&self) -> bool {
        self.allow_privileged
    }

    /// A one-way stream checks its refs at `Commit` alone.
    fn check_hello(&self, _refs: &[Ref]) -> std::result::Result<(), Failure> {
        Ok(())
    }

    /// Refuses an update that no rule covers and an update whose rule
    /// refuses it. The rule takes no server key.
    fn rule(
        &self,
        name: &Ref,
        _update: &RefUpdate,
        own: Option<&str>,
    ) -> std::result::Result<UpdateRule<'_>, Failure> {
        match self.rule_for(name, own) {
            Some(rule) if rule.accept => Ok(UpdateRule {
                create_only: false,
                allow_delete: rule.allow_delete,
                allow_non_fast_forward: rule.allow_non_fast_forward,
                verify: &rule.verify,
                allow_unsigned: false,
                signers: &[],
            }),
            Some(_) => Err(ref_denied(format!(
                "the policy refuses updates of ref '{name}'"
            ))),
            None => Err(ref_denied(format!(
                "no rule of the policy covers the ref '{name}'"
            ))),
        }
    }

    /// A one-way stream carries no server commit.
    fn server_commit_rule(
        &self,
        _branch: &Ref,
        _tags: &[Ref],
    ) -> std::result::Result<ServerCommitRule<'_>, Failure> {
        Err(Failure::Wire(remote::Error::Protocol(
            "a one-way stream carries no server commit".into(),
        )))
    }

    fn verifies_ref_bindings(&self) -> bool {
        !self.disable_verify_bindings
    }

    /// A one-way stream does not regenerate the summary.
    fn regenerates_summary(&self) -> bool {
        false
    }

    /// A one-way stream does not regenerate the summary.
    fn summary_keys(&self) -> &[Arc<SigningKey>] {
        &[]
    }

    /// A one-way stream has no client group.
    fn group(&self) -> Option<&str> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::access::{AccessRules, AllowItem};
    use crate::remote::Expected;

    fn rules(allow: &[&str]) -> AccessRules {
        AccessRules {
            allow: allow.iter().map(|t| AllowItem::parse(t).unwrap()).collect(),
            deny: Vec::new(),
        }
    }

    fn policy(allow: &[&str]) -> ReceivePolicy {
        ReceivePolicy {
            rules: rules(allow).into(),
            ..ReceivePolicy::default()
        }
    }

    fn local(name: &str) -> Ref {
        Ref::local(name)
    }

    fn refs(names: &[&str]) -> Vec<Ref> {
        names.iter().map(|n| n.parse().unwrap()).collect()
    }

    fn update(name: &str, new: bool) -> RefUpdate {
        RefUpdate {
            name: name.into(),
            expected: Expected::Any,
            new: new.then(|| ostrya_core::Checksum::from_bytes([1; 32])),
        }
    }

    fn accepted<T>(result: std::result::Result<T, Failure>) -> T {
        match result {
            Ok(value) => value,
            Err(_) => panic!("refused"),
        }
    }

    fn denied<T>(result: std::result::Result<T, Failure>) -> String {
        match result {
            Err(Failure::Wire(remote::Error::RefDenied(message))) => message,
            Err(_) => panic!("another failure"),
            Ok(_) => panic!("accepted"),
        }
    }

    /// A remote ref has no right, also under an item that matches each ref.
    /// The rules alone read `origin:main` as one part, which `**` matches.
    #[test]
    fn a_remote_ref_has_no_right() {
        let policy = policy(&["rwctd:**"]);
        let remote = Ref::remote("origin", "main");
        assert_eq!(policy.rights(&local("main")).to_string(), "rwctd");
        assert_eq!(
            policy
                .rules
                .rights(&Namespace::Local, "origin:main")
                .to_string(),
            "rwctd"
        );
        assert_eq!(policy.rights(&remote), AccessModes::NONE);
        let message = denied(policy.check_hello(std::slice::from_ref(&remote)));
        assert!(message.contains("remote ref"), "{message}");
        let message = denied(policy.rule(&remote, &update("origin:main", true), None));
        assert!(message.contains("remote ref"), "{message}");
    }

    /// `Hello` needs a push mode in an allow item and `r` on each ref.
    #[test]
    fn hello_needs_a_push_mode_and_read() {
        denied(ReceivePolicy::default().check_hello(&[]));
        denied(policy(&["r:**"]).check_hello(&refs(&["a"])));
        denied(policy(&["d:a"]).check_hello(&refs(&["a"])));
        accepted(policy(&["rd:a"]).check_hello(&refs(&["a"])));
        accepted(policy(&["r:**", "w:a"]).check_hello(&refs(&["a", "b"])));
        let message = denied(policy(&["w:a"]).check_hello(&refs(&["a", "b"])));
        assert!(message.contains("'b'"), "{message}");
    }

    /// A push mode in the rules of any namespace opens a session. Each ref
    /// of `Hello` needs `r` in its own namespace, and the rules of the other
    /// namespaces give no right there. One `Hello` can name refs of more
    /// than one namespace.
    #[test]
    fn each_ref_reads_the_rights_of_its_namespace() {
        let mut both = policy(&["r:main"]);
        both.rules
            .collections
            .insert("org.example.Os".into(), rules(&["w:os/**"]));
        accepted(both.check_hello(&refs(&["main"])));
        accepted(both.check_hello(&refs(&["@org.example.Os:os/a"])));
        accepted(both.check_hello(&refs(&["main", "@org.example.Os:os/a"])));
        let message = denied(both.check_hello(&refs(&["@org.example.Os:main"])));
        assert!(
            message.contains("no r on ref '@org.example.Os:main'"),
            "{message}"
        );
        denied(both.check_hello(&refs(&["@org.example.Other:os/a"])));
        denied(both.check_hello(&refs(&["os/a"])));

        let local_only = policy(&["w:**"]);
        denied(local_only.check_hello(&refs(&["@org.example.Os:main"])));
        accepted(local_only.check_hello(&[]));
        let os = Ref::collection("org.example.Os", "os/a");
        let rule = accepted(both.rule(&os, &update("@org.example.Os:os/a", true), None));
        assert!(!rule.create_only);
        denied(both.rule(&local("os/a"), &update("os/a", true), None));
        let other = Ref::collection("org.example.Other", "os/a");
        denied(both.rule(&other, &update("@org.example.Other:os/a", true), None));
    }

    /// A write needs `w` or `t`, and the modes give the rule of an update.
    #[test]
    fn the_modes_give_the_rule_of_an_update() {
        let a = local("a");
        denied(policy(&["rd:a"]).rule(&a, &update("a", true), None));
        let delete = policy(&["rd:a"]);
        let rule = accepted(delete.rule(&a, &update("a", false), None));
        assert!(rule.allow_delete && !rule.allow_non_fast_forward);
        let tag = policy(&["t:a"]);
        let rule = accepted(tag.rule(&a, &update("a", true), None));
        assert!(rule.create_only && !rule.allow_delete);
        let write_tag = policy(&["wt:a"]);
        let rule = accepted(write_tag.rule(&a, &update("a", true), None));
        assert!(!rule.create_only && !rule.allow_non_fast_forward);
        let forced = policy(&["w:a", "d:a"]);
        let rule = accepted(forced.rule(&a, &update("a", true), None));
        assert!(rule.allow_non_fast_forward && rule.allow_delete);
    }

    /// A server commit needs `c` on its branch and `t` or `w` on each tag.
    /// `d` on the branch allows `orphan` over a branch that exists. A deny
    /// item takes each right, and a bound name needs none.
    #[test]
    fn the_modes_give_the_rule_of_a_server_commit() {
        let main = local("main");
        let commit = policy(&["c:main"]);
        let rule = accepted(commit.server_commit_rule(&main, &[]));
        assert!(!rule.allow_orphan_over_branch);
        let orphan = policy(&["cd:main"]);
        let rule = accepted(orphan.server_commit_rule(&main, &[]));
        assert!(rule.allow_orphan_over_branch);
        let message = denied(policy(&["wtd:main"]).server_commit_rule(&main, &[]));
        assert!(message.contains("no c on ref 'main'"), "{message}");
        let message = denied(policy(&["r:**"]).server_commit_rule(&main, &[]));
        assert!(message.contains("no c"), "{message}");

        let both = policy(&["c:main", "t:v1", "w:v2"]);
        accepted(both.server_commit_rule(&main, &refs(&["v1", "v2"])));
        let message = denied(both.server_commit_rule(&main, &refs(&["v1", "v3"])));
        assert!(message.contains("no t or w on ref 'v3'"), "{message}");
        let message =
            denied(policy(&["c:main", "cd:v1"]).server_commit_rule(&main, &refs(&["v1"])));
        assert!(message.contains("'v1'"), "{message}");

        let denying = ReceivePolicy {
            rules: AccessRules {
                allow: vec![AllowItem::parse("ctwd:**").unwrap()],
                deny: vec![ostrya_core::RefPattern::parse("v1").unwrap()],
            }
            .into(),
            ..ReceivePolicy::default()
        };
        accepted(denying.server_commit_rule(&main, &refs(&["v2"])));
        let message = denied(denying.server_commit_rule(&main, &refs(&["v1"])));
        assert!(message.contains("'v1'"), "{message}");
        let message = denied(denying.server_commit_rule(&local("v1"), &[]));
        assert!(message.contains("no c"), "{message}");

        let remote = Ref::remote("origin", "main");
        let message = denied(policy(&["c:**"]).server_commit_rule(&remote, &[]));
        assert!(message.contains("remote ref"), "{message}");
    }

    /// The rights of a tag of a server commit come from the namespace of the
    /// tag. A tag of a collection needs `t` or `w` in that collection.
    #[test]
    fn a_tag_takes_the_rights_of_its_namespace() {
        let mut both = policy(&["c:a", "t:**"]);
        both.rules
            .collections
            .insert("org.example.Os".into(), rules(&["c:a", "w:v1"]));
        let branch = Ref::collection("org.example.Os", "a");
        accepted(both.server_commit_rule(&branch, &refs(&["@org.example.Os:v1"])));
        let message = denied(both.server_commit_rule(&branch, &refs(&["@org.example.Os:v2"])));
        assert!(
            message.contains("no t or w on ref '@org.example.Os:v2'"),
            "{message}"
        );
        accepted(both.server_commit_rule(&local("a"), &refs(&["v2"])));
    }
}