#!/usr/bin/env python3
"""Convert a Boundary deployment into Warpgate GitOps resource files.

Reads Boundary through the `boundary` CLI, so it uses whatever address and
token the CLI is already logged in with (BOUNDARY_ADDR, BOUNDARY_TOKEN or the
keyring). Nothing is written to Boundary. Boundary only lists what the token
may read, so log in as an administrator of the global scope.

Writes two files:
  boundary.yaml      Warpgate TargetGroup, Role and Target resources
  boundary-report.txt  everything that could not be converted, per object

Review both, then `warpgate config plan boundary.yaml` and `config apply`.

Usage: boundary-to-warpgate.py [-o DIR] [--port-map 2222=ssh ...] [--boundary PATH]
"""

import argparse
import json
import re
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path

DEFAULT_PORTS = {
    22: "ssh",
    3389: "rdp",
    5432: "postgres",
    3306: "mysql",
    5900: "vnc",
    80: "http",
    443: "https",
}
KINDS = {"ssh", "rdp", "postgres", "mysql", "vnc", "http", "https"}
TYPE_KINDS = {"ssh": "ssh", "rdp": "rdp"}
TARGET_ACTIONS = {"authorize-session", "*"}


class BoundaryError(Exception):
    pass


class Boundary:
    def __init__(self, binary):
        self.binary = binary

    def __call__(self, *args):
        cmd = [self.binary, *args, "-format", "json"]
        res = subprocess.run(cmd, capture_output=True, text=True)
        if res.returncode != 0:
            raise BoundaryError(
                f"{' '.join(cmd)} failed: {(res.stderr or res.stdout).strip()}"
            )
        return json.loads(res.stdout)

    def list(self, *args):
        return self(*args).get("items") or []

    def read(self, kind, id_):
        return self(kind, "read", "-id", id_)["item"]


def slug(*parts):
    """Lowercase, since Warpgate compares names ignoring case"""
    s = "-".join(str(p) for p in parts if p)
    return re.sub(r"[^\w.-]+", "-", s.lower()).strip("-") or "unnamed"


def stable_names(candidates):
    """{key: [name, ...]} -> {key: name}. Each key gets the first of its
    candidates that no other key wants at that level, so a name depends on
    which objects exist, not on the order Boundary lists them in. The last
    candidate of every key must be unique (it carries the Boundary ID)."""
    names, taken, pending, level = {}, set(), dict(candidates), 0
    while pending:
        pick = {k: c[min(level, len(c) - 1)] for k, c in pending.items()}
        counts = Counter(pick.values())
        last = level >= max(len(c) for c in pending.values()) - 1
        for k, n in sorted(pick.items()):
            if last or (counts[n] == 1 and n not in taken):
                names[k] = n
                taken.add(n)
                del pending[k]
        level += 1
    return names


def parse_grant(grant):
    """`ids=*;type=target;actions=authorize-session` -> dict of sets"""
    out = {}
    for part in grant.split(";"):
        k, _, v = part.partition("=")
        out[k.strip()] = set(v.split(",")) if v else set()
    if "id" in out:
        out.setdefault("ids", out.pop("id"))
    return out


def grant_targets(grant, targets):
    """Target IDs a grant string lets its principals connect to.
    None: JSON grant, not parsed. False: grants no sessions at all."""
    if grant.startswith("{"):
        return None
    g = parse_grant(grant)
    if not g.get("actions", set()) & TARGET_ACTIONS:
        return False
    ids, types = g.get("ids", set()), g.get("type")
    if types is None:
        # without `type`, ids name the resources themselves
        return (ids - {"*"}) & set(targets)
    if "*" in ids and types & {"target", "*"}:
        return set(targets)
    # `ids=<id>;type=<t>` covers children of <id>, and targets have none
    return False


def scopes_granted(role, children):
    """Scope IDs a role's grants apply in"""
    own = role["scope_id"]
    gs = role.get("grant_scope_ids") or [role.get("grant_scope_id") or "this"]
    out = set()
    for g in gs:
        if g == "this":
            out.add(own)
        elif g in ("children", "descendants"):
            stack = list(children[own])
            while stack:
                s = stack.pop()
                out.add(s)
                if g == "descendants":
                    stack += children[s]
        else:
            out.add(g)
    return out


def http_url(scheme, addr, port):
    host = f"[{addr}]" if ":" in addr else addr
    return f"{scheme}://{host}:{port}" if port else f"{scheme}://{host}"


