rebecca-core 0.3.0

Core planning, safety, scanning, and history models for Rebecca.
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

use crate::{Platform, RebeccaError, Result};

pub const SAFETY_CATALOG_VERSION: u16 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SafetyCategory {
    Credentials,
    VpnProxyState,
    AiToolDurableState,
    BrowserPrivateData,
    CloudSyncedData,
    ContainerRuntimeState,
    StartupAutomation,
    ApplicationDurableData,
}

impl SafetyCategory {
    pub fn label(self) -> &'static str {
        match self {
            Self::Credentials => "credentials",
            Self::VpnProxyState => "vpn-proxy-state",
            Self::AiToolDurableState => "ai-tool-durable-state",
            Self::BrowserPrivateData => "browser-private-data",
            Self::CloudSyncedData => "cloud-synced-data",
            Self::ContainerRuntimeState => "container-runtime-state",
            Self::StartupAutomation => "startup-automation",
            Self::ApplicationDurableData => "application-durable-data",
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SafetyCatalogFile {
    catalog_version: u16,
    default_platform: Platform,
    #[serde(default)]
    warning_kinds: Vec<WarningKindDefinition>,
    #[serde(default)]
    protected_categories: Vec<ProtectedCategoryDefinition>,
    #[serde(default)]
    maintenance_allowlist: SafetyPatternSetFile,
    #[serde(default)]
    protected_patterns: Vec<ProtectedPatternDefinition>,
    #[serde(default)]
    platforms: Vec<PlatformSafetyDefinition>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PlatformSafetyDefinition {
    platform: Platform,
    #[serde(default)]
    critical_path_prefixes: Vec<String>,
    #[serde(default)]
    maintenance_allowlist: SafetyPatternSetFile,
    #[serde(default)]
    protected_patterns: Vec<ProtectedPatternDefinition>,
    #[serde(default)]
    steam_install_allowlist: Vec<String>,
    #[serde(default)]
    steam_library_allowlist: Vec<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct WarningKindDefinition {
    id: String,
    description: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ProtectedCategoryDefinition {
    id: SafetyCategory,
    description: String,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct SafetyPatternSetFile {
    #[serde(default)]
    segments: Vec<String>,
    #[serde(default)]
    sequences: Vec<Vec<String>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ProtectedPatternDefinition {
    category: SafetyCategory,
    #[serde(default)]
    segments: Vec<String>,
    #[serde(default)]
    leaf_names: Vec<String>,
    #[serde(default)]
    sequences: Vec<Vec<String>>,
}

#[derive(Debug, Clone)]
pub struct SafetyKnowledge {
    platform: Platform,
    warning_kinds: Vec<WarningKind>,
    categories: Vec<ProtectedCategoryKnowledge>,
    critical_path_prefixes: Vec<String>,
    maintenance_allowlist: SafetyPatternSet,
    protected_patterns: Vec<ProtectedPattern>,
    steam_install_allowlist: Vec<String>,
    steam_library_allowlist: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct SafetyCatalog {
    default_platform: Platform,
    platform_knowledge: Vec<SafetyKnowledge>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WarningKind {
    id: String,
    description: String,
}

impl WarningKind {
    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn description(&self) -> &str {
        &self.description
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProtectedCategoryKnowledge {
    id: SafetyCategory,
    description: String,
}

impl ProtectedCategoryKnowledge {
    pub fn id(&self) -> SafetyCategory {
        self.id
    }

    pub fn description(&self) -> &str {
        &self.description
    }
}

#[derive(Debug, Clone, Default)]
pub struct SafetyPatternSet {
    segment_matches: Vec<String>,
    sequence_matches: Vec<Vec<String>>,
}

impl SafetyPatternSet {
    pub fn matches(&self, segments: &[&str]) -> bool {
        self.has_any_segment(segments) || self.has_any_sequence(segments)
    }

    fn merged(&self, other: Self) -> Self {
        let mut segment_matches = self.segment_matches.clone();
        segment_matches.extend(other.segment_matches);
        segment_matches.sort();
        segment_matches.dedup();

        let mut sequence_matches = self.sequence_matches.clone();
        sequence_matches.extend(other.sequence_matches);
        sequence_matches.sort();
        sequence_matches.dedup();

        Self {
            segment_matches,
            sequence_matches,
        }
    }

    fn has_any_segment(&self, segments: &[&str]) -> bool {
        segments
            .iter()
            .any(|segment| self.segment_matches.iter().any(|needle| segment == needle))
    }

    fn has_any_sequence(&self, segments: &[&str]) -> bool {
        self.sequence_matches
            .iter()
            .any(|sequence| has_sequence(segments, sequence))
    }
}

#[derive(Debug, Clone)]
pub struct ProtectedPattern {
    category: SafetyCategory,
    segment_matches: Vec<String>,
    leaf_names: Vec<String>,
    sequence_matches: Vec<Vec<String>>,
}

impl ProtectedPattern {
    pub fn category(&self) -> SafetyCategory {
        self.category
    }

    pub fn matches(&self, segments: &[&str]) -> bool {
        self.matches_segment(segments)
            || self.matches_leaf(segments)
            || self.matches_sequence(segments)
    }

    fn matches_segment(&self, segments: &[&str]) -> bool {
        segments
            .iter()
            .any(|segment| self.segment_matches.iter().any(|needle| segment == needle))
    }

    fn matches_leaf(&self, segments: &[&str]) -> bool {
        segments
            .last()
            .is_some_and(|leaf| self.leaf_names.iter().any(|needle| leaf == needle))
    }

    fn matches_sequence(&self, segments: &[&str]) -> bool {
        self.sequence_matches
            .iter()
            .any(|sequence| has_sequence(segments, sequence))
    }
}

impl SafetyKnowledge {
    pub fn platform(&self) -> Platform {
        self.platform
    }

    pub fn warning_kinds(&self) -> &[WarningKind] {
        &self.warning_kinds
    }

    pub fn categories(&self) -> &[ProtectedCategoryKnowledge] {
        &self.categories
    }

    pub fn critical_path_prefixes(&self) -> &[String] {
        &self.critical_path_prefixes
    }

    pub fn maintenance_allowlist(&self) -> &SafetyPatternSet {
        &self.maintenance_allowlist
    }

    pub fn protected_patterns(&self) -> &[ProtectedPattern] {
        &self.protected_patterns
    }

    pub fn category_description(&self, category: SafetyCategory) -> Option<&str> {
        self.categories
            .iter()
            .find(|entry| entry.id == category)
            .map(ProtectedCategoryKnowledge::description)
    }

    pub fn is_allowed_steam_install_target(&self, normalized: &str) -> bool {
        self.steam_install_allowlist
            .iter()
            .any(|target| target == normalized)
    }

    pub fn is_allowed_steam_library_target(&self, normalized: &str) -> bool {
        self.steam_library_allowlist
            .iter()
            .any(|target| target == normalized)
    }
}

impl SafetyCatalog {
    pub fn default_platform(&self) -> Platform {
        self.default_platform
    }

    pub fn platform_knowledge(&self) -> &[SafetyKnowledge] {
        &self.platform_knowledge
    }

    pub fn default_knowledge(&self) -> Option<&SafetyKnowledge> {
        self.knowledge_for_platform(self.default_platform)
    }

    pub fn knowledge_for_platform(&self, platform: Platform) -> Option<&SafetyKnowledge> {
        self.platform_knowledge
            .iter()
            .find(|knowledge| knowledge.platform == platform)
    }
}

pub fn parse_safety_catalog(path: &str, raw: &str) -> Result<SafetyCatalog> {
    let catalog = toml::from_str::<SafetyCatalogFile>(raw).map_err(|err| {
        RebeccaError::SafetyCatalogInvalid(format!("{path} is invalid safety catalog data: {err}"))
    })?;
    compile_safety_catalog(path, catalog)
}

pub fn parse_safety_catalog_file(path: &str, raw: &str) -> Result<SafetyKnowledge> {
    let catalog = parse_safety_catalog(path, raw)?;
    catalog.default_knowledge().cloned().ok_or_else(|| {
        RebeccaError::SafetyCatalogInvalid(format!(
            "{path} default platform {} has no platform safety block",
            catalog.default_platform().label()
        ))
    })
}

pub fn parse_safety_catalog_file_for_platform(
    path: &str,
    raw: &str,
    platform: Platform,
) -> Result<SafetyKnowledge> {
    let catalog = parse_safety_catalog(path, raw)?;
    catalog
        .knowledge_for_platform(platform)
        .cloned()
        .ok_or_else(|| {
            RebeccaError::SafetyCatalogInvalid(format!(
                "{path} has no safety knowledge for platform {}",
                platform.label()
            ))
        })
}

pub fn default_safety_catalog() -> &'static SafetyCatalog {
    static DEFAULT: OnceLock<SafetyCatalog> = OnceLock::new();
    DEFAULT.get_or_init(|| {
        parse_safety_catalog(
            rebecca_safety::CLEANUP_SAFETY_CATALOG_PATH,
            rebecca_safety::CLEANUP_SAFETY_CATALOG,
        )
        .expect("embedded default safety catalog should be valid")
    })
}

pub fn default_safety_knowledge() -> &'static SafetyKnowledge {
    default_safety_catalog()
        .default_knowledge()
        .expect("embedded default safety catalog should define its default platform")
}

pub fn default_safety_knowledge_for_platform(
    platform: Platform,
) -> Option<&'static SafetyKnowledge> {
    default_safety_catalog().knowledge_for_platform(platform)
}

fn compile_safety_catalog(path: &str, catalog: SafetyCatalogFile) -> Result<SafetyCatalog> {
    if catalog.catalog_version != SAFETY_CATALOG_VERSION {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} uses unsupported safety catalog version {}; expected {SAFETY_CATALOG_VERSION}",
            catalog.catalog_version
        )));
    }

    if catalog.default_platform == Platform::Unknown {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} default_platform must target a supported platform"
        )));
    }

