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| globset::Glob::new(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        message: rule.message.clone(),
288        severity: severity.to_string(),
289        suppress_token: format!("policy-violation:{pack}/{}", rule.id),
290    })
291}
292
293const fn rule_kind(kind: RulePackRuleKind) -> &'static str {
294    match kind {
295        RulePackRuleKind::BannedCall => "banned-call",
296        RulePackRuleKind::BannedImport => "banned-import",
297        RulePackRuleKind::BannedEffect => "banned-effect",
298        RulePackRuleKind::BannedExport => "banned-export",
299    }
300}
301
302fn rule_patterns(rule: &RulePackRule) -> Vec<String> {
303    match rule.kind {
304        RulePackRuleKind::BannedCall => rule.callees.clone(),
305        RulePackRuleKind::BannedImport => rule.specifiers.clone(),
306        RulePackRuleKind::BannedEffect => rule
307            .effects
308            .iter()
309            .map(|effect| effect.as_str().to_string())
310            .collect(),
311        RulePackRuleKind::BannedExport => rule.exports.clone(),
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use fallow_config::{
319        BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryRule, BoundaryZone,
320        EffectKind, FallowConfig, ForbiddenCallRule, ForbiddenCallee, OutputFormat, RulePackDef,
321        RulePackRule, RulePackRuleKind, RulesConfig, Severity,
322    };
323    use std::fs;
324
325    fn rule(id: &str, kind: RulePackRuleKind) -> RulePackRule {
326        RulePackRule {
327            id: id.to_string(),
328            kind,
329            callees: Vec::new(),
330            specifiers: Vec::new(),
331            effects: Vec::new(),
332            exports: Vec::new(),
333            ignore_type_only: false,
334            files: Vec::new(),
335            exclude: Vec::new(),
336            zones: Vec::new(),
337            message: None,
338            severity: None,
339        }
340    }
341
342    fn pack(rules: Vec<RulePackRule>) -> RulePackDef {
343        RulePackDef {
344            schema: None,
345            version: 1,
346            name: "team-policy".to_string(),
347            description: None,
348            rules,
349        }
350    }
351
352    fn resolve(root: &Path, configure: impl FnOnce(&mut FallowConfig)) -> ResolvedConfig {
353        let mut config = FallowConfig {
354            rules: RulesConfig {
355                policy_violation: Severity::Warn,
356                ..RulesConfig::default()
357            },
358            ..FallowConfig::default()
359        };
360        configure(&mut config);
361        config.resolve(root.to_path_buf(), OutputFormat::Json, 1, true, true, None)
362    }
363
364    #[test]
365    fn zoned_file_reports_allow_rule_and_forbidden_call() {
366        let temp = tempfile::tempdir().expect("tempdir");
367        fs::create_dir_all(temp.path().join("src/domain")).expect("create dir");
368        fs::write(temp.path().join("src/domain/user.ts"), "").expect("write file");
369        let config = resolve(temp.path(), |config| {
370            config.boundaries = BoundaryConfig {
371                zones: vec![
372                    BoundaryZone {
373                        name: "domain".to_string(),
374                        patterns: vec!["src/domain/**".to_string()],
375                        auto_discover: Vec::new(),
376                        root: None,
377                    },
378                    BoundaryZone {
379                        name: "shared".to_string(),
380                        patterns: vec!["src/shared/**".to_string()],
381                        auto_discover: Vec::new(),
382                        root: None,
383                    },
384                ],
385                rules: vec![BoundaryRule {
386                    from: "domain".to_string(),
387                    allow: vec!["shared".to_string()],
388                    allow_type_only: vec!["ui".to_string()],
389                }],
390                calls: BoundaryCallsConfig {
391                    forbidden: vec![ForbiddenCallRule {
392                        from: "domain".to_string(),
393                        callee: ForbiddenCallee::Single("child_process.*".to_string()),
394                    }],
395                },
396                ..BoundaryConfig::default()
397            };
398        });
399
400        let report =
401            build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
402        let file = &report.files[0];
403
404        assert!(file.exists);
405        assert_eq!(
406            file.zone.as_ref().map(|zone| zone.name.as_str()),
407            Some("domain")
408        );
409        assert!(!file.boundary.unrestricted);
410        assert_eq!(file.boundary.allowed_zones, vec!["domain", "shared"]);
411        assert_eq!(file.boundary.allowed_type_only_zones, vec!["ui"]);
412        assert_eq!(file.boundary.forbidden_calls, vec!["child_process.*"]);
413        assert!(file.notes.iter().any(|note| note.contains("Same-zone")));
414    }
415
416    fn required_coverage_config(root: &Path) -> ResolvedConfig {
417        resolve(root, |config| {
418            config.boundaries = BoundaryConfig {
419                zones: vec![BoundaryZone {
420                    name: "domain".to_string(),
421                    patterns: vec!["src/domain/**".to_string()],
422                    auto_discover: Vec::new(),
423                    root: None,
424                }],
425                coverage: BoundaryCoverageConfig {
426                    require_all_files: true,
427                    allow_unmatched: vec!["src/generated/**".to_string()],
428                },
429                ..BoundaryConfig::default()
430            };
431        })
432    }
433
434    #[test]
435    fn unzoned_file_reports_required_coverage() {
436        let temp = tempfile::tempdir().expect("tempdir");
437        let config = required_coverage_config(temp.path());
438
439        let report =
440            build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
441        let file = &report.files[0];
442
443        assert!(file.zone.is_none());
444        assert!(file.boundary.unrestricted);
445        assert!(file.boundary.coverage_required);
446        assert!(
447            file.notes
448                .iter()
449                .any(|note| note.contains("outside every zone"))
450        );
451
452        let allowed =
453            build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
454        assert!(!allowed.files[0].boundary.coverage_required);
455    }
456
457    #[test]
458    fn required_coverage_notes_state_the_requirement() {
459        let temp = tempfile::tempdir().expect("tempdir");
460        let config = required_coverage_config(temp.path());
461
462        let report =
463            build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
464        let notes = &report.files[0].notes;
465
466        assert!(
467            notes
468                .iter()
469                .any(|note| note.contains("requireAllFiles") && note.contains("boundary-coverage")),
470            "unzoned file under required coverage must state the requirement: {notes:?}"
471        );
472        assert!(
473            !notes
474                .iter()
475                .any(|note| note.contains("unrestricted for boundary checks")),
476            "the unrestricted note must not claim to cover the coverage check: {notes:?}"
477        );
478
479        let allowed =
480            build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
481        assert!(
482            !allowed.files[0]
483                .notes
484                .iter()
485                .any(|note| note.contains("requireAllFiles")),
486            "allowUnmatched paths must not state a coverage requirement"
487        );
488    }
489
490    #[test]
491    fn pack_rule_scope_filters_policy_rules() {
492        let temp = tempfile::tempdir().expect("tempdir");
493        let mut domain_rule = rule("pure-domain", RulePackRuleKind::BannedEffect);
494        domain_rule.effects = vec![EffectKind::Network];
495        domain_rule.files = vec!["src/domain/**".to_string()];
496        let mut excluded_rule = rule("no-generated-process", RulePackRuleKind::BannedCall);
497        excluded_rule.callees = vec!["child_process.*".to_string()];
498        excluded_rule.exclude = vec!["src/domain/**".to_string()];
499        let mut config = resolve(temp.path(), |_| {});
500        config.rule_packs = vec![pack(vec![domain_rule, excluded_rule])];
501
502        let report =
503            build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
504        let rules = &report.files[0].policy_rules;
505
506        assert_eq!(rules.len(), 1);
507        assert_eq!(rules[0].rule_id, "pure-domain");
508        assert_eq!(rules[0].kind, "banned-effect");
509        assert_eq!(rules[0].patterns, vec!["network"]);
510        assert_eq!(
511            rules[0].suppress_token,
512            "policy-violation:team-policy/pure-domain"
513        );
514        assert_eq!(rules[0].severity, "warn");
515    }
516
517    #[test]
518    fn compiled_rule_scopes_match_individual_file_reports() {
519        let temp = tempfile::tempdir().expect("tempdir");
520        let mut config = resolve(temp.path(), |config| {
521            config.boundaries = BoundaryConfig {
522                zones: vec![
523                    BoundaryZone {
524                        name: "domain".to_string(),
525                        patterns: vec!["src/domain/**".to_string()],
526                        auto_discover: Vec::new(),
527                        root: None,
528                    },
529                    BoundaryZone {
530                        name: "app".to_string(),
531                        patterns: vec!["src/app/**".to_string()],
532                        auto_discover: Vec::new(),
533                        root: None,
534                    },
535                ],
536                ..BoundaryConfig::default()
537            };
538        });
539        let mut domain_rule = rule("domain-only", RulePackRuleKind::BannedImport);
540        domain_rule.files = vec!["src/domain/**".to_string()];
541        domain_rule.exclude = vec!["src/domain/generated/**".to_string()];
542        let mut app_rule = rule("app-zone", RulePackRuleKind::BannedCall);
543        app_rule.zones = vec!["app".to_string()];
544        let mut invalid_glob_rule = rule("invalid-glob", RulePackRuleKind::BannedExport);
545        invalid_glob_rule.files = vec!["[".to_string()];
546        config.rule_packs = vec![pack(vec![domain_rule, app_rule, invalid_glob_rule])];
547
548        let files = vec![
549            "src/domain/user.ts".to_string(),
550            "src/domain/generated/client.ts".to_string(),
551            "src/app/page.ts".to_string(),
552            "src/other.ts".to_string(),
553        ];
554        let batch = build_guard_report(&config, &files).expect("batch report");
555        let individual = files
556            .iter()
557            .flat_map(|file| {
558                build_guard_report(&config, std::slice::from_ref(file))
559                    .expect("individual report")
560                    .files
561            })
562            .collect::<Vec<_>>();
563
564        assert_eq!(
565            serde_json::to_value(&batch.files).expect("serialize batch reports"),
566            serde_json::to_value(&individual).expect("serialize individual reports")
567        );
568        let rule_ids = batch
569            .files
570            .iter()
571            .map(|file| {
572                file.policy_rules
573                    .iter()
574                    .map(|rule| rule.rule_id.as_str())
575                    .collect::<Vec<_>>()
576            })
577            .collect::<Vec<_>>();
578        assert_eq!(
579            rule_ids,
580            vec![
581                vec!["domain-only", "invalid-glob"],
582                vec!["invalid-glob"],
583                vec!["app-zone", "invalid-glob"],
584                vec!["invalid-glob"],
585            ]
586        );
587    }
588
589    #[test]
590    fn nonexistent_target_reports_exists_false() {
591        let temp = tempfile::tempdir().expect("tempdir");
592        let config = resolve(temp.path(), |_| {});
593
594        let report = build_guard_report(&config, &["src/missing.ts".to_string()]).expect("report");
595
596        assert_eq!(report.files[0].path, "src/missing.ts");
597        assert!(!report.files[0].exists);
598    }
599
600    #[test]
601    fn path_outside_root_errors() {
602        let temp = tempfile::tempdir().expect("tempdir");
603        let config = resolve(temp.path(), |_| {});
604
605        let err = build_guard_report(&config, &["../outside.ts".to_string()]).unwrap_err();
606
607        assert!(matches!(err, GuardError::OutsideRoot(_)));
608    }
609}