auth.py 6.9 KB

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