aaai-core 0.27.0

Core engine for aaai — audit for asset integrity
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
//! Audit definition — the "expected values" YAML document (version 1).
//!
//! # Phase 3 additions
//!
//! Each [`AuditEntry`] now carries optional metadata for traceability:
//!
//! ```yaml
//! - path: "config/server.toml"
//!   diff_type: Modified
//!   reason: "Port change — INF-42"
//!   ticket: "INF-42"
//!   approved_by: "alice"
//!   approved_at: "2025-01-15T09:23:00Z"
//!   expires_at: "2025-07-01"
//!   strategy:
//!     type: LineMatch
//!     rules:
//!       - action: Removed
//!         line: "port = 80"
//!       - action: Added
//!         line: "port = 8080"
//!   enabled: true
//! ```

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};

use crate::diff::entry::DiffType;

// ── Top-level document ────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditDefinition {
    pub version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<AuditMeta>,
    #[serde(default)]
    pub entries: Vec<AuditEntry>,
}

impl AuditDefinition {
    pub fn new_empty() -> Self {
        Self { version: "1".into(), meta: None, entries: Vec::new() }
    }

    /// Find by exact path first, then by first matching glob.
    pub fn find_entry(&self, path: &str) -> Option<&AuditEntry> {
        self.entries.iter().find(|e| !e.is_glob() && e.path == path)
            .or_else(|| self.entries.iter().find(|e| e.is_glob() && e.glob_matches(path)))
    }

    pub fn find_entry_mut(&mut self, path: &str) -> Option<&mut AuditEntry> {
        self.entries.iter_mut().find(|e| !e.is_glob() && e.path == path)
    }

    pub fn upsert_entry(&mut self, entry: AuditEntry) {
        if let Some(existing) = self.find_entry_mut(&entry.path.clone()) {
            *existing = entry;
        } else {
            self.entries.push(entry);
        }
    }

    /// Return all entries whose `expires_at` is today or in the past.
    pub fn expired_entries(&self) -> Vec<&AuditEntry> {
        let today = Utc::now().date_naive();
        self.entries.iter()
            .filter(|e| e.expires_at.map_or(false, |d| d <= today))
            .collect()
    }

    /// Return entries expiring within `days` days from today.
    pub fn expiring_soon(&self, days: i64) -> Vec<&AuditEntry> {
        let today = Utc::now().date_naive();
        let threshold = today + chrono::Duration::days(days);
        self.entries.iter()
            .filter(|e| e.expires_at.map_or(false, |d| d > today && d <= threshold))
            .collect()
    }
}

// ── Metadata ─────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

// ── Per-file entry ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Root-relative path or glob pattern.
    pub path: String,
    pub diff_type: DiffType,
    /// Mandatory human-readable justification.
    pub reason: String,
    #[serde(default)]
    pub strategy: AuditStrategy,
    #[serde(default = "default_true")]
    pub enabled: bool,

    // ── Phase 3: traceability fields ────────────────────────────────────
    /// Ticket or issue reference (e.g. "JIRA-123", "INF-42").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ticket: Option<String>,

    /// Identity of the person who approved this entry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_by: Option<String>,

    /// UTC timestamp when approval was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_at: Option<DateTime<Utc>>,

    /// Date after which this entry should be re-reviewed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<NaiveDate>,

    /// Free-form note (stored but not used for judgement).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,

    // ── Phase 6: versioning ──────────────────────────────────────────
    /// UTC timestamp when this entry was first created.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_at: Option<DateTime<Utc>>,

    /// UTC timestamp when this entry was last modified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<DateTime<Utc>>,
}

fn default_true() -> bool { true }

impl AuditEntry {
    pub fn is_glob(&self) -> bool {
        self.path.contains('*') || self.path.contains('?') || self.path.contains('[')
    }

    pub fn glob_matches(&self, candidate: &str) -> bool {
        if !self.is_glob() { return self.path == candidate; }
        glob::Pattern::new(&self.path)
            .map(|p| p.matches(candidate))
            .unwrap_or(false)
    }

    /// True if `expires_at` is today or in the past.
    pub fn is_expired(&self) -> bool {
        self.expires_at.map_or(false, |d| d <= Utc::now().date_naive())
    }

    /// True if expiring within `days` days but not yet expired.
    pub fn expires_soon(&self, days: i64) -> bool {
        let today = Utc::now().date_naive();
        let threshold = today + chrono::Duration::days(days);
        self.expires_at.map_or(false, |d| d > today && d <= threshold)
    }

