bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
//! Golden Trace Regression Detection (§6)
//!
//! This module provides golden trace capture and comparison for installer regression detection.
//! It is designed for future integration with [renacer](https://github.com/paiml/renacer)
//! for syscall-level tracing.
//!
//! # Example
//!
//! ```ignore
//! use bashrs::installer::{GoldenTraceManager, GoldenTraceConfig};
//!
//! let manager = GoldenTraceManager::new(".golden-traces");
//! manager.capture("install-v1", &installer)?;
//! let comparison = manager.compare("install-v1", &installer)?;
//! ```

use crate::models::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

/// Golden trace configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoldenTraceConfig {
    /// Enable golden trace capture/comparison
    #[serde(default)]
    pub enabled: bool,

    /// Directory for storing golden traces
    #[serde(default = "default_trace_dir")]
    pub trace_dir: String,

    /// Syscall categories to capture
    #[serde(default = "default_capture_categories")]
    pub capture: Vec<String>,

    /// Paths to ignore (noise reduction)
    #[serde(default = "default_ignore_paths")]
    pub ignore_paths: Vec<String>,
}

fn default_trace_dir() -> String {
    ".golden-traces".to_string()
}

fn default_capture_categories() -> Vec<String> {
    vec![
        "file".to_string(),
        "network".to_string(),
        "process".to_string(),
        "permission".to_string(),
    ]
}

fn default_ignore_paths() -> Vec<String> {
    vec![
        "/proc/*".to_string(),
        "/sys/*".to_string(),
        "/dev/null".to_string(),
        "/tmp/bashrs-*".to_string(),
    ]
}

impl Default for GoldenTraceConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            trace_dir: default_trace_dir(),
            capture: default_capture_categories(),
            ignore_paths: default_ignore_paths(),
        }
    }
}

/// Event type in a trace
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TraceEventType {
    /// File operation (open, read, write, close, unlink)
    File {
        operation: String,
        path: String,
        flags: Option<String>,
    },
    /// Network operation (connect, bind, listen)
    Network {
        operation: String,
        address: Option<String>,
        port: Option<u16>,
    },
    /// Process operation (fork, exec, wait)
    Process {
        operation: String,
        command: Option<String>,
        args: Option<Vec<String>>,
    },
    /// Permission change (chmod, chown)
    Permission {
        operation: String,
        path: String,
        mode: Option<u32>,
    },
}

/// A trace event with timestamp and metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceEvent {
    /// Event sequence number
    pub sequence: u64,
    /// Timestamp (nanoseconds since trace start)
    pub timestamp_ns: u64,
    /// Event type and data
    pub event_type: TraceEventType,
    /// Step ID that triggered this event
    pub step_id: Option<String>,
    /// Return value or status
    pub result: TraceResult,
}

/// Result of a trace event
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TraceResult {
    /// Operation succeeded
    Success,
    /// Operation failed with error code
    Error(i32),
    /// Operation result unknown
    Unknown,
}

impl TraceEvent {
    /// Create a summary string for display
    pub fn summary(&self) -> String {
        match &self.event_type {
            TraceEventType::File {
                operation, path, ..
            } => {
                format!("{}(\"{}\")", operation, path)
            }
            TraceEventType::Network {
                operation,
                address,
                port,
            } => {
                if let (Some(addr), Some(p)) = (address, port) {
                    format!("{}({}:{})", operation, addr, p)
                } else {
                    operation.clone()
                }
            }
            TraceEventType::Process {
                operation, command, ..
            } => {
                if let Some(cmd) = command {
                    format!("{}(\"{}\")", operation, cmd)
                } else {
                    operation.clone()
                }
            }
            TraceEventType::Permission {
                operation,
                path,
                mode,
            } => {
                if let Some(m) = mode {
                    format!("{}(\"{}\", {:o})", operation, path, m)
                } else {
                    format!("{}(\"{}\")", operation, path)
                }
            }
        }
    }

    /// Get the category of this event
    pub fn category(&self) -> &'static str {
        match &self.event_type {
            TraceEventType::File { .. } => "file",
            TraceEventType::Network { .. } => "network",
            TraceEventType::Process { .. } => "process",
            TraceEventType::Permission { .. } => "permission",
        }
    }
}

