secret_rule.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """The one rule for what counts as a missing or placeholder secret.
  2. A required secret that is empty, unset or a placeholder means the project would
  3. run with no security (or with a value everyone has read in the docs). Every
  4. place that reads a required secret asks this rule and refuses on a bad value.
  5. Definition (case-insensitive, after stripping whitespace). A value is rejected
  6. when it is empty, or
  7. - starts with your_ your- changeme change-me replace-with replace_with
  8. xxx dp.st.your
  9. - is wrapped in <...>
  10. - contains example placeholder changeme
  11. - equals todo tbd admin password secret test
  12. The OpenTofu validations carry PLACEHOLDER_RE2, the same rule as one pattern;
  13. tests/test_secret_rule.py pins the copies to this file. The Spacelift hook
  14. script (scripts/spacelift/doppler-env.sh) has a POSIX shell copy, pinned the
  15. same way.
  16. Command line, used by the lab shell scripts (the value arrives on standard
  17. input so it never shows in a process list, and is never printed):
  18. printf '%s' "$VALUE" | python3 -I scripts/secret_rule.py NAME
  19. Exit 0 when the value is usable, 1 when it is empty or a placeholder (the
  20. message names NAME and never the value), 2 on bad usage.
  21. """
  22. from __future__ import annotations
  23. import re
  24. import sys
  25. # RE2-safe (no quote, no backslash) so it can sit inside an OpenTofu string.
  26. PLACEHOLDER_RE2 = (
  27. "(?i)(^(your[_-]|changeme|change-me|replace[_-]with|xxx|dp[.]st[.]your"
  28. "|(todo|tbd|admin|password|secret|test)$)|^<.*>$|example|placeholder|changeme)"
  29. )
  30. _PLACEHOLDER = re.compile(PLACEHOLDER_RE2)
  31. class SecretError(ValueError):
  32. """A required secret is empty, unset or a placeholder. Never holds the value."""
  33. def is_placeholder(value: str | None) -> bool:
  34. if value is None:
  35. return True
  36. value = value.strip()
  37. return value == "" or _PLACEHOLDER.search(value) is not None
  38. def require_secret(name: str, value: str | None) -> str:
  39. """Return value, or raise SecretError naming `name` (never the value)."""
  40. if is_placeholder(value):
  41. raise SecretError(
  42. f"{name} is empty or a placeholder. Set a real value (see README, Required secrets)."
  43. )
  44. assert value is not None
  45. return value
  46. def main(argv: list[str]) -> int:
  47. if len(argv) != 2 or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", argv[1]):
  48. print("usage: secret_rule.py NAME (the value is read from standard input)", file=sys.stderr)
  49. return 2
  50. try:
  51. require_secret(argv[1], sys.stdin.read().rstrip("\r\n"))
  52. except SecretError as err:
  53. print(err, file=sys.stderr)
  54. return 1
  55. return 0
  56. if __name__ == "__main__":
  57. sys.exit(main(sys.argv))