"""
authz.py -- authorization: once a request's origin is authenticated, may it do what it asks? The two
classic answers -- access-control lists (ACLs) and capabilities -- with AFS-style directory ACLs,
groups and negative rights, and unforgeable, delegatable, revocable capability tokens.

[Questions this module answers]
  Authentication (kerberos.py) tells a server WHO is asking. Authorization
  decides whether that who may read, write or administer this object. Two
  data structures answer it, and they differ in who holds the list and how
  rights are delegated and revoked:
    - an ACL lists, PER OBJECT, which principals have which rights (the
      question "who may touch X?" is easy; "what may A touch?" is a scan);
    - a capability is an unforgeable token that IS a right to an object, held
      by the subject ("what may A touch?" is easy; "who may touch X?" is a scan).

[ACLs here] (after AFS, Lecture 5)
  - Rights are a set drawn from {read, write, insert, delete, lookup, admin}.
  - A principal's rights are the UNION of the entries for it and for every
    group it belongs to (groups may contain groups).
  - A NEGATIVE entry denies rights, and denial wins over any grant: this
    decouples fast revocation from slow propagation of group membership
    (AFS's reason). AFS attaches ACLs to DIRECTORIES, not files; a file's
    rights come from its directory, and Unix mode bits add a within-file
    refinement. `Volume` models that.

[Capabilities here]
  - A capability names (object, rights) and is signed by the issuer with a MAC
    under a server secret, so a holder cannot forge or widen one (it is an
    unforgeable bearer token, like a signed cookie or an OAuth token).
  - It can be ATTENUATED (a holder makes a weaker one for someone else:
    fewer rights, a shorter life, bound to one object) but never widened.
  - Revocation is the hard part: a bearer token is valid until it expires, so
    real systems add short lifetimes plus a revocation list or a generation
    number the server bumps. Both are modelled.

[DS link] Lecture 26 section 4. Saltzer and Schroeder 1975 (the protection survey); Lampson's
  access matrix (ACLs are its columns, capabilities its rows); AFS (Satyanarayanan 1989);
  macaroons (Birgisson et al. 2014) for attenuable tokens. MACs come from toycrypto.py.
"""

import course_path
course_path.use("lecture03")

import toycrypto as C
import wire

RIGHTS = ("read", "write", "insert", "delete", "lookup", "admin")


# ----------------------------------------------------------------------------------------------
# Access-control lists
# ----------------------------------------------------------------------------------------------

class Groups:
    """A group database: each group lists principals and other groups (membership may nest)."""

    def __init__(self):
        self.members = {}

    def define(self, group, members):
        self.members[group] = set(members)

    def expand(self, principal):
        """All identities that count as `principal`: itself and every group it is (transitively) in.

        [Edge cases] Cycles among groups are handled (a visited set); a principal in no group
          expands to just itself.
        """
        out, frontier = {principal}, [principal]
        while frontier:
            cur = frontier.pop()
            for g, members in self.members.items():
                if g not in out and cur in members:
                    out.add(g)
                    frontier.append(g)
        return out


class ACL:
    """An access-control list: positive and negative rights per principal or group.

    [Idea] grant(p, rights) adds rights for p; deny(p, rights) adds a NEGATIVE entry. A request
      by principal q is allowed iff the right is in the union of positive entries for q's
      identities AND not in the union of negative entries (denial wins).
    """

    def __init__(self, groups=None):
        self.groups = groups or Groups()
        self.positive = {}
        self.negative = {}

    def grant(self, principal, rights):
        self.positive.setdefault(principal, set()).update(rights)
        return self

    def deny(self, principal, rights):
        self.negative.setdefault(principal, set()).update(rights)
        return self

    def rights_of(self, principal):
        """The effective rights of `principal`. [Returns] a set drawn from RIGHTS."""
        ids = self.groups.expand(principal)
        pos = set().union(*(self.positive.get(i, set()) for i in ids)) if ids else set()
        neg = set().union(*(self.negative.get(i, set()) for i in ids)) if ids else set()
        return pos - neg

    def allows(self, principal, right):
        return right in self.rights_of(principal)


class Volume:
    """An AFS-style volume: ACLs on directories; a file inherits its directory's ACL, narrowed by
    the owner's mode bits (r/w/x apply to the file owner only, as AFS superimposes Unix semantics)."""

    def __init__(self):
        self.dir_acl = {}
        self.file_dir = {}
        self.owner = {}
        self.mode = {}

    def set_dir_acl(self, directory, acl):
        self.dir_acl[directory] = acl

    def add_file(self, path, directory, owner, mode="rw"):
        self.file_dir[path] = directory
        self.owner[path] = owner
        self.mode[path] = set(mode)

    def may(self, principal, path, right):
        """[Returns] True iff `principal` may exercise `right` on `path`.

        [Idea] The directory ACL decides first. Then, for the file's OWNER, the mode bits can
          REMOVE a right the ACL granted (e.g. a read-only file the owner cannot write), matching
          AFS's "mode bits say what, ACL says who" compromise.
        """
        acl = self.dir_acl.get(self.file_dir.get(path))
        if acl is None or not acl.allows(principal, right):
            return False
        if principal == self.owner.get(path):
            bit = {"read": "r", "write": "w", "lookup": "x"}.get(right)
            if bit is not None and bit not in self.mode.get(path, set("rwx")):
                return False
        return True


