Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 66 additions & 12 deletions crates/mise-util/src/env.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Environment variables mise reads, and the directories derived from them.

use crate::env_diff::{EnvDiff, EnvMap};
use crate::env_diff::{EnvDiff, EnvMap, env_value_matches};
use crate::env_value::EnvValue;
use crate::file::replace_path;
use indexmap::IndexMap;
Expand Down Expand Up @@ -931,7 +931,9 @@ fn get_pristine_env(mise_diff: &EnvDiff, orig_env: EnvMap) -> EnvMap {
fn reverse_diff_preserving_overrides(mise_diff: &EnvDiff, mut env: EnvMap) -> EnvMap {
for (key, old_value) in &mise_diff.old {
match env_diff_get(&mise_diff.new, key) {
Some(new_value) if env_map_get(&env, key) == Some(new_value) => {
Some(new_value)
if env_map_get(&env, key).is_some_and(|v| env_value_matches(new_value, v)) =>
{
let key = env_map_key(&env, key)
.cloned()
.unwrap_or_else(|| key.clone());
Expand All @@ -946,7 +948,7 @@ fn reverse_diff_preserving_overrides(mise_diff: &EnvDiff, mut env: EnvMap) -> En

for (key, new_value) in &mise_diff.new {
if env_diff_get(&mise_diff.old, key).is_none()
&& env_map_get(&env, key) == Some(new_value)
&& env_map_get(&env, key).is_some_and(|v| env_value_matches(new_value, v))
&& let Some(key) = env_map_key(&env, key).cloned()
{
env.remove(&key);
Expand Down Expand Up @@ -1429,8 +1431,8 @@ mod tests {
]
.into(),
new: [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "managed".into()),
("ADDED".into(), crate::env_diff::hash_env_value("managed")),
("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
]
.into(),
..Default::default()
Expand All @@ -1452,6 +1454,55 @@ mod tests {
.into()
);
}
#[test]
fn test_reverse_diff_with_hashed_new_values() {
let diff = EnvDiff {
old: [("CHANGED".into(), "before".into())].into(),
new: [
("ADDED".into(), crate::env_diff::hash_env_value("managed")),
("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
]
.into(),
..Default::default()
};
let current = [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "override".into()),
]
.into();
// CHANGED was overridden after mise applied it, so it is left alone;
// ADDED is still the managed value and is removed.
assert_eq!(
reverse_diff_preserving_overrides(&diff, current),
[("CHANGED".into(), "override".into())].into()
);
}

/// A shell that keeps running across a mise upgrade still holds a `__MISE_DIFF` the
/// previous version wrote with plaintext `new` values. It must reverse cleanly, or the
/// managed variables would be treated as part of the pristine environment.
#[test]
fn test_reverse_diff_with_plaintext_new_values_from_older_mise() {
let diff = EnvDiff {
old: [("CHANGED".into(), "before".into())].into(),
new: [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "managed".into()),
]
.into(),
..Default::default()
};
let current = [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "managed".into()),
]
.into();
assert_eq!(
reverse_diff_preserving_overrides(&diff, current),
[("CHANGED".into(), "before".into())].into()
);
}

#[test]
fn test_reverse_diff_restores_unchanged_managed_values() {
let diff = EnvDiff {
Expand All @@ -1461,8 +1512,8 @@ mod tests {
]
.into(),
new: [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "managed".into()),
("ADDED".into(), crate::env_diff::hash_env_value("managed")),
("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
]
.into(),
..Default::default()
Expand All @@ -1487,8 +1538,8 @@ mod tests {
let diff = EnvDiff {
old: [("CHANGED".into(), "before".into())].into(),
new: [
("ADDED".into(), "managed".into()),
("CHANGED".into(), "managed".into()),
("ADDED".into(), crate::env_diff::hash_env_value("managed")),
("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
]
.into(),
..Default::default()
Expand All @@ -1509,9 +1560,12 @@ mod tests {
]
.into(),
new: [
("Added".into(), "managed".into()),
("Changed".into(), "managed".into()),
("MÎSE_FOO".into(), "managed-unicode".into()),
("Added".into(), crate::env_diff::hash_env_value("managed")),
("Changed".into(), crate::env_diff::hash_env_value("managed")),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
(
"MÎSE_FOO".into(),
crate::env_diff::hash_env_value("managed-unicode"),
),
]
.into(),
..Default::default()
Expand Down
67 changes: 66 additions & 1 deletion crates/mise-util/src/env_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ pub struct EnvDiff {
pub path: Vec<PathBuf>,
}

const HASH_PREFIX: &str = "blake3:";

/// Digest stored in place of an env value in `__MISE_DIFF` and `__MISE_SESSION`.
/// This is not a secret store: a low-entropy value can be brute-forced from its
/// digest, and the value itself is in every child's environment anyway. The
/// point is not to keep a second plaintext copy around.
pub fn hash_env_value(value: &str) -> String {
format!("{HASH_PREFIX}{}", blake3::hash(value.as_bytes()).to_hex())
}

/// Whether `actual` is the value recorded as `stored`. Blobs written by this mise hold a
/// [`hash_env_value`] digest; a shell that keeps running across an upgrade still holds
/// plaintext written by the previous version, which must reverse cleanly.
pub fn env_value_matches(stored: &str, actual: &str) -> bool {
stored == actual || stored == hash_env_value(actual)
}

#[derive(Debug)]
pub enum EnvDiffOperation {
Add(String, String),
Expand Down Expand Up @@ -197,9 +214,29 @@ impl EnvDiff {
Ok(rmp_serde::from_slice(&writer[..])?)
}

/// Serializes for `__MISE_DIFF`. The `new` values are replaced by
/// [`hash_env_value`] digests: they are only ever compared against the live
/// environment (see [`env_value_matches`]), so secrets mise injected are
/// not duplicated as plaintext in a variable every child process inherits.
/// `old` stays as-is because restoring the environment needs those values.
pub fn serialize(&self) -> Result<String> {
#[derive(Serialize)]
struct Wire<'a> {
old: &'a IndexMap<String, String>,
new: IndexMap<&'a str, String>,
path: &'a [PathBuf],
}
let wire = Wire {
old: &self.old,
new: self
.new
.iter()
.map(|(k, v)| (k.as_str(), hash_env_value(v)))
.collect(),
path: &self.path,
};
let mut gz = ZlibEncoder::new(Vec::new(), Compression::fast());
gz.write_all(&rmp_serde::to_vec_named(self)?)?;
gz.write_all(&rmp_serde::to_vec_named(&wire)?)?;
Ok(BASE64_STANDARD_NO_PAD.encode(gz.finish()?))
}

Expand Down Expand Up @@ -496,4 +533,32 @@ mod tests {
assert_eq!(parsed.get("AFTER").map(String::as_str), Some("\"after\""));
assert!(!parsed.keys().any(|k| k.starts_with("BASH_FUNC_")));
}

#[test]
fn test_serialize_does_not_store_new_values() {
let original: EnvMap = [("CHANGED".into(), "before".into())].into();
let diff = EnvDiff::new(
&original,
[
("CHANGED".to_string(), "after-secret".to_string()),
("ADDED".to_string(), "added-secret".to_string()),
],
);
let raw = diff.serialize().unwrap();
let back = EnvDiff::deserialize(&raw).unwrap();

assert_eq!(back.old.get("CHANGED").map(String::as_str), Some("before"));
for value in back.new.values() {
assert!(!value.contains("secret"), "{value}");
}
assert!(env_value_matches(&back.new["CHANGED"], "after-secret"));
assert!(!env_value_matches(&back.new["CHANGED"], "other"));
assert!(env_value_matches(&back.new["ADDED"], "added-secret"));
}

#[test]
fn test_env_value_matches_plaintext_from_older_mise() {
assert!(env_value_matches("plain", "plain"));
assert!(!env_value_matches("plain", "other"));
}
}
5 changes: 5 additions & 0 deletions docs/cache-behavior.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ a cached environment. Clear or disable the cache if those edits are not reflecte
Changes in an external service, such as a
rotated secret, are not file changes: choose a suitable TTL or disable environment caching.

mise does not cache secrets. A configuration with an `age`-encrypted value, a sops-encrypted
`_.file`, any directive with `redact = true`, or an env plugin that returns `redact = true` is
not environment-cached at all; mise recomputes its environment every time instead of writing the
decrypted values to disk.

For a command that must recompute environment values, set `MISE_ENV_CACHE=0` before starting
mise. For example, in a Node.js project with a `test` script:

Expand Down
1 change: 1 addition & 0 deletions docs/env-plugin-development.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ separate policy if your plugin also accepts absolute paths.
| `redact` | Request redaction of returned values in mise's processed output; defaults to `false` |

A user's explicit directive-level `redact` option overrides the plugin's preference.
A module whose values are redacted is never environment-cached, whatever `cacheable` says.
Redaction does not remove values from the environment and raw task output bypasses it.
See [redactions](/environments/#redactions).

Expand Down
35 changes: 35 additions & 0 deletions e2e/env/test_env_age_not_cached
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bash

# A decrypted age value is never written to the env cache, even with redact = false.
export MISE_EXPERIMENTAL=true
export MISE_ENV_CACHE=1
export __MISE_ENV_CACHE_KEY="dGVzdGtleXRlc3RrZXl0ZXN0a2V5dGVzdGtleXRlc3Q="
rm -f mise.toml age.txt

mise x age -- age-keygen -o age.txt 2>/dev/null
AGE_PUBLIC_KEY=$(grep "# public key:" age.txt | cut -d: -f2 | tr -d ' ')
export MISE_AGE_KEY
MISE_AGE_KEY=$(grep "AGE-SECRET-KEY-" age.txt)

mise set AGE_SECRET="my-secret-value" --age-encrypt --age-recipient "$AGE_PUBLIC_KEY"
sed -i.bak 's/^\(AGE_SECRET = { age = "[^"]*"\) }/\1, redact = false }/' mise.toml
assert_contains "cat mise.toml" "redact = false"

rm -rf "$MISE_STATE_DIR/env-cache"
assert_contains "mise env -s bash" "export AGE_SECRET=my-secret-value"
assert_contains "mise env -s bash" "export AGE_SECRET=my-secret-value"
assert "find '$MISE_STATE_DIR/env-cache' -type f 2>/dev/null | wc -l | tr -d ' '" "0"

# The same holds for an age value in [vars] that [env] renders through a template.
VARS_LINE=$(grep '^AGE_SECRET = ' mise.toml | sed 's/^AGE_SECRET/VAR_SECRET/; s/, redact = false//')
cat >mise.toml <<EOF
[vars]
$VARS_LINE

[env]
FROM_VAR = "{{ vars.VAR_SECRET }}"
EOF
rm -rf "$MISE_STATE_DIR/env-cache"
assert_contains "mise env -s bash" "export FROM_VAR=my-secret-value"
assert_contains "mise env -s bash" "export FROM_VAR=my-secret-value"
assert "find '$MISE_STATE_DIR/env-cache' -type f 2>/dev/null | wc -l | tr -d ' '" "0"
80 changes: 80 additions & 0 deletions e2e/env/test_env_cache_plugin_uncacheable
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env bash

# An env module that is not cacheable must keep the whole environment out of the env cache,
# whether it says so itself (cacheable = false) or the user marks its values redact = true.

export MISE_ENV_CACHE=1
export __MISE_ENV_CACHE_KEY="dGVzdGtleXRlc3RrZXl0ZXN0a2V5dGVzdGtleXRlc3Q="

COUNTER_FILE="$MISE_DATA_DIR/env_cache_test_counter"

make_plugin() {
local name="$1" cacheable="$2"
local dir="$MISE_DATA_DIR/plugins/$name"
mkdir -p "$dir/hooks"
cat >"$dir/metadata.lua" <<EOFMETA
PLUGIN = {}
PLUGIN.name = "$name"
PLUGIN.version = "1.0.0"
PLUGIN.homepage = "https://example.com"
PLUGIN.license = "MIT"
PLUGIN.description = "Test plugin"
PLUGIN.minRuntimeVersion = "0.3.0"
EOFMETA
cat >"$dir/hooks/mise_env.lua" <<EOFHOOK
function PLUGIN:MiseEnv(ctx)
local f = io.open("$COUNTER_FILE", "r")
local count = tonumber(f:read("*all")) or 0
f:close()
f = io.open("$COUNTER_FILE", "w")
f:write(tostring(count + 1))
f:close()
return {
env = {{key = "UNCACHEABLE_TEST_VAR", value = "value"}},
cacheable = $cacheable,
watch_files = {}
}
end
EOFHOOK
}

cached_files() {
find "$MISE_STATE_DIR/env-cache" -type f 2>/dev/null | wc -l | tr -d ' '
}

run_three_times() {
rm -rf "$MISE_STATE_DIR/env-cache"
echo 0 >"$COUNTER_FILE"
mise env -s bash >/dev/null 2>&1
mise env -s bash >/dev/null 2>&1
mise env -s bash >/dev/null 2>&1
cat "$COUNTER_FILE"
}

make_plugin test-uncacheable-env false
cat >"$MISE_CONFIG_DIR/config.toml" <<EOF
[env]
_.test-uncacheable-env = {}
EOF
count="$(run_three_times)"
assert "echo $count" "3"
assert "echo 0" "$(cached_files)"

# the plugin says cacheable = true, but the user redacts its values: still not cached
make_plugin test-redacted-env true
cat >"$MISE_CONFIG_DIR/config.toml" <<EOF
[env]
_.test-redacted-env = { redact = true }
EOF
count="$(run_three_times)"
assert "echo $count" "3"
assert "echo 0" "$(cached_files)"

# control: without redact the same plugin is cached
cat >"$MISE_CONFIG_DIR/config.toml" <<EOF
[env]
_.test-redacted-env = {}
EOF
count="$(run_three_times)"
assert "echo $count" "1"
[ "$(cached_files)" -gt 0 ] || fail "expected the cacheable environment to be cached"
Loading
Loading