    /// Stamp created_at (first time) and updated_at (always) with the current UTC time.
    pub fn stamp_now(&mut self) {
        let now = Utc::now();
        if self.created_at.is_none() {
            self.created_at = Some(now);
        }
        self.updated_at = Some(now);
    }

    pub fn is_approvable(&self) -> Result<(), String> {
        if self.path.trim().is_empty() {
            return Err("Path must not be empty.".into());
        }
        if self.reason.trim().is_empty() {
            return Err("Reason must not be empty.".into());
        }
        self.strategy.validate()?;
        Ok(())
    }
}

// ── Content-audit strategy ────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum AuditStrategy {
    None,
    Checksum { expected_sha256: String },
    LineMatch { rules: Vec<LineRule> },
    Regex { pattern: String, #[serde(default)] target: RegexTarget },
    Exact { expected_content: String },
}

impl Default for AuditStrategy {
    fn default() -> Self { AuditStrategy::None }
}

impl AuditStrategy {
    #[allow(dead_code)]
    pub fn label(&self) -> &'static str {
        match self {
            AuditStrategy::None           => "None",
            AuditStrategy::Checksum { .. } => "Checksum",
            AuditStrategy::LineMatch { .. } => "LineMatch",
            AuditStrategy::Regex { .. }    => "Regex",
            AuditStrategy::Exact { .. }    => "Exact",
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            AuditStrategy::None =>
                "Checks only that the expected change type occurred. No content inspection.",
            AuditStrategy::Checksum { .. } =>
                "Verifies the file's SHA-256 digest. Best for binaries, images, archives.",
            AuditStrategy::LineMatch { .. } =>
                "Verifies specific lines were added or removed. Primary strategy for config changes.",
            AuditStrategy::Regex { .. } =>
                "Verifies changed lines match a regular expression. Good for environment-dependent values.",
            AuditStrategy::Exact { .. } =>
                "Verifies the file's full content exactly matches expected text. Avoid for large files.",
        }
    }

    pub fn validate(&self) -> Result<(), String> {
        match self {
            AuditStrategy::None => Ok(()),
            AuditStrategy::Checksum { expected_sha256 } => {
                if expected_sha256.trim().is_empty() {
                    return Err("Checksum: expected_sha256 must not be empty.".into());
                }
                if !expected_sha256.chars().all(|c| c.is_ascii_hexdigit()) {
                    return Err("Checksum: expected_sha256 must be a valid hex string.".into());
                }
                if expected_sha256.len() != 64 {
                    return Err("Checksum: must be a 64-character SHA-256 hex digest.".into());
                }
                Ok(())
            }
            AuditStrategy::LineMatch { rules } => {
                if rules.is_empty() {
                    return Err("LineMatch: at least one rule is required.".into());
                }
                for (i, r) in rules.iter().enumerate() {
                    if r.line.trim().is_empty() {
                        return Err(format!("LineMatch rule {}: line must not be empty.", i + 1));
                    }
                }
                Ok(())
            }
            AuditStrategy::Regex { pattern, .. } => {
                if pattern.trim().is_empty() {
                    return Err("Regex: pattern must not be empty.".into());
                }
                regex::Regex::new(pattern)
                    .map(|_| ())
                    .map_err(|e| format!("Regex: invalid pattern — {e}"))
            }
            AuditStrategy::Exact { expected_content } => {
                if expected_content.is_empty() {
                    return Err("Exact: expected_content must not be empty.".into());
                }
                Ok(())
            }
        }
    }
}

// ── LineMatch rule ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineRule {
    pub action: LineAction,
    pub line: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LineAction { Added, Removed }

impl std::fmt::Display for LineAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LineAction::Added   => write!(f, "Added"),
            LineAction::Removed => write!(f, "Removed"),
        }
    }
}

// ── Regex target ──────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RegexTarget {
    #[default] AddedLines,
    RemovedLines,
    AllChangedLines,
}

impl std::fmt::Display for RegexTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RegexTarget::AddedLines      => write!(f, "Added lines"),
            RegexTarget::RemovedLines    => write!(f, "Removed lines"),
            RegexTarget::AllChangedLines => write!(f, "All changed lines"),
        }
    }
}

