#!/usr/bin/env python3
# Security posture check #6: map any remaining administrative/privileged namespaces and verify they are
# uniformly denied; plus verify secrets scoping with an agent-scoped query (own vs foreign).
# Status code + size only.
import socket, urllib.request, urllib.error, ssl, os
OUT="/opt/data/workspace/i26007/sec_check6.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
JWT=open("/opt/data/workspace/i26007/JWT").read().strip() if os.path.exists("/opt/data/workspace/i26007/JWT") else None
def req(url,headers,timeout=8):
    r=urllib.request.Request(url,headers=headers,method="GET")
    try:
        with urllib.request.urlopen(r,timeout=timeout,context=CTX) as resp:
            resp.read(24); return resp.status, str(resp.headers.get("Content-Length","?")), resp.headers.get("Content-Type","")[:16]
    except urllib.error.HTTPError as e:
        try: e.read(24)
        except: pass
        return e.code, str(e.headers.get("Content-Length","?")), e.headers.get("Content-Type","")[:16]
    except Exception as e:
        return "ERR", str(e)[:30], ""
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
def A(p): return req(base+p, H({"Authorization":"Bearer "+JWT}) if JWT else H())
adm=["/api/_admin","/api/__admin","/api/backoffice","/api/manage","/api/console","/api/root","/api/superuser","/api/sudo","/api/ops","/api/devops","/api/infra","/internal/admin","/api/v1/admin","/api/v2/admin","/api/admin/users/1","/api/admin/spaces/4","/api/admin/agents/4","/api/privileged","/api/elevate","/api/impersonate","/api/support","/api/staff/users","/api/admin/organizations","/api/admin/billing"]
log("=== HIDDEN ADMIN NAMESPACES (none-auth / low-priv) ===")
for p in adm:
    s0,_,_=req(base+p,H()); s1,_,_=A(p)
    log("%-30s none=%-4s jwt=%-4s"%(p,s0,s1))
log("=== SECRETS AGENT-SCOPED (own vs foreign) ===")
for p,lab in [("/api/secrets?scope=agent&spaceId=476&agentId=604","own"),
              ("/api/secrets?scope=agent&spaceId=4&agentId=4","FOREIGN"),
              ("/api/secrets?scope=agent&spaceId=476&agentId=4","FOREIGN-agent-in-own-space"),
              ("/api/secrets?scope=space&spaceId=476&officeId=1","own-office")]:
    s,cl,ct=A(p); log("%-52s %-22s %-4s len=%s"%(p,lab,s,cl))
log("DONE")
