#!/usr/bin/env python3
# pop_lab.py: a generic proof-of-possession demo for an agent. NOT AAuth: the AAuth
# specification is not published, so nothing here claims to implement or test it.
#
# Two roles, both on 127.0.0.1:
#   issuer    POST /token issues an ES256 JWT whose cnf.jkt is the thumbprint of the
#             public key the agent sends. GET /healthz.
#   resource  GET /v1/calendar needs a bearer token AND an Agent-Proof header signed
#             with the key the token is bound to. GET /v1/legacy/calendar takes the
#             bearer token alone (the old way, for comparison). GET /healthz.
#
# Standard library only. ECDSA P-256 signing and verification call the openssl command.
#
# Run:
#   python3 -I pop_lab.py --role issuer --port 4901 --key issuer.key.pem --log run/issuer.log
#   python3 -I pop_lab.py --role resource --port 4902 --issuer-pub issuer.pub.pem --log run/resource.log
import argparse
import base64
import hashlib
import json
import os
import secrets
import subprocess
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

ISSUER_URL = "http://127.0.0.1:4901"
AUDIENCE = "calendar-api"
TOKEN_LIFETIME = 300
PROOF_WINDOW = 60  # seconds either side of the resource clock

ROLE = None
KEY = None          # issuer private key path
ISSUER_PUB = None   # issuer public key PEM text (resource role)
LOG = None
SEEN = {}           # jti -> time after which it can be forgotten
LOCK = threading.Lock()


class Refused(Exception):
    def __init__(self, status, code, detail, www=None):
        super().__init__(code)
        self.status = status
        self.code = code
        self.detail = detail
        self.www = www


def b64url(data):
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def b64url_dec(text):
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def norm(pem):
    return pem.strip().replace("\r\n", "\n") + "\n"


def jkt_of(pem):
    return b64url(hashlib.sha256(norm(pem).encode()).digest())


def openssl_sign(key_path, data):
    r = subprocess.run(["openssl", "dgst", "-sha256", "-sign", key_path], input=data, capture_output=True)
    if r.returncode != 0:
        raise RuntimeError("openssl could not sign")
    return r.stdout  # DER encoded ECDSA signature


def openssl_verify(pem, data, der_sig):
    with tempfile.TemporaryDirectory() as d:
        pub = os.path.join(d, "pub.pem")
        sig = os.path.join(d, "sig.der")
        with open(pub, "w") as f:
            f.write(norm(pem))
        with open(sig, "wb") as f:
            f.write(der_sig)
        r = subprocess.run(["openssl", "dgst", "-sha256", "-verify", pub, "-signature", sig],
                           input=data, capture_output=True)
    return r.returncode == 0


def der_to_raw(der):
    # SEQUENCE { INTEGER r, INTEGER s } -> 64 raw bytes for JWS ES256
    if der[0] != 0x30:
        raise ValueError("not DER")
    i, out = 2, []
    for _ in range(2):
        if der[i] != 0x02:
            raise ValueError("not DER")
        n = der[i + 1]
        v = der[i + 2:i + 2 + n]
        i += 2 + n
        out.append(v.lstrip(b"\x00").rjust(32, b"\x00"))
    return b"".join(out)


def raw_to_der(raw):
    if len(raw) != 64:
        raise ValueError("bad signature length")
    body = b""
    for v in (raw[:32], raw[32:]):
        v = v.lstrip(b"\x00") or b"\x00"
        if v[0] & 0x80:
            v = b"\x00" + v
        body += b"\x02" + bytes([len(v)]) + v
    return b"\x30" + bytes([len(body)]) + body


def make_token(sub, scope, jkt):
    now = int(time.time())
    header = b64url(json.dumps({"alg": "ES256", "typ": "JWT"}, separators=(",", ":")).encode())
    claims = {"iss": ISSUER_URL, "aud": AUDIENCE, "sub": sub, "scope": scope,
              "iat": now, "exp": now + TOKEN_LIFETIME, "jti": secrets.token_hex(8),
              "cnf": {"jkt": jkt}}
    payload = b64url(json.dumps(claims, separators=(",", ":")).encode())
    sig = b64url(der_to_raw(openssl_sign(KEY, f"{header}.{payload}".encode())))
    return f"{header}.{payload}.{sig}"


def check_token(token):
    parts = token.split(".")
    if len(parts) != 3:
        raise Refused(401, "invalid_token", "the token is not a three part JWT")
    try:
        header = json.loads(b64url_dec(parts[0]))
        claims = json.loads(b64url_dec(parts[1]))
        raw = b64url_dec(parts[2])
        der = raw_to_der(raw)
    except Exception:
        raise Refused(401, "invalid_token", "the token does not decode")
    if header.get("alg") != "ES256":
        raise Refused(401, "invalid_token", "unexpected alg")
    if not openssl_verify(ISSUER_PUB, f"{parts[0]}.{parts[1]}".encode(), der):
        raise Refused(401, "invalid_token", "the issuer signature does not verify")
    if claims.get("aud") != AUDIENCE:
        raise Refused(401, "invalid_token", "wrong audience")
    if claims.get("exp", 0) < time.time():
        raise Refused(401, "invalid_token", "the token has expired")
    return claims


