auth.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Gateway-side relay authentication primitives. EXPERIMENTAL.
  2. WS upgrade auth (gateway -> connector): ``Authorization: Bearer <token>`` on the
  3. ``/relay`` upgrade, ``token = make_upgrade_token(gateway_id, secret)``. Wire bytes
  4. must match the connector's ``relayAuthToken.ts`` ``makeToken`` exactly:
  5. ``base64url(f"{payload}:{exp}:{sig}")`` with ``sig = HMAC_SHA256(f"{payload}:{exp}",
  6. secret).hexdigest()``. The connector verifies against a multi-secret rotation list.
  7. """
  8. from __future__ import annotations
  9. import base64
  10. import hashlib
  11. import hmac
  12. import time
  13. _DEFAULT_UPGRADE_TTL_SECONDS = 300 # connector makeUpgradeToken default
  14. def sign(payload: str, secret: str) -> str:
  15. """HMAC-SHA256 hex digest (UTF-8) — the connector's ``sign``."""
  16. return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
  17. def make_token(payload: str, secret: str, ttl_seconds: int = 0) -> str:
  18. """``base64url(f"{payload}:{exp}:{sig}")``; ``exp`` unix seconds (0 = never).
  19. base64url is unpadded to match Node's ``Buffer.toString("base64url")``.
  20. """
  21. exp = int(time.time()) + ttl_seconds if ttl_seconds > 0 else 0
  22. signed = f"{payload}:{exp}"
  23. raw = f"{signed}:{sign(signed, secret)}".encode()
  24. return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
  25. def make_upgrade_token(
  26. gateway_id: str, secret: str, ttl_seconds: int = _DEFAULT_UPGRADE_TTL_SECONDS
  27. ) -> str:
  28. """WS-upgrade bearer: ``payload = gateway_id`` (the connector peeks it to index its verify list)."""
  29. return make_token(gateway_id, secret, ttl_seconds)