#!/usr/bin/env python3 import base64 import json import os import re import urllib.error import urllib.request from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import urlparse, parse_qs import psycopg2 PASS = Path("/root/.pg-superuser-pass").read_text().strip() GITEA = os.environ.get("AUDIT360_GITEA_URL", "http://192.168.1.140:3000") GITEA_REPO = os.environ.get("AUDIT360_GITEA_REPO", "infrastructure/buryan-audit") GITEA_TOKEN = Path("/root/.gitea-admin-token").read_text().strip() ALLOWED_EMAILS = {x.strip().lower() for x in os.environ.get("AUDIT360_ALLOWED_EMAILS", "maloyakapg@gmail.com,akadmin").split(",") if x.strip()} HOST = os.environ.get("AUDIT360_HOST", "127.0.0.1") PORT = int(os.environ.get("AUDIT360_PORT", "9160")) def db(): return psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8") def gitea(method, path, body=None): data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None req = urllib.request.Request(GITEA + "/api/v1" + path, data=data, headers={"Authorization": "token " + GITEA_TOKEN, "Content-Type": "application/json"}, method=method) try: with urllib.request.urlopen(req, timeout=20) as r: raw = r.read().decode() except urllib.error.HTTPError as e: raw = e.read().decode(errors="replace") raise RuntimeError("gitea HTTP %s: %s" % (e.code, raw[:300])) try: return json.loads(raw or "{}") except Exception: raise RuntimeError("gitea invalid JSON: %s" % raw[:300]) def gitea_user_map(): out = {} try: for u in gitea("GET", "/admin/users?limit=100") or []: login = str(u.get("login") or "") for key in (u.get("email"), u.get("full_name"), login): if key: out[str(key).strip().lower()] = login except Exception: pass return out def match_owner(owner, users): s = str(owner or "").strip() candidates = [s, s.split("<")[0].strip()] m = re.search(r"<([^>]+)>", s) if m: candidates.append(m.group(1).strip()) for c in candidates: if c and c.lower() in users: return users[c.lower()] return None def gitea_issue_for_decision(did): c = db(); cur = c.cursor() cur.execute("select id,title,rationale,alternatives,owner,gitea_issue_url,gitea_issue_number from audit.decisions where id=%s", (did,)) r = cur.fetchone() if not r: c.close(); raise RuntimeError("decision not found") ident, title, rationale, alternatives, owner, url, num = r if url: c.close(); return {"ok": True, "url": url, "number": num, "existing": True} login = match_owner(owner, gitea_user_map()) body = "**Decision:** %s\n\n**Rationale:**\n%s\n\n**Alternatives:**\n%s\n\n**Owner:** %s\n\n**Audit 360:** http://192.168.1.10:9161/\n" % (title, rationale or "", alternatives or "", owner or "") payload = {"title": "[DECISION] %s" % title, "body": body} if login: payload["assignees"] = [login] issue = gitea("POST", "/repos/%s/issues" % GITEA_REPO, payload) cur.execute("update audit.decisions set gitea_issue_url=%s,gitea_issue_number=%s,updated_at=now() where id=%s", (issue.get("html_url"), issue.get("number"), did)) c.commit(); c.close() return {"ok": True, "url": issue.get("html_url"), "number": issue.get("number")} def gitea_assign_for_finding(fid): c = db(); cur = c.cursor() cur.execute("select owner,gitea_issue_number from audit.findings where id=%s", (fid,)) r = cur.fetchone() if not r or not r[1]: c.close(); return {"ok": False, "error": "finding or issue missing"} login = match_owner(r[0], gitea_user_map()) if not login: c.close(); return {"ok": False, "error": "owner not mapped to Gitea user"} gitea("PATCH", "/repos/%s/issues/%s" % (GITEA_REPO, r[1]), {"assignees": [login]}) cur.execute("update audit.findings set gitea_assignee=%s,updated_at=now() where id=%s", (login, fid)) c.commit(); c.close() return {"ok": True, "assignee": login} def gitea_issue_for_finding(fid): c = db(); cur = c.cursor() cur.execute("select id,severity,area,title,evidence,recommendation,owner,gitea_issue_url,gitea_issue_number,gitea_assignee from audit.findings where id=%s", (fid,)) r = cur.fetchone() if not r: c.close(); raise RuntimeError("finding not found") ident, sev, area, title, evidence, rec, owner, url, num, assignee = r if url: c.close(); return {"ok": True, "url": url, "number": num, "assignee": assignee, "existing": True} body = "**Severity:** %s\n\n**Area:** %s\n\n**Evidence:**\n%s\n\n**Recommendation:**\n%s\n\n**Owner:** %s\n\n**Audit 360:** http://192.168.1.10:9161/\n" % (sev, area, evidence or "", rec or "", owner or "") login = match_owner(owner, gitea_user_map()) payload = {"title": "[AUDIT][%s] %s" % (str(sev).upper(), title), "body": body} if login: payload["assignees"] = [login] issue = gitea("POST", "/repos/%s/issues" % GITEA_REPO, payload) cur.execute("update audit.findings set gitea_issue_url=%s,gitea_issue_number=%s,gitea_assignee=%s,updated_at=now() where id=%s", (issue.get("html_url"), issue.get("number"), login, fid)) c.commit(); c.close() return {"ok": True, "url": issue.get("html_url"), "number": issue.get("number"), "assignee": login} def gitea_sync(): c = db(); cur = c.cursor() cur.execute("select id,gitea_issue_number from audit.findings where gitea_issue_number is not null") rows = cur.fetchall(); synced = 0 for fid, num in rows: issue = gitea("GET", "/repos/%s/issues/%s" % (GITEA_REPO, num)) state = issue.get("state") if state == "closed": status = "fixed" else: cur.execute("select status from audit.findings where id=%s", (fid,)) old = (cur.fetchone() or ["open"])[0] status = old if old in ("accepted", "in_progress", "wontfix") else "in_progress" cur.execute("update audit.findings set status=%s,updated_at=now() where id=%s", (status, fid)) synced += 1 c.commit(); c.close() return {"ok": True, "synced": synced} def identity_owners(): try: with urllib.request.urlopen("http://127.0.0.1:9150/v1/accounts", timeout=5) as r: accounts = json.loads(r.read().decode()).get("accounts") or [] with urllib.request.urlopen("http://127.0.0.1:9150/v1/persons", timeout=5) as r: persons = {x.get("id"): x.get("display_name") for x in (json.loads(r.read().decode()).get("persons") or [])} out = [] for a in accounts: name = persons.get(a.get("person_id")) or a.get("email") or a.get("subject") out.append({"id": a.get("person_id") or a.get("subject"), "name": name, "email": a.get("email"), "role": a.get("role")}) return out except Exception: return [{"id": "admin", "name": "admin", "email": None, "role": "admin"}] def graph_data(node=""): c = db(); cur = c.cursor() cur.execute("select max(r.id) from audit.runs r where exists(select 1 from audit.capabilities c where c.run_id=r.id)") rid = cur.fetchone()[0] cur.execute("select count(*) from audit.entities where run_id=%s", (rid,)); nodes = cur.fetchone()[0] cur.execute("select count(*) from audit.links where run_id=%s", (rid,)); edges = cur.fetchone()[0] node = str(node or "").strip() if node: cur.execute("""select src,dst,kind,evidence from audit.links where run_id=%s and (src=%s or dst=%s) order by id limit 120""", (rid, node, node)) else: cur.execute("""select src,dst,kind,evidence from audit.links where run_id=%s order by id limit 120""", (rid,)) links = [{"src": r[0], "dst": r[1], "kind": r[2], "evidence": r[3]} for r in cur.fetchall()] cur.execute("""select kind,name,status from audit.entities where run_id=%s and (%s='' or name=%s or kind=%s) order by kind,name limit 120""", (rid, node, node, node)) ents = [{"kind": r[0], "name": r[1], "status": r[2]} for r in cur.fetchall()] c.close() return {"ok": True, "node": node, "nodes_total": nodes, "edges_total": edges, "nodes": ents, "links": links} def diff_data(frm=None, to=None): c = db(); cur = c.cursor() cur.execute("select id from audit.runs order by id desc limit 2") ids = [x[0] for x in cur.fetchall()] a = int(frm) if frm else (ids[1] if len(ids) > 1 else None) b = int(to) if to else (ids[0] if ids else None) if not a or not b: c.close(); return {"ok": False, "error": "need two runs"} def rows(run): cur.execute("select title,severity,status,owner,evidence from audit.findings where run_id=%s", (run,)) return {r[0]: {"severity": r[1], "status": r[2], "owner": r[3], "evidence": r[4]} for r in cur.fetchall()} A, B = rows(a), rows(b) new = [{"title": k, **B[k]} for k in sorted(set(B) - set(A))] resolved = [{"title": k, **A[k]} for k in sorted(set(A) - set(B))] changed = [] for k in sorted(set(A) & set(B)): delta = {f: [A[k].get(f), B[k].get(f)] for f in ("severity", "status", "owner") if A[k].get(f) != B[k].get(f)} if delta: changed.append({"title": k, "changes": delta}) c.close() return {"ok": True, "from": a, "to": b, "new": new, "resolved": resolved, "changed": changed, "counts": {"from": len(A), "to": len(B), "new": len(new), "resolved": len(resolved), "changed": len(changed)}} def api_data(): c = db(); cur = c.cursor() cur.execute("select id,started_at,finished_at,status,summary from audit.runs r where exists(select 1 from audit.capabilities c where c.run_id=r.id) order by id desc limit 1") r = cur.fetchone() if not r: c.close(); return {"ok": False, "error": "audit run not found"} rid, started, finished, status, summary = r out = {"ok": True, "id": rid, "started_at": str(started), "finished_at": str(finished), "status": status, "summary": summary or {}} def q(sql): cur.execute(sql) return [dict(zip([d[0] for d in cur.description], row)) for row in cur.fetchall()] out["findings"] = q("select id,severity,area,title,evidence,recommendation,owner,status,gitea_issue_url,gitea_issue_number from audit.findings where run_id=%d order by case severity when 'high' then 1 when 'medium' then 2 else 3 end,id" % rid) out["capabilities"] = q("select key,title,maturity,automation,leverage,criticality,gaps from audit.capabilities where run_id=%d order by criticality desc,key" % rid) out["opportunities"] = q("select title,capability,impact,effort,risk,hypothesis,first_step,evidence,source from audit.opportunities where run_id=%d order by impact desc,effort asc" % rid) out["arena"] = q("select title,capability,voices,impact,effort,risk,score,evidence,hypothesis,first_step from audit.arena_items where selected and arena_run_id=(select max(id) from audit.arena_runs where status='done') order by score desc") out["decisions"] = q("select id,finding_id,title,rationale,alternatives,owner,status,review_at,created_at,gitea_issue_url,gitea_issue_number from audit.decisions order by id desc") out["experiments"] = q("select id,decision_id,title,hypothesis,metric,baseline,target,status,result,verification,verify_run_id,started_at,finished_at from audit.experiments order by id desc") out["sprint"] = q("select code,phase,seq,title,detail,owner,status,requires_user,user_action,evidence,source,gitea_issue,gate,updated_at,closed_at from audit.sprint_items order by phase,seq") out["sprint_comments"] = q("select code,count(*) as n from audit.sprint_comments group by code") f = out["findings"]; d = out["decisions"]; e = out["experiments"] out["semantic"] = q("""select distinct on (name) name,status,ok,latency_ms,error,checked_at from audit.semantic_checks order by name,checked_at desc""") out["owners"] = identity_owners() out["metrics"] = { "findings": len(f), "owned": sum(1 for x in f if x.get("owner")), "open": sum(1 for x in f if x.get("status") not in ("fixed", "wontfix")), "fixed": sum(1 for x in f if x.get("status") == "fixed"), "decisions": len(d), "experiments": len(e), "experiments_done": sum(1 for x in e if x.get("status") == "done"), "gitea_issues": sum(1 for x in f if x.get("gitea_issue_url")), "sprint": len(out["sprint"]), "sprint_done": sum(1 for x in out["sprint"] if x.get("status") == "done"), "sprint_user": sum(1 for x in out["sprint"] if x.get("requires_user") and x.get("status") != "done"), } try: out["diff"] = diff_data() except Exception as e: out["diff"] = {"ok": False, "error": str(e)[:200]} c.close() return out def bundle(): d = api_data() d["schema"] = "audit360/v1" d["generated_at"] = datetime.now(timezone.utc).isoformat() d["agent_packet"] = { "purpose": "Manual multi-model audit: feed this packet to any agent/model. Facts are evidence-based.", "instructions": "Do not invent services. Return opportunities/risks with evidence. Preserve IDs.", "facts": (d.get("summary") or {}).get("facts", {}), "capabilities": d.get("capabilities", []), "findings": d.get("findings", []), "opportunities": d.get("opportunities", []), "arena": d.get("arena", []), } return d def publish_file(path, content, message): data = base64.b64encode(content).decode() body = {"message": message, "content": data, "branch": "main"} try: old = gitea("GET", "/repos/%s/contents/%s" % (GITEA_REPO, path)) if old.get("sha"): body["sha"] = old["sha"] except Exception: pass res = gitea("PUT", "/repos/%s/contents/%s" % (GITEA_REPO, path), body) return {"path": path, "url": (res.get("content") or {}).get("html_url"), "sha": (res.get("content") or {}).get("sha")} def publish_gitea(): d = bundle() raw = json.dumps(d, ensure_ascii=False, indent=2, default=str).encode() out = [publish_file("audit-360.json", raw, "Audit 360: JSON snapshot")] md = Path("/root/buryan-infra/ops/audit/reports/AUDIT-360-%s.md" % d.get("id")) if md.exists(): out.append(publish_file("AUDIT-360.md", md.read_bytes(), "Audit 360: report")) return {"ok": True, "files": out} def export_markdown(): d = bundle() lines = ["# Audit 360 export", "", "Generated: %s" % d.get("generated_at"), ""] lines += ["## Findings", ""] for x in d.get("findings") or []: lines.append("- [%s] %s — `%s`" % (x.get("severity"), x.get("title"), x.get("evidence") or "")) lines += ["", "## Capabilities", ""] for x in d.get("capabilities") or []: lines.append("- %s: maturity %s, leverage %s, criticality %s. %s" % (x.get("title"), x.get("maturity"), x.get("leverage"), x.get("criticality"), x.get("gaps") or "")) lines += ["", "## Opportunities", ""] for x in d.get("opportunities") or []: lines.append("- %s (I%s/E%s/R%s): %s" % (x.get("title"), x.get("impact"), x.get("effort"), x.get("risk"), x.get("hypothesis") or "")) lines += ["", "## Arena", ""] for x in d.get("arena") or []: lines.append("- %s [%s] score %s" % (x.get("title"), x.get("voices"), x.get("score"))) return "\n".join(lines).encode() HTML = """Audit 360 — Buryans Hub