# ----------------------------------------------------------------------------------------------
# Capabilities
# ----------------------------------------------------------------------------------------------

class CapabilityServer:
    """Issues and checks capability tokens for its objects, under one secret.

    [Idea] A token is {object, rights, expires, generation, nonce} with a MAC over all of it.
      A holder cannot change any field without invalidating the MAC, so it cannot widen the
      rights or move to another object. The server checks the MAC, the expiry, and the object's
      current generation (bumping the generation revokes every token for that object at once).
    """

    def __init__(self, secret, clock):
        self.secret = secret
        self.clock = clock
        self.generation = {}            # object -> current generation (bumped to revoke)

    def _sign(self, body):
        return C.mac(self.secret, wire.dumps(body))

    def issue(self, obj, rights, life=600_000.0):
        body = {"obj": obj, "rights": sorted(rights), "exp": self.clock() + life,
                "gen": self.generation.get(obj, 0), "nonce": C.Rng(self.clock() + len(obj)).nonce(8)}
        return {"body": body, "mac": self._sign(body)}

    def attenuate(self, cap, rights=None, life=None, obj=None):
        """Make a weaker token from one you hold: a subset of its rights, a shorter life, and
        (optionally) narrowed to one object. [Returns] a new capability, or raises if it would widen.

        [Edge cases] Requesting a right or a longer life than the parent has raises ValueError --
          attenuation can only remove. (This models the server re-issuing under its secret; a
          chained scheme such as macaroons lets the holder attenuate offline, with the same rule.)
        """
        b = cap["body"]
        rights = set(b["rights"]) if rights is None else set(rights)
        if not rights <= set(b["rights"]):
            raise ValueError("attenuation cannot add rights")
        exp = b["exp"] if life is None else min(b["exp"], self.clock() + life)
        if exp > b["exp"]:
            raise ValueError("attenuation cannot extend the lifetime")
        o = b["obj"] if obj is None else obj
        if o != b["obj"]:
            raise ValueError("attenuation cannot change the object")
        body = {"obj": o, "rights": sorted(rights), "exp": exp, "gen": b["gen"], "nonce": b["nonce"]}
        return {"body": body, "mac": self._sign(body)}

    def revoke(self, obj):
        """Invalidate every outstanding token for `obj` by bumping its generation."""
        self.generation[obj] = self.generation.get(obj, 0) + 1

    def check(self, cap, obj, right):
        """[Returns] (True, "ok") or (False, reason). The server needs no per-subject state."""
        try:
            body, tag = cap["body"], cap["mac"]
        except (TypeError, KeyError):
            return False, "malformed"
        if not C.mac_ok(self.secret, wire.dumps(body), tag):
            return False, "bad MAC (forged or altered)"
        if body["obj"] != obj:
            return False, "wrong object"
        if right not in body["rights"]:
            return False, "right not in token"
        if self.clock() > body["exp"]:
            return False, "expired"
        if body["gen"] != self.generation.get(obj, 0):
            return False, "revoked (old generation)"
        return True, "ok"


def _selftest():
    checks = 0
    g = Groups()
    g.define("staff", {"alice", "bob"})
    g.define("admins", {"staff", "carol"})               # a group inside a group
    acl = ACL(g).grant("admins", {"read", "write", "admin"}).deny("bob", {"write"})
    assert acl.rights_of("alice") == {"read", "write", "admin"}
    assert acl.rights_of("bob") == {"read", "admin"}      # denial wins over the group grant
    assert acl.rights_of("carol") == {"read", "write", "admin"} and acl.rights_of("dave") == set()
    checks += 1
    vol = Volume()
    vol.set_dir_acl("/proj", acl)
    vol.add_file("/proj/plan", "/proj", "alice", mode="r")   # read-only even for its owner
    assert vol.may("alice", "/proj/plan", "read") and not vol.may("alice", "/proj/plan", "write")
    assert not vol.may("dave", "/proj/plan", "read")
    checks += 1
    now = [1000.0]
    srv = CapabilityServer(C.Rng(1).key(), lambda: now[0])
    cap = srv.issue("file42", {"read", "write"})
    assert srv.check(cap, "file42", "read")[0] and not srv.check(cap, "file99", "read")[0]
    assert not srv.check(cap, "file42", "admin")[0]
    checks += 1
    weak = srv.attenuate(cap, rights={"read"}, life=1000.0)
    assert srv.check(weak, "file42", "read")[0] and not srv.check(weak, "file42", "write")[0]
    try:
        srv.attenuate(cap, rights={"read", "admin"})
        raise AssertionError("widening should fail")
    except ValueError:
        pass
    checks += 1
    srv.revoke("file42")
    assert not srv.check(cap, "file42", "read")[0] and srv.check(cap, "file42", "read")[1].startswith("revoked")
    short = srv.issue("f", {"read"}, life=1000.0)
    assert srv.check(short, "f", "read")[0]
    now[0] += 2000.0
    assert srv.check(short, "f", "read")[1] == "expired"     # the clock has passed its lifetime
    checks += 1
    forged = {"body": dict(cap["body"], rights=["read", "write", "admin"]), "mac": cap["mac"]}
    assert not srv.check(forged, "file42", "admin")[0]
    checks += 1
    print("authz self-test: OK (%d checks)" % checks)


if __name__ == "__main__":
    _selftest()
