ghsa_status.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #!/usr/bin/env python3
  2. """Set or list the [status:...] tag on OliveTin's repository security advisories.
  3. Advisories in triage or draft carry a status tag at the end of their summary,
  4. so maintainers and reporters can see where each one is. The tag is removed
  5. when an advisory is published or closed, and before a CVE is requested.
  6. Usage:
  7. ghsa_status.py --list
  8. ghsa_status.py <GHSA-ID> <status>
  9. ghsa_status.py <GHSA-ID> clear
  10. Statuses: pending-review, awaiting-reporter, accepted, feedback-on-fix,
  11. pending-release. Requires the GitHub CLI (gh), authenticated with access to
  12. the repository's security advisories.
  13. """
  14. from __future__ import annotations
  15. import json
  16. import re
  17. import subprocess
  18. import sys
  19. REPO = "OliveTin/OliveTin"
  20. STATUSES = (
  21. "pending-review",
  22. "awaiting-reporter",
  23. "accepted",
  24. "feedback-on-fix",
  25. "pending-release",
  26. )
  27. OPEN_STATES = ("triage", "draft")
  28. TAG_PATTERN = re.compile(r"\s*\[status:[^\]]*\]\s*$")
  29. GHSA_PATTERN = re.compile(r"^GHSA(-[23456789cfghjmpqrvwx]{4}){3}$")
  30. def gh_api(path: str, method: str = "GET", body: dict | None = None, paginate: bool = False) -> object:
  31. command = ["gh", "api", "-X", method, path]
  32. if paginate:
  33. command += ["--paginate", "--slurp"]
  34. if body is not None:
  35. command += ["--input", "-"]
  36. result = subprocess.run(
  37. command,
  38. input=json.dumps(body) if body is not None else None,
  39. capture_output=True,
  40. text=True,
  41. check=False,
  42. )
  43. if result.returncode != 0:
  44. raise SystemExit(f"gh api {method} {path} failed: {result.stderr.strip() or result.stdout.strip()}")
  45. return json.loads(result.stdout)
  46. def strip_status(summary: str) -> str:
  47. return TAG_PATTERN.sub("", summary).rstrip()
  48. def current_status(summary: str) -> str:
  49. match = TAG_PATTERN.search(summary)
  50. if not match:
  51. return ""
  52. return match.group(0).strip()[len("[status:"):-1]
  53. def with_status(summary: str, status: str) -> str:
  54. base = strip_status(summary)
  55. if status == "clear":
  56. return base
  57. return f"{base} [status:{status}]"
  58. def list_advisories() -> int:
  59. pages = gh_api(f"/repos/{REPO}/security-advisories?per_page=100", paginate=True)
  60. advisories = [advisory for page in pages for advisory in page]
  61. problems = 0
  62. for advisory in advisories:
  63. status = current_status(advisory["summary"])
  64. is_open = advisory["state"] in OPEN_STATES
  65. note = ""
  66. if is_open and status not in STATUSES:
  67. note = " <- missing or unknown status"
  68. problems += 1
  69. elif not is_open and status:
  70. note = " <- should not have a status"
  71. problems += 1
  72. if is_open or status:
  73. print(f"{advisory['ghsa_id']} {advisory['state']:<9} {status or '-':<18} {strip_status(advisory['summary'])}{note}")
  74. return 1 if problems else 0
  75. def set_status(ghsa_id: str, status: str) -> int:
  76. if not GHSA_PATTERN.match(ghsa_id):
  77. raise SystemExit(f"Not a GHSA ID: {ghsa_id}")
  78. if status != "clear" and status not in STATUSES:
  79. raise SystemExit(f"Unknown status '{status}'. Use one of: {', '.join(STATUSES)}, or clear")
  80. advisory = gh_api(f"/repos/{REPO}/security-advisories/{ghsa_id}")
  81. if status != "clear" and advisory["state"] not in OPEN_STATES:
  82. raise SystemExit(f"{ghsa_id} is {advisory['state']}; only triage and draft advisories carry a status")
  83. summary = with_status(advisory["summary"], status)
  84. if summary == advisory["summary"]:
  85. print(f"{ghsa_id} already has that status.")
  86. return 0
  87. updated = gh_api(f"/repos/{REPO}/security-advisories/{ghsa_id}", method="PATCH", body={"summary": summary})
  88. print(f"{ghsa_id}: {updated['summary']}")
  89. return 0
  90. def main(argv: list[str]) -> int:
  91. if argv[1:] == ["--list"]:
  92. return list_advisories()
  93. if len(argv) == 3:
  94. return set_status(argv[1], argv[2])
  95. print(__doc__, file=sys.stderr)
  96. return 2
  97. if __name__ == "__main__":
  98. sys.exit(main(sys.argv))