def check_proof(header, token, claims, method, path):
    if not header:
        raise Refused(401, "proof_required",
                      "this endpoint needs an Agent-Proof header signed with the key the token is bound to",
                      www='Agent-Proof realm="calendar-api"')
    try:
        p = json.loads(b64url_dec(header))
        pub = norm(base64.b64decode(p["pub"]).decode())
        sig = base64.b64decode(p["sig"])
        ts = int(p["ts"])
        jti = str(p["jti"])
        ath = str(p["ath"])
        htm = str(p["htm"])
        htu = str(p["htu"])
    except Exception:
        raise Refused(401, "bad_proof", "the Agent-Proof header does not decode")
    if htm != method or htu != path:
        raise Refused(401, "bad_proof", "the proof was made for another request")
    if ath != b64url(hashlib.sha256(token.encode()).digest()):
        raise Refused(401, "bad_proof", "the proof was made for another token")
    if jkt_of(pub) != claims["cnf"]["jkt"]:
        raise Refused(401, "key_mismatch", "the proof key is not the key this token is bound to")
    msg = "\n".join([htm, htu, str(ts), jti, ath]).encode()
    if not openssl_verify(pub, msg, sig):
        raise Refused(401, "bad_signature", "the proof signature does not verify")
    now = time.time()
    with LOCK:
        for k in [k for k, v in SEEN.items() if v < now]:
            del SEEN[k]
        if jti in SEEN:
            raise Refused(401, "replay", "this proof was already used once")
        if abs(now - ts) > PROOF_WINDOW:
            raise Refused(401, "stale_proof", "the proof timestamp is outside the window")
        SEEN[jti] = now + 2 * PROOF_WINDOW


class Handler(BaseHTTPRequestHandler):
    server_version = "pop-lab"
    sys_version = ""

    def log_message(self, fmt, *args):
        pass

    def respond(self, status, body, www=None):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        if www:
            self.send_header("WWW-Authenticate", www)
        self.end_headers()
        self.wfile.write(data)
        note = body.get("error", "ok") if isinstance(body, dict) else "ok"
        if LOG:
            with open(LOG, "a") as f:
                f.write(f"{self.command} {urlsplit(self.path).path} {status} {note}\n")

    def do_GET(self):
        path = urlsplit(self.path).path
        try:
            if path == "/healthz":
                return self.respond(200, {"role": ROLE, "ok": True})
            if ROLE != "resource" or path not in ("/v1/calendar", "/v1/legacy/calendar"):
                raise Refused(404, "not_found", "no such path")
            auth = self.headers.get("Authorization", "")
            if not auth.startswith("Bearer "):
                raise Refused(401, "missing_token", "send Authorization: Bearer <token>", www="Bearer")
            token = auth[7:].strip()
            claims = check_token(token)
            bound = path == "/v1/calendar"
            if bound:
                check_proof(self.headers.get("Agent-Proof"), token, claims, "GET", path)
            return self.respond(200, {
                "ok": True,
                "endpoint": path,
                "agent": claims["sub"],
                "scope": claims["scope"],
                "proof": "checked" if bound else "not required",
                "events": [{"title": "Team sync", "start": "09:30"},
                           {"title": "Dentist", "start": "14:00"}],
            })
        except Refused as e:
            www = e.www or ("Bearer" if e.status == 401 else None)
            self.respond(e.status, {"error": e.code, "detail": e.detail}, www)

    def do_POST(self):
        path = urlsplit(self.path).path
        try:
            if ROLE != "issuer" or path != "/token":
                raise Refused(404, "not_found", "no such path")
            length = int(self.headers.get("Content-Length", "0") or 0)
            raw = self.rfile.read(length).decode()
            form = {k: v[0] for k, v in parse_qs(raw, keep_blank_values=True).items()}
            if form.get("agent") != "demo-agent":
                raise Refused(400, "unknown_agent", "agent must be demo-agent")
            if form.get("scope") != "calendar.read":
                raise Refused(400, "invalid_scope", "only calendar.read is issued in this demo")
            pem = form.get("public_key", "")
            if "BEGIN PUBLIC KEY" not in pem:
                raise Refused(400, "invalid_key", "public_key must be a PEM public key")
            token = make_token("demo-agent", "calendar.read", jkt_of(pem))
            return self.respond(200, {"access_token": token, "token_type": "Bearer",
                                      "expires_in": TOKEN_LIFETIME})
        except Refused as e:
            self.respond(e.status, {"error": e.code, "detail": e.detail})


def main():
    global ROLE, KEY, ISSUER_PUB, LOG
    ap = argparse.ArgumentParser(description="Generic proof-of-possession demo (not AAuth)")
    ap.add_argument("--role", choices=["issuer", "resource"], required=True)
    ap.add_argument("--port", type=int, required=True)
    ap.add_argument("--key", help="issuer private key, PEM (issuer role)")
    ap.add_argument("--issuer-pub", help="issuer public key, PEM (resource role)")
    ap.add_argument("--log", required=True)
    a = ap.parse_args()
    ROLE, LOG = a.role, a.log
    if ROLE == "issuer":
        if not a.key:
            ap.error("the issuer needs --key")
        KEY = a.key
    else:
        if not a.issuer_pub:
            ap.error("the resource needs --issuer-pub")
        with open(a.issuer_pub) as f:
            ISSUER_PUB = f.read()
    server = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
    print(f"{ROLE} listening on 127.0.0.1:{a.port}", flush=True)
    server.serve_forever()


if __name__ == "__main__":
    main()
