smith-attestation 0.1.0

Supply chain attestation and cryptographic signing
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! SLSA provenance metadata generation
//!
//! Implements SLSA (Supply-chain Levels for Software Artifacts) provenance
//! generation for Smith platform builds, providing complete build attestation
//! and supply chain transparency.

use crate::{AttestationError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// SLSA provenance generator for Smith builds
#[derive(Debug)]
pub struct ProvenanceGenerator {
    /// Build environment configuration
    config: ProvenanceConfig,
}

/// Provenance generation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceConfig {
    /// Build environment identifier
    pub build_environment: String,

    /// Builder identity (e.g., GitHub Actions runner)
    pub builder_id: String,

    /// Repository URL
    pub repository_url: String,

    /// Build trigger (manual, scheduled, PR, etc.)
    pub build_trigger: String,

    /// Output directory for provenance files
    pub output_dir: PathBuf,
}

/// SLSA provenance metadata (v0.2 format)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlsaProvenance {
    /// SLSA predicate type
    #[serde(rename = "_type")]
    pub predicate_type: String,

    /// Subject artifacts
    pub subject: Vec<ProvenanceSubject>,

    /// Provenance predicate
    pub predicate: ProvenancePredicate,
}

/// Subject artifact in provenance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceSubject {
    /// Artifact name
    pub name: String,

    /// Digest information
    pub digest: HashMap<String, String>,
}

/// SLSA provenance predicate
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenancePredicate {
    /// Builder information
    pub builder: BuilderInfo,

    /// Build type
    #[serde(rename = "buildType")]
    pub build_type: String,

    /// Invocation details
    pub invocation: InvocationInfo,

    /// Build configuration
    #[serde(rename = "buildConfig")]
    pub build_config: BuildConfig,

    /// Materials (source code, dependencies)
    pub materials: Vec<Material>,

    /// Metadata
    pub metadata: ProvenanceMetadata,
}

/// Builder information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuilderInfo {
    /// Builder identifier
    pub id: String,

    /// Builder version
    pub version: HashMap<String, String>,
}

/// Build invocation information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvocationInfo {
    /// Configuration source
    #[serde(rename = "configSource")]
    pub config_source: ConfigSource,

    /// Parameters
    pub parameters: HashMap<String, serde_json::Value>,

    /// Environment variables
    pub environment: HashMap<String, String>,
}

/// Configuration source
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigSource {
    /// URI of build configuration
    pub uri: String,

    /// Digest of configuration
    pub digest: HashMap<String, String>,

    /// Entry point
    #[serde(rename = "entryPoint")]
    pub entry_point: String,
}

/// Build configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildConfig {
    /// Build steps
    pub steps: Vec<BuildStep>,

    /// Build artifacts
    pub artifacts: Vec<BuildArtifact>,
}

/// Individual build step
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildStep {
    /// Step command
    pub command: String,

    /// Arguments
    pub args: Vec<String>,

    /// Environment variables
    pub env: HashMap<String, String>,

    /// Working directory
    pub workdir: Option<String>,
}

/// Build artifact information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildArtifact {
    /// Artifact name
    pub name: String,

    /// Artifact path
    pub path: String,

    /// Digest
    pub digest: HashMap<String, String>,
}

/// Material (dependency or source)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Material {
    /// Material URI
    pub uri: String,

    /// Digest
    pub digest: HashMap<String, String>,
}

/// Provenance metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceMetadata {
    /// Build start time
    #[serde(rename = "buildStartedOn")]
    pub build_started_on: chrono::DateTime<chrono::Utc>,

    /// Build finished time
    #[serde(rename = "buildFinishedOn")]
    pub build_finished_on: chrono::DateTime<chrono::Utc>,

    /// Build invocation ID
    #[serde(rename = "buildInvocationId")]
    pub build_invocation_id: String,

    /// Completeness information
    pub completeness: CompletenessInfo,

    /// Reproducibility information
    pub reproducible: bool,
}

/// Completeness information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletenessInfo {
    /// Parameters complete
    pub parameters: bool,

    /// Environment complete
    pub environment: bool,

    /// Materials complete  
    pub materials: bool,
}

/// Build information collector
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildInfo {
    /// Git commit SHA
    pub git_commit: String,

    /// Git branch
    pub git_branch: String,

    /// Git repository URL
    pub git_repository: String,

    /// Build timestamp
    pub build_timestamp: chrono::DateTime<chrono::Utc>,

    /// Builder environment
    pub builder_environment: String,

    /// Rust toolchain version
    pub rust_version: String,

    /// Cargo version
    pub cargo_version: String,

    /// Target triple
    pub target_triple: String,

    /// Build flags
    pub build_flags: Vec<String>,

    /// Dependencies
    pub dependencies: Vec<Dependency>,
}

