change-capsule 0.3.0

Isolated Git worktree attempts for coding agents, sealed into portable verifiable receipts
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
//! Offline verification of exported result bundles.
//!
//! A bundle produced by `capsule export` is a portable receipt: `bundle.json`,
//! `result.json`, and `result.patch`. Verification needs no capsule state
//! directory and no workspace, so any reviewer, CI job, or merge gate can
//! confirm that the diff it is looking at is exactly the diff that was sealed.

use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

use crate::error::{Error, Result};
use crate::git::Git;
use crate::model::{
    ArtifactBundle, ArtifactDescriptor, ArtifactKind, BUNDLE_SCHEMA_VERSION, CapsuleResult,
    HARD_PATCH_BYTES, ResultKind, SCHEMA_VERSION, VerificationReport,
};
use crate::signature::verify_bundle_signature_bytes;
use crate::state::{read_bytes_bounded, validate_id};

const BUNDLE_JSON_CAP: u64 = 1024 * 1024;

/// What a verification run should require beyond structural consistency.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct VerifyOptions {
    /// Reject bundles whose evidence is absent or contains *any* non-zero exit code.
    ///
    /// A receipt from an attempt that failed once and was then fixed carries
    /// that earlier failure, so this rejects it. Prefer
    /// [`Self::require_executed_evidence`] unless a spotless history is the
    /// property you actually want.
    pub require_successful_evidence: bool,
    /// Reject unless successful evidence is bound to the sealed patch.
    pub require_current_successful_evidence: bool,
    /// Reject unless Capsule itself ran a passing command against the sealed patch.
    ///
    /// This is the only evidence requirement that checks a fact rather than a
    /// caller's assertion, and it subsumes
    /// [`Self::require_current_successful_evidence`]. Set it in a merge gate.
    pub require_executed_evidence: bool,
    /// When set, additionally confirm against this repository that the pinned
    /// base commit exists and that the sealed patch applies to it, reproducing
    /// exactly the sealed patch bytes and changed paths.
    pub repository: Option<PathBuf>,
}

impl VerifyOptions {
    /// Check receipt integrity only, against no repository.
    #[must_use]
    pub fn integrity() -> Self {
        Self::default()
    }

    /// Verify with an explicit combination of evidence requirements.
    #[must_use]
    pub fn requiring(
        require_successful_evidence: bool,
        require_current_successful_evidence: bool,
        require_executed_evidence: bool,
    ) -> Self {
        Self {
            require_successful_evidence,
            require_current_successful_evidence,
            require_executed_evidence,
            repository: None,
        }
    }

    /// Re-derive the tree from `repository` and require executed evidence.
    ///
    /// This is what a merge gate should use. It deliberately does not also
    /// demand that every record on the capsule passed: an attempt that failed
    /// once and was then fixed produces a perfectly good receipt.
    #[must_use]
    pub fn strict(repository: impl Into<PathBuf>) -> Self {
        Self {
            require_successful_evidence: false,
            require_current_successful_evidence: false,
            require_executed_evidence: true,
            repository: Some(repository.into()),
        }
    }

    /// Require the sealed patch to apply to its pinned base in `repository`.
    #[must_use]
    pub fn with_repository(mut self, repository: impl Into<PathBuf>) -> Self {
        self.repository = Some(repository.into());
        self
    }
}

/// Verify an exported receipt directory.
///
/// Checks, in order: that `bundle.json` is a supported bundle naming exactly
/// the two expected artifacts; that `result.json` and `result.patch` match
/// their descriptors' digests and byte counts; and that the sealed result is
/// internally consistent, including that its patch digest, byte count, kind,
/// and changed-path list all agree with the patch bytes on disk.
///
/// With [`VerifyOptions::repository`] set, it additionally proves the pinned
/// base exists there and that applying the sealed patch to it reproduces
/// exactly the sealed bytes and changed paths. That step needs no clean
/// worktree and mutates nothing: the patch is applied to a private temporary
/// index.
///
/// Returns [`Error::Verification`] describing the first failed check, so the
/// message is safe to surface directly in CI output.
///
/// # Example
///
/// ```no_run
/// use change_capsule::{VerifyOptions, verify_bundle};
///
/// // The strongest option set: re-derive the tree from the repository, and
/// // require that Capsule itself ran a passing command against this patch.
/// let report = verify_bundle("./receipt", &VerifyOptions::strict("."))?;
/// println!("{} changed {} path(s)", report.capsule_id, report.changed_paths);
/// # Ok::<(), change_capsule::Error>(())
/// ```
pub fn verify_bundle(
    directory: impl AsRef<Path>,
    options: &VerifyOptions,
) -> Result<VerificationReport> {
    let directory = directory.as_ref();
    let bundle_bytes = read_bundle_snapshot(directory)?;
    verify_bundle_snapshot(directory, &bundle_bytes, options)
}

