approval_provenance.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Why a flagged command ran without a prompt.
  2. When a prior user decision (a ``command_allowlist`` entry, an 'always' approval, or an
  3. earlier approval in this session) covers every finding in a dangerous command, the guard still
  4. approves silently; these helpers attach that provenance to the guard result and turn it into
  5. the terminal tool's ``approval`` note, so the run is explained instead of looking like a bypass.
  6. Provenance never decides anything: callers build it only after the approval check passed.
  7. """
  8. def preapproved_result(findings: list[tuple[str, str]], scope_of) -> dict:
  9. """Approved guard result for *findings* ``[(pattern_key, description)]`` that are all already
  10. approved; ``scope_of(key)`` labels each one 'permanent' or 'session'."""
  11. return {
  12. "approved": True,
  13. "message": None,
  14. "pre_approved": [{"description": text, "scope": scope_of(key)} for key, text in findings],
  15. }
  16. def allowlisted_result(rule: str, description: str) -> dict:
  17. """Approved guard result for a flagged command waved through by a ``command_allowlist`` entry."""
  18. return {
  19. "approved": True,
  20. "message": None,
  21. "pre_approved": [{"description": description, "scope": "allowlist", "rule": rule}],
  22. }
  23. _SCOPE_PHRASES = {
  24. "allowlist": "the command_allowlist entry `{rule}` in config.yaml",
  25. "permanent": "an 'always' approval the user saved earlier",
  26. # Both a 'session' and an 'always' answer session-approve their keys, so a session-only grant may
  27. # be what is left of an 'always' answer whose command_allowlist entry the operator removed.
  28. "session": "an approval the user gave earlier in this session",
  29. }
  30. def preapproval_note(entries: list[dict]) -> str:
  31. """One-sentence ``approval`` note for a guard result's ``pre_approved`` entries."""
  32. flagged = "; ".join(entry["description"] for entry in entries)
  33. reasons = []
  34. for entry in entries:
  35. phrase = _SCOPE_PHRASES[entry["scope"]].format(rule=entry.get("rule", ""))
  36. if len(entries) > 1:
  37. phrase = f"{entry['description']}: {phrase}"
  38. if phrase not in reasons:
  39. reasons.append(phrase)
  40. return f"Command was flagged ({flagged}) and auto-approved by {'; '.join(reasons)}."