_base.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """
  2. Shared low-level helpers for the security-guidance hook modules.
  3. This module exists so that ``patterns``/``session_state``/``gitutil`` can use
  4. ``debug_log`` without importing ``security_reminder_hook`` (which would be a
  5. circular import). It must stay free of any other intra-plugin imports.
  6. """
  7. import json
  8. import os
  9. import threading
  10. from datetime import datetime
  11. # Debug log file. Lives under the plugin state dir (default ~/.claude/security/)
  12. # rather than /tmp because /tmp is world-writable on multi-user hosts (TOCTOU /
  13. # symlink-attack surface, cross-user log leakage). Overridable per-process via
  14. # SECURITY_GUIDANCE_DEBUG_LOG, or per-state-dir via SECURITY_WARNINGS_STATE_DIR.
  15. _DEFAULT_STATE_DIR = os.path.expanduser(
  16. os.environ.get("SECURITY_WARNINGS_STATE_DIR") or "~/.claude/security"
  17. )
  18. DEBUG_LOG_FILE = os.environ.get("SECURITY_GUIDANCE_DEBUG_LOG") or os.path.join(
  19. _DEFAULT_STATE_DIR, "log.txt"
  20. )
  21. # Cap the debug log so parallel-worker fleets don't fill disk. When the active
  22. # file exceeds this it's atomically rotated to <file>.1 (overwriting any prior
  23. # rotation), so total disk stays ~2× this.
  24. DEBUG_LOG_MAX_BYTES = 1 * 1024 * 1024
  25. def debug_log(message):
  26. """Append debug message to log file with timestamp."""
  27. try:
  28. # Ensure parent dir exists — first hook invocation on a fresh install
  29. # creates ~/.claude/security/ if it isn't already there. 0700 so other
  30. # local users can't read review/debug output (only applies on creation).
  31. try:
  32. os.makedirs(os.path.dirname(DEBUG_LOG_FILE), mode=0o700, exist_ok=True)
  33. except OSError:
  34. pass
  35. try:
  36. if os.path.getsize(DEBUG_LOG_FILE) > DEBUG_LOG_MAX_BYTES:
  37. # os.replace is atomic on POSIX; under a racing fleet the loser
  38. # gets FileNotFoundError, which is fine — the append below
  39. # recreates the file.
  40. os.replace(DEBUG_LOG_FILE, DEBUG_LOG_FILE + ".1")
  41. except OSError:
  42. pass
  43. timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
  44. # 0600 on creation; existing files keep their mode.
  45. fd = os.open(DEBUG_LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
  46. with os.fdopen(fd, "a") as f:
  47. f.write(f"[{timestamp}] {message}\n")
  48. except Exception:
  49. pass
  50. # Provenance tag prepended to injected/emitted text so a reader (especially a
  51. # model hardened against prompt injection) can recognize the source. Not an
  52. # authority claim — an attacker could spoof the exact string; the tag is a
  53. # signpost so the agent can ask the operator "is this from your plugin?" with
  54. # a concrete reference instead of treating it as unknown-actor injection.
  55. # Some autonomous-agent setups flag un-attributed injected text as prompt
  56. # injection and stall; the banner makes the provenance explicit.
  57. PROVENANCE_TAG = "[from security-guidance@claude-code-plugins plugin]"
  58. PROVENANCE_BANNER = (
  59. "[from security-guidance@claude-code-plugins plugin — automated "
  60. "security review, not user input.]"
  61. )
  62. def _read_plugin_version_int():
  63. """Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the
  64. bool|number metrics constraint. Returns 0 if unreadable."""
  65. try:
  66. with open(os.path.join(os.path.dirname(__file__), "..", ".claude-plugin", "plugin.json")) as f:
  67. v = json.load(f)["version"]
  68. major, minor, patch = (int(x) for x in v.split(".")[:3])
  69. return major * 10000 + minor * 100 + patch
  70. except Exception:
  71. return 0
  72. _PV = _read_plugin_version_int()
  73. # ──────────────────────────────────────────────────────────────────────────
  74. # Token-usage accumulator. Each hook invocation is a fresh subprocess, so a
  75. # module-global is naturally per-invocation. _call_claude_dual_or and
  76. # _agentic_review_with_race run legs in ThreadPoolExecutor → lock required.
  77. # Emitted via _usage_metrics() into the existing emit_metrics() channel so
  78. # hook metrics rows carry per-invocation token/cost totals
  79. # alongside the existing skip_reason / vulns_found fields.
  80. _USAGE = {"in": 0, "out": 0, "cr": 0, "cw": 0, "cost": 0.0, "n": 0}
  81. _USAGE_LOCK = threading.Lock()
  82. # $/Mtok (input, output). Used only for the raw-HTTP path; the SDK path
  83. # reports total_cost_usd directly. Cache reads/writes are priced at the
  84. # canonical 0.1×/1.25× of input. Unknown models fall back to sonnet pricing
  85. # so cost_usd is never silently zero. Re-pricing downstream from the raw tok_*
  86. # fields is the source of truth — cost_usd here is a convenience rollup.
  87. _PRICE_PER_MTOK = {
  88. "claude-haiku-4-5": (1.0, 5.0),
  89. "claude-sonnet-4-6": (3.0, 15.0),
  90. "claude-opus-4-6": (15.0, 75.0),
  91. "claude-opus-4-7": (5.0, 25.0),
  92. }
  93. _PRICE_DEFAULT = (3.0, 15.0)
  94. def _record_usage(usage, model, cost_usd=None):
  95. """Accumulate one API response's token usage. `usage` is the Anthropic
  96. `usage` dict (HTTP) or the SDK ResultMessage.usage dict — both use the
  97. same key names. `cost_usd` (SDK-provided) is preferred when present;
  98. otherwise computed from _PRICE_PER_MTOK keyed on the response model id
  99. (longest-prefix match so `claude-sonnet-4-6-20251015` → sonnet row)."""
  100. if not usage and cost_usd is None:
  101. return
  102. u = usage or {}
  103. try:
  104. i = int(u.get("input_tokens") or 0)
  105. o = int(u.get("output_tokens") or 0)
  106. cr = int(u.get("cache_read_input_tokens") or 0)
  107. cw = int(u.get("cache_creation_input_tokens") or 0)
  108. except (TypeError, ValueError):
  109. return
  110. if cost_usd is None:
  111. pin, pout = _PRICE_DEFAULT
  112. m = (model or "").lower()
  113. for k, v in sorted(_PRICE_PER_MTOK.items(), key=lambda kv: -len(kv[0])):
  114. if m.startswith(k):
  115. pin, pout = v
  116. break
  117. cost_usd = (i * pin + o * pout + cr * pin * 0.1 + cw * pin * 1.25) / 1_000_000
  118. with _USAGE_LOCK:
  119. _USAGE["in"] += i
  120. _USAGE["out"] += o
  121. _USAGE["cr"] += cr
  122. _USAGE["cw"] += cw
  123. _USAGE["cost"] += float(cost_usd or 0.0)
  124. _USAGE["n"] += 1
  125. def _usage_metrics():
  126. """Snapshot the accumulator as metric keys. Returns {} when no API calls
  127. were made so skip-path emits don't burn key budget. cost_usd rounded to
  128. 1e-6 to keep the float finite/short for the zod schema."""
  129. with _USAGE_LOCK:
  130. if _USAGE["n"] == 0:
  131. return {}
  132. return {
  133. "tok_in": _USAGE["in"],
  134. "tok_out": _USAGE["out"],
  135. "tok_cache_r": _USAGE["cr"],
  136. "tok_cache_w": _USAGE["cw"],
  137. "cost_usd": round(_USAGE["cost"], 6),
  138. "api_calls": _USAGE["n"],
  139. }