/// Dependency information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dependency {
    /// Package name
    pub name: String,

    /// Version
    pub version: String,

    /// Source (crates.io, git, etc.)
    pub source: String,

    /// Checksum
    pub checksum: Option<String>,
}

impl ProvenanceGenerator {
    /// Create new provenance generator
    pub fn new(config: ProvenanceConfig) -> Self {
        Self { config }
    }

    /// Generate provenance for Smith build
    pub async fn generate_provenance(
        &self,
        build_info: &BuildInfo,
        artifacts: Vec<BuildArtifact>,
    ) -> Result<SlsaProvenance> {
        let build_start = chrono::Utc::now() - chrono::Duration::hours(1); // Estimate
        let build_finish = chrono::Utc::now();

        // Create subjects from artifacts
        let subjects = artifacts
            .iter()
            .map(|artifact| ProvenanceSubject {
                name: artifact.name.clone(),
                digest: artifact.digest.clone(),
            })
            .collect();

        // Collect materials (source code and dependencies)
        let mut materials = Vec::new();

        // Add git repository as material
        materials.push(Material {
            uri: build_info.git_repository.clone(),
            digest: {
                let mut digest = HashMap::new();
                digest.insert("sha1".to_string(), build_info.git_commit.clone());
                digest
            },
        });

        // Add dependencies as materials
        for dep in &build_info.dependencies {
            materials.push(Material {
                uri: format!("pkg:cargo/{}@{}", dep.name, dep.version),
                digest: dep
                    .checksum
                    .as_ref()
                    .map(|checksum| {
                        let mut digest = HashMap::new();
                        digest.insert("sha256".to_string(), checksum.clone());
                        digest
                    })
                    .unwrap_or_default(),
            });
        }

        let provenance = SlsaProvenance {
            predicate_type: "https://slsa.dev/provenance/v0.2".to_string(),
            subject: subjects,
            predicate: ProvenancePredicate {
                builder: BuilderInfo {
                    id: self.config.builder_id.clone(),
                    version: {
                        let mut version = HashMap::new();
                        version.insert("rust".to_string(), build_info.rust_version.clone());
                        version.insert("cargo".to_string(), build_info.cargo_version.clone());
                        version
                    },
                },
                build_type: "https://smith.rs/build-types/cargo@v1".to_string(),
                invocation: InvocationInfo {
                    config_source: ConfigSource {
                        uri: self.config.repository_url.clone(),
                        digest: {
                            let mut digest = HashMap::new();
                            digest.insert("sha1".to_string(), build_info.git_commit.clone());
                            digest
                        },
                        entry_point: "cargo build --release".to_string(),
                    },
                    parameters: {
                        let mut params = HashMap::new();
                        params.insert(
                            "target".to_string(),
                            serde_json::Value::String(build_info.target_triple.clone()),
                        );
                        params.insert(
                            "flags".to_string(),
                            serde_json::Value::Array(
                                build_info
                                    .build_flags
                                    .iter()
                                    .map(|f| serde_json::Value::String(f.clone()))
                                    .collect(),
                            ),
                        );
                        params
                    },
                    environment: {
                        let mut env = HashMap::new();
                        env.insert("RUST_VERSION".to_string(), build_info.rust_version.clone());
                        env.insert(
                            "CARGO_VERSION".to_string(),
                            build_info.cargo_version.clone(),
                        );
                        env
                    },
                },
                build_config: BuildConfig {
                    steps: vec![BuildStep {
                        command: "cargo".to_string(),
                        args: vec!["build".to_string(), "--release".to_string()],
                        env: HashMap::new(),
                        workdir: Some("/workspace".to_string()),
                    }],
                    artifacts: artifacts.clone(),
                },
                materials,
                metadata: ProvenanceMetadata {
                    build_started_on: build_start,
                    build_finished_on: build_finish,
                    build_invocation_id: uuid::Uuid::new_v4().to_string(),
                    completeness: CompletenessInfo {
                        parameters: true,
                        environment: true,
                        materials: true,
                    },
                    reproducible: true,
                },
            },
        };

        Ok(provenance)
    }

    /// Save provenance to file
    pub async fn save_provenance(
        &self,
        provenance: &SlsaProvenance,
        filename: &str,
    ) -> Result<PathBuf> {
        // Ensure output directory exists
        tokio::fs::create_dir_all(&self.config.output_dir).await?;

        let file_path = self.config.output_dir.join(filename);

        // Serialize provenance to JSON with pretty printing
        let json = serde_json::to_string_pretty(provenance).map_err(|e| {
            AttestationError::ProvenanceError(format!("Failed to serialize provenance: {}", e))
        })?;

        tokio::fs::write(&file_path, json).await?;

        tracing::info!("SLSA provenance saved to: {}", file_path.display());
        Ok(file_path)
    }

