"""
sebbi_contain.py - sebbi.pro Containment Gate guard. One file, standard library only.

    export SEBBI_BOX=CB-XXXXXXXX  SEBBI_BOX_TOKEN=cgt_...
    import sebbi_contain; sebbi_contain.arm()

After arm(), every network connection, every file opened outside the box's folders and every
command started from this Python process is checked with the gate first. Anything the gate does
not ALLOW raises PermissionError. If the gate cannot be reached, the action is stopped.
Checking is sealed on sebbi.pro, so the record of what the agent tried exists outside the agent.
"""
import builtins, json, os, socket, subprocess, threading, urllib.request

GATE = os.environ.get("SEBBI_GATE", "https://sebbi.pro")
_local = threading.local()
_rules = {}
_orig = {}


def _ask(op):
    _local.inside = True
    try:
        body = dict(op, box=os.environ["SEBBI_BOX"], token=os.environ["SEBBI_BOX_TOKEN"])
        req = urllib.request.Request(GATE + "/x/contain/check", json.dumps(body).encode(), {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=8) as r:
            return json.loads(r.read().decode())
    except Exception as e:
        return {"verdict": "BLOCK", "why": ["gate unreachable, failing closed: %s" % e]}
    finally:
        _local.inside = False


def _need(op):
    if getattr(_local, "inside", False):
        return
    r = _ask(op)
    if r.get("verdict") != "ALLOW":
        raise PermissionError("sebbi Containment Gate: BLOCK - %s" % "; ".join(r.get("why", [])))


def _inside_paths(p):
    p = os.path.realpath(os.fspath(p)) if not isinstance(p, int) else None
    return p is not None and any(p == a or p.startswith(a.rstrip("/") + "/") for a in _rules.get("paths", []))


def arm():
    r = _ask_rules()
    _rules.update(r.get("rules", {}))

    def connect(self, address, *a, **k):
        if not getattr(_local, "inside", False) and isinstance(address, tuple):
            _need({"kind": "net", "target": str(address[0])})
        return _orig["connect"](self, address, *a, **k)

    def open_(file, *a, **k):
        if not isinstance(file, int) and not getattr(_local, "inside", False) and not _inside_paths(file):
            _need({"kind": "file", "target": os.path.realpath(os.fspath(file))})
        return _orig["open"](file, *a, **k)

    class Popen(_orig.setdefault("Popen", subprocess.Popen)):
        def __init__(self, args, *a, **k):
            cmd = args if isinstance(args, str) else " ".join(map(str, args))
            _need({"kind": "exec", "command": cmd})
            super().__init__(args, *a, **k)

    def system(cmd):
        _need({"kind": "exec", "command": str(cmd)})
        return _orig["system"](cmd)

    _orig.setdefault("connect", socket.socket.connect)
    _orig.setdefault("open", builtins.open)
    _orig.setdefault("system", os.system)
    socket.socket.connect = connect
    builtins.open = open_
    subprocess.Popen = Popen
    os.system = system
    return _rules


def _ask_rules():
    _local.inside = True
    try:
        u = GATE + "/x/contain/rules?box=%s&token=%s" % (os.environ["SEBBI_BOX"], os.environ["SEBBI_BOX_TOKEN"])
        with urllib.request.urlopen(u, timeout=8) as r:
            return json.loads(r.read().decode())
    finally:
        _local.inside = False
