auth.py 7.2 KB

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