mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
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
//! Encryption before Git capture and process-local decryption for live files.
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::{LazyLock, Mutex};

use eyre::{Result, WrapErr, bail};
use serde::{Deserialize, Serialize};

use super::{layout, reconcile::Object};
use crate::{agecrypt, system::history::shadow::HistoryRepo};

const MAGIC: &[u8] = b"mise-encrypted-file-v1\n";

#[derive(Clone)]
struct VerifiedAncestry {
    head: String,
    protected: BTreeSet<String>,
}

// Process-local only: never trust an editable on-disk cache as proof that
// plaintext was audited. The watcher reuses this across its short-lived stores.
static AUDITS: LazyLock<Mutex<BTreeMap<PathBuf, VerifiedAncestry>>> =
    LazyLock::new(|| Mutex::new(BTreeMap::new()));

/// Raw bytes serialized as a MessagePack `bin`, whatever the serializer's
/// default for `Vec<u8>` is.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Bytes(pub Vec<u8>);

impl Serialize for Bytes {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(&self.0)
    }
}

impl<'de> Deserialize<'de> for Bytes {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;
        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = Bytes;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("bytes")
            }
            fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Bytes, E> {
                Ok(Bytes(v.to_vec()))
            }
            fn visit_byte_buf<E: serde::de::Error>(self, v: Vec<u8>) -> Result<Bytes, E> {
                Ok(Bytes(v))
            }
        }
        deserializer.deserialize_byte_buf(Visitor)
    }
}

/// Audit the complete proposed ancestry, not just the latest tree. A newly
/// encrypted path cannot make its previously committed plaintext safe to push.
pub(crate) fn audit_history(
    repo: &HistoryRepo,
    head: &str,
    protected: &BTreeSet<String>,
) -> Result<()> {
    audit_history_cached(repo, head, protected).map(|_| ())
}

fn audit_history_cached(
    repo: &HistoryRepo,
    head: &str,
    protected: &BTreeSet<String>,
) -> Result<usize> {
    let cached = AUDITS
        .lock()
        .ok()
        .and_then(|cache| cache.get(repo.dir()).cloned())
        .filter(|cached| {
            cached.head == head
                || repo
                    .merge_bases(&cached.head, head)
                    .is_ok_and(|bases| bases.len() == 1 && bases[0] == cached.head)
        });
    if cached
        .as_ref()
        .is_some_and(|cached| cached.head == head && protected.is_subset(&cached.protected))
    {
        return Ok(0);
    }
    let mut commits = match &cached {
        Some(cached) => repo.rev_list_after(head, &cached.head)?,
        None => repo.rev_list(head, usize::MAX)?,
    };
    let mut protected = protected.clone();
    if let Some(cached) = &cached {
        protected.extend(cached.protected.iter().cloned());
    }
    // Policy changes cannot hide older plaintext, including on a merge
    // parent or a platform that this machine never activates.
    for commit in &commits {
        if let Some(manifest) = crate::system::history::manifest::Manifest::read(repo, commit)? {
            protected.extend(manifest.encrypted_paths());
        }
    }
    // A newly protected path invalidates the old proof for that policy: its
    // plaintext may live anywhere in old ancestry, including a merge parent.
    if cached
        .as_ref()
        .is_some_and(|cached| cached.protected != protected)
    {
        commits = repo.rev_list(head, usize::MAX)?;
    }
    let inspected = commits.len();
    let mut checked = BTreeSet::new();
    for commit in commits.into_iter().filter(|_| !protected.is_empty()) {
        for entry in repo.ls_tree(&commit)? {
            if !protected.iter().any(|path| {
                entry.path == *path
                    || entry
                        .path
                        .strip_prefix(path)
                        .is_some_and(|rest| rest.starts_with('/'))
            }) || !checked.insert((entry.path.clone(), entry.mode.clone(), entry.oid.clone()))
            {
                continue;
            }
            let object = (entry.mode, entry.oid);
            let valid =
                envelope(repo, &object, agecrypt::MAX_ENCRYPTED_BYTES)?.is_some_and(|outer| {
                    outer.path == entry.path
                        && matches!(outer.mode.as_str(), "100644" | "100755" | "120000")
                        && outer.ciphertext.0.starts_with(b"age-encryption.org/v1\n")
                });
            if !valid {
                bail!(
                    "cannot publish: encrypted path {} has an unencrypted or invalid version in commit {commit}; encrypting the latest version does not erase earlier plaintext. Review and explicitly rewrite or replace that history before connecting it to origin; mise will not rewrite it automatically",
                    entry.path
                );
            }
        }
    }
    if let Ok(mut cache) = AUDITS.lock() {
        // One watcher normally uses one repository. Bound temporary onboarding
        // probes without adding another durable history or state file.
        if cache.len() >= 64 && !cache.contains_key(repo.dir()) {
            cache.pop_first();
        }
        cache.insert(
            repo.dir().to_path_buf(),
            VerifiedAncestry {
                head: head.into(),
                protected,
            },
        );
    }
    Ok(inspected)
}

