68 lines
3.3 KiB
Python
68 lines
3.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Weekly Audit 360 diff -> Gitea weekly/AUDIT-WEEKLY-<date>.md."""
|
|
import base64
|
|
import json
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
import psycopg2
|
|
|
|
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
|
|
TOKEN = Path("/root/.gitea-admin-token").read_text().strip()
|
|
REPO = "infrastructure/buryan-audit"
|
|
GITEA = "http://192.168.1.140:3000"
|
|
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
|
cur = conn.cursor()
|
|
cur.execute("select id,started_at from audit.runs where started_at >= now()-interval '7 days' order by id")
|
|
runs = cur.fetchall()
|
|
if len(runs) < 2:
|
|
cur.execute("select id,started_at from audit.runs order by id desc limit 2")
|
|
runs = list(reversed(cur.fetchall()))
|
|
if not runs:
|
|
raise SystemExit("no audit runs")
|
|
frm, to = runs[0][0], runs[-1][0]
|
|
|
|
def findings(rid):
|
|
cur.execute("select title,severity,status,owner from audit.findings where run_id=%s", (rid,))
|
|
return {r[0]: {"severity": r[1], "status": r[2], "owner": r[3]} for r in cur.fetchall()}
|
|
A, B = findings(frm), findings(to)
|
|
new = sorted(set(B) - set(A))
|
|
resolved = sorted(set(A) - set(B))
|
|
changed = []
|
|
for k in sorted(set(A) & set(B)):
|
|
d = {f: [A[k][f], B[k][f]] for f in ("severity", "status", "owner") if A[k][f] != B[k][f]}
|
|
if d:
|
|
changed.append((k, d))
|
|
cur.execute("select count(*) from audit.decisions")
|
|
decisions = cur.fetchone()[0]
|
|
cur.execute("select count(*),count(*) filter (where verification='confirmed') from audit.experiments")
|
|
exp_total, exp_ok = cur.fetchone()
|
|
|
|
lines = ["# Audit 360 weekly", "", "Period: run %s → run %s" % (frm, to),
|
|
"Generated: %s" % datetime.now(timezone.utc).isoformat(), "",
|
|
"## Summary", "", "| Metric | Value |", "|---|---:|",
|
|
"| New findings | %d |" % len(new), "| Resolved | %d |" % len(resolved),
|
|
"| Changed | %d |" % len(changed), "| Decisions | %d |" % decisions,
|
|
"| Experiments | %d |" % exp_total, "| Confirmed experiments | %d |" % exp_ok,
|
|
"", "## New", ""]
|
|
lines += ["- [%s] %s" % (B[k]["severity"], k) for k in new] or ["—"]
|
|
lines += ["", "## Resolved", ""] + (["- %s" % k for k in resolved] or ["—"])
|
|
lines += ["", "## Changed", ""] + (["- %s: %s" % (k, json.dumps(d, ensure_ascii=False)) for k, d in changed] or ["—"])
|
|
md = "\n".join(lines).encode()
|
|
path = "weekly/AUDIT-WEEKLY-%s.md" % datetime.now().strftime("%Y-%m-%d")
|
|
body = {"message": "Audit 360 weekly %s" % datetime.now().strftime("%Y-%m-%d"), "content": base64.b64encode(md).decode(), "branch": "main"}
|
|
try:
|
|
req = urllib.request.Request(GITEA + "/api/v1/repos/%s/contents/%s" % (REPO, path),
|
|
headers={"Authorization": "token " + TOKEN}, method="GET")
|
|
with urllib.request.urlopen(req, timeout=15) as r:
|
|
old = json.loads(r.read().decode())
|
|
body["sha"] = old.get("sha")
|
|
except Exception:
|
|
pass
|
|
req = urllib.request.Request(GITEA + "/api/v1/repos/%s/contents/%s" % (REPO, path),
|
|
data=json.dumps(body).encode(), headers={"Authorization": "token " + TOKEN, "Content-Type": "application/json"}, method="PUT")
|
|
with urllib.request.urlopen(req, timeout=20) as r:
|
|
res = json.loads(r.read().decode())
|
|
print("weekly", frm, "->", to, "new", len(new), "resolved", len(resolved), "url", (res.get("content") or {}).get("html_url"))
|
|
conn.close()
|