diff options
Diffstat (limited to 'plugins/code-modernization/scripts')
| -rw-r--r-- | plugins/code-modernization/scripts/build_report.py | 529 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/compare.py | 352 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/make_shards.py | 100 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_report_tools.py | 779 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_rules_tools.py | 61 |
5 files changed, 1794 insertions, 27 deletions
diff --git a/plugins/code-modernization/scripts/build_report.py b/plugins/code-modernization/scripts/build_report.py new file mode 100644 index 00000000..c6c58c66 --- /dev/null +++ b/plugins/code-modernization/scripts/build_report.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +"""Build one self-contained HTML report from a system's modernization artifacts. + + python3 build_report.py <system> [--workspace DIR] [--out FILE] + +Reads whatever exists under <workspace>/analysis/<system>/ and <workspace>/modernized/ (every file is +optional; a missing or malformed one is reported in the page, never an error) and writes +<workspace>/analysis/<system>/REPORT.html by default. Standard library only. Exit 0; 1 when nothing +at all was found; 2 for a system name that is not a folder name. + +The artifacts come from untrusted code, so every byte is treated as hostile: text travels only as +escaped JSON inside <script type="application/json"> blocks, the page builds its DOM with +textContent, a Content-Security-Policy pins the only scripts that may run (by hash) and blocks every +external request, and files named *.local.*, SECRETS* or reached through a symlink are never read. +""" +import argparse +import base64 +import collections +import datetime +import hashlib +import json +import os +import re +import stat +import sys +import tempfile +from urllib.parse import quote + +HERE = os.path.dirname(os.path.abspath(__file__)) +ASSETS = os.path.join(os.path.dirname(HERE), "assets") +FILE_CAP, TOTAL_CAP, LINE_CAP, MAX_CASES, MAX_NOTES = 3 << 20, 6 << 20, 20000, 2000, 100 +NOTE_NAMES = ("TRANSFORMATION_NOTES.md", "UPLIFT_NOTES.md", "README.md") +STEPS = [("preflight", "Preflight"), ("assess", "Assess"), ("map", "Map"), ("rules", "Rules"), + ("brief", "Brief"), ("build", "Build"), ("harden", "Harden")] +TITLES = [("overview", "Overview"), ("assessment", "Assessment"), ("diagrams", "Diagrams"), + ("rules", "Business rules"), ("brief", "Brief"), ("security", "Security"), + ("delta", "Delta catalog & baseline"), ("spec", "Spec & architecture"), + ("build", "Build notes"), ("equivalence", "Equivalence")] +DOCS = [("overview", ["PREFLIGHT.md"]), ("assessment", ["ASSESSMENT.md"]), + ("rules", ["BUSINESS_RULES.md", "RULE_REVIEWS.md", "DATA_OBJECTS.md"]), ("brief", ["MODERNIZATION_BRIEF.md"]), + ("security", ["SECURITY_FINDINGS.md"]), ("delta", ["DELTA_CATALOG.md", "BASELINE.md", "PLAYBOOK.md"]), + ("spec", ["AI_NATIVE_SPEC.md", "REIMAGINED_ARCHITECTURE.md"])] +MERMAID_FENCE = re.compile(r"(?m)^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b") +ID = r"[A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*-\d+[a-z]?" +CARD = re.compile(r"^(#{3,4})[ \t]+[*`]*(" + ID + r")[*`]*(?:[ \t]*[·:\-–—][ \t]*(.*?))?[ \t]*#*[ \t]*$") +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})") +CITE = re.compile(r"[A-Za-z0-9_][\w./+-]*\.[A-Za-z][A-Za-z0-9]{0,7}:\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*") +DAY = "%Y-%m-%d" + + +def num(n): + return "{:,}".format(n) + + +def utc_day(ts): + return datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).strftime(DAY) + + +# ---------------------------------------------------------------- reading files safely +class Source: + """Everything read from the workspace goes through here: caps, notes, and refusals.""" + + def __init__(self, workspace, system): + self.root, self.system, self.used = os.path.realpath(workspace), system, 0 + self.adir, self.mdir = os.path.join(workspace, "analysis", system), os.path.join(workspace, "modernized") + self.notes, self.found = [], [] + + def read(self, path, label): + """Cleaned text of a regular file inside the workspace; None when absent or refused.""" + name = os.path.basename(path).lower() + if ".local." in name or name.startswith("secrets"): + return None + try: + st = os.lstat(path) + except OSError: + return None + if not stat.S_ISREG(st.st_mode) or os.path.commonpath([self.root, os.path.realpath(path)]) != self.root: + self.notes.append("%s is a link or not a regular file inside the workspace, so it was not read." % label) + return None + self.found.append((label, st.st_size, utc_day(st.st_mtime))) + try: + with open(path, "rb") as fh: + raw = fh.read(FILE_CAP + 1) + except OSError as err: + self.notes.append("%s could not be read (%s)." % (label, err.__class__.__name__)) + return "" + text = raw[:FILE_CAP].decode("utf-8", "replace").lstrip("\N{ZERO WIDTH NO-BREAK SPACE}").replace("\r\n", "\n").replace("\r", "\n") + lines, shortened = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "\N{REPLACEMENT CHARACTER}", text).split("\n"), 0 + for i, line in enumerate(lines): + if len(line) > LINE_CAP: + lines[i] = "%s ... [%s more characters not shown]" % (line[:LINE_CAP], num(len(line) - LINE_CAP)) + shortened += 1 + text = "\n".join(lines) + if shortened: + self.notes.append("%s: %d line(s) longer than %s characters were shortened." % (label, shortened, num(LINE_CAP))) + room = TOTAL_CAP - self.used + if len(raw) > FILE_CAP or len(text.encode("utf-8")) > room: + text = text.encode("utf-8")[:max(0, min(FILE_CAP, room))].decode("utf-8", "ignore") + text = text[:text.rfind("\n")] if "\n" in text else "" + self.notes.append("%s: %s (report size limit; the file is %s KB)." % ( + label, "only the first %s KB is included" % num(len(text.encode("utf-8")) >> 10) if text else "left out", + num(max(1, st.st_size >> 10)))) + self.used += len(text.encode("utf-8")) + return text + + def json(self, path, label): + """-> (parsed value or None, whether the file exists).""" + text = self.read(path, label) + if text is None: + return None, False + try: + return json.loads(text), True + except ValueError as err: + self.notes.append("%s could not be parsed as JSON (%s)." % (label, str(err)[:80])) + return None, True + + +# ---------------------------------------------------------------- what the markdown says +def cells(line): + s = line.strip() + s = s[1:] if s.startswith("|") else s + s = s[:-1] if s.endswith("|") and not s.endswith("\\|") else s + return [re.sub(r"[*`]", "", c).strip() for c in re.split(r"(?<!\\)\|", s)] + + +def tables(text): + """(nearest heading, header cells, rows) for every pipe table in a markdown text.""" + lines, head = text.split("\n"), "" + for i, line in enumerate(lines): + m = re.match(r"#{1,6}\s+(.*)", line) + head = m.group(1) if m else head + if "|" in line and i + 1 < len(lines) and "|" in lines[i + 1] and re.fullmatch(r"\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*", lines[i + 1]): + rows, j = [], i + 2 + while j < len(lines) and "|" in lines[j] and lines[j].strip(): + rows.append(cells(lines[j])) + j += 1 + yield head, cells(line), rows + + +def field(body, name): + m = re.search(r"(?im)^[ \t>*-]*\**" + name + r"\**[ \t]*:[ \t]*\**[ \t]*(.+?)[ \t]*$", body) + return m.group(1) if m else "" + + +def parse_rules(text): + """Split a rules file into markdown chunks and rule cards. With no card headings it is one chunk.""" + blocks, buf, card, fence = [], [], None, "" + + def flush(): + nonlocal buf, card + if card is not None: + blocks.append({"k": "rule", **finish(card, "\n".join(buf))}) + elif "".join(buf).strip(): + blocks.append({"k": "md", "text": "\n".join(buf)}) + buf, card = [], None + + for line in text.split("\n"): + f = FENCE.match(line) + if fence: + if f and f.group(1)[0] == fence[0] and len(f.group(1)) >= len(fence) and not line.strip().strip(fence[0]): + fence = "" + elif f: + fence = f.group(1) + else: + m, h = CARD.match(line), re.match(r"(#{1,6})\s", line) + if m or (h and card is not None and len(h.group(1)) <= len(card[0])): + flush() + if m: + card = (m.group(1), m.group(2), (m.group(3) or "").strip(), re.sub(r"^#+\s*", "", line).strip()) + continue + buf.append(line) + flush() + return blocks + + +def finish(card, body): + _, rid, title, heading = card + head = next((ln for ln in body.split("\n") if ln.strip()), "") + prio = re.search(r"\b(P\d)\b", field(body, "Priority")) or re.match(r"(P\d)-", rid) or re.match(r"[ `*]*(P\d)[ `*]*(?:·|$)", head) + conf = re.search(r"(?i)\b(high|medium|low)\b", field(body, "Confidence")) or re.search(r"(?i)confidence:?\s*(high|medium|low)", head) + source, defect, cat = field(body, "Source") or head, field(body, "Suspected defect"), field(body, "Category") + body = re.sub(r"(?im)^[ \t>*-]*\**(?:Priority|Category|Source)\**[ \t]*:.*\n?", "", body).strip("\n") + return {"id": rid, "heading": heading[:300], "title": title[:300], "p": prio.group(1).upper() if prio else "", + "cat": re.sub(r"\s+", " ", cat)[:60], "conf": conf.group(1).capitalize() if conf else "", + "cites": list(dict.fromkeys(CITE.findall(source)))[:12], + "defect": bool(defect) and not re.match(r"(?i)\W*(none|n/?a|no|nil)\W*$", defect), "body": body} + + +def rule_facts(text, cards, reviews): + """Priority tally: from each card, else from the index-table row that carries its id.""" + rated = {} + for _, _, rows in tables(text): + for row in rows: + m, p = re.search(ID, row[0]) if row else None, next((c for c in row if re.fullmatch(r"P\d", c)), None) + if m and p: + rated.setdefault(m.group(0), p) + counts = collections.Counter(c["p"] or rated.get(c["id"], "") for c in cards) + unrated = counts.pop("", 0) + out = {"total": len(cards), "byPriority": dict(sorted(counts.items())), "unrated": unrated, "defects": sum(1 for c in cards if c["defect"])} + if reviews: + out["reviews"] = dict(collections.Counter(str(v.get("verdict", "?"))[:20] for v in reviews.values() if isinstance(v, dict))) + return out + + +def security_facts(text): + """Severity tally from the findings table; a summary scorecard only when there is no findings table.""" + finds, score = collections.Counter(), collections.Counter() + for head, header, rows in tables(text): + low = [h.lower() for h in header] + sev = next((i for i, h in enumerate(low) if "severity" in h), None) + if sev is None or any(re.search(r"package|installed|fixed", h) for h in low) or \ + re.search(r"coverage|not judged|unverified|dependenc|cve|patch review|remediation", head, re.I): + continue + count = next((i for i, h in enumerate(low) if h in ("count", "total", "n", "#", "findings")), None) + for row in rows: + m = re.match(r"(?i)(critical|high|medium|low)\b", row[sev] if sev < len(row) else "") + if m and count is not None and len(header) <= 3 and count < len(row) and row[count].isdigit(): + score[m.group(1).capitalize()] += int(row[count]) + elif m: + finds[m.group(1).capitalize()] += 1 + return dict(finds or score) or None + + +def baseline_facts(text): + """Pass/fail/skip counts from a per-test result column, or from a sentence like '12 passed, 1 failed'.""" + words, counts = {"pass": "pass", "passed": "pass", "passing": "pass", "ok": "pass", "fail": "fail", "failed": "fail", + "failing": "fail", "skip": "skip", "skipped": "skip", "ignored": "skip"}, collections.Counter() + for _, header, rows in tables(text): + col = next((i for i, h in enumerate(header) if re.search(r"result|status|outcome|verdict|passed", h, re.I)), None) + for row in rows if col is not None else []: + if col < len(row) and row[col].lower() in words: + counts[words[row[col].lower()]] += 1 + for key, pat in (() if counts else (("pass", r"(\d+)\s+(?:tests?\s+|cases?\s+)?(?:passed|passing)|(?:passed|passing)\s*[:=]\s*(\d+)"), + ("fail", r"(\d+)\s+(?:tests?\s+|cases?\s+)?(?:failed|failing)|(?:failed|failing)\s*[:=]\s*(\d+)"))): + m = re.search(r"(?i)" + pat, text) + if m: + counts[key] = int(m.group(1) or m.group(2)) + target_only = bool(re.search(r"(?im)^\W*target-only:", text)) + return {**counts, "targetOnly": target_only} if counts or target_only else None + + +def topology_facts(obj): + nodes = [] + + def walk(n, depth): + if isinstance(n, dict) and depth < 12: + nodes.append(n) + for c in n.get("children") or []: + walk(c, depth + 1) + + if isinstance(obj, dict): + walk(obj.get("root"), 0) + mods = [n for n in nodes if n.get("kind") == "module"] or [n for n in nodes if not n.get("children") and n.get("file") and isinstance(n.get("loc"), int)] + if not mods: + return None + seen = obj.get("observations") + return {"modules": len(mods), "loc": sum(n["loc"] for n in mods if isinstance(n.get("loc"), int) and n["loc"] > 0), + "languages": sorted({str(n["language"])[:20] for n in mods if isinstance(n.get("language"), str)})[:6], + "edges": len(obj["edges"]) if isinstance(obj.get("edges"), list) else None, + "observations": [str(o)[:600] for o in seen[:12]] if isinstance(seen, list) else []} + + +VERDICTS = ("same", "differs", "differs-approved", "missing") + + +def endpoint(o): + return {k: str(o.get(k) or "")[:300] for k in ("label", "command")} if isinstance(o, dict) else {"label": "", "command": ""} + + +def equivalence_view(obj): + """Tally the verdicts from the case list itself: the file's own totals and wording are never trusted.""" + if not isinstance(obj, dict) or not isinstance(obj.get("cases"), list): + return None + problems, tally, rows = [], collections.Counter(), [] + for c in (c for c in obj["cases"] if isinstance(c, dict)): + s = lambda k, n=300: str(c.get(k) or "")[:n] # noqa: E731 + masked = [str(m)[:200] for m in c["masked"][:20]] if isinstance(c.get("masked"), list) else [] + ld, nd = (d if re.fullmatch(r"[0-9a-f]{64}", d) else "" for d in (s("legacySha256", 80), s("newSha256", 80))) + v = s("verdict", 30) if s("verdict", 30) in VERDICTS else "unknown" + if v == "same" and (c.get("firstDiff") or (not masked and ld and nd and ld != nd)) or (v == "differs-approved" and not s("approvedDifference").strip()): + v = "inconsistent" + tally[v] += 1 + row = {"id": s("id", 80), "title": s("title"), "verdict": v, "reason": s("reason", 500), "legacyPath": s("legacyPath"), "newPath": s("newPath"), + "legacySha256": s("legacySha256", 80), "newSha256": s("newSha256", 80), "masked": masked, + "approvedDifference": s("approvedDifference", 500), "note": s("note", 500), "empty": c.get("empty") is True} + if isinstance(c.get("firstDiff"), dict): + fd = c["firstDiff"] + row["firstDiff"] = {k: fd[k] if isinstance(fd.get(k), int) else 0 for k in ("offset", "line", "at")} + row["firstDiff"].update({k: str(fd.get(k) or "")[:120] for k in ("legacy", "new")}) + if isinstance(c.get("bytes"), dict) and isinstance(c.get("maskedBytes"), dict): + row["sizes"] = {k: [c["bytes"].get(k), c["maskedBytes"].get(k)] for k in ("legacy", "new") if isinstance(c["bytes"].get(k), int) and isinstance(c["maskedBytes"].get(k), int)} + if v == "inconsistent": + problems.append("Case %s: the recorded verdict contradicts its own evidence, so it counts as a failure." % row["id"]) + rows.append(row) + ran = ("same", "differs", "differs-approved", "inconsistent") + executed, bad = sum(tally[k] for k in ran), tally["differs"] + tally["missing"] + tally["inconsistent"] + tally["unknown"] + sc = obj["selfCheck"] if isinstance(obj.get("selfCheck"), dict) else None + check = {"passed": sc["passed"] if sc and isinstance(sc.get("passed"), bool) else None, "detail": str(sc.get("detail") or "")[:300] if sc else "", "recorded": sc is not None} + if not sc: + problems.append("No self-check is recorded, so this file may not have been written by scripts/compare.py.") + declared = obj["totals"] if isinstance(obj.get("totals"), dict) else {} + if declared and (declared.get("cases") != len(rows) or declared.get("executed") != executed): + problems.append("The totals stored in the file disagree with its case list; the case list was used.") + empty = executed > 0 and all(r["empty"] for r in rows if r["verdict"] in ran) + if executed == 0: + headline = "Equivalence not proven: no case was executed." + elif empty: + headline = "Equivalence not proven: every compared output was empty." + elif bad or check["passed"] is False: + why = ["%d %s" % (tally[k], w) for k, w in (("differs", "differing"), ("missing", "missing"), ("inconsistent", "contradictory"), ("unknown", "unrecognised")) if tally[k]] + headline = "Equivalence not proven: %s%s (%d of %d cases executed)." % ( + ", ".join(why) or "no case failed", "; the comparator's self-check failed" if check["passed"] is False else "", executed, len(rows)) + else: + approved = tally["differs-approved"] + headline = "Outputs match on all %d executed cases%s." % (executed, " (%d with a difference a person approved)" % approved if approved else "") + return {"state": "red" if (executed == 0 or empty or bad or check["passed"] is False) else "green", "headline": headline, "problems": problems, + "selfCheck": check, "generated": str(obj.get("generated") or "")[:40], "tally": {"cases": len(rows), "executed": executed, **dict(tally)}, + "legacy": endpoint(obj.get("legacy")), "new": endpoint(obj.get("new")), "cases": rows[:MAX_CASES], "cut": max(0, len(rows) - MAX_CASES)} + + +# ---------------------------------------------------------------- assembling the report +def nonempty_dir(p): + try: + return os.path.isdir(p) and bool(os.listdir(p)) + except OSError: + return False + + +def newest(paths): + """(mtime, path) of the newest existing file, or non-empty folder, among `paths`.""" + best = None + for p in paths: + try: + if os.path.islink(p) or (os.path.isdir(p) and not nonempty_dir(p)): + continue + times = [os.stat(p).st_mtime] + ([e.stat().st_mtime for e in os.scandir(p)] if os.path.isdir(p) else []) + except OSError: + continue + best = max(best, (max(times), p)) if best else (max(times), p) + return best + + +def modernized_docs(src): + """(label, text) for the notes files of modernized/<system>{,-uplifted,-reimagined}, one folder level down.""" + out, skipped = [], 0 + for suffix in ("", "-uplifted", "-reimagined"): + base = os.path.join(src.mdir, src.system + suffix) + try: + folders = [base] + sorted(e.path for e in os.scandir(base) if e.is_dir(follow_symlinks=False))[:200] + except OSError: + continue + for folder in folders: + for name in NOTE_NAMES: + path = os.path.join(folder, name) + label = os.path.relpath(path, src.mdir).replace(os.sep, "/") + if len(out) >= MAX_NOTES and os.path.lexists(path): + skipped += 1 + continue + text = src.read(path, "modernized/" + label) + if text is not None: + out.append((label, text)) + if skipped: + src.notes.append("%d more notes files under modernized/ are not included (limit %d)." % (skipped, MAX_NOTES)) + return out + + +def load_mermaid(src): + try: + with open(os.path.join(ASSETS, "vendor", "mermaid.min.js"), encoding="utf-8") as fh: + return fh.read().replace("</script", "<\\/script").replace("<!--", "<\\!--") + except OSError: + src.notes.append("The Mermaid library was not found next to the template, so diagrams are shown as source.") + return "" + + +def build(system, workspace, out=None): + """-> (html, section count, output path), or None when nothing was found.""" + src = Source(workspace, system) + out = os.path.abspath(out or os.path.join(src.adir, "REPORT.html")) + a = lambda name: os.path.join(src.adir, name) # noqa: E731 + parts, texts, docs = {k: [] for k, _ in TITLES}, [], {} + reviews, _ = src.json(a("RULE_REVIEWS.json"), "RULE_REVIEWS.json") + reviews = {k: v for k, v in reviews["reviews"].items() if isinstance(v, dict)} if isinstance(reviews, dict) and isinstance(reviews.get("reviews"), dict) else {} + glance = {"rules": None, "security": None, "baseline": None, "topology": None, "equivalence": None} + + for key, names in DOCS: + for name in names: + text = src.read(a(name), name) + if text is None: + continue + docs[name] = text + blocks = parse_rules(text) if name == "BUSINESS_RULES.md" else [] + cards = [b for b in blocks if b["k"] == "rule"] + if cards: + glance["rules"] = rule_facts(text, cards, reviews) + parts[key].append({"t": "rules", "name": name, "blocks": blocks, "reviews": {k: str(v.get("verdict", ""))[:20] for k, v in reviews.items()}}) + else: + parts[key].append({"t": "md", "name": name, "text": text}) + texts += docs.values() + glance["security"] = security_facts(docs["SECURITY_FINDINGS.md"]) if "SECURITY_FINDINGS.md" in docs else None + glance["baseline"] = baseline_facts(docs["BASELINE.md"]) if "BASELINE.md" in docs else None + + topo, topo_seen = src.json(a("topology.json"), "topology.json") + t = glance["topology"] = topology_facts(topo) + try: + names = sorted(e.name for e in os.scandir(src.adir) if e.name.lower().endswith(".mmd")) + except OSError: + names = [] + figures = [{"name": n, "src": text} for n in names for text in [src.read(a(n), n)] if text is not None] + texts += [f["src"] for f in figures] + if t: + parts["diagrams"].append({"t": "facts", "items": [["Modules", num(t["modules"])], ["Lines of code", num(t["loc"])]] + ( + [["Dependencies", num(t["edges"])]] if t["edges"] is not None else []) + ([["Languages", ", ".join(t["languages"])]] if t["languages"] else [])}) + html_map = a("TOPOLOGY.html") + has_map = os.path.isfile(html_map) and not os.path.islink(html_map) + if has_map: + src.found.append(("TOPOLOGY.html", os.path.getsize(html_map), utc_day(os.path.getmtime(html_map)))) + try: + rel = quote(os.path.relpath(html_map, os.path.dirname(out)).replace(os.sep, "/"), safe="/") + parts["diagrams"].append({"t": "link", "href": rel, "text": "Open the interactive map (TOPOLOGY.html, kept as a separate file)"}) + except ValueError: + pass + if t and t["observations"]: + parts["diagrams"].append({"t": "list", "title": "What the map found", "items": t["observations"]}) + if figures: + parts["diagrams"].append({"t": "figures", "items": figures}) + + for label, text in modernized_docs(src): + texts.append(text) + parts["build"].append({"t": "md", "name": "modernized/" + label, "text": text}) + + eq, eq_seen = src.json(a("EQUIVALENCE.json"), "EQUIVALENCE.json") + if eq_seen: + view = equivalence_view(eq) + if view: + parts["equivalence"].append({"t": "equiv", "eq": view}) + glance["equivalence"] = {k: view[k] for k in ("state", "headline", "problems", "tally")} + else: + glance["equivalence"] = {"state": "red", "headline": "EQUIVALENCE.json could not be used, so equivalence is not proven.", "problems": [], "tally": None} + parts["equivalence"].append({"t": "p", "text": glance["equivalence"]["headline"]}) + + mods = [os.path.join(src.mdir, system + s) for s in ("", "-uplifted", "-reimagined")] + done = {"preflight": "PREFLIGHT.md" in docs, "assess": "ASSESSMENT.md" in docs, "rules": "BUSINESS_RULES.md" in docs, "brief": "MODERNIZATION_BRIEF.md" in docs, + "map": topo is not None or has_map or any(f["name"] != "ARCHITECTURE.mmd" for f in figures), "build": any(nonempty_dir(p) for p in mods), "harden": "SECURITY_FINDINGS.md" in docs} + glance["steps"] = [{"key": k, "label": label, "done": bool(done[k])} for k, label in STEPS] + tracks = {"rewrite": [mods[0]], "same-stack uplift": [a("DELTA_CATALOG.md"), a("PLAYBOOK.md"), mods[1]], "reimagine": [a("AI_NATIVE_SPEC.md"), a("REIMAGINED_ARCHITECTURE.md"), mods[2]]} + ranked = sorted(((newest(p), k) for k, p in tracks.items() if newest(p)), reverse=True) + glance["track"] = {"label": ranked[0][1], "why": "newest artifact: " + os.path.relpath(ranked[0][0][1], workspace).replace(os.sep, "/")} if ranked else None + if not src.found: + return None + + lib = load_mermaid(src) if figures or any(MERMAID_FENCE.search(x) for x in texts) else "" + parts["overview"].insert(0, {"t": "table", "head": ["Artifact", "Size", "Modified"], "rows": [[n, "%s KB" % num(s >> 10) if s >= 1024 else "%d B" % s, m] for n, s, m in sorted(src.found)]}) + if src.notes: + parts["overview"].insert(0, {"t": "list", "title": "Notes about this report", "items": src.notes}) + sections = [{"id": k, "title": title, "parts": parts[k]} for k, title in TITLES if parts[k]] + data = {"v": 1, "system": system[:200], "generated": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), "glance": glance, "sections": sections} + return render(data, lib), len(sections), out + + +def script_json(data): + """JSON that can sit inside a <script> element: no <, > or & appears in it, so </script> and <!-- cannot.""" + return json.dumps(data, ensure_ascii=True, separators=(",", ":")).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") + + +def render(data, lib): + with open(os.path.join(ASSETS, "report-template.html"), encoding="utf-8") as fh: + template = fh.read().replace("\r\n", "\n") + app = re.search(r'<script id="app">(.*?)</script>', template, re.S).group(1) + sha = lambda text: "'sha256-%s'" % base64.b64encode(hashlib.sha256(text.encode("utf-8")).digest()).decode() # noqa: E731 + policy = "default-src 'none'; script-src %s; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'" % " ".join([sha(app)] + ([sha(lib)] if lib else [])) + fill = {"CSP": policy, "DATA": script_json(data), "MERMAID": '<script id="mermaid-lib">%s</script>' % lib if lib else ""} + return re.sub(r"@@(CSP|DATA|MERMAID)@@", lambda m: fill[m.group(1)], template) + + +def write_atomic(path, data): + """Write `data` to a temp file beside `path`, then rename it over `path`. + Returns why it refused (a symlinked path or folder), or None once written.""" + folder = os.path.dirname(path) + for p in (path, folder): + if os.path.islink(p): + return "refusing to write through a symbolic link: %s" % p + os.makedirs(folder, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=folder, prefix=".report-", suffix=".tmp") + try: + with os.fdopen(fd, "wb") as fh: + fh.write(data) + umask = os.umask(0) + os.umask(umask) + os.chmod(tmp, 0o666 & ~umask) + os.replace(tmp, path) + except BaseException: + if os.path.lexists(tmp): + os.unlink(tmp) + raise + return None + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Build a self-contained HTML report from a system's modernization artifacts.") + ap.add_argument("system", help="the system's folder name under analysis/") + ap.add_argument("--workspace", default=".", help="the project root holding analysis/ and modernized/ (default: current folder)") + ap.add_argument("--out", help="where to write the report (default: <workspace>/analysis/<system>/REPORT.html)") + args = ap.parse_args(argv) + if not args.system or args.system in (".", "..") or re.search(r"[\\/\x00]", args.system): + print("build_report.py: the system must be a folder name under analysis/, not a path", file=sys.stderr) + return 2 + try: + result = build(args.system, args.workspace, args.out) + except OSError as err: + print("build_report.py: %s" % err, file=sys.stderr) + return 1 + if result is None: + print("build_report.py: nothing found for %r under %s (analysis/ or modernized/)" % (args.system, os.path.abspath(args.workspace)), file=sys.stderr) + return 1 + html, count, path = result + try: + refused = write_atomic(path, html.encode("utf-8")) + except OSError as err: + refused = "could not write %s (%s)" % (path, err.__class__.__name__) + if refused: + print("build_report.py: %s" % refused, file=sys.stderr) + return 1 + print("%s: %d section%s, %s KB" % (path, count, "" if count == 1 else "s", num(os.path.getsize(path) >> 10))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/code-modernization/scripts/compare.py b/plugins/code-modernization/scripts/compare.py new file mode 100644 index 00000000..5bd0c74a --- /dev/null +++ b/plugins/code-modernization/scripts/compare.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Deterministic judge of "does the new system give the same output as the legacy one". + + python3 compare.py <cases.json> [--out EQUIVALENCE.json] [--quiet] [--allow-outside] + +The verdict comes from comparing bytes, never from a model's opinion. Input: + + {"system": "carddemo", + "legacy": {"label": "COBOL, GnuCOBOL 3.2", "command": "optional free text"}, + "new": {"label": "Java 17", "command": "optional free text"}, + "cases": [{"id": "C01", "title": "Interest posting, normal account", + "legacy": "out/legacy/C01.out", "new": "out/new/C01.out", + "mask": [{"bytes": "278-330", "why": "run timestamp"}, + {"regex": "\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}"}], + "approvedDifference": "optional: why a person accepted a difference", + "note": "optional"}]} + +Paths are relative to the cases file's folder and may not leave it unless --allow-outside is +given. `bytes` ranges are 0-based and inclusive; `regex` runs on the bytes decoded as latin-1. +Every masked span, on both sides, is replaced by one fixed marker, so masks never hide the +position of a difference and a variable-length match still compares equal. A case is: + same identical after masking + differs different; the first difference is recorded (a person may approve it: differs-approved) + missing a file is absent, unreadable or outside the cases folder. Never a pass. + +Writes EQUIVALENCE.json (default: next to the cases file). Exit 0 only when at least one case +executed, none is missing or differs (approved differences are allowed), the self-check did not +fail and some compared output was not empty; 1 otherwise; 2 for unusable input. +""" +import argparse +import bisect +import datetime +import hashlib +import json +import os +import re +import sys +import tempfile + +MARK = b"\x00<MASK>\x00" +MAX_BYTES = 256 * 1024 * 1024 + + +class InputError(Exception): + pass + + +def clip(value, limit): + return value[:limit] if isinstance(value, str) else "" + + +def parse_masks(specs, cid): + """[{"bytes": "0-3,10"} | {"regex": "..."}] -> [(kind, ranges-or-pattern, label)].""" + masks = [] + for spec in specs if isinstance(specs, list) else []: + if not isinstance(spec, dict) or ("bytes" in spec) == ("regex" in spec): + raise InputError("case %s: each mask needs exactly one of 'bytes' or 'regex'" % cid) + why = " (%s)" % clip(spec.get("why"), 120) if spec.get("why") else "" + if "bytes" in spec: + ranges = [] + for part in str(spec["bytes"]).split(","): + m = re.fullmatch(r"\s*(\d+)\s*(?:-\s*(\d+))?\s*", part) + if not m or (m.group(2) and int(m.group(2)) < int(m.group(1))): + raise InputError("case %s: bad byte range %r" % (cid, part)) + ranges.append((int(m.group(1)), int(m.group(2) or m.group(1)))) + masks.append(("bytes", ranges, "bytes %s%s" % (spec["bytes"], why))) + else: + try: + masks.append(("regex", re.compile(str(spec["regex"])), "regex %s%s" % (clip(str(spec["regex"]), 120), why))) + except re.error as err: + raise InputError("case %s: bad regex %r: %s" % (cid, spec["regex"], err)) + return masks + + +def mask_spans(data, masks): + """Merged (start, end) spans of `data` that the masks hide.""" + spans, text = [], None + for kind, spec, _ in masks: + if kind == "bytes": + spans += [(s, min(e + 1, len(data))) for s, e in spec if s < len(data)] + else: + text = data.decode("latin-1") if text is None else text + spans += [m.span() for m in spec.finditer(text) if m.end() > m.start()] + merged = [] + for s, e in sorted(spans): + if merged and s <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(e, merged[-1][1])) + else: + merged.append((s, e)) + return merged + + +def apply_masks(data, masks): + """-> (masked bytes, cuts, hidden byte count); cuts map masked offsets back to file offsets.""" + out, pos, cuts, hidden, at = [], 0, [], 0, 0 + for s, e in mask_spans(data, masks): + out.append(data[pos:s]) + at += s - pos + cuts.append((at, s, e)) + out.append(MARK) + at += len(MARK) + hidden += e - s + pos = e + out.append(data[pos:]) + return b"".join(out), cuts, hidden + + +def original_offset(cuts, masked_offset): + shift = 0 + for at, s, e in cuts: + if masked_offset < at: + break + if masked_offset < at + len(MARK): + return s + shift += (e - s) - len(MARK) + return masked_offset + shift + + +def first_diff(a, b): + n, step, i = min(len(a), len(b)), 1 << 16, 0 + while i < n: + j = min(i + step, n) + if a[i:j] != b[i:j]: + return next(k for k in range(i, j) if a[k] != b[k]) + i = j + return n if len(a) != len(b) else None + + +def escape(chunk): + out = [] + for byte in chunk: + if byte == 0x5C: + out.append("\\\\") + elif 0x20 <= byte < 0x7F: + out.append(chr(byte)) + else: + out.append({10: "\\n", 13: "\\r", 9: "\\t"}.get(byte, "\\x%02x" % byte)) + return "".join(out).replace("\\x00<MASK>\\x00", "[masked]") + + +def context(masked, off): + before = escape(masked[max(0, off - 12):off])[-12:] + after = escape(masked[off:off + 28])[:28] if off < len(masked) else "<end of output>" + return before + after, len(before) + + +def read_file(rel, base, allow_outside): + """-> (bytes, None) or (None, plain-English problem).""" + if not isinstance(rel, str) or not rel: + return None, "no path was given" + path = os.path.join(base, rel) + try: + real, root = os.path.realpath(path), os.path.realpath(base) + if not allow_outside and os.path.commonpath([root, real]) != root: + return None, "the path leaves the cases folder (pass --allow-outside if that is intended)" + if not os.path.exists(path): + return None, "the file does not exist" + if os.path.getsize(path) > MAX_BYTES: + return None, "the file is larger than %d MB" % (MAX_BYTES >> 20) + with open(path, "rb") as fh: + return fh.read(), None + except (OSError, ValueError) as err: + return None, "the file could not be read (%s)" % err.__class__.__name__ + + +def rel_to(path, folder): + try: + return os.path.relpath(path, folder).replace(os.sep, "/") + except ValueError: + return path + + +def judge(case, index, base, out_dir, allow_outside): + """-> (case record, legacy bytes or None, masks).""" + cid = clip(str(case.get("id") or "C%02d" % (index + 1)), 80) + masks = parse_masks(case.get("mask"), cid) + rec = {"id": cid, "title": clip(case.get("title"), 300), "verdict": "missing", "reason": "", + "legacyPath": "", "newPath": "", "legacySha256": "", "newSha256": "", + "masked": [m[2] for m in masks], "approvedDifference": clip(case.get("approvedDifference"), 500), + "note": clip(case.get("note"), 500)} + data, problems = {}, [] + for side in ("legacy", "new"): + given = case.get(side) + rec[side + "Path"] = rel_to(os.path.join(base, given), out_dir) if isinstance(given, str) and given else "" + data[side], why = read_file(given, base, allow_outside) + if why: + problems.append("The %s output was not compared: %s (%s)." % (side, why, clip(str(given), 200))) + if problems: + rec["reason"] = " ".join(problems) + return rec, None, masks + legacy, new = data["legacy"], data["new"] + rec["legacySha256"], rec["newSha256"] = hashlib.sha256(legacy).hexdigest(), hashlib.sha256(new).hexdigest() + a, cuts, hid_a = apply_masks(legacy, masks) + b, _, hid_b = apply_masks(new, masks) + rec["bytes"], rec["maskedBytes"] = {"legacy": len(legacy), "new": len(new)}, {"legacy": hid_a, "new": hid_b} + rec["empty"] = not legacy and not new + at = first_diff(a, b) + if at is None: + rec["verdict"] = "same" + rec["reason"] = ("Both outputs are empty, so nothing was compared." if rec["empty"] else + "Identical after masking: %d of %d bytes were hidden by %d mask(s)." % (hid_a, len(legacy), len(masks)) if masks else + "Identical, %d bytes." % len(legacy)) + return rec, legacy, masks + seen, seen_at = context(a, at) + got, _ = context(b, at) + line = a.count(b"\n", 0, at) + 1 + rec["firstDiff"] = {"offset": original_offset(cuts, at), "line": line, "legacy": seen, "new": got, "at": seen_at} + where = "line %d, byte %d" % (line, rec["firstDiff"]["offset"]) + if at >= len(a) or at >= len(b): + rec["reason"] = "The %s output ends at %s while the %s output continues." % ( + "legacy" if at >= len(a) else "new", where, "new" if at >= len(a) else "legacy") + else: + rec["reason"] = "The outputs first differ at %s." % where + if rec["approvedDifference"].strip(): + rec["verdict"] = "differs-approved" + rec["reason"] += " A person approved this difference: %s" % clip(rec["approvedDifference"], 200) + else: + rec["verdict"] = "differs" + return rec, legacy, masks + + +def self_check(items): + """Prove the comparator can fail: change one unmasked byte of each legacy output; it must differ.""" + tested = 0 + for cid, data, masks in items: + if not data: + continue + tested += 1 + base, _, _ = apply_masks(data, masks) + free, pos = [], 0 + for s, e in mask_spans(data, masks) + [(len(data), len(data))]: + if s > pos: + free.append((pos, s)) + pos = e + if not free: + return False, "case %s: the masks hide every byte, so no difference could ever be seen" % cid + biggest = max(free, key=lambda f: f[1] - f[0]) + for p in (free[0][0], free[-1][1] - 1, (biggest[0] + biggest[1]) // 2): + changed = data[:p] + bytes([data[p] ^ 1]) + data[p + 1:] + if apply_masks(changed, masks)[0] != base: + break + else: + return False, "case %s: a one-byte change to the legacy output was not reported as different" % cid + if not tested: + return None, "not applicable: no executed case had bytes to test" + return True, "each legacy output was compared with a copy changed by one byte and reported as different" + + +def run(cases_path, out_path=None, allow_outside=False): + """-> the EQUIVALENCE record. Raises InputError for a cases file that cannot be used.""" + try: + with open(cases_path, "rb") as fh: + spec = json.loads(fh.read().decode("utf-8-sig")) + except (OSError, ValueError) as err: + raise InputError("cannot read %s: %s" % (cases_path, err)) + if not isinstance(spec, dict) or not isinstance(spec.get("cases"), list): + raise InputError("%s must be a JSON object with a 'cases' list" % cases_path) + base = os.path.dirname(os.path.abspath(cases_path)) + out_dir = os.path.dirname(os.path.abspath(out_path)) if out_path else base + records, items, ids = [], [], set() + for i, case in enumerate(spec["cases"]): + if not isinstance(case, dict): + raise InputError("case %d is not an object" % (i + 1)) + rec, data, masks = judge(case, i, base, out_dir, allow_outside) + if rec["id"] in ids: + raise InputError("duplicate case id %r" % rec["id"]) + ids.add(rec["id"]) + records.append(rec) + if data is not None: + items.append((rec["id"], data, masks)) + passed, detail = self_check(items) + count = lambda v: sum(1 for r in records if r["verdict"] == v) + ends = lambda key: {k: clip(spec.get(key, {}).get(k), 300) for k in ("label", "command")} if isinstance(spec.get(key), dict) else {"label": "", "command": ""} + return {"system": clip(spec.get("system"), 200), "generated": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "legacy": ends("legacy"), "new": ends("new"), "selfCheck": {"passed": passed, "detail": detail}, + "totals": {"cases": len(records), "executed": len(items), "same": count("same"), "differs": count("differs"), + "differsApproved": count("differs-approved"), "missing": count("missing")}, + "cases": records} + + +def verdict_of(result): + """-> None when proven, else the reason it is not.""" + t = result["totals"] + if t["executed"] == 0: + return "no case executed" + if t["missing"] or t["differs"]: + return " and ".join(filter(None, ["%d case(s) differ" % t["differs"] if t["differs"] else "", + "%d case(s) are missing" % t["missing"] if t["missing"] else ""])) + if result["selfCheck"]["passed"] is False: + return "the self-check failed: " + result["selfCheck"]["detail"] + if all(r.get("empty") for r in result["cases"] if r["verdict"] != "missing"): + return "every compared output was empty" + return None + + +def write_atomic(path, text): + path = os.path.abspath(path) + folder = os.path.dirname(path) + for p in (path, folder): + if os.path.islink(p): + raise InputError("refusing to write through a symbolic link: %s" % p) + os.makedirs(folder, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=folder, prefix=".equivalence-", suffix=".tmp") + try: + with os.fdopen(fd, "wb") as fh: + fh.write(text.encode("utf-8")) + umask = os.umask(0) + os.umask(umask) + os.chmod(tmp, 0o666 & ~umask) + os.replace(tmp, path) + except BaseException: + if os.path.lexists(tmp): + os.unlink(tmp) + raise + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Compare legacy and new outputs byte for byte.") + ap.add_argument("cases", help="cases.json (see the module docstring for the schema)") + ap.add_argument("--out", help="where to write EQUIVALENCE.json (default: next to the cases file)") + ap.add_argument("--quiet", action="store_true", help="write the file, print nothing") + ap.add_argument("--allow-outside", action="store_true", help="allow case paths that leave the cases folder") + args = ap.parse_args(argv) + out = args.out or os.path.join(os.path.dirname(os.path.abspath(args.cases)), "EQUIVALENCE.json") + try: + result = run(args.cases, out, args.allow_outside) + except InputError as err: + print("compare.py: %s" % err, file=sys.stderr) + return 2 + try: + write_atomic(out, json.dumps(result, indent=2, ensure_ascii=True) + "\n") + except InputError as err: + print("compare.py: %s" % err, file=sys.stderr) + return 2 + problem = verdict_of(result) + if not args.quiet: + t, plain = result["totals"], lambda s: re.sub(r"[\x00-\x1f\x7f-\x9f]", "?", s) + print("equivalence cases executed: %d" % t["executed"]) + print("same %d | differs %d | differs but approved %d | missing %d | of %d cases" % + (t["same"], t["differs"], t["differsApproved"], t["missing"], t["cases"])) + sc = result["selfCheck"] + print("self-check: %s - %s" % ({True: "passed", False: "FAILED", None: "not applicable"}[sc["passed"]], plain(sc["detail"]))) + for r in result["cases"]: + if r["verdict"] != "same": + print(" %s %s: %s" % (plain(r["id"]), r["verdict"], plain(r["reason"])[:200])) + print(("NOT PROVEN: %s" % problem) if problem else "PROVEN: %d case(s) executed, none differ" % t["executed"]) + print("wrote %s" % out) + return 1 if problem else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/code-modernization/scripts/make_shards.py b/plugins/code-modernization/scripts/make_shards.py index ff6671cc..175d6980 100644 --- a/plugins/code-modernization/scripts/make_shards.py +++ b/plugins/code-modernization/scripts/make_shards.py @@ -3,8 +3,7 @@ python3 make_shards.py <system> [module-pattern] [--workspace DIR] [--all] -The source directory is the first line of analysis/<system>/SOURCE when that file -exists, else legacy/<system>. With analysis/<system>/topology.json, one shard per map +The source directory is legacy/<system> (a copy, or a symlink to where the code lives). With analysis/<system>/topology.json, one shard per map module (small modules of a domain merged); without it, one shard per directory of source files. The list is written to analysis/<system>/extract-rules.modules.json as [{"name", "domain", "files": [relative to the source dir], "loc"}], the form the @@ -38,13 +37,16 @@ TINY_ESTATE = 30 MAX_BYTES = 5_000_000 +def too_broad(path): + """The filesystem root, the home directory or one of its parents, or a top-level system directory: never a system's code.""" + real = os.path.realpath(path) + home = os.path.realpath(os.path.expanduser('~')) + parts = [p for p in real.split(os.sep) if p] + return real == os.sep or len(parts) < 2 or home == real or home.startswith(real + os.sep) + + def source_dir(workspace, system): - marker = os.path.join(workspace, 'analysis', system, 'SOURCE') - if os.path.isfile(marker): - with open(marker, encoding='utf-8', errors='replace') as handle: - first = handle.readline().strip() - if first: - return first if os.path.isabs(first) else os.path.join(workspace, first) + """The code is legacy/<system>: a copy, or a symlink to where it really lives.""" return os.path.join(workspace, 'legacy', system) @@ -61,6 +63,29 @@ def count_lines(path): return data.count(b'\n') + (1 if data and not data.endswith(b'\n') else 0) +def matcher(pattern): + """A glob matches a name or a path (or its file name); a plain name such as `jetty-util` also matches what lies beneath it.""" + plain_name = not any(ch in pattern for ch in '*?[') + wanted = pattern.strip('/') + + def match(text): + if fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern): + return True + if plain_name: + padded = '/' + text.strip('/') + '/' + return padded.startswith('/' + wanted + '/') or ('/' + wanted + '/') in padded + return False + + return match + + +def contained(source, rel): + """True when `rel` under the source directory really resolves inside it (no `..`, no symlink out).""" + root = os.path.realpath(source) + real = os.path.realpath(os.path.join(source, rel)) + return real == root or real.startswith(root + os.sep) + + def relative_to_source(path, source, system): """A topology `file` may be absolute, workspace-relative or source-relative: return it source-relative.""" path = path.replace('\\', '/') @@ -73,8 +98,20 @@ def relative_to_source(path, source, system): return path +def shared_locations(modules, source): + """Locations several map modules share, or that are directories: modules without files of their own cannot be sharded.""" + seen, shared = {}, [] + for module in modules: + for rel in module['files']: + seen.setdefault(rel, []).append(module['name']) + for rel, owners in seen.items(): + if len(owners) > 1 or os.path.isdir(os.path.join(source, rel)): + shared.append((rel, len(owners))) + return shared + + def from_topology(topology, source, system, pattern): - modules, names = [], set() + modules, names, escaped = [], set(), [] def walk(node, domain): kind = node.get('kind') @@ -82,7 +119,9 @@ def from_topology(topology, source, system, pattern): domain = node.get('name') or node.get('id', '') if kind == 'module' and node.get('file'): rel = relative_to_source(str(node['file']), source, system) - if rel: + if rel and not contained(source, rel): + escaped.append(rel) + elif rel: name = str(node.get('name') or node.get('id')) if name in names: name = str(node.get('id') or name) # names can repeat across domains; ids are unique @@ -92,9 +131,12 @@ def from_topology(topology, source, system, pattern): walk(child, domain) walk(topology['root'], '') + total = len(modules) + unusable = shared_locations(modules, source) + if unusable: + raise ValueError('%d map module(s) share a location or name a directory instead of a file (first: %s)' % (len(unusable), unusable[0][0])) if pattern: - def match(text): - return fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern) + match = matcher(pattern) modules = [m for m in modules if match(m['name']) or any(match(f) for f in m['files'])] # merge small modules of the same domain; never split one shards, pool, counter = [], {}, {} @@ -112,11 +154,11 @@ def from_topology(topology, source, system, pattern): current['loc'] += module['loc'] else: shards.append(module) - return shards, len(modules) + return shards, len(modules), escaped, total def from_tree(source, pattern, include_all): - by_dir, skipped = {}, {'vendored or generated': 0, 'tests': 0, 'unreadable or binary': 0} + by_dir, skipped = {}, {'vendored or generated': 0, 'tests': 0, 'unreadable or binary': 0, 'symbolic links': 0} for root, dirs, files in os.walk(source): kept = [] for d in sorted(dirs): @@ -131,15 +173,18 @@ def from_tree(source, pattern, include_all): if os.path.splitext(name)[1].lower() not in SOURCE_EXT or name.endswith('.min.js'): continue path = os.path.join(root, name) + if os.path.islink(path): + skipped['symbolic links'] += 1 # a link can point outside the source directory + continue lines = count_lines(path) if lines is None: skipped['unreadable or binary'] += 1 continue rel = os.path.relpath(path, source).replace(os.sep, '/') by_dir.setdefault(os.path.dirname(rel), []).append((rel, lines)) + whole = sum(len(fs) for fs in by_dir.values()) if pattern: - def match(text): - return fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(os.path.basename(text), pattern) + match = matcher(pattern) by_dir = {d: [f for f in fs if match(f[0])] for d, fs in by_dir.items()} shards, total = [], 0 for directory in sorted(by_dir): @@ -157,7 +202,7 @@ def from_tree(source, pattern, include_all): if rel is not None: chunk.append((rel, lines)) chunk_loc += lines - return shards, total, skipped + return shards, total, skipped, whole def main(argv): @@ -172,8 +217,13 @@ def main(argv): return 2 system, pattern = args[0], (args[1] if len(args) > 1 else '') source = source_dir(workspace, system) + print(f'source: {source}') + if os.path.isdir(source) and too_broad(source): + print(f'{source} is too broad to be one system (the filesystem root, your home directory or a top-level directory). ' + 'Point --source at the directory that holds the code.', file=sys.stderr) + return 1 if not os.path.isdir(source): - print(f'No source directory at {source}. Run preflight (with --source <path> if the code is elsewhere) first.', file=sys.stderr) + print(f'No code at {source}. Run preflight first (with --source <path> if the code lives elsewhere).', file=sys.stderr) return 1 out = os.path.join(workspace, 'analysis', system, 'extract-rules.modules.json') topo_path = os.path.join(workspace, 'analysis', system, 'topology.json') @@ -182,17 +232,19 @@ def main(argv): try: with open(topo_path, encoding='utf-8') as handle: topology = json.load(handle) - shards, modules = from_topology(topology, source, system, pattern) + shards, modules, escaped, whole = from_topology(topology, source, system, pattern) origin = f'{modules} map modules' + if escaped: + notes.append(f'{len(escaped)} map file(s) resolve outside the source directory and were left out (first: {escaped[0]})') missing = [f for s in shards for f in s['files'] if not os.path.exists(os.path.join(source, f))] if missing: notes.append(f'{len(missing)} file(s) named by the map do not exist under the source directory (first: {missing[0]})') except (ValueError, KeyError, OSError) as error: - print(f'topology.json is unusable ({error}); reading the directory tree instead.', file=sys.stderr) - shards, files, skipped = from_tree(source, pattern, '--all' in flags) + print(f'note: the map cannot be sharded by module ({error}); reading the directory tree instead.') + shards, files, skipped, whole = from_tree(source, pattern, '--all' in flags) origin = f'{files} source files (tree)' else: - shards, files, skipped = from_tree(source, pattern, '--all' in flags) + shards, files, skipped, whole = from_tree(source, pattern, '--all' in flags) origin = f'{files} source files (no topology.json: read from the directory tree)' left_out = ', '.join(f'{n} {k}' for k, n in skipped.items() if n) if left_out: @@ -208,8 +260,8 @@ def main(argv): file_count = sum(len(s['files']) for s in shards) loc = sum(s['loc'] or 0 for s in shards) print(f'{len(shards)} shards from {origin}, {file_count} files, {loc} lines -> {os.path.relpath(out, workspace)}') - if file_count < TINY_ESTATE: - print(f'tiny estate: fewer than {TINY_ESTATE} source files, so sharding adds little (run the workflow in lens mode).') + if whole < TINY_ESTATE: + print(f'tiny estate: the system has fewer than {TINY_ESTATE} source files, so sharding adds little (run the workflow in lens mode).') for note in notes: print(f'note: {note}') return 0 diff --git a/plugins/code-modernization/scripts/tests/test_report_tools.py b/plugins/code-modernization/scripts/tests/test_report_tools.py new file mode 100644 index 00000000..07c892bc --- /dev/null +++ b/plugins/code-modernization/scripts/tests/test_report_tools.py @@ -0,0 +1,779 @@ +"""Tests for scripts/build_report.py, scripts/compare.py and assets/report-template.html. + +Run: python3 -m unittest discover -s plugins/code-modernization/scripts/tests +The template's JavaScript is exercised with Node when it is installed (those tests are skipped otherwise). +""" +import base64 +import contextlib +import hashlib +import io +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from html.parser import HTMLParser +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +PLUGIN = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, os.path.join(PLUGIN, "scripts")) +import build_report as br # noqa: E402 +import compare as cmp # noqa: E402 + +TEMPLATE = os.path.join(PLUGIN, "assets", "report-template.html") +MERMAID = os.path.join(PLUGIN, "assets", "vendor", "mermaid.min.js") +SECRET = "TOP-SECRET-MARKER-9f3c" +LS, PS = chr(0x2028), chr(0x2029) + + +def put(root, rel, data): + path = os.path.join(root, *rel.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as fh: + fh.write(data if isinstance(data, bytes) else data.encode("utf-8")) + return path + + +def run_main(fn, argv): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = fn(argv) + return code, out.getvalue(), err.getvalue() + + +def make_symlink(test, target, link): + try: + os.symlink(target, link) + except (OSError, NotImplementedError, AttributeError): + test.skipTest("symbolic links are not available here") + + +class Scripts(HTMLParser): + """Every <script> element of a page: its attributes and its text.""" + + def __init__(self, html): + super().__init__(convert_charrefs=False) + self.found, self._cur = [], None + self.feed(html) + + def handle_starttag(self, tag, attrs): + if tag == "script": + self._cur = {"attrs": dict(attrs), "text": ""} + + def handle_data(self, data): + if self._cur is not None: + self._cur["text"] += data + + def handle_endtag(self, tag): + if tag == "script" and self._cur is not None: + self.found.append(self._cur) + self._cur = None + + +def page_data(html): + block = [s for s in Scripts(html).found if s["attrs"].get("id") == "report-data"] + assert len(block) == 1 + return json.loads(block[0]["text"]) + + +HOSTILE_MD = "\n".join([ + "# Assessment <script>window.__pwned=1</script>", + '<img src=x onerror="window.__pwned=2">', + "</script><script>window.__pwned=3</script> <!-- and <!--", + "[a](javascript:window.__pwned=4) [b](JavaScript:alert(1)) [c](java\tscript:alert(1)) [d](" + chr(1) + "javascript:alert(1))", + "[e](data:text/html,<script>1</script>) [f](//evil.example/x) [g](/\\evil.example) ", + '<a href="javascript:alert(1)">raw anchor</a> <iframe src="https://evil.example"></iframe>', + "| a | b |", "|---|---|", "| <b onmouseover=alert(1)>x</b> | <img src=x onerror=window.__pwned=5> |", + "`<script>` and **<img src=x onerror=1>** " + LS + PS, + "```mermaid", 'graph TD; A["<img src=x onerror=window.__pwned=7>"]-->B', "```", + "x" * 1000000, "*" * 200000, "[" * 50000, "|" * 50000, +]) +HOSTILE_RULES = "\n".join([ + "# Rules", "", + "### RULE-001: Title with `backticks` and <angle> <script>x</script> & ampersand", + "**Category:** Validation ", "**Priority:** P0 ", "**Source:** `evil/../../etc/passwd:1-2` and `a.cbl:10` ", + "**Confidence:** High ", "**Suspected defect:** <img src=x onerror=window.__pwned=6>", "", + "### P1-002 \u00b7 Second card, other id style", "P1 \u00b7 Policy \u00b7 confidence Low \u00b7 `b.cbl:5-9`", "", +]) + + +def hostile_workspace(root, system="evil"): + a = "analysis/" + system + put(root, a + "/ASSESSMENT.md", HOSTILE_MD) + put(root, a + "/BUSINESS_RULES.md", HOSTILE_RULES) + put(root, a + "/MODERNIZATION_BRIEF.md", "# Brief\n\n```mermaid\n%%{init: {\"themeCSS\": \".x{background:url(https://evil.example/t.gif)}\"}}%%\ngraph TD; A-->B\n```\n") + put(root, a + "/good.mmd", "graph TD\n A[Start] --> B[End]\n") + put(root, a + "/bad.mmd", "graph TD\n A --> --> ((\n") + put(root, a + "/topology.json", '{"root": {"id": ') + put(root, a + "/RULE_REVIEWS.json", "not json at all") + put(root, a + "/SECRETS.local.md", SECRET) + put(root, a + "/security_remediation.local.patch", SECRET) + put(root, a + "/SECURITY_FINDINGS.md", "# Findings\n\n| ID | Severity | Title |\n|---|---|---|\n| SEC-1 | Critical | <script>x</script> |\n| SEC-2 | High | y |\n| SEC-3 | high | z |\n") + put(root, "modernized/%s/README.md" % system, "# Module <img src=x onerror=1>\n") + put(root, "modernized/%s/mod1/TRANSFORMATION_NOTES.md" % system, "# Notes\n</script>\n") + outside = tempfile.mkdtemp() + put(outside, "secret.txt", "OUTSIDE-MARKER") + try: + os.symlink(os.path.join(outside, "secret.txt"), os.path.join(root, *(a + "/PLAYBOOK.md").split("/"))) + except (OSError, NotImplementedError, AttributeError): + pass + return outside + + +class CompareTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + + def cases(self, cases, **extra): + path = put(self.tmp, "cases.json", json.dumps({"system": "s", "cases": cases, **extra})) + return path + + def files(self, name, legacy, new): + put(self.tmp, "legacy/%s" % name, legacy) + if new is not None: + put(self.tmp, "new/%s" % name, new) + return {"id": name, "title": "case " + name, "legacy": "legacy/" + name, "new": "new/" + name} + + def result(self, cases, **extra): + out = os.path.join(self.tmp, "analysis", "EQUIVALENCE.json") + code, stdout, _ = run_main(cmp.main, [self.cases(cases, **extra), "--out", out]) + with open(out, encoding="utf-8") as fh: + return code, stdout, json.load(fh) + + def test_same_differs_missing_approved_and_exit_codes(self): + same, diff, miss = self.files("a", b"one\ntwo\n", b"one\ntwo\n"), self.files("b", b"one\ntwo\n", b"one\ntw0\n"), self.files("c", b"x", None) + code, out, res = self.result([same, diff, miss]) + self.assertEqual(code, 1) + self.assertEqual([c["verdict"] for c in res["cases"]], ["same", "differs", "missing"]) + self.assertEqual(res["totals"], {"cases": 3, "executed": 2, "same": 1, "differs": 1, "differsApproved": 0, "missing": 1}) + self.assertIn("equivalence cases executed: 2", out) + self.assertIn("NOT PROVEN", out) + d = res["cases"][1]["firstDiff"] + self.assertEqual((d["offset"], d["line"]), (6, 2)) + self.assertIn("legacy", res["cases"][2]["reason"].lower() + "legacy") + self.assertEqual(res["cases"][0]["legacySha256"], hashlib.sha256(b"one\ntwo\n").hexdigest()) + approved = dict(diff, id="b2", approvedDifference="fixed on purpose") + code, _, res = self.result([same, approved]) + self.assertEqual(code, 0) + self.assertEqual(res["cases"][1]["verdict"], "differs-approved") + self.assertEqual(res["totals"]["differsApproved"], 1) + + def test_all_same_is_proven(self): + code, out, res = self.result([self.files("a", b"abc", b"abc")]) + self.assertEqual(code, 0) + self.assertIn("PROVEN", out) + self.assertNotIn("NOT PROVEN", out) + self.assertEqual(res["selfCheck"]["passed"], True) + + def test_missing_alone_is_never_a_pass(self): + code, out, res = self.result([self.files("a", b"x", b"x"), self.files("m", b"x", None)]) + self.assertEqual(code, 1) + self.assertIn("missing", out) + self.assertEqual((res["totals"]["executed"], res["totals"]["missing"], res["totals"]["differs"]), (1, 1, 0)) + + def test_no_case_executed_is_not_proven(self): + for cases in ([], [self.files("m", b"x", None)]): + code, out, res = self.result(cases) + self.assertEqual(code, 1) + self.assertIn("equivalence cases executed: 0", out) + self.assertIn("NOT PROVEN: no case executed", out) + self.assertEqual(res["selfCheck"]["passed"], None) + + def test_empty_outputs_prove_nothing(self): + code, out, res = self.result([self.files("e", b"", b"")]) + self.assertEqual(code, 1) + self.assertIn("empty", out) + self.assertEqual(res["cases"][0]["verdict"], "same") + self.assertTrue(res["cases"][0]["empty"]) + + def test_masks_hide_only_what_they_name(self): + legacy, new = b"id=12 at 2026-09-01 10:11:12 total=5\n", b"id=1234 at 2026-09-24 03:04:05 total=5\n" + case = dict(self.files("t", legacy, new), mask=[{"regex": r"id=\d+"}, {"regex": r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d"}]) + code, _, res = self.result([case]) + self.assertEqual((code, res["cases"][0]["verdict"]), (0, "same")) + case["new"] = self.files("t2", legacy, new.replace(b"total=5", b"total=6"))["new"] + _, _, res = self.result([case]) + self.assertEqual(res["cases"][0]["verdict"], "differs") + self.assertEqual(res["cases"][0]["firstDiff"]["offset"], legacy.index(b"5")) + ranged = dict(self.files("r", b"aaXXbb", b"aaYYbb"), mask=[{"bytes": "2-3"}]) + self.assertEqual(self.result([ranged])[2]["cases"][0]["verdict"], "same") + beyond = dict(self.files("r2", b"aaXXbb", b"aaYYbc"), mask=[{"bytes": "2-3"}, {"bytes": "50-60"}]) + self.assertEqual(self.result([beyond])[2]["cases"][0]["verdict"], "differs") + + def test_a_mask_that_hides_everything_fails_the_self_check(self): + case = dict(self.files("h", b"abc", b"xyz"), mask=[{"regex": ".*"}]) + code, out, res = self.result([case]) + self.assertEqual(code, 1) + self.assertIs(res["selfCheck"]["passed"], False) + self.assertIn("hide every byte", res["selfCheck"]["detail"]) + self.assertIn("NOT PROVEN", out) + + def test_bad_input_is_exit_2_and_writes_nothing(self): + out = os.path.join(self.tmp, "EQ.json") + bad = [put(self.tmp, "a.json", "{not json"), put(self.tmp, "b.json", json.dumps({"cases": "x"})), + self.cases([dict(self.files("z", b"a", b"a"), mask=[{"regex": "("}])]), self.cases([dict(self.files("y", b"a", b"a"), mask=[{"bytes": "9-2"}])]), + self.cases([self.files("d", b"a", b"a"), self.files("d", b"a", b"a")]), os.path.join(self.tmp, "missing.json")] + for path in bad: + code, _, err = run_main(cmp.main, [path, "--out", out]) + self.assertEqual(code, 2, path) + self.assertFalse(os.path.exists(out)) + self.assertIn("compare.py", err) + + def test_paths_may_not_leave_the_cases_folder(self): + outside = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, outside, True) + put(outside, "o.txt", "same") + sub = os.path.join(self.tmp, "sub") + put(sub, "n.txt", "same") + case = {"id": "o", "legacy": os.path.join(outside, "o.txt"), "new": "n.txt"} + path = put(sub, "cases.json", json.dumps({"cases": [case]})) + out = os.path.join(sub, "E.json") + self.assertEqual(run_main(cmp.main, [path, "--out", out, "--quiet"])[0], 1) + with open(out) as fh: + self.assertEqual(json.load(fh)["cases"][0]["verdict"], "missing") + self.assertEqual(run_main(cmp.main, [path, "--out", out, "--quiet", "--allow-outside"])[0], 0) + + def test_first_difference_context_is_escaped_and_bounded(self): + _, _, res = self.result([self.files("c", b"a\x00\x1b[31m\tb" + b"z" * 200, b"a\x00\x1b[31m\tc" + b"z" * 200)]) + d = res["cases"][0]["firstDiff"] + self.assertLessEqual(len(d["legacy"]), 40) + self.assertNotRegex(d["legacy"] + d["new"], r"[\x00-\x1f\x7f]") + self.assertEqual(d["legacy"][d["at"]], "b") + _, _, res = self.result([self.files("p", b"abc", b"abcdef")]) + self.assertIn("ends", res["cases"][0]["reason"]) + self.assertIn("<end of output>", res["cases"][0]["firstDiff"]["legacy"]) + + def test_summary_neutralises_terminal_escapes_and_quiet_is_quiet(self): + case = dict(self.files("q", b"a", b"b"), id="q\x1b[2J") + code, out, _ = run_main(cmp.main, [self.cases([case]), "--out", os.path.join(self.tmp, "E.json")]) + self.assertNotIn("\x1b", out) + code, out, _ = run_main(cmp.main, [self.cases([case]), "--out", os.path.join(self.tmp, "E.json"), "--quiet"]) + self.assertEqual((code, out), (1, "")) + + def test_default_output_and_atomic_write(self): + code, _, _ = run_main(cmp.main, [self.cases([self.files("a", b"x", b"x")]), "--quiet"]) + self.assertEqual(code, 0) + self.assertEqual(sorted(f for f in os.listdir(self.tmp) if "equivalence" in f.lower()), ["EQUIVALENCE.json"]) + + def test_a_symlinked_output_is_refused(self): + real = put(self.tmp, "elsewhere/E.json", "ORIGINAL") + link = os.path.join(self.tmp, "E.json") + make_symlink(self, real, link) + code, _, err = run_main(cmp.main, [self.cases([self.files("a", b"x", b"x")]), "--out", link, "--quiet"]) + self.assertEqual(code, 2) + self.assertIn("symbolic link", err) + with open(real) as fh: + self.assertEqual(fh.read(), "ORIGINAL") + + +class BuildFacts(unittest.TestCase): + def test_rule_cards_in_several_layouts(self): + text = "\n".join([ + "## Rules", "### RULE-012: Interest is truncated", "**Priority:** P0", "**Confidence:** High \u2014 checked", "**Category:** Calculation", + "**Source:** `a/B.cbl:10-20,30` and `C.cbl:5`", "**Suspected defect:** rounds down", "```", "### not a heading in a fence", "```", "", + "### P1-001 \u00b7 Header line style", "`P1` \u00b7 Validation \u00b7 confidence Medium \u00b7 `d/E.cbl:1-2`", "", + "#### R-12: Short id", "Priority: P2", "**Suspected defect:** none", "", "### BR-D7-09 \u2014 Domain coded", "### Plain heading", "text", + ]) + blocks = br.parse_rules(text) + cards = [b for b in blocks if b["k"] == "rule"] + self.assertEqual([c["id"] for c in cards], ["RULE-012", "P1-001", "R-12", "BR-D7-09"]) + self.assertEqual([c["p"] for c in cards], ["P0", "P1", "P2", ""]) + self.assertEqual([c["conf"] for c in cards], ["High", "Medium", "", ""]) + self.assertEqual([c["defect"] for c in cards], [True, False, False, False]) + self.assertEqual(cards[0]["cites"], ["a/B.cbl:10-20,30", "C.cbl:5"]) + self.assertEqual(cards[1]["cites"], ["d/E.cbl:1-2"]) + self.assertNotIn("Priority", cards[0]["body"]) + self.assertIn("### not a heading in a fence", cards[0]["body"]) + self.assertEqual(blocks[0]["k"], "md") + self.assertEqual(br.parse_rules("just text\n\n## Heading")[0]["k"], "md") + + def test_rule_priority_falls_back_to_the_index_table(self): + text = "| ID | Name | Priority |\n|---|---|---|\n| [RULE-007](#x) | Merged | P0 |\n\n### RULE-007: Merged\n**Merged into:** RULE-006\n\n### RULE-008: Real\n**Priority:** P1\n" + cards = [b for b in br.parse_rules(text) if b["k"] == "rule"] + facts = br.rule_facts(text, cards, {"RULE-008": {"verdict": "confirmed"}}) + self.assertEqual((facts["total"], facts["byPriority"], facts["unrated"]), (2, {"P0": 1, "P1": 1}, 0)) + self.assertEqual(facts["reviews"], {"confirmed": 1}) + + def test_security_tally(self): + findings = "## Summary scorecard\n| Severity | Count |\n|---|---|\n| Critical | 9 |\n\n## Findings\n| ID | Severity | Title |\n|---|---|---|\n| S1 | **Critical** | a |\n| S2 | High | b |\n| S3 | high | c |\n| S4 | Low | d |\n\n## Dependency CVEs\n| Package | Installed | CVE | Severity |\n|---|---|---|---|\n| x | 1 | CVE-1 | High |\n\n## Coverage gaps\n| Finding | Severity |\n|---|---|\n| n | Medium |\n" + self.assertEqual(br.security_facts(findings), {"Critical": 1, "High": 2, "Low": 1}) + self.assertEqual(br.security_facts("| Severity | Count |\n|---|---|\n| Critical | 2 |\n| High | 3 |\n"), {"Critical": 2, "High": 3}) + self.assertIsNone(br.security_facts("Nothing recognisable here.")) + + def test_baseline_facts(self): + table = "| Test | Result |\n|---|---|\n| a | pass |\n| b | PASS |\n| c | fail |\n| d | skipped |\n" + self.assertEqual(br.baseline_facts(table), {"pass": 2, "fail": 1, "skip": 1, "targetOnly": False}) + self.assertEqual(br.baseline_facts("Run: 12 tests passed, 1 failed"), {"pass": 12, "fail": 1, "targetOnly": False}) + self.assertEqual(br.baseline_facts("target-only: the source runtime is not available")["targetOnly"], True) + self.assertIsNone(br.baseline_facts("| Fixture | RC |\n|---|---|\n| seed | 0 |\n")) + + def test_topology_facts(self): + topo = {"root": {"id": "s", "kind": "system", "children": [{"id": "d", "kind": "domain", "children": [ + {"id": "A", "kind": "module", "loc": 100, "language": "cobol", "file": "a.cbl"}, {"id": "B", "kind": "module", "loc": 50, "file": "b.cbl"}, + {"id": "F", "kind": "datastore"}]}]}, "edges": [{}, {}]} + self.assertEqual(br.topology_facts(topo), {"modules": 2, "loc": 150, "languages": ["cobol"], "edges": 2, "observations": []}) + self.assertIsNone(br.topology_facts([1, 2])) + self.assertIsNone(br.topology_facts({"root": {"id": "x", "children": "oops"}})) + + def test_equivalence_view_never_trusts_the_files_own_words(self): + digest = "a" * 64 + good = {"cases": [{"id": "1", "verdict": "same", "legacySha256": digest, "newSha256": digest}, {"id": "2", "verdict": "differs-approved", "approvedDifference": "ok"}], + "selfCheck": {"passed": True, "detail": "d"}, "totals": {"cases": 2, "executed": 2}} + view = br.equivalence_view(good) + self.assertEqual((view["state"], view["problems"]), ("green", [])) + self.assertEqual(br.equivalence_view(dict(good, cases=[dict(good["cases"][0], newSha256="b" * 64)]))["state"], "red") + for bad_case in ({"id": "x", "verdict": "differs"}, {"id": "x", "verdict": "missing"}, {"id": "x", "verdict": "pass"}, + {"id": "x", "verdict": "differs-approved"}, {"id": "x", "verdict": "same", "firstDiff": {"offset": 1}}): + view = br.equivalence_view(dict(good, cases=good["cases"] + [bad_case], totals={})) + self.assertEqual(view["state"], "red", bad_case) + self.assertEqual(br.equivalence_view(dict(good, cases=[]))["state"], "red") + self.assertEqual(br.equivalence_view(dict(good, selfCheck={"passed": False, "detail": "x"}))["state"], "red") + self.assertEqual(br.equivalence_view(dict(good, cases=[dict(good["cases"][0], empty=True)]))["state"], "red") + no_check = br.equivalence_view({"cases": good["cases"]}) + self.assertEqual(no_check["state"], "green") + self.assertTrue(any("self-check" in p for p in no_check["problems"])) + self.assertTrue(any("disagree" in p for p in br.equivalence_view(dict(good, totals={"cases": 9, "executed": 9}))["problems"])) + self.assertIsNone(br.equivalence_view({"cases": "x"})) + self.assertIsNone(br.equivalence_view([])) + + +class BuildReport(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.out = os.path.join(self.tmp, "out", "REPORT.html") + + def build(self, system="s", extra=()): + code, out, err = run_main(br.main, [system, "--workspace", self.tmp, "--out", self.out, *extra]) + return code, out, err + + def html(self): + with open(self.out, encoding="utf-8") as fh: + return fh.read() + + def test_nothing_found_is_exit_1_with_one_line(self): + os.makedirs(os.path.join(self.tmp, "analysis", "s")) + code, out, err = self.build() + self.assertEqual(code, 1) + self.assertEqual(len(err.strip().splitlines()), 1) + self.assertFalse(os.path.exists(self.out)) + + def test_bad_system_names_are_refused(self): + for name in ("..", "a/b", "a\\b", ""): + self.assertEqual(self.build(name)[0], 2, name) + + def test_nearly_empty_workspace(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "# Preflight\nAll good.\n") + code, out, _ = self.build() + self.assertEqual(code, 0) + self.assertRegex(out.strip(), r"REPORT\.html: 1 section, \d+ KB$") + html = self.html() + self.assertEqual([s["attrs"].get("id") for s in Scripts(html).found], ["report-data", "app"]) + data = page_data(html) + self.assertEqual([s["id"] for s in data["sections"]], ["overview"]) + self.assertFalse(any(x["done"] for x in data["glance"]["steps"] if x["key"] != "preflight")) + self.assertIsNone(data["glance"]["track"]) + self.assertIsNone(data["glance"]["equivalence"]) + + def test_default_output_path(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "x") + code, out, _ = run_main(br.main, ["s", "--workspace", self.tmp]) + self.assertEqual(code, 0) + self.assertTrue(os.path.isfile(os.path.join(self.tmp, "analysis", "s", "REPORT.html"))) + self.assertEqual([f for f in os.listdir(os.path.join(self.tmp, "analysis", "s")) if f.endswith(".tmp")], []) + + def test_malformed_files_are_reported_in_the_page_not_raised(self): + a = "analysis/s/" + put(self.tmp, a + "topology.json", "{broken") + put(self.tmp, a + "EQUIVALENCE.json", "[1, 2") + put(self.tmp, a + "RULE_REVIEWS.json", '{"reviews": 5}') + put(self.tmp, a + "BUSINESS_RULES.md", b"\xff\xfe\x00binary\x00\x01### RULE-001: x\n") + put(self.tmp, a + "ASSESSMENT.md", b"") + put(self.tmp, a + "BASELINE.md", "| a |\n|---") + put(self.tmp, a + "SECURITY_FINDINGS.md", "|||\n|||\n") + put(self.tmp, a + "broken.mmd", "") + code, _, _ = self.build() + self.assertEqual(code, 0) + data = page_data(self.html()) + notes = json.dumps(data["sections"][0]["parts"]) + self.assertIn("topology.json could not be parsed", notes) + self.assertIn("EQUIVALENCE.json could not be parsed", notes) + self.assertEqual(data["glance"]["equivalence"]["state"], "red") + self.assertIn("RULE_REVIEWS.json", notes) + + def test_hostile_input_cannot_reach_the_page_as_markup_or_script(self): + outside = hostile_workspace(self.tmp) + self.addCleanup(shutil.rmtree, outside, True) + code, _, _ = self.build("evil") + self.assertEqual(code, 0) + html = self.html() + scripts = Scripts(html).found + ids = [s["attrs"].get("id") for s in scripts] + self.assertEqual(ids, ["report-data", "mermaid-lib", "app"]) + for s in scripts: + self.assertLessEqual(set(s["attrs"]), {"id", "type"}) + block = scripts[0]["text"] + for bad in ("<", ">", "&", LS, PS): + self.assertNotIn(bad, block) + self.assertNotIn("</script", scripts[1]["text"].lower()) + self.assertNotIn("<!--", scripts[1]["text"]) + page = html.replace(scripts[0]["text"], "").replace(scripts[1]["text"], "") + for needle in ("__pwned=", "onerror", "evil.example", "javascript:"): + self.assertNotIn(needle, page.split('<script id="app">')[0].split("</style>")[1], needle) + text = json.dumps(page_data(html)) + self.assertIn("window.__pwned=1", text) + self.assertNotIn(SECRET, html) + self.assertNotIn("OUTSIDE-MARKER", html) + notes = json.dumps(page_data(html)["sections"][0]["parts"]) + if os.path.islink(os.path.join(self.tmp, "analysis", "evil", "PLAYBOOK.md")): + self.assertIn("PLAYBOOK.md is a link", notes) + self.assertIn("longer than 20,000 characters were shortened", notes) + self.assertLess(len(html), 6 << 20) + data = page_data(html) + self.assertEqual(data["glance"]["security"], {"Critical": 1, "High": 2}) + self.assertEqual(data["glance"]["rules"]["total"], 2) + titles = [b["title"] for s in data["sections"] for p in s["parts"] for b in p.get("blocks", []) if b["k"] == "rule"] + self.assertIn("Title with `backticks` and <angle> <script>x</script> & ampersand", titles) + + def test_secret_and_local_files_are_never_read_even_when_asked_for_by_name(self): + for name in ("SECRETS.local.md", "secrets.txt", "security_remediation.local.patch", "notes.LOCAL.md"): + path = put(self.tmp, "analysis/s/" + name, SECRET) + src = br.Source(self.tmp, "s") + self.assertIsNone(src.read(path, name), name) + self.assertEqual(src.found, []) + + def test_csp_pins_exactly_the_scripts_on_the_page(self): + put(self.tmp, "analysis/s/good.mmd", "graph TD\n A-->B\n") + self.build() + html = self.html() + policy = re.search(r'http-equiv="Content-Security-Policy" content="([^"]*)"', html).group(1) + self.assertIn("default-src 'none'", policy) + self.assertNotIn("unsafe-eval", policy) + self.assertNotRegex(policy, r"script-src[^;]*unsafe-inline") + hashes = re.findall(r"'sha256-([^']+)'", policy.split("script-src")[1].split(";")[0]) + code_scripts = [s for s in Scripts(html).found if s["attrs"].get("type") != "application/json"] + expected = [base64.b64encode(hashlib.sha256(s["text"].encode("utf-8")).digest()).decode() for s in code_scripts] + self.assertEqual(sorted(hashes), sorted(expected)) + self.assertEqual(len(expected), 2) + + def test_mermaid_is_inlined_only_when_a_diagram_exists(self): + put(self.tmp, "analysis/s/ASSESSMENT.md", "# A\nno diagram\n") + self.build() + self.assertNotIn("mermaid-lib", self.html()) + self.assertLess(len(self.html()), 300000) + put(self.tmp, "analysis/s/ASSESSMENT.md", "# A\n\n```mermaid\ngraph TD\n A-->B\n```\n") + self.build() + scripts = Scripts(self.html()).found + lib = next(s for s in scripts if s["attrs"].get("id") == "mermaid-lib") + with open(MERMAID, encoding="utf-8") as fh: + original = fh.read() + self.assertEqual(lib["text"].replace("<\\/script", "</script").replace("<\\!--", "<!--"), original) + os.remove(os.path.join(self.tmp, "analysis", "s", "ASSESSMENT.md")) + put(self.tmp, "analysis/s/x.mmd", "graph TD\n A-->B\n") + self.build() + self.assertIn("mermaid-lib", self.html()) + + def test_size_cap_says_what_was_left_out(self): + for name in ("ASSESSMENT.md", "MODERNIZATION_BRIEF.md", "DATA_OBJECTS.md"): + put(self.tmp, "analysis/s/" + name, ("line of text that is long enough to count\n" * 80000)) + self.build() + data = page_data(self.html()) + notes = "\n".join(json.dumps(p) for p in data["sections"][0]["parts"]) + self.assertIn("report size limit", notes) + embedded = sum(len(p["text"]) for s in data["sections"] for p in s["parts"] if p["t"] == "md") + self.assertLessEqual(embedded, br.TOTAL_CAP) + + def test_sections_follow_the_workflow_order_and_only_exist_when_found(self): + a = "analysis/s/" + for name in ("EQUIVALENCE.json", "SECURITY_FINDINGS.md", "MODERNIZATION_BRIEF.md", "ASSESSMENT.md", "PREFLIGHT.md", "DELTA_CATALOG.md", "AI_NATIVE_SPEC.md"): + put(self.tmp, a + name, "{}" if name.endswith(".json") else "# " + name) + put(self.tmp, "modernized/s-reimagined/svc/README.md", "# svc") + self.build() + data = page_data(self.html()) + self.assertEqual([s["id"] for s in data["sections"]], ["overview", "assessment", "brief", "security", "delta", "spec", "build", "equivalence"]) + steps = {x["key"]: x["done"] for x in data["glance"]["steps"]} + self.assertEqual(steps, {"preflight": True, "assess": True, "map": False, "rules": False, "brief": True, "build": True, "harden": True}) + self.assertEqual(data["glance"]["track"]["label"], "reimagine") + + def test_track_follows_the_newest_track_artifact(self): + a = "analysis/s/" + put(self.tmp, a + "ASSESSMENT.md", "x") + put(self.tmp, a + "BASELINE.md", "x") + put(self.tmp, "modernized/s/mod/TRANSFORMATION_NOTES.md", "x") + self.build() + self.assertEqual(page_data(self.html())["glance"]["track"]["label"], "rewrite") + past = os.path.getmtime(os.path.join(self.tmp, "modernized", "s", "mod", "TRANSFORMATION_NOTES.md")) + 50 + put(self.tmp, a + "DELTA_CATALOG.md", "x") + os.utime(os.path.join(self.tmp, "analysis", "s", "DELTA_CATALOG.md"), (past, past)) + self.build() + self.assertEqual(page_data(self.html())["glance"]["track"]["label"], "same-stack uplift") + + def test_topology_link_is_relative_and_the_map_is_not_embedded(self): + put(self.tmp, "analysis/s/TOPOLOGY.html", "<html>" + "x" * 5000 + "</html>") + self.build() + data = page_data(self.html()) + link = next(p for s in data["sections"] for p in s["parts"] if p["t"] == "link") + self.assertEqual(os.path.normpath(os.path.join(os.path.dirname(self.out), link["href"])), os.path.join(self.tmp, "analysis", "s", "TOPOLOGY.html")) + self.assertNotIn("xxxxxxxxxx", self.html()) + + def test_report_shows_what_compare_py_wrote(self): + eq_dir = os.path.join(self.tmp, "analysis", "s", "equivalence") + put(eq_dir, "legacy/a.out", "same") + put(eq_dir, "new/a.out", "same") + put(eq_dir, "legacy/b.out", "one") + put(eq_dir, "new/b.out", "two") + cases = {"system": "s", "cases": [{"id": "A", "legacy": "legacy/a.out", "new": "new/a.out"}, {"id": "B", "legacy": "legacy/b.out", "new": "new/b.out"}]} + put(eq_dir, "cases.json", json.dumps(cases)) + target = os.path.join(self.tmp, "analysis", "s", "EQUIVALENCE.json") + cmp.main([os.path.join(eq_dir, "cases.json"), "--out", target, "--quiet"]) + self.build() + data = page_data(self.html()) + eq = data["glance"]["equivalence"] + self.assertEqual(eq["state"], "red") + self.assertEqual((eq["tally"]["same"], eq["tally"]["differs"], eq["tally"]["executed"]), (1, 1, 2)) + section = next(s for s in data["sections"] if s["id"] == "equivalence")["parts"][0]["eq"] + self.assertEqual(section["cases"][1]["firstDiff"]["line"], 1) + self.assertEqual(section["cases"][1]["legacyPath"], "equivalence/legacy/b.out") + cases["cases"].pop() + put(eq_dir, "cases.json", json.dumps(cases)) + cmp.main([os.path.join(eq_dir, "cases.json"), "--out", target, "--quiet"]) + self.build() + self.assertEqual(page_data(self.html())["glance"]["equivalence"]["state"], "green") + + def test_a_symlinked_output_path_is_refused_and_nothing_is_written_through_it(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "x") + target = put(self.tmp, "elsewhere/real.html", "ORIGINAL") + os.makedirs(os.path.dirname(self.out)) + make_symlink(self, target, self.out) + code, out, err = self.build() + self.assertEqual((code, out), (1, "")) + self.assertEqual(len(err.strip().splitlines()), 1) + self.assertIn("symbolic link", err) + with open(target) as fh: + self.assertEqual(fh.read(), "ORIGINAL") + self.assertEqual(os.listdir(os.path.dirname(target)), ["real.html"]) + self.assertEqual(os.listdir(os.path.dirname(self.out)), ["REPORT.html"]) + + def test_a_symlinked_output_folder_is_refused(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "x") + real = os.path.join(self.tmp, "real") + os.makedirs(real) + make_symlink(self, real, os.path.join(self.tmp, "linked")) + code, _, err = run_main(br.main, ["s", "--workspace", self.tmp, "--out", os.path.join(self.tmp, "linked", "REPORT.html")]) + self.assertEqual(code, 1) + self.assertIn("symbolic link", err) + self.assertEqual(os.listdir(real), []) + + def test_a_failed_write_leaves_no_temp_file_behind(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "x") + with mock.patch.object(br.os, "replace", side_effect=OSError("disk full")): + code, _, err = self.build() + self.assertEqual(code, 1) + self.assertEqual(len(err.strip().splitlines()), 1) + self.assertEqual(os.listdir(os.path.dirname(self.out)), []) + + @unittest.skipIf(os.name == "nt", "POSIX permissions") + def test_the_report_gets_the_permissions_a_normal_file_would(self): + put(self.tmp, "analysis/s/PREFLIGHT.md", "x") + umask = os.umask(0o022) + os.umask(umask) + self.build() + self.assertEqual(stat.S_IMODE(os.stat(self.out).st_mode), 0o666 & ~umask) + + +class Template(unittest.TestCase): + @classmethod + def setUpClass(cls): + with open(TEMPLATE, encoding="utf-8") as fh: + cls.text = fh.read() + cls.css = re.search(r"<style>(.*?)</style>", cls.text, re.S).group(1) + cls.app = re.search(r'<script id="app">(.*?)</script>', cls.text, re.S).group(1) + + def test_no_external_urls_and_no_dangerous_apis(self): + self.assertNotRegex(self.text, r"https?://") + self.assertNotRegex(self.text, r"(?i)(?:src|href|action)\s*=\s*[\"']?\s*//") + self.assertNotRegex(self.css, r"@import|url\(") + for word in ("innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "eval(", "new Function", "setTimeout(\"", "fetch(", "XMLHttpRequest", "WebSocket"): + self.assertNotIn(word, self.app, word) + self.assertNotRegex(self.text, r"(?i)\son[a-z]+\s*=") + self.assertEqual(len(re.findall(r"@@(CSP|DATA|MERMAID)@@", self.text)), 3) + self.assertNotIn("@@", self.app) + + def test_theme_and_layout_contract(self): + root = re.search(r":root\{(.*?)\}", self.css, re.S).group(1) + tokens = set(re.findall(r"--([a-z-]+):", root)) + media = re.search(r"@media \(prefers-color-scheme:dark\)\{:root:not\(\[data-theme=\"light\"\]\)\{(.*?)\}\}", self.css, re.S).group(1) + forced = re.search(r":root\[data-theme=\"dark\"\]\{(.*?)\}", self.css, re.S).group(1) + self.assertEqual(set(re.findall(r"--([a-z-]+):", media)) - tokens, set()) + self.assertEqual(re.findall(r"--([a-z-]+):[^;]*", media), re.findall(r"--([a-z-]+):[^;]*", forced)) + self.assertRegex(re.search(r"body\{([^}]*)\}", self.css).group(1), r"background:var\(--bg\)") + self.assertIn("system-ui", self.css) + self.assertIn("width=device-width", self.text) + self.assertIn("@media print", self.css) + self.assertIn(":focus-visible", self.css) + self.assertRegex(self.css, r"\.wrap\{[^}]*padding:0 16px") + + def test_every_text_colour_pair_meets_4_5_to_1(self): + def parse(block): + return dict(re.findall(r"--([a-z-]+):(#[0-9a-fA-F]{3,6})", block)) + + def lum(hexcolor): + h = hexcolor.lstrip("#") + h = "".join(c * 2 for c in h) if len(h) == 3 else h + chan = [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)] + lin = [c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 for c in chan] + return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2] + + def ratio(a, b): + hi, lo = sorted((lum(a), lum(b)), reverse=True) + return (hi + 0.05) / (lo + 0.05) + + light = parse(re.search(r":root\{(.*?)\}", self.css, re.S).group(1)) + dark = dict(light, **parse(re.search(r":root\[data-theme=\"dark\"\]\{(.*?)\}", self.css, re.S).group(1))) + pairs = [("text", "bg"), ("text", "surface"), ("muted", "bg"), ("muted", "surface"), ("muted", "code"), ("text", "code"), ("link", "surface"), ("link", "bg"), + ("link", "code"), ("ok", "ok-bg"), ("bad", "bad-bg"), ("warn", "warn-bg"), ("info", "info-bg"), ("flat", "flat-bg"), ("hit-text", "hit"), + ("text", "flat-bg"), ("text", "info-bg"), ("muted", "flat-bg")] + for name, palette in (("light", light), ("dark", dark)): + for fg, bg in pairs: + self.assertGreaterEqual(ratio(palette[fg], palette[bg]), 4.5, "%s: %s on %s" % (name, fg, bg)) + self.assertGreaterEqual(ratio("#1a1f27", light["paper"]), 4.5) + for name, palette in (("light", light), ("dark", dark)): + self.assertGreaterEqual(ratio(palette["focus"], palette["bg"]), 3, name) + self.assertGreaterEqual(ratio(palette["focus"], palette["surface"]), 3, name) + + +NODE = shutil.which("node") +LINK_CASES = { # markdown -> the href it must produce, or None when it must stay plain text + "[x](javascript:alert(1))": None, "[x](data:text/html,x)": None, "[x](file:///etc/passwd)": None, "[x](JaVaScRiPt:x)": None, "[x](java script:x)": None, "[x](javascript:alert(1))": None, "[x](javascript:alert(1))": None, + "[x](https://example.com/a?b=1)": "https://example.com/a?b=1", "[x](mailto:a@b.c)": "mailto:a@b.c", "[x](#anchor)": "#anchor", + "[x](./relative/path.md)": "./relative/path.md", "[x](../up/README.md#top)": "../up/README.md#top", +} +JS_INPUTS = [ + "<script>alert(1)</script>", "</script><script>alert(1)</script>", "<img src=x onerror=alert(1)>", "<!-- <!--", '<a href="javascript:alert(1)">x</a>', + "[x](javascript:alert(1))", "[x](JavaScript:alert(1))", "[x](java\tscript:alert(1))", "[x](" + chr(1) + "javascript:alert(1))", "[x]( javascript:alert(1))", + "[x](data:text/html;base64,PHNjcmlwdD4=)", "[x](//evil.example)", "[x](/\\evil.example)", "[x](vbscript:msgbox(1))", "[x](file:///etc/passwd)", + "[x](javascript:alert(1))", "[x](%6Aavascript:alert(1))", "[x](" + LS + "javascript:alert(1))", "[x](\u00a0javascript:alert(1))", ")", + "| <b onmouseover=alert(1)>x</b> | y |\n|---|---|\n| <img src=x onerror=alert(2)> | z |", "### RULE-001: `<b>title</b>` <img src=x>", + "`<script>`", "**<img src=x onerror=1>** _<b>_", "- [ ] <b>a</b>\n- [x] *b*\n - nested <i>c</i>", "> <script>\n> x", + "```js\n<script>alert(1)</script>\n```", "~~~\n</script>\n~~~", "```mermaid\ngraph TD; A-->B\n```", "a" * 200000, "*" * 200000, "[" * 100000, "`" * 100000, + "_" * 100000, "|" * 100000, "- " * 50000, "> " * 20000 + "x", "\n".join(" " * (i * 2) + "- x" for i in range(300)), "#" * 100000, "[a](" + "b" * 100000 + ")", + "\n".join("| " + "c | " * 200 for _ in range(50)), "*a " * 60000, "**a " * 60000, "[a " * 60000, "`a " * 60000, +] + list(LINK_CASES) +SAFE_URLS = ["https://example.com/a?b=1&c=2", "https://example.com/?q=a&b=c#frag", "http://x.y", "HTTPS://X.Y", "mailto:a@b.c", "../x/y.md#z", "#anchor", "README.md", "a/b:c", "TOPOLOGY.html", "./p:q", "x.md#a:b"] +BAD_URLS = ["java script:x", "javascript:alert(1)", "javascript:1", "a:b", "x&y", "javascript:alert(1)", "JavaScript:alert(1)", " javascript:alert(1)", "java\tscript:alert(1)", "java\nscript:alert(1)", chr(1) + "javascript:alert(1)", "data:text/html,x", + "//evil.example", "/\\evil.example", "\\\\evil", "/abs/path", "vbscript:x", "file:///etc/passwd", "C:\\x", "a:b", chr(0xA0) + "javascript:1", LS + "javascript:1", + chr(0xFEFF) + "javascript:1", "jav" + chr(0x200B) + "ascript:1", "", "x" * 3000] +NODE_HARNESS = r""" +const fs = require('fs'), vm = require('vm'); +const tpl = fs.readFileSync(process.env.TEMPLATE, 'utf8'); +const core = /\/\* core:start[^\n]*\n([\s\S]*?)\/\* core:end \*\//.exec(tpl)[1]; +class Text { constructor(t) { this.text = String(t); } } +class El { constructor(t) { this.tag = t; this.attrs = {}; this.kids = []; } + setAttribute(k, v) { this.attrs[k] = String(v); } appendChild(c) { this.kids.push(c); return c; } } +const ctx = { document: { createElement: t => new El(t), createTextNode: t => new Text(t) } }; +vm.createContext(ctx); +const api = vm.runInContext('(function(){"use strict";' + core + ';return {safeUrl:safeUrl,md:md,ruleCard:ruleCard,inline:inline};})()', ctx); +function walk(n, acc) { + if (n instanceof Text) { acc.text += n.text; return; } + acc.tags.add(n.tag); Object.keys(n.attrs).forEach(k => { acc.attrs.add(k); if (k === 'href') acc.hrefs.push(n.attrs[k]); }); + n.kids.forEach(c => walk(c, acc)); +} +const input = JSON.parse(fs.readFileSync(0, 'utf8')), out = { urls: input.urls.map(u => api.safeUrl(u)), docs: [] }; +for (const src of input.docs) { + const t0 = Date.now(), acc = { tags: new Set(), attrs: new Set(), hrefs: [], text: '' }; + api.md(src, 3).forEach(n => walk(n, acc)); + out.docs.push({ ms: Date.now() - t0, tags: [...acc.tags], attrs: [...acc.attrs], hrefs: acc.hrefs, text: acc.text.slice(0, 5000) }); +} +const card = { id: 'RULE-1', heading: 'RULE-1: <b>x</b>', title: '<img src=x onerror=1>`a`', p: 'P0', conf: 'High', cat: '<i>', cites: ['<b>a.cbl:1</b>'], defect: true, body: '**x** <script>1</script>' }; +const acc = { tags: new Set(), attrs: new Set(), hrefs: [], text: '' }; +walk(api.ruleCard(card, 'confirmed'), acc); +out.card = { tags: [...acc.tags], attrs: [...acc.attrs], text: acc.text }; +process.stdout.write(JSON.stringify(out)); +""" + + +@unittest.skipUnless(NODE, "node is not installed") +class TemplateScript(unittest.TestCase): + @classmethod + def setUpClass(cls): + proc = subprocess.run([NODE, "-e", NODE_HARNESS], input=json.dumps({"urls": SAFE_URLS + BAD_URLS, "docs": JS_INPUTS}), capture_output=True, text=True, + env=dict(os.environ, TEMPLATE=TEMPLATE), timeout=300) + assert proc.returncode == 0, proc.stderr + cls.out = json.loads(proc.stdout) + + def test_the_page_script_parses(self): + with open(TEMPLATE, encoding="utf-8") as src, tempfile.NamedTemporaryFile("w", suffix=".js", delete=False, encoding="utf-8") as fh: + fh.write(re.search(r'<script id="app">(.*?)</script>', src.read(), re.S).group(1)) + self.addCleanup(os.unlink, fh.name) + self.assertEqual(subprocess.run([NODE, "--check", fh.name], capture_output=True, text=True).returncode, 0) + + def test_link_allowlist(self): + urls = self.out["urls"] + for url, got in zip(SAFE_URLS, urls[:len(SAFE_URLS)]): + self.assertIsNotNone(got, url) + for url, got in zip(BAD_URLS, urls[len(SAFE_URLS):]): + self.assertIsNone(got, repr(url)) + + def test_hostile_markdown_becomes_text_never_elements(self): + allowed_tags = {"p", "h3", "h4", "h5", "h6", "ul", "ol", "li", "code", "pre", "strong", "em", "del", "a", "br", "hr", "blockquote", "table", "thead", "tbody", "tr", + "th", "td", "div", "span"} + allowed_attrs = {"href", "rel", "target", "referrerpolicy", "id", "class", "role", "tabindex", "aria-label", "scope"} + for src, doc in zip(JS_INPUTS, self.out["docs"]): + label = src[:50] + self.assertLessEqual(set(doc["tags"]), allowed_tags, label) + self.assertLessEqual(set(doc["attrs"]), allowed_attrs, label) + self.assertLess(doc["ms"], 5000, label) + for href in doc["hrefs"]: + stripped = re.sub(r"[\x00-\x20]", "", href).lower() + self.assertRegex(stripped, r"^(https?://|mailto:|#|[^:/?#\\]*(?:[/?#]|$))", href) + first = self.out["docs"][0] + self.assertIn("<script>alert(1)</script>", first["text"]) + self.assertEqual(self.out["docs"][2]["tags"], ["p"]) + self.assertIn("[x](javascript:alert(1))", self.out["docs"][5]["text"]) + self.assertEqual(self.out["docs"][5]["hrefs"], []) + table = self.out["docs"][20] + self.assertIn("<b onmouseover=alert(1)>x</b>", table["text"]) + self.assertNotIn("img", table["tags"]) + + def test_links_fail_closed_and_safe_ones_stay_links(self): + docs = dict(zip(JS_INPUTS, self.out["docs"])) + for source, href in LINK_CASES.items(): + doc = docs[source] + if href is None: + self.assertEqual(doc["hrefs"], [], source) + self.assertNotIn("a", doc["tags"], source) + self.assertIn(source, doc["text"], source) + else: + self.assertEqual(doc["hrefs"], [href], source) + self.assertIn("a", doc["tags"], source) + self.assertEqual(doc["text"], "x", source) + + def test_rule_card_renders_hostile_fields_as_text(self): + card = self.out["card"] + self.assertLessEqual(set(card["tags"]), {"article", "span", "h4", "div", "p", "strong"}) + self.assertLessEqual(set(card["attrs"]), {"class", "id", "data-p", "data-d", "aria-label"}) + self.assertIn("<img src=x onerror=1>`a`", card["text"]) + self.assertIn("<b>a.cbl:1</b>", card["text"]) + + +class Vendored(unittest.TestCase): + def test_mermaid_matches_the_recorded_digest_and_license(self): + with open(os.path.join(PLUGIN, "assets", "vendor", "LICENSE-mermaid.txt"), encoding="utf-8") as fh: + lic = fh.read() + with open(MERMAID, "rb") as fh: + raw = fh.read() + self.assertIn("Copyright (c) 2014 - 2022 Knut Sveidqvist", lic) + self.assertIn("MIT License", lic) + self.assertIn(hashlib.sha256(raw).hexdigest(), lic) + self.assertIn("mermaid@11.17.2", lic) + self.assertIn(str(len(raw)), lic) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/code-modernization/scripts/tests/test_rules_tools.py b/plugins/code-modernization/scripts/tests/test_rules_tools.py index 4551209f..f0bbc391 100644 --- a/plugins/code-modernization/scripts/tests/test_rules_tools.py +++ b/plugins/code-modernization/scripts/tests/test_rules_tools.py @@ -44,11 +44,13 @@ class ShardTests(unittest.TestCase): self.assertNotIn('tests/t.pl', json.dumps(shards)) self.assertTrue(all(not f.startswith('legacy/') for s in shards for f in s['files'])) - def test_source_marker_moves_the_tree_and_files_stay_relative_to_it(self): + def test_a_symlinked_source_is_followed_and_files_stay_relative_to_it(self): with tempfile.TemporaryDirectory() as ws, tempfile.TemporaryDirectory() as elsewhere: write(elsewhere, 'src/a.cbl', 'a\n' * 50) - write(ws, 'analysis/big/SOURCE', elsewhere + '\n') - self.assertEqual(run('make_shards.py', 'big', '--workspace', ws).returncode, 0) + os.makedirs(os.path.join(ws, 'legacy')) + os.symlink(elsewhere, os.path.join(ws, 'legacy', 'big')) + done = run('make_shards.py', 'big', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) shards = load(os.path.join(ws, 'analysis/big/extract-rules.modules.json')) self.assertEqual(shards[0]['files'], ['src/a.cbl']) @@ -67,6 +69,59 @@ class ShardTests(unittest.TestCase): self.assertEqual(run('make_shards.py', 's', 'C*', '--workspace', ws).returncode, 0) self.assertEqual(run('make_shards.py', 's', 'nothing*', '--workspace', ws).returncode, 1) + def test_links_and_paths_that_leave_the_source_are_not_shards(self): + with tempfile.TemporaryDirectory() as ws, tempfile.TemporaryDirectory() as outside: + write(ws, 'legacy/s/ok.pl', 'a\n' * 5) + write(outside, 'secret.pl', 'not part of the system\n') + os.symlink(os.path.join(outside, 'secret.pl'), os.path.join(ws, 'legacy/s/link.pl')) + self.assertEqual(run('make_shards.py', 's', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for s in shards for f in s['files']], ['ok.pl']) + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D', 'id': 'd', 'children': [ + {'kind': 'module', 'id': 'A', 'name': 'A', 'file': 'ok.pl', 'loc': 500}, + {'kind': 'module', 'id': 'B', 'name': 'B', 'file': '../../../etc/hosts', 'loc': 500}, + {'kind': 'module', 'id': 'C', 'name': 'C', 'file': 'link.pl', 'loc': 500}]}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for s in shards for f in s['files']], ['ok.pl']) + self.assertIn('outside the source directory', done.stdout) + + def test_a_link_to_the_home_directory_or_root_is_refused(self): + with tempfile.TemporaryDirectory() as ws: + os.makedirs(os.path.join(ws, 'legacy')) + for broad in (os.path.expanduser('~'), '/', '/usr'): + link = os.path.join(ws, 'legacy', 's') + if os.path.islink(link): + os.unlink(link) + os.symlink(broad, link) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 1, broad) + self.assertIn('too broad', done.stderr) + + def test_a_plain_name_matches_what_lies_beneath_it(self): + with tempfile.TemporaryDirectory() as ws: + write(ws, 'legacy/s/jetty-util/src/A.java', 'a\n' * 5) + write(ws, 'legacy/s/jetty-util-ajax/src/B.java', 'a\n' * 5) + write(ws, 'legacy/s/other/C.java', 'a\n' * 5) + self.assertEqual(run('make_shards.py', 's', 'jetty-util', '--workspace', ws).returncode, 0) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual([f for sh in shards for f in sh['files']], ['jetty-util/src/A.java']) + + def test_a_map_whose_modules_share_one_directory_falls_back_to_the_tree(self): + with tempfile.TemporaryDirectory() as ws: + for name in ('a', 'b'): + write(ws, f'legacy/s/pkg/{name}/X.java', 'a\n' * 50) + children = [{'kind': 'module', 'id': f'pkg/{n}', 'name': f'pkg/{n}', 'file': 'pkg', 'loc': 900} for n in ('a', 'b')] + topology = {'root': {'kind': 'system', 'id': 'sys', 'children': [{'kind': 'domain', 'name': 'D', 'id': 'd', 'children': children}]}} + write(ws, 'analysis/s/topology.json', json.dumps(topology)) + done = run('make_shards.py', 's', '--workspace', ws) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn('cannot be sharded by module', done.stdout) + shards = load(os.path.join(ws, 'analysis/s/extract-rules.modules.json')) + self.assertEqual(sorted(f for sh in shards for f in sh['files']), ['pkg/a/X.java', 'pkg/b/X.java']) + def test_missing_source_says_what_to_do(self): with tempfile.TemporaryDirectory() as ws: done = run('make_shards.py', 'nope', '--workspace', ws) |