/// Resolve encrypted files from the same committed enrollment metadata.
pub(crate) fn encrypted_paths(
    repo: &HistoryRepo,
    commit: Option<&str>,
) -> Result<BTreeSet<String>> {
    let Some(commit) = commit else {
        return Ok(BTreeSet::new());
    };
    let Some(manifest) = crate::system::history::manifest::Manifest::read(repo, commit)? else {
        return Ok(BTreeSet::new());
    };
    let protected = manifest.encrypted_paths();
    Ok(repo
        .ls_tree(commit)?
        .into_iter()
        .filter(|entry| {
            protected.iter().any(|prefix| {
                entry.path == *prefix
                    || entry
                        .path
                        .strip_prefix(prefix)
                        .is_some_and(|rest| rest.starts_with('/'))
            })
        })
        .map(|entry| entry.path)
        .collect())
}

#[derive(Serialize, Deserialize)]
struct Envelope {
    path: String,
    mode: String,
    scheme: String,
    ciphertext: Bytes,
}

#[derive(Serialize, Deserialize)]
struct Plaintext {
    path: String,
    mode: String,
    scheme: String,
    content: Bytes,
}

fn control_file(path: &str) -> bool {
    if path.starts_with(".mise-history/") {
        return true;
    }
    let Some((root, path)) = path.split_once('/') else {
        return false;
    };
    if root.split('@').next() != Some("config") {
        return false;
    }
    (path.starts_with("conf.d/") && path.ends_with(".toml"))
        || (!path.contains('/')
            && path.ends_with(".toml")
            && (path.starts_with("config.") || path.starts_with("mise.")))
}

fn envelope(repo: &HistoryRepo, object: &Object, limit: u64) -> Result<Option<Envelope>> {
    // A gitlink names a commit in another repository, not a readable blob.
    if object.0 == "160000" {
        return Ok(None);
    }
    if !repo.blob_starts_with(&object.1, MAGIC)? {
        return Ok(None);
    }
    // Only encrypted envelopes have this limit; do not change plaintext sync.
    let bytes = repo.cat_object_bounded(&object.1, limit)?;
    let Some(body) = bytes.strip_prefix(MAGIC) else {
        return Ok(None);
    };
    Ok(Some(
        rmp_serde::from_slice(body).wrap_err("invalid encrypted file envelope")?,
    ))
}

fn validate(path: &str, outer: &Envelope, inner: &Plaintext) -> Result<()> {
    if outer.path != path
        || inner.path != path
        || inner.mode != outer.mode
        || inner.scheme != outer.scheme
        || !layout::is_safe_branch_path(path)
        || !matches!(inner.mode.as_str(), "100644" | "100755" | "120000")
    {
        bail!("encrypted file does not match its path or mode: {path}");
    }
    Ok(())
}

