auth.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import logging
  2. import uuid
  3. import jwt
  4. import base64
  5. import hmac
  6. import hashlib
  7. import requests
  8. import os
  9. from datetime import UTC, datetime, timedelta
  10. from typing import Optional, Union, List, Dict
  11. from open_webui.models.users import Users
  12. from open_webui.constants import ERROR_MESSAGES
  13. from open_webui.env import WEBUI_SECRET_KEY, TRUSTED_SIGNATURE_KEY, STATIC_DIR, SRC_LOG_LEVELS
  14. from fastapi import BackgroundTasks, Depends, HTTPException, Request, Response, status
  15. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  16. from passlib.context import CryptContext
  17. logging.getLogger("passlib").setLevel(logging.ERROR)
  18. log = logging.getLogger(__name__)
  19. log.setLevel(SRC_LOG_LEVELS["OAUTH"])
  20. SESSION_SECRET = WEBUI_SECRET_KEY
  21. ALGORITHM = "HS256"
  22. ##############
  23. # Auth Utils
  24. ##############
  25. def verify_signature(payload: str, signature: str) -> bool:
  26. """
  27. Verifies the HMAC signature of the received payload.
  28. """
  29. try:
  30. expected_signature = base64.b64encode(
  31. hmac.new(TRUSTED_SIGNATURE_KEY, payload.encode(), hashlib.sha256).digest()
  32. ).decode()
  33. # Compare securely to prevent timing attacks
  34. return hmac.compare_digest(expected_signature, signature)
  35. except Exception:
  36. return False
  37. def override_static(path: str, content: str):
  38. # Ensure path is safe
  39. if "/" in path or ".." in path:
  40. log.error(f"Invalid path: {path}")
  41. return
  42. file_path = os.path.join(STATIC_DIR, path)
  43. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  44. with open(file_path, "wb") as f:
  45. f.write(base64.b64decode(content)) # Convert Base64 back to raw binary
  46. def get_license_data(app, key):
  47. if key:
  48. try:
  49. res = requests.post(
  50. "https://api.openwebui.com/api/v1/license",
  51. json={"key": key, "version": "1"},
  52. timeout=5,
  53. )
  54. if getattr(res, "ok", False):
  55. payload = getattr(res, "json", lambda: {})()
  56. for k, v in payload.items():
  57. if k == "resources":
  58. for p, c in v.items():
  59. globals().get("override_static", lambda a, b: None)(p, c)
  60. elif k == "user_count":
  61. setattr(app.state, "USER_COUNT", v)
  62. elif k == "webui_name":
  63. setattr(app.state, "WEBUI_NAME", v)
  64. return True
  65. else:
  66. log.error(
  67. f"License: retrieval issue: {getattr(res, 'text', 'unknown error')}"
  68. )
  69. except Exception as ex:
  70. log.exception(f"License: Uncaught Exception: {ex}")
  71. return False
  72. bearer_security = HTTPBearer(auto_error=False)
  73. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  74. def verify_password(plain_password, hashed_password):
  75. return (
  76. pwd_context.verify(plain_password, hashed_password) if hashed_password else None
  77. )
  78. def get_password_hash(password):
  79. return pwd_context.hash(password)
  80. def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str:
  81. payload = data.copy()
  82. if expires_delta:
  83. expire = datetime.now(UTC) + expires_delta
  84. payload.update({"exp": expire})
  85. encoded_jwt = jwt.encode(payload, SESSION_SECRET, algorithm=ALGORITHM)
  86. return encoded_jwt
  87. def decode_token(token: str) -> Optional[dict]:
  88. try:
  89. decoded = jwt.decode(token, SESSION_SECRET, algorithms=[ALGORITHM])
  90. return decoded
  91. except Exception:
  92. return None
  93. def extract_token_from_auth_header(auth_header: str):
  94. return auth_header[len("Bearer ") :]
  95. def create_api_key():
  96. key = str(uuid.uuid4()).replace("-", "")
  97. return f"sk-{key}"
  98. def get_http_authorization_cred(auth_header: str):
  99. try:
  100. scheme, credentials = auth_header.split(" ")
  101. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  102. except Exception:
  103. raise ValueError(ERROR_MESSAGES.INVALID_TOKEN)
  104. def get_current_user(
  105. request: Request,
  106. background_tasks: BackgroundTasks,
  107. auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
  108. ):
  109. token = None
  110. if auth_token is not None:
  111. token = auth_token.credentials
  112. if token is None and "token" in request.cookies:
  113. token = request.cookies.get("token")
  114. if token is None:
  115. raise HTTPException(status_code=403, detail="Not authenticated")
  116. # auth by api key
  117. if token.startswith("sk-"):
  118. if not request.state.enable_api_key:
  119. raise HTTPException(
  120. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  121. )
  122. if request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS:
  123. allowed_paths = [
  124. path.strip()
  125. for path in str(
  126. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS
  127. ).split(",")
  128. ]
  129. if request.url.path not in allowed_paths:
  130. raise HTTPException(
  131. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  132. )
  133. return get_current_user_by_api_key(token)
  134. # auth by jwt token
  135. try:
  136. data = decode_token(token)
  137. except Exception as e:
  138. raise HTTPException(
  139. status_code=status.HTTP_401_UNAUTHORIZED,
  140. detail="Invalid token",
  141. )
  142. if data is not None and "id" in data:
  143. user = Users.get_user_by_id(data["id"])
  144. if user is None:
  145. raise HTTPException(
  146. status_code=status.HTTP_401_UNAUTHORIZED,
  147. detail=ERROR_MESSAGES.INVALID_TOKEN,
  148. )
  149. else:
  150. # Refresh the user's last active timestamp asynchronously
  151. # to prevent blocking the request
  152. background_tasks.add_task(Users.update_user_last_active_by_id, user.id)
  153. return user
  154. else:
  155. raise HTTPException(
  156. status_code=status.HTTP_401_UNAUTHORIZED,
  157. detail=ERROR_MESSAGES.UNAUTHORIZED,
  158. )
  159. def get_current_user_by_api_key(api_key: str):
  160. user = Users.get_user_by_api_key(api_key)
  161. if user is None:
  162. raise HTTPException(
  163. status_code=status.HTTP_401_UNAUTHORIZED,
  164. detail=ERROR_MESSAGES.INVALID_TOKEN,
  165. )
  166. else:
  167. Users.update_user_last_active_by_id(user.id)
  168. return user
  169. def get_verified_user(user=Depends(get_current_user)):
  170. if user.role not in {"user", "admin"}:
  171. raise HTTPException(
  172. status_code=status.HTTP_401_UNAUTHORIZED,
  173. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  174. )
  175. return user
  176. def get_admin_user(user=Depends(get_current_user)):
  177. if user.role != "admin":
  178. raise HTTPException(
  179. status_code=status.HTTP_401_UNAUTHORIZED,
  180. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  181. )
  182. return user