haps 0.1.24

Hashtree Package System: signed packages, content-addressed distribution, social discovery
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
//! Release audit evidence. A review and a reproducible-build check are distinct.
use crate::progress::Progress;
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
use std::{path::Path, process::Command};
mod failure;
pub mod repair;
pub use failure::{Finding, retain_failed, retain_failed_release};

pub const REVIEW_SCOPE: &str = "Inspect the exact source, recipe, and direct/transitive runtime and build dependencies, including install hooks and build scripts. Read pinned dependency source independently; do not run npm install, builds, hooks, or project/dependency scripts during review. Check that downloads are content-pinned and verified before use. Record dependency versions, sources, findings, unreviewed parts, and OS/toolchain assumptions; a hash alone is not a code audit.";

/// Terminal summaries are bounded; the signed or retained report keeps the note.
pub fn summary(note: &str) -> String {
    let clean = note.split_whitespace().collect::<Vec<_>>().join(" ");
    let clean: String = clean.chars().filter(|c| !c.is_control()).collect();
    if clean.chars().count() <= 280 {
        return clean;
    }
    let prefix: String = clean.chars().take(280).collect();
    format!(
        "{}…",
        prefix
            .rsplit_once(' ')
            .map_or(prefix.as_str(), |(words, _)| words)
    )
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Reviewer {
    pub agent: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reported_model: Option<String>,
}

#[derive(Deserialize)]
pub struct Review {
    verdict: String,
    pub note: String,
    pub reviewer: Reviewer,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Evidence {
    pub schema: String,
    pub method: String,
    pub provenance: String,
    pub binary_match: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewer: Option<Reviewer>,
    /// Exact reviewed recipe and the complete output manifest, including file modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildIdentity>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildIdentity {
    pub recipe_sha256: String,
    pub manifest: String,
}

pub fn recipe_sha256(recipe: &crate::build::Recipe) -> Result<String> {
    use sha2::{Digest, Sha256};
    Ok(hex::encode(Sha256::digest(serde_json::to_vec(recipe)?)))
}

pub fn local_build_metadata(recipe_hash: &str, manifest: &str) -> Result<semver::BuildMetadata> {
    use sha2::{Digest, Sha256};
    let build_id = hex::encode(Sha256::digest(format!("{recipe_hash}:{manifest}")));
    Ok(semver::BuildMetadata::new(&format!(
        "haps.{}",
        &build_id[..20]
    ))?)
}

/// A published local build retains the committed version plus an identifier
/// derived from the exact recipe and payload. No other metadata may differ.
pub fn recipe_matches_release(
    recipe: &crate::build::Recipe,
    release: &crate::model::Release,
) -> Result<bool> {
    if recipe.package == release.data.package {
        return Ok(true);
    }
    let mut package = recipe.package.clone();
    package.version.build = local_build_metadata(&recipe_sha256(recipe)?, &release.data.manifest)?;
    Ok(package == release.data.package)
}

fn runner() -> Command {
    let mut command =
        Command::new(std::env::var_os("HAPS_PYTHON").unwrap_or_else(|| "python3".into()));
    command.arg("-c").arg(include_str!("integrations/audit.py"));
    command
}

pub fn agents() -> Result<Vec<String>> {
    let output = runner()
        .arg("agents")
        .output()
        .context("agent detection needs Python 3")?;
    ensure!(output.status.success(), "agent detection failed");
    Ok(serde_json::from_slice(&output.stdout)?)
}

/// Propose commands from project instructions; this does not approve or execute them.
pub fn plan_build(
    source: &crate::build::SourceCheckout,
    package: &crate::model::PackageSpec,
    agent: &str,
    model: Option<&str>,
) -> Result<crate::build::Recipe> {
    ensure!(
        matches!(agent, "codex" | "claude"),
        "manual source builds need build instructions in haps.toml or --recipe-file FILE"
    );
    let (progress, _reporter) = Progress::stderr(true)?;
    progress.stage(format!("Reading project build instructions with {agent}"));
    let input = tempfile::NamedTempFile::new()?;
    crate::model::atomic_write(
        input.path(),
        &serde_json::to_vec(&serde_json::json!({"package": package, "build": null}))?,
    )?;
    let output = runner()
        .arg("plan")
        .arg(source.root())
        .arg(input.path())
        .arg(agent)
        .arg(model.unwrap_or(""))
        .output()
        .context("could not start build planning agent")?;
    ensure!(
        output.status.success(),
        "build planning incomplete: {}",
        String::from_utf8_lossy(&output.stderr)
            .trim()
            .escape_debug()
    );
    #[derive(Deserialize)]
    struct Plan {
        verdict: String,
        note: String,
        build: Option<Build>,
    }
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Build {
        builder: crate::build::Builder,
        commands: Vec<Vec<String>>,
        artifacts: Vec<Artifact>,
    }
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Artifact {
        destination: String,
        path: String,
    }
    let plan: Plan = serde_json::from_slice(&output.stdout).context("invalid build plan")?;
    ensure!(
        plan.verdict == "ready",
        "build instructions incomplete: {}",
        plan.note.escape_debug()
    );
    let build = plan
        .build
        .context("agent did not provide build instructions")?;
    let mut artifacts = std::collections::BTreeMap::new();
    for artifact in build.artifacts {
        ensure!(
            artifacts
                .insert(artifact.destination, artifact.path)
                .is_none(),
            "duplicate build artifact destination"
        );
    }
    source.ensure_pristine()?;
    Ok(crate::build::Recipe {
        package: package.clone(),
        build: crate::build::Steps {
            unavailable: None,
            builder: build.builder,
            commands: build.commands,
            artifacts,
        },
    })
}

/// A user-selected agent reviews a bounded source snapshot without executing it.
/// Manual reviewers inspect the checkout before confirming in the terminal.
pub fn review(
    checkout: &crate::build::Checkout,
    agent: &str,
    model: Option<&str>,
    interactive: bool,
) -> Result<Review> {
    let (progress, _reporter) = Progress::stderr(true)?;
    review_with_progress(checkout, agent, model, interactive, &progress, None)
}

pub fn review_repair(
    checkout: &crate::build::Checkout,
    agent: &str,
    model: Option<&str>,
    interactive: bool,
    repair: &repair::ReviewContext,
) -> Result<Review> {
    let (progress, _reporter) = Progress::stderr(true)?;
    review_with_progress(checkout, agent, model, interactive, &progress, Some(repair))
}

fn review_with_progress(
    checkout: &crate::build::Checkout,
    agent: &str,
    model: Option<&str>,
    interactive: bool,
    progress: &Progress,
    repair: Option<&repair::ReviewContext>,
) -> Result<Review> {
    progress.clear();
    let root = checkout.root();
    eprintln!("Audit source: {}", root.display());
    if let Some(repair) = repair {
        eprintln!("Repair review: {}", serde_json::to_string(repair)?);
        eprintln!(
            "Check the original findings are resolved and review the complete fork. Stop if it is unsafe or the evidence is incomplete."
        );
    }
    let review = if agent == "manual" {
        ensure!(model.is_none(), "a model applies only to an agent review");
        ensure!(
            interactive,
            "manual audits need a terminal; use haps attest --audited to record a completed review"
        );
        eprintln!("{REVIEW_SCOPE}");
        let passed = dialoguer::Confirm::new()
            .with_prompt(
                "Review this source and recipe. Pass the review and continue to the build?",
            )
            .default(false)
            .interact()?;
        ensure!(passed, "audit not approved; nothing installed");
        let note = dialoguer::Input::<String>::new()
            .with_prompt("What did you check?")
            .interact_text()?;
        Review {
            verdict: "pass".into(),
            note,
            reviewer: Reviewer {
                agent: "manual".into(),
                requested_model: None,
                reported_model: None,
            },
        }
    } else {
        ensure!(
            matches!(agent, "codex" | "claude"),
            "supported audit agents: codex, claude, manual"
        );
        eprintln!(
            "Reviewing with {agent}; source is sent to its configured service. A passing review permits a separate build step."
        );
        progress.stage(format!("Reviewing source with {agent}"));
        let input = tempfile::NamedTempFile::new()?;
        let mut packet = serde_json::to_value(&checkout.recipe)?;
        if let Some(repair) = repair {
            packet["repair_review"] = serde_json::to_value(repair)?;
        }
        crate::model::atomic_write(input.path(), &serde_json::to_vec(&packet)?)?;
        let output = runner()
            .arg("review")
            .arg(&root)
            .arg(input.path())
            .arg(agent)
            .arg(model.unwrap_or(""))
            .output()
            .context("could not start audit agent")?;
        ensure!(
            output.status.success(),
            "audit incomplete: {}",
            String::from_utf8_lossy(&output.stderr)
                .trim()
                .escape_debug()
        );
        let report: Review = serde_json::from_slice(&output.stdout)
            .context("agent returned an invalid audit report")?;
        ensure!(
            !report.note.trim().is_empty() && report.note.len() <= 4096,
            "audit needs a review note of at most 4096 bytes"
        );
        if report.verdict != "pass" {
            return Err(Finding {
                verdict: report.verdict,
                note: report.note,
            }
            .into());
        }
        report
    };
    ensure!(
        !review.note.trim().is_empty() && review.note.len() <= 4096,
        "audit needs a review note of at most 4096 bytes"
    );
    checkout.ensure_pristine()?;
    progress.clear();
    Ok(review)
}

pub async fn review_and_rebuild(
    home: &Path,
    release: &crate::model::Release,
    repository: &crate::repository::Repository,
    agent: &str,
    model: Option<&str>,
    interactive: bool,
    execution: crate::build::sandbox::Execution,
) -> Result<(Evidence, String)> {
    execution.preflight()?;
    let source = release.data.package.source.clone().context("this release has no pinned source; Audit and install cannot reproduce it. A reviewer can record an explicit audit with provenance instead")?;
    let (progress, _reporter) = Progress::stderr(true)?;
    progress.stage("Fetching pinned source for audit");
    let checkout = crate::build::Checkout::project_for(
        source.clone(),
        &home.join("audits/work"),
        Some(&release.data.package.name),
    )?;
    let result = async {
        ensure!(
            recipe_matches_release(&checkout.recipe, release)?,
            "source recipe does not describe the exact published package"
        );
        progress.stage("Checking published package manifest");
        let manifest: crate::model::Manifest = repository.json(&release.data.manifest).await?;
        manifest.validate(&release.data.package)?;
        let review = review_with_progress(&checkout, agent, model, interactive, &progress, None)?;
        let evidence = rebuild(
            home,
            release,
            &checkout,
            review.reviewer,
            &progress,
            execution,
        )
        .await?;
        Ok((evidence, review.note))
    }
    .await;
    result.map_err(|error| retain_failed_release(checkout, error, Some(release)))
}

async fn rebuild(
    home: &Path,
    release: &crate::model::Release,
    checkout: &crate::build::Checkout,
    reviewer: Reviewer,
    progress: &Progress,
    execution: crate::build::sandbox::Execution,
) -> Result<Evidence> {
    execution.preflight()?;
    if crate::security::enabled(home) {
        progress.stage("Scanning source before the audit build");
        let report = crate::security::scan_source(
            home,
            release
                .data
                .package
                .source
                .as_ref()
                .context("source missing")?,
            &checkout.root(),
        )?;
        crate::security::bind_report(home, release, report)?;
    }
    progress.stage("Rebuilding the audited source");
    progress.clear(); // Build commands own the terminal while they run.
    let payload = checkout.execute_with(execution)?;
    progress.stage("Comparing rebuilt files with the published package");
    let rebuilt_repo =
        crate::repository::Repository::local(checkout.root().parent().unwrap().join("comparison"))?;
    let rebuilt = rebuilt_repo
        .pack_payload_with_mode(
            &release.data.package,
            &payload,
            crate::repository::rebuild_mode(release)?,
        )
        .await?;
    let binary_match = rebuilt == release.data.manifest;
    progress.clear();
    eprintln!(
        "{}",
        if binary_match {
            "Rebuilt payload matches the published release."
        } else {
            "Published binary differs from the audited build; only the source review is recorded."
        }
    );
    Ok(Evidence {
        schema: "haps.audit.v1".into(),
        method: if binary_match {
            format!("{}-review-and-rebuild", reviewer.agent)
        } else {
            "source-review".into()
        },
        provenance: format!(
            "Reviewed pinned source {}; rebuilt with the committed recipe and local toolchain. {} Built payload manifest: {}. Publisher binary match: {binary_match}. Dependencies and toolchain are not independently verified.",
            release
                .data
                .package
                .source
                .as_ref()
                .context("source missing")?
                .rev,
            execution.description(),
            rebuilt
        ),
        binary_match,
        reviewer: Some(reviewer),
        build: Some(BuildIdentity {
            recipe_sha256: recipe_sha256(&checkout.recipe)?,
            manifest: rebuilt,
        }),
    })
}

/// A persistent, private checkout. Preparation never executes the build recipe.
pub fn prepare(home: &Path, release: &crate::model::Release) -> Result<std::path::PathBuf> {
    let source = release.data.package.source.clone().context("this release has no pinned source; record an explicit completed audit with provenance instead")?;
    let (progress, _reporter) = Progress::stderr(true)?;
    progress.stage("Fetching pinned source for audit");
    let checkout = crate::build::SourceCheckout::fetch(source, &home.join("audits/pending"))?;
    let directory = checkout
        .root()
        .parent()
        .context("checkout parent missing")?
        .to_owned();
    crate::model::atomic_write(
        &directory.join("release.json"),
        &serde_json::to_vec_pretty(&release.event)?,
    )?;
    Ok(checkout.keep())
}

fn source_fingerprint(
    root: &Path,
) -> Result<std::collections::BTreeMap<std::path::PathBuf, String>> {
    use sha2::{Digest, Sha256};
    use std::io::Read;
    let mut files = std::collections::BTreeMap::new();
    let mut pending = vec![root.to_owned()];
    while let Some(directory) = pending.pop() {
        for entry in std::fs::read_dir(directory)? {
            let path = entry?.path();
            let relative = path.strip_prefix(root)?;
            if relative == Path::new(".git") {
                continue;
            }
            let metadata = std::fs::symlink_metadata(&path)?;
            let value = if metadata.is_dir() {
                pending.push(path.clone());
                "directory".to_owned()
            } else if metadata.is_symlink() {
                format!("symlink:{:?}", std::fs::read_link(&path)?)
            } else {
                ensure!(metadata.is_file(), "unsupported file in prepared source");
                let mut file = std::fs::File::open(&path)?;
                let mut hash = Sha256::new();
                let mut buffer = [0_u8; 65536];
                loop {
                    let count = file.read(&mut buffer)?;
                    if count == 0 {
                        break;
                    }
                    hash.update(&buffer[..count]);
                }
                #[cfg(unix)]
                let executable = {
                    use std::os::unix::fs::PermissionsExt;
                    metadata.permissions().mode() & 0o111 != 0
                };
                #[cfg(not(unix))]
                let executable = false;
                format!("file:{executable}:{}", hex::encode(hash.finalize()))
            };
            files.insert(relative.to_owned(), value);
            ensure!(files.len() <= 100_000, "too many source files");
        }
    }
    Ok(files)
}

/// Finish an external review by comparing to a fresh pinned checkout, so edited
/// Git configuration, hooks, or untracked files cannot become build inputs.
pub async fn finish(
    home: &Path,
    session: &str,
    note: &str,
    reviewer: Reviewer,
    execution: crate::build::sandbox::Execution,
) -> Result<(crate::model::Release, Evidence)> {
    ensure!(
        !session.is_empty()
            && session.len() <= 100
            && session
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'),
        "invalid audit session name"
    );
    ensure!(
        !note.trim().is_empty() && note.len() <= 4096,
        "audit needs a review note of at most 4096 bytes"
    );
    let directory = home.join("audits/pending").join(session);
    let release =
        crate::model::Release::verify(crate::model::read_json(&directory.join("release.json"))?)?;
    let source = release
        .data
        .package
        .source
        .clone()
        .context("pinned source missing")?;
    let (progress, _reporter) = Progress::stderr(true)?;
    progress.stage("Fetching pinned source for audit");
    let checkout = crate::build::SourceCheckout::fetch(source, &home.join("audits/work"))?;
    progress.stage("Checking prepared source has not changed");
    ensure!(
        source_fingerprint(&directory.join("repo"))? == source_fingerprint(&checkout.root())?,
        "prepared source has changed; start a new audit instead of approving different files"
    );
    let recipe = checkout
        .recipe_for(None, Some(&release.data.package.name))?
        .filter(|recipe| recipe.build.unavailable.is_none());
    let evidence = if let Some(recipe) = recipe {
        let checkout = crate::build::Checkout::with_recipe(checkout, recipe)?;
        ensure!(
            recipe_matches_release(&checkout.recipe, &release)?,
            "source recipe does not describe the exact published package"
        );
        rebuild(home, &release, &checkout, reviewer, &progress, execution).await?
    } else {
        Evidence {
            schema: "haps.audit.v1".into(),
            method: "source-review".into(),
            provenance: format!(
                "Reviewed pinned source {}. No build was executed; the published binary has not been verified or audited by this source review.",
                checkout.source.rev
            ),
            binary_match: false,
            reviewer: Some(reviewer),
            build: None,
        }
    };
    Ok((release, evidence))
}

impl Evidence {
    pub fn manual(provenance: String) -> Result<Self> {
        let value = Self {
            schema: "haps.audit.v1".into(),
            method: "explicit-review".into(),
            provenance,
            binary_match: false,
            reviewer: None,
            build: None,
        };
        value.validate()?;
        Ok(value)
    }

    pub fn validate(&self) -> Result<()> {
        if let Some(build) = &self.build {
            ensure!(
                build.recipe_sha256.len() == 64
                    && build
                        .recipe_sha256
                        .bytes()
                        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
                "invalid audited recipe hash"
            );
            hashtree_core::Cid::parse(&build.manifest)?;
        }
        if let Some(reviewer) = &self.reviewer {
            for value in std::iter::once(&reviewer.agent)
                .chain(reviewer.requested_model.iter())
                .chain(reviewer.reported_model.iter())
            {
                ensure!(
                    !value.trim().is_empty()
                        && value.len() <= 200
                        && !value.chars().any(char::is_control),
                    "invalid audit agent or model"
                );
            }
        }
        ensure!(self.schema == "haps.audit.v1", "unsupported audit evidence");
        ensure!(
            self.method != "source-review" || !self.binary_match,
            "source-only review cannot claim a binary match"
        );
        ensure!(
            !self.method.trim().is_empty() && self.method.len() <= 100,
            "audit method is required"
        );
        ensure!(
            !self.provenance.trim().is_empty() && self.provenance.len() <= 4096,
            "describe the audited artifact's provenance (including any unverified source-to-binary relationship)"
        );
        Ok(())
    }
}