pub(crate) fn decrypt(
    repo: &HistoryRepo,
    path: &str,
    object: &Object,
    interactive: bool,
) -> Result<Object> {
    let outer = envelope(repo, object, agecrypt::MAX_ENCRYPTED_BYTES)?
        .ok_or_else(|| eyre::eyre!("missing encrypted file envelope: {path}"))?;
    if control_file(path) {
        bail!("setup configuration itself cannot be encrypted: {path}");
    }
    if outer.path != path {
        bail!("encrypted file does not match its path: {path}");
    }
    if let Some(decrypted) = repo.decrypted_object(&object.1) {
        return Ok(decrypted);
    }
    let bytes = agecrypt::decrypt_sync(&outer.ciphertext.0, interactive)
        .wrap_err_with(|| format!("cannot unlock {path}; run mise bootstrap dotfiles pull interactively with a matching age identity"))?;
    let inner: Plaintext =
        rmp_serde::from_slice(&bytes).wrap_err("invalid encrypted file payload")?;
    validate(path, &outer, &inner)?;
    let oid = repo.transient_blob_id(&inner.content.0)?;
    let decrypted = (inner.mode, oid);
    repo.remember_decrypted(&object.1, decrypted.clone());
    Ok(decrypted)
}

fn encrypt(
    repo: &HistoryRepo,
    path: &str,
    object: &Object,
    scheme: &str,
    recipients: &[Box<dyn age::Recipient + Send>],
) -> Result<Object> {
    let content = repo.cat_object_bounded(&object.1, agecrypt::MAX_PLAINTEXT_BYTES)?;
    let encoded = encode(path, &object.0, &content, scheme, recipients)?;
    let encrypted = ("100644".into(), repo.hash_blob(&encoded)?);
    repo.remember_decrypted(&encrypted.1, object.clone());
    Ok(encrypted)
}

/// Turn a reconciled process-local object into its committed representation.
/// Reuse an unchanged envelope; a merged plaintext is encrypted before hashing.
pub(super) fn commit_object(
    repo: &HistoryRepo,
    path: &str,
    object: &Object,
    manifest: &crate::system::history::manifest::Manifest,
    parents: &[&str],
    interactive: bool,
) -> Result<Object> {
    if !manifest.encrypted_paths().iter().any(|prefix| {
        path == prefix
            || path
                .strip_prefix(prefix)
                .is_some_and(|rest| rest.starts_with('/'))
    }) {
        return Ok(object.clone());
    }
    let mut strings = manifest.recipients.clone();
    strings.sort();
    strings.dedup();
    let scheme = crate::hash::hash_sha256_to_str(&strings.join("\n"));
    for parent in parents {
        if let Some(raw) = repo.object_at(parent, path)?
            && envelope(repo, &raw, agecrypt::MAX_ENCRYPTED_BYTES)?
                .is_some_and(|outer| outer.scheme == scheme)
            && decrypt(repo, path, &raw, interactive)? == *object
        {
            return Ok(raw);
        }
    }
    let recipients = strings
        .iter()
        .map(|recipient| {
            agecrypt::parse_recipient_mode(recipient, interactive)?
                .ok_or_else(|| eyre::eyre!("invalid age recipient: {recipient}"))
        })
        .collect::<Result<Vec<_>>>()?;
    encrypt(repo, path, object, &scheme, &recipients)
}

/// Encrypt bytes before they enter Git. Callers may store only the returned
/// envelope, never the input or the decrypted payload in repository objects.
pub(crate) fn encode(
    path: &str,
    mode: &str,
    content: &[u8],
    scheme: &str,
    recipients: &[Box<dyn age::Recipient + Send>],
) -> Result<Vec<u8>> {
    if control_file(path) {
        bail!("encrypt an external dotfile source instead of configuration: {path}");
    }
    if !matches!(mode, "100644" | "100755" | "120000") {
        bail!("unsupported encrypted file mode: {path}");
    }
    let inner = Plaintext {
        path: path.into(),
        mode: mode.into(),
        scheme: scheme.into(),
        content: Bytes(content.to_vec()),
    };
    let bytes = rmp_serde::to_vec_named(&inner)?;
    let outer = Envelope {
        path: path.into(),
        mode: mode.into(),
        scheme: scheme.into(),
        ciphertext: Bytes(agecrypt::encrypt_bytes(&bytes, recipients)?),
    };
    let mut encoded = MAGIC.to_vec();
    encoded.extend(rmp_serde::to_vec_named(&outer)?);
    if encoded.len() as u64 > agecrypt::MAX_ENCRYPTED_BYTES {
        bail!("encrypted file exceeds the size limit: {path}");
    }
    Ok(encoded)
}

