from flask import Flask, jsonify
import os
import requests

app = Flask(__name__)

TRAVERSAL_URL = os.environ.get(
    "TRAVERSAL_URL",
    "http://proxy:8080/files/internal/secret.txt",
)
TRAVERSAL_BYPASS_URL = os.environ.get(
    "TRAVERSAL_BYPASS_URL",
    "http://proxy:8080/files//internal/secret.txt",
)
FILES_ROOT_URL = os.environ.get(
    "FILES_ROOT_URL",
    "http://proxy:8080/files/",
)
PUBLIC_URL = os.environ.get(
    "PUBLIC_URL",
    "http://proxy:8080/files/public.txt",
)
FLAG = os.environ.get("FLAG", "FLAG_NOT_SET")


def secret_leak_open(url: str) -> bool:
    try:
        resp = requests.get(url, timeout=3)
        return resp.status_code == 200 and "ELDER_SCROLL" in resp.text
    except requests.exceptions.RequestException:
        return False


def files_root_hardened() -> bool:
    try:
        resp = requests.get(FILES_ROOT_URL, timeout=3)
        return resp.status_code == 404
    except requests.exceptions.RequestException:
        return False


def public_access_ok() -> bool:
    try:
        resp = requests.get(PUBLIC_URL, timeout=3)
        return resp.status_code == 200 and "PUBLIC_OK" in resp.text
    except requests.exceptions.RequestException:
        return False


@app.route("/get_flag", methods=["GET"])
def get_flag():
    if secret_leak_open(TRAVERSAL_URL):
        return jsonify({
            "status": "open",
            "message": "Nginx alias traversal is still open. Fix nginx locations.",
        })
    if secret_leak_open(TRAVERSAL_BYPASS_URL):
        return jsonify({
            "status": "open",
            "message": "Traversal bypass via doubled slash is still open. Harden /files/ location.",
        })
    if not public_access_ok():
        return jsonify({
            "status": "blocked",
            "message": "Public file is blocked. Keep /files/public.txt reachable.",
        })
    if not files_root_hardened():
        return jsonify({
            "status": "open",
            "message": "Directory endpoint /files/ should return 404. Add strict try_files policy.",
        })
    return jsonify({"status": "fixed", "flag": FLAG})


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "9090"))
    app.run(host="0.0.0.0", port=port)
