#!/usr/bin/env bash

export MISE_LOCKFILE=1

detect_platform
PLATFORM="$MISE_PLATFORM"

echo "=== Testing mise lock writes provenance ==="
# Use a tool that has SLSA provenance in the aqua registry (sops)
cat <<EOF >mise.toml
[tools]
sops = "3.12.1"
EOF

# Generate lockfile - provenance detection should be on by default
mise lock --platform "$PLATFORM"
assert "test -f mise.lock"
# sops has SLSA provenance configured in the aqua registry
# Lock-time verification records the SLSA provenance URL (intoto.jsonl)
assert_contains "cat mise.lock" 'provenance.slsa'

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

# Set up a tool via aqua backend
cat <<EOF >mise.toml
[tools]
"aqua:jqlang/jq" = "1.7.1"
EOF

# Generate lockfile with real checksums/URLs for the current platform only
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)
# Use awk for portable sed-like editing (works on both macOS and Linux)
awk -v platform="$PLATFORM" '
    # Remove existing provenance lines in the target platform section
    /^provenance/ && in_section { next }
    # Detect entering the target platform section and add provenance after the header
    { print }
    index($0, "platforms." platform) > 0 { in_section=1; print "provenance = \"github-attestations\"" }
    /^\[/ { in_section=0 }
' mise.lock >mise.lock.tmp && mv mise.lock.tmp mise.lock
assert_contains "cat mise.lock" 'provenance = "github-attestations"'

# Attempt install with provenance verification disabled.
# The lockfile says provenance was verified, but settings are off,
# so mise should refuse to install (downgrade/stripping attack).
rm -rf "$MISE_DATA_DIR/installs/aqua-jqlang-jq"
export MISE_GITHUB_ATTESTATIONS=0
export MISE_AQUA__GITHUB_ATTESTATIONS=0
assert_fail_contains "mise install 2>&1" "downgrade attack"

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

echo "mise lockfile provenance tests passed!"