    if catalog.platforms.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} must define at least one platform safety block"
        )));
    }

    let warning_kinds = catalog
        .warning_kinds
        .into_iter()
        .map(|entry| {
            let id = normalize_scalar(path, "warning_kinds.id", entry.id)?;
            let description =
                normalize_description(path, "warning_kinds.description", entry.description)?;
            Ok(WarningKind { id, description })
        })
        .collect::<Result<Vec<_>>>()?;
    validate_unique_by(path, "warning_kinds.id", &warning_kinds, WarningKind::id)?;

    let categories = catalog
        .protected_categories
        .into_iter()
        .map(|entry| {
            let description =
                normalize_description(path, "protected_categories.description", entry.description)?;
            Ok(ProtectedCategoryKnowledge {
                id: entry.id,
                description,
            })
        })
        .collect::<Result<Vec<_>>>()?;
    validate_complete_categories(path, &categories)?;

    let maintenance_allowlist =
        compile_pattern_set(path, "maintenance_allowlist", catalog.maintenance_allowlist)?;

    let shared_protected_patterns = catalog
        .protected_patterns
        .into_iter()
        .map(|entry| compile_protected_pattern(path, entry))
        .collect::<Result<Vec<_>>>()?;

    let mut platform_knowledge = Vec::with_capacity(catalog.platforms.len());
    for platform in catalog.platforms {
        platform_knowledge.push(compile_platform_safety_knowledge(
            path,
            &warning_kinds,
            &categories,
            &maintenance_allowlist,
            &shared_protected_patterns,
            platform,
        )?);
    }

    validate_unique_platforms(path, &platform_knowledge)?;

    if !platform_knowledge
        .iter()
        .any(|knowledge| knowledge.platform == catalog.default_platform)
    {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} default platform {} has no platform safety block",
            catalog.default_platform.label()
        )));
    }

    Ok(SafetyCatalog {
        default_platform: catalog.default_platform,
        platform_knowledge,
    })
}

