"""Intentionally vulnerable and remediated owned APIs, Python 3.13+.

The in-memory repository models a data-access boundary, not SQL/RLS.
"""
import copy
import hashlib
import json
import secrets
import threading
import time
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit


def seed():
    return {
        "tenants": {"tenant-a": "Synthetic A", "tenant-b": "Synthetic B"},
        "users": {
            "alice": {"tenant": "tenant-a", "role": "manager"},
            "aaron": {"tenant": "tenant-a", "role": "reader"},
            "bob": {"tenant": "tenant-b", "role": "manager"}},
        "customers": {
            "customer-a": {"tenant": "tenant-a", "owner": "alice"},
            "customer-aaron": {"tenant": "tenant-a", "owner": "aaron"},
            "customer-b": {"tenant": "tenant-b", "owner": "bob"}},
        "documents": {
            "doc-a": {"tenant": "tenant-a", "owner": "alice", "customer": "customer-a",
                      "title": "SYNTHETIC_A", "amount_cents": 1000},
            "doc-aaron": {"tenant": "tenant-a", "owner": "aaron", "customer": "customer-aaron",
                          "title": "SYNTHETIC_AARON", "amount_cents": 2000},
            "doc-b": {"tenant": "tenant-b", "owner": "bob", "customer": "customer-b",
                      "title": "SYNTHETIC_B", "amount_cents": 3000}},
        "refunds": []}


class Rejected(Exception):
    def __init__(self, status, reason):
        self.status, self.reason = status, reason


class Repository:
    def __init__(self, state, secure):
        self.state, self.secure = state, secure

    def visible(self, actor, row):
        return row["tenant"] == actor["tenant"] and row["owner"] == actor["user"]

    def object(self, actor, object_id):
        row = self.state["documents"].get(object_id)
        if row is None or (self.secure and not self.visible(actor, row)):
            raise Rejected(404, "not_found")
        return row

    def export(self, actor, client_tenant):
        if self.secure:
            return {key: copy.deepcopy(row) for key, row in self.state["documents"].items()
                    if self.visible(actor, row)}
        return {key: copy.deepcopy(row) for key, row in self.state["documents"].items()
                if row["tenant"] == (client_tenant or actor["tenant"])}

    def execute(self, actor, operation, object_id=None, body=None, client_tenant=None):
        body = body or {}
        if operation == "export":
            return {"documents": self.export(actor, client_tenant)}
        row = self.object(actor, object_id)
        if self.secure and operation not in {"read", "update", "delete", "refund"}:
            raise Rejected(403, "operation_denied")
        if self.secure and operation in {"update", "delete", "refund"} and actor["role"] != "manager":
            raise Rejected(403, "operation_denied")
        if operation == "read":
            return copy.deepcopy(row)
        if operation == "update":
            if self.secure:
                if set(body) != {"title"} or not isinstance(body["title"], str) or not 1 <= len(body["title"]) <= 80:
                    raise Rejected(400, "invalid_fields")
            row.update(body)  # Vulnerable path permits authorization-driving fields.
            return copy.deepcopy(row)
        if operation == "delete":
            del self.state["documents"][object_id]
            return {"deleted": True}
        if operation == "refund":
            if self.secure and body:
                raise Rejected(400, "invalid_fields")
            # Customer relationship is derived from the authorized object.
            customer = self.state["customers"].get(row["customer"])
            if self.secure and (not customer or customer["tenant"] != actor["tenant"]
                                or customer["owner"] != actor["user"]):
                raise Rejected(404, "not_found")
            refund = {"document": object_id, "customer": row["customer"],
                      "tenant": row["tenant"], "amount_cents": row["amount_cents"]}
            self.state["refunds"].append(refund)
            return {"refund": copy.deepcopy(refund)}
        raise Rejected(403, "operation_denied")


class Application:
    def __init__(self, secure):
        self.secure, self.state, self.sessions, self.audit = secure, seed(), {}, []
        self.repository = Repository(self.state, secure)
        self.lock = threading.Lock()

    def session(self, user, lifetime=300):
        token = secrets.token_urlsafe(32)
        self.sessions[hashlib.sha256(token.encode()).hexdigest()] = {
            "user": user, **self.state["users"][user], "expires": time.time() + lifetime}
        return token

    def authenticate(self, cookie):
        cookies = SimpleCookie()
        try:
            cookies.load(cookie or "")
            token = cookies["lab_session"].value
        except (KeyError, ValueError):
            raise Rejected(401, "unauthenticated") from None
        actor = self.sessions.get(hashlib.sha256(token.encode()).hexdigest())
        if not actor or actor["expires"] <= time.time():
            raise Rejected(401, "unauthenticated")
        return actor

    def dispatch(self, method, path, headers, body):
        actor, operation = None, "unknown"
        try:
            actor = self.authenticate(headers.get("Cookie"))
            parsed = urlsplit(path)
            pieces = parsed.path.strip("/").split("/")
            client_tenant = headers.get("X-Tenant-ID")
            if pieces == ["export"] and method == "GET":
                operation, object_id = "export", None
            elif len(pieces) == 2 and pieces[0] == "documents":
                operation = {"GET": "read", "PATCH": "update", "DELETE": "delete"}.get(method)
                object_id = pieces[1]
            elif len(pieces) == 3 and pieces[0] == "documents" and pieces[2] == "refund" and method == "POST":
                operation, object_id = "refund", pieces[1]
            elif pieces == ["agent", "refund"] and method == "POST":
                operation, object_id = "refund", body.get("document")
                body = {key: value for key, value in body.items() if key != "document"}
                if not self.secure:
                    # Deliberate confused deputy: replaces user context with object owner's context.
                    row = self.state["documents"].get(object_id)
                    if row:
                        user = row["owner"]
                        actor = {"user": user, **self.state["users"][user]}
            else:
                raise Rejected(404, "not_found")
            if not operation:
                raise Rejected(403, "operation_denied")
            with self.lock:
                result = self.repository.execute(actor, operation, object_id, body, client_tenant)
            self.audit.append({"event": "authorization", "decision": "allow",
                               "operation": operation, "principal": actor["user"],
                               "tenant": actor["tenant"]})
            return 200, result
        except Rejected as error:
            self.audit.append({"event": "authorization", "decision": "deny",
                               "operation": operation or "unknown", "reason": error.reason,
                               "principal": actor["user"] if actor else "anonymous",
                               "tenant": actor["tenant"] if actor else None})
            return error.status, {"error": error.reason}


def handler(application):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_args):
            pass

        def handle_request(self):
            try:
                length = int(self.headers.get("Content-Length", "0"))
                if not 0 <= length <= 4096:
                    raise ValueError("length")
                body = json.loads(self.rfile.read(length)) if length else {}
                if not isinstance(body, dict):
                    raise ValueError("body")
                status, result = application.dispatch(self.command, self.path, self.headers, body)
            except (ValueError, TypeError):
                status, result = 400, {"error": "invalid_request"}
            encoded = json.dumps(result, sort_keys=True).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(encoded)))
            self.end_headers()
            self.wfile.write(encoded)

        do_GET = do_PATCH = do_DELETE = do_POST = handle_request
    return Handler


def serve(application):
    # No bind to a public interface, even when run without Docker.
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler(application))
    server.daemon_threads = True
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    return server
