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
//! Hermetic Build Mode for Installer Framework (#109)
//!
//! Provides lockfile-based reproducible installations with:
//! - Pinned artifact versions and hashes
//! - SOURCE_DATE_EPOCH for deterministic timestamps
//! - Lockfile drift detection
//!
//! # Usage
//!
//! ```bash
//! # Generate lockfile
//! bashrs installer lock ./my-installer
//!
//! # Run in hermetic mode
//! bashrs installer run ./my-installer --hermetic
//! ```

use crate::models::{Error, Result};
use std::collections::HashMap;
use std::path::Path;

/// Lockfile format version
pub const LOCKFILE_VERSION: &str = "1.0.0";

/// Lockfile for hermetic builds
#[derive(Debug, Clone)]
pub struct Lockfile {
    /// When the lockfile was generated
    pub generated_at: u64,
    /// Generator version
    pub generator: String,
    /// Hash of the lockfile content for verification
    pub content_hash: String,
    /// Locked artifacts
    pub artifacts: Vec<LockedArtifact>,
    /// Captured environment for reproducibility
    pub environment: LockfileEnvironment,
}

impl Lockfile {
    /// Create a new lockfile
    pub fn new() -> Self {
        Self {
            generated_at: current_timestamp(),
            generator: format!("bashrs-installer/{}", env!("CARGO_PKG_VERSION")),
            content_hash: String::new(),
            artifacts: Vec::new(),
            environment: LockfileEnvironment::capture(),
        }
    }

    /// Add a locked artifact
    pub fn add_artifact(&mut self, artifact: LockedArtifact) {
        self.artifacts.push(artifact);
    }

    /// Compute and update content hash
    pub fn finalize(&mut self) {
        self.content_hash = self.compute_hash();
    }

    /// Compute hash of lockfile content
    fn compute_hash(&self) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();

        // Hash all artifact data
        for artifact in &self.artifacts {
            artifact.id.hash(&mut hasher);
            artifact.version.hash(&mut hasher);
            artifact.sha256.hash(&mut hasher);
            artifact.url.hash(&mut hasher);
        }

        // Hash environment
        self.environment.source_date_epoch.hash(&mut hasher);

