vfa-tui 0.0.8

Enterprise-grade terminal UI for the Vanguard Frontier Agentic marketplace catalog
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
//! Policy TOML parser — loads `policies.toml` into [`PolicyConfig`].
//!
//! Missing file → empty config (no error, Req 11.5).
//! Syntax errors → collect with line number, skip malformed rules (Req 25.3).
//! Validate rules against catalog (Req 11.4).

#![deny(warnings)]

use std::path::Path;

use serde::Deserialize;

use crate::catalog::store::CatalogStore;
use crate::error::TuiError;
use crate::models::agent::Lifecycle;
use crate::models::policy::{PolicyRule, PolicyRuleType, PolicyScope, Severity, Suppression};

// ---------------------------------------------------------------------------
// TOML intermediate structs
// ---------------------------------------------------------------------------

/// Top-level deserialization target for `policies.toml`.
#[derive(Debug, Deserialize, Default)]
struct TomlConfig {
    #[serde(default)]
    rule: Vec<TomlRule>,
    #[serde(default)]
    suppression: Vec<TomlSuppression>,
}

/// A single `[[rule]]` entry as it appears in TOML.
#[derive(Debug, Deserialize)]
struct TomlRule {
    id: String,
    #[serde(rename = "type")]
    rule_type: String,
    severity: String,
    /// Scope: either the string "all" OR an inline table {team="…"} / {name_pattern="…"}.
    scope: toml::Value,
    description: String,
    // Type-specific optional fields
    asset_id: Option<String>,
    role_id: Option<String>,
    threshold: Option<u32>,
    max_mutation: Option<bool>,
    max_egress: Option<bool>,
    max_credentials: Option<bool>,
    min_stage: Option<String>,
}

/// A single `[[suppression]]` entry as it appears in TOML.
#[derive(Debug, Deserialize)]
struct TomlSuppression {
    rule_id: String,
    workspace: String,
    reason: String,
    #[serde(default)]
    approver: String,
    #[serde(default)]
    expires: String,
}

// ---------------------------------------------------------------------------
// PolicyConfig — the parsed result returned to callers
// ---------------------------------------------------------------------------