    /// Collect build information from environment
    pub async fn collect_build_info() -> Result<BuildInfo> {
        let now = chrono::Utc::now();

        // Get git information
        let git_commit = Self::get_git_commit()
            .await
            .unwrap_or_else(|| "unknown".to_string());
        let git_branch = Self::get_git_branch()
            .await
            .unwrap_or_else(|| "main".to_string());
        let git_repository = Self::get_git_repository()
            .await
            .unwrap_or_else(|| "unknown".to_string());

        // Get Rust toolchain information
        let rust_version = Self::get_rust_version()
            .await
            .unwrap_or_else(|| "unknown".to_string());
        let cargo_version = Self::get_cargo_version()
            .await
            .unwrap_or_else(|| "unknown".to_string());
        let target_triple = Self::get_target_triple()
            .await
            .unwrap_or_else(|| "unknown".to_string());

        // Get build flags
        let build_flags = std::env::var("RUSTFLAGS")
            .unwrap_or_default()
            .split_whitespace()
            .map(|s| s.to_string())
            .collect();

        // Get builder environment
        let builder_environment =
            std::env::var("BUILD_ENVIRONMENT").unwrap_or_else(|_| "local".to_string());

        // Get dependencies (simplified - would use cargo metadata in production)
        let dependencies = Self::collect_dependencies().await.unwrap_or_default();

        Ok(BuildInfo {
            git_commit,
            git_branch,
            git_repository,
            build_timestamp: now,
            builder_environment,
            rust_version,
            cargo_version,
            target_triple,
            build_flags,
            dependencies,
        })
    }

    /// Get git commit SHA
    async fn get_git_commit() -> Option<String> {
        let output = tokio::process::Command::new("git")
            .args(["rev-parse", "HEAD"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Get git branch
    async fn get_git_branch() -> Option<String> {
        let output = tokio::process::Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Get git repository URL
    async fn get_git_repository() -> Option<String> {
        let output = tokio::process::Command::new("git")
            .args(["config", "--get", "remote.origin.url"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Get Rust version
    async fn get_rust_version() -> Option<String> {
        let output = tokio::process::Command::new("rustc")
            .args(["--version"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Get Cargo version
    async fn get_cargo_version() -> Option<String> {
        let output = tokio::process::Command::new("cargo")
            .args(["--version"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Get target triple
    async fn get_target_triple() -> Option<String> {
        let output = tokio::process::Command::new("rustc")
            .args(["-vV"])
            .output()
            .await
            .ok()?;

        if output.status.success() {
            let output_str = String::from_utf8_lossy(&output.stdout);
            for line in output_str.lines() {
                if line.starts_with("host: ") {
                    return Some(line.strip_prefix("host: ")?.to_string());
                }
            }
        }

        None
    }

    /// Collect dependency information
    async fn collect_dependencies() -> Option<Vec<Dependency>> {
        // In production, would use `cargo metadata` to get accurate dependency info
        // For now, return empty list
        Some(Vec::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_provenance_generation() {
        let temp_dir = TempDir::new().unwrap();
        let config = ProvenanceConfig {
            build_environment: "test".to_string(),
            builder_id: "test-builder".to_string(),
            repository_url: "https://github.com/test/repo".to_string(),
            build_trigger: "manual".to_string(),
            output_dir: temp_dir.path().to_path_buf(),
        };

        let generator = ProvenanceGenerator::new(config);
        let build_info = BuildInfo {
            git_commit: "abc123".to_string(),
            git_branch: "main".to_string(),
            git_repository: "https://github.com/test/repo".to_string(),
            build_timestamp: chrono::Utc::now(),
            builder_environment: "test".to_string(),
            rust_version: "1.70.0".to_string(),
            cargo_version: "1.70.0".to_string(),
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            build_flags: vec!["-C".to_string(), "target-cpu=native".to_string()],
            dependencies: vec![],
        };

        let artifacts = vec![BuildArtifact {
            name: "smith-core".to_string(),
            path: "target/release/smith-core".to_string(),
            digest: {
                let mut digest = HashMap::new();
                digest.insert("sha256".to_string(), "test-digest".to_string());
                digest
            },
        }];

        let provenance = generator
            .generate_provenance(&build_info, artifacts)
            .await
            .unwrap();

        assert_eq!(
            provenance.predicate_type,
            "https://slsa.dev/provenance/v0.2"
        );
        assert_eq!(provenance.subject.len(), 1);
        assert_eq!(provenance.subject[0].name, "smith-core");
    }

    #[tokio::test]
    async fn test_build_info_collection() {
        let build_info = ProvenanceGenerator::collect_build_info().await.unwrap();

        // Build info should have been collected
        assert!(!build_info.rust_version.is_empty());
        assert!(!build_info.cargo_version.is_empty());
    }
}