#!/usr/bin/env python3
"""Original local token-validation exercise, Python 3.11+.

Real PyJWT signature/claim validation and permission-scoped SQLite reads over
fictional records. Ephemeral RSA keys remain in memory. No network, login flow,
account, external issuer, token output or production authentication changes.
This deliberately narrow JWT access-token profile is not a production verifier.
"""

import argparse
import hashlib
import json
import platform
import sqlite3
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

try:
    import cryptography
    import jwt
    from cryptography.hazmat.primitives.asymmetric import rsa
except ImportError:
    raise SystemExit(
        "Missing lab packages. In a new virtual environment run: "
        "python -m pip install -r fde-token-validation-requirements.txt"
    ) from None

TRUSTED_ISSUER = "https://issuer.training.invalid"
EXPECTED_AUDIENCE = "urn:lockedin:training:documents"
DOCUMENT_AUDIENCE = "urn:lockedin:training:documents"
OTHER_AUDIENCE = "urn:lockedin:training:billing"
REQUIRED_SCOPE = "documents:read"
ACTIVE_WORKSPACE = "north"  # Supplied trusted workspace, not a token claim.
DOCUMENT_ID = "P-7"
CASES = (
    "valid", "signature-tampered", "wrong-audience", "wrong-type", "expired",
    "missing-scope", "valid-no-resource-grant", "wrong-issuer", "future-nbf",
)
REQUIRED_CLAIMS = ("iss", "aud", "exp", "iat", "sub", "client_id", "jti")


class TokenProfileError(ValueError):
    """A library-verified token does not meet this lab's declared profile."""


def prepare_database():
    db = sqlite3.connect(":memory:")
    db.executescript("""
        CREATE TABLE documents (
            tenant TEXT, id TEXT, text TEXT, PRIMARY KEY (tenant, id));
        CREATE TABLE grants (
            tenant TEXT, document_id TEXT, subject TEXT, action TEXT,
            PRIMARY KEY (tenant, document_id, subject, action));
        INSERT INTO documents VALUES
            ('north', 'P-7', 'NORTH ONLY: Pump-7 uses checklist N.'),
            ('south', 'P-7', 'SOUTH ONLY: Pump-7 uses checklist S.');
        INSERT INTO grants VALUES
            ('north', 'P-7', 'U-7', 'read'),
            ('south', 'P-7', 'U-7', 'read'),
            ('north', 'P-7', 'U-8', 'read'),
            ('north', 'P-7', 'U-7', 'write');
    """)
    return db


def issue_case(case, private_key, now):
    # Issuance is a local fixture, not an OAuth authorization-server flow.
    claims = {
        "iss": TRUSTED_ISSUER, "aud": DOCUMENT_AUDIENCE,
        "sub": "U-7", "client_id": "training-client", "jti": "synthetic-" + case,
        "iat": now - 3600, "exp": now + 3600, "scope": REQUIRED_SCOPE,
    }
    token_type = "at+jwt"
    if case == "wrong-audience":
        claims["aud"] = OTHER_AUDIENCE
    elif case == "wrong-type":
        token_type = "JWT"
    elif case == "expired":
        claims["exp"] = now - 1800
    elif case == "missing-scope":
        claims["scope"] = "documents:write"
    elif case == "wrong-issuer":
        claims["iss"] = "https://other-issuer.training.invalid"
    elif case == "future-nbf":
        claims["nbf"] = now + 1800
    token = jwt.encode(claims, private_key, algorithm="RS256", headers={"typ": token_type})
    if case == "signature-tampered":
        # Inject an input fault, not another signing implementation: change a
        # significant character near the end of PyJWT's encoded signature.
        token = token[:-2] + ("A" if token[-2] != "A" else "B") + token[-1:]
    return token


