#!/usr/bin/env python3
# Security posture check #2: (a) discover non-standard/observability routes reachable directly on the
# backend; (b) verify that cross-tenant access is denied; (c) verify the backend does NOT trust
# client-supplied forwarding headers. Records ONLY HTTP status code + size; no bodies / tokens / PII.
import socket, urllib.request, urllib.error, ssl, os
OUT="/opt/data/workspace/i26007/sec_check2.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
try: ips=sorted(set(x[4][0] for x in socket.getaddrinfo(HOST,PORT,proto=socket.IPPROTO_TCP)))
except Exception as e: ips=[]; log("RESOLVE_FAIL",e)
log("RESOLVE",HOST,"->",ips)
JWT=open("/opt/data/workspace/i26007/JWT").read().strip() if os.path.exists("/opt/data/workspace/i26007/JWT") else None
MCP=open("/opt/data/workspace/i26007/MCP").read().strip() if os.path.exists("/opt/data/workspace/i26007/MCP") else None
def req(url,headers,timeout=7):
    r=urllib.request.Request(url,headers=headers,method="GET")
    try:
        with urllib.request.urlopen(r,timeout=timeout,context=CTX) as resp:
            resp.read(32); return resp.status, str(resp.headers.get("Content-Length","?"))
    except urllib.error.HTTPError as e:
        try: e.read(32)
        except: pass
        return e.code, str(e.headers.get("Content-Length","?"))
    except Exception as e:
        return "ERR", str(e)[:50]
base="http://%s:%d"%(HOST,PORT)
def H(extra=None):
    h={"User-Agent":"curl/8.5.0","Accept":"*/*","Connection":"close"}
    if extra: h.update(extra)
    return h
# (a) extra route discovery
extra_paths=["/socket.io/","/ws","/events","/stream","/sse","/api/socket","/metrics/","/-/health","/ready",
 "/api/v1/health","/.env","/config","/status","/admin","/dashboard","/management","/healthz/","/api/metrics",
 "/api/debug","/api/tracing","/api/healthz","/api/ready","/api/livez","/api/prometheus","/prometheus","/pgmetrics",
 "/debug/pprof/","/api/system/status","/api/info","/api/versionz","/api/queue","/api/jobs","/api/workers","/api/celery",
 "/api/webhooks","/api/cron","/api/scheduler","/api/migrations","/api/db-check","/api/dbcheck","/api/ping"]
log("=== A ROUTE DISCOVERY (no auth) ===")
for p in extra_paths:
    sc,cl=req(base+p,H()); log("%-26s %-4s len=%s"%(p,sc,cl))
# (b) cross-tenant access-control (status only): our own low-priv token vs none vs mcp token
log("=== B CROSS-TENANT ACCESS CONTROL (status only) ===")
ten=["/api/agents/4","/api/agents/2","/api/agents/4/files","/api/agents/4/chats","/api/agents/2/chats",
 "/api/spaces/4","/api/spaces/2","/api/users/4","/api/users/2","/api/agents/604","/api/spaces","/api/agents",
 "/api/secrets/effective?agentId=4","/api/agents/4/mcp","/api/mcp-tokens","/api/accounts","/api/admin"]
for p in ten:
    sn,_=req(base+p,H()); sj,_=req(base+p,H({"Authorization":"Bearer "+JWT})) if JWT else ("-","-")
    sm,_=req(base+p,H({"Authorization":"Bearer "+MCP})) if MCP else ("-","-")
    log("%-34s none=%-4s jwt=%-4s mcp=%-4s"%(p,sn,sj,sm))
# (c) forwarding-header trust test: compare status vs spoofed headers on protected paths
log("=== C FORWARDING-HEADER TRUST (status compare; expect NO change if hardened) ===")
xff_paths=["/api/admin","/api/spaces","/api/agents/4","/api/secrets/effective?agentId=4"]
for p in xff_paths:
    s0,_=req(base+p,H())
    s1,_=req(base+p,H({"X-Forwarded-For":"127.0.0.1"}))
    s2,_=req(base+p,H({"X-Forwarded-For":"10.0.0.1","X-Real-IP":"10.0.0.1"}))
    s3,_=req(base+p,H({"X-Real-IP":"127.0.0.1"}))
    diff="DIFF" if len({s0,s1,s2,s3})>1 else "same"
    log("%-30s none=%-4s xff127=%-4s xff10=%-4s realip127=%-4s %s"%(p,s0,s1,s2,s3,diff))
log("DONE")