        format!("sha256:{:016x}", hasher.finish())
    }

    /// Verify lockfile integrity
    pub fn verify(&self) -> Result<()> {
        let computed = self.compute_hash();
        if computed != self.content_hash {
            return Err(Error::Validation(format!(
                "Lockfile integrity check failed: expected {}, got {}",
                self.content_hash, computed
            )));
        }
        Ok(())
    }

    /// Save lockfile to path
    pub fn save(&self, path: &Path) -> Result<()> {
        let toml = self.to_toml();
        std::fs::write(path, toml).map_err(|e| {
            Error::Io(std::io::Error::new(
                e.kind(),
                format!("Failed to write lockfile: {}", e),
            ))
        })
    }

    /// Load lockfile from path
    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 lockfile: {}", e),
            ))
        })?;

        Self::from_toml(&content)
    }

    /// Convert to TOML string
    pub fn to_toml(&self) -> String {
        let mut toml = String::new();

        toml.push_str("# Lockfile for hermetic builds\n");
        toml.push_str("# Generated by bashrs installer\n\n");

        toml.push_str("[lockfile]\n");
        toml.push_str(&format!("version = \"{}\"\n", LOCKFILE_VERSION));
        toml.push_str(&format!("generated_at = {}\n", self.generated_at));
        toml.push_str(&format!("generator = \"{}\"\n", self.generator));
        toml.push_str(&format!("content_hash = \"{}\"\n", self.content_hash));
        toml.push('\n');

        toml.push_str("[environment]\n");
        toml.push_str(&format!(
            "source_date_epoch = {}\n",
            self.environment.source_date_epoch
        ));
        toml.push_str(&format!("lc_all = \"{}\"\n", self.environment.lc_all));
        toml.push_str(&format!("tz = \"{}\"\n", self.environment.tz));
        toml.push('\n');

        for artifact in &self.artifacts {
            toml.push_str("[[locked.artifact]]\n");
            toml.push_str(&format!("id = \"{}\"\n", artifact.id));
            toml.push_str(&format!("version = \"{}\"\n", artifact.version));
            toml.push_str(&format!("url = \"{}\"\n", artifact.url));
            toml.push_str(&format!("sha256 = \"{}\"\n", artifact.sha256));
            toml.push_str(&format!("size = {}\n", artifact.size));
            toml.push_str(&format!("fetched_at = {}\n", artifact.fetched_at));
            toml.push('\n');
        }

        toml
    }

    /// Apply a key-value pair to the lockfile header section
    fn apply_lockfile_field(&mut self, key: &str, value: &str) {
        match key {
            "generated_at" => self.generated_at = value.parse().unwrap_or(0),
            "generator" => self.generator = value.to_string(),
            "content_hash" => self.content_hash = value.to_string(),
            _ => {}
        }
    }

    /// Apply a key-value pair to the environment section
    fn apply_environment_field(&mut self, key: &str, value: &str) {
        match key {
            "source_date_epoch" => self.environment.source_date_epoch = value.parse().unwrap_or(0),
            "lc_all" => self.environment.lc_all = value.to_string(),
            "tz" => self.environment.tz = value.to_string(),
            _ => {}
        }
    }

    /// Parse from TOML string
    pub fn from_toml(content: &str) -> Result<Self> {
        let mut lockfile = Lockfile::new();
        let mut in_lockfile = false;
        let mut in_environment = false;
        let mut in_artifact = false;
        let mut current_artifact: Option<LockedArtifact> = None;

        for line in content.lines() {
            let line = line.trim();

            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            if line == "[lockfile]" {
                in_lockfile = true;
                in_environment = false;
                in_artifact = false;
                continue;
            }

            if line == "[environment]" {
                in_lockfile = false;
                in_environment = true;
                in_artifact = false;
                continue;
            }

            if line == "[[locked.artifact]]" {
                if let Some(artifact) = current_artifact.take() {
                    lockfile.artifacts.push(artifact);
                }
                current_artifact = Some(LockedArtifact::default());
                in_lockfile = false;
                in_environment = false;
                in_artifact = true;
                continue;
            }

            if let Some((key, value)) = parse_toml_line(line) {
                if in_lockfile {
                    lockfile.apply_lockfile_field(key, value);
                } else if in_environment {
                    lockfile.apply_environment_field(key, value);
                } else if in_artifact {
                    if let Some(ref mut artifact) = current_artifact {
                        artifact.apply_field(key, value);
                    }
                }
            }
        }

        if let Some(artifact) = current_artifact {
            lockfile.artifacts.push(artifact);
        }

        Ok(lockfile)
    }

    /// Get artifact by ID
    pub fn get_artifact(&self, id: &str) -> Option<&LockedArtifact> {
        self.artifacts.iter().find(|a| a.id == id)
    }
}

impl Default for Lockfile {
    fn default() -> Self {
        Self::new()
    }
}

/// A locked artifact with pinned version and hash
#[derive(Debug, Clone, Default)]
pub struct LockedArtifact {
    /// Artifact identifier
    pub id: String,
    /// Pinned version
    pub version: String,
    /// Download URL
    pub url: String,
    /// SHA256 hash of content
    pub sha256: String,
    /// Size in bytes
    pub size: u64,
    /// When the artifact was fetched
    pub fetched_at: u64,
}

impl LockedArtifact {
    /// Apply a key-value pair to this artifact
    fn apply_field(&mut self, key: &str, value: &str) {
        match key {
            "id" => self.id = value.to_string(),
            "version" => self.version = value.to_string(),
            "url" => self.url = value.to_string(),
            "sha256" => self.sha256 = value.to_string(),
            "size" => self.size = value.parse().unwrap_or(0),
            "fetched_at" => self.fetched_at = value.parse().unwrap_or(0),
            _ => {}
        }
    }

