#!/usr/bin/env bash

export __MISE_SECRET_KEYS=FOO FOO=inherited-s3cr3t-9
cat >mise.toml <<'TOML'
[env]
BAR = "{{ get_env(name='FOO', default='hidden') }}"
[tasks.t]
run = 'echo "foo=${FOO-unset} marker=${__MISE_SECRET_KEYS-unset}"'
[tasks.u]
run = 'echo {{ env.FOO }}'
TOML
# tasks of a nested mise run do not inherit the parent's secrets or the marker
assert "mise run t" "foo=unset marker=unset"
# templates cannot see them
assert_contains "mise env -s bash" "hidden"
assert_not_contains "mise env -s bash" "inherited-s3cr3t-9"
assert_fail "mise run u"
# mise x still passes them through
assert "mise x -- sh -c 'printf %s \"\$FOO\"'" "inherited-s3cr3t-9"
# logs are redacted from the first line (ARGS is logged before Config loads)
MISE_DEBUG=1 MISE_LOG_FILE="$PWD/log" mise run t -- "$FOO" >/dev/null 2>&1 || true
assert_not_contains "cat log" "inherited-s3cr3t-9"
# env cache: positive control first, then the marker turns it off
export MISE_ENV_CACHE=1 __MISE_ENV_CACHE_KEY="dGVzdGtleXRlc3RrZXl0ZXN0a2V5dGVzdGtleXRlc3Q="
env -u __MISE_SECRET_KEYS mise env -s bash >/dev/null
assert_directory_not_empty "$MISE_STATE_DIR/env-cache"
rm -rf "$MISE_STATE_DIR/env-cache"
mise env -s bash >/dev/null
[[ ! -d $MISE_STATE_DIR/env-cache ]] || assert_directory_empty "$MISE_STATE_DIR/env-cache"
# dotenv expansion must not copy an inherited secret into a new name
cat >.env <<'DOTENV'
BAR=${FOO}
DOTENV
cat >mise.toml <<'TOML'
[env]
_.file = ".env"
[tasks.t]
run = 'echo "bar=${BAR-unset}"'
TOML
assert_not_contains "mise env -s bash" "inherited-s3cr3t-9"
assert "mise run t" "bar="
# the env_file setting expands against the same filtered environment
printf '[tasks.t]\nrun = %s\n' "'echo \"bar=\${BAR-unset}\"'" >mise.toml
assert_not_contains "MISE_ENV_FILE=.env mise env -s bash" "inherited-s3cr3t-9"
assert "MISE_ENV_FILE=.env mise run t" "bar="
# a sandbox allow_env must not read the secret back from mise's own environment
cat >mise.toml <<'TOML'
[tasks.named]
allow_env = ["FOO"]
run = 'echo "foo=${FOO-unset} marker=${__MISE_SECRET_KEYS-unset}"'
[tasks.wild]
allow_env = ["*"]
run = 'echo "foo=${FOO-unset} marker=${__MISE_SECRET_KEYS-unset}"'
TOML
assert "mise run named" "foo=unset marker=unset"
assert "mise run wild" "foo=unset marker=unset"