fn compile_platform_safety_knowledge(
    path: &str,
    warning_kinds: &[WarningKind],
    categories: &[ProtectedCategoryKnowledge],
    shared_maintenance_allowlist: &SafetyPatternSet,
    shared_protected_patterns: &[ProtectedPattern],
    platform: PlatformSafetyDefinition,
) -> Result<SafetyKnowledge> {
    if platform.platform == Platform::Unknown {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} platform safety block must target a supported platform"
        )));
    }

    validate_non_empty(
        path,
        &format!(
            "platforms.{}.critical_path_prefixes",
            platform.platform.label()
        ),
        &platform.critical_path_prefixes,
    )?;

    let critical_path_prefixes = platform
        .critical_path_prefixes
        .into_iter()
        .map(|prefix| normalize_pathish(path, "platforms.critical_path_prefixes", prefix))
        .collect::<Result<Vec<_>>>()?;
    validate_unique_strings(
        path,
        "platforms.critical_path_prefixes",
        &critical_path_prefixes,
    )?;

    let platform_maintenance_allowlist = compile_pattern_set(
        path,
        "platforms.maintenance_allowlist",
        platform.maintenance_allowlist,
    )?;
    let maintenance_allowlist = shared_maintenance_allowlist.merged(platform_maintenance_allowlist);

    let mut protected_patterns = shared_protected_patterns.to_vec();
    protected_patterns.extend(
        platform
            .protected_patterns
            .into_iter()
            .map(|entry| compile_protected_pattern(path, entry))
            .collect::<Result<Vec<_>>>()?,
    );
    validate_non_empty_patterns(path, "protected_patterns", &protected_patterns)?;

    let steam_install_allowlist = normalize_pathish_list(
        path,
        "platforms.steam_install_allowlist",
        platform.steam_install_allowlist,
    )?;
    let steam_library_allowlist = normalize_pathish_list(
        path,
        "platforms.steam_library_allowlist",
        platform.steam_library_allowlist,
    )?;

    Ok(SafetyKnowledge {
        platform: platform.platform,
        warning_kinds: warning_kinds.to_vec(),
        categories: categories.to_vec(),
        critical_path_prefixes,
        maintenance_allowlist,
        protected_patterns,
        steam_install_allowlist,
        steam_library_allowlist,
    })
}