#[cfg(test)]
mod tests {
    #[test]
    fn audit_reuses_verified_ancestry_but_rechecks_new_encryption_policy() {
        use crate::system::history::manifest::{Enrollment, Manifest};
        let tmp = tempfile::tempdir().unwrap();
        let repo = HistoryRepo::open_or_init_in(tmp.path()).unwrap().unwrap();
        let tree = repo
            .write_tree(&[(
                "100644".into(),
                repo.hash_blob(b"plain").unwrap(),
                "home/secret".into(),
            )])
            .unwrap();
        let first = repo.commit_tree(&tree, vec![], "first").unwrap();
        assert_eq!(
            audit_history_cached(&repo, &first, &BTreeSet::new()).unwrap(),
            1
        );
        assert_eq!(
            audit_history_cached(&repo, &first, &BTreeSet::new()).unwrap(),
            0
        );
        let second = repo.commit_tree(&tree, vec![&first], "second").unwrap();
        assert_eq!(
            audit_history_cached(&repo, &second, &BTreeSet::new()).unwrap(),
            1
        );

        let key = age::x25519::Identity::generate();
        let recipients: Vec<Box<dyn age::Recipient + Send>> = vec![Box::new(key.to_public())];
        let encrypted = repo
            .hash_blob(&encode("home/secret", "100644", b"plain", "test", &recipients).unwrap())
            .unwrap();
        let encrypted_tree = repo
            .write_tree(&[("100644".into(), encrypted, "home/secret".into())])
            .unwrap();
        let manifest = Manifest {
            enrollment: vec![Enrollment {
                path: "home/secret".into(),
                autosave: true,
                encrypt: true,
                variants: vec![],
            }],
            ..Default::default()
        };
        let encrypted_tree = manifest.write(&repo, &encrypted_tree).unwrap();
        let encrypted = repo
            .commit_tree(&encrypted_tree, vec![&second], "encrypt now")
            .unwrap();
        // No caller-supplied policy is needed: the new manifest expands the
        // protected set and forces the earlier plaintext commits to be checked.
        assert!(audit_history_cached(&repo, &encrypted, &BTreeSet::new()).is_err());

        // An unrelated branch cannot reuse proof about the previous branch.
        let other = repo.commit_tree(&tree, vec![], "unrelated").unwrap();
        assert_eq!(
            audit_history_cached(&repo, &other, &BTreeSet::new()).unwrap(),
            1
        );
        // A live policy change at the same head also invalidates the proof.
        assert!(
            audit_history_cached(&repo, &other, &BTreeSet::from(["home/secret".into()])).is_err()
        );
    }

