#!/usr/bin/env python3 """Extract internal API/URL integrations from code/config into audit graph.""" import json import re from pathlib import Path import psycopg2 PASS = Path("/root/.pg-superuser-pass").read_text().strip() conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8") cur = conn.cursor() import sys RUN = int(sys.argv[1]) if len(sys.argv) > 1 else 1 ROOTS = [Path("/opt/hub-core"), Path("/opt/hub-bots"), Path("/opt/hub-agents"), Path("/root/buryan-infra/ops/scripts"), Path("/root/buryan-infra/deploy"), Path("/root/buryan-infra/services")] EXT = {".py", ".sh", ".yml", ".yaml", ".conf", ".json", ".js", ".ts", ".env", ".ini"} URL = re.compile(r"https?://([A-Za-z0-9_.-]+)(?::(\d+))?([^\s\"'`)\]}>]*)") HOSTPORT = re.compile(r"\b(127\.0\.0\.1|localhost|192\.168\.1\.\d+|10\.\d+\.\d+\.\d+):(\d{2,5})\b") def ent(kind, name, status="", payload=None): cur.execute("""insert into audit.entities(run_id,kind,name,status,payload) values(%s,%s,%s,%s,%s) on conflict(run_id,kind,name) do update set status=excluded.status,payload=excluded.payload""", (RUN, kind, str(name)[:300], status, json.dumps(payload or {}, ensure_ascii=False))) def link(src, dst, kind, evidence=""): cur.execute("""insert into audit.links(run_id,src,dst,kind,evidence) values(%s,%s,%s,%s,%s) on conflict(run_id,src,dst,kind) do nothing""", (RUN, src, dst, kind, evidence[:500])) def finding(sev, area, title, evidence="", rec=""): cur.execute("select 1 from audit.findings where run_id=%s and title=%s", (RUN, title)) if not cur.fetchone(): cur.execute("insert into audit.findings(run_id,severity,area,title,evidence,recommendation) values(%s,%s,%s,%s,%s,%s)", (RUN, sev, area, title, evidence[:2000], rec[:2000])) seen_endpoints = {} files = 0 links = 0 for root in ROOTS: if not root.exists(): continue for p in root.rglob("*"): if p.is_file() and p.suffix.lower() in EXT and p.stat().st_size < 1_500_000: try: text = p.read_text(encoding="utf-8", errors="ignore") except Exception: continue files += 1 rel = str(p) for m in URL.finditer(text): host, port, path = m.group(1), m.group(2), m.group(3) if "@" in m.group(0): continue port = port or ("443" if m.group(0).startswith("https") else "80") if not (host.startswith("127.") or host == "localhost" or host.startswith("192.168.1.") or host.startswith("10.") or "." not in host): continue key = "%s:%s" % (host, port) seen_endpoints[key] = True line = text[max(0, m.start()-70):m.end()+70].replace("\n", " ") link("config:%s" % rel, "endpoint:%s" % key, "calls_api", line) links += 1 for m in HOSTPORT.finditer(text): host, port = m.group(1), m.group(2) key = "%s:%s" % (host, port) seen_endpoints[key] = True line = text[max(0, m.start()-70):m.end()+70].replace("\n", " ") link("config:%s" % rel, "endpoint:%s" % key, "uses_port", line) links += 1 for key in seen_endpoints: host, port = key.rsplit(":", 1) ent("endpoint", key, "referenced", {"host": host, "port": port}) link("endpoint:%s" % key, "port:%s" % port, "listens_or_should", key) # config entities cur.execute("select distinct src from audit.links where run_id=%s and src like 'config:%%'", (RUN,)) for (src,) in cur.fetchall(): ent("config", src[7:], "referenced") if seen_endpoints: finding("medium", "integrations", "Внутренние API-зависимости зашиты в код/конфиги", "Найдено %d уникальных endpoint в %d файлах; часть может быть hardcoded." % (len(seen_endpoints), files), "Свести endpoint'ы в реестр сервисов; проверить владельцев и health-check.") cur.execute("update audit.runs set summary=jsonb_set(jsonb_set(summary,'{facts,api_endpoints}',%s::jsonb,true),'{facts,api_graph_links}',%s::jsonb,true) where id=%s", (json.dumps(len(seen_endpoints)), json.dumps(links), RUN)) conn.commit() print("files", files, "endpoints", len(seen_endpoints), "links", links) cur.close(); conn.close()