managed_gateway_auth.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """First-party gateway bearer trust, ported from connectors-only 43608084f4."""
  2. import logging
  3. from typing import Callable, Optional
  4. from urllib.parse import urlsplit
  5. from tools.managed_tool_gateway import build_vendor_gateway_url, read_nous_access_token
  6. logger = logging.getLogger(__name__)
  7. def managed_gateway_origin() -> str:
  8. """Origin for on-origin managed vendors and media uploads."""
  9. return build_vendor_gateway_url("tool")
  10. def connector_gateway_origin() -> str:
  11. """Separate connector deployment; honors CONNECTOR_GATEWAY_URL."""
  12. return build_vendor_gateway_url("connector")
  13. def is_managed_nous_gateway_url(
  14. url: object,
  15. gateway_builder: Optional[Callable[[str], str]] = None,
  16. ) -> bool:
  17. """True when ``url`` is on one of the first-party gateway origins we build.
  18. Both first-party surfaces count: the media/on-origin-vendor host
  19. (:func:`managed_gateway_origin`) and the connectors host
  20. (:func:`connector_gateway_origin`). Each is compared as an exact
  21. ``(scheme, netloc)`` pair — never as a name or a domain suffix — so
  22. ``evil-connector-gateway.nousresearch.com.attacker.dev`` and an ``http``
  23. downgrade of a real host both stay outside the set.
  24. Anything granting a URL extra trust — our bearer, reading files off disk to
  25. upload — must gate on this, so an arbitrary URL can never inherit it.
  26. """
  27. if not isinstance(url, str) or not url.strip():
  28. return False
  29. build_origin = gateway_builder or build_vendor_gateway_url
  30. try:
  31. expected = {
  32. urlsplit(build_origin(label))[:2]
  33. for label in ("tool", "connector")
  34. }
  35. actual = urlsplit(url.strip())
  36. except ValueError:
  37. return False
  38. return bool(actual.scheme) and (actual.scheme, actual.netloc) in expected
  39. def managed_gateway_auth_headers(
  40. url: object,
  41. gateway_builder: Optional[Callable[[str], str]] = None,
  42. token_reader: Optional[Callable[[], Optional[str]]] = None,
  43. ) -> dict:
  44. """Live auth headers for a managed gateway URL, or ``{}`` when not managed.
  45. Read fresh on every call rather than cached: a Nous access token expires
  46. within the hour, and a long session would otherwise keep presenting a dead
  47. bearer. Returns ``{}`` rather than raising when no token is available, so a
  48. caller can report "sign in" instead of sending an unauthenticated request.
  49. """
  50. if not is_managed_nous_gateway_url(url, gateway_builder):
  51. return {}
  52. resolved_token_reader = token_reader or read_nous_access_token
  53. try:
  54. token = resolved_token_reader()
  55. except Exception as exc: # pragma: no cover — defensive
  56. logger.debug("Managed gateway token read failed for %s: %s", url, exc)
  57. return {}
  58. if not isinstance(token, str) or not token.strip():
  59. return {}
  60. from tools.managed_gateway_identity import user_agent
  61. return {"Authorization": f"Bearer {token.strip()}", "User-Agent": user_agent()}