def port_kind(s):
    p, _, k = s.partition("=")
    if not p.isdigit() or not 0 < int(p) < 65536 or k not in KINDS:
        raise argparse.ArgumentTypeError(
            f"{s!r}: expected PORT=KIND, KIND one of {', '.join(sorted(KINDS))}"
        )
    return int(p), k


def self_test():
    ts = {"t1", "t2"}
    assert grant_targets("ids=*;type=target;actions=list,authorize-session", ts) == ts
    assert grant_targets("ids=*;type=*;actions=*", ts) == ts
    assert grant_targets("ids=t1;actions=authorize-session", ts) == {"t1"}
    assert grant_targets("id=t2;actions=*", ts) == {"t2"}
    assert grant_targets("ids=*;type=session;actions=list", ts) is False
    assert grant_targets("ids=*;type=scope;actions=*", ts) is False
    assert grant_targets("ids=t1;type=host;actions=*", ts) is False
    assert grant_targets("ids=t1;type=*;actions=*", ts) is False
    assert grant_targets("ids=t3;actions=authorize-session", ts) == set()
    assert grant_targets('{"ids": ["*"]}', ts) is None
    kids = defaultdict(list, {"global": ["o"], "o": ["p"]})
    assert scopes_granted({"scope_id": "o", "grant_scope_ids": ["this"]}, kids) == {"o"}
    assert scopes_granted(
        {"scope_id": "global", "grant_scope_ids": ["children"]}, kids
    ) == {"o"}
    assert scopes_granted(
        {"scope_id": "global", "grant_scope_ids": ["descendants"]}, kids
    ) == {"o", "p"}
    assert slug("Prod", "Web Server", None) == "prod-web-server"
    assert slug("prod", "Сервер") == "prod-сервер"
    assert http_url("https", "::1", 443) == "https://[::1]:443"
    assert port_kind("8443=https") == (8443, "https")
    for bad in ("foo", "9000=tcp", "0=ssh"):
        try:
            port_kind(bad)
            raise AssertionError(bad)
        except argparse.ArgumentTypeError:
            pass
    c = {
        "r1": ["admin", "eng-admin", "eng-admin-r1"],
        "r2": ["admin", "ops-admin", "ops-admin-r2"],
        "r3": ["dba", "x", "x-r3"],
    }
    want = {"r1": "eng-admin", "r2": "ops-admin", "r3": "dba"}
    assert stable_names(c) == want
    assert stable_names(dict(reversed(list(c.items())))) == want
    assert stable_names({"a": ["x", "x-a"], "b": ["x", "x-b"]}) == {
        "a": "x-a",
        "b": "x-b",
    }
    print("ok")


def main():
    if sys.argv[1:] == ["--self-test"]:
        return self_test()
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("-o", "--out", default=".", help="output directory")
    ap.add_argument("--boundary", default="boundary", help="boundary CLI binary")
    ap.add_argument(
        "--port-map",
        action="append",
        default=[],
        type=port_kind,
        metavar="PORT=KIND",
        help=f"treat tcp targets on PORT as KIND ({', '.join(sorted(KINDS))})",
    )
    args = ap.parse_args()
    ports = {**DEFAULT_PORTS, **dict(args.port_map)}
    try:
        convert(Boundary(args.boundary), ports, Path(args.out))
    except BoundaryError as e:
        sys.exit(str(e))


