#!/usr/bin/env bash

export MISE_LOCKFILE=1

detect_platform
PLATFORM="$MISE_PLATFORM"

echo "=== Testing mise lock writes URL for vfox tool ==="
cat <<EOF >mise.toml
[tools]
"vfox:version-fox/vfox-cmake" = "3.30.2"
EOF

# Generate lockfile - should include a URL from the vfox plugin
mise lock --platform "$PLATFORM"
assert "test -f mise.lock"
assert_contains "cat mise.lock" "url ="

echo "=== Testing vfox provenance downgrade attack detection ==="
rm -f mise.lock

# Regenerate a clean lockfile
mise lock --platform "$PLATFORM"
assert "test -f mise.lock"
assert_contains "cat mise.lock" "\"platforms.$PLATFORM\""

# Inject provenance into the lockfile (simulating a previously-verified install).
# NOTE: This awk matches every platform section header. It works here because
# the fixture has a single tool. For multi-tool lockfiles, add the tool name
# to the match (e.g. index($0, "vfox:version-fox/vfox-cmake") && ...).
awk -v platform="$PLATFORM" '
    { print }
    index($0, "platforms." platform) > 0 { print "provenance = \"github-attestations\"" }
' mise.lock >mise.lock.tmp && mv mise.lock.tmp mise.lock
assert_contains "cat mise.lock" 'provenance = "github-attestations"'

# Attempt install — the lockfile says provenance was verified, but the vfox
# plugin does not actually perform attestation verification, so mise should
# refuse to install (downgrade/stripping attack).
# NOTE: The downgrade check fires after the download, so a network failure here
# would produce a download error rather than "downgrade attack". This is an
# inherent limitation of testing against a real tool; a local fixture mock
# would be needed to make this assertion network-independent.
# Remove any previously installed version to ensure mise install must re-download,
# so the downgrade check is reached during this run.
rm -rf "$MISE_DATA_DIR/installs/vfox-version-fox-vfox-cmake"
assert_fail_contains "mise install 2>&1" "downgrade attack"

echo "=== Cleanup ==="
rm -f mise.lock mise.toml

echo "mise vfox lockfile provenance tests passed!"
