"""Offline authorization simulation. No network, credentials, models or OS changes.
Run: python3 sandbox-authority-demo.py
The caller and task policy represent trusted server-side context. The request
represents untrusted model output; this does not test whether a model produces it.
"""
import json

POLICY = {"review-17": {"project": "demo-repo", "actions": {"read"}}}


def execute(enforce_task_policy, caller, request, permissions):
    policy = POLICY.get(caller)
    if not policy or request["project"] != policy["project"]:
        return "DENIED"
    action = request["action"]
    # Vulnerability in the first run: caller authentication and project checks
    # substitute for checking whether this task may change permissions.
    if enforce_task_policy and action not in policy["actions"]:
        return "DENIED"
    if action == "grant_write":
        permissions.add("write")  # Mock privileged service changes a mock ACL.
        return "GRANTED"
    if action == "read":
        return "READ_OK"
    return "DENIED"


def simulate(enforce_task_policy):
    permissions = {"read"}
    before = sorted(permissions)
    decision = execute(enforce_task_policy, "review-17", {
        "project": "demo-repo", "action": "grant_write"
    }, permissions)
    return {"before": before, "grant_request": decision,
            "after": sorted(permissions), "write_allowed": "write" in permissions}


if __name__ == "__main__":
    vulnerable = simulate(False)
    constrained = simulate(True)
    assert vulnerable["write_allowed"] is True
    assert constrained["write_allowed"] is False
    # Legitimate work still works; unknown callers and other projects do not.
    assert execute(True, "review-17", {"project": "demo-repo", "action": "read"}, {"read"}) == "READ_OK"
    assert execute(False, "unknown", {"project": "demo-repo", "action": "grant_write"}, {"read"}) == "DENIED"
    assert execute(False, "review-17", {"project": "other", "action": "grant_write"}, {"read"}) == "DENIED"
    print(json.dumps({"authentication_only": vulnerable, "task_authorized": constrained}, indent=2))