    /// Create a new locked artifact
    pub fn new(id: &str, version: &str, url: &str, sha256: &str, size: u64) -> Self {
        Self {
            id: id.to_string(),
            version: version.to_string(),
            url: url.to_string(),
            sha256: sha256.to_string(),
            size,
            fetched_at: current_timestamp(),
        }
    }
}

/// Captured environment for reproducibility
#[derive(Debug, Clone)]
pub struct LockfileEnvironment {
    /// Fixed timestamp for all operations
    pub source_date_epoch: u64,
    /// Locale setting
    pub lc_all: String,
    /// Timezone
    pub tz: String,
}

impl LockfileEnvironment {
    /// Capture current environment
    pub fn capture() -> Self {
        Self {
            source_date_epoch: std::env::var("SOURCE_DATE_EPOCH")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or_else(current_timestamp),
            lc_all: std::env::var("LC_ALL").unwrap_or_else(|_| "C.UTF-8".to_string()),
            tz: std::env::var("TZ").unwrap_or_else(|_| "UTC".to_string()),
        }
    }

    /// Create a deterministic environment for hermetic builds
    pub fn deterministic(source_date_epoch: u64) -> Self {
        Self {
            source_date_epoch,
            lc_all: "C.UTF-8".to_string(),
            tz: "UTC".to_string(),
        }
    }
}

impl Default for LockfileEnvironment {
    fn default() -> Self {
        Self::capture()
    }
}

/// Hermetic execution context
#[derive(Debug, Clone)]
pub struct HermeticContext {
    /// Lockfile for this execution
    pub lockfile: Lockfile,
    /// Whether to fail on lockfile drift
    pub strict: bool,
    /// Cached artifact hashes (for verification)
    artifact_cache: HashMap<String, String>,
}

impl HermeticContext {
    /// Create a new hermetic context from a lockfile
    pub fn from_lockfile(lockfile: Lockfile) -> Result<Self> {
        lockfile.verify()?;

        let artifact_cache = lockfile
            .artifacts
            .iter()
            .map(|a| (a.id.clone(), a.sha256.clone()))
            .collect();

        Ok(Self {
            lockfile,
            strict: true,
            artifact_cache,
        })
    }

    /// Load hermetic context from lockfile path
    pub fn load(lockfile_path: &Path) -> Result<Self> {
        let lockfile = Lockfile::load(lockfile_path)?;
        Self::from_lockfile(lockfile)
    }

    /// Get the SOURCE_DATE_EPOCH for this context
    pub fn source_date_epoch(&self) -> u64 {
        self.lockfile.environment.source_date_epoch
    }

    /// Verify an artifact matches the lockfile
    pub fn verify_artifact(&self, id: &str, sha256: &str) -> Result<()> {
        let expected = self
            .artifact_cache
            .get(id)
            .ok_or_else(|| Error::Validation(format!("Artifact '{}' not found in lockfile", id)))?;

        if expected != sha256 {
            return Err(Error::Validation(format!(
                "Artifact '{}' hash mismatch: lockfile={}, actual={}",
                id, expected, sha256
            )));
        }

        Ok(())
    }

    /// Check if an artifact is in the lockfile
    pub fn has_artifact(&self, id: &str) -> bool {
        self.artifact_cache.contains_key(id)
    }
}

/// Parse a TOML key = value line
fn parse_toml_line(line: &str) -> Option<(&str, &str)> {
    let mut parts = line.splitn(2, '=');
    let key = parts.next()?.trim();
    let value = parts.next()?.trim();

    // Remove quotes from string values
    let value = value.trim_matches('"');

    Some((key, value))
}

/// Get current timestamp
fn current_timestamp() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

#[cfg(test)]
#[path = "hermetic_tests_hermetic_109.rs"]
mod tests_extracted;