auth.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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: str):
  108. try:
  109. scheme, credentials = auth_header.split(" ")
  110. return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
  111. except Exception:
  112. raise ValueError(ERROR_MESSAGES.INVALID_TOKEN)
  113. def get_current_user(
  114. request: Request,
  115. background_tasks: BackgroundTasks,
  116. auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
  117. ):
  118. token = None
  119. if auth_token is not None:
  120. token = auth_token.credentials
  121. if token is None and "token" in request.cookies:
  122. token = request.cookies.get("token")
  123. if token is None:
  124. raise HTTPException(status_code=403, detail="Not authenticated")
  125. # auth by api key
  126. if token.startswith("sk-"):
  127. if not request.state.enable_api_key:
  128. raise HTTPException(
  129. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  130. )
  131. if request.app.state.config.ENABLE_API_KEY_ENDPOINT_RESTRICTIONS:
  132. allowed_paths = [
  133. path.strip()
  134. for path in str(
  135. request.app.state.config.API_KEY_ALLOWED_ENDPOINTS
  136. ).split(",")
  137. ]
  138. # Check if the request path matches any allowed endpoint.
  139. if not any(
  140. request.url.path == allowed
  141. or request.url.path.startswith(allowed + "/")
  142. for allowed in allowed_paths
  143. ):
  144. raise HTTPException(
  145. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.API_KEY_NOT_ALLOWED
  146. )
  147. return get_current_user_by_api_key(token)
  148. # auth by jwt token
  149. try:
  150. data = decode_token(token)
  151. except Exception as e:
  152. raise HTTPException(
  153. status_code=status.HTTP_401_UNAUTHORIZED,
  154. detail="Invalid token",
  155. )
  156. if data is not None and "id" in data:
  157. user = Users.get_user_by_id(data["id"])
  158. if user is None:
  159. raise HTTPException(
  160. status_code=status.HTTP_401_UNAUTHORIZED,
  161. detail=ERROR_MESSAGES.INVALID_TOKEN,
  162. )
  163. else:
  164. # Refresh the user's last active timestamp asynchronously
  165. # to prevent blocking the request
  166. if background_tasks:
  167. background_tasks.add_task(Users.update_user_last_active_by_id, user.id)
  168. return user
  169. else:
  170. raise HTTPException(
  171. status_code=status.HTTP_401_UNAUTHORIZED,
  172. detail=ERROR_MESSAGES.UNAUTHORIZED,
  173. )
  174. def get_current_user_by_api_key(api_key: str):
  175. user = Users.get_user_by_api_key(api_key)
  176. if user is None:
  177. raise HTTPException(
  178. status_code=status.HTTP_401_UNAUTHORIZED,
  179. detail=ERROR_MESSAGES.INVALID_TOKEN,
  180. )
  181. else:
  182. Users.update_user_last_active_by_id(user.id)
  183. return user
  184. def get_verified_user(user=Depends(get_current_user)):
  185. if user.role not in {"user", "admin"}:
  186. raise HTTPException(
  187. status_code=status.HTTP_401_UNAUTHORIZED,
  188. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  189. )
  190. return user
  191. def get_admin_user(user=Depends(get_current_user)):
  192. if user.role != "admin":
  193. raise HTTPException(
  194. status_code=status.HTTP_401_UNAUTHORIZED,
  195. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  196. )
  197. return user