"""Authorization, explicit input limits, safe paths and log redaction."""
from dataclasses import dataclass
import json
from pathlib import Path
import tempfile


@dataclass(frozen=True)
class Principal:
    tenant: str  # Created by trusted authentication boundary, not request JSON.
    can_read: bool


def read_record(principal, record):
    if not principal.can_read or principal.tenant != record["tenant"]:
        raise PermissionError("forbidden")
    return {"message": record["message"]}


def parse_body(raw):
    if len(raw) > 1024:  # Byte budget before decoding and parsing.
        raise ValueError("body too large")
    data = json.loads(raw.decode("utf-8"))
    if type(data) is not dict or set(data) != {"message"}:
        raise ValueError("invalid fields")
    message = data["message"]
    if type(message) is not str or len(message) > 64:
        raise ValueError("invalid message")
    return data


def safe_path(root, untrusted_name):
    target = (root / untrusted_name).resolve()
    if not target.is_relative_to(root.resolve()) or target == root.resolve():
        raise ValueError("outside allowed root")
    return target  # Directory must not be writable by adversaries: resolve has TOCTOU limits.


def audit(principal, operation, status):
    # Allow-list fields; never log token, password or complete request body.
    return {"tenant": principal.tenant, "operation": operation, "status": status}


def must_reject(function, *args):
    try:
        function(*args)
    except (PermissionError, ValueError):
        return
    raise AssertionError("dangerous input accepted")


def main():
    alice, bob = Principal("A", True), Principal("B", True)
    record = {"tenant": "A", "message": "ok", "token": "example-secret"}
    assert read_record(alice, record) == {"message": "ok"}
    must_reject(read_record, bob, record)
    must_reject(read_record, Principal("A", False), record)
    assert parse_body(b'{"message":"ok"}') == {"message": "ok"}
    for raw in (b'x'*1025, b'{"message":1}', b'{"message":"ok","tenant":"A"}'):
        must_reject(parse_body, raw)
    with tempfile.TemporaryDirectory() as directory:
        root = Path(directory)
        assert safe_path(root, "export.json").parent == root.resolve()
        must_reject(safe_path, root, "../outside.json")
        must_reject(safe_path, root, str(root.parent / "outside.json"))
    entry = audit(alice, "read", 200)
    assert "example-secret" not in json.dumps(entry)
    print("authorization, shape/size, traversal and redaction negatives: passed")


if __name__ == "__main__":
    main()