fn compile_pattern_set(
    path: &str,
    field: &str,
    input: SafetyPatternSetFile,
) -> Result<SafetyPatternSet> {
    let segment_matches =
        normalize_scalar_list(path, &format!("{field}.segments"), input.segments)?;
    let sequence_matches =
        normalize_sequence_list(path, &format!("{field}.sequences"), input.sequences)?;

    Ok(SafetyPatternSet {
        segment_matches,
        sequence_matches,
    })
}

fn compile_protected_pattern(
    path: &str,
    input: ProtectedPatternDefinition,
) -> Result<ProtectedPattern> {
    let segment_matches =
        normalize_scalar_list(path, "protected_patterns.segments", input.segments)?;
    let leaf_names =
        normalize_scalar_list(path, "protected_patterns.leaf_names", input.leaf_names)?;
    let sequence_matches =
        normalize_sequence_list(path, "protected_patterns.sequences", input.sequences)?;

    if segment_matches.is_empty() && leaf_names.is_empty() && sequence_matches.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} protected pattern for {} must define at least one matcher",
            input.category.label()
        )));
    }

    Ok(ProtectedPattern {
        category: input.category,
        segment_matches,
        leaf_names,
        sequence_matches,
    })
}

fn normalize_scalar_list(path: &str, field: &str, values: Vec<String>) -> Result<Vec<String>> {
    let values = values
        .into_iter()
        .map(|value| normalize_scalar(path, field, value))
        .collect::<Result<Vec<_>>>()?;
    validate_unique_strings(path, field, &values)?;
    Ok(values)
}

fn normalize_pathish_list(path: &str, field: &str, values: Vec<String>) -> Result<Vec<String>> {
    let values = values
        .into_iter()
        .map(|value| normalize_pathish(path, field, value))
        .collect::<Result<Vec<_>>>()?;
    validate_unique_strings(path, field, &values)?;
    Ok(values)
}

fn normalize_sequence_list(
    path: &str,
    field: &str,
    values: Vec<Vec<String>>,
) -> Result<Vec<Vec<String>>> {
    let mut normalized = Vec::with_capacity(values.len());
    for sequence in values {
        if sequence.is_empty() {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} {field} contains an empty sequence"
            )));
        }

        normalized.push(
            sequence
                .into_iter()
                .map(|value| normalize_scalar(path, field, value))
                .collect::<Result<Vec<_>>>()?,
        );
    }

    normalized.sort();
    normalized.dedup();
    Ok(normalized)
}

