init
This commit is contained in:
commit
303438d206
217 files changed
+66681
No files matched your search
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Back up explicitly approved scalar JSON settings, never whole config files."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
MAX_FILE = 1024 * 1024
|
||||
SENSITIVE = re.compile(r"password|passwd|pwd|secret|token|credential|auth|cookie|"
|
||||
r"privatekey|apikey|accesskey|session|dsn|url|uri|connectionstring")
|
||||
|
||||
|
||||
def sensitive_key(key):
|
||||
return bool(SENSITIVE.search(re.sub(r"[^a-z0-9]", "", key.lower())))
|
||||
|
||||
|
||||
def unique_object(pairs):
|
||||
obj = {}
|
||||
for key, value in pairs:
|
||||
if key in obj:
|
||||
raise ValueError("duplicate JSON key")
|
||||
obj[key] = value
|
||||
return obj
|
||||
|
||||
|
||||
def reject_constant(value):
|
||||
raise ValueError("non-finite JSON number")
|
||||
|
||||
|
||||
def read_json(path):
|
||||
if not stat.S_ISREG(path.lstat().st_mode):
|
||||
raise ValueError("expected regular JSON file")
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(MAX_FILE + 1)
|
||||
if len(data) > MAX_FILE:
|
||||
raise ValueError("JSON file exceeds 1 MiB")
|
||||
return json.loads(data, object_pairs_hook=unique_object, parse_constant=reject_constant)
|
||||
|
||||
|
||||
def source_path(root, relative):
|
||||
if not isinstance(relative, str) or "\\" in relative or ":" in relative:
|
||||
raise ValueError("expected relative POSIX path")
|
||||
parts = relative.split("/")
|
||||
if any(part in {"", ".", ".."} for part in parts):
|
||||
raise ValueError("empty or traversal path component")
|
||||
rel = PurePosixPath(relative)
|
||||
if rel.suffix != ".json" or len(parts) > 16:
|
||||
raise ValueError("only relative JSON paths are supported")
|
||||
current = root
|
||||
for part in parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
raise ValueError("source symlinks are not supported")
|
||||
return current
|
||||
|
||||
|
||||
def project_settings(source, allowed):
|
||||
if not isinstance(allowed, list) or not 1 <= len(allowed) <= 256:
|
||||
raise ValueError("allow must contain 1..256 key paths")
|
||||
output, seen = {}, set()
|
||||
for keys in allowed:
|
||||
if (not isinstance(keys, list) or not 1 <= len(keys) <= 16
|
||||
or any(not isinstance(k, str) or not k or len(k) > 128 for k in keys)):
|
||||
raise ValueError("each key path must be a nonempty list of strings")
|
||||
if any(sensitive_key(k) for k in keys):
|
||||
raise ValueError("sensitive field name is not allowed")
|
||||
key_tuple = tuple(keys)
|
||||
if key_tuple in seen:
|
||||
raise ValueError("duplicate key path")
|
||||
seen.add(key_tuple)
|
||||
value = source
|
||||
for key in keys:
|
||||
if not isinstance(value, dict) or key not in value:
|
||||
raise ValueError("selected field is missing")
|
||||
value = value[key]
|
||||
if isinstance(value, (dict, list)):
|
||||
raise ValueError("select scalar leaves, not entire objects or lists")
|
||||
# Never implicitly retain an unselected sibling or nested value.
|
||||
target = output
|
||||
for key in keys[:-1]:
|
||||
target = target.setdefault(key, {})
|
||||
target[keys[-1]] = value
|
||||
return output
|
||||
|
||||
|
||||
def backup(root, manifest, output):
|
||||
root = root.resolve(strict=True)
|
||||
if not root.is_dir():
|
||||
raise ValueError("root must be a directory")
|
||||
if not isinstance(manifest, dict) or set(manifest) != {"files"}:
|
||||
raise ValueError("manifest needs only the files field")
|
||||
files = manifest["files"]
|
||||
if not isinstance(files, list) or not 1 <= len(files) <= 64:
|
||||
raise ValueError("files must contain 1..64 entries")
|
||||
prepared, seen = [], set()
|
||||
for entry in files:
|
||||
if not isinstance(entry, dict) or set(entry) != {"path", "allow"}:
|
||||
raise ValueError("file entry needs path and allow")
|
||||
source = source_path(root, entry["path"])
|
||||
if entry["path"] in seen:
|
||||
raise ValueError("duplicate source path")
|
||||
seen.add(entry["path"])
|
||||
selected = project_settings(read_json(source), entry["allow"])
|
||||
payload = (json.dumps(selected, ensure_ascii=True, indent=2, allow_nan=False) + "\n").encode()
|
||||
prepared.append((entry["path"], payload))
|
||||
|
||||
# Validate and sanitize every source before creating any backup files.
|
||||
output.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
session = Path(tempfile.mkdtemp(prefix="config-", dir=output))
|
||||
try:
|
||||
session.chmod(0o700)
|
||||
index = {"format": 1, "kind": "selected-settings", "files": []}
|
||||
for number, (source, payload) in enumerate(prepared, 1):
|
||||
name = f"settings-{number:03d}.json"
|
||||
dest = session / name
|
||||
with dest.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
dest.chmod(0o600)
|
||||
index["files"].append({"source": source, "backup": name,
|
||||
"sha256": hashlib.sha256(payload).hexdigest()})
|
||||
index_path = session / "manifest.json"
|
||||
index_path.write_text(json.dumps(index, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
|
||||
index_path.chmod(0o600)
|
||||
except BaseException:
|
||||
shutil.rmtree(session)
|
||||
raise
|
||||
return session
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("manifest", type=Path)
|
||||
parser.add_argument("--root", required=True, type=Path, help="directory containing source configs")
|
||||
parser.add_argument("--output", type=Path, default=Path("artifacts/config-backups"))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
session = backup(args.root, read_json(args.manifest), args.output)
|
||||
print(session)
|
||||
return 0
|
||||
except (OSError, ValueError, TypeError, RecursionError) as exc:
|
||||
print(f"config backup: {type(exc).__name__}; no source values printed", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
"""Small shared helpers; Python 3.10+, standard library only."""
|
||||
import argparse
|
||||
import math
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def opener():
|
||||
# Direct connections and no redirects: do not forward farm credentials.
|
||||
return build_opener(ProxyHandler({}), NoRedirect())
|
||||
|
||||
|
||||
def http_url(value):
|
||||
p = urlsplit(value)
|
||||
if p.scheme not in {"http", "https"} or not p.hostname:
|
||||
raise ValueError("expected an absolute http(s) URL")
|
||||
if p.username is not None or p.password is not None or p.fragment:
|
||||
raise ValueError("userinfo and fragments are not allowed in URLs")
|
||||
_ = p.port # Validate malformed/out-of-range ports.
|
||||
return value
|
||||
|
||||
|
||||
def positive_float(value):
|
||||
n = float(value)
|
||||
if not math.isfinite(n) or n <= 0:
|
||||
raise argparse.ArgumentTypeError("must be finite and greater than zero")
|
||||
return n
|
||||
|
||||
|
||||
def flag_pattern(value):
|
||||
pattern = re.compile(value)
|
||||
if pattern.search("") is not None:
|
||||
raise ValueError("flag regex must not match the empty string")
|
||||
return pattern
|
||||
|
||||
|
||||
def limited_read(response, limit=1024 * 1024):
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError(f"response exceeds {limit} bytes")
|
||||
return data
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare two saved defense_scan JSON reports offline; never open source paths."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
|
||||
|
||||
MAX_REPORT_BYTES = 32 * 1024 * 1024
|
||||
MAX_FINDINGS = 100000
|
||||
SCOPE_SCHEMA = "durkahelper.scanner-scope.v2"
|
||||
LEGACY_SCOPE_SCHEMA = "durkahelper.scanner-scope.v1"
|
||||
PATH_SEMANTICS = "root-relative-posix.v1"
|
||||
NOTE = ("Matches exact path, line and rule ID without comparing source code. Moving lines creates a "
|
||||
"new/not-observed pair. A disappearing signal does not prove a fix. "
|
||||
"A clean comparison requires identical verified scopes.")
|
||||
|
||||
|
||||
def file_identity(metadata):
|
||||
return (metadata.st_dev, metadata.st_ino, metadata.st_mode, metadata.st_size,
|
||||
metadata.st_mtime_ns, getattr(metadata, "st_ctime_ns", 0))
|
||||
|
||||
|
||||
def unique_object(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError("duplicate JSON key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _canonical_json(value):
|
||||
return json.dumps(value, ensure_ascii=True, sort_keys=True,
|
||||
separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def _timestamp(value):
|
||||
if not isinstance(value, str) or len(value) > 64 or not value.endswith("Z"):
|
||||
raise ValueError("invalid timestamp")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
except ValueError as exc:
|
||||
raise ValueError("invalid timestamp") from exc
|
||||
if parsed.utcoffset() is None or parsed.utcoffset().total_seconds() != 0:
|
||||
raise ValueError("invalid timestamp")
|
||||
return value
|
||||
|
||||
|
||||
def _positive_integer(value):
|
||||
if type(value) is not int or not 1 <= value <= 2**63 - 1:
|
||||
raise ValueError("invalid scope integer")
|
||||
return value
|
||||
|
||||
|
||||
def validate_scope(scope):
|
||||
expected = {"schema", "root", "rules_sha256", "exclude", "limits",
|
||||
"path_semantics", "sha256"}
|
||||
if not isinstance(scope, dict):
|
||||
raise ValueError("invalid scope")
|
||||
if scope.get("schema") == SCOPE_SCHEMA:
|
||||
expected |= {"semantic_revision", "context_sha256"}
|
||||
if set(scope) != expected:
|
||||
raise ValueError("invalid scope")
|
||||
if (not isinstance(scope["schema"], str)
|
||||
or scope["schema"] not in {SCOPE_SCHEMA, LEGACY_SCOPE_SCHEMA}
|
||||
or scope["path_semantics"] != PATH_SEMANTICS):
|
||||
raise ValueError("unsupported scope")
|
||||
if not isinstance(scope["root"], str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", scope["root"]):
|
||||
raise ValueError("invalid root identity")
|
||||
if not isinstance(scope["rules_sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", scope["rules_sha256"]):
|
||||
raise ValueError("invalid rules scope")
|
||||
exclude = scope["exclude"]
|
||||
if (not isinstance(exclude, list) or len(exclude) > 10000
|
||||
or any(not isinstance(item, str) or len(item) > 4096 or "\x00" in item
|
||||
for item in exclude)
|
||||
or exclude != sorted(set(exclude))):
|
||||
raise ValueError("invalid exclusions scope")
|
||||
limits = scope["limits"]
|
||||
if not isinstance(limits, dict) or set(limits) != {"max_bytes", "max_files", "max_findings"}:
|
||||
raise ValueError("invalid limits scope")
|
||||
for field in ("max_bytes", "max_files", "max_findings"):
|
||||
_positive_integer(limits[field])
|
||||
if not isinstance(scope["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", scope["sha256"]):
|
||||
raise ValueError("invalid scope digest")
|
||||
sanitized = {
|
||||
"schema": scope["schema"],
|
||||
"root": scope["root"],
|
||||
"rules_sha256": scope["rules_sha256"],
|
||||
"exclude": list(exclude),
|
||||
"limits": {field: limits[field] for field in
|
||||
("max_bytes", "max_files", "max_findings")},
|
||||
"path_semantics": PATH_SEMANTICS,
|
||||
}
|
||||
if scope["schema"] == SCOPE_SCHEMA:
|
||||
if (scope["semantic_revision"] not in {"bounded-source-signals.v2", "bounded-source-signals.v3"}
|
||||
or not isinstance(scope["context_sha256"], str)
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", scope["context_sha256"])):
|
||||
raise ValueError("invalid scanner semantics or context digest")
|
||||
sanitized.update(semantic_revision=scope["semantic_revision"], context_sha256=scope["context_sha256"])
|
||||
expected_digest = hashlib.sha256(_canonical_json(sanitized)).hexdigest()
|
||||
if scope["sha256"] != expected_digest:
|
||||
raise ValueError("scope digest mismatch")
|
||||
sanitized["sha256"] = expected_digest
|
||||
return sanitized
|
||||
|
||||
|
||||
def load_report(filename, max_bytes=MAX_REPORT_BYTES):
|
||||
requested = Path(os.path.abspath(filename))
|
||||
requested_metadata = requested.lstat()
|
||||
if stat.S_ISLNK(requested_metadata.st_mode):
|
||||
raise ValueError("symlink report")
|
||||
# Resolve ordinary symlinked ancestors (notably macOS /tmp -> /private/tmp)
|
||||
# before the no-follow leaf open. This prevents an ancestor swap from
|
||||
# redirecting the descriptor while preserving the leaf-symlink boundary.
|
||||
# Path.resolve() may require extra handle permissions on Windows. The
|
||||
# macOS/Linux branch canonicalizes ancestors; Windows retains the absolute
|
||||
# path after the explicit leaf-symlink check.
|
||||
path = requested if os.name == "nt" else requested.parent.resolve(strict=True) / requested.name
|
||||
canonical_metadata = path.lstat()
|
||||
if stat.S_ISLNK(canonical_metadata.st_mode):
|
||||
raise ValueError("symlink report")
|
||||
if ((requested_metadata.st_dev, requested_metadata.st_ino,
|
||||
stat.S_IFMT(requested_metadata.st_mode)) !=
|
||||
(canonical_metadata.st_dev, canonical_metadata.st_ino,
|
||||
stat.S_IFMT(canonical_metadata.st_mode))):
|
||||
raise ValueError("report changed before reading")
|
||||
flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) |
|
||||
getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
||||
fd = os.open(path, flags)
|
||||
try:
|
||||
metadata = os.fstat(fd)
|
||||
if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > max_bytes:
|
||||
raise ValueError("report is not a bounded regular file")
|
||||
if ((canonical_metadata.st_dev, canonical_metadata.st_ino,
|
||||
stat.S_IFMT(canonical_metadata.st_mode)) !=
|
||||
(metadata.st_dev, metadata.st_ino, stat.S_IFMT(metadata.st_mode))):
|
||||
raise ValueError("report changed before reading")
|
||||
with os.fdopen(fd, "rb", closefd=False) as stream:
|
||||
raw = stream.read(max_bytes + 1)
|
||||
after = os.fstat(fd)
|
||||
if len(raw) > max_bytes:
|
||||
raise ValueError("report too large")
|
||||
if file_identity(metadata) != file_identity(after) or len(raw) != metadata.st_size:
|
||||
raise ValueError("report changed while reading")
|
||||
finally:
|
||||
os.close(fd)
|
||||
data = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=unique_object)
|
||||
return validate_report(data)
|
||||
|
||||
|
||||
def validate_report(data):
|
||||
if not isinstance(data, dict) or data.get("tool") != "DurkaHelper defense_scan":
|
||||
raise ValueError("not a scanner report")
|
||||
if data.get("offline") is not True or type(data.get("partial")) is not bool:
|
||||
raise ValueError("invalid report status")
|
||||
version = data.get("version")
|
||||
if not isinstance(version, str) or not re.fullmatch(r"[0-9][0-9A-Za-z.+-]{0,63}", version):
|
||||
raise ValueError("invalid version")
|
||||
if type(data.get("exit_code")) is not int or data["exit_code"] not in (0, 1, 2):
|
||||
raise ValueError("invalid exit code")
|
||||
scope = data.get("scope")
|
||||
created_at = data.get("created_at")
|
||||
if scope is None:
|
||||
if created_at is not None:
|
||||
_timestamp(created_at)
|
||||
else:
|
||||
if created_at is None:
|
||||
raise ValueError("scoped report has no timestamp")
|
||||
_timestamp(created_at)
|
||||
scope = validate_scope(scope)
|
||||
issues = data.get("issues")
|
||||
findings = data.get("findings")
|
||||
if not isinstance(issues, list) or not isinstance(findings, list) or len(findings) > MAX_FINDINGS:
|
||||
raise ValueError("invalid collections")
|
||||
indexed = {}
|
||||
for finding in findings:
|
||||
if not isinstance(finding, dict):
|
||||
raise ValueError("invalid finding")
|
||||
path, line, rule = (finding.get(field) for field in ("path", "line", "rule"))
|
||||
if not isinstance(path, str) or not 1 <= len(path) <= 4096 or "\x00" in path:
|
||||
raise ValueError("invalid path")
|
||||
if type(line) is not int or not 1 <= line <= 2**63 - 1:
|
||||
raise ValueError("invalid line")
|
||||
if not isinstance(rule, str) or not re.fullmatch(r"[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+", rule) or len(rule) > 100:
|
||||
raise ValueError("invalid rule ID")
|
||||
key = (path, line, rule)
|
||||
if key in indexed:
|
||||
raise ValueError("duplicate finding")
|
||||
# Do not copy source text, patches, arbitrary descriptions or issue payloads.
|
||||
indexed[key] = {"path": path, "line": line, "rule": rule}
|
||||
return {"version": version, "created_at": created_at, "scope": scope,
|
||||
"scope_sha256": scope["sha256"] if scope is not None else None,
|
||||
"partial": data["partial"] or bool(issues) or data["exit_code"] == 2,
|
||||
"issue_count": len(issues), "findings": indexed}
|
||||
|
||||
|
||||
def compare_reports(before, after):
|
||||
old, new = before["findings"], after["findings"]
|
||||
warnings = []
|
||||
if before["partial"]:
|
||||
warnings.append("before_partial")
|
||||
if after["partial"]:
|
||||
warnings.append("after_partial")
|
||||
if before["version"] != after["version"]:
|
||||
warnings.append("scanner_version_changed")
|
||||
if before["scope"] is None or after["scope"] is None:
|
||||
warnings.append("scope_unverified")
|
||||
elif before["scope"] != after["scope"]:
|
||||
warnings.append("scope_changed")
|
||||
scope_verified = before["scope"] is not None and before["scope"] == after["scope"]
|
||||
added = [new[key] for key in sorted(new.keys() - old.keys())]
|
||||
existing = [new[key] for key in sorted(new.keys() & old.keys())]
|
||||
absent = [old[key] for key in sorted(old.keys() - new.keys())]
|
||||
return {"tool": "DurkaHelper defense_diff", "offline": True,
|
||||
"matching": ["path", "line", "rule"], "scope_verified": scope_verified,
|
||||
"before": {"version": before["version"], "partial": before["partial"],
|
||||
"issue_count": before["issue_count"],
|
||||
"scope_sha256": before["scope_sha256"]},
|
||||
"after": {"version": after["version"], "partial": after["partial"],
|
||||
"issue_count": after["issue_count"],
|
||||
"scope_sha256": after["scope_sha256"]},
|
||||
"new": added, "existing": existing, "not_observed": absent,
|
||||
"counts": {"new": len(added), "existing": len(existing), "not_observed": len(absent)},
|
||||
"warnings": warnings, "partial": bool(warnings), "note": NOTE,
|
||||
"exit_code": 2 if warnings else 1 if added else 0}
|
||||
|
||||
|
||||
def printable(value):
|
||||
return str(value) if str(value).isprintable() else json.dumps(str(value), ensure_ascii=True)
|
||||
|
||||
|
||||
def positive(value):
|
||||
number = int(value)
|
||||
if number <= 0:
|
||||
raise argparse.ArgumentTypeError("expected a positive integer")
|
||||
return number
|
||||
|
||||
|
||||
def configure_text_output():
|
||||
"""Keep CLI diagnostics printable on legacy Windows code pages."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
reconfigure = getattr(stream, "reconfigure", None)
|
||||
if reconfigure is not None:
|
||||
try:
|
||||
reconfigure(errors="backslashreplace")
|
||||
except (AttributeError, OSError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
configure_text_output()
|
||||
parser = argparse.ArgumentParser(description="Compare two defense_scan JSON reports without reading source files.")
|
||||
parser.add_argument("before", help="previous JSON report")
|
||||
parser.add_argument("after", help="current JSON report")
|
||||
parser.add_argument("--json", action="store_true", help="structured JSON result")
|
||||
parser.add_argument("--show-existing", action="store_true", help="also show unchanged signals in text output")
|
||||
parser.add_argument("--max-bytes", type=positive, default=MAX_REPORT_BYTES, help="size limit for each report; default 32 MiB")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
report = compare_reports(load_report(args.before, args.max_bytes), load_report(args.after, args.max_bytes))
|
||||
except (OSError, ValueError, OverflowError, RecursionError, MemoryError) as exc:
|
||||
# Exception messages can contain report contents, paths or secret fields.
|
||||
error = {"error": "invalid_or_unreadable_report", "type": type(exc).__name__, "exit_code": 2}
|
||||
print(json.dumps(error) if args.json else "ERROR: invalid or unreadable report (" + type(exc).__name__ + ").")
|
||||
return 2
|
||||
if args.json:
|
||||
print(json.dumps(report, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
for field, label in (("new", "NEW"), ("not_observed", "NOT OBSERVED"), ("existing", "EXISTING")):
|
||||
if field == "existing" and not args.show_existing:
|
||||
continue
|
||||
for finding in report[field]:
|
||||
print(f"{label}: {printable(finding['path'])}:{finding['line']} [{finding['rule']}]")
|
||||
counts = report["counts"]
|
||||
print(f"New: {counts['new']}; existing: {counts['existing']}; not observed: {counts['not_observed']}.")
|
||||
if report["warnings"]:
|
||||
descriptions = {"before_partial": "previous scan is partial",
|
||||
"after_partial": "current scan is partial",
|
||||
"scanner_version_changed": "scanner versions differ",
|
||||
"scope_unverified": "scope is missing or unverified",
|
||||
"scope_changed": "report scopes differ"}
|
||||
print("Incomplete comparison: " + ", ".join(descriptions[item] for item in report["warnings"]))
|
||||
print(NOTE)
|
||||
return report["exit_code"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-pass HTTP status/content checks against an explicit JSON service list."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
|
||||
from common import http_url, limited_read, opener, positive_float
|
||||
|
||||
|
||||
def validate(config):
|
||||
if not isinstance(config, list) or not 1 <= len(config) <= 128:
|
||||
raise ValueError("config must be a list of 1..128 checks")
|
||||
for item in config:
|
||||
if not isinstance(item, dict) or not isinstance(item.get("name"), str):
|
||||
raise ValueError("each check needs a string name")
|
||||
if not item["name"].strip() or len(item["name"]) > 120:
|
||||
raise ValueError("name must contain 1..120 characters")
|
||||
if set(item) - {"name", "url", "status", "contains"}:
|
||||
raise ValueError("unknown check field")
|
||||
if not isinstance(item.get("url"), str) or any(c.isspace() for c in item["url"]):
|
||||
raise ValueError("url must be a string without whitespace")
|
||||
http_url(item["url"])
|
||||
expected = item.get("status", 200)
|
||||
if type(expected) is not int or not 100 <= expected <= 599:
|
||||
raise ValueError("status must be an integer HTTP status")
|
||||
if "contains" in item and not isinstance(item["contains"], str):
|
||||
raise ValueError("contains must be a string")
|
||||
return config
|
||||
|
||||
|
||||
def probe(item, timeout):
|
||||
started = time.monotonic()
|
||||
result = {"name": item["name"], "ok": False, "status": None}
|
||||
try:
|
||||
req = Request(item["url"], headers={"User-Agent": "DurkaHelper/0.1"})
|
||||
try:
|
||||
response = opener().open(req, timeout=timeout)
|
||||
except HTTPError as exc:
|
||||
response = exc # An expected 403/404 is a legitimate probe outcome.
|
||||
with response:
|
||||
result["status"] = response.code
|
||||
body = limited_read(response).decode("utf-8", errors="replace")
|
||||
result["ok"] = (result["status"] == item.get("status", 200)
|
||||
and item.get("contains", "") in body)
|
||||
except (OSError, ValueError) as exc:
|
||||
result["error"] = type(exc).__name__
|
||||
result["ms"] = round((time.monotonic() - started) * 1000)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("config", help="JSON list with name, url, status and optional contains")
|
||||
parser.add_argument("--timeout", type=positive_float, default=3.0)
|
||||
parser.add_argument("--workers", type=int, choices=range(1, 17), default=4)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
with open(args.config, encoding="utf-8") as f:
|
||||
config = validate(json.load(f))
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
results = list(pool.map(lambda x: probe(x, args.timeout), config))
|
||||
for result in results:
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
return 0 if all(r["ok"] for r in results) else 1
|
||||
except (KeyError, TypeError, ValueError, OSError) as exc:
|
||||
print(f"probe configuration: {type(exc).__name__}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize a local JSONL log without printing messages or arbitrary fields."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
MAX_LINE = 256 * 1024
|
||||
MAX_FILE = 64 * 1024 * 1024
|
||||
LEVELS = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
||||
ALIASES = {"WARN": "WARNING", "FATAL": "CRITICAL"}
|
||||
|
||||
|
||||
def summarize(stream, max_bytes=MAX_FILE):
|
||||
result = {"lines": 0, "records": 0, "blank_lines": 0, "invalid_lines": 0,
|
||||
"invalid_fields": 0, "http_errors": 0}
|
||||
levels, statuses = Counter(), Counter()
|
||||
consumed = 0
|
||||
while True:
|
||||
raw = stream.readline(MAX_LINE + 1)
|
||||
if not raw:
|
||||
break
|
||||
consumed += len(raw)
|
||||
too_long = len(raw) > MAX_LINE
|
||||
# Drain one oversized record without retaining it in memory.
|
||||
while len(raw) == MAX_LINE + 1 and not raw.endswith(b"\n"):
|
||||
if consumed > max_bytes:
|
||||
raise ValueError("log exceeds byte limit")
|
||||
raw = stream.readline(MAX_LINE + 1)
|
||||
consumed += len(raw)
|
||||
if consumed > max_bytes:
|
||||
raise ValueError("log exceeds byte limit")
|
||||
result["lines"] += 1
|
||||
if too_long:
|
||||
result["invalid_lines"] += 1
|
||||
continue
|
||||
if not raw.strip():
|
||||
result["blank_lines"] += 1
|
||||
continue
|
||||
try:
|
||||
record = json.loads(raw)
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError("expected object")
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
result["invalid_lines"] += 1
|
||||
continue
|
||||
result["records"] += 1
|
||||
if "level" in record:
|
||||
level = record["level"]
|
||||
if isinstance(level, str):
|
||||
level = ALIASES.get(level.upper(), level.upper())
|
||||
if not isinstance(level, str) or level not in LEVELS:
|
||||
result["invalid_fields"] += 1
|
||||
else:
|
||||
levels[level] += 1
|
||||
if "status" in record:
|
||||
status = record["status"]
|
||||
if type(status) is not int or not 100 <= status <= 599:
|
||||
result["invalid_fields"] += 1
|
||||
else:
|
||||
statuses[str(status)] += 1
|
||||
result["http_errors"] += int(status >= 400)
|
||||
result["levels"] = dict(sorted(levels.items()))
|
||||
result["statuses"] = dict(sorted(statuses.items()))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("log", type=Path, help="local UTF-8 JSONL file, at most 64 MiB")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
info = args.log.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE:
|
||||
raise ValueError("expected a regular file within size limit")
|
||||
with args.log.open("rb") as stream:
|
||||
result = summarize(stream)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return 1 if result["invalid_lines"] or result["invalid_fields"] else 0
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"log summary: {type(exc).__name__}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded publication hygiene checks. Findings contain locations, never values.
|
||||
|
||||
Checks the tracked/non-ignored worktree by default. --history inspects only
|
||||
commits reachable from explicitly selected --ref values (HEAD by default).
|
||||
This heuristic gate does not replace manual review of images, CI artifacts,
|
||||
PR discussions, licenses, or the remote repository's publication settings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LIMIT = 8 * 1024 * 1024
|
||||
MAX_FILES = 20000
|
||||
PATTERNS = {
|
||||
"private-key": re.compile(br"-----BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY-----"),
|
||||
"access-token": re.compile(br"\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{30,255}|AKIA[0-9A-Z]{16})\b"),
|
||||
"ssh-identity": re.compile(br"\b(?:ssh-ed25519|ssh-rsa) [A-Za-z0-9+/]{40,}={0,3}(?: |$)"),
|
||||
"personal-home": re.compile(br"(?:[A-Za-z]:[\\/]Users[\\/](?!Public\b|USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+|/Users/(?!USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+|/home/(?!USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+)"),
|
||||
"url-credentials": re.compile(br"\b(?:https?|ssh)://[^\s/:@]{1,100}:[^\s/@]{4,200}@"),
|
||||
}
|
||||
FORBIDDEN_PARTS = {".ssh", ".aws", ".gnupg", ".codex-remote-attachments", "local", "artifacts", "upstream", ".git", "secrets"}
|
||||
FORBIDDEN_SUFFIXES = {".pcap", ".pcapng", ".pem", ".key", ".p12", ".pfx", ".sqlite", ".db", ".log"}
|
||||
REVIEW_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".pdf", ".zip", ".tar", ".gz"}
|
||||
|
||||
|
||||
class CheckError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def git(root, *args, limit=LIMIT):
|
||||
# No shell, filters, target commands, or network operations.
|
||||
command = ["git", "--no-pager", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(root), *args]
|
||||
environment = {key: value for key, value in os.environ.items() if not key.upper().startswith("GIT_")}
|
||||
environment.update({"GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0",
|
||||
"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull})
|
||||
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=environment) as process:
|
||||
def stop():
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
deadline = threading.Timer(30, stop)
|
||||
deadline.daemon = True
|
||||
deadline.start()
|
||||
try:
|
||||
output = process.stdout.read(limit + 1)
|
||||
if len(output) > limit:
|
||||
raise CheckError("Git output exceeds the publication audit limit")
|
||||
if process.wait(timeout=30):
|
||||
raise CheckError("Git could not read the selected publication scope")
|
||||
return output
|
||||
finally:
|
||||
deadline.cancel()
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def safe_path(value):
|
||||
parts = value.split("/")
|
||||
if (not value or value.startswith("/") or "\\" in value or ":" in value or
|
||||
any(p in {"", ".", ".."} for p in parts) or any(ord(c) < 32 for c in value)):
|
||||
raise CheckError("non-portable path in publication scope")
|
||||
return value
|
||||
|
||||
|
||||
def finding(path, category, line=0, ref="worktree", fingerprint=None):
|
||||
value = {"path": path, "category": category, "line": line, "ref": ref}
|
||||
if fingerprint is not None:
|
||||
value["fingerprint"] = fingerprint
|
||||
return value
|
||||
|
||||
|
||||
def scan_bytes(path, data, ref="worktree", private_terms=()):
|
||||
rows = []
|
||||
suffix = Path(path).suffix.lower()
|
||||
if (set(p.lower() for p in path.split("/")) & FORBIDDEN_PARTS or suffix in FORBIDDEN_SUFFIXES or
|
||||
Path(path).name == ".env" or (Path(path).name.startswith(".env.") and Path(path).name != ".env.example")):
|
||||
rows.append(finding(path, "private-or-runtime-file", ref=ref))
|
||||
if suffix in REVIEW_SUFFIXES or b"\x00" in data:
|
||||
rows.append(finding(path, "manual-asset-review", ref=ref))
|
||||
for number, line in enumerate(data.splitlines(), 1):
|
||||
fingerprint = hashlib.sha256(line).hexdigest()
|
||||
for category, pattern in PATTERNS.items():
|
||||
if pattern.search(line):
|
||||
rows.append(finding(path, category, number, ref, fingerprint))
|
||||
if any(term in line for term in private_terms):
|
||||
rows.append(finding(path, "private-environment-reference", number, ref, fingerprint))
|
||||
return rows
|
||||
|
||||
|
||||
def read_file(path):
|
||||
before = path.lstat()
|
||||
if not stat.S_ISREG(before.st_mode) or before.st_size > LIMIT:
|
||||
raise CheckError("publication input is not a bounded regular file")
|
||||
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
||||
fd = os.open(path, flags)
|
||||
try:
|
||||
signature = lambda s: (s.st_dev, s.st_ino, s.st_mode, s.st_size, s.st_mtime_ns, s.st_ctime_ns)
|
||||
opened = os.fstat(fd)
|
||||
if signature(opened) != signature(before) or not stat.S_ISREG(opened.st_mode):
|
||||
raise CheckError("publication input changed while opening")
|
||||
with os.fdopen(fd, "rb", closefd=False) as stream:
|
||||
data = stream.read(LIMIT + 1)
|
||||
if len(data) > LIMIT or signature(os.fstat(fd)) != signature(opened) or signature(path.lstat()) != signature(opened):
|
||||
raise CheckError("publication input changed while reading")
|
||||
return data
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def audit(root, *, history=False, refs=("HEAD",), max_commits=500, private_terms=(), allowlist=()):
|
||||
root = Path(root).resolve(strict=True)
|
||||
rows, issues, files = [], [], 0
|
||||
seen = set()
|
||||
if history:
|
||||
if not 1 <= max_commits <= 10000 or not 1 <= len(refs) <= 32:
|
||||
raise CheckError("invalid history scope limits")
|
||||
resolved = []
|
||||
for ref in refs:
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_./-]{0,200}", ref):
|
||||
raise CheckError("invalid publication ref")
|
||||
resolved.append(git(root, "rev-parse", "--verify", ref + "^{commit}").decode("ascii").strip())
|
||||
commits = git(root, "rev-list", "--max-count=" + str(max_commits + 1), *resolved).decode("ascii").splitlines()
|
||||
if len(commits) > max_commits:
|
||||
issues.append("history_commit_limit")
|
||||
for commit in commits[:max_commits]:
|
||||
entries = git(root, "ls-tree", "-r", "-z", commit).split(b"\x00")
|
||||
for entry in filter(None, entries):
|
||||
metadata, raw_name = entry.split(b"\t", 1)
|
||||
mode, kind, oid = metadata.decode("ascii").split()
|
||||
name = safe_path(raw_name.decode("utf-8"))
|
||||
if (oid, name) in seen:
|
||||
continue
|
||||
seen.add((oid, name))
|
||||
if files >= MAX_FILES:
|
||||
issues.append("history_file_limit")
|
||||
break
|
||||
files += 1
|
||||
if kind != "blob" or mode not in {"100644", "100755"}:
|
||||
rows.append(finding(name, "unreviewed-link-or-submodule", ref=commit))
|
||||
continue
|
||||
if int(git(root, "cat-file", "-s", oid)) > LIMIT:
|
||||
issues.append("oversized_history_blob")
|
||||
continue
|
||||
rows.extend(scan_bytes(name, git(root, "cat-file", "blob", oid), commit, private_terms))
|
||||
if "history_file_limit" in issues:
|
||||
break
|
||||
scope = {"kind": "selected-history", "refs": resolved, "commits": min(len(commits), max_commits)}
|
||||
else:
|
||||
names = git(root, "ls-files", "--cached", "--others", "--exclude-standard", "-z").split(b"\x00")
|
||||
names = sorted(set(filter(None, names)))
|
||||
if len(names) > MAX_FILES:
|
||||
issues.append("worktree_file_limit")
|
||||
for raw_name in names[:MAX_FILES]:
|
||||
name = safe_path(raw_name.decode("utf-8"))
|
||||
path = root / name
|
||||
files += 1
|
||||
if any(parent.is_symlink() for parent in [path, *path.parents] if parent != root.parent):
|
||||
rows.append(finding(name, "unreviewed-link-or-submodule"))
|
||||
continue
|
||||
try:
|
||||
rows.extend(scan_bytes(name, read_file(path), private_terms=private_terms))
|
||||
except (CheckError, OSError):
|
||||
rows.append(finding(name, "unreadable-or-unstable-input"))
|
||||
scope = {"kind": "tracked-and-nonignored-worktree"}
|
||||
accepted = set()
|
||||
for entry in allowlist:
|
||||
if (not isinstance(entry, dict) or set(entry) != {"path", "category", "fingerprint", "reason"} or
|
||||
entry["category"] not in PATTERNS or not isinstance(entry["reason"], str) or
|
||||
not 10 <= len(entry["reason"]) <= 512 or
|
||||
not isinstance(entry["fingerprint"], str) or not re.fullmatch(r"[0-9a-f]{64}", entry["fingerprint"])):
|
||||
raise CheckError("allowlist requires exact path, category, line digest and review reason")
|
||||
accepted.add((safe_path(entry["path"]), entry["category"], entry["fingerprint"]))
|
||||
suppressed = [r for r in rows if (r["path"], r["category"], r.get("fingerprint")) in accepted]
|
||||
rows = [r for r in rows if r not in suppressed]
|
||||
partial = bool(issues) or any(r["category"] in {"manual-asset-review", "unreadable-or-unstable-input", "unreviewed-link-or-submodule"} for r in rows)
|
||||
return {"schema": "durkahelper.publication-check.v1", "scope": scope, "files_checked": files,
|
||||
"findings": rows, "issues": sorted(set(issues)), "reviewed_exceptions": len(suppressed),
|
||||
"external_surfaces": "NOT_RUN: CI artifacts, PR content, remote refs/settings, asset visual review",
|
||||
"exit_code": 2 if partial else 1 if rows else 0}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".")
|
||||
parser.add_argument("--history", action="store_true")
|
||||
parser.add_argument("--ref", action="append")
|
||||
parser.add_argument("--max-commits", type=int, default=500)
|
||||
parser.add_argument("--private-denylist", help="ignored local JSON array; never copied into a report")
|
||||
parser.add_argument("--allowlist", help="JSON array of exact reviewed synthetic line exceptions")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
terms = json.loads(read_file(Path(args.private_denylist))) if args.private_denylist else []
|
||||
if not isinstance(terms, list) or len(terms) > 256 or any(not isinstance(t, str) or not 4 <= len(t) <= 1024 for t in terms):
|
||||
raise CheckError("invalid private denylist")
|
||||
allowlist = json.loads(read_file(Path(args.allowlist))) if args.allowlist else []
|
||||
if not isinstance(allowlist, list) or len(allowlist) > 1000:
|
||||
raise CheckError("invalid reviewed exceptions")
|
||||
result = audit(args.root, history=args.history, refs=args.ref or ["HEAD"], max_commits=args.max_commits,
|
||||
private_terms=[t.encode("utf-8") for t in terms], allowlist=allowlist)
|
||||
print(json.dumps(result, ensure_ascii=True, sort_keys=True))
|
||||
return result["exit_code"]
|
||||
except (CheckError, OSError, UnicodeError, ValueError, subprocess.SubprocessError) as exc:
|
||||
print(json.dumps({"error": type(exc).__name__, "exit_code": 2, "details": "suppressed"}))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build an honest offline rule/language coverage ledger from inert fixtures.
|
||||
|
||||
Authored before/after examples are not independent cases. Legacy gaps are
|
||||
reported, not invented; every rule introduced in 1.7.0 requires two distinct
|
||||
positive and two negative independent sources per claimed language. Expanded
|
||||
forms opt in per language with coverage_required; legacy gaps stay visible.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
_SCANNER_SPEC = importlib.util.spec_from_file_location("durkahelper_coverage_scanner", ROOT / "scripts/defense_scan.py")
|
||||
scanner = importlib.util.module_from_spec(_SCANNER_SPEC)
|
||||
_SCANNER_SPEC.loader.exec_module(scanner)
|
||||
|
||||
|
||||
FIXTURES = (ROOT / "tests/fixtures/defense_variants.json",
|
||||
ROOT / "tests/fixtures/defense_expansion.json",
|
||||
ROOT / "tests/fixtures/defense_boundaries.json")
|
||||
|
||||
|
||||
def build_ledger(rules=None, cases=None, *, run_checks=False):
|
||||
rules = scanner.load_rules() if rules is None else rules
|
||||
if cases is None:
|
||||
cases = []
|
||||
for path in FIXTURES:
|
||||
data = json.loads(scanner.read_regular(scanner.canonical_scan_root(path), 4 * 1024 * 1024))
|
||||
if data.get("schema_version") != 1 or not isinstance(data.get("cases"), list):
|
||||
raise ValueError("unsupported fixture contract")
|
||||
cases.extend(data["cases"])
|
||||
by_id = {rule["id"]: rule for rule in rules}
|
||||
seen = set()
|
||||
coverage = {(r["id"], lang): {"positive": set(), "negative": set()}
|
||||
for r in rules for lang in r["languages"]}
|
||||
failures = []
|
||||
for case in cases:
|
||||
if (not isinstance(case, dict) or not isinstance(case.get("id"), str)
|
||||
or case["id"] in seen or not isinstance(case.get("source"), str)
|
||||
or not case["source"] or len(case["source"]) > 1048576
|
||||
or not isinstance(case.get("language"), str)):
|
||||
raise ValueError("invalid or duplicate fixture")
|
||||
seen.add(case["id"])
|
||||
expectations = {}
|
||||
for source_key, category in (("expected", "positive"), ("forbidden", "negative")):
|
||||
values = case.get(source_key)
|
||||
if (not isinstance(values, list) or not all(isinstance(value, str) for value in values)
|
||||
or len(values) != len(set(values))):
|
||||
raise ValueError("invalid fixture expectations")
|
||||
expectations[category] = set(values)
|
||||
for rid in values:
|
||||
pair = (rid, case["language"])
|
||||
if pair not in coverage:
|
||||
raise ValueError("fixture rule/language mismatch")
|
||||
# A duplicate or pasted authored example is never extra coverage.
|
||||
source = case["source"].strip()
|
||||
if source not in {by_id[rid]["before"].strip(), by_id[rid]["after"].strip()}:
|
||||
coverage[pair][category].add(hashlib.sha256(source.encode("utf-8")).hexdigest())
|
||||
if (not expectations["positive"] and not expectations["negative"]
|
||||
or expectations["positive"] & expectations["negative"]):
|
||||
raise ValueError("contradictory or empty fixture expectations")
|
||||
if run_checks:
|
||||
hits, issues = scanner.scan_text(case["source"], case["language"], rules)
|
||||
ids = {rid for rid, _ in hits}
|
||||
if expectations["positive"] - ids or expectations["negative"] & ids or issues:
|
||||
failures.append(case["id"])
|
||||
rows = []
|
||||
for (rid, language), counts in sorted(coverage.items()):
|
||||
positive, negative = len(counts["positive"]), len(counts["negative"])
|
||||
meets_target = positive >= 2 and negative >= 2
|
||||
rows.append({"rule": rid, "language": language, "family": by_id[rid]["family"],
|
||||
"engine": by_id[rid]["engine"], "independent_positive": positive,
|
||||
"independent_negative": negative, "meets_independent_target": meets_target,
|
||||
"required_for_release": (by_id[rid].get("introduced") in {"1.7.0", "1.8.0"}
|
||||
or language in by_id[rid].get("coverage_required", [])),
|
||||
"limitations": by_id[rid]["limitations"]})
|
||||
unmet = [{"rule": row["rule"], "language": row["language"]} for row in rows
|
||||
if row["required_for_release"] and not row["meets_independent_target"]]
|
||||
return {"schema": "durkahelper.scanner-coverage.v1", "scanner_version": scanner.VERSION,
|
||||
"rules_sha256": scanner.rules_fingerprint(rules), "rule_count": len(rules),
|
||||
"rule_language_pairs": len(rows), "independent_fixture_records": len(cases),
|
||||
"authored_examples_counted": False, "checks_executed": run_checks,
|
||||
"failing_case_ids": sorted(failures), "unmet_release_pairs": unmet,
|
||||
"rows": rows, "exit_code": 1 if failures or unmet else 0}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
scanner.configure_text_output()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--json", action="store_true", help="print the complete deterministic coverage ledger")
|
||||
parser.add_argument("--check", action="store_true", help="also run inert fixture detector checks; no target code is executed")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
ledger = build_ledger(run_checks=args.check)
|
||||
except (OSError, ValueError, KeyError, TypeError, RecursionError, MemoryError) as exc:
|
||||
print(json.dumps({"error": "invalid_coverage_input", "type": type(exc).__name__, "exit_code": 2}))
|
||||
return 2
|
||||
if args.json:
|
||||
print(json.dumps(ledger, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
print(f"Rules: {ledger['rule_count']}; rule/language pairs: {ledger['rule_language_pairs']}; independent records: {ledger['independent_fixture_records']}")
|
||||
print("Authored examples excluded. Legacy gaps remain visible; this is not proof of complete vulnerability coverage.")
|
||||
print(f"Checks executed: {ledger['checks_executed']}; failed cases: {len(ledger['failing_case_ids'])}; unmet release pairs: {len(ledger['unmet_release_pairs'])}")
|
||||
return ledger["exit_code"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,340 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check a private offline cache and prepare the strict v2 assembly manifest.
|
||||
|
||||
This does not download, execute installers, inspect Docker, or prove cold-start
|
||||
readiness. Pins authenticate an explicitly reviewed cache recipe; source archive
|
||||
provenance and license suitability still require operator review.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location("inventory_bundle", Path(__file__).with_name("toolchain_bundle.py"))
|
||||
kit = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(kit)
|
||||
ops, Error = kit.ops, kit.Error
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCHEMA = "durkahelper.toolchain-inventory.v1"
|
||||
REPORT_SCHEMA = "durkahelper.toolchain-readiness.v1"
|
||||
NATIVE_COMPONENTS = {"container-runtime", "python", "ripgrep"}
|
||||
ID = re.compile(r"[a-z0-9][a-z0-9_.-]{0,63}")
|
||||
SHA = re.compile(r"[0-9a-f]{64}")
|
||||
COMMIT = re.compile(r"[0-9a-f]{40}")
|
||||
ASSET_FIELDS = {"id", "path", "kind", "component", "architecture", "version", "sha256", "size",
|
||||
"license", "redistribution", "source_pins"}
|
||||
|
||||
|
||||
def _matches(pattern, value):
|
||||
return isinstance(value, str) and pattern.fullmatch(value) is not None
|
||||
|
||||
|
||||
def _path(value):
|
||||
value = ops._portable_relative_posix(value, "cache member")
|
||||
if (set(part.casefold() for part in value.split("/")) & kit.FORBIDDEN or
|
||||
any(part.casefold().startswith(".env.") for part in value.split("/")) or
|
||||
Path(value).suffix.lower() in {".key", ".pem", ".pcap", ".pcapng", ".db", ".sqlite", ".log"}):
|
||||
raise Error("private operational data is not an inventory member")
|
||||
return value
|
||||
|
||||
|
||||
def recipe(value):
|
||||
fields = {"schema", "release_commit", "target", "receipt", "image_export", "artifacts"}
|
||||
ops._strict_keys(value, fields, fields, "toolchain inventory")
|
||||
if value["schema"] != SCHEMA or not _matches(COMMIT, value["release_commit"]):
|
||||
raise Error("invalid inventory schema or release")
|
||||
ops._strict_keys(value["target"], {"id", "platform"}, {"id", "platform"}, "inventory target")
|
||||
if not _matches(ID, value["target"]["id"]):
|
||||
raise Error("invalid target identity")
|
||||
ops._deployment_enum(value["target"]["platform"], kit.NATIVE_PLATFORMS, "target platform")
|
||||
for key in ("receipt", "image_export"):
|
||||
reference = value[key]
|
||||
ops._strict_keys(reference, {"path", "sha256"}, {"path", "sha256"}, "inventory reference")
|
||||
_path(reference["path"])
|
||||
if not _matches(SHA, reference["sha256"]):
|
||||
raise Error("inventory reference requires a detached checksum")
|
||||
if value["receipt"]["path"].casefold() == value["image_export"]["path"].casefold():
|
||||
raise Error("ambiguous inventory references")
|
||||
assets = value["artifacts"]
|
||||
if not isinstance(assets, list) or len(assets) > 128:
|
||||
raise Error("inventory requires at most 128 non-image artifacts")
|
||||
ids, paths, component_kinds = set(), set(), set()
|
||||
total = 0
|
||||
for asset in assets:
|
||||
ops._strict_keys(asset, ASSET_FIELDS, ASSET_FIELDS, "inventory artifact")
|
||||
if not _matches(ID, asset["id"]) or not _matches(ID, asset["component"]):
|
||||
raise Error("invalid artifact identity")
|
||||
component, kind = asset["component"], asset["kind"]
|
||||
if (not isinstance(kind, str) or component not in kit.REQUIRED_COMPONENT_KINDS or
|
||||
kind == "image" or kind not in kit.REQUIRED_COMPONENT_KINDS[component]):
|
||||
raise Error("artifact outside the maintained component contract")
|
||||
path = _path(asset["path"])
|
||||
if (asset["id"] in ids or path.casefold() in paths or
|
||||
(component, kind) in component_kinds or path.casefold() == "manifest.json" or
|
||||
path.casefold() in {value[key]["path"].casefold() for key in ("receipt", "image_export")}):
|
||||
raise Error("ambiguous cache artifact")
|
||||
ids.add(asset["id"])
|
||||
paths.add(path.casefold())
|
||||
component_kinds.add((component, kind))
|
||||
ops._deployment_enum(asset["architecture"], {"all", *kit.NATIVE_PLATFORMS}, "artifact architecture")
|
||||
if asset["architecture"] not in {"all", value["target"]["platform"]}:
|
||||
raise Error("cache artifact architecture does not match target")
|
||||
if kind in {"client", "runtime", "installer"} and asset["architecture"] != value["target"]["platform"]:
|
||||
raise Error("native artifacts require the exact target platform")
|
||||
version = asset["version"]
|
||||
if (not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+:/@-]{0,127}", version) or
|
||||
set(re.split(r"[:/@._+-]+", version.casefold())) & kit.FLOATING_VERSIONS):
|
||||
raise Error("artifact requires an exact version")
|
||||
if not _matches(SHA, asset["sha256"]):
|
||||
raise Error("artifact checksum required")
|
||||
ops._positive_int(asset["size"], "artifact size", kit.MAX_ARTIFACT)
|
||||
total += asset["size"]
|
||||
if not isinstance(asset["license"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}", asset["license"]):
|
||||
raise Error("artifact license reference required")
|
||||
if asset["redistribution"] != "local-only":
|
||||
raise Error("inventory preparation is local-only, not redistribution approval")
|
||||
pins = asset["source_pins"]
|
||||
if not isinstance(pins, dict) or len(pins) > 32:
|
||||
raise Error("invalid source pin inventory")
|
||||
for name, commit in pins.items():
|
||||
if name != ".":
|
||||
_path(name)
|
||||
if not _matches(COMMIT, commit):
|
||||
raise Error("source pin must be a full commit")
|
||||
if kind == "source":
|
||||
if pins.get(".") != version:
|
||||
raise Error("source archive must declare its root commit")
|
||||
elif pins:
|
||||
raise Error("only source archives declare source pins")
|
||||
if kind == "core" and version != value["release_commit"]:
|
||||
raise Error("core release differs from inventory release")
|
||||
if total > kit.MAX_TOTAL:
|
||||
raise Error("inventory exceeds total byte budget")
|
||||
return value
|
||||
|
||||
|
||||
def _json_member(root, identity, reference):
|
||||
"""Read a checksum-bound JSON member without following cache ancestor links."""
|
||||
descriptor = ops._open_anchored_regular(root, reference["path"], identity)
|
||||
try:
|
||||
before = os.fstat(descriptor)
|
||||
if not stat.S_ISREG(before.st_mode) or before.st_size > ops.MAX_PROFILE_BYTES:
|
||||
raise Error("inventory reference exceeds limit")
|
||||
with os.fdopen(descriptor, "rb", closefd=False) as stream:
|
||||
raw = stream.read(ops.MAX_PROFILE_BYTES + 1)
|
||||
if len(raw) > ops.MAX_PROFILE_BYTES or ops._stat_identity(before) != ops._stat_identity(os.fstat(descriptor)):
|
||||
raise Error("inventory reference changed")
|
||||
if hashlib.sha256(raw).hexdigest() != reference["sha256"]:
|
||||
raise Error("inventory reference checksum mismatch")
|
||||
return json.loads(raw.decode("utf-8"), object_pairs_hook=ops._unique_object,
|
||||
parse_constant=ops._reject_constant)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _receipt(value):
|
||||
fields = {"schema", "compose_sha256", "runtime_sha256", "images"}
|
||||
ops._strict_keys(value, fields, fields, "deployment receipt")
|
||||
if (value["schema"] != "durkahelper.deployment-build.v2" or
|
||||
not _matches(SHA, value["compose_sha256"]) or not _matches(SHA, value["runtime_sha256"]) or
|
||||
not isinstance(value["images"], dict) or set(value["images"]) != set(kit.MAINTAINED_ROLES) or
|
||||
any(not isinstance(i, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", i) for i in value["images"].values())):
|
||||
raise Error("receipt must pin exactly the maintained runtime roles")
|
||||
for group in kit.SHARED_IMAGE_IDENTITY_GROUPS:
|
||||
if len({value["images"][role] for role in group}) != 1:
|
||||
raise Error("receipt shared image identities disagree")
|
||||
return value
|
||||
|
||||
|
||||
def _pin_problem(asset, lock, platform):
|
||||
"""Return a safe category, never a URL, path, checksum or lock value."""
|
||||
component, kind = asset["component"], asset["kind"]
|
||||
if kind in {"core", "license"}:
|
||||
return None
|
||||
pinned = lock.get("components", {}).get(component, {})
|
||||
if kind == "source":
|
||||
commit = pinned.get("source", {}).get("commit")
|
||||
submodules = pinned.get("submodules", {})
|
||||
if not _matches(COMMIT, commit) or submodules.get("status") != "EXISTING":
|
||||
return "unresolved-source-pin"
|
||||
expected = {".": commit}
|
||||
for entry in submodules.get("items", []):
|
||||
if not isinstance(entry, dict) or not _matches(COMMIT, entry.get("commit")):
|
||||
return "unresolved-submodule-pin"
|
||||
expected[entry.get("path")] = entry["commit"]
|
||||
return None if asset["source_pins"] == expected else "source-pin-mismatch"
|
||||
if kind == "client":
|
||||
system, arch = platform.split("/")
|
||||
candidates = [entry for entry in pinned.get("release", {}).get("assets", [])
|
||||
if entry.get("os") == system and entry.get("architecture") == arch]
|
||||
version = pinned.get("version")
|
||||
if not version or len(candidates) != 1:
|
||||
return "unresolved-client-pin"
|
||||
candidate = candidates[0]
|
||||
if (asset["version"].removeprefix("v") != str(version).removeprefix("v") or
|
||||
asset["sha256"] != candidate.get("published_sha256") or asset["size"] != candidate.get("size")):
|
||||
return "client-pin-mismatch"
|
||||
return None
|
||||
# Native prerequisites need a platform-specific official asset pin in the
|
||||
# maintained lock. A locally measured hash cannot authenticate its origin.
|
||||
candidate = pinned.get("asset", {})
|
||||
candidates = pinned.get("assets", [])
|
||||
if candidates:
|
||||
candidates = [entry for entry in candidates if entry.get("platform") == platform]
|
||||
candidate = candidates[0] if len(candidates) == 1 else {}
|
||||
elif not any(entry.get("arch") == platform.split("/")[1] and
|
||||
entry.get("os") in ({"darwin", "macos"} if platform.startswith("darwin/") else {platform.split("/")[0]})
|
||||
for entry in pinned.get("architectures", [])):
|
||||
candidate = {}
|
||||
checksum = candidate.get("sha256") or candidate.get("digest")
|
||||
if isinstance(checksum, str):
|
||||
checksum = checksum.removeprefix("sha256:")
|
||||
if not _matches(SHA, checksum) or not pinned.get("version"):
|
||||
return "unresolved-prerequisite-pin"
|
||||
if (asset["sha256"] != checksum or asset["version"] != pinned["version"] or
|
||||
(candidate.get("size") is not None and asset["size"] != candidate["size"])):
|
||||
return "prerequisite-pin-mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def inspect(root, value, lock):
|
||||
"""Return a sanitized report and, only when complete, a validated manifest."""
|
||||
value = recipe(value)
|
||||
if not isinstance(lock, dict) or lock.get("schema") != "durkahelper.toolchain-lock.v1" or not isinstance(lock.get("components"), dict):
|
||||
raise Error("invalid maintained toolchain lock")
|
||||
root = ops._canonical_root_directory(Path(root))
|
||||
identity = ops._root_anchor_identity(root.lstat())
|
||||
receipt = _receipt(_json_member(root, identity, value["receipt"]))
|
||||
exported = kit.manifest(_json_member(root, identity, value["image_export"]), expected_scope="image-export")
|
||||
kit._check_release_commit(exported, value["release_commit"])
|
||||
if set(receipt["images"].values()) != {i for item in exported["artifacts"] for i in item["image_ids"]}:
|
||||
raise Error("image export does not exactly cover the deployment receipt")
|
||||
target_platform = value["target"]["platform"]
|
||||
container_platform = "linux/" + target_platform.split("/")[1]
|
||||
sources = {item["component"]: item["id"] for item in value["artifacts"] if item["kind"] == "source"}
|
||||
artifacts, issues = [], []
|
||||
export_parent = PurePosixPath(value["image_export"]["path"]).parent
|
||||
for exported_item in exported["artifacts"]:
|
||||
item = copy.deepcopy(exported_item)
|
||||
roles = sorted(role for role, image in receipt["images"].items() if image in item["image_ids"])
|
||||
components = {kit.ROLE_IMAGE_COMPONENTS[role] for role in roles}
|
||||
platforms = {kit.FIXED_ROLE_PLATFORMS.get(role, container_platform) for role in roles}
|
||||
if len(components) != 1 or platforms != {item["architecture"]}:
|
||||
raise Error("image archive cannot map unambiguously to target roles")
|
||||
item["component"] = components.pop()
|
||||
item["path"] = _path((export_parent / item["path"]).as_posix())
|
||||
item["runtime_roles"] = roles
|
||||
item["compatible_with"] = [sources[item["component"]]] if item["component"] in sources else []
|
||||
item["redistribution"] = "local-only"
|
||||
artifacts.append(item)
|
||||
ids = {item["id"] for item in artifacts}
|
||||
paths = {item["path"].casefold() for item in artifacts}
|
||||
reference_paths = {value[key]["path"].casefold() for key in ("receipt", "image_export")}
|
||||
if paths & reference_paths:
|
||||
raise Error("image payload collides with an inventory reference")
|
||||
worker = next(item["id"] for item in artifacts if "neo-worker" in item["runtime_roles"])
|
||||
for original in value["artifacts"]:
|
||||
item = {key: val for key, val in original.items() if key != "source_pins"}
|
||||
if item["id"] in ids or item["path"].casefold() in paths:
|
||||
raise Error("image and artifact inventory collide")
|
||||
ids.add(item["id"])
|
||||
paths.add(item["path"].casefold())
|
||||
item.update(image_ids=[], runtime_roles=[], compatible_with=[])
|
||||
if item["kind"] == "client" and "neo" in sources:
|
||||
item["compatible_with"] = [worker, sources["neo"]]
|
||||
try:
|
||||
problem = _pin_problem(original, lock, target_platform)
|
||||
except (AttributeError, KeyError, TypeError):
|
||||
problem = "invalid-component-pin"
|
||||
if problem:
|
||||
issues.append({"component": item["component"], "kind": item["kind"], "issue": problem})
|
||||
artifacts.append(item)
|
||||
if sum(item["size"] for item in artifacts) > kit.MAX_TOTAL:
|
||||
raise Error("complete cache exceeds byte budget")
|
||||
# Verify each declared file independently so all missing/corrupt items are
|
||||
# reported in one pass. Exceptions are deliberately not copied to evidence.
|
||||
for item in artifacts:
|
||||
if ops._root_anchor_identity(root.lstat()) != identity:
|
||||
raise Error("cache root changed during inventory")
|
||||
try:
|
||||
kit.check_files(root, {"artifacts": [item]})
|
||||
except (Error, OSError, ValueError, kit.tarfile.TarError):
|
||||
issues.append({"component": item["component"], "kind": item["kind"], "issue": "cache-file-unverified"})
|
||||
if ops._root_anchor_identity(root.lstat()) != identity:
|
||||
raise Error("cache root changed during inventory")
|
||||
have = {(item["component"], item["kind"]) for item in artifacts}
|
||||
for component, kinds in sorted(kit.REQUIRED_COMPONENT_KINDS.items()):
|
||||
for kind in sorted(kinds):
|
||||
if (component, kind) not in have:
|
||||
issues.append({"component": component, "kind": kind, "issue": "missing-artifact"})
|
||||
issues = sorted({(item["component"], item["kind"], item["issue"]) for item in issues})
|
||||
issues = [dict(zip(("component", "kind", "issue"), item)) for item in issues]
|
||||
existing_issues = [item for item in issues if item["component"] not in NATIVE_COMPONENTS]
|
||||
candidate = None
|
||||
if not issues:
|
||||
candidate = kit.manifest({
|
||||
"schema": kit.SCHEMA, "release_commit": value["release_commit"], "scope": "complete-target",
|
||||
"required_ids": [item["id"] for item in artifacts], "artifacts": artifacts,
|
||||
"targets": [{**value["target"],
|
||||
"container_platforms": sorted({container_platform, *kit.FIXED_ROLE_PLATFORMS.values()}),
|
||||
"deployment_contract_sha256": kit.DEPLOYMENT_CONTRACT_SHA256,
|
||||
"runtime_roles": [{"id": role, "component": component,
|
||||
"platform": kit.FIXED_ROLE_PLATFORMS.get(role, container_platform),
|
||||
"image_id": receipt["images"][role]} for role, component in kit.MAINTAINED_ROLES.items()],
|
||||
"artifact_ids": [item["id"] for item in artifacts]}]})
|
||||
report = {
|
||||
"schema": REPORT_SCHEMA, "status": "PASS" if candidate else "BLOCKED", "action": "inventory",
|
||||
"target_platform": target_platform, "release_commit": value["release_commit"],
|
||||
"artifacts_declared": len(artifacts), "runtime_roles_bound": len(receipt["images"]),
|
||||
"existing_runtime_inventory": "PASS" if not existing_issues else "BLOCKED",
|
||||
"clean_machine_inventory": "PASS" if candidate else "BLOCKED", "issues": issues,
|
||||
"manifest_sha256": hashlib.sha256(ops._canonical(candidate)).hexdigest() if candidate else None,
|
||||
"complete_target": candidate is not None, "offline_runtime": "NOT_RUN", "competition_ready": False,
|
||||
"installed_prerequisites": "NOT_CHECKED", "source_provenance": "DECLARED_NOT_VERIFIED",
|
||||
"redistribution": "local-only", "daemon_checked": False,
|
||||
"verification_scope": "receipt identities, declared pins, payload hashes and image structure; not installation or runtime acceptance",
|
||||
}
|
||||
return report, candidate
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", required=True, help="Private cache directory; files are never modified")
|
||||
parser.add_argument("--inventory", required=True, help="Operator-reviewed inventory recipe JSON")
|
||||
parser.add_argument("--expected-inventory-sha256", required=True, help="Detached trusted recipe digest")
|
||||
parser.add_argument("--lock", default=str(ROOT / "config/toolchain.lock.json"))
|
||||
parser.add_argument("--emit-manifest", help="Create a NEW assembly manifest only when the full inventory passes")
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument("--approval-id")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.apply and (not args.emit_manifest or not args.approval_id or not ops.APPROVAL_ID.fullmatch(args.approval_id)):
|
||||
raise Error("manifest publication requires output and a non-secret approval ID")
|
||||
value, raw = ops._read_json(args.inventory, ops.MAX_PROFILE_BYTES)
|
||||
kit._check_manifest_digest(raw, args.expected_inventory_sha256, required=True)
|
||||
lock, _ = ops._read_json(args.lock, ops.MAX_PROFILE_BYTES)
|
||||
report, candidate = inspect(args.root, value, lock)
|
||||
if args.emit_manifest:
|
||||
report["manifest_written"] = False
|
||||
if candidate and args.apply:
|
||||
ops._atomic_write_new(args.emit_manifest, ops._canonical(candidate))
|
||||
report["manifest_written"] = True
|
||||
elif candidate:
|
||||
report["action"] = "manifest-preview"
|
||||
print(json.dumps(report, sort_keys=True))
|
||||
return 0 if candidate else 2
|
||||
except (Error, OSError, ValueError, TypeError, RecursionError, kit.tarfile.TarError):
|
||||
print(json.dumps({"schema": REPORT_SCHEMA, "status": "BLOCKED", "error": "invalid-or-unreadable-inventory", "details": "suppressed", "exit_code": 2}, sort_keys=True))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user