Skip to main content

fallow_engine/
guard.rs

1//! Typed guard report assembly for pre-edit architecture guidance.
2
3use std::fmt;
4use std::path::{Component, Path};
5
6use fallow_config::{ResolvedBoundaryConfig, ResolvedConfig, RulePackRule, RulePackRuleKind};
7use fallow_types::guard::{
8    GuardBoundary, GuardFileReport, GuardPolicyRule, GuardReport, GuardSeverities, GuardZone,
9};
10use rustc_hash::FxHashSet;
11
12/// Error returned when a guard target cannot be represented safely.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum GuardError {
15    /// The requested target is outside the resolved project root.
16    OutsideRoot(String),
17}
18
19impl fmt::Display for GuardError {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        match self {
22            Self::OutsideRoot(path) => write!(f, "guard target is outside project root: {path}"),
23        }
24    }
25}
26
27impl std::error::Error for GuardError {}
28
29/// Build a typed guard report for one or more target files.
30///
31/// Paths may be project-relative or absolute under `config.root`. Returned
32/// paths are project-root-relative and use forward slashes.
33///
34/// # Errors
35///
36/// Returns [`GuardError::OutsideRoot`] for absolute paths outside the project
37/// root or relative paths containing parent-directory traversal.
38pub fn build_guard_report(
39    config: &ResolvedConfig,
40    files: &[String],
41) -> Result<GuardReport, GuardError> {
42    let scopes = compile_rule_scopes(config);
43    let mut reports = Vec::with_capacity(files.len());
44    for file in files {
45        reports.push(build_file_report(config, &scopes, file)?);
46    }
47    Ok(GuardReport { files: reports })
48}
49
50fn build_file_report(
51    config: &ResolvedConfig,
52    scopes: &[RuleScope<'_>],
53    input: &str,
54) -> Result<GuardFileReport, GuardError> {
55    let rel_path = normalize_target_path(config, input)?;
56    let full_path = config.root.join(&rel_path);
57    let rules = config.resolve_rules_for_path(&full_path);
58    let zone_name = config.boundaries.classify_zone(&rel_path);
59    let zone = zone_name.and_then(|name| guard_zone(&config.boundaries, name));
60    let boundary = guard_boundary(&config.boundaries, &rel_path, zone_name);
61    let notes = guard_notes(config, zone_name, boundary.coverage_required);
62
63    Ok(GuardFileReport {
64        exists: full_path.exists(),
65        boundary,
66        policy_rules: guard_policy_rules(scopes, &rel_path, zone_name, rules.policy_violation),
67        severities: GuardSeverities {
68            boundary_violation: rules.boundary_violation.to_string(),
69            policy_violation: rules.policy_violation.to_string(),
70        },
71        path: rel_path,
72        zone,
73        notes,
74    })
75}
76
77fn normalize_target_path(config: &ResolvedConfig, input: &str) -> Result<String, GuardError> {
78    let normalized = input.replace('\\', "/");
79    let path = Path::new(&normalized);
80    if looks_windows_absolute(&normalized) && !path.is_absolute() {
81        return Err(GuardError::OutsideRoot(input.to_string()));
82    }
83    let relative = if path.is_absolute() {
84        path.strip_prefix(&config.root)
85            .map_err(|_| GuardError::OutsideRoot(input.to_string()))?
86    } else {
87        path
88    };
89    normalize_relative_path(relative, input)
90}
91
92fn looks_windows_absolute(path: &str) -> bool {
93    let bytes = path.as_bytes();
94    bytes.len() >= 3 && bytes[1] == b':' && bytes[2] == b'/'
95}
96
97fn normalize_relative_path(path: &Path, original: &str) -> Result<String, GuardError> {
98    let mut parts = Vec::new();
99    for component in path.components() {
100        match component {
101            Component::CurDir => {}
102            Component::Normal(part) => parts.push(part.to_string_lossy().replace('\\', "/")),
103            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
104                return Err(GuardError::OutsideRoot(original.to_string()));
105            }
106        }
107    }
108    Ok(parts.join("/"))
109}
110
111fn guard_zone(boundaries: &ResolvedBoundaryConfig, name: &str) -> Option<GuardZone> {
112    boundaries
113        .zones
114        .iter()
115        .find(|zone| zone.name == name)
116        .map(|zone| GuardZone {
117            name: zone.name.clone(),
118            patterns: zone.patterns.clone(),
119        })
120}
121
122fn guard_boundary(
123    boundaries: &ResolvedBoundaryConfig,
124    rel_path: &str,
125    zone_name: Option<&str>,
126) -> GuardBoundary {
127    let configured = boundaries_configured(boundaries);
128    let coverage_required = zone_name.is_none()
129        && boundaries.coverage.require_all_files
130        && !boundaries.allows_unmatched(rel_path);
131
132    let Some(zone_name) = zone_name else {
133        return GuardBoundary {
134            configured,
135            unrestricted: true,
136            allowed_zones: Vec::new(),
137            allowed_type_only_zones: Vec::new(),
138            forbidden_calls: Vec::new(),
139            coverage_required,
140        };
141    };
142
143    let forbidden_calls = boundaries
144        .calls_forbidden_by_zone
145        .get(zone_name)
146        .cloned()
147        .unwrap_or_default();
148    let Some(rule) = boundaries
149        .rules
150        .iter()
151        .find(|rule| rule.from_zone == zone_name)
152    else {
153        return GuardBoundary {
154            configured,
155            unrestricted: true,
156            allowed_zones: Vec::new(),
157            allowed_type_only_zones: Vec::new(),
158            forbidden_calls,
159            coverage_required,
160        };
161    };
162
163    let mut allowed_zones = vec![zone_name.to_string()];
164    allowed_zones.extend(rule.allowed_zones.iter().cloned());
165    allowed_zones.sort();
166    allowed_zones.dedup();
167
168    GuardBoundary {
169        configured,
170        unrestricted: false,
171        allowed_zones,
172        allowed_type_only_zones: rule.allow_type_only_zones.clone(),
173        forbidden_calls,
174        coverage_required,
175    }
176}
177
178fn guard_notes(
179    config: &ResolvedConfig,
180    zone_name: Option<&str>,
181    coverage_required: bool,
182) -> Vec<String> {
183    let mut notes = Vec::new();
184    if boundaries_configured(&config.boundaries) && zone_name.is_none() {
185        notes.push(
186            "Files outside every zone are unrestricted for import and call checks.".to_string(),
187        );
188        if coverage_required {
189            notes.push(
190                "boundaries.coverage.requireAllFiles is enabled: reachable files with no zone are reported as boundary-coverage violations."
191                    .to_string(),
192            );
193        }
194    }
195    if !boundaries_configured(&config.boundaries) && config.rule_packs.is_empty() {
196        notes.push("No boundary zones or rule packs are configured.".to_string());
197    }
198    if zone_name.is_some() {
199        notes.push("Same-zone imports are always allowed.".to_string());
200    }
201    notes
202}
203
204fn boundaries_configured(boundaries: &ResolvedBoundaryConfig) -> bool {
205    !boundaries.zones.is_empty() || !boundaries.logical_groups.is_empty()
206}
207
208fn guard_policy_rules(
209    scopes: &[RuleScope<'_>],
210    rel_path: &str,
211    zone: Option<&str>,
212    master_severity: fallow_config::Severity,
213) -> Vec<GuardPolicyRule> {
214    if master_severity == fallow_config::Severity::Off {
215        return Vec::new();
216    }
217
218    scopes
219        .iter()
220        .filter(|scope| {
221            compiled_scope_applies(&scope.files, &scope.exclude, &scope.zones, rel_path, zone)
222        })
223        .filter_map(|scope| guard_policy_rule(scope.pack, scope.rule, master_severity))
224        .collect()
225}
226
227/// One rule-pack rule with its file and zone scope compiled once per report.
228struct RuleScope<'a> {
229    pack: &'a str,
230    rule: &'a RulePackRule,
231    files: Vec<globset::GlobMatcher>,
232    exclude: Vec<globset::GlobMatcher>,
233    zones: FxHashSet<String>,
234}
235
236fn compile_rule_scopes(config: &ResolvedConfig) -> Vec<RuleScope<'_>> {
237    config
238        .rule_packs
239        .iter()
240        .flat_map(|pack| {
241            pack.rules.iter().map(move |rule| RuleScope {
242                pack: pack.name.as_str(),
243                rule,
244                files: compile_scope_globs(&rule.files),
245                exclude: compile_scope_globs(&rule.exclude),
246                zones: rule.zones.iter().cloned().collect(),
247            })
248        })
249        .collect()
250}
251
252fn compile_scope_globs(patterns: &[String]) -> Vec<globset::GlobMatcher> {
253    patterns
254        .iter()
255        .filter_map(|pattern| fallow_config::compile_path_glob(pattern).ok())
256        .map(|glob| glob.compile_matcher())
257        .collect()
258}
259
260fn compiled_scope_applies(
261    files: &[globset::GlobMatcher],
262    exclude: &[globset::GlobMatcher],
263    zones: &FxHashSet<String>,
264    relative: &str,
265    zone: Option<&str>,
266) -> bool {
267    (files.is_empty() || files.iter().any(|matcher| matcher.is_match(relative)))
268        && !exclude.iter().any(|matcher| matcher.is_match(relative))
269        && (zones.is_empty() || zone.is_some_and(|zone| zones.contains(zone)))
270}
271
272fn guard_policy_rule(
273    pack: &str,
274    rule: &RulePackRule,
275    master_severity: fallow_config::Severity,
276) -> Option<GuardPolicyRule> {
277    let severity = rule.severity.unwrap_or(master_severity);
278    if severity == fallow_config::Severity::Off {
279        return None;
280    }
281
282    Some(GuardPolicyRule {
283        pack: pack.to_string(),
284        rule_id: rule.id.clone(),
285        kind: rule_kind(rule.kind).to_string(),
286        patterns: rule_patterns(rule),
287        allowed_names: rule.allow_names.clone(),
288        allowed_files: rule.allowed_files.clone(),
289        proof_kinds: rule.proof_kinds.clone(),
290        message: rule.message.clone(),
291        severity: severity.to_string(),
292        suppress_token: format!("policy-violation:{pack}/{}", rule.id),
293    })
294}
295
296const fn rule_kind(kind: RulePackRuleKind) -> &'static str {
297    match kind {
298        RulePackRuleKind::BannedCall => "banned-call",
299        RulePackRuleKind::BannedImport => "banned-import",
300        RulePackRuleKind::BannedEffect => "banned-effect",
301        RulePackRuleKind::BannedExport => "banned-export",
302        RulePackRuleKind::GdpProofProducer => "gdp-proof-producer",
303    }
304}
305
306fn rule_patterns(rule: &RulePackRule) -> Vec<String> {
307    match rule.kind {
308        RulePackRuleKind::BannedCall => rule.callees.clone(),
309        RulePackRuleKind::BannedImport => rule.specifiers.clone(),
310        RulePackRuleKind::BannedEffect => rule
311            .effects
312            .iter()
313            .map(|effect| effect.as_str().to_string())
314            .collect(),
315        RulePackRuleKind::BannedExport => rule.exports.clone(),
316        RulePackRuleKind::GdpProofProducer => vec!["@gdp-ts/core.defineProof".to_string()],
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use fallow_config::{
324        BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryRule, BoundaryZone,
325        EffectKind, FallowConfig, ForbiddenCallRule, ForbiddenCallee, OutputFormat, RulePackDef,
326        RulePackRule, RulePackRuleKind, RulesConfig, Severity,
327    };
328    use std::fs;
329
330    fn rule(id: &str, kind: RulePackRuleKind) -> RulePackRule {
331        RulePackRule {
332            id: id.to_string(),
333            kind,
334            callees: Vec::new(),
335            specifiers: Vec::new(),
336            allow_names: Vec::new(),
337            effects: Vec::new(),
338            exports: Vec::new(),
339            allowed_files: Vec::new(),
340            proof_kinds: Vec::new(),
341            ignore_type_only: false,
342            files: Vec::new(),
343            exclude: Vec::new(),
344            zones: Vec::new(),
345            message: None,
346            severity: None,
347        }
348    }
349
350    fn pack(rules: Vec<RulePackRule>) -> RulePackDef {
351        RulePackDef {
352            schema: None,
353            version: 1,
354            name: "team-policy".to_string(),
355            description: None,
356            rules,
357        }
358    }
359
360    #[test]
361    fn scope_glob_single_star_stays_within_one_segment() {
362        let matchers = compile_scope_globs(&["src/*.ts".to_string()]);
363        let matches = |path: &str| matchers.iter().any(|m| m.is_match(path));
364        assert!(matches("src/a.ts"));
365        assert!(!matches("src/nested/a.ts"));
366    }
367
368    fn resolve(root: &Path, configure: impl FnOnce(&mut FallowConfig)) -> ResolvedConfig {
369        let mut config = FallowConfig {
370            rules: RulesConfig {
371                policy_violation: Severity::Warn,
372                ..RulesConfig::default()
373            },
374            ..FallowConfig::default()
375        };
376        configure(&mut config);
377        config.resolve(root.to_path_buf(), OutputFormat::Json, 1, true, true, None)
378    }
379
380    #[test]
381    fn zoned_file_reports_allow_rule_and_forbidden_call() {
382        let temp = tempfile::tempdir().expect("tempdir");
383        fs::create_dir_all(temp.path().join("src/domain")).expect("create dir");
384        fs::write(temp.path().join("src/domain/user.ts"), "").expect("write file");
385        let config = resolve(temp.path(), |config| {
386            config.boundaries = BoundaryConfig {
387                zones: vec![
388                    BoundaryZone {
389                        name: "domain".to_string(),
390                        patterns: vec!["src/domain/**".to_string()],
391                        auto_discover: Vec::new(),
392                        root: None,
393                        public_files: vec![],
394                    },
395                    BoundaryZone {
396                        name: "shared".to_string(),
397                        patterns: vec!["src/shared/**".to_string()],
398                        auto_discover: Vec::new(),
399                        root: None,
400                        public_files: vec![],
401                    },
402                ],
403                rules: vec![BoundaryRule {
404                    from: "domain".to_string(),
405                    allow: vec!["shared".to_string()],
406                    allow_type_only: vec!["ui".to_string()],
407                }],
408                calls: BoundaryCallsConfig {
409                    forbidden: vec![ForbiddenCallRule {
410                        from: "domain".to_string(),
411                        callee: ForbiddenCallee::Single("child_process.*".to_string()),
412                    }],
413                },
414                ..BoundaryConfig::default()
415            };
416        });
417
418        let report =
419            build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
420        let file = &report.files[0];
421
422        assert!(file.exists);
423        assert_eq!(
424            file.zone.as_ref().map(|zone| zone.name.as_str()),
425            Some("domain")
426        );
427        assert!(!file.boundary.unrestricted);
428        assert_eq!(file.boundary.allowed_zones, vec!["domain", "shared"]);
429        assert_eq!(file.boundary.allowed_type_only_zones, vec!["ui"]);
430        assert_eq!(file.boundary.forbidden_calls, vec!["child_process.*"]);
431        assert!(file.notes.iter().any(|note| note.contains("Same-zone")));
432    }
433
434    fn required_coverage_config(root: &Path) -> ResolvedConfig {
435        resolve(root, |config| {
436            config.boundaries = BoundaryConfig {
437                zones: vec![BoundaryZone {
438                    name: "domain".to_string(),
439                    patterns: vec!["src/domain/**".to_string()],
440                    auto_discover: Vec::new(),
441                    root: None,
442                    public_files: vec![],
443                }],
444                coverage: BoundaryCoverageConfig {
445                    require_all_files: true,
446                    allow_unmatched: vec!["src/generated/**".to_string()],
447                },
448                ..BoundaryConfig::default()
449            };
450        })
451    }
452
453    #[test]
454    fn unzoned_file_reports_required_coverage() {
455        let temp = tempfile::tempdir().expect("tempdir");
456        let config = required_coverage_config(temp.path());
457
458        let report =
459            build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
460        let file = &report.files[0];
461
462        assert!(file.zone.is_none());
463        assert!(file.boundary.unrestricted);
464        assert!(file.boundary.coverage_required);
465        assert!(
466            file.notes
467                .iter()
468                .any(|note| note.contains("outside every zone"))
469        );
470
471        let allowed =
472            build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
473        assert!(!allowed.files[0].boundary.coverage_required);
474    }
475
476    #[test]
477    fn required_coverage_notes_state_the_requirement() {
478        let temp = tempfile::tempdir().expect("tempdir");
479        let config = required_coverage_config(temp.path());
480
481        let report =
482            build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
483        let notes = &report.files[0].notes;
484
485        assert!(
486            notes
487                .iter()
488                .any(|note| note.contains("requireAllFiles") && note.contains("boundary-coverage")),
489            "unzoned file under required coverage must state the requirement: {notes:?}"
490        );
491        assert!(
492            !notes
493                .iter()
494                .any(|note| note.contains("unrestricted for boundary checks")),
495            "the unrestricted note must not claim to cover the coverage check: {notes:?}"
496        );
497
498        let allowed =
499            build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
500        assert!(
501            !allowed.files[0]
502                .notes
503                .iter()
504                .any(|note| note.contains("requireAllFiles")),
505            "allowUnmatched paths must not state a coverage requirement"
506        );
507    }
508
509    #[test]
510    fn pack_rule_scope_filters_policy_rules() {
511        let temp = tempfile::tempdir().expect("tempdir");
512        let mut domain_rule = rule("pure-domain", RulePackRuleKind::BannedEffect);
513        domain_rule.effects = vec![EffectKind::Network];
514        domain_rule.files = vec!["src/domain/**".to_string()];
515        let mut excluded_rule = rule("no-generated-process", RulePackRuleKind::BannedCall);
516        excluded_rule.callees = vec!["child_process.*".to_string()];
517        excluded_rule.exclude = vec!["src/domain/**".to_string()];
518        let mut config = resolve(temp.path(), |_| {});
519        config.rule_packs = vec![pack(vec![domain_rule, excluded_rule])];
520
521        let report =
522            build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
523        let rules = &report.files[0].policy_rules;
524
525        assert_eq!(rules.len(), 1);
526        assert_eq!(rules[0].rule_id, "pure-domain");
527        assert_eq!(rules[0].kind, "banned-effect");
528        assert_eq!(rules[0].patterns, vec!["network"]);
529        assert_eq!(
530            rules[0].suppress_token,
531            "policy-violation:team-policy/pure-domain"
532        );
533        assert_eq!(rules[0].severity, "warn");
534    }
535
536    #[test]
537    fn compiled_rule_scopes_match_individual_file_reports() {
538        let temp = tempfile::tempdir().expect("tempdir");
539        let mut config = resolve(temp.path(), |config| {
540            config.boundaries = BoundaryConfig {
541                zones: vec![
542                    BoundaryZone {
543                        name: "domain".to_string(),
544                        patterns: vec!["src/domain/**".to_string()],
545                        auto_discover: Vec::new(),
546                        root: None,
547                        public_files: vec![],
548                    },
549                    BoundaryZone {
550                        name: "app".to_string(),
551                        patterns: vec!["src/app/**".to_string()],
552                        auto_discover: Vec::new(),
553                        root: None,
554                        public_files: vec![],
555                    },
556                ],
557                ..BoundaryConfig::default()
558            };
559        });
560        let mut domain_rule = rule("domain-only", RulePackRuleKind::BannedImport);
561        domain_rule.files = vec!["src/domain/**".to_string()];
562        domain_rule.exclude = vec!["src/domain/generated/**".to_string()];
563        let mut app_rule = rule("app-zone", RulePackRuleKind::BannedCall);
564        app_rule.zones = vec!["app".to_string()];
565        let mut invalid_glob_rule = rule("invalid-glob", RulePackRuleKind::BannedExport);
566        invalid_glob_rule.files = vec!["[".to_string()];
567        config.rule_packs = vec![pack(vec![domain_rule, app_rule, invalid_glob_rule])];
568
569        let files = vec![
570            "src/domain/user.ts".to_string(),
571            "src/domain/generated/client.ts".to_string(),
572            "src/app/page.ts".to_string(),
573            "src/other.ts".to_string(),
574        ];
575        let batch = build_guard_report(&config, &files).expect("batch report");
576        let individual = files
577            .iter()
578            .flat_map(|file| {
579                build_guard_report(&config, std::slice::from_ref(file))
580                    .expect("individual report")
581                    .files
582            })
583            .collect::<Vec<_>>();
584
585        assert_eq!(
586            serde_json::to_value(&batch.files).expect("serialize batch reports"),
587            serde_json::to_value(&individual).expect("serialize individual reports")
588        );
589        let rule_ids = batch
590            .files
591            .iter()
592            .map(|file| {
593                file.policy_rules
594                    .iter()
595                    .map(|rule| rule.rule_id.as_str())
596                    .collect::<Vec<_>>()
597            })
598            .collect::<Vec<_>>();
599        assert_eq!(
600            rule_ids,
601            vec![
602                vec!["domain-only", "invalid-glob"],
603                vec!["invalid-glob"],
604                vec!["app-zone", "invalid-glob"],
605                vec!["invalid-glob"],
606            ]
607        );
608    }
609
610    #[test]
611    fn nonexistent_target_reports_exists_false() {
612        let temp = tempfile::tempdir().expect("tempdir");
613        let config = resolve(temp.path(), |_| {});
614
615        let report = build_guard_report(&config, &["src/missing.ts".to_string()]).expect("report");
616
617        assert_eq!(report.files[0].path, "src/missing.ts");
618        assert!(!report.files[0].exists);
619    }
620
621    #[test]
622    fn path_outside_root_errors() {
623        let temp = tempfile::tempdir().expect("tempdir");
624        let config = resolve(temp.path(), |_| {});
625
626        let err = build_guard_report(&config, &["../outside.ts".to_string()]).unwrap_err();
627
628        assert!(matches!(err, GuardError::OutsideRoot(_)));
629    }
630}