/// Authenticate and verify one exact `bundle.json` byte snapshot.
///
/// The trusted public key is caller-supplied out of band. This function opens
/// `bundle.json` exactly once, authenticates those bytes, and uses those same
/// bytes for ordinary receipt verification. Receipt-contained key material is
/// never consulted.
pub fn verify_authenticated_bundle(
    directory: impl AsRef<Path>,
    signature: &[u8; 64],
    trusted_public_key: &[u8; 32],
    options: &VerifyOptions,
) -> Result<VerificationReport> {
    let directory = directory.as_ref();
    let bundle_bytes = read_bundle_snapshot(directory)?;
    verify_bundle_signature_bytes(&bundle_bytes, signature, trusted_public_key)?;
    let mut report = verify_bundle_snapshot(directory, &bundle_bytes, options)?;
    report.signature_authenticated = true;
    Ok(report)
}

fn read_bundle_snapshot(directory: &Path) -> Result<Vec<u8>> {
    read_bytes_bounded(&directory.join("bundle.json"), BUNDLE_JSON_CAP)
        .map_err(|error| fail(format!("cannot read bundle.json: {error}")))
}

fn verify_bundle_snapshot(
    directory: &Path,
    bundle_bytes: &[u8],
    options: &VerifyOptions,
) -> Result<VerificationReport> {
    verify_bundle_snapshot_full(directory, bundle_bytes, options).map(|(report, _)| report)
}

/// Verify a bundle and hand back the validated result alongside its report.
///
/// Attestation needs the decoded result, and must never be able to describe a
/// receipt that did not verify, so both come from this one checked path.
fn verify_bundle_snapshot_full(
    directory: &Path,
    bundle_bytes: &[u8],
    options: &VerifyOptions,
) -> Result<(VerificationReport, CapsuleResult)> {
    let bundle: ArtifactBundle = serde_json::from_slice(bundle_bytes)
        .map_err(|error| fail(format!("bundle.json is not a valid bundle: {error}")))?;
    if bundle.schema_version != BUNDLE_SCHEMA_VERSION {
        return Err(fail(format!(
            "bundle schema version {} is not the supported version {BUNDLE_SCHEMA_VERSION}",
            bundle.schema_version
        )));
    }
    validate_id(&bundle.capsule_id)
        .map_err(|_| fail(format!("invalid bundle capsule id: {}", bundle.capsule_id)))?;

    let manifest_descriptor = single_descriptor(&bundle, ArtifactKind::ResultManifest)?;
    let patch_descriptor = single_descriptor(&bundle, ArtifactKind::ResultPatch)?;
    if bundle.artifacts.len() != 2 {
        return Err(fail("bundle must describe exactly two artifacts"));
    }
    if manifest_descriptor.name != "result.json" || patch_descriptor.name != "result.patch" {
        return Err(fail(
            "bundle artifact names must be result.json and result.patch",
        ));
    }

    let result_bytes = read_bytes_bounded(&directory.join("result.json"), BUNDLE_JSON_CAP)
        .map_err(|error| fail(format!("cannot read result.json: {error}")))?;
    let patch = read_bytes_bounded(&directory.join("result.patch"), HARD_PATCH_BYTES)
        .map_err(|error| fail(format!("cannot read result.patch: {error}")))?;
    check_descriptor(manifest_descriptor, &result_bytes)?;
    check_descriptor(patch_descriptor, &patch)?;

    let result: CapsuleResult =
        decode_receipt_result(&directory.join("result.json"), &result_bytes)
            .map_err(|error| fail(format!("result.json is not a valid sealed result: {error}")))?;
    verify_result_consistency(&bundle, &result, &patch)?;

    if options.require_successful_evidence
        && (result.evidence.is_empty() || result.evidence.iter().any(|item| item.exit_code != 0))
    {
        return Err(fail(
            "successful evidence is required, but evidence is absent or contains failures",
        ));
    }

    if options.require_current_successful_evidence
        && !result
            .evidence
            .iter()
            .any(|item| item.exit_code == 0 && item.patch_sha256 == result.patch_sha256)
    {
        return Err(fail(
            "current successful evidence is required, but no successful evidence is bound to the sealed patch",
        ));
    }

    if options.require_executed_evidence
        && !result.evidence.iter().any(|item| {
            item.executed && item.exit_code == 0 && item.patch_sha256 == result.patch_sha256
        })
    {
        return Err(fail(
            "executed evidence is required, but no command that Capsule ran itself passed against the sealed patch",
        ));
    }

    let repository_checked = if let Some(repository) = &options.repository {
        verify_against_repository(repository, &result, &patch)?;
        true
    } else {
        false
    };

    let report = VerificationReport {
        bundle_directory: directory.to_path_buf(),
        capsule_id: result.capsule_id.clone(),
        kind: result.kind,
        base_commit: result.base_commit.clone(),
        head_commit: result.head_commit.clone(),
        patch_bytes: result.patch_bytes,
        patch_sha256: result.patch_sha256.clone(),
        changed_paths: result.changed_paths.len(),
        evidence_total: result.evidence.len(),
        evidence_executed: result.evidence.iter().filter(|item| item.executed).count(),
        evidence_failed: result
            .evidence
            .iter()
            .filter(|item| item.exit_code != 0)
            .count(),
        repository_checked,
        signature_authenticated: false,
    };
    Ok((report, result))
}