    #[test]
    fn encrypted_tip_does_not_hide_plaintext_in_ancestry_or_merge_parents() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = HistoryRepo::open_or_init_in(tmp.path()).unwrap().unwrap();
        let key = age::x25519::Identity::generate();
        let recipients: Vec<Box<dyn age::Recipient + Send>> = vec![Box::new(key.to_public())];
        let path = "home/secret";
        let plain = repo.hash_blob(b"private").unwrap();
        let cipher = repo
            .hash_blob(&encode(path, "100644", b"private", "test", &recipients).unwrap())
            .unwrap();
        let empty = repo.empty_object("tree").unwrap();
        let make_tree = |oid: String| {
            repo.compose(
                &empty,
                &[crate::system::history::shadow::Overlay {
                    path: path.into(),
                    object: Some(("100644".into(), oid)),
                }],
            )
            .unwrap()
        };
        let plain_tree = make_tree(plain);
        let encrypted_tree = make_tree(cipher);
        let exposed = repo.commit_tree(&plain_tree, vec![], "plaintext").unwrap();
        let encrypted = repo
            .commit_tree(&encrypted_tree, vec![&exposed], "encrypted now")
            .unwrap();
        let protected = BTreeSet::from([path.into()]);
        assert!(audit_history(&repo, &encrypted, &protected).is_err());
        let clean = repo
            .commit_tree(&encrypted_tree, vec![], "encrypted from first commit")
            .unwrap();
        audit_history(&repo, &clean, &protected).unwrap();
        let merge = repo
            .commit_tree(&encrypted_tree, vec![&clean, &exposed], "merge")
            .unwrap();
        assert!(audit_history(&repo, &merge, &protected).is_err());
    }

    #[test]
    fn plaintext_magic_is_not_an_encryption_declaration() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = HistoryRepo::open_or_init_in(tmp.path()).unwrap().unwrap();
        let oid = repo.hash_blob(MAGIC).unwrap();
        let tree = repo
            .write_tree(&[("100644".into(), oid.clone(), "tracked/home/literal".into())])
            .unwrap();
        let upstream = super::super::reconcile::upstream(&repo, Some(&tree)).unwrap();
        assert_eq!(upstream.files["tracked/home/literal"].1, oid);
        assert!(encrypted_paths(&repo, Some(&tree)).unwrap().is_empty());
    }
    use super::*;

    #[test]
    fn plaintext_bypasses_envelope_limit_but_ciphertext_does_not() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = HistoryRepo::open_or_init_in(tmp.path()).unwrap().unwrap();
        let larger_than_pipe = vec![b'x'; 128 * 1024];
        for bytes in [
            b"".as_slice(),
            b"ordinary plaintext longer than the envelope limit".as_slice(),
            larger_than_pipe.as_slice(),
        ] {
            let object = ("100644".into(), repo.hash_blob(bytes).unwrap());
            assert!(envelope(&repo, &object, 4).unwrap().is_none());
        }
        let object = ("100644".into(), repo.hash_blob(MAGIC).unwrap());
        assert!(envelope(&repo, &object, 4).is_err());
        // The referenced submodule commit need not exist in the setup repo.
        let gitlink = ("160000".into(), "a".repeat(40));
        assert!(envelope(&repo, &gitlink, 4).unwrap().is_none());
    }

    #[test]
    fn envelope_preserves_modes_and_binds_path_and_scheme() {
        use age::secrecy::ExposeSecret;
        let tmp = tempfile::tempdir().unwrap();
        let repo = HistoryRepo::open_or_init_in(tmp.path()).unwrap().unwrap();
        let key = age::x25519::Identity::generate();
        let mut environment = crate::test::EnvVarGuard::new();
        environment.set("MISE_AGE_KEY", key.to_string().expose_secret());
        let recipients: Vec<Box<dyn age::Recipient + Send>> = vec![Box::new(key.to_public())];
        for mode in ["100644", "100755", "120000"] {
            let object = (
                mode.into(),
                repo.transient_blob_id(b"private contents").unwrap(),
            );
            let encrypted =
                encrypt(&repo, "tracked/home/secret", &object, "scheme", &recipients).unwrap();
            assert_eq!(encrypted.0, "100644");
            let wire = repo.cat_object(&encrypted.1).unwrap();
            assert!(!wire.windows(16).any(|w| w == b"private contents"));
            assert_eq!(
                decrypt(&repo, "tracked/home/secret", &encrypted, false).unwrap(),
                object
            );
            assert!(repo.object_type(&object.1).unwrap().is_none());
            assert!(
                repo.list_refs("refs/mise-decrypted-files/")
                    .unwrap()
                    .is_empty()
            );
            assert_eq!(repo.cat_object(&object.1).unwrap(), b"private contents");
            assert!(decrypt(&repo, "tracked/home/other", &encrypted, false).is_err());
            let mut outer = envelope(&repo, &encrypted, agecrypt::MAX_ENCRYPTED_BYTES)
                .unwrap()
                .unwrap();
            outer.scheme = "forged".into();
            let inner = Plaintext {
                path: outer.path.clone(),
                mode: mode.into(),
                scheme: "scheme".into(),
                content: Bytes(vec![]),
            };
            assert!(validate("tracked/home/secret", &outer, &inner).is_err());
        }
    }

    #[test]
    fn refuses_encryption_of_control_configuration() {
        assert!(control_file("config/config.toml"));
        assert!(control_file("config/conf.d/tools.toml"));
        assert!(control_file("config@macos/config.toml"));
        assert!(!control_file("templates/app.toml"));
        assert!(!control_file("home/config.toml"));
    }
}