#!/usr/bin/env python3
"""Minimal HTTP server for the FSA downgraded_read_paths escalation POC.

Serves poc.html on http://127.0.0.1:8080/poc.html and provides one endpoint:
  GET /recreate  -- recreates /tmp/fsa-poc-target.txt with sensitive content
                    (simulates the user/OS recreating the file after the
                    origin called handle.remove()).
"""
import http.server
import os
import socketserver

HOST, PORT = "127.0.0.1", 8080
HERE = os.path.dirname(os.path.abspath(__file__))
TARGET = "/tmp/fsa-poc-target.txt"
SECRET = "SECRET-CONTENT-WRITTEN-AFTER-REVOCATION\n"


def seed_target():
    with open(TARGET, "w") as f:
        f.write("original (pre-attack) content\n")
    print(f"[server] seeded {TARGET}")


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=HERE, **kw)

    def do_GET(self):
        if self.path.startswith("/recreate"):
            with open(TARGET, "w") as f:
                f.write(SECRET)
            print(f"[server] recreated {TARGET} with SECRET content")
            self.send_response(200)
            self.send_header("Content-Type", "text/plain")
            self.end_headers()
            self.wfile.write(b"ok")
            return
        return super().do_GET()


if __name__ == "__main__":
    seed_target()
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer((HOST, PORT), Handler) as httpd:
        print(f"[server] http://{HOST}:{PORT}/poc.html")
        httpd.serve_forever()