def convert(b, ports, out):
    report = defaultdict(list)

    def read(kind, id_, label):
        """A single object the token can't read is reported, not fatal"""
        try:
            return b.read(kind, id_)
        except BoundaryError as e:
            report[label].append(f"not readable, skipped: {e}")
            return None

    scopes = {
        s["id"]: s
        for s in b.list("scopes", "list", "-recursive", "-scope-id", "global")
    }
    scopes["global"] = {"id": "global", "name": "global", "scope": {}}
    children = defaultdict(list)
    for s in scopes.values():
        if parent := s.get("scope", {}).get("id"):
            children[parent].append(s["id"])

    def scope_path(sid):
        s = scopes.get(sid, {})
        parent = s.get("scope", {}).get("id")
        if not parent or parent == "global":
            return [s.get("name") or sid]
        return [*scope_path(parent), s.get("name") or sid]

    host_cache, set_cache = {}, {}

    def hosts_of_set(set_id):
        if set_id in set_cache:
            return set_cache[set_id]
        set_cache[set_id] = out = []
        hs = read("host-sets", set_id, f"host set {set_id}")
        if not hs:
            return out
        for hid in hs.get("host_ids") or []:
            if hid not in host_cache:
                host_cache[hid] = read("hosts", hid, f"host {hid}")
            h = host_cache[hid]
            if not h:
                continue
            attrs = h.get("attributes") or {}
            addr = attrs.get("address") or next(
                iter(h.get("dns_names") or h.get("ip_addresses") or []), None
            )
            if addr:
                out.append((h.get("name") or hid, addr))
            else:
                report[f"host {hid}"].append("no address, skipped")
        if hs.get("type") == "plugin":
            report[f"host set {set_id}"].append(
                "dynamic host set: hosts converted as discovered now, later changes are not followed"
            )
        return out

    # endpoint key (target ID, host name) -> data for the Target resource
    endpoints = {}
    group_scopes = set()

    for t in b.list("targets", "list", "-recursive", "-scope-id", "global"):
        label = f"target {t.get('name')} ({t['id']})"
        t = read("targets", t["id"], label)
        if not t:
            continue
        tid, attrs = t["id"], t.get("attributes") or {}
        port = attrs.get("default_port")
        kind = TYPE_KINDS.get(t["type"]) or ports.get(port)
        if not kind:
            report[label].append(
                f"type {t['type']} on port {port}: no matching Warpgate protocol, skipped "
                "(use --port-map, or reach it with SSH port forwarding)"
            )
            continue

        eps = []
        if addr := t.get("address"):
            eps.append((None, addr))
        for hs in t.get("host_source_ids") or []:
            eps += hosts_of_set(hs)
        if not eps:
            report[label].append("no address and no hosts, skipped")
            continue

        for key, note in [
            ("session_max_seconds", "session max duration"),
            ("session_connection_limit", "connection limit"),
        ]:
            if t.get(key) not in (None, -1, 28800):
                report[label].append(f"{note} {t[key]} has no Warpgate equivalent")
        if (
            t.get("egress_worker_filter")
            or t.get("ingress_worker_filter")
            or t.get("worker_filter")
        ):
            report[label].append(
                "uses a worker filter: Warpgate must reach the host directly"
            )
        for a in t.get("aliases") or []:
            report[label].append(
                f"alias {a.get('value')} dropped, targets have one name"
            )
        creds = (t.get("brokered_credential_source_ids") or []) + (
            t.get("injected_application_credential_source_ids") or []
        )
        if creds:
            report[label].append(
                f"credential sources {', '.join(creds)}: set target auth by hand "
                "(stored password, secret backend reference or SSH certificate auth)"
            )
        if kind == "ssh":
            report[label].append("username defaults to root: set options.ssh.username")
        elif kind in ("mysql", "postgres", "rdp"):
            report[label].append("set username and password in options")
        elif kind == "vnc":
            report[label].append(
                "set the VNC password in options.vnc.auth if the server needs one"
            )
        else:
            report[label].append(
                "users open it from the Warpgate portal, or set options.http.external_host "
                "to give it its own domain; certificates are verified (options.http.tls.verify), "
                "which fails for IP addresses and self-signed certificates"
            )

        group_scopes.add(t["scope_id"])
        multi = len(eps) > 1
        for host_name, addr in eps:
            endpoints[(tid, host_name or "")] = {
                "t": t,
                "kind": kind,
                "port": port,
                "addr": addr,
                "host": host_name if multi else None,
            }

    group_names = stable_names(
        {
            sid: [slug(*scope_path(sid)), slug(*scope_path(sid), sid)]
            for sid in group_scopes
        }
    )
    target_names = stable_names(
        {
            k: [
                slug(scope_path(e["t"]["scope_id"])[-1], e["t"].get("name"), e["host"]),
                slug(*scope_path(e["t"]["scope_id"]), e["t"].get("name"), e["host"]),
                slug(
                    *scope_path(e["t"]["scope_id"]), e["t"].get("name"), e["host"], k[0]
                ),
            ]
            for k, e in endpoints.items()
        }
    )

    principal_cache = {}

    def principal(p):
        """Readable description of a role principal"""
        pid = p.get("id")
        if pid not in principal_cache:
            kind = {"u": "users", "g": "groups", "m": "managed-groups"}.get(
                pid.split("_")[0]
            )
            item = read(kind, pid, f"principal {pid}") if kind else None
            name = (item or {}).get("login_name") or (item or {}).get("name") or pid
            if kind == "users":
                desc = f"user {name}"
            elif kind == "groups":
                members = [
                    principal({"id": m}) for m in (item or {}).get("member_ids") or []
                ]
                desc = f"group {name} ({', '.join(members) or 'no members'})"
            elif kind == "managed-groups":
                desc = f"managed group {name} (map via SSO role_mappings)"
            else:
                desc = pid
            principal_cache[pid] = desc
        return principal_cache[pid]

    roles = {}
    for r in b.list("roles", "list", "-recursive", "-scope-id", "global"):
        label = f"role {r.get('name')} ({r['id']})"
        r = read("roles", r["id"], label)
        if not r:
            continue
        ids = {p.get("id") for p in r.get("principals") or []}
        if "u_anon" in ids:
            report[label].append("granted to anonymous users: no Warpgate equivalent")
            if ids == {"u_anon"}:
                continue
        granted_scopes = scopes_granted(r, children)
        reachable = {
            k[0] for k, e in endpoints.items() if e["t"]["scope_id"] in granted_scopes
        }
        granted = set()
        for g in r.get("grant_strings") or []:
            hit = grant_targets(g, reachable)
            if hit is None:
                report[label].append(f"grant {g}: JSON grant format not converted")
            elif hit is False:
                report[label].append(f"grant {g}: not a session grant, no equivalent")
            elif hit:
                granted |= hit
            else:
                report[label].append(
                    f"grant {g}: no converted target in its grant scopes"
                )
        if granted:
            roles[r["id"]] = (r, label, granted)

    role_names = stable_names(
        {
            rid: [
                slug(r.get("name") or rid),
                slug(*scope_path(r["scope_id"]), r.get("name")),
                slug(*scope_path(r["scope_id"]), r.get("name"), rid),
            ]
            for rid, (r, _, _) in roles.items()
        }
    )

    targets = {}
    for k, e in endpoints.items():
        t, kind = e["t"], e["kind"]
        if kind in ("http", "https"):
            options = {"http": {"url": http_url(kind, e["addr"], e["port"])}}
        else:
            options = {
                kind: {"host": e["addr"], **({"port": e["port"]} if e["port"] else {})}
            }
        targets[k] = {
            "apiVersion": "warpgate/v1",
            "kind": "Target",
            "metadata": {"name": target_names[k]},
            "spec": {
                "description": t.get("description") or f"from Boundary {t['id']}",
                "group": group_names[t["scope_id"]],
                "roles": [],
                "options": options,
            },
        }

    resources = []
    for rid, (r, label, granted) in roles.items():
        name = role_names[rid]
        ids = [p.get("id") for p in r.get("principals") or []]
        # u_auth: every authenticated user
        everyone = "u_auth" in ids
        resources.append(
            {
                "apiVersion": "warpgate/v1",
                "kind": "Role",
                "metadata": {"name": name},
                "spec": {
                    "description": r.get("description") or f"from Boundary {rid}",
                    "is_default": everyone,
                },
            }
        )
        for k, doc in targets.items():
            if k[0] in granted:
                doc["spec"]["roles"].append(name)
        if everyone:
            report[label].append(
                f"granted to all users in Boundary: Warpgate role {name} is a default role "
                "for new users, assign it to existing users too"
            )
        principals = [
            principal(p)
            for p in r.get("principals") or []
            if p.get("id") not in ("u_auth", "u_anon")
        ]
        if principals:
            report[label].append(
                f"assign Warpgate role {name} to: {'; '.join(principals)}"
            )
        elif not ids:
            report[label].append(
                f"no principals: Warpgate role {name} is assigned to nobody"
            )

    resources = (
        [
            {
                "apiVersion": "warpgate/v1",
                "kind": "TargetGroup",
                "metadata": {"name": group_names[sid]},
                "spec": {"description": f"Boundary scope {'/'.join(scope_path(sid))}"},
            }
            for sid in sorted(group_scopes)
        ]
        + resources
        + list(targets.values())
    )

    out.mkdir(parents=True, exist_ok=True)
    # ponytail: JSON documents are valid YAML, so no YAML library is needed
    (out / "boundary.yaml").write_text(
        "".join(
            f"---\n{json.dumps(d, indent=2, ensure_ascii=False)}\n" for d in resources
        ),
        encoding="utf-8",
    )
    lines = []
    for obj, notes in report.items():
        lines.append("\n" + obj)
        lines += [f"  - {n}" for n in notes]
    (out / "boundary-report.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")

    counts = Counter(d["kind"] for d in resources)
    print(
        f"wrote {out / 'boundary.yaml'}: "
        + ", ".join(f"{v} {k}" for k, v in counts.items())
        + f"; {len(report)} objects need attention, see {out / 'boundary-report.txt'}"
    )


if __name__ == "__main__":
    main()