// ── RFC 066: AuditDefinition direct unit tests ────────────────────────────
#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, Utc};

    fn entry(path: &str) -> AuditEntry {
        AuditEntry {
            path: path.to_string(),
            diff_type: crate::DiffType::Modified,
            reason: "test reason".into(),
            strategy: AuditStrategy::None,
            enabled: true,
            ticket: None,
            approved_by: None,
            approved_at: None,
            expires_at: None,
            note: None,
            created_at: None,
            updated_at: None,
        }
    }

    // find_entry — exact match
    #[test]
    fn find_entry_exact_match() {
        let mut def = AuditDefinition::new_empty();
        def.upsert_entry(entry("src/main.rs"));
        assert!(def.find_entry("src/main.rs").is_some());
        assert!(def.find_entry("src/lib.rs").is_none());
    }

    // find_entry — glob fallback after exact miss
    #[test]
    fn find_entry_glob_fallback() {
        let mut def = AuditDefinition::new_empty();
        def.upsert_entry(entry("node_modules/**"));
        // exact path should match via glob
        assert!(def.find_entry("node_modules/lodash/index.js").is_some(),
            "glob entry should match concrete path");
        assert!(def.find_entry("src/main.rs").is_none(),
            "glob should not match unrelated path");
    }

    // exact entry wins over glob when both present
    #[test]
    fn find_entry_exact_wins_over_glob() {
        let mut def = AuditDefinition::new_empty();
        def.upsert_entry(entry("node_modules/**"));
        let mut specific = entry("node_modules/lodash/index.js");
        specific.reason = "specific override".into();
        def.upsert_entry(specific);
        let found = def.find_entry("node_modules/lodash/index.js").unwrap();
        assert_eq!(found.reason, "specific override",
            "exact path should take precedence over glob");
    }

    // is_glob
    #[test]
    fn is_glob_detection() {
        assert!(entry("src/**").is_glob());
        assert!(entry("**/*.rs").is_glob());
        assert!(entry("src/?.rs").is_glob());
        assert!(entry("[ab].rs").is_glob());
        assert!(!entry("src/main.rs").is_glob());
        assert!(!entry("a/b/c.txt").is_glob());
    }

    // glob_matches edge cases
    #[test]
    fn glob_matches_depth() {
        let e = entry("dist/**");
        assert!(e.glob_matches("dist/bundle.js"));
        assert!(e.glob_matches("dist/css/style.css"));
        assert!(!e.glob_matches("src/main.rs"));
    }

    #[test]
    fn glob_matches_extension_pattern() {
        let e = entry("**/*.lock");
        assert!(e.glob_matches("Cargo.lock"));
        assert!(e.glob_matches("package-lock.json") == false,
            "*.lock should not match .json");
        assert!(e.glob_matches("sub/dir/yarn.lock"));
    }

    // upsert_entry — updates in place
    #[test]
    fn upsert_entry_updates_existing() {
        let mut def = AuditDefinition::new_empty();
        def.upsert_entry(entry("a.txt"));
        assert_eq!(def.entries.len(), 1);
        let mut updated = entry("a.txt");
        updated.reason = "updated".into();
        def.upsert_entry(updated);
        assert_eq!(def.entries.len(), 1, "should not duplicate");
        assert_eq!(def.entries[0].reason, "updated");
    }

    // expired_entries
    #[test]
    fn expired_entries_detects_past_date() {
        let mut def = AuditDefinition::new_empty();
        let mut e = entry("old.txt");
        e.expires_at = Some((Utc::now() - Duration::days(1)).date_naive());
        def.upsert_entry(e);
        def.upsert_entry(entry("current.txt"));
        let expired = def.expired_entries();
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0].path, "old.txt");
    }

    // expiring_soon
    #[test]
    fn expiring_soon_within_window() {
        let mut def = AuditDefinition::new_empty();
        let mut e = entry("soon.txt");
        e.expires_at = Some((Utc::now() + Duration::days(10)).date_naive());
        def.upsert_entry(e);
        let mut far = entry("far.txt");
        far.expires_at = Some((Utc::now() + Duration::days(60)).date_naive());
        def.upsert_entry(far);
        let soon = def.expiring_soon(30);
        assert_eq!(soon.len(), 1);
        assert_eq!(soon[0].path, "soon.txt");
    }

    // is_approvable
    #[test]
    fn is_approvable_requires_non_empty_reason() {
        let mut e = entry("a.txt");
        assert!(e.is_approvable().is_ok());
        e.reason = "  ".into();   // whitespace-only
        assert!(e.is_approvable().is_err(), "whitespace-only reason should fail");
        e.reason = String::new();
        assert!(e.is_approvable().is_err(), "empty reason should fail");
    }
}