1use 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#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum GuardError {
15 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
29pub 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
227struct 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 },
394 BoundaryZone {
395 name: "shared".to_string(),
396 patterns: vec!["src/shared/**".to_string()],
397 auto_discover: Vec::new(),
398 root: None,
399 },
400 ],
401 rules: vec![BoundaryRule {
402 from: "domain".to_string(),
403 allow: vec!["shared".to_string()],
404 allow_type_only: vec!["ui".to_string()],
405 }],
406 calls: BoundaryCallsConfig {
407 forbidden: vec![ForbiddenCallRule {
408 from: "domain".to_string(),
409 callee: ForbiddenCallee::Single("child_process.*".to_string()),
410 }],
411 },
412 ..BoundaryConfig::default()
413 };
414 });
415
416 let report =
417 build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
418 let file = &report.files[0];
419
420 assert!(file.exists);
421 assert_eq!(
422 file.zone.as_ref().map(|zone| zone.name.as_str()),
423 Some("domain")
424 );
425 assert!(!file.boundary.unrestricted);
426 assert_eq!(file.boundary.allowed_zones, vec!["domain", "shared"]);
427 assert_eq!(file.boundary.allowed_type_only_zones, vec!["ui"]);
428 assert_eq!(file.boundary.forbidden_calls, vec!["child_process.*"]);
429 assert!(file.notes.iter().any(|note| note.contains("Same-zone")));
430 }
431
432 fn required_coverage_config(root: &Path) -> ResolvedConfig {
433 resolve(root, |config| {
434 config.boundaries = BoundaryConfig {
435 zones: vec![BoundaryZone {
436 name: "domain".to_string(),
437 patterns: vec!["src/domain/**".to_string()],
438 auto_discover: Vec::new(),
439 root: None,
440 }],
441 coverage: BoundaryCoverageConfig {
442 require_all_files: true,
443 allow_unmatched: vec!["src/generated/**".to_string()],
444 },
445 ..BoundaryConfig::default()
446 };
447 })
448 }
449
450 #[test]
451 fn unzoned_file_reports_required_coverage() {
452 let temp = tempfile::tempdir().expect("tempdir");
453 let config = required_coverage_config(temp.path());
454
455 let report =
456 build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
457 let file = &report.files[0];
458
459 assert!(file.zone.is_none());
460 assert!(file.boundary.unrestricted);
461 assert!(file.boundary.coverage_required);
462 assert!(
463 file.notes
464 .iter()
465 .any(|note| note.contains("outside every zone"))
466 );
467
468 let allowed =
469 build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
470 assert!(!allowed.files[0].boundary.coverage_required);
471 }
472
473 #[test]
474 fn required_coverage_notes_state_the_requirement() {
475 let temp = tempfile::tempdir().expect("tempdir");
476 let config = required_coverage_config(temp.path());
477
478 let report =
479 build_guard_report(&config, &["src/ui/button.ts".to_string()]).expect("report");
480 let notes = &report.files[0].notes;
481
482 assert!(
483 notes
484 .iter()
485 .any(|note| note.contains("requireAllFiles") && note.contains("boundary-coverage")),
486 "unzoned file under required coverage must state the requirement: {notes:?}"
487 );
488 assert!(
489 !notes
490 .iter()
491 .any(|note| note.contains("unrestricted for boundary checks")),
492 "the unrestricted note must not claim to cover the coverage check: {notes:?}"
493 );
494
495 let allowed =
496 build_guard_report(&config, &["src/generated/client.ts".to_string()]).expect("report");
497 assert!(
498 !allowed.files[0]
499 .notes
500 .iter()
501 .any(|note| note.contains("requireAllFiles")),
502 "allowUnmatched paths must not state a coverage requirement"
503 );
504 }
505
506 #[test]
507 fn pack_rule_scope_filters_policy_rules() {
508 let temp = tempfile::tempdir().expect("tempdir");
509 let mut domain_rule = rule("pure-domain", RulePackRuleKind::BannedEffect);
510 domain_rule.effects = vec![EffectKind::Network];
511 domain_rule.files = vec!["src/domain/**".to_string()];
512 let mut excluded_rule = rule("no-generated-process", RulePackRuleKind::BannedCall);
513 excluded_rule.callees = vec!["child_process.*".to_string()];
514 excluded_rule.exclude = vec!["src/domain/**".to_string()];
515 let mut config = resolve(temp.path(), |_| {});
516 config.rule_packs = vec![pack(vec![domain_rule, excluded_rule])];
517
518 let report =
519 build_guard_report(&config, &["src/domain/user.ts".to_string()]).expect("report");
520 let rules = &report.files[0].policy_rules;
521
522 assert_eq!(rules.len(), 1);
523 assert_eq!(rules[0].rule_id, "pure-domain");
524 assert_eq!(rules[0].kind, "banned-effect");
525 assert_eq!(rules[0].patterns, vec!["network"]);
526 assert_eq!(
527 rules[0].suppress_token,
528 "policy-violation:team-policy/pure-domain"
529 );
530 assert_eq!(rules[0].severity, "warn");
531 }
532
533 #[test]
534 fn compiled_rule_scopes_match_individual_file_reports() {
535 let temp = tempfile::tempdir().expect("tempdir");
536 let mut config = resolve(temp.path(), |config| {
537 config.boundaries = BoundaryConfig {
538 zones: vec![
539 BoundaryZone {
540 name: "domain".to_string(),
541 patterns: vec!["src/domain/**".to_string()],
542 auto_discover: Vec::new(),
543 root: None,
544 },
545 BoundaryZone {
546 name: "app".to_string(),
547 patterns: vec!["src/app/**".to_string()],
548 auto_discover: Vec::new(),
549 root: None,
550 },
551 ],
552 ..BoundaryConfig::default()
553 };
554 });
555 let mut domain_rule = rule("domain-only", RulePackRuleKind::BannedImport);
556 domain_rule.files = vec!["src/domain/**".to_string()];
557 domain_rule.exclude = vec!["src/domain/generated/**".to_string()];
558 let mut app_rule = rule("app-zone", RulePackRuleKind::BannedCall);
559 app_rule.zones = vec!["app".to_string()];
560 let mut invalid_glob_rule = rule("invalid-glob", RulePackRuleKind::BannedExport);
561 invalid_glob_rule.files = vec!["[".to_string()];
562 config.rule_packs = vec![pack(vec![domain_rule, app_rule, invalid_glob_rule])];
563
564 let files = vec![
565 "src/domain/user.ts".to_string(),
566 "src/domain/generated/client.ts".to_string(),
567 "src/app/page.ts".to_string(),
568 "src/other.ts".to_string(),
569 ];
570 let batch = build_guard_report(&config, &files).expect("batch report");
571 let individual = files
572 .iter()
573 .flat_map(|file| {
574 build_guard_report(&config, std::slice::from_ref(file))
575 .expect("individual report")
576 .files
577 })
578 .collect::<Vec<_>>();
579
580 assert_eq!(
581 serde_json::to_value(&batch.files).expect("serialize batch reports"),
582 serde_json::to_value(&individual).expect("serialize individual reports")
583 );
584 let rule_ids = batch
585 .files
586 .iter()
587 .map(|file| {
588 file.policy_rules
589 .iter()
590 .map(|rule| rule.rule_id.as_str())
591 .collect::<Vec<_>>()
592 })
593 .collect::<Vec<_>>();
594 assert_eq!(
595 rule_ids,
596 vec![
597 vec!["domain-only", "invalid-glob"],
598 vec!["invalid-glob"],
599 vec!["app-zone", "invalid-glob"],
600 vec!["invalid-glob"],
601 ]
602 );
603 }
604
605 #[test]
606 fn nonexistent_target_reports_exists_false() {
607 let temp = tempfile::tempdir().expect("tempdir");
608 let config = resolve(temp.path(), |_| {});
609
610 let report = build_guard_report(&config, &["src/missing.ts".to_string()]).expect("report");
611
612 assert_eq!(report.files[0].path, "src/missing.ts");
613 assert!(!report.files[0].exists);
614 }
615
616 #[test]
617 fn path_outside_root_errors() {
618 let temp = tempfile::tempdir().expect("tempdir");
619 let config = resolve(temp.path(), |_| {});
620
621 let err = build_guard_report(&config, &["../outside.ts".to_string()]).unwrap_err();
622
623 assert!(matches!(err, GuardError::OutsideRoot(_)));
624 }
625}