"""Independence test of counterfactual cut analysis, run on admin_graph.yaml.
A control is independent of the compromised workload only if no path in the administrative
graph leads from that workload to a node holding any of the control's six authorities.

  python3 independence.py               verdicts, reachable holders and one path for each
  python3 independence.py --b-fails     the same with egress property B failing
  python3 independence.py --markdown    the table used in the article
  python3 independence.py --json        machine output, used to draw figure 5
  python3 independence.py --article     the compact table printed in the article
  python3 independence.py --pairs       for each pair of controls, the nodes whose compromise or failure
                                        reaches a holder of both. Controls with any such node are distinct,
                                        not independent of each other
"""
import sys, json, yaml
from collections import deque
A = yaml.safe_load(open("admin_graph.yaml"))
EXTRA = {"B_fails"} if "--b-fails" in sys.argv else set()

def edges(flags):
    return [e for e in A["edges"] if e.get("when") is None or e["when"] in flags]

def paths_from(start, flags):
    """breadth first search: shortest path to every reachable node"""
    adj = {}
    for e in edges(flags): adj.setdefault(e["from"], []).append(e["to"])
    prev = {start: None}; q = deque([start])
    while q:
        x = q.popleft()
        for y in adj.get(x, []):
            if y not in prev: prev[y] = x; q.append(y)
    def path(n):
        out = []
        while n is not None: out.append(n); n = prev[n]
        return out[::-1]
    return {n: path(n) for n in prev}

def holders(spec, arr):
    return spec[arr] if isinstance(spec, dict) else spec

def run():
    res = {}
    for arr, a in A["arrangements"].items():
        flags = set(a["flags"]) | EXTRA
        P = paths_from(A["start"], flags)
        res[arr] = {"label": a["label"], "reachable": sorted(n for n in P if n != A["start"]), "edges": edges(flags), "controls": {}}
        for cid, c in A["controls"].items():
            cells = {}
            for k in A["authorities"]:
                hs = holders(c["holders"][k], arr)
                hit = [h for h in hs if h in P]
                cells[k] = {"holders": hs, "reachable": bool(hit), "path": P[hit[0]] if hit else None}
            n = sum(v["reachable"] for v in cells.values())
            res[arr]["controls"][cid] = {"name": c["name"], "cells": cells, "reachable_count": n, "independent": n == 0}
    return res

def common_causes(arr):
    """nodes from which a holder of each of two controls is reachable"""
    flags = set(A["arrangements"][arr]["flags"]) | EXTRA
    ids = list(A["controls"]); out = {}
    hold = {c: {h for k in A["authorities"] for h in holders(A["controls"][c]["holders"][k], arr)} for c in ids}
    reach = {n: set(paths_from(n, flags)) for n in A["nodes"]}
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            a, b = ids[i], ids[j]
            out[(a, b)] = sorted(n for n in A["nodes"] if reach[n] & hold[a] and reach[n] & hold[b])
    return out

if __name__ == "__main__":
    R = run(); N = A["nodes"]
    if "--pairs" in sys.argv:
        for arr in A["arrangements"]:
            for (a, b), ns in common_causes(arr).items():
                v = "distinct, not independent of each other" if ns else "independent of each other in this graph"
                print(f"[{A['arrangements'][arr]['label']}] {A['controls'][a]['name']} and {A['controls'][b]['name']}: {v}")
                if ns: print("   common nodes: " + ", ".join(N[n] for n in ns))
        sys.exit(0)
    if "--json" in sys.argv: print(json.dumps(R, indent=1)); sys.exit(0)
    if "--article" in sys.argv:
        cols = [("separate", "P1"), ("separate", "D1"), ("shared", "D1")]
        head = ["Egress rule inside the proxy, either arrangement", "D1, separate administration", "D1, shared secrets store and identity provider"]
        print("| Authority | " + " | ".join(head) + " |\n|---|---|---|---|")
        for k in A["authorities"]:
            row = []
            for a, c in cols:
                cell = R[a]["controls"][c]["cells"][k]
                h = ", ".join(N[x] for x in cell["holders"])
                if cell["reachable"]:
                    via = cell["path"][1:-1]
                    nm = ["the " + (N[x] if x == "PX" else N[x].lower()) for x in via]
                    txt = (", ".join(nm[:-1]) + " and " + nm[-1]) if len(nm) > 1 else (nm[0] if nm else "")
                    row.append(f"{h}. Reachable" + (f" through {txt}" if via else " in one step"))
                else: row.append(f"{h}. No path")
            print(f"| {k.capitalize()} | " + " | ".join(row) + " |")
        print("| Verdict | " + " | ".join(("Independent" if R[a]['controls'][c]['independent'] else f"Not independent. {R[a]['controls'][c]['reachable_count']} of 6 holders reachable") for a, c in cols) + " |")
        sys.exit(0)
    if "--markdown" in sys.argv:
        cols = [(arr, cid) for arr in R for cid in A["controls"]]
        print("| Authority | " + " | ".join(f"{A['controls'][c]['name']}, {R[a]['label'].lower()}" for a, c in cols) + " |")
        print("|---|" + "---|" * len(cols))
        for k in A["authorities"]:
            row = []
            for a, c in cols:
                cell = R[a]["controls"][c]["cells"][k]
                h = ", ".join(N[x] for x in cell["holders"])
                row.append(f"{h}. Reachable by {' to '.join(N[x] for x in cell['path'])}" if cell["reachable"] else f"{h}. No path")
            print(f"| {k.capitalize()} | " + " | ".join(row) + " |")
        print("| Verdict | " + " | ".join(("Independent" if R[a]['controls'][c]['independent'] else f"Not independent, {R[a]['controls'][c]['reachable_count']} of 6 holders reachable") for a, c in cols) + " |")
        sys.exit(0)
    for arr, r in R.items():
        print(f"\n[{r['label']}]  reachable from {N[A['start']]}: {', '.join(N[x] for x in r['reachable'])}")
        for cid, c in r["controls"].items():
            v = "INDEPENDENT" if c["independent"] else f"NOT INDEPENDENT ({c['reachable_count']} of 6 authority holders reachable)"
            print(f"   {c['name']}: {v}")
            for k, cell in c["cells"].items():
                if cell["reachable"]: print(f"      {k}: {' -> '.join(N[x] for x in cell['path'])}")