/// A captured golden trace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoldenTrace {
    /// Trace name
    pub name: String,
    /// When the trace was captured
    pub captured_at: String,
    /// Installer version at capture time
    pub installer_version: String,
    /// Trace events
    pub events: Vec<TraceEvent>,
    /// Hash of the final result state
    pub result_hash: String,
    /// Number of steps executed
    pub steps_executed: usize,
    /// Total duration in milliseconds
    pub duration_ms: u64,
}

impl GoldenTrace {
    /// Save trace to file
    pub fn save(&self, path: &Path) -> Result<()> {
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| Error::Validation(format!("Failed to serialize golden trace: {}", e)))?;
        std::fs::write(path, content).map_err(|e| {
            Error::Io(std::io::Error::new(
                e.kind(),
                format!("Failed to write golden trace: {}", e),
            ))
        })?;
        Ok(())
    }

    /// Load trace from file
    pub fn load(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            Error::Io(std::io::Error::new(
                e.kind(),
                format!("Failed to read golden trace: {}", e),
            ))
        })?;
        serde_json::from_str(&content)
            .map_err(|e| Error::Validation(format!("Failed to parse golden trace: {}", e)))
    }
}

/// Comparison result between golden trace and current execution
#[derive(Debug, Clone, Default)]
pub struct TraceComparison {
    /// Events in current that weren't in golden
    pub added: Vec<TraceEvent>,
    /// Events in golden that aren't in current
    pub removed: Vec<TraceEvent>,
    /// Events that changed between golden and current
    pub changed: Vec<(TraceEvent, TraceEvent)>,
    /// Trace comparison metadata
    pub metadata: ComparisonMetadata,
}

/// Metadata about the comparison
#[derive(Debug, Clone, Default)]
pub struct ComparisonMetadata {
    /// Golden trace name
    pub golden_name: String,
    /// Golden trace timestamp
    pub golden_captured_at: String,
    /// Current execution timestamp
    pub current_captured_at: String,
    /// Number of events in golden
    pub golden_event_count: usize,
    /// Number of events in current
    pub current_event_count: usize,
}

impl TraceComparison {
    /// Check if traces are equivalent
    pub fn is_equivalent(&self) -> bool {
        self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
    }

    /// Generate a human-readable report
    pub fn to_report(&self) -> String {
        let mut report = String::new();

        report.push_str(&format!(
            "Golden Trace Comparison: {}\n",
            self.metadata.golden_name
        ));
        report.push_str(&format!(
            "Golden captured: {}, Current: {}\n",
            self.metadata.golden_captured_at, self.metadata.current_captured_at
        ));
        report.push_str(&format!(
            "Events: {} (golden) vs {} (current)\n\n",
            self.metadata.golden_event_count, self.metadata.current_event_count
        ));

        if self.is_equivalent() {
            report.push_str("✅ Traces are EQUIVALENT - no regression detected\n");
            return report;
        }

        if !self.added.is_empty() {
            report.push_str("=== New events (potential security concern) ===\n");
            for event in &self.added {
                report.push_str(&format!(
                    "+ [{}] {} ({:?})\n",
                    event.category(),
                    event.summary(),
                    event.result
                ));
            }
            report.push('\n');
        }

        if !self.removed.is_empty() {
            report.push_str("=== Missing events (potential regression) ===\n");
            for event in &self.removed {
                report.push_str(&format!(
                    "- [{}] {} ({:?})\n",
                    event.category(),
                    event.summary(),
                    event.result
                ));
            }
            report.push('\n');
        }

        if !self.changed.is_empty() {
            report.push_str("=== Changed events ===\n");
            for (old, new) in &self.changed {
                report.push_str(&format!(
                    "~ [{}] {} -> {}\n",
                    old.category(),
                    old.summary(),
                    new.summary()
                ));
            }
        }

        report
    }

