oauth.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. import base64
  2. import copy
  3. import hashlib
  4. import logging
  5. import mimetypes
  6. import sys
  7. import urllib
  8. import uuid
  9. import json
  10. from datetime import datetime, timedelta
  11. import re
  12. import fnmatch
  13. import time
  14. import secrets
  15. from cryptography.fernet import Fernet
  16. import aiohttp
  17. from authlib.integrations.starlette_client import OAuth
  18. from authlib.oidc.core import UserInfo
  19. from fastapi import (
  20. HTTPException,
  21. status,
  22. )
  23. from starlette.responses import RedirectResponse
  24. from typing import Optional
  25. from open_webui.models.auths import Auths
  26. from open_webui.models.oauth_sessions import OAuthSessions
  27. from open_webui.models.users import Users
  28. from open_webui.models.groups import Groups, GroupModel, GroupUpdateForm, GroupForm
  29. from open_webui.config import (
  30. DEFAULT_USER_ROLE,
  31. ENABLE_OAUTH_SIGNUP,
  32. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  33. OAUTH_PROVIDERS,
  34. ENABLE_OAUTH_ROLE_MANAGEMENT,
  35. ENABLE_OAUTH_GROUP_MANAGEMENT,
  36. ENABLE_OAUTH_GROUP_CREATION,
  37. OAUTH_BLOCKED_GROUPS,
  38. OAUTH_GROUPS_SEPARATOR,
  39. OAUTH_ROLES_CLAIM,
  40. OAUTH_SUB_CLAIM,
  41. OAUTH_GROUPS_CLAIM,
  42. OAUTH_EMAIL_CLAIM,
  43. OAUTH_PICTURE_CLAIM,
  44. OAUTH_USERNAME_CLAIM,
  45. OAUTH_ALLOWED_ROLES,
  46. OAUTH_ADMIN_ROLES,
  47. OAUTH_ALLOWED_DOMAINS,
  48. OAUTH_UPDATE_PICTURE_ON_LOGIN,
  49. WEBHOOK_URL,
  50. JWT_EXPIRES_IN,
  51. AppConfig,
  52. )
  53. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  54. from open_webui.env import (
  55. AIOHTTP_CLIENT_SESSION_SSL,
  56. WEBUI_NAME,
  57. WEBUI_AUTH_COOKIE_SAME_SITE,
  58. WEBUI_AUTH_COOKIE_SECURE,
  59. ENABLE_OAUTH_ID_TOKEN_COOKIE,
  60. ENABLE_OAUTH_EMAIL_FALLBACK,
  61. OAUTH_CLIENT_INFO_ENCRYPTION_KEY,
  62. )
  63. from open_webui.utils.misc import parse_duration
  64. from open_webui.utils.auth import get_password_hash, create_token
  65. from open_webui.utils.webhook import post_webhook
  66. from mcp.shared.auth import (
  67. OAuthClientMetadata,
  68. OAuthMetadata,
  69. )
  70. from authlib.oauth2.rfc6749.errors import OAuth2Error
  71. class OAuthClientInformationFull(OAuthClientMetadata):
  72. issuer: Optional[str] = None # URL of the OAuth server that issued this client
  73. client_id: str
  74. client_secret: str | None = None
  75. client_id_issued_at: int | None = None
  76. client_secret_expires_at: int | None = None
  77. server_metadata: Optional[OAuthMetadata] = None # Fetched from the OAuth server
  78. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  79. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  80. log = logging.getLogger(__name__)
  81. log.setLevel(SRC_LOG_LEVELS["OAUTH"])
  82. auth_manager_config = AppConfig()
  83. auth_manager_config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  84. auth_manager_config.ENABLE_OAUTH_SIGNUP = ENABLE_OAUTH_SIGNUP
  85. auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL = OAUTH_MERGE_ACCOUNTS_BY_EMAIL
  86. auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  87. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT = ENABLE_OAUTH_GROUP_MANAGEMENT
  88. auth_manager_config.ENABLE_OAUTH_GROUP_CREATION = ENABLE_OAUTH_GROUP_CREATION
  89. auth_manager_config.OAUTH_BLOCKED_GROUPS = OAUTH_BLOCKED_GROUPS
  90. auth_manager_config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  91. auth_manager_config.OAUTH_SUB_CLAIM = OAUTH_SUB_CLAIM
  92. auth_manager_config.OAUTH_GROUPS_CLAIM = OAUTH_GROUPS_CLAIM
  93. auth_manager_config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  94. auth_manager_config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  95. auth_manager_config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  96. auth_manager_config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  97. auth_manager_config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  98. auth_manager_config.OAUTH_ALLOWED_DOMAINS = OAUTH_ALLOWED_DOMAINS
  99. auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
  100. auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  101. auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN = OAUTH_UPDATE_PICTURE_ON_LOGIN
  102. FERNET = None
  103. if len(OAUTH_CLIENT_INFO_ENCRYPTION_KEY) != 44:
  104. key_bytes = hashlib.sha256(OAUTH_CLIENT_INFO_ENCRYPTION_KEY.encode()).digest()
  105. OAUTH_CLIENT_INFO_ENCRYPTION_KEY = base64.urlsafe_b64encode(key_bytes)
  106. else:
  107. OAUTH_CLIENT_INFO_ENCRYPTION_KEY = OAUTH_CLIENT_INFO_ENCRYPTION_KEY.encode()
  108. try:
  109. FERNET = Fernet(OAUTH_CLIENT_INFO_ENCRYPTION_KEY)
  110. except Exception as e:
  111. log.error(f"Error initializing Fernet with provided key: {e}")
  112. raise
  113. def encrypt_data(data) -> str:
  114. """Encrypt data for storage"""
  115. try:
  116. data_json = json.dumps(data)
  117. encrypted = FERNET.encrypt(data_json.encode()).decode()
  118. return encrypted
  119. except Exception as e:
  120. log.error(f"Error encrypting data: {e}")
  121. raise
  122. def decrypt_data(data: str):
  123. """Decrypt data from storage"""
  124. try:
  125. decrypted = FERNET.decrypt(data.encode()).decode()
  126. return json.loads(decrypted)
  127. except Exception as e:
  128. log.error(f"Error decrypting data: {e}")
  129. raise
  130. def _build_oauth_callback_error_message(e: Exception) -> str:
  131. """
  132. Produce a user-facing callback error string with actionable context.
  133. Keeps the message short and strips newlines for safe redirect usage.
  134. """
  135. if isinstance(e, OAuth2Error):
  136. parts = [p for p in [e.error, e.description] if p]
  137. detail = " - ".join(parts)
  138. elif isinstance(e, HTTPException):
  139. detail = e.detail if isinstance(e.detail, str) else str(e.detail)
  140. elif isinstance(e, aiohttp.ClientResponseError):
  141. detail = f"Upstream provider returned {e.status}: {e.message}"
  142. elif isinstance(e, aiohttp.ClientError):
  143. detail = str(e)
  144. elif isinstance(e, KeyError):
  145. missing = str(e).strip("'")
  146. if missing.lower() == "state":
  147. detail = "Missing state parameter in callback (session may have expired)"
  148. else:
  149. detail = f"Missing expected key '{missing}' in OAuth response"
  150. else:
  151. detail = str(e)
  152. detail = detail.replace("\n", " ").strip()
  153. if not detail:
  154. detail = e.__class__.__name__
  155. message = f"OAuth callback failed: {detail}"
  156. return message[:197] + "..." if len(message) > 200 else message
  157. def is_in_blocked_groups(group_name: str, groups: list) -> bool:
  158. """
  159. Check if a group name matches any blocked pattern.
  160. Supports exact matches, shell-style wildcards (*, ?), and regex patterns.
  161. Args:
  162. group_name: The group name to check
  163. groups: List of patterns to match against
  164. Returns:
  165. True if the group is blocked, False otherwise
  166. """
  167. if not groups:
  168. return False
  169. for group_pattern in groups:
  170. if not group_pattern: # Skip empty patterns
  171. continue
  172. # Exact match
  173. if group_name == group_pattern:
  174. return True
  175. # Try as regex pattern first if it contains regex-specific characters
  176. if any(
  177. char in group_pattern
  178. for char in ["^", "$", "[", "]", "(", ")", "{", "}", "+", "\\", "|"]
  179. ):
  180. try:
  181. # Use the original pattern as-is for regex matching
  182. if re.search(group_pattern, group_name):
  183. return True
  184. except re.error:
  185. # If regex is invalid, fall through to wildcard check
  186. pass
  187. # Shell-style wildcard match (supports * and ?)
  188. if "*" in group_pattern or "?" in group_pattern:
  189. if fnmatch.fnmatch(group_name, group_pattern):
  190. return True
  191. return False
  192. def get_parsed_and_base_url(server_url) -> tuple[urllib.parse.ParseResult, str]:
  193. parsed = urllib.parse.urlparse(server_url)
  194. base_url = f"{parsed.scheme}://{parsed.netloc}"
  195. return parsed, base_url
  196. def get_discovery_urls(server_url) -> list[str]:
  197. parsed, base_url = get_parsed_and_base_url(server_url)
  198. urls = [
  199. urllib.parse.urljoin(base_url, "/.well-known/oauth-authorization-server"),
  200. urllib.parse.urljoin(base_url, "/.well-known/openid-configuration"),
  201. ]
  202. if parsed.path and parsed.path != "/":
  203. urls.append(
  204. urllib.parse.urljoin(
  205. base_url,
  206. f"/.well-known/oauth-authorization-server{parsed.path.rstrip('/')}",
  207. )
  208. )
  209. urls.append(
  210. urllib.parse.urljoin(
  211. base_url, f"/.well-known/openid-configuration{parsed.path.rstrip('/')}"
  212. )
  213. )
  214. return urls
  215. # TODO: Some OAuth providers require Initial Access Tokens (IATs) for dynamic client registration.
  216. # This is not currently supported.
  217. async def get_oauth_client_info_with_dynamic_client_registration(
  218. request,
  219. client_id: str,
  220. oauth_server_url: str,
  221. oauth_server_key: Optional[str] = None,
  222. ) -> OAuthClientInformationFull:
  223. try:
  224. oauth_server_metadata = None
  225. oauth_server_metadata_url = None
  226. redirect_base_url = (
  227. str(request.app.state.config.WEBUI_URL or request.base_url)
  228. ).rstrip("/")
  229. oauth_client_metadata = OAuthClientMetadata(
  230. client_name="Open WebUI",
  231. redirect_uris=[f"{redirect_base_url}/oauth/clients/{client_id}/callback"],
  232. grant_types=["authorization_code", "refresh_token"],
  233. response_types=["code"],
  234. token_endpoint_auth_method="client_secret_post",
  235. )
  236. # Attempt to fetch OAuth server metadata to get registration endpoint & scopes
  237. discovery_urls = get_discovery_urls(oauth_server_url)
  238. for url in discovery_urls:
  239. async with aiohttp.ClientSession(trust_env=True) as session:
  240. async with session.get(
  241. url, ssl=AIOHTTP_CLIENT_SESSION_SSL
  242. ) as oauth_server_metadata_response:
  243. if oauth_server_metadata_response.status == 200:
  244. try:
  245. oauth_server_metadata = OAuthMetadata.model_validate(
  246. await oauth_server_metadata_response.json()
  247. )
  248. oauth_server_metadata_url = url
  249. if (
  250. oauth_client_metadata.scope is None
  251. and oauth_server_metadata.scopes_supported is not None
  252. ):
  253. oauth_client_metadata.scope = " ".join(
  254. oauth_server_metadata.scopes_supported
  255. )
  256. break
  257. except Exception as e:
  258. log.error(f"Error parsing OAuth metadata from {url}: {e}")
  259. continue
  260. registration_url = None
  261. if oauth_server_metadata and oauth_server_metadata.registration_endpoint:
  262. registration_url = str(oauth_server_metadata.registration_endpoint)
  263. else:
  264. _, base_url = get_parsed_and_base_url(oauth_server_url)
  265. registration_url = urllib.parse.urljoin(base_url, "/register")
  266. registration_data = oauth_client_metadata.model_dump(
  267. exclude_none=True,
  268. mode="json",
  269. by_alias=True,
  270. )
  271. # Perform dynamic client registration and return client info
  272. async with aiohttp.ClientSession(trust_env=True) as session:
  273. async with session.post(
  274. registration_url, json=registration_data, ssl=AIOHTTP_CLIENT_SESSION_SSL
  275. ) as oauth_client_registration_response:
  276. try:
  277. registration_response_json = (
  278. await oauth_client_registration_response.json()
  279. )
  280. oauth_client_info = OAuthClientInformationFull.model_validate(
  281. {
  282. **registration_response_json,
  283. **{"issuer": oauth_server_metadata_url},
  284. **{"server_metadata": oauth_server_metadata},
  285. }
  286. )
  287. log.info(
  288. f"Dynamic client registration successful at {registration_url}, client_id: {oauth_client_info.client_id}"
  289. )
  290. return oauth_client_info
  291. except Exception as e:
  292. error_text = None
  293. try:
  294. error_text = await oauth_client_registration_response.text()
  295. log.error(
  296. f"Dynamic client registration failed at {registration_url}: {oauth_client_registration_response.status} - {error_text}"
  297. )
  298. except Exception as e:
  299. pass
  300. log.error(f"Error parsing client registration response: {e}")
  301. raise Exception(
  302. f"Dynamic client registration failed: {error_text}"
  303. if error_text
  304. else "Error parsing client registration response"
  305. )
  306. raise Exception("Dynamic client registration failed")
  307. except Exception as e:
  308. log.error(f"Exception during dynamic client registration: {e}")
  309. raise e
  310. class OAuthClientManager:
  311. def __init__(self, app):
  312. self.oauth = OAuth()
  313. self.app = app
  314. self.clients = {}
  315. def add_client(self, client_id, oauth_client_info: OAuthClientInformationFull):
  316. kwargs = {
  317. "name": client_id,
  318. "client_id": oauth_client_info.client_id,
  319. "client_secret": oauth_client_info.client_secret,
  320. "client_kwargs": (
  321. {"scope": oauth_client_info.scope} if oauth_client_info.scope else {}
  322. ),
  323. "server_metadata_url": (
  324. oauth_client_info.issuer if oauth_client_info.issuer else None
  325. ),
  326. }
  327. if (
  328. oauth_client_info.server_metadata
  329. and oauth_client_info.server_metadata.code_challenge_methods_supported
  330. ):
  331. if (
  332. isinstance(
  333. oauth_client_info.server_metadata.code_challenge_methods_supported,
  334. list,
  335. )
  336. and "S256"
  337. in oauth_client_info.server_metadata.code_challenge_methods_supported
  338. ):
  339. kwargs["code_challenge_method"] = "S256"
  340. self.clients[client_id] = {
  341. "client": self.oauth.register(**kwargs),
  342. "client_info": oauth_client_info,
  343. }
  344. return self.clients[client_id]
  345. def remove_client(self, client_id):
  346. if client_id in self.clients:
  347. del self.clients[client_id]
  348. log.info(f"Removed OAuth client {client_id}")
  349. if hasattr(self.oauth, "_clients"):
  350. if client_id in self.oauth._clients:
  351. self.oauth._clients.pop(client_id, None)
  352. if hasattr(self.oauth, "_registry"):
  353. if client_id in self.oauth._registry:
  354. self.oauth._registry.pop(client_id, None)
  355. return True
  356. async def _preflight_authorization_url(
  357. self, client, client_info: OAuthClientInformationFull
  358. ) -> bool:
  359. # TODO: Replace this logic with a more robust OAuth client registration validation
  360. # Only perform preflight checks for Starlette OAuth clients
  361. if not hasattr(client, "create_authorization_url"):
  362. return True
  363. redirect_uri = None
  364. if client_info.redirect_uris:
  365. redirect_uri = str(client_info.redirect_uris[0])
  366. try:
  367. auth_data = await client.create_authorization_url(redirect_uri=redirect_uri)
  368. authorization_url = auth_data.get("url")
  369. if not authorization_url:
  370. return True
  371. except Exception as e:
  372. log.debug(
  373. f"Skipping OAuth preflight for client {client_info.client_id}: {e}",
  374. )
  375. return True
  376. try:
  377. async with aiohttp.ClientSession(trust_env=True) as session:
  378. async with session.get(
  379. authorization_url,
  380. allow_redirects=False,
  381. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  382. ) as resp:
  383. if resp.status < 400:
  384. return True
  385. response_text = await resp.text()
  386. error = None
  387. error_description = ""
  388. content_type = resp.headers.get("content-type", "")
  389. if "application/json" in content_type:
  390. try:
  391. payload = json.loads(response_text)
  392. error = payload.get("error")
  393. error_description = payload.get("error_description", "")
  394. except:
  395. pass
  396. else:
  397. error_description = response_text
  398. error_message = f"{error or ''} {error_description or ''}".lower()
  399. if any(
  400. keyword in error_message
  401. for keyword in ("invalid_client", "invalid client", "client id")
  402. ):
  403. log.warning(
  404. f"OAuth client preflight detected invalid registration for {client_info.client_id}: {error} {error_description}"
  405. )
  406. return False
  407. except Exception as e:
  408. log.debug(
  409. f"Skipping OAuth preflight network check for client {client_info.client_id}: {e}"
  410. )
  411. return True
  412. def get_client(self, client_id):
  413. client = self.clients.get(client_id)
  414. return client["client"] if client else None
  415. def get_client_info(self, client_id):
  416. client = self.clients.get(client_id)
  417. return client["client_info"] if client else None
  418. def get_server_metadata_url(self, client_id):
  419. if client_id in self.clients:
  420. client = self.clients[client_id]
  421. return (
  422. client._server_metadata_url
  423. if hasattr(client, "_server_metadata_url")
  424. else None
  425. )
  426. return None
  427. async def get_oauth_token(
  428. self, user_id: str, client_id: str, force_refresh: bool = False
  429. ):
  430. """
  431. Get a valid OAuth token for the user, automatically refreshing if needed.
  432. Args:
  433. user_id: The user ID
  434. client_id: The OAuth client ID (provider)
  435. force_refresh: Force token refresh even if current token appears valid
  436. Returns:
  437. dict: OAuth token data with access_token, or None if no valid token available
  438. """
  439. try:
  440. # Get the OAuth session
  441. session = OAuthSessions.get_session_by_provider_and_user_id(
  442. client_id, user_id
  443. )
  444. if not session:
  445. log.warning(
  446. f"No OAuth session found for user {user_id}, client_id {client_id}"
  447. )
  448. return None
  449. if force_refresh or datetime.now() + timedelta(
  450. minutes=5
  451. ) >= datetime.fromtimestamp(session.expires_at):
  452. log.debug(
  453. f"Token refresh needed for user {user_id}, client_id {session.provider}"
  454. )
  455. refreshed_token = await self._refresh_token(session)
  456. if refreshed_token:
  457. return refreshed_token
  458. else:
  459. log.warning(
  460. f"Token refresh failed for user {user_id}, client_id {session.provider}, deleting session {session.id}"
  461. )
  462. OAuthSessions.delete_session_by_id(session.id)
  463. return None
  464. return session.token
  465. except Exception as e:
  466. log.error(f"Error getting OAuth token for user {user_id}: {e}")
  467. return None
  468. async def _refresh_token(self, session) -> dict:
  469. """
  470. Refresh an OAuth token if needed, with concurrency protection.
  471. Args:
  472. session: The OAuth session object
  473. Returns:
  474. dict: Refreshed token data, or None if refresh failed
  475. """
  476. try:
  477. # Perform the actual refresh
  478. refreshed_token = await self._perform_token_refresh(session)
  479. if refreshed_token:
  480. # Update the session with new token data
  481. session = OAuthSessions.update_session_by_id(
  482. session.id, refreshed_token
  483. )
  484. log.info(f"Successfully refreshed token for session {session.id}")
  485. return session.token
  486. else:
  487. log.error(f"Failed to refresh token for session {session.id}")
  488. return None
  489. except Exception as e:
  490. log.error(f"Error refreshing token for session {session.id}: {e}")
  491. return None
  492. async def _perform_token_refresh(self, session) -> dict:
  493. """
  494. Perform the actual OAuth token refresh.
  495. Args:
  496. session: The OAuth session object
  497. Returns:
  498. dict: New token data, or None if refresh failed
  499. """
  500. client_id = session.provider
  501. token_data = session.token
  502. if not token_data.get("refresh_token"):
  503. log.warning(f"No refresh token available for session {session.id}")
  504. return None
  505. try:
  506. client = self.get_client(client_id)
  507. if not client:
  508. log.error(f"No OAuth client found for provider {client_id}")
  509. return None
  510. token_endpoint = None
  511. async with aiohttp.ClientSession(trust_env=True) as session_http:
  512. async with session_http.get(
  513. self.get_server_metadata_url(client_id)
  514. ) as r:
  515. if r.status == 200:
  516. openid_data = await r.json()
  517. token_endpoint = openid_data.get("token_endpoint")
  518. else:
  519. log.error(
  520. f"Failed to fetch OpenID configuration for client_id {client_id}"
  521. )
  522. if not token_endpoint:
  523. log.error(f"No token endpoint found for client_id {client_id}")
  524. return None
  525. # Prepare refresh request
  526. refresh_data = {
  527. "grant_type": "refresh_token",
  528. "refresh_token": token_data["refresh_token"],
  529. "client_id": client.client_id,
  530. }
  531. if hasattr(client, "client_secret") and client.client_secret:
  532. refresh_data["client_secret"] = client.client_secret
  533. # Make refresh request
  534. async with aiohttp.ClientSession(trust_env=True) as session_http:
  535. async with session_http.post(
  536. token_endpoint,
  537. data=refresh_data,
  538. headers={"Content-Type": "application/x-www-form-urlencoded"},
  539. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  540. ) as r:
  541. if r.status == 200:
  542. new_token_data = await r.json()
  543. # Merge with existing token data (preserve refresh_token if not provided)
  544. if "refresh_token" not in new_token_data:
  545. new_token_data["refresh_token"] = token_data[
  546. "refresh_token"
  547. ]
  548. # Add timestamp for tracking
  549. new_token_data["issued_at"] = datetime.now().timestamp()
  550. # Calculate expires_at if we have expires_in
  551. if (
  552. "expires_in" in new_token_data
  553. and "expires_at" not in new_token_data
  554. ):
  555. new_token_data["expires_at"] = int(
  556. datetime.now().timestamp()
  557. + new_token_data["expires_in"]
  558. )
  559. log.debug(f"Token refresh successful for client_id {client_id}")
  560. return new_token_data
  561. else:
  562. error_text = await r.text()
  563. log.error(
  564. f"Token refresh failed for client_id {client_id}: {r.status} - {error_text}"
  565. )
  566. return None
  567. except Exception as e:
  568. log.error(f"Exception during token refresh for client_id {client_id}: {e}")
  569. return None
  570. async def handle_authorize(self, request, client_id: str) -> RedirectResponse:
  571. client = self.get_client(client_id)
  572. if client is None:
  573. raise HTTPException(404)
  574. client_info = self.get_client_info(client_id)
  575. if client_info is None:
  576. raise HTTPException(404)
  577. redirect_uri = (
  578. client_info.redirect_uris[0] if client_info.redirect_uris else None
  579. )
  580. redirect_uri_str = str(redirect_uri) if redirect_uri else None
  581. return await client.authorize_redirect(request, redirect_uri_str)
  582. async def handle_callback(self, request, client_id: str, user_id: str, response):
  583. client = self.get_client(client_id)
  584. if client is None:
  585. raise HTTPException(404)
  586. error_message = None
  587. try:
  588. client_info = self.get_client_info(client_id)
  589. token_params = {}
  590. if (
  591. client_info
  592. and hasattr(client_info, "client_id")
  593. and hasattr(client_info, "client_secret")
  594. ):
  595. token_params["client_id"] = client_info.client_id
  596. token_params["client_secret"] = client_info.client_secret
  597. token = await client.authorize_access_token(request, **token_params)
  598. if token:
  599. try:
  600. # Add timestamp for tracking
  601. token["issued_at"] = datetime.now().timestamp()
  602. # Calculate expires_at if we have expires_in
  603. if "expires_in" in token and "expires_at" not in token:
  604. token["expires_at"] = (
  605. datetime.now().timestamp() + token["expires_in"]
  606. )
  607. # Clean up any existing sessions for this user/client_id first
  608. sessions = OAuthSessions.get_sessions_by_user_id(user_id)
  609. for session in sessions:
  610. if session.provider == client_id:
  611. OAuthSessions.delete_session_by_id(session.id)
  612. session = OAuthSessions.create_session(
  613. user_id=user_id,
  614. provider=client_id,
  615. token=token,
  616. )
  617. log.info(
  618. f"Stored OAuth session server-side for user {user_id}, client_id {client_id}"
  619. )
  620. except Exception as e:
  621. error_message = "Failed to store OAuth session server-side"
  622. log.error(f"Failed to store OAuth session server-side: {e}")
  623. else:
  624. error_message = "Failed to obtain OAuth token"
  625. log.warning(error_message)
  626. except Exception as e:
  627. error_message = _build_oauth_callback_error_message(e)
  628. log.warning(
  629. "OAuth callback error for user_id=%s client_id=%s: %s",
  630. user_id,
  631. client_id,
  632. error_message,
  633. exc_info=True,
  634. )
  635. redirect_url = (
  636. str(request.app.state.config.WEBUI_URL or request.base_url)
  637. ).rstrip("/")
  638. if error_message:
  639. log.debug(error_message)
  640. redirect_url = (
  641. f"{redirect_url}/?error={urllib.parse.quote_plus(error_message)}"
  642. )
  643. return RedirectResponse(url=redirect_url, headers=response.headers)
  644. response = RedirectResponse(url=redirect_url, headers=response.headers)
  645. return response
  646. class OAuthManager:
  647. def __init__(self, app):
  648. self.oauth = OAuth()
  649. self.app = app
  650. self._clients = {}
  651. for name, provider_config in OAUTH_PROVIDERS.items():
  652. if "register" not in provider_config:
  653. log.error(f"OAuth provider {name} missing register function")
  654. continue
  655. client = provider_config["register"](self.oauth)
  656. self._clients[name] = client
  657. def get_client(self, provider_name):
  658. if provider_name not in self._clients:
  659. self._clients[provider_name] = self.oauth.create_client(provider_name)
  660. return self._clients[provider_name]
  661. def get_server_metadata_url(self, provider_name):
  662. if provider_name in self._clients:
  663. client = self._clients[provider_name]
  664. return (
  665. client._server_metadata_url
  666. if hasattr(client, "_server_metadata_url")
  667. else None
  668. )
  669. return None
  670. async def get_oauth_token(
  671. self, user_id: str, session_id: str, force_refresh: bool = False
  672. ):
  673. """
  674. Get a valid OAuth token for the user, automatically refreshing if needed.
  675. Args:
  676. user_id: The user ID
  677. provider: Optional provider name. If None, gets the most recent session.
  678. force_refresh: Force token refresh even if current token appears valid
  679. Returns:
  680. dict: OAuth token data with access_token, or None if no valid token available
  681. """
  682. try:
  683. # Get the OAuth session
  684. session = OAuthSessions.get_session_by_id_and_user_id(session_id, user_id)
  685. if not session:
  686. log.warning(
  687. f"No OAuth session found for user {user_id}, session {session_id}"
  688. )
  689. return None
  690. if force_refresh or datetime.now() + timedelta(
  691. minutes=5
  692. ) >= datetime.fromtimestamp(session.expires_at):
  693. log.debug(
  694. f"Token refresh needed for user {user_id}, provider {session.provider}"
  695. )
  696. refreshed_token = await self._refresh_token(session)
  697. if refreshed_token:
  698. return refreshed_token
  699. else:
  700. log.warning(
  701. f"Token refresh failed for user {user_id}, provider {session.provider}, deleting session {session.id}"
  702. )
  703. OAuthSessions.delete_session_by_id(session.id)
  704. return None
  705. return session.token
  706. except Exception as e:
  707. log.error(f"Error getting OAuth token for user {user_id}: {e}")
  708. return None
  709. async def _refresh_token(self, session) -> dict:
  710. """
  711. Refresh an OAuth token if needed, with concurrency protection.
  712. Args:
  713. session: The OAuth session object
  714. Returns:
  715. dict: Refreshed token data, or None if refresh failed
  716. """
  717. try:
  718. # Perform the actual refresh
  719. refreshed_token = await self._perform_token_refresh(session)
  720. if refreshed_token:
  721. # Update the session with new token data
  722. session = OAuthSessions.update_session_by_id(
  723. session.id, refreshed_token
  724. )
  725. log.info(f"Successfully refreshed token for session {session.id}")
  726. return session.token
  727. else:
  728. log.error(f"Failed to refresh token for session {session.id}")
  729. return None
  730. except Exception as e:
  731. log.error(f"Error refreshing token for session {session.id}: {e}")
  732. return None
  733. async def _perform_token_refresh(self, session) -> dict:
  734. """
  735. Perform the actual OAuth token refresh.
  736. Args:
  737. session: The OAuth session object
  738. Returns:
  739. dict: New token data, or None if refresh failed
  740. """
  741. provider = session.provider
  742. token_data = session.token
  743. if not token_data.get("refresh_token"):
  744. log.warning(f"No refresh token available for session {session.id}")
  745. return None
  746. try:
  747. client = self.get_client(provider)
  748. if not client:
  749. log.error(f"No OAuth client found for provider {provider}")
  750. return None
  751. server_metadata_url = self.get_server_metadata_url(provider)
  752. token_endpoint = None
  753. async with aiohttp.ClientSession(trust_env=True) as session_http:
  754. async with session_http.get(server_metadata_url) as r:
  755. if r.status == 200:
  756. openid_data = await r.json()
  757. token_endpoint = openid_data.get("token_endpoint")
  758. else:
  759. log.error(
  760. f"Failed to fetch OpenID configuration for provider {provider}"
  761. )
  762. if not token_endpoint:
  763. log.error(f"No token endpoint found for provider {provider}")
  764. return None
  765. # Prepare refresh request
  766. refresh_data = {
  767. "grant_type": "refresh_token",
  768. "refresh_token": token_data["refresh_token"],
  769. "client_id": client.client_id,
  770. }
  771. # Add client_secret if available (some providers require it)
  772. if hasattr(client, "client_secret") and client.client_secret:
  773. refresh_data["client_secret"] = client.client_secret
  774. # Make refresh request
  775. async with aiohttp.ClientSession(trust_env=True) as session_http:
  776. async with session_http.post(
  777. token_endpoint,
  778. data=refresh_data,
  779. headers={"Content-Type": "application/x-www-form-urlencoded"},
  780. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  781. ) as r:
  782. if r.status == 200:
  783. new_token_data = await r.json()
  784. # Merge with existing token data (preserve refresh_token if not provided)
  785. if "refresh_token" not in new_token_data:
  786. new_token_data["refresh_token"] = token_data[
  787. "refresh_token"
  788. ]
  789. # Add timestamp for tracking
  790. new_token_data["issued_at"] = datetime.now().timestamp()
  791. # Calculate expires_at if we have expires_in
  792. if (
  793. "expires_in" in new_token_data
  794. and "expires_at" not in new_token_data
  795. ):
  796. new_token_data["expires_at"] = int(
  797. datetime.now().timestamp()
  798. + new_token_data["expires_in"]
  799. )
  800. log.debug(f"Token refresh successful for provider {provider}")
  801. return new_token_data
  802. else:
  803. error_text = await r.text()
  804. log.error(
  805. f"Token refresh failed for provider {provider}: {r.status} - {error_text}"
  806. )
  807. return None
  808. except Exception as e:
  809. log.error(f"Exception during token refresh for provider {provider}: {e}")
  810. return None
  811. def get_user_role(self, user, user_data):
  812. user_count = Users.get_num_users()
  813. if user and user_count == 1:
  814. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  815. log.debug("Assigning the only user the admin role")
  816. return "admin"
  817. if not user and user_count == 0:
  818. # If there are no users, assign the role "admin", as the first user will be an admin
  819. log.debug("Assigning the first user the admin role")
  820. return "admin"
  821. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  822. log.debug("Running OAUTH Role management")
  823. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  824. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  825. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  826. oauth_roles = []
  827. # Default/fallback role if no matching roles are found
  828. role = auth_manager_config.DEFAULT_USER_ROLE
  829. # Next block extracts the roles from the user data, accepting nested claims of any depth
  830. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  831. claim_data = user_data
  832. nested_claims = oauth_claim.split(".")
  833. for nested_claim in nested_claims:
  834. claim_data = claim_data.get(nested_claim, {})
  835. oauth_roles = []
  836. if isinstance(claim_data, list):
  837. oauth_roles = claim_data
  838. if isinstance(claim_data, str) or isinstance(claim_data, int):
  839. oauth_roles = [str(claim_data)]
  840. log.debug(f"Oauth Roles claim: {oauth_claim}")
  841. log.debug(f"User roles from oauth: {oauth_roles}")
  842. log.debug(f"Accepted user roles: {oauth_allowed_roles}")
  843. log.debug(f"Accepted admin roles: {oauth_admin_roles}")
  844. # If any roles are found, check if they match the allowed or admin roles
  845. if oauth_roles:
  846. # If role management is enabled, and matching roles are provided, use the roles
  847. for allowed_role in oauth_allowed_roles:
  848. # If the user has any of the allowed roles, assign the role "user"
  849. if allowed_role in oauth_roles:
  850. log.debug("Assigned user the user role")
  851. role = "user"
  852. break
  853. for admin_role in oauth_admin_roles:
  854. # If the user has any of the admin roles, assign the role "admin"
  855. if admin_role in oauth_roles:
  856. log.debug("Assigned user the admin role")
  857. role = "admin"
  858. break
  859. else:
  860. if not user:
  861. # If role management is disabled, use the default role for new users
  862. role = auth_manager_config.DEFAULT_USER_ROLE
  863. else:
  864. # If role management is disabled, use the existing role for existing users
  865. role = user.role
  866. return role
  867. def update_user_groups(self, user, user_data, default_permissions):
  868. log.debug("Running OAUTH Group management")
  869. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  870. try:
  871. blocked_groups = json.loads(auth_manager_config.OAUTH_BLOCKED_GROUPS)
  872. except Exception as e:
  873. log.exception(f"Error loading OAUTH_BLOCKED_GROUPS: {e}")
  874. blocked_groups = []
  875. user_oauth_groups = []
  876. # Nested claim search for groups claim
  877. if oauth_claim:
  878. claim_data = user_data
  879. nested_claims = oauth_claim.split(".")
  880. for nested_claim in nested_claims:
  881. claim_data = claim_data.get(nested_claim, {})
  882. if isinstance(claim_data, list):
  883. user_oauth_groups = claim_data
  884. elif isinstance(claim_data, str):
  885. # Split by the configured separator if present
  886. if OAUTH_GROUPS_SEPARATOR in claim_data:
  887. user_oauth_groups = claim_data.split(OAUTH_GROUPS_SEPARATOR)
  888. else:
  889. user_oauth_groups = [claim_data]
  890. else:
  891. user_oauth_groups = []
  892. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  893. all_available_groups: list[GroupModel] = Groups.get_groups()
  894. # Create groups if they don't exist and creation is enabled
  895. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  896. log.debug("Checking for missing groups to create...")
  897. all_group_names = {g.name for g in all_available_groups}
  898. groups_created = False
  899. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  900. admin_user = Users.get_super_admin_user()
  901. creator_id = admin_user.id if admin_user else user.id
  902. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  903. for group_name in user_oauth_groups:
  904. if group_name not in all_group_names:
  905. log.info(
  906. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  907. )
  908. try:
  909. new_group_form = GroupForm(
  910. name=group_name,
  911. description=f"Group '{group_name}' created automatically via OAuth.",
  912. permissions=default_permissions, # Use default permissions from function args
  913. user_ids=[], # Start with no users, user will be added later by subsequent logic
  914. )
  915. # Use determined creator ID (admin or fallback to current user)
  916. created_group = Groups.insert_new_group(
  917. creator_id, new_group_form
  918. )
  919. if created_group:
  920. log.info(
  921. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  922. )
  923. groups_created = True
  924. # Add to local set to prevent duplicate creation attempts in this run
  925. all_group_names.add(group_name)
  926. else:
  927. log.error(
  928. f"Failed to create group '{group_name}' via OAuth."
  929. )
  930. except Exception as e:
  931. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  932. # Refresh the list of all available groups if any were created
  933. if groups_created:
  934. all_available_groups = Groups.get_groups()
  935. log.debug("Refreshed list of all available groups after creation.")
  936. log.debug(f"Oauth Groups claim: {oauth_claim}")
  937. log.debug(f"User oauth groups: {user_oauth_groups}")
  938. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  939. log.debug(
  940. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  941. )
  942. # Remove groups that user is no longer a part of
  943. for group_model in user_current_groups:
  944. if (
  945. user_oauth_groups
  946. and group_model.name not in user_oauth_groups
  947. and not is_in_blocked_groups(group_model.name, blocked_groups)
  948. ):
  949. # Remove group from user
  950. log.debug(
  951. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  952. )
  953. user_ids = group_model.user_ids
  954. user_ids = [i for i in user_ids if i != user.id]
  955. # In case a group is created, but perms are never assigned to the group by hitting "save"
  956. group_permissions = group_model.permissions
  957. if not group_permissions:
  958. group_permissions = default_permissions
  959. update_form = GroupUpdateForm(
  960. name=group_model.name,
  961. description=group_model.description,
  962. permissions=group_permissions,
  963. user_ids=user_ids,
  964. )
  965. Groups.update_group_by_id(
  966. id=group_model.id, form_data=update_form, overwrite=False
  967. )
  968. # Add user to new groups
  969. for group_model in all_available_groups:
  970. if (
  971. user_oauth_groups
  972. and group_model.name in user_oauth_groups
  973. and not any(gm.name == group_model.name for gm in user_current_groups)
  974. and not is_in_blocked_groups(group_model.name, blocked_groups)
  975. ):
  976. # Add user to group
  977. log.debug(
  978. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  979. )
  980. user_ids = group_model.user_ids
  981. user_ids.append(user.id)
  982. # In case a group is created, but perms are never assigned to the group by hitting "save"
  983. group_permissions = group_model.permissions
  984. if not group_permissions:
  985. group_permissions = default_permissions
  986. update_form = GroupUpdateForm(
  987. name=group_model.name,
  988. description=group_model.description,
  989. permissions=group_permissions,
  990. user_ids=user_ids,
  991. )
  992. Groups.update_group_by_id(
  993. id=group_model.id, form_data=update_form, overwrite=False
  994. )
  995. async def _process_picture_url(
  996. self, picture_url: str, access_token: str = None
  997. ) -> str:
  998. """Process a picture URL and return a base64 encoded data URL.
  999. Args:
  1000. picture_url: The URL of the picture to process
  1001. access_token: Optional OAuth access token for authenticated requests
  1002. Returns:
  1003. A data URL containing the base64 encoded picture, or "/user.png" if processing fails
  1004. """
  1005. if not picture_url:
  1006. return "/user.png"
  1007. try:
  1008. get_kwargs = {}
  1009. if access_token:
  1010. get_kwargs["headers"] = {
  1011. "Authorization": f"Bearer {access_token}",
  1012. }
  1013. async with aiohttp.ClientSession(trust_env=True) as session:
  1014. async with session.get(
  1015. picture_url, **get_kwargs, ssl=AIOHTTP_CLIENT_SESSION_SSL
  1016. ) as resp:
  1017. if resp.ok:
  1018. picture = await resp.read()
  1019. base64_encoded_picture = base64.b64encode(picture).decode(
  1020. "utf-8"
  1021. )
  1022. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1023. if guessed_mime_type is None:
  1024. guessed_mime_type = "image/jpeg"
  1025. return (
  1026. f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1027. )
  1028. else:
  1029. log.warning(
  1030. f"Failed to fetch profile picture from {picture_url}"
  1031. )
  1032. return "/user.png"
  1033. except Exception as e:
  1034. log.error(f"Error processing profile picture '{picture_url}': {e}")
  1035. return "/user.png"
  1036. async def handle_login(self, request, provider):
  1037. if provider not in OAUTH_PROVIDERS:
  1038. raise HTTPException(404)
  1039. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1040. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1041. "oauth_login_callback", provider=provider
  1042. )
  1043. client = self.get_client(provider)
  1044. if client is None:
  1045. raise HTTPException(404)
  1046. return await client.authorize_redirect(request, redirect_uri)
  1047. async def handle_callback(self, request, provider, response):
  1048. if provider not in OAUTH_PROVIDERS:
  1049. raise HTTPException(404)
  1050. error_message = None
  1051. try:
  1052. client = self.get_client(provider)
  1053. try:
  1054. token = await client.authorize_access_token(request)
  1055. except Exception as e:
  1056. detailed_error = _build_oauth_callback_error_message(e)
  1057. log.warning(
  1058. "OAuth callback error during authorize_access_token for provider %s: %s",
  1059. provider,
  1060. detailed_error,
  1061. exc_info=True,
  1062. )
  1063. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1064. # Try to get userinfo from the token first, some providers include it there
  1065. user_data: UserInfo = token.get("userinfo")
  1066. if (
  1067. (not user_data)
  1068. or (auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data)
  1069. or (auth_manager_config.OAUTH_USERNAME_CLAIM not in user_data)
  1070. ):
  1071. user_data: UserInfo = await client.userinfo(token=token)
  1072. if (
  1073. provider == "feishu"
  1074. and isinstance(user_data, dict)
  1075. and "data" in user_data
  1076. ):
  1077. user_data = user_data["data"]
  1078. if not user_data:
  1079. log.warning(f"OAuth callback failed, user data is missing: {token}")
  1080. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1081. # Extract the "sub" claim, using custom claim if configured
  1082. if auth_manager_config.OAUTH_SUB_CLAIM:
  1083. sub = user_data.get(auth_manager_config.OAUTH_SUB_CLAIM)
  1084. else:
  1085. # Fallback to the default sub claim if not configured
  1086. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  1087. if not sub:
  1088. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1089. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1090. provider_sub = f"{provider}@{sub}"
  1091. # Email extraction
  1092. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  1093. email = user_data.get(email_claim, "")
  1094. # We currently mandate that email addresses are provided
  1095. if not email:
  1096. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  1097. if provider == "github":
  1098. try:
  1099. access_token = token.get("access_token")
  1100. headers = {"Authorization": f"Bearer {access_token}"}
  1101. async with aiohttp.ClientSession(trust_env=True) as session:
  1102. async with session.get(
  1103. "https://api.github.com/user/emails",
  1104. headers=headers,
  1105. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  1106. ) as resp:
  1107. if resp.ok:
  1108. emails = await resp.json()
  1109. # use the primary email as the user's email
  1110. primary_email = next(
  1111. (
  1112. e["email"]
  1113. for e in emails
  1114. if e.get("primary")
  1115. ),
  1116. None,
  1117. )
  1118. if primary_email:
  1119. email = primary_email
  1120. else:
  1121. log.warning(
  1122. "No primary email found in GitHub response"
  1123. )
  1124. raise HTTPException(
  1125. 400, detail=ERROR_MESSAGES.INVALID_CRED
  1126. )
  1127. else:
  1128. log.warning("Failed to fetch GitHub email")
  1129. raise HTTPException(
  1130. 400, detail=ERROR_MESSAGES.INVALID_CRED
  1131. )
  1132. except Exception as e:
  1133. log.warning(f"Error fetching GitHub email: {e}")
  1134. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1135. elif ENABLE_OAUTH_EMAIL_FALLBACK:
  1136. email = f"{provider_sub}.local"
  1137. else:
  1138. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1139. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1140. email = email.lower()
  1141. # If allowed domains are configured, check if the email domain is in the list
  1142. if (
  1143. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  1144. and email.split("@")[-1]
  1145. not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  1146. ):
  1147. log.warning(
  1148. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  1149. )
  1150. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1151. # Check if the user exists
  1152. user = Users.get_user_by_oauth_sub(provider_sub)
  1153. if not user:
  1154. # If the user does not exist, check if merging is enabled
  1155. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  1156. # Check if the user exists by email
  1157. user = Users.get_user_by_email(email)
  1158. if user:
  1159. # Update the user with the new oauth sub
  1160. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1161. if user:
  1162. determined_role = self.get_user_role(user, user_data)
  1163. if user.role != determined_role:
  1164. Users.update_user_role_by_id(user.id, determined_role)
  1165. # Update profile picture if enabled and different from current
  1166. if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
  1167. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  1168. if picture_claim:
  1169. new_picture_url = user_data.get(
  1170. picture_claim,
  1171. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  1172. )
  1173. processed_picture_url = await self._process_picture_url(
  1174. new_picture_url, token.get("access_token")
  1175. )
  1176. if processed_picture_url != user.profile_image_url:
  1177. Users.update_user_profile_image_url_by_id(
  1178. user.id, processed_picture_url
  1179. )
  1180. log.debug(f"Updated profile picture for user {user.email}")
  1181. else:
  1182. # If the user does not exist, check if signups are enabled
  1183. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  1184. # Check if an existing user with the same email already exists
  1185. existing_user = Users.get_user_by_email(email)
  1186. if existing_user:
  1187. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1188. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  1189. if picture_claim:
  1190. picture_url = user_data.get(
  1191. picture_claim,
  1192. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  1193. )
  1194. picture_url = await self._process_picture_url(
  1195. picture_url, token.get("access_token")
  1196. )
  1197. else:
  1198. picture_url = "/user.png"
  1199. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  1200. name = user_data.get(username_claim)
  1201. if not name:
  1202. log.warning("Username claim is missing, using email as name")
  1203. name = email
  1204. user = Auths.insert_new_auth(
  1205. email=email,
  1206. password=get_password_hash(
  1207. str(uuid.uuid4())
  1208. ), # Random password, not used
  1209. name=name,
  1210. profile_image_url=picture_url,
  1211. role=self.get_user_role(None, user_data),
  1212. oauth_sub=provider_sub,
  1213. )
  1214. if auth_manager_config.WEBHOOK_URL:
  1215. await post_webhook(
  1216. WEBUI_NAME,
  1217. auth_manager_config.WEBHOOK_URL,
  1218. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1219. {
  1220. "action": "signup",
  1221. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1222. "user": user.model_dump_json(exclude_none=True),
  1223. },
  1224. )
  1225. else:
  1226. raise HTTPException(
  1227. status.HTTP_403_FORBIDDEN,
  1228. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1229. )
  1230. jwt_token = create_token(
  1231. data={"id": user.id},
  1232. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  1233. )
  1234. if (
  1235. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT
  1236. and user.role != "admin"
  1237. ):
  1238. self.update_user_groups(
  1239. user=user,
  1240. user_data=user_data,
  1241. default_permissions=request.app.state.config.USER_PERMISSIONS,
  1242. )
  1243. except Exception as e:
  1244. log.error(f"Error during OAuth process: {e}")
  1245. error_message = (
  1246. e.detail
  1247. if isinstance(e, HTTPException) and e.detail
  1248. else ERROR_MESSAGES.DEFAULT("Error during OAuth process")
  1249. )
  1250. redirect_base_url = (
  1251. str(request.app.state.config.WEBUI_URL or request.base_url)
  1252. ).rstrip("/")
  1253. redirect_url = f"{redirect_base_url}/auth"
  1254. if error_message:
  1255. redirect_url = f"{redirect_url}?error={error_message}"
  1256. return RedirectResponse(url=redirect_url, headers=response.headers)
  1257. response = RedirectResponse(url=redirect_url, headers=response.headers)
  1258. # Set the cookie token
  1259. # Redirect back to the frontend with the JWT token
  1260. response.set_cookie(
  1261. key="token",
  1262. value=jwt_token,
  1263. httponly=False, # Required for frontend access
  1264. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1265. secure=WEBUI_AUTH_COOKIE_SECURE,
  1266. )
  1267. # Legacy cookies for compatibility with older frontend versions
  1268. if ENABLE_OAUTH_ID_TOKEN_COOKIE:
  1269. response.set_cookie(
  1270. key="oauth_id_token",
  1271. value=token.get("id_token"),
  1272. httponly=True,
  1273. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1274. secure=WEBUI_AUTH_COOKIE_SECURE,
  1275. )
  1276. try:
  1277. # Add timestamp for tracking
  1278. token["issued_at"] = datetime.now().timestamp()
  1279. # Calculate expires_at if we have expires_in
  1280. if "expires_in" in token and "expires_at" not in token:
  1281. token["expires_at"] = datetime.now().timestamp() + token["expires_in"]
  1282. # Clean up any existing sessions for this user/provider first
  1283. sessions = OAuthSessions.get_sessions_by_user_id(user.id)
  1284. for session in sessions:
  1285. if session.provider == provider:
  1286. OAuthSessions.delete_session_by_id(session.id)
  1287. session = OAuthSessions.create_session(
  1288. user_id=user.id,
  1289. provider=provider,
  1290. token=token,
  1291. )
  1292. response.set_cookie(
  1293. key="oauth_session_id",
  1294. value=session.id,
  1295. httponly=True,
  1296. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1297. secure=WEBUI_AUTH_COOKIE_SECURE,
  1298. )
  1299. log.info(
  1300. f"Stored OAuth session server-side for user {user.id}, provider {provider}"
  1301. )
  1302. except Exception as e:
  1303. log.error(f"Failed to store OAuth session server-side: {e}")
  1304. return response