/// Verify a receipt directory and return its validated sealed result.
pub(crate) fn verified_bundle_result(
    directory: &Path,
    options: &VerifyOptions,
) -> Result<(VerificationReport, CapsuleResult)> {
    let bundle_bytes = read_bundle_snapshot(directory)?;
    verify_bundle_snapshot_full(directory, &bundle_bytes, options)
}

fn single_descriptor(bundle: &ArtifactBundle, kind: ArtifactKind) -> Result<&ArtifactDescriptor> {
    let mut matches = bundle
        .artifacts
        .iter()
        .filter(|descriptor| descriptor.kind == kind);
    let descriptor = matches
        .next()
        .ok_or_else(|| fail(format!("bundle is missing a {kind:?} artifact")))?;
    if matches.next().is_some() {
        return Err(fail(format!("bundle has duplicate {kind:?} artifacts")));
    }
    Ok(descriptor)
}

fn check_descriptor(descriptor: &ArtifactDescriptor, bytes: &[u8]) -> Result<()> {
    let digest = hex::encode(Sha256::digest(bytes));
    if descriptor.bytes != bytes.len() as u64 {
        return Err(fail(format!(
            "{} is {} bytes but its descriptor records {}",
            descriptor.name,
            bytes.len(),
            descriptor.bytes
        )));
    }
    if descriptor.sha256 != digest {
        return Err(fail(format!(
            "{} does not match its descriptor digest",
            descriptor.name
        )));
    }
    if descriptor.content_address != format!("sha256:{digest}") {
        return Err(fail(format!(
            "{} content address does not match its bytes",
            descriptor.name
        )));
    }
    Ok(())
}

