routing_test_helpers/
policy.rs

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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::Error;
use assert_matches::assert_matches;
use async_trait::async_trait;
use cm_config::{
    AllowlistEntry, AllowlistEntryBuilder, CapabilityAllowlistKey, CapabilityAllowlistSource,
    ChildPolicyAllowlists, DebugCapabilityAllowlistEntry, DebugCapabilityKey, JobPolicyAllowlists,
    SecurityPolicy,
};
use cm_rust::{CapabilityTypeName, ProtocolDecl, StorageDecl, StorageDirectorySource};
use cm_types::Name;
use fidl_fuchsia_component_decl as fdecl;
use moniker::{ExtendedMoniker, Moniker};
use routing::capability_source::{
    BuiltinSource, CapabilitySource, CapabilityToCapabilitySource, ComponentCapability,
    ComponentSource, FrameworkSource, InternalCapability, NamespaceSource,
};
use routing::component_instance::ComponentInstanceInterface;
use routing::policy::GlobalPolicyChecker;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// These GlobalPolicyChecker tests are run under multiple contexts, e.g. both on Fuchsia under
/// component_manager and on the build host under cm_fidl_analyzer. This macro helps ensure that all
/// tests are run in each context.
#[macro_export]
macro_rules! instantiate_global_policy_checker_tests {
    ($fixture_impl:path) => {
        // New GlobalPolicyCheckerTest tests must be added to this list to run.
        instantiate_global_policy_checker_tests! {
            $fixture_impl,
            global_policy_checker_can_route_capability_framework_cap,
            global_policy_checker_can_route_capability_namespace_cap,
            global_policy_checker_can_route_capability_component_cap,
            global_policy_checker_can_route_capability_capability_cap,
            global_policy_checker_can_route_debug_capability_capability_cap,
            global_policy_checker_can_route_debug_capability_with_realm_allowlist_entry,
            global_policy_checker_can_route_debug_capability_with_collection_allowlist_entry,
            global_policy_checker_can_route_capability_builtin_cap,
            global_policy_checker_can_route_capability_with_realm_allowlist_entry,
            global_policy_checker_can_route_capability_with_collection_allowlist_entry,
        }
    };
    ($fixture_impl:path, $test:ident, $($remaining:ident),+ $(,)?) => {
        instantiate_global_policy_checker_tests! { $fixture_impl, $test }
        instantiate_global_policy_checker_tests! { $fixture_impl, $($remaining),+ }
    };
    ($fixture_impl:path, $test:ident) => {
        fn $test() -> Result<(), Error> {
            let mut executor = fuchsia_async::LocalExecutor::new();
            executor.run_singlethreaded(<$fixture_impl as Default>::default().$test())
        }
    };
}

