#!/usr/bin/env python3
# Security posture check #4: verify tenant isolation on the parameterized API.
# For each resource we request it once for OUR OWN tenant id and once for a NEIGHBORING tenant id,
# and confirm the foreign id is properly rejected (expected 401/403/404). Status code + size only.
import socket, urllib.request, urllib.error, ssl, os
OUT="/opt/data/workspace/i26007/sec_check4.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(32); return resp.status, str(resp.headers.get("Content-Length","?")), resp.headers.get("Content-Type","")[:20]
    except urllib.error.HTTPError as e:
        try: e.read(32)
        except: pass
        return e.code, str(e.headers.get("Content-Length","?")), e.headers.get("Content-Type","")[:20]
    except Exception as e:
        return "ERR", str(e)[:40], ""
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 authed(p): return req(base+p, H({"Authorization":"Bearer "+JWT}) if JWT else H())
# (own ids: space 476, agent 604; foreign ids: space 4, space 2, agent 4)
tests=[
 ("/api/spaces?spaceId=476","own-space"),
 ("/api/spaces?spaceId=4","FOREIGN-space4"),
 ("/api/spaces?spaceId=2","FOREIGN-space2"),
 ("/api/agents?spaceId=476","own-space"),
 ("/api/agents?spaceId=4","FOREIGN-space4"),
 ("/api/agents?spaceId=2","FOREIGN-space2"),
 ("/api/agents?agentId=604","own-agent604"),
 ("/api/agents?agentId=4","FOREIGN-agent4"),
 ("/api/chats?agentId=604","own-agent604"),
 ("/api/chats?agentId=4","FOREIGN-agent4"),
 ("/api/secrets?agentId=604","own-agent604"),
 ("/api/secrets?agentId=4","FOREIGN-agent4"),
 ("/api/services?agentId=604","own-agent604"),
 ("/api/services?agentId=4","FOREIGN-agent4"),
 ("/api/knowledge-bases?spaceId=476","own-space"),
 ("/api/knowledge-bases?spaceId=4","FOREIGN-space4"),
 ("/api/models?spaceId=476","own-space"),
 ("/api/models?spaceId=4","FOREIGN-space4"),
]
log("=== TENANT ISOLATION (query-param API, with our low-priv session) ===")
for p,label in tests:
    sc,cl,ct=authed(p)
    log("%-38s %-16s %-4s len=%-8s %s"%(p,label,sc,cl,ct))
log("DONE")
