#!/usr/bin/env bash
source "$(dirname "$0")/../scripts/common.sh"
TESTROOT=$(mktemp -d "$ROOT/runs/managed-secrets.XXXXXX")
mkdir -p "$TESTROOT/source" "$TESTROOT/reports"
python3 - "$TESTROOT/source" <<'PY'
from pathlib import Path
import sys

p = Path(sys.argv[1])
(p / "fixture.py").write_text(
    'aws_access_key_id = "' + "AKIA" + "ABCDEFGHIJKLMNOP" + '" # gitleaks:allow\n'
)
(p / ".gitleaks.toml").write_text('[allowlist]\nregexes = [".*"]\n')
PY
git -C "$TESTROOT/source" init -qb main
git -C "$TESTROOT/source" add .
git -C "$TESTROOT/source" -c user.name=Validation -c user.email=validation@localhost.invalid commit -qm 'Synthetic secret fixture'
set +e
e run --rm --pull=never --network none -v "$TESTROOT/source:/src:ro,z" -v "$TESTROOT/reports:/reports:z" \
    -v "$ROOT/ci/gitleaks.sh:/managed-gitleaks.sh:ro,z" localhost/devsecops/gitleaks:8.30.1 bash /managed-gitleaks.sh
status=$?
set -e
[[ $status == 1 ]] || fail 'Expected a finding rejection'
python3 - "$TESTROOT/reports" <<'PY'
import json
import sys
from pathlib import Path

for mode in ["git", "dir"]:
    findings = json.loads(
        (Path(sys.argv[1]) / "gitleaks" / (mode + ".json")).read_text()
    )
    assert findings and any(
        x["RuleID"] == "aws-access-token" for x in findings
    ), findings
    assert all(x["Secret"] == "REDACTED" for x in findings)
print(
    "PASS: managed Gitleaks rejects synthetic secrets despite repository config and allow comments."
)
PY