/// Fully-parsed policy configuration.
#[derive(Debug, Default)]
pub struct PolicyConfig {
    /// Parsed and valid policy rules.
    pub rules: Vec<PolicyRule>,
    /// Parsed suppressions.
    pub suppressions: Vec<Suppression>,
    /// True when the file was absent; callers may display a "no policies" notice.
    pub no_policies_file: bool,
    /// Parse errors collected during loading (malformed rules were skipped).
    /// Stored as error messages so PolicyConfig remains cheaply cloneable.
    pub parse_errors: Vec<String>,
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Load `policies.toml` from `path`.
///
/// - File absent → returns `PolicyConfig { no_policies_file: true, .. }`, no error.
/// - Syntax error → returns collected errors in `parse_errors`; valid rules are kept.
pub fn load(path: &Path) -> Result<PolicyConfig, TuiError> {
    if !path.exists() {
        return Ok(PolicyConfig {
            no_policies_file: true,
            ..Default::default()
        });
    }

    let content = std::fs::read_to_string(path).map_err(|e| TuiError::PolicyParse {
        path: path.display().to_string(),
        line: None,
        detail: e.to_string(),
    })?;

    parse_content(&content, path)
}

/// Parse TOML `content` as a policy config; `path` is used only for error messages.
///
/// Returns `Err` only for fatal top-level parse failures.
/// Rule-level failures are collected in `PolicyConfig::parse_errors`.
pub fn parse_content(content: &str, path: &Path) -> Result<PolicyConfig, TuiError> {
    let raw: TomlConfig = match toml::from_str(content) {
        Ok(v) => v,
        Err(e) => {
            // Extract 1-based line number from the span if available.
            let line = e.span().map(|span| {
                let before = content.get(..span.start).unwrap_or("");
                let n = before.lines().count();
                if n == 0 {
                    1usize
                } else {
                    n
                }
            });
            return Err(TuiError::PolicyParse {
                path: path.display().to_string(),
                line,
                detail: e.to_string(),
            });
        }
    };

    let mut rules = Vec::new();
    let mut parse_errors = Vec::new();

    for toml_rule in raw.rule {
        match convert_rule(toml_rule, path) {
            Ok(rule) => rules.push(rule),
            Err(e) => parse_errors.push(e.to_string()),
        }
    }

    let suppressions: Vec<Suppression> = raw
        .suppression
        .into_iter()
        .map(|s| Suppression {
            rule_id: s.rule_id,
            workspace: s.workspace,
            reason: s.reason,
            approver: s.approver,
            expires: s.expires,
        })
        .collect();

    Ok(PolicyConfig {
        rules,
        suppressions,
        no_policies_file: false,
        parse_errors,
    })
}

/// Validate rules in `config` against the catalog, returning errors for references
/// to nonexistent assets or roles (Req 11.4).
pub fn validate_rules(config: &PolicyConfig, catalog: &CatalogStore) -> Vec<TuiError> {
    let mut errors = Vec::new();
    let asset_ids = catalog.all_asset_ids();

    for rule in &config.rules {
        match &rule.rule_type {
            PolicyRuleType::RequireAsset { asset_id } if !asset_ids.contains(asset_id) => {
                errors.push(TuiError::PolicyInvalidRule {
                    rule: rule.id.clone(),
                    reason: format!("references nonexistent asset '{}'", asset_id),
                });
            }
            PolicyRuleType::RequireRole { role_id }
                if !catalog.roles.contains_key(role_id.as_str()) =>
            {
                errors.push(TuiError::PolicyInvalidRule {
                    rule: rule.id.clone(),
                    reason: format!("references nonexistent role '{}'", role_id),
                });
            }
            // Satisfied RequireAsset/RequireRole references, plus MaxStale,
            // TrustBoundary, and LifecycleGate, have no catalog refs to validate.
            _ => {}
        }
    }

    errors
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

fn convert_severity(s: &str, rule_id: &str, path: &Path) -> Result<Severity, TuiError> {
    match s.to_lowercase().as_str() {
        "critical" => Ok(Severity::Critical),
        "warning" => Ok(Severity::Warning),
        "info" => Ok(Severity::Info),
        other => Err(TuiError::PolicyParse {
            path: path.display().to_string(),
            line: None,
            detail: format!("rule '{}': unknown severity '{}'", rule_id, other),
        }),
    }
}

fn convert_scope(val: &toml::Value, rule_id: &str, path: &Path) -> Result<PolicyScope, TuiError> {
    match val {
        toml::Value::String(s) if s == "all" => Ok(PolicyScope::All),
        toml::Value::Table(t) => {
            if let Some(toml::Value::String(team)) = t.get("team") {
                Ok(PolicyScope::Team(team.clone()))
            } else if let Some(toml::Value::String(pat)) = t.get("name_pattern") {
                Ok(PolicyScope::NamePattern(pat.clone()))
            } else {
                Err(TuiError::PolicyParse {
                    path: path.display().to_string(),
                    line: None,
                    detail: format!(
                        "rule '{}': scope table must have 'team' or 'name_pattern'",
                        rule_id
                    ),
                })
            }
        }
        _ => Err(TuiError::PolicyParse {
            path: path.display().to_string(),
            line: None,
            detail: format!(
                "rule '{}': scope must be \"all\" or a table {{team=…}} / {{name_pattern=…}}",
                rule_id
            ),
        }),
    }
}

fn convert_lifecycle(s: &str, rule_id: &str, path: &Path) -> Result<Lifecycle, TuiError> {
    match s.to_lowercase().as_str() {
        "experimental" => Ok(Lifecycle::Experimental),
        "beta" => Ok(Lifecycle::Beta),
        "stable" => Ok(Lifecycle::Stable),
        "deprecated" => Ok(Lifecycle::Deprecated),
        other => Err(TuiError::PolicyParse {
            path: path.display().to_string(),
            line: None,
            detail: format!("rule '{}': unknown lifecycle stage '{}'", rule_id, other),
        }),
    }
}

fn convert_rule(r: TomlRule, path: &Path) -> Result<PolicyRule, TuiError> {
    let severity = convert_severity(&r.severity, &r.id, path)?;
    let scope = convert_scope(&r.scope, &r.id, path)?;

    let rule_type = match r.rule_type.as_str() {
        "require_asset" => {
            let asset_id = r.asset_id.ok_or_else(|| TuiError::PolicyParse {
                path: path.display().to_string(),
                line: None,
                detail: format!("rule '{}': require_asset needs 'asset_id'", r.id),
            })?;
            PolicyRuleType::RequireAsset { asset_id }
        }
        "require_role" => {
            let role_id = r.role_id.ok_or_else(|| TuiError::PolicyParse {
                path: path.display().to_string(),
                line: None,
                detail: format!("rule '{}': require_role needs 'role_id'", r.id),
            })?;
            PolicyRuleType::RequireRole { role_id }
        }
        "max_stale" => {
            let threshold = r.threshold.ok_or_else(|| TuiError::PolicyParse {
                path: path.display().to_string(),
                line: None,
                detail: format!("rule '{}': max_stale needs 'threshold'", r.id),
            })?;
            PolicyRuleType::MaxStale { threshold }
        }
        "trust_boundary" => {
            let max_mutation = r.max_mutation.unwrap_or(true);
            let max_egress = r.max_egress.unwrap_or(true);
            let max_credentials = r.max_credentials.unwrap_or(true);
            PolicyRuleType::TrustBoundary {
                max_mutation,
                max_egress,
                max_credentials,
            }
        }
        "lifecycle_gate" => {
            let stage_str = r.min_stage.ok_or_else(|| TuiError::PolicyParse {
                path: path.display().to_string(),
                line: None,
                detail: format!("rule '{}': lifecycle_gate needs 'min_stage'", r.id),
            })?;
            let min_stage = convert_lifecycle(&stage_str, &r.id, path)?;
            PolicyRuleType::LifecycleGate { min_stage }
        }
        other => {
            return Err(TuiError::PolicyParse {
                path: path.display().to_string(),
                line: None,
                detail: format!("rule '{}': unknown rule type '{}'", r.id, other),
            });
        }
    };

    Ok(PolicyRule {
        id: r.id,
        rule_type,
        severity,
        scope,
        description: r.description,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn path() -> &'static Path {
        Path::new("policies.toml")
    }

    #[test]
    fn parse_full_policy_toml() {
        let toml = r#"
[[rule]]
id = "require-scanner"
type = "require_asset"
asset_id = "aws-iam-analyzer"
severity = "critical"
scope = "all"
description = "Need scanner"

[[rule]]
id = "require-role"
type = "require_role"
role_id = "cloud-security-engineer"
severity = "warning"
scope = { team = "platform-security" }
description = "Need role"

[[rule]]
id = "max-stale"
type = "max_stale"
threshold = 5
severity = "warning"
scope = "all"
description = "Max stale"

[[rule]]
id = "trust-boundary"
type = "trust_boundary"
max_mutation = false
max_egress = true
max_credentials = true
severity = "critical"
scope = { name_pattern = "production-*" }
description = "Trust boundary"

[[rule]]
id = "lifecycle-gate"
type = "lifecycle_gate"
min_stage = "stable"
severity = "critical"
scope = { name_pattern = "production-*" }
description = "Lifecycle gate"

[[suppression]]
rule_id = "trust-boundary"
workspace = "staging-infra"
reason = "Approved"
approver = "lead@example.com"
expires = "2025-06-01"
"#;
        let cfg = parse_content(toml, path()).unwrap();
        assert_eq!(cfg.rules.len(), 5);
        assert_eq!(cfg.suppressions.len(), 1);
        assert!(!cfg.no_policies_file);
        assert!(cfg.parse_errors.is_empty());
    }

    #[test]
    fn missing_file_gives_empty_config() {
        let cfg = load(Path::new("/nonexistent/policies.toml")).unwrap();
        assert!(cfg.no_policies_file);
        assert!(cfg.rules.is_empty());
    }

    #[test]
    fn malformed_rule_is_skipped_but_valid_rules_kept() {
        let toml = r#"
[[rule]]
id = "good-rule"
type = "max_stale"
threshold = 3
severity = "warning"
scope = "all"
description = "OK"

[[rule]]
id = "bad-rule"
type = "require_asset"
# missing asset_id — should be skipped
severity = "critical"
scope = "all"
description = "Missing asset_id"
"#;
        let cfg = parse_content(toml, path()).unwrap();
        assert_eq!(cfg.rules.len(), 1, "expected 1 valid rule");
        assert_eq!(cfg.rules[0].id, "good-rule");
        assert_eq!(cfg.parse_errors.len(), 1, "expected 1 parse error");
    }

    #[test]
    fn validate_rules_catches_nonexistent_asset() {
        let toml = r#"
[[rule]]
id = "bad-asset"
type = "require_asset"
asset_id = "nonexistent-asset-xyz"
severity = "critical"
scope = "all"
description = "Bad"
"#;
        let cfg = parse_content(toml, path()).unwrap();
        let store = CatalogStore::from_parts(vec![], vec![], HashMap::new(), vec![], vec![]);
        let errors = validate_rules(&cfg, &store);
        assert_eq!(errors.len(), 1);
        assert!(
            matches!(&errors[0], TuiError::PolicyInvalidRule { rule, .. } if rule == "bad-asset")
        );
    }

    #[test]
    fn validate_rules_catches_nonexistent_role() {
        let toml = r#"
[[rule]]
id = "bad-role"
type = "require_role"
role_id = "nonexistent-role-xyz"
severity = "warning"
scope = "all"
description = "Bad"
"#;
        let cfg = parse_content(toml, path()).unwrap();
        let store = CatalogStore::from_parts(vec![], vec![], HashMap::new(), vec![], vec![]);
        let errors = validate_rules(&cfg, &store);
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn invalid_rule_type_is_collected_as_error() {
        let toml = r#"
[[rule]]
id = "unknown-type"
type = "future_rule"
severity = "info"
scope = "all"
description = "Future"
"#;
        let cfg = parse_content(toml, path()).unwrap();
        assert!(cfg.rules.is_empty());
        assert_eq!(cfg.parse_errors.len(), 1);
    }

    proptest::proptest! {
        #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))]

        #[test]
        fn parse_does_not_panic_on_arbitrary_input(s in ".*") {
            // Must never panic — may return Ok or Err.
            let _ = parse_content(&s, path());
        }
    }
}