fn normalize_scalar(path: &str, field: &str, value: String) -> Result<String> {
    let normalized = value.trim().to_ascii_lowercase();
    if normalized.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} {field} contains an empty value"
        )));
    }
    Ok(normalized)
}

fn normalize_pathish(path: &str, field: &str, value: String) -> Result<String> {
    let normalized = value.replace('\\', "/").trim().to_ascii_lowercase();
    if normalized.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} {field} contains an empty value"
        )));
    }
    Ok(trim_trailing_separators(&normalized))
}

fn normalize_description(path: &str, field: &str, value: String) -> Result<String> {
    let description = value.trim().to_string();
    if description.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} {field} contains an empty value"
        )));
    }
    Ok(description)
}

fn validate_non_empty(path: &str, field: &str, values: &[String]) -> Result<()> {
    if values.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} {field} must not be empty"
        )));
    }
    Ok(())
}

fn validate_non_empty_patterns(path: &str, field: &str, values: &[ProtectedPattern]) -> Result<()> {
    if values.is_empty() {
        return Err(RebeccaError::SafetyCatalogInvalid(format!(
            "{path} {field} must not be empty"
        )));
    }
    Ok(())
}

fn validate_unique_strings(path: &str, field: &str, values: &[String]) -> Result<()> {
    let mut sorted = values.to_vec();
    sorted.sort();
    for window in sorted.windows(2) {
        if window[0] == window[1] {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} {field} contains duplicate value {}",
                window[0]
            )));
        }
    }
    Ok(())
}

fn validate_unique_by<T, F>(path: &str, field: &str, values: &[T], mut key: F) -> Result<()>
where
    F: FnMut(&T) -> &str,
{
    let mut keys = values
        .iter()
        .map(|value| key(value).to_string())
        .collect::<Vec<_>>();
    keys.sort();
    for window in keys.windows(2) {
        if window[0] == window[1] {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} {field} contains duplicate value {}",
                window[0]
            )));
        }
    }
    Ok(())
}

fn validate_unique_platforms(path: &str, values: &[SafetyKnowledge]) -> Result<()> {
    let mut labels = values
        .iter()
        .map(|knowledge| knowledge.platform.label().to_string())
        .collect::<Vec<_>>();
    labels.sort();
    for window in labels.windows(2) {
        if window[0] == window[1] {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} platforms contains duplicate platform {}",
                window[0]
            )));
        }
    }
    Ok(())
}

fn validate_complete_categories(
    path: &str,
    categories: &[ProtectedCategoryKnowledge],
) -> Result<()> {
    const REQUIRED: &[SafetyCategory] = &[
        SafetyCategory::Credentials,
        SafetyCategory::VpnProxyState,
        SafetyCategory::AiToolDurableState,
        SafetyCategory::BrowserPrivateData,
        SafetyCategory::CloudSyncedData,
        SafetyCategory::ContainerRuntimeState,
        SafetyCategory::StartupAutomation,
        SafetyCategory::ApplicationDurableData,
    ];

    for required in REQUIRED {
        if !categories.iter().any(|category| category.id == *required) {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} missing protected category {}",
                required.label()
            )));
        }
    }

    let mut labels = categories
        .iter()
        .map(|category| category.id.label().to_string())
        .collect::<Vec<_>>();
    labels.sort();
    for window in labels.windows(2) {
        if window[0] == window[1] {
            return Err(RebeccaError::SafetyCatalogInvalid(format!(
                "{path} protected_categories contains duplicate category {}",
                window[0]
            )));
        }
    }

    Ok(())
}

fn trim_trailing_separators(path: &str) -> String {
    let mut normalized = path.to_string();

    while normalized.ends_with('/') && normalized.len() > 3 {
        normalized.pop();
    }

    normalized
}

fn has_sequence(segments: &[&str], sequence: &[String]) -> bool {
    if sequence.is_empty() || segments.len() < sequence.len() {
        return false;
    }

    segments.windows(sequence.len()).any(|window| {
        window
            .iter()
            .zip(sequence)
            .all(|(segment, expected)| segment == expected)
    })
}