Audit 360 Buryans Hub

Скачать JSON · Скачать Markdown ·
загрузка…
""" class H(BaseHTTPRequestHandler): def _allowed(self): user = (self.headers.get("X-Audit-User") or self.headers.get("X-Audit-User-Name") or self.headers.get("X-Auth-Request-Email") or "").strip().lower() gateway = self.headers.get("X-Audit-Gateway") == "1" if not user and not gateway and self.client_address[0] in ("127.0.0.1", "::1"): return True return user in ALLOWED_EMAILS def _deny(self): print("AUDIT_DENY path=%s user=%r name=%r client=%s" % ( self.path, self.headers.get("X-Audit-User"), self.headers.get("X-Audit-User-Name"), self.client_address[0]), flush=True) data = b"forbidden: Audit 360 access is restricted" self.send_response(403) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers(); self.wfile.write(data) def do_GET(self): if not self._allowed(): return self._deny() if self.path.startswith("/api/graph"): q = parse_qs(urlparse(self.path).query) data = json.dumps(graph_data(q.get("node", [""])[0]), ensure_ascii=False, default=str).encode() self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return if self.path.startswith("/api/diff"): q = parse_qs(urlparse(self.path).query) data = json.dumps(diff_data(q.get("from", [None])[0], q.get("to", [None])[0]), ensure_ascii=False, default=str).encode() self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return if self.path.startswith("/api/export.md"): data = export_markdown() self.send_response(200); self.send_header("Content-Type", "text/markdown; charset=utf-8") self.send_header("Content-Disposition", "attachment; filename=AUDIT-360.md") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return if self.path.startswith("/api/export"): data = json.dumps(bundle(), ensure_ascii=False, indent=2, default=str).encode() self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Disposition", "attachment; filename=audit-360.json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return if self.path.startswith("/api/audit"): try: data = json.dumps(api_data(), ensure_ascii=False, default=str).encode() self.send_response(200) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers(); self.wfile.write(data) except Exception as e: data = json.dumps({"ok": False, "error": str(e)[:300]}, ensure_ascii=False).encode() self.send_response(500); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(data) return if self.path.startswith("/health"): self.send_response(200); self.end_headers(); self.wfile.write(b"ok"); return data = HTML.encode() self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) def do_POST(self): if not self._allowed(): return self._deny() try: n = int(self.headers.get("Content-Length") or 0) p = json.loads(self.rfile.read(n).decode() or "{}") c = db(); cur = c.cursor() if self.path == "/api/gitea/finding": res = gitea_issue_for_finding(int(p.get("id"))) c.close() data = json.dumps(res, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/gitea/decision": res = gitea_issue_for_decision(int(p.get("id"))) c.close() data = json.dumps(res, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/decision/status": cur.execute("update audit.decisions set status=%s,review_at=coalesce(%s,review_at),updated_at=now() where id=%s", (p.get("status") or "proposed", p.get("review_at") or None, int(p.get("id")))) elif self.path == "/api/gitea/assign": res = gitea_assign_for_finding(int(p.get("id"))) c.close() data = json.dumps(res, ensure_ascii=False).encode() self.send_response(200 if res.get("ok") else 400); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/gitea/publish": res = publish_gitea() c.close() data = json.dumps(res, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/gitea/sync": res = gitea_sync() c.close() data = json.dumps(res, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/sprint/status": code = str(p.get("code") or "").strip() status = str(p.get("status") or "open") comment = str(p.get("comment") or "").strip() if not code: raise RuntimeError("sprint code required") if status == "done" and not comment: raise RuntimeError("comment required to close sprint item") cur.execute("""update audit.sprint_items set status=%s,evidence=coalesce(%s,evidence), user_action=coalesce(%s,user_action),requires_user=coalesce(%s,requires_user), updated_at=now(),closed_at=case when %s='done' then now() else null end where code=%s""", (status, p.get("evidence") or None, p.get("user_action") or None, p.get("requires_user"), status, code)) if cur.rowcount == 0: raise RuntimeError("sprint item not found") if comment: cur.execute("insert into audit.sprint_comments(code,author,body) values(%s,%s,%s)", (code, p.get("author") or "agent", comment)) c.commit(); c.close() data = json.dumps({"ok": True, "code": code, "status": status}, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/sprint/comment": code = str(p.get("code") or "").strip() body = str(p.get("body") or "").strip() if not code or not body: raise RuntimeError("code and body required") cur.execute("insert into audit.sprint_comments(code,author,body) values(%s,%s,%s)", (code, p.get("author") or "agent", body)) cur.execute("update audit.sprint_items set updated_at=now() where code=%s", (code,)) c.commit(); c.close() data = json.dumps({"ok": True}, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) return if self.path == "/api/finding": cur.execute("update audit.findings set owner=%s,status=%s,updated_at=now() where id=%s", (p.get("owner") or None, p.get("status") or "open", int(p.get("id")))) elif self.path == "/api/decision": cur.execute("""insert into audit.decisions(run_id,finding_id,title,rationale,alternatives,owner,status,review_at) values(1,%s,%s,%s,%s,%s,%s,%s) returning id""", (p.get("finding_id"), p.get("title") or "Решение", p.get("rationale") or "", p.get("alternatives") or "", p.get("owner") or "", p.get("status") or "proposed", p.get("review_at") or None)) did = cur.fetchone()[0] elif self.path == "/api/experiment": cur.execute("""insert into audit.experiments(decision_id,title,hypothesis,metric,baseline,target,status) values(%s,%s,%s,%s,%s,%s,%s) returning id""", (p.get("decision_id"), p.get("title") or "Эксперимент", p.get("hypothesis") or "", p.get("metric") or "", p.get("baseline") or "", p.get("target") or "", p.get("status") or "planned")) did = cur.fetchone()[0] elif self.path == "/api/experiment/status": cur.execute("""update audit.experiments set status=%s,result=%s, started_at=coalesce(started_at,case when %s='running' then now() end), finished_at=case when %s in ('done','failed') then now() else finished_at end where id=%s""", (p.get("status") or "planned", p.get("result") or "", p.get("status"), p.get("status"), int(p.get("id")))) else: raise RuntimeError("unknown endpoint") c.commit(); c.close() data = json.dumps({"ok": True}, ensure_ascii=False).encode() self.send_response(200); self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data) except Exception as e: data = json.dumps({"ok": False, "error": str(e)[:300]}, ensure_ascii=False).encode() self.send_response(500); self.send_header("Content-Type", "application/json") self.end_headers(); self.wfile.write(data) def log_message(self, fmt, *args): pass if __name__ == "__main__": ThreadingHTTPServer((HOST, PORT), H).serve_forever()