// Tests `GlobalPolicyChecker` for implementations of `ComponentInstanceInterface`.
#[async_trait]
pub trait GlobalPolicyCheckerTest<C>
where
    C: ComponentInstanceInterface + 'static,
{
    // Creates a `ComponentInstanceInterface` with the given `Moniker`.
    async fn make_component(&self, moniker: Moniker) -> Arc<C>;

    // Tests `GlobalPolicyChecker::can_route_capability()` for framework capability sources.
    async fn global_policy_checker_can_route_capability_framework_cap(&self) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentInstance(
                    Moniker::try_from(vec!["foo", "bar"]).unwrap(),
                ),
                source_name: "fuchsia.component.Realm".parse().unwrap(),
                source: CapabilityAllowlistSource::Framework,
                capability: CapabilityTypeName::Protocol,
            },
            vec![
                AllowlistEntryBuilder::new().exact("foo").exact("bar").build(),
                AllowlistEntryBuilder::new().exact("foo").exact("bar").exact("baz").build(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let component = self.make_component(vec!["foo:0", "bar:0"].try_into().unwrap()).await;

        let protocol_capability = CapabilitySource::Framework(FrameworkSource {
            capability: InternalCapability::Protocol("fuchsia.component.Realm".parse().unwrap()),
            moniker: component.moniker().clone(),
        });
        let valid_path_0 = Moniker::try_from(vec!["foo", "bar"]).unwrap();
        let valid_path_1 = Moniker::try_from(vec!["foo", "bar", "baz"]).unwrap();
        let invalid_path_0 = Moniker::try_from(vec!["foobar"]).unwrap();
        let invalid_path_1 = Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap();

        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_0),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_1),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_0),
            Err(_)
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_1),
            Err(_)
        );
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for namespace capability sources.
    async fn global_policy_checker_can_route_capability_namespace_cap(&self) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentManager,
                source_name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
            },
            vec![
                AllowlistEntryBuilder::new().exact("root").build(),
                AllowlistEntryBuilder::new().exact("root").exact("bootstrap").build(),
                AllowlistEntryBuilder::new().exact("root").exact("core").build(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));

        let protocol_capability = CapabilitySource::Namespace(NamespaceSource {
            capability: ComponentCapability::Protocol(ProtocolDecl {
                name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source_path: Some("/svc/fuchsia.kernel.MmioResource".parse().unwrap()),
                delivery: Default::default(),
            }),
        });
        let valid_path_0 = Moniker::try_from(vec!["root"]).unwrap();
        let valid_path_2 = Moniker::try_from(vec!["root", "core"]).unwrap();
        let valid_path_1 = Moniker::try_from(vec!["root", "bootstrap"]).unwrap();
        let invalid_path_0 = Moniker::try_from(vec!["foobar"]).unwrap();
        let invalid_path_1 = Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap();

        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_0),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_1),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_2),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_0),
            Err(_)
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_1),
            Err(_)
        );
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for component capability sources.
    async fn global_policy_checker_can_route_capability_component_cap(&self) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentInstance(
                    Moniker::try_from(vec!["foo"]).unwrap(),
                ),
                source_name: "fuchsia.foo.FooBar".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
            },
            vec![
                AllowlistEntryBuilder::new().exact("foo").build(),
                AllowlistEntryBuilder::new().exact("root").exact("bootstrap").build(),
                AllowlistEntryBuilder::new().exact("root").exact("core").build(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let component = self.make_component(vec!["foo:0"].try_into().unwrap()).await;

        let protocol_capability = CapabilitySource::Component(ComponentSource {
            capability: ComponentCapability::Protocol(ProtocolDecl {
                name: "fuchsia.foo.FooBar".parse().unwrap(),
                source_path: Some("/svc/fuchsia.foo.FooBar".parse().unwrap()),
                delivery: Default::default(),
            }),
            moniker: component.moniker().clone(),
        });
        let valid_path_0 = Moniker::try_from(vec!["root", "bootstrap"]).unwrap();
        let valid_path_1 = Moniker::try_from(vec!["root", "core"]).unwrap();
        let invalid_path_0 = Moniker::try_from(vec!["foobar"]).unwrap();
        let invalid_path_1 = Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap();

        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_0),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_1),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_0),
            Err(_)
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_1),
            Err(_)
        );
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for capability sources of type `Capability`.
    async fn global_policy_checker_can_route_capability_capability_cap(&self) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentInstance(
                    Moniker::try_from(vec!["foo"]).unwrap(),
                ),
                source_name: "cache".parse().unwrap(),
                source: CapabilityAllowlistSource::Capability,
                capability: CapabilityTypeName::Storage,
            },
            vec![
                AllowlistEntryBuilder::new().exact("foo").build(),
                AllowlistEntryBuilder::new().exact("root").exact("bootstrap").build(),
                AllowlistEntryBuilder::new().exact("root").exact("core").build(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let component = self.make_component(vec!["foo:0"].try_into().unwrap()).await;

        let protocol_capability = CapabilitySource::Capability(CapabilityToCapabilitySource {
            source_capability: ComponentCapability::Storage(StorageDecl {
                backing_dir: "cache".parse().unwrap(),
                name: "cache".parse().unwrap(),
                source: StorageDirectorySource::Parent,
                subdir: Default::default(),
                storage_id: fdecl::StorageId::StaticInstanceIdOrMoniker,
            }),
            moniker: component.moniker().clone(),
        });
        let valid_path_0 = Moniker::try_from(vec!["root", "bootstrap"]).unwrap();
        let valid_path_1 = Moniker::try_from(vec!["root", "core"]).unwrap();
        let invalid_path_0 = Moniker::try_from(vec!["foobar"]).unwrap();
        let invalid_path_1 = Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap();

        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_0),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &valid_path_1),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_0),
            Err(_)
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&protocol_capability, &invalid_path_1),
            Err(_)
        );
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_debug_capability()` for capability sources of type `Capability`.
    async fn global_policy_checker_can_route_debug_capability_capability_cap(
        &self,
    ) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "foo_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("foo").build(),
        );
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "bootstrap_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("root").exact("bootstrap").build(),
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let protocol_name: Name = "debug_service1".parse().unwrap();

        let valid_cases = vec![
            (Moniker::try_from(vec!["root", "bootstrap"]).unwrap(), "bootstrap_env"),
            (Moniker::try_from(vec!["foo"]).unwrap(), "foo_env"),
        ];

        let invalid_cases = vec![
            (Moniker::try_from(vec!["foobar"]).unwrap(), "foobar_env"),
            (Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap(), "foobar_env"),
            (Moniker::try_from(vec!["root", "bootstrap"]).unwrap(), "foo_env"),
            (Moniker::try_from(vec!["root", "baz"]).unwrap(), "foo_env"),
        ];

        for valid_case in valid_cases {
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &valid_case.0,
                    &valid_case.1.parse().unwrap(),
                ),
                Ok(()),
                "{:?}",
                valid_case
            );
        }

        for invalid_case in invalid_cases {
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &invalid_case.0,
                    &invalid_case.1.parse().unwrap(),
                ),
                Err(_),
                "{:?}",
                invalid_case
            );
        }

        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_debug_capability()` for capability sources of type
    // `Capability` with realm allowlist entries.
    async fn global_policy_checker_can_route_debug_capability_with_realm_allowlist_entry(
        &self,
    ) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "bar_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("root").exact("bootstrap1").any_descendant(),
        );
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "foo_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("root").exact("bootstrap2").build(),
        );
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "baz_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("root").exact("bootstrap3").any_descendant(),
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));

        // dest, env
        let valid_cases = vec![
            (vec!["root", "bootstrap1", "child"], "bar_env".to_string()),
            (vec!["root", "bootstrap1", "child", "grandchild"], "bar_env".to_string()),
            (vec!["root", "bootstrap2"], "foo_env".to_string()),
            (vec!["root", "bootstrap3", "child"], "baz_env".to_string()),
            (vec!["root", "bootstrap3", "child", "grandchild"], "baz_env".to_string()),
        ];

        let invalid_cases = vec![
            (vec!["root", "not_bootstrap"], "bar_env".to_string()),
            (vec!["root", "not_bootstrap"], "foo_env".to_string()),
            (vec!["root", "bootstrap1"], "baz_env".to_string()),
        ];

        for (dest, env) in valid_cases {
            let protocol_name: Name = "debug_service1".parse().unwrap();
            let env: Name = env.parse().unwrap();
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &Moniker::try_from(dest.clone()).unwrap(),
                    &env,
                ),
                Ok(()),
                "{:?}",
                (dest, env)
            );
        }

        for (dest, env) in invalid_cases {
            let protocol_name: Name = "debug_service1".parse().unwrap();
            let env: Name = env.parse().unwrap();
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &Moniker::try_from(dest.clone()).unwrap(),
                    &env,
                ),
                Err(_),
                "{:?}",
                (dest, env)
            );
        }

        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_debug_capability()` for capability sources of type
    // `Capability` with collection allowlist entries.
    async fn global_policy_checker_can_route_debug_capability_with_collection_allowlist_entry(
        &self,
    ) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "bar_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new()
                .exact("root")
                .exact("bootstrap")
                .any_descendant_in_collection("coll1"),
        );
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "foo_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new().exact("root").exact("bootstrap2").build(),
        );
        policy_builder.add_debug_capability_policy(
            DebugCapabilityKey {
                name: "debug_service1".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
                env_name: "baz_env".parse().unwrap(),
            },
            AllowlistEntryBuilder::new()
                .exact("root")
                .exact("bootstrap3")
                .any_descendant_in_collection("coll4"),
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));

        // dest, env
        let valid_cases = vec![
            (vec!["root", "bootstrap", "coll1:instance1"], "bar_env".to_string()),
            (vec!["root", "bootstrap", "coll1:instance1", "child"], "bar_env".to_string()),
            (vec!["root", "bootstrap2"], "foo_env".to_string()),
            (vec!["root", "bootstrap3", "coll4:instance4"], "baz_env".to_string()),
            (vec!["root", "bootstrap3", "coll4:instance4", "child"], "baz_env".to_string()),
        ];

        let invalid_cases = vec![
            (vec!["root", "bootstrap"], "bar_env".to_string()),
            (vec!["root", "not_bootstrap"], "bar_env".to_string()),
            (vec!["root", "not_bootstrap"], "foo_env".to_string()),
            (vec!["root", "bootstrap3", "child"], "baz_env".to_string()),
            (vec!["root", "bootstrap"], "baz_env".to_string()),
        ];

        for (dest, env) in valid_cases {
            let protocol_name: Name = "debug_service1".parse().unwrap();
            let env: Name = env.parse().unwrap();
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &Moniker::try_from(dest.clone()).unwrap(),
                    &env,
                ),
                Ok(()),
                "{:?}",
                (dest, env)
            );
        }

        for (dest, env) in invalid_cases {
            let protocol_name: Name = "debug_service1".parse().unwrap();
            let env: Name = env.parse().unwrap();
            assert_matches!(
                global_policy_checker.can_register_debug_capability(
                    CapabilityTypeName::Protocol,
                    &protocol_name,
                    &Moniker::try_from(dest.clone()).unwrap(),
                    &env,
                ),
                Err(_),
                "{:?}",
                (dest, env)
            );
        }

        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for builtin capabilities.
    async fn global_policy_checker_can_route_capability_builtin_cap(&self) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentManager,
                source_name: "test".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Directory,
            },
            vec![
                AllowlistEntryBuilder::new().exact("root").build(),
                AllowlistEntryBuilder::new().exact("root").exact("core").build(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));

        let dir_capability = CapabilitySource::Builtin(BuiltinSource {
            capability: InternalCapability::Directory("test".parse().unwrap()),
        });
        let valid_path_0 = Moniker::try_from(vec!["root"]).unwrap();
        let valid_path_1 = Moniker::try_from(vec!["root", "core"]).unwrap();
        let invalid_path_0 = Moniker::try_from(vec!["foobar"]).unwrap();
        let invalid_path_1 = Moniker::try_from(vec!["foo", "bar", "foobar"]).unwrap();

        assert_matches!(
            global_policy_checker.can_route_capability(&dir_capability, &valid_path_0),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&dir_capability, &valid_path_1),
            Ok(())
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&dir_capability, &invalid_path_0),
            Err(_)
        );
        assert_matches!(
            global_policy_checker.can_route_capability(&dir_capability, &invalid_path_1),
            Err(_)
        );
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for policy that includes non-exact
    // `AllowlistEntry::Realm` entries.
    async fn global_policy_checker_can_route_capability_with_realm_allowlist_entry(
        &self,
    ) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentManager,
                source_name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
            },
            vec![
                AllowlistEntryBuilder::new().exact("tests").any_descendant(),
                AllowlistEntryBuilder::new().exact("core").exact("tests").any_descendant(),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let protocol_capability = CapabilitySource::Namespace(NamespaceSource {
            capability: ComponentCapability::Protocol(ProtocolDecl {
                name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source_path: Some("/svc/fuchsia.kernel.MmioResource".parse().unwrap()),
                delivery: Default::default(),
            }),
        });

        macro_rules! can_route {
            ($moniker:expr) => {
                global_policy_checker.can_route_capability(&protocol_capability, $moniker)
            };
        }

        assert!(can_route!(&Moniker::try_from(vec!["tests", "test1"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["tests", "coll:test1"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["tests", "test1", "util"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["tests", "test2"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests", "test"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests", "coll:t"]).unwrap()).is_ok());

        assert!(can_route!(&Moniker::try_from(vec!["foo"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["tests"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["core", "foo"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests:test"]).unwrap()).is_err());
        Ok(())
    }

    // Tests `GlobalPolicyChecker::can_route_capability()` for policy that includes non-exact
    // `AllowlistEntry::Collection` entries.
    async fn global_policy_checker_can_route_capability_with_collection_allowlist_entry(
        &self,
    ) -> Result<(), Error> {
        let mut policy_builder = CapabilityAllowlistPolicyBuilder::new();
        policy_builder.add_capability_policy(
            CapabilityAllowlistKey {
                source_moniker: ExtendedMoniker::ComponentManager,
                source_name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source: CapabilityAllowlistSource::Self_,
                capability: CapabilityTypeName::Protocol,
            },
            vec![
                AllowlistEntryBuilder::new().any_descendant_in_collection("tests"),
                AllowlistEntryBuilder::new().exact("core").any_descendant_in_collection("tests"),
            ],
        );
        let global_policy_checker = GlobalPolicyChecker::new(Arc::new(policy_builder.build()));
        let protocol_capability = CapabilitySource::Namespace(NamespaceSource {
            capability: ComponentCapability::Protocol(ProtocolDecl {
                name: "fuchsia.kernel.MmioResource".parse().unwrap(),
                source_path: Some("/svc/fuchsia.kernel.MmioResource".parse().unwrap()),
                delivery: Default::default(),
            }),
        });

        macro_rules! can_route {
            ($moniker:expr) => {
                global_policy_checker.can_route_capability(&protocol_capability, $moniker)
            };
        }

        assert!(can_route!(&Moniker::try_from(vec!["tests:t1"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["tests:t2"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["tests:t1", "util"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests:t1"]).unwrap()).is_ok());
        assert!(can_route!(&Moniker::try_from(vec!["core", "tests:t2"]).unwrap()).is_ok());

        assert!(can_route!(&Moniker::try_from(vec!["foo"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["tests"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["coll:foo"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["core", "foo"]).unwrap()).is_err());
        assert!(can_route!(&Moniker::try_from(vec!["core", "coll:tests"]).unwrap()).is_err());
        Ok(())
    }
}

// Creates a SecurityPolicy based on the capability allowlist entries provided during
// construction.
struct CapabilityAllowlistPolicyBuilder {
    capability_policy: HashMap<CapabilityAllowlistKey, HashSet<AllowlistEntry>>,
    debug_capability_policy: HashMap<DebugCapabilityKey, HashSet<DebugCapabilityAllowlistEntry>>,
}

impl CapabilityAllowlistPolicyBuilder {
    pub fn new() -> Self {
        Self { capability_policy: HashMap::new(), debug_capability_policy: HashMap::new() }
    }

    /// Add a new entry to the configuration.
    pub fn add_capability_policy<'a>(
        &'a mut self,
        key: CapabilityAllowlistKey,
        value: Vec<AllowlistEntry>,
    ) -> &'a mut Self {
        let value_set = HashSet::from_iter(value.iter().cloned());
        self.capability_policy.insert(key, value_set);
        self
    }

    /// Add a new entry to the configuration.
    pub fn add_debug_capability_policy<'a>(
        &'a mut self,
        key: DebugCapabilityKey,
        dest: AllowlistEntry,
    ) -> &'a mut Self {
        self.debug_capability_policy
            .entry(key)
            .or_default()
            .insert(DebugCapabilityAllowlistEntry::new(dest));
        self
    }

    /// Creates a configuration from the provided policies.
    pub fn build(&self) -> SecurityPolicy {
        SecurityPolicy {
            job_policy: JobPolicyAllowlists {
                ambient_mark_vmo_exec: vec![],
                main_process_critical: vec![],
                create_raw_processes: vec![],
            },
            capability_policy: self.capability_policy.clone(),
            debug_capability_policy: self.debug_capability_policy.clone(),
            child_policy: ChildPolicyAllowlists { reboot_on_terminate: vec![] },
            ..Default::default()
        }
    }
}