def validate_token(token, public_key):
    verified = jwt.decode_complete(
        token, public_key, algorithms=["RS256"],
        issuer=TRUSTED_ISSUER, audience=EXPECTED_AUDIENCE, leeway=0,
        options={"require": list(REQUIRED_CLAIMS), "strict_aud": True},
    )
    # Read the header/claims returned by the verifying library. Nothing in an
    # incoming token chooses the key, issuer, algorithm or network destination.
    if verified["header"].get("typ") != "at+jwt":
        raise TokenProfileError("wrong-token-type")
    claims = verified["payload"]
    for field in ("sub", "client_id", "jti"):
        if not isinstance(claims[field], str) or not claims[field].strip():
            raise TokenProfileError("invalid-" + field)
    for field in ("iat", "exp", "nbf"):
        if field in claims and type(claims[field]) is not int:
            raise TokenProfileError("invalid-" + field)
    if claims["exp"] <= claims["iat"]:
        raise TokenProfileError("invalid-validity-window")
    return claims


def read_with_token(token, public_key, db):
    result = {
        "token_validation": "rejected", "validation_error": None,
        "scope_check": "not-reached", "query_executed": False,
        "rows_returned": 0, "permitted": False, "reason": "invalid-token",
        "document": None,
    }
    try:
        claims = validate_token(token, public_key)
    except (jwt.InvalidTokenError, TokenProfileError) as error:
        # Exception class only: library messages may contain supplied values.
        result["validation_error"] = type(error).__name__
        if isinstance(error, TokenProfileError):
            result["reason"] = str(error)  # Only fixed, locally authored codes.
        return result
    result["token_validation"] = "accepted"
    scope = claims.get("scope")
    if not isinstance(scope, str) or REQUIRED_SCOPE not in scope.split(" "):
        result.update(scope_check="rejected", reason="insufficient-scope")
        return result
    result["scope_check"] = "accepted"
    result["query_executed"] = True
    rows = db.execute("""
        SELECT d.id, d.text FROM documents d JOIN grants g
        ON g.tenant = d.tenant AND g.document_id = d.id
        WHERE d.tenant = ? AND d.id = ? AND g.subject = ? AND g.action = ?
    """, (ACTIVE_WORKSPACE, DOCUMENT_ID, claims["sub"], "read")).fetchall()
    result["rows_returned"] = len(rows)
    result["permitted"] = bool(rows)
    result["reason"] = "current-resource-grant" if rows else "no-current-resource-grant"
    if rows:
        result["document"] = {"id": rows[0][0], "text": rows[0][1]}
    return result


def report(case="compare"):
    now = int(time.time())  # Real wall clock; broad margins avoid edge timing.
    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    public_key = private_key.public_key()
    observations = []
    for name in CASES if case == "compare" else (case,):
        db = prepare_database()
        try:
            if name == "valid-no-resource-grant":
                db.execute(
                    "DELETE FROM grants WHERE tenant=? AND document_id=? AND subject=? AND action=?",
                    (ACTIVE_WORKSPACE, DOCUMENT_ID, "U-7", "read"),
                )
                db.commit()
            token = issue_case(name, private_key, now)
            observations.append({"case": name, **read_with_token(token, public_key, db)})
        finally:
            db.close()
    return {
        "synthetic": True,
        "execution": "Real local JWT verification and SQLite; no OAuth login flow or network",
        "observed_at": datetime.now(timezone.utc).isoformat(),
        "issued_at_epoch": now - 3600, "ordinary_expiry_epoch": now + 3600,
        "runtime": {"python": platform.python_version(), "pyjwt": jwt.__version__,
                    "cryptography": cryptography.__version__, "sqlite": sqlite3.sqlite_version},
        "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "trust": {"issuer": TRUSTED_ISSUER, "expected_audience": EXPECTED_AUDIENCE,
                  "algorithm": "RS256", "required_type": "at+jwt", "required_scope": REQUIRED_SCOPE},
        "results": observations,
        "limits": [
            "The signing key and trusted public key are supplied locally, not discovered from a remote issuer.",
            "Only this declared single-audience JWT profile is accepted; OAuth can also use opaque access tokens.",
            "Workspace selection is supplied trusted context; token scope does not replace a current resource grant.",
            "No login, refresh, key rotation, revocation service, TLS, concurrent access or production SSO is exercised.",
            "Reports are local learning evidence, not caller-facing authorization error responses.",
        ],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("case", choices=("compare", *CASES), nargs="?", default="compare")
    args = parser.parse_args()
    print(json.dumps(report(args.case), indent=2, sort_keys=True))


if __name__ == "__main__":
    main()