    /// Compare two traces
    pub fn compare(golden: &GoldenTrace, current: &GoldenTrace) -> Self {
        let mut comparison = TraceComparison {
            metadata: ComparisonMetadata {
                golden_name: golden.name.clone(),
                golden_captured_at: golden.captured_at.clone(),
                current_captured_at: current.captured_at.clone(),
                golden_event_count: golden.events.len(),
                current_event_count: current.events.len(),
            },
            ..Default::default()
        };

        // Build sets of event signatures for quick lookup
        let golden_sigs: HashSet<String> = golden.events.iter().map(|e| e.summary()).collect();
        let current_sigs: HashSet<String> = current.events.iter().map(|e| e.summary()).collect();

        // Find added events (in current but not in golden)
        for event in &current.events {
            if !golden_sigs.contains(&event.summary()) {
                comparison.added.push(event.clone());
            }
        }

        // Find removed events (in golden but not in current)
        for event in &golden.events {
            if !current_sigs.contains(&event.summary()) {
                comparison.removed.push(event.clone());
            }
        }

        comparison
    }
}

/// Manager for golden trace capture and comparison
#[derive(Debug, Clone)]
pub struct GoldenTraceManager {
    /// Directory for storing traces
    trace_dir: PathBuf,
    /// Configuration
    config: GoldenTraceConfig,
}

impl GoldenTraceManager {
    /// Create a new manager with the given trace directory
    pub fn new(trace_dir: impl Into<PathBuf>) -> Self {
        Self {
            trace_dir: trace_dir.into(),
            config: GoldenTraceConfig::default(),
        }
    }

    /// Create a new manager with configuration
    pub fn with_config(trace_dir: impl Into<PathBuf>, config: GoldenTraceConfig) -> Self {
        Self {
            trace_dir: trace_dir.into(),
            config,
        }
    }

    /// Get the path for a trace file
    pub fn trace_path(&self, trace_name: &str) -> PathBuf {
        self.trace_dir.join(format!("{}.trace.json", trace_name))
    }

    /// Check if a golden trace exists
    pub fn trace_exists(&self, trace_name: &str) -> bool {
        self.trace_path(trace_name).exists()
    }

    /// List all available golden traces
    pub fn list_traces(&self) -> Result<Vec<String>> {
        if !self.trace_dir.exists() {
            return Ok(Vec::new());
        }

        let mut traces = Vec::new();
        for entry in std::fs::read_dir(&self.trace_dir).map_err(|e| {
            Error::Io(std::io::Error::new(
                e.kind(),
                format!("Failed to read trace directory: {}", e),
            ))
        })? {
            let entry = entry.map_err(|e| {
                Error::Io(std::io::Error::new(
                    e.kind(),
                    format!("Failed to read directory entry: {}", e),
                ))
            })?;
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "json") {
                if let Some(stem) = path.file_stem() {
                    if let Some(name) = stem.to_str() {
                        if let Some(trace_name) = name.strip_suffix(".trace") {
                            traces.push(trace_name.to_string());
                        }
                    }
                }
            }
        }
        Ok(traces)
    }

    /// Save a golden trace
    pub fn save_trace(&self, trace: &GoldenTrace) -> Result<PathBuf> {
        // Ensure trace directory exists
        std::fs::create_dir_all(&self.trace_dir).map_err(|e| {
            Error::Io(std::io::Error::new(
                e.kind(),
                format!("Failed to create trace directory: {}", e),
            ))
        })?;

        let path = self.trace_path(&trace.name);
        trace.save(&path)?;
        Ok(path)
    }

    /// Load a golden trace
    pub fn load_trace(&self, trace_name: &str) -> Result<GoldenTrace> {
        let path = self.trace_path(trace_name);
        if !path.exists() {
            return Err(Error::Validation(format!(
                "Golden trace '{}' not found at {}",
                trace_name,
                path.display()
            )));
        }
        GoldenTrace::load(&path)
    }

    /// Compare a current trace against a golden trace
    pub fn compare(&self, golden_name: &str, current: &GoldenTrace) -> Result<TraceComparison> {
        let golden = self.load_trace(golden_name)?;
        Ok(TraceComparison::compare(&golden, current))
    }

    /// Check if a path should be ignored based on configuration
    pub fn should_ignore_path(&self, path: &str) -> bool {
        for pattern in &self.config.ignore_paths {
            if pattern.ends_with('*') {
                let prefix = &pattern[..pattern.len() - 1];
                if path.starts_with(prefix) {
                    return true;
                }
            } else if path == pattern {
                return true;
            }
        }
        false
    }


}

    include!("golden_trace_part2_incl2.rs");