authentication_utils.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. try:
  2. from ray._raylet import (
  3. AuthenticationMode,
  4. get_authentication_mode,
  5. validate_authentication_token,
  6. )
  7. _RAYLET_AVAILABLE = True
  8. except ImportError:
  9. # ray._raylet not available during doc builds
  10. _RAYLET_AVAILABLE = False
  11. def is_token_auth_enabled() -> bool:
  12. """Check if token authentication is enabled.
  13. Returns:
  14. bool: True if AUTH_MODE is set to "token".
  15. """
  16. if not _RAYLET_AVAILABLE:
  17. return False
  18. return get_authentication_mode() == AuthenticationMode.TOKEN
  19. def validate_request_token(auth_header: str) -> bool:
  20. """Validate the Authorization header from an HTTP request.
  21. Args:
  22. auth_header: The Authorization header value (e.g., "Bearer <token>")
  23. Returns:
  24. bool: True if token is valid, False otherwise
  25. """
  26. if not _RAYLET_AVAILABLE or not auth_header:
  27. return False
  28. # validate_authentication_token expects full "Bearer <token>" format
  29. # and performs equality comparison via C++ layer
  30. return validate_authentication_token(auth_header)
  31. def get_authentication_mode_name(mode: AuthenticationMode) -> str:
  32. """Convert AuthenticationMode enum value to string name.
  33. Args:
  34. mode: AuthenticationMode enum value from ray._raylet
  35. Returns:
  36. String name: "disabled", "token"
  37. """
  38. from ray._raylet import AuthenticationMode
  39. _MODE_NAMES = {
  40. AuthenticationMode.DISABLED: "disabled",
  41. AuthenticationMode.TOKEN: "token",
  42. }
  43. return _MODE_NAMES.get(mode, "unknown")