fn verify_result_consistency(
    bundle: &ArtifactBundle,
    result: &CapsuleResult,
    patch: &[u8],
) -> Result<()> {
    if result.schema_version != SCHEMA_VERSION {
        return Err(fail("result schema version is unsupported"));
    }
    if result.capsule_id != bundle.capsule_id {
        return Err(fail(format!(
            "result capsule id {} does not match bundle capsule id {}",
            result.capsule_id, bundle.capsule_id
        )));
    }
    if !valid_object_id(&result.base_commit) || !valid_object_id(&result.head_commit) {
        return Err(fail("result base or head commit is malformed"));
    }
    if !valid_sha256(&result.patch_sha256)
        || result
            .ignored_content_sha256
            .as_ref()
            .is_some_and(|digest| !valid_sha256(digest))
    {
        return Err(fail("result digests are malformed"));
    }
    if result.patch_sha256 != hex::encode(Sha256::digest(patch)) {
        return Err(fail("result.patch does not match the sealed patch digest"));
    }
    if result.patch_bytes != patch.len() as u64 {
        return Err(fail("result.patch does not match the sealed byte count"));
    }
    if result.created_at_unix > result.sealed_at_unix {
        return Err(fail("result was sealed before it was created"));
    }
    if result.ignored_content_sha256.is_none() {
        return Err(fail(
            "result is missing its ignored-content structural digest",
        ));
    }
    if result
        .changed_paths
        .iter()
        .chain(&result.ignored_paths)
        .any(|path| !path.is_valid_encoding())
    {
        return Err(fail("result contains a non-canonical path encoding"));
    }
    if result.evidence.iter().any(|item| {
        !valid_sha256(&item.patch_sha256)
            || item
                .output_sha256
                .as_ref()
                .is_some_and(|digest| !valid_sha256(digest))
    }) {
        return Err(fail("evidence digest is malformed"));
    }
    if result
        .evidence
        .iter()
        .any(|item| !item.executed && (item.output_sha256.is_some() || item.output_bytes.is_some()))
    {
        return Err(fail(
            "evidence claims output bytes without being executed by Capsule",
        ));
    }
    // The mirror of the check above, and the more important direction. Execution
    // is the one thing `--require-executed-evidence` rests on, and running a
    // command is exactly what produces an output digest and byte count. A record
    // asserting `executed` without them did not come from an execution, so
    // flipping that one boolean must not turn a rejected receipt into an
    // accepted one.
    if result
        .evidence
        .iter()
        .any(|item| item.executed && (item.output_sha256.is_none() || item.output_bytes.is_none()))
    {
        return Err(fail(
            "evidence claims Capsule executed it but carries no captured-output digest",
        ));
    }
    let empty = patch.is_empty();
    if (result.kind == ResultKind::NoChange) != empty {
        return Err(fail(
            "result kind does not agree with whether the sealed patch is empty",
        ));
    }
    if empty && !result.changed_paths.is_empty() {
        return Err(fail("empty result lists changed paths"));
    }
    if !empty && result.changed_paths.is_empty() {
        return Err(fail("non-empty result lists no changed paths"));
    }
    Ok(())
}

fn verify_against_repository(
    repository: &Path,
    result: &CapsuleResult,
    patch: &[u8],
) -> Result<()> {
    let git = Git::discover()?;
    let repository = git.repository(repository)?;
    let resolved = git
        .resolve_commit(&repository.worktree, &result.base_commit)
        .map_err(|error| {
            fail(format!(
                "pinned base {} is not available in the repository: {error}",
                result.base_commit
            ))
        })?;
    if resolved != result.base_commit {
        return Err(fail(format!(
            "pinned base resolved to a different commit: {resolved}"
        )));
    }
    if result.kind == ResultKind::NoChange {
        return Ok(());
    }
    let scratch = tempfile::tempdir()
        .map_err(|error| crate::error::io("temporary verification index", error))?;
    let index = scratch.path().join("index");
    let preview = git
        .apply_patch_preview(&repository.worktree, &result.base_commit, patch, &index)
        .map_err(|error| fail(format!("sealed patch does not apply to the base: {error}")))?;
    if preview.patch != patch {
        return Err(fail(
            "applying the sealed patch does not reproduce its exact bytes",
        ));
    }
    if preview.changed_paths != result.changed_paths {
        return Err(fail(
            "applying the sealed patch does not reproduce the sealed changed paths",
        ));
    }
    Ok(())
}

fn decode_receipt_result(path: &Path, bytes: &[u8]) -> Result<CapsuleResult> {
    let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|source| Error::Json {
        path: path.to_path_buf(),
        source,
    })?;
    let version = value
        .get("schema_version")
        .and_then(serde_json::Value::as_u64)
        .and_then(|value| u32::try_from(value).ok())
        .ok_or_else(|| fail("result has no valid schema version"))?;
    if version != SCHEMA_VERSION {
        return Err(fail(format!("unsupported result schema version {version}")));
    }
    serde_json::from_value(value).map_err(|source| Error::Json {
        path: path.to_path_buf(),
        source,
    })
}

fn valid_object_id(value: &str) -> bool {
    matches!(value.len(), 40 | 64)
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn valid_sha256(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

fn fail(message: impl Into<String>) -> Error {
    Error::Verification(message.into())
}