4
0

ghsa_status.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. TRAILING_TAGS_PATTERN = re.compile(r"(?:\s*\[status:[^\]]*\])+\s*$")
  29. TAG_PATTERN = re.compile(r"\[status:([^\]]*)\]")
  30. GHSA_PATTERN = re.compile(r"^GHSA(-[23456789cfghjmpqrvwx]{4}){3}$")
  31. def gh_api(path: str, method: str = "GET", body: dict | None = None, paginate: bool = False) -> object:
  32. command = ["gh", "api", "-X", method, path]
  33. if paginate:
  34. command += ["--paginate", "--slurp"]
  35. if body is not None:
  36. command += ["--input", "-"]
  37. result = subprocess.run(
  38. command,
  39. input=json.dumps(body) if body is not None else None,
  40. capture_output=True,
  41. text=True,
  42. check=False,
  43. )
  44. if result.returncode != 0:
  45. raise SystemExit(f"gh api {method} {path} failed: {result.stderr.strip() or result.stdout.strip()}")
  46. return json.loads(result.stdout)
  47. def strip_status(summary: str) -> str:
  48. return TRAILING_TAGS_PATTERN.sub("", summary).rstrip()
  49. def status_tags(summary: str) -> list[str]:
  50. match = TRAILING_TAGS_PATTERN.search(summary)
  51. if not match:
  52. return []
  53. return TAG_PATTERN.findall(match.group(0))
  54. def has_valid_status(tags: list[str]) -> bool:
  55. return len(tags) == 1 and tags[0] in STATUSES
  56. def with_status(summary: str, status: str) -> str:
  57. base = strip_status(summary)
  58. if status == "clear":
  59. return base
  60. return f"{base} [status:{status}]"
  61. def list_advisories() -> int:
  62. pages = gh_api(f"/repos/{REPO}/security-advisories?per_page=100", paginate=True)
  63. advisories = [advisory for page in pages for advisory in page]
  64. problems = 0
  65. for advisory in advisories:
  66. tags = status_tags(advisory["summary"])
  67. is_open = advisory["state"] in OPEN_STATES
  68. note = ""
  69. if is_open and not has_valid_status(tags):
  70. note = " <- missing, unknown or multiple statuses"
  71. problems += 1
  72. elif not is_open and tags:
  73. note = " <- should not have a status"
  74. problems += 1
  75. if is_open or tags:
  76. shown = ",".join(tag or "(empty)" for tag in tags) or "-"
  77. print(f"{advisory['ghsa_id']} {advisory['state']:<9} {shown:<18} {strip_status(advisory['summary'])}{note}")
  78. return 1 if problems else 0
  79. def set_status(ghsa_id: str, status: str) -> int:
  80. if not GHSA_PATTERN.match(ghsa_id):
  81. raise SystemExit(f"Not a GHSA ID: {ghsa_id}")
  82. if status != "clear" and status not in STATUSES:
  83. raise SystemExit(f"Unknown status '{status}'. Use one of: {', '.join(STATUSES)}, or clear")
  84. advisory = gh_api(f"/repos/{REPO}/security-advisories/{ghsa_id}")
  85. if status != "clear" and advisory["state"] not in OPEN_STATES:
  86. raise SystemExit(f"{ghsa_id} is {advisory['state']}; only triage and draft advisories carry a status")
  87. summary = with_status(advisory["summary"], status)
  88. if summary == advisory["summary"]:
  89. print(f"{ghsa_id} already has that status.")
  90. return 0
  91. updated = gh_api(f"/repos/{REPO}/security-advisories/{ghsa_id}", method="PATCH", body={"summary": summary})
  92. print(f"{ghsa_id}: {updated['summary']}")
  93. return 0
  94. def main(argv: list[str]) -> int:
  95. if argv[1:] == ["--list"]:
  96. return list_advisories()
  97. if len(argv) == 3:
  98. return set_status(argv[1], argv[2])
  99. print(__doc__, file=sys.stderr)
  100. return 2
  101. if __name__ == "__main__":
  102. sys.exit(main(sys.argv))