oauth.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. # The mcp package requires optional unset values to be None. If an empty string is passed, it gets validated and fails.
  281. # This replaces all empty strings with None.
  282. registration_response_json = {
  283. k: (None if v == "" else v)
  284. for k, v in registration_response_json.items()
  285. }
  286. oauth_client_info = OAuthClientInformationFull.model_validate(
  287. {
  288. **registration_response_json,
  289. **{"issuer": oauth_server_metadata_url},
  290. **{"server_metadata": oauth_server_metadata},
  291. }
  292. )
  293. log.info(
  294. f"Dynamic client registration successful at {registration_url}, client_id: {oauth_client_info.client_id}"
  295. )
  296. return oauth_client_info
  297. except Exception as e:
  298. error_text = None
  299. try:
  300. error_text = await oauth_client_registration_response.text()
  301. log.error(
  302. f"Dynamic client registration failed at {registration_url}: {oauth_client_registration_response.status} - {error_text}"
  303. )
  304. except Exception as e:
  305. pass
  306. log.error(f"Error parsing client registration response: {e}")
  307. raise Exception(
  308. f"Dynamic client registration failed: {error_text}"
  309. if error_text
  310. else "Error parsing client registration response"
  311. )
  312. raise Exception("Dynamic client registration failed")
  313. except Exception as e:
  314. log.error(f"Exception during dynamic client registration: {e}")
  315. raise e
  316. class OAuthClientManager:
  317. def __init__(self, app):
  318. self.oauth = OAuth()
  319. self.app = app
  320. self.clients = {}
  321. def add_client(self, client_id, oauth_client_info: OAuthClientInformationFull):
  322. kwargs = {
  323. "name": client_id,
  324. "client_id": oauth_client_info.client_id,
  325. "client_secret": oauth_client_info.client_secret,
  326. "client_kwargs": {
  327. **(
  328. {"scope": oauth_client_info.scope}
  329. if oauth_client_info.scope
  330. else {}
  331. ),
  332. **(
  333. {
  334. "token_endpoint_auth_method": oauth_client_info.token_endpoint_auth_method
  335. }
  336. if oauth_client_info.token_endpoint_auth_method
  337. else {}
  338. ),
  339. },
  340. "server_metadata_url": (
  341. oauth_client_info.issuer if oauth_client_info.issuer else None
  342. ),
  343. }
  344. if (
  345. oauth_client_info.server_metadata
  346. and oauth_client_info.server_metadata.code_challenge_methods_supported
  347. ):
  348. if (
  349. isinstance(
  350. oauth_client_info.server_metadata.code_challenge_methods_supported,
  351. list,
  352. )
  353. and "S256"
  354. in oauth_client_info.server_metadata.code_challenge_methods_supported
  355. ):
  356. kwargs["code_challenge_method"] = "S256"
  357. self.clients[client_id] = {
  358. "client": self.oauth.register(**kwargs),
  359. "client_info": oauth_client_info,
  360. }
  361. return self.clients[client_id]
  362. def remove_client(self, client_id):
  363. if client_id in self.clients:
  364. del self.clients[client_id]
  365. log.info(f"Removed OAuth client {client_id}")
  366. if hasattr(self.oauth, "_clients"):
  367. if client_id in self.oauth._clients:
  368. self.oauth._clients.pop(client_id, None)
  369. if hasattr(self.oauth, "_registry"):
  370. if client_id in self.oauth._registry:
  371. self.oauth._registry.pop(client_id, None)
  372. return True
  373. async def _preflight_authorization_url(
  374. self, client, client_info: OAuthClientInformationFull
  375. ) -> bool:
  376. # TODO: Replace this logic with a more robust OAuth client registration validation
  377. # Only perform preflight checks for Starlette OAuth clients
  378. if not hasattr(client, "create_authorization_url"):
  379. return True
  380. redirect_uri = None
  381. if client_info.redirect_uris:
  382. redirect_uri = str(client_info.redirect_uris[0])
  383. try:
  384. auth_data = await client.create_authorization_url(redirect_uri=redirect_uri)
  385. authorization_url = auth_data.get("url")
  386. if not authorization_url:
  387. return True
  388. except Exception as e:
  389. log.debug(
  390. f"Skipping OAuth preflight for client {client_info.client_id}: {e}",
  391. )
  392. return True
  393. try:
  394. async with aiohttp.ClientSession(trust_env=True) as session:
  395. async with session.get(
  396. authorization_url,
  397. allow_redirects=False,
  398. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  399. ) as resp:
  400. if resp.status < 400:
  401. return True
  402. response_text = await resp.text()
  403. error = None
  404. error_description = ""
  405. content_type = resp.headers.get("content-type", "")
  406. if "application/json" in content_type:
  407. try:
  408. payload = json.loads(response_text)
  409. error = payload.get("error")
  410. error_description = payload.get("error_description", "")
  411. except:
  412. pass
  413. else:
  414. error_description = response_text
  415. error_message = f"{error or ''} {error_description or ''}".lower()
  416. if any(
  417. keyword in error_message
  418. for keyword in ("invalid_client", "invalid client", "client id")
  419. ):
  420. log.warning(
  421. f"OAuth client preflight detected invalid registration for {client_info.client_id}: {error} {error_description}"
  422. )
  423. return False
  424. except Exception as e:
  425. log.debug(
  426. f"Skipping OAuth preflight network check for client {client_info.client_id}: {e}"
  427. )
  428. return True
  429. def get_client(self, client_id):
  430. client = self.clients.get(client_id)
  431. return client["client"] if client else None
  432. def get_client_info(self, client_id):
  433. client = self.clients.get(client_id)
  434. return client["client_info"] if client else None
  435. def get_server_metadata_url(self, client_id):
  436. if client_id in self.clients:
  437. client = self.clients[client_id]
  438. return (
  439. client._server_metadata_url
  440. if hasattr(client, "_server_metadata_url")
  441. else None
  442. )
  443. return None
  444. async def get_oauth_token(
  445. self, user_id: str, client_id: str, force_refresh: bool = False
  446. ):
  447. """
  448. Get a valid OAuth token for the user, automatically refreshing if needed.
  449. Args:
  450. user_id: The user ID
  451. client_id: The OAuth client ID (provider)
  452. force_refresh: Force token refresh even if current token appears valid
  453. Returns:
  454. dict: OAuth token data with access_token, or None if no valid token available
  455. """
  456. try:
  457. # Get the OAuth session
  458. session = OAuthSessions.get_session_by_provider_and_user_id(
  459. client_id, user_id
  460. )
  461. if not session:
  462. log.warning(
  463. f"No OAuth session found for user {user_id}, client_id {client_id}"
  464. )
  465. return None
  466. if force_refresh or datetime.now() + timedelta(
  467. minutes=5
  468. ) >= datetime.fromtimestamp(session.expires_at):
  469. log.debug(
  470. f"Token refresh needed for user {user_id}, client_id {session.provider}"
  471. )
  472. refreshed_token = await self._refresh_token(session)
  473. if refreshed_token:
  474. return refreshed_token
  475. else:
  476. log.warning(
  477. f"Token refresh failed for user {user_id}, client_id {session.provider}, deleting session {session.id}"
  478. )
  479. OAuthSessions.delete_session_by_id(session.id)
  480. return None
  481. return session.token
  482. except Exception as e:
  483. log.error(f"Error getting OAuth token for user {user_id}: {e}")
  484. return None
  485. async def _refresh_token(self, session) -> dict:
  486. """
  487. Refresh an OAuth token if needed, with concurrency protection.
  488. Args:
  489. session: The OAuth session object
  490. Returns:
  491. dict: Refreshed token data, or None if refresh failed
  492. """
  493. try:
  494. # Perform the actual refresh
  495. refreshed_token = await self._perform_token_refresh(session)
  496. if refreshed_token:
  497. # Update the session with new token data
  498. session = OAuthSessions.update_session_by_id(
  499. session.id, refreshed_token
  500. )
  501. log.info(f"Successfully refreshed token for session {session.id}")
  502. return session.token
  503. else:
  504. log.error(f"Failed to refresh token for session {session.id}")
  505. return None
  506. except Exception as e:
  507. log.error(f"Error refreshing token for session {session.id}: {e}")
  508. return None
  509. async def _perform_token_refresh(self, session) -> dict:
  510. """
  511. Perform the actual OAuth token refresh.
  512. Args:
  513. session: The OAuth session object
  514. Returns:
  515. dict: New token data, or None if refresh failed
  516. """
  517. client_id = session.provider
  518. token_data = session.token
  519. if not token_data.get("refresh_token"):
  520. log.warning(f"No refresh token available for session {session.id}")
  521. return None
  522. try:
  523. client = self.get_client(client_id)
  524. if not client:
  525. log.error(f"No OAuth client found for provider {client_id}")
  526. return None
  527. token_endpoint = None
  528. async with aiohttp.ClientSession(trust_env=True) as session_http:
  529. async with session_http.get(
  530. self.get_server_metadata_url(client_id)
  531. ) as r:
  532. if r.status == 200:
  533. openid_data = await r.json()
  534. token_endpoint = openid_data.get("token_endpoint")
  535. else:
  536. log.error(
  537. f"Failed to fetch OpenID configuration for client_id {client_id}"
  538. )
  539. if not token_endpoint:
  540. log.error(f"No token endpoint found for client_id {client_id}")
  541. return None
  542. # Prepare refresh request
  543. refresh_data = {
  544. "grant_type": "refresh_token",
  545. "refresh_token": token_data["refresh_token"],
  546. "client_id": client.client_id,
  547. }
  548. if hasattr(client, "client_secret") and client.client_secret:
  549. refresh_data["client_secret"] = client.client_secret
  550. # Make refresh request
  551. async with aiohttp.ClientSession(trust_env=True) as session_http:
  552. async with session_http.post(
  553. token_endpoint,
  554. data=refresh_data,
  555. headers={"Content-Type": "application/x-www-form-urlencoded"},
  556. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  557. ) as r:
  558. if r.status == 200:
  559. new_token_data = await r.json()
  560. # Merge with existing token data (preserve refresh_token if not provided)
  561. if "refresh_token" not in new_token_data:
  562. new_token_data["refresh_token"] = token_data[
  563. "refresh_token"
  564. ]
  565. # Add timestamp for tracking
  566. new_token_data["issued_at"] = datetime.now().timestamp()
  567. # Calculate expires_at if we have expires_in
  568. if (
  569. "expires_in" in new_token_data
  570. and "expires_at" not in new_token_data
  571. ):
  572. new_token_data["expires_at"] = int(
  573. datetime.now().timestamp()
  574. + new_token_data["expires_in"]
  575. )
  576. log.debug(f"Token refresh successful for client_id {client_id}")
  577. return new_token_data
  578. else:
  579. error_text = await r.text()
  580. log.error(
  581. f"Token refresh failed for client_id {client_id}: {r.status} - {error_text}"
  582. )
  583. return None
  584. except Exception as e:
  585. log.error(f"Exception during token refresh for client_id {client_id}: {e}")
  586. return None
  587. async def handle_authorize(self, request, client_id: str) -> RedirectResponse:
  588. client = self.get_client(client_id)
  589. if client is None:
  590. raise HTTPException(404)
  591. client_info = self.get_client_info(client_id)
  592. if client_info is None:
  593. raise HTTPException(404)
  594. redirect_uri = (
  595. client_info.redirect_uris[0] if client_info.redirect_uris else None
  596. )
  597. redirect_uri_str = str(redirect_uri) if redirect_uri else None
  598. return await client.authorize_redirect(request, redirect_uri_str)
  599. async def handle_callback(self, request, client_id: str, user_id: str, response):
  600. client = self.get_client(client_id)
  601. if client is None:
  602. raise HTTPException(404)
  603. error_message = None
  604. try:
  605. client_info = self.get_client_info(client_id)
  606. auth_params = {}
  607. if (
  608. client_info
  609. and hasattr(client_info, "client_id")
  610. and hasattr(client_info, "client_secret")
  611. ):
  612. auth_params["client_id"] = client_info.client_id
  613. auth_params["client_secret"] = client_info.client_secret
  614. token = await client.authorize_access_token(request, **auth_params)
  615. if token:
  616. try:
  617. # Add timestamp for tracking
  618. token["issued_at"] = datetime.now().timestamp()
  619. # Calculate expires_at if we have expires_in
  620. if "expires_in" in token and "expires_at" not in token:
  621. token["expires_at"] = (
  622. datetime.now().timestamp() + token["expires_in"]
  623. )
  624. # Clean up any existing sessions for this user/client_id first
  625. sessions = OAuthSessions.get_sessions_by_user_id(user_id)
  626. for session in sessions:
  627. if session.provider == client_id:
  628. OAuthSessions.delete_session_by_id(session.id)
  629. session = OAuthSessions.create_session(
  630. user_id=user_id,
  631. provider=client_id,
  632. token=token,
  633. )
  634. log.info(
  635. f"Stored OAuth session server-side for user {user_id}, client_id {client_id}"
  636. )
  637. except Exception as e:
  638. error_message = "Failed to store OAuth session server-side"
  639. log.error(f"Failed to store OAuth session server-side: {e}")
  640. else:
  641. error_message = "Failed to obtain OAuth token"
  642. log.warning(error_message)
  643. except Exception as e:
  644. error_message = _build_oauth_callback_error_message(e)
  645. log.warning(
  646. "OAuth callback error for user_id=%s client_id=%s: %s",
  647. user_id,
  648. client_id,
  649. error_message,
  650. exc_info=True,
  651. )
  652. redirect_url = (
  653. str(request.app.state.config.WEBUI_URL or request.base_url)
  654. ).rstrip("/")
  655. if error_message:
  656. log.debug(error_message)
  657. redirect_url = (
  658. f"{redirect_url}/?error={urllib.parse.quote_plus(error_message)}"
  659. )
  660. return RedirectResponse(url=redirect_url, headers=response.headers)
  661. response = RedirectResponse(url=redirect_url, headers=response.headers)
  662. return response
  663. class OAuthManager:
  664. def __init__(self, app):
  665. self.oauth = OAuth()
  666. self.app = app
  667. self._clients = {}
  668. for name, provider_config in OAUTH_PROVIDERS.items():
  669. if "register" not in provider_config:
  670. log.error(f"OAuth provider {name} missing register function")
  671. continue
  672. client = provider_config["register"](self.oauth)
  673. self._clients[name] = client
  674. def get_client(self, provider_name):
  675. if provider_name not in self._clients:
  676. self._clients[provider_name] = self.oauth.create_client(provider_name)
  677. return self._clients[provider_name]
  678. def get_server_metadata_url(self, provider_name):
  679. if provider_name in self._clients:
  680. client = self._clients[provider_name]
  681. return (
  682. client._server_metadata_url
  683. if hasattr(client, "_server_metadata_url")
  684. else None
  685. )
  686. return None
  687. async def get_oauth_token(
  688. self, user_id: str, session_id: str, force_refresh: bool = False
  689. ):
  690. """
  691. Get a valid OAuth token for the user, automatically refreshing if needed.
  692. Args:
  693. user_id: The user ID
  694. provider: Optional provider name. If None, gets the most recent session.
  695. force_refresh: Force token refresh even if current token appears valid
  696. Returns:
  697. dict: OAuth token data with access_token, or None if no valid token available
  698. """
  699. try:
  700. # Get the OAuth session
  701. session = OAuthSessions.get_session_by_id_and_user_id(session_id, user_id)
  702. if not session:
  703. log.warning(
  704. f"No OAuth session found for user {user_id}, session {session_id}"
  705. )
  706. return None
  707. if force_refresh or datetime.now() + timedelta(
  708. minutes=5
  709. ) >= datetime.fromtimestamp(session.expires_at):
  710. log.debug(
  711. f"Token refresh needed for user {user_id}, provider {session.provider}"
  712. )
  713. refreshed_token = await self._refresh_token(session)
  714. if refreshed_token:
  715. return refreshed_token
  716. else:
  717. log.warning(
  718. f"Token refresh failed for user {user_id}, provider {session.provider}, deleting session {session.id}"
  719. )
  720. OAuthSessions.delete_session_by_id(session.id)
  721. return None
  722. return session.token
  723. except Exception as e:
  724. log.error(f"Error getting OAuth token for user {user_id}: {e}")
  725. return None
  726. async def _refresh_token(self, session) -> dict:
  727. """
  728. Refresh an OAuth token if needed, with concurrency protection.
  729. Args:
  730. session: The OAuth session object
  731. Returns:
  732. dict: Refreshed token data, or None if refresh failed
  733. """
  734. try:
  735. # Perform the actual refresh
  736. refreshed_token = await self._perform_token_refresh(session)
  737. if refreshed_token:
  738. # Update the session with new token data
  739. session = OAuthSessions.update_session_by_id(
  740. session.id, refreshed_token
  741. )
  742. log.info(f"Successfully refreshed token for session {session.id}")
  743. return session.token
  744. else:
  745. log.error(f"Failed to refresh token for session {session.id}")
  746. return None
  747. except Exception as e:
  748. log.error(f"Error refreshing token for session {session.id}: {e}")
  749. return None
  750. async def _perform_token_refresh(self, session) -> dict:
  751. """
  752. Perform the actual OAuth token refresh.
  753. Args:
  754. session: The OAuth session object
  755. Returns:
  756. dict: New token data, or None if refresh failed
  757. """
  758. provider = session.provider
  759. token_data = session.token
  760. if not token_data.get("refresh_token"):
  761. log.warning(f"No refresh token available for session {session.id}")
  762. return None
  763. try:
  764. client = self.get_client(provider)
  765. if not client:
  766. log.error(f"No OAuth client found for provider {provider}")
  767. return None
  768. server_metadata_url = self.get_server_metadata_url(provider)
  769. token_endpoint = None
  770. async with aiohttp.ClientSession(trust_env=True) as session_http:
  771. async with session_http.get(server_metadata_url) as r:
  772. if r.status == 200:
  773. openid_data = await r.json()
  774. token_endpoint = openid_data.get("token_endpoint")
  775. else:
  776. log.error(
  777. f"Failed to fetch OpenID configuration for provider {provider}"
  778. )
  779. if not token_endpoint:
  780. log.error(f"No token endpoint found for provider {provider}")
  781. return None
  782. # Prepare refresh request
  783. refresh_data = {
  784. "grant_type": "refresh_token",
  785. "refresh_token": token_data["refresh_token"],
  786. "client_id": client.client_id,
  787. }
  788. # Add client_secret if available (some providers require it)
  789. if hasattr(client, "client_secret") and client.client_secret:
  790. refresh_data["client_secret"] = client.client_secret
  791. # Make refresh request
  792. async with aiohttp.ClientSession(trust_env=True) as session_http:
  793. async with session_http.post(
  794. token_endpoint,
  795. data=refresh_data,
  796. headers={"Content-Type": "application/x-www-form-urlencoded"},
  797. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  798. ) as r:
  799. if r.status == 200:
  800. new_token_data = await r.json()
  801. # Merge with existing token data (preserve refresh_token if not provided)
  802. if "refresh_token" not in new_token_data:
  803. new_token_data["refresh_token"] = token_data[
  804. "refresh_token"
  805. ]
  806. # Add timestamp for tracking
  807. new_token_data["issued_at"] = datetime.now().timestamp()
  808. # Calculate expires_at if we have expires_in
  809. if (
  810. "expires_in" in new_token_data
  811. and "expires_at" not in new_token_data
  812. ):
  813. new_token_data["expires_at"] = int(
  814. datetime.now().timestamp()
  815. + new_token_data["expires_in"]
  816. )
  817. log.debug(f"Token refresh successful for provider {provider}")
  818. return new_token_data
  819. else:
  820. error_text = await r.text()
  821. log.error(
  822. f"Token refresh failed for provider {provider}: {r.status} - {error_text}"
  823. )
  824. return None
  825. except Exception as e:
  826. log.error(f"Exception during token refresh for provider {provider}: {e}")
  827. return None
  828. def get_user_role(self, user, user_data):
  829. user_count = Users.get_num_users()
  830. if user and user_count == 1:
  831. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  832. log.debug("Assigning the only user the admin role")
  833. return "admin"
  834. if not user and user_count == 0:
  835. # If there are no users, assign the role "admin", as the first user will be an admin
  836. log.debug("Assigning the first user the admin role")
  837. return "admin"
  838. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  839. log.debug("Running OAUTH Role management")
  840. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  841. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  842. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  843. oauth_roles = []
  844. # Default/fallback role if no matching roles are found
  845. role = auth_manager_config.DEFAULT_USER_ROLE
  846. # Next block extracts the roles from the user data, accepting nested claims of any depth
  847. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  848. claim_data = user_data
  849. nested_claims = oauth_claim.split(".")
  850. for nested_claim in nested_claims:
  851. claim_data = claim_data.get(nested_claim, {})
  852. oauth_roles = []
  853. if isinstance(claim_data, list):
  854. oauth_roles = claim_data
  855. if isinstance(claim_data, str) or isinstance(claim_data, int):
  856. oauth_roles = [str(claim_data)]
  857. log.debug(f"Oauth Roles claim: {oauth_claim}")
  858. log.debug(f"User roles from oauth: {oauth_roles}")
  859. log.debug(f"Accepted user roles: {oauth_allowed_roles}")
  860. log.debug(f"Accepted admin roles: {oauth_admin_roles}")
  861. # If any roles are found, check if they match the allowed or admin roles
  862. if oauth_roles:
  863. # If role management is enabled, and matching roles are provided, use the roles
  864. for allowed_role in oauth_allowed_roles:
  865. # If the user has any of the allowed roles, assign the role "user"
  866. if allowed_role in oauth_roles:
  867. log.debug("Assigned user the user role")
  868. role = "user"
  869. break
  870. for admin_role in oauth_admin_roles:
  871. # If the user has any of the admin roles, assign the role "admin"
  872. if admin_role in oauth_roles:
  873. log.debug("Assigned user the admin role")
  874. role = "admin"
  875. break
  876. else:
  877. if not user:
  878. # If role management is disabled, use the default role for new users
  879. role = auth_manager_config.DEFAULT_USER_ROLE
  880. else:
  881. # If role management is disabled, use the existing role for existing users
  882. role = user.role
  883. return role
  884. def update_user_groups(self, user, user_data, default_permissions):
  885. log.debug("Running OAUTH Group management")
  886. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  887. try:
  888. blocked_groups = json.loads(auth_manager_config.OAUTH_BLOCKED_GROUPS)
  889. except Exception as e:
  890. log.exception(f"Error loading OAUTH_BLOCKED_GROUPS: {e}")
  891. blocked_groups = []
  892. user_oauth_groups = []
  893. # Nested claim search for groups claim
  894. if oauth_claim:
  895. claim_data = user_data
  896. nested_claims = oauth_claim.split(".")
  897. for nested_claim in nested_claims:
  898. claim_data = claim_data.get(nested_claim, {})
  899. if isinstance(claim_data, list):
  900. user_oauth_groups = claim_data
  901. elif isinstance(claim_data, str):
  902. # Split by the configured separator if present
  903. if OAUTH_GROUPS_SEPARATOR in claim_data:
  904. user_oauth_groups = claim_data.split(OAUTH_GROUPS_SEPARATOR)
  905. else:
  906. user_oauth_groups = [claim_data]
  907. else:
  908. user_oauth_groups = []
  909. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  910. all_available_groups: list[GroupModel] = Groups.get_groups()
  911. # Create groups if they don't exist and creation is enabled
  912. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  913. log.debug("Checking for missing groups to create...")
  914. all_group_names = {g.name for g in all_available_groups}
  915. groups_created = False
  916. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  917. admin_user = Users.get_super_admin_user()
  918. creator_id = admin_user.id if admin_user else user.id
  919. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  920. for group_name in user_oauth_groups:
  921. if group_name not in all_group_names:
  922. log.info(
  923. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  924. )
  925. try:
  926. new_group_form = GroupForm(
  927. name=group_name,
  928. description=f"Group '{group_name}' created automatically via OAuth.",
  929. permissions=default_permissions, # Use default permissions from function args
  930. user_ids=[], # Start with no users, user will be added later by subsequent logic
  931. )
  932. # Use determined creator ID (admin or fallback to current user)
  933. created_group = Groups.insert_new_group(
  934. creator_id, new_group_form
  935. )
  936. if created_group:
  937. log.info(
  938. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  939. )
  940. groups_created = True
  941. # Add to local set to prevent duplicate creation attempts in this run
  942. all_group_names.add(group_name)
  943. else:
  944. log.error(
  945. f"Failed to create group '{group_name}' via OAuth."
  946. )
  947. except Exception as e:
  948. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  949. # Refresh the list of all available groups if any were created
  950. if groups_created:
  951. all_available_groups = Groups.get_groups()
  952. log.debug("Refreshed list of all available groups after creation.")
  953. log.debug(f"Oauth Groups claim: {oauth_claim}")
  954. log.debug(f"User oauth groups: {user_oauth_groups}")
  955. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  956. log.debug(
  957. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  958. )
  959. # Remove groups that user is no longer a part of
  960. for group_model in user_current_groups:
  961. if (
  962. user_oauth_groups
  963. and group_model.name not in user_oauth_groups
  964. and not is_in_blocked_groups(group_model.name, blocked_groups)
  965. ):
  966. # Remove group from user
  967. log.debug(
  968. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  969. )
  970. user_ids = group_model.user_ids
  971. user_ids = [i for i in user_ids if i != user.id]
  972. # In case a group is created, but perms are never assigned to the group by hitting "save"
  973. group_permissions = group_model.permissions
  974. if not group_permissions:
  975. group_permissions = default_permissions
  976. update_form = GroupUpdateForm(
  977. name=group_model.name,
  978. description=group_model.description,
  979. permissions=group_permissions,
  980. user_ids=user_ids,
  981. )
  982. Groups.update_group_by_id(
  983. id=group_model.id, form_data=update_form, overwrite=False
  984. )
  985. # Add user to new groups
  986. for group_model in all_available_groups:
  987. if (
  988. user_oauth_groups
  989. and group_model.name in user_oauth_groups
  990. and not any(gm.name == group_model.name for gm in user_current_groups)
  991. and not is_in_blocked_groups(group_model.name, blocked_groups)
  992. ):
  993. # Add user to group
  994. log.debug(
  995. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  996. )
  997. user_ids = group_model.user_ids
  998. user_ids.append(user.id)
  999. # In case a group is created, but perms are never assigned to the group by hitting "save"
  1000. group_permissions = group_model.permissions
  1001. if not group_permissions:
  1002. group_permissions = default_permissions
  1003. update_form = GroupUpdateForm(
  1004. name=group_model.name,
  1005. description=group_model.description,
  1006. permissions=group_permissions,
  1007. user_ids=user_ids,
  1008. )
  1009. Groups.update_group_by_id(
  1010. id=group_model.id, form_data=update_form, overwrite=False
  1011. )
  1012. async def _process_picture_url(
  1013. self, picture_url: str, access_token: str = None
  1014. ) -> str:
  1015. """Process a picture URL and return a base64 encoded data URL.
  1016. Args:
  1017. picture_url: The URL of the picture to process
  1018. access_token: Optional OAuth access token for authenticated requests
  1019. Returns:
  1020. A data URL containing the base64 encoded picture, or "/user.png" if processing fails
  1021. """
  1022. if not picture_url:
  1023. return "/user.png"
  1024. try:
  1025. get_kwargs = {}
  1026. if access_token:
  1027. get_kwargs["headers"] = {
  1028. "Authorization": f"Bearer {access_token}",
  1029. }
  1030. async with aiohttp.ClientSession(trust_env=True) as session:
  1031. async with session.get(
  1032. picture_url, **get_kwargs, ssl=AIOHTTP_CLIENT_SESSION_SSL
  1033. ) as resp:
  1034. if resp.ok:
  1035. picture = await resp.read()
  1036. base64_encoded_picture = base64.b64encode(picture).decode(
  1037. "utf-8"
  1038. )
  1039. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  1040. if guessed_mime_type is None:
  1041. guessed_mime_type = "image/jpeg"
  1042. return (
  1043. f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  1044. )
  1045. else:
  1046. log.warning(
  1047. f"Failed to fetch profile picture from {picture_url}"
  1048. )
  1049. return "/user.png"
  1050. except Exception as e:
  1051. log.error(f"Error processing profile picture '{picture_url}': {e}")
  1052. return "/user.png"
  1053. async def handle_login(self, request, provider):
  1054. if provider not in OAUTH_PROVIDERS:
  1055. raise HTTPException(404)
  1056. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  1057. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  1058. "oauth_login_callback", provider=provider
  1059. )
  1060. client = self.get_client(provider)
  1061. if client is None:
  1062. raise HTTPException(404)
  1063. return await client.authorize_redirect(request, redirect_uri)
  1064. async def handle_callback(self, request, provider, response):
  1065. if provider not in OAUTH_PROVIDERS:
  1066. raise HTTPException(404)
  1067. error_message = None
  1068. try:
  1069. client = self.get_client(provider)
  1070. auth_params = {}
  1071. if client:
  1072. if hasattr(client, "client_id"):
  1073. auth_params["client_id"] = client.client_id
  1074. if hasattr(client, "client_secret"):
  1075. auth_params["client_secret"] = client.client_secret
  1076. try:
  1077. token = await client.authorize_access_token(request, **auth_params)
  1078. except Exception as e:
  1079. detailed_error = _build_oauth_callback_error_message(e)
  1080. log.warning(
  1081. "OAuth callback error during authorize_access_token for provider %s: %s",
  1082. provider,
  1083. detailed_error,
  1084. exc_info=True,
  1085. )
  1086. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1087. # Try to get userinfo from the token first, some providers include it there
  1088. user_data: UserInfo = token.get("userinfo")
  1089. if (
  1090. (not user_data)
  1091. or (auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data)
  1092. or (auth_manager_config.OAUTH_USERNAME_CLAIM not in user_data)
  1093. ):
  1094. user_data: UserInfo = await client.userinfo(token=token)
  1095. if (
  1096. provider == "feishu"
  1097. and isinstance(user_data, dict)
  1098. and "data" in user_data
  1099. ):
  1100. user_data = user_data["data"]
  1101. if not user_data:
  1102. log.warning(f"OAuth callback failed, user data is missing: {token}")
  1103. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1104. # Extract the "sub" claim, using custom claim if configured
  1105. if auth_manager_config.OAUTH_SUB_CLAIM:
  1106. sub = user_data.get(auth_manager_config.OAUTH_SUB_CLAIM)
  1107. else:
  1108. # Fallback to the default sub claim if not configured
  1109. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  1110. if not sub:
  1111. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  1112. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1113. provider_sub = f"{provider}@{sub}"
  1114. # Email extraction
  1115. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  1116. email = user_data.get(email_claim, "")
  1117. # We currently mandate that email addresses are provided
  1118. if not email:
  1119. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  1120. if provider == "github":
  1121. try:
  1122. access_token = token.get("access_token")
  1123. headers = {"Authorization": f"Bearer {access_token}"}
  1124. async with aiohttp.ClientSession(trust_env=True) as session:
  1125. async with session.get(
  1126. "https://api.github.com/user/emails",
  1127. headers=headers,
  1128. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  1129. ) as resp:
  1130. if resp.ok:
  1131. emails = await resp.json()
  1132. # use the primary email as the user's email
  1133. primary_email = next(
  1134. (
  1135. e["email"]
  1136. for e in emails
  1137. if e.get("primary")
  1138. ),
  1139. None,
  1140. )
  1141. if primary_email:
  1142. email = primary_email
  1143. else:
  1144. log.warning(
  1145. "No primary email found in GitHub response"
  1146. )
  1147. raise HTTPException(
  1148. 400, detail=ERROR_MESSAGES.INVALID_CRED
  1149. )
  1150. else:
  1151. log.warning("Failed to fetch GitHub email")
  1152. raise HTTPException(
  1153. 400, detail=ERROR_MESSAGES.INVALID_CRED
  1154. )
  1155. except Exception as e:
  1156. log.warning(f"Error fetching GitHub email: {e}")
  1157. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1158. elif ENABLE_OAUTH_EMAIL_FALLBACK:
  1159. email = f"{provider_sub}.local"
  1160. else:
  1161. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  1162. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1163. email = email.lower()
  1164. # If allowed domains are configured, check if the email domain is in the list
  1165. if (
  1166. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  1167. and email.split("@")[-1]
  1168. not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  1169. ):
  1170. log.warning(
  1171. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  1172. )
  1173. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  1174. # Check if the user exists
  1175. user = Users.get_user_by_oauth_sub(provider_sub)
  1176. if not user:
  1177. # If the user does not exist, check if merging is enabled
  1178. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  1179. # Check if the user exists by email
  1180. user = Users.get_user_by_email(email)
  1181. if user:
  1182. # Update the user with the new oauth sub
  1183. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  1184. if user:
  1185. determined_role = self.get_user_role(user, user_data)
  1186. if user.role != determined_role:
  1187. Users.update_user_role_by_id(user.id, determined_role)
  1188. # Update profile picture if enabled and different from current
  1189. if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
  1190. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  1191. if picture_claim:
  1192. new_picture_url = user_data.get(
  1193. picture_claim,
  1194. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  1195. )
  1196. processed_picture_url = await self._process_picture_url(
  1197. new_picture_url, token.get("access_token")
  1198. )
  1199. if processed_picture_url != user.profile_image_url:
  1200. Users.update_user_profile_image_url_by_id(
  1201. user.id, processed_picture_url
  1202. )
  1203. log.debug(f"Updated profile picture for user {user.email}")
  1204. else:
  1205. # If the user does not exist, check if signups are enabled
  1206. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  1207. # Check if an existing user with the same email already exists
  1208. existing_user = Users.get_user_by_email(email)
  1209. if existing_user:
  1210. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  1211. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  1212. if picture_claim:
  1213. picture_url = user_data.get(
  1214. picture_claim,
  1215. OAUTH_PROVIDERS[provider].get("picture_url", ""),
  1216. )
  1217. picture_url = await self._process_picture_url(
  1218. picture_url, token.get("access_token")
  1219. )
  1220. else:
  1221. picture_url = "/user.png"
  1222. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  1223. name = user_data.get(username_claim)
  1224. if not name:
  1225. log.warning("Username claim is missing, using email as name")
  1226. name = email
  1227. user = Auths.insert_new_auth(
  1228. email=email,
  1229. password=get_password_hash(
  1230. str(uuid.uuid4())
  1231. ), # Random password, not used
  1232. name=name,
  1233. profile_image_url=picture_url,
  1234. role=self.get_user_role(None, user_data),
  1235. oauth_sub=provider_sub,
  1236. )
  1237. if auth_manager_config.WEBHOOK_URL:
  1238. await post_webhook(
  1239. WEBUI_NAME,
  1240. auth_manager_config.WEBHOOK_URL,
  1241. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1242. {
  1243. "action": "signup",
  1244. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  1245. "user": user.model_dump_json(exclude_none=True),
  1246. },
  1247. )
  1248. else:
  1249. raise HTTPException(
  1250. status.HTTP_403_FORBIDDEN,
  1251. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1252. )
  1253. jwt_token = create_token(
  1254. data={"id": user.id},
  1255. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  1256. )
  1257. if (
  1258. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT
  1259. and user.role != "admin"
  1260. ):
  1261. self.update_user_groups(
  1262. user=user,
  1263. user_data=user_data,
  1264. default_permissions=request.app.state.config.USER_PERMISSIONS,
  1265. )
  1266. except Exception as e:
  1267. log.error(f"Error during OAuth process: {e}")
  1268. error_message = (
  1269. e.detail
  1270. if isinstance(e, HTTPException) and e.detail
  1271. else ERROR_MESSAGES.DEFAULT("Error during OAuth process")
  1272. )
  1273. redirect_base_url = (
  1274. str(request.app.state.config.WEBUI_URL or request.base_url)
  1275. ).rstrip("/")
  1276. redirect_url = f"{redirect_base_url}/auth"
  1277. if error_message:
  1278. redirect_url = f"{redirect_url}?error={error_message}"
  1279. return RedirectResponse(url=redirect_url, headers=response.headers)
  1280. response = RedirectResponse(url=redirect_url, headers=response.headers)
  1281. # Set the cookie token
  1282. # Redirect back to the frontend with the JWT token
  1283. response.set_cookie(
  1284. key="token",
  1285. value=jwt_token,
  1286. httponly=False, # Required for frontend access
  1287. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1288. secure=WEBUI_AUTH_COOKIE_SECURE,
  1289. )
  1290. # Legacy cookies for compatibility with older frontend versions
  1291. if ENABLE_OAUTH_ID_TOKEN_COOKIE:
  1292. response.set_cookie(
  1293. key="oauth_id_token",
  1294. value=token.get("id_token"),
  1295. httponly=True,
  1296. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1297. secure=WEBUI_AUTH_COOKIE_SECURE,
  1298. )
  1299. try:
  1300. # Add timestamp for tracking
  1301. token["issued_at"] = datetime.now().timestamp()
  1302. # Calculate expires_at if we have expires_in
  1303. if "expires_in" in token and "expires_at" not in token:
  1304. token["expires_at"] = datetime.now().timestamp() + token["expires_in"]
  1305. # Clean up any existing sessions for this user/provider first
  1306. sessions = OAuthSessions.get_sessions_by_user_id(user.id)
  1307. for session in sessions:
  1308. if session.provider == provider:
  1309. OAuthSessions.delete_session_by_id(session.id)
  1310. session = OAuthSessions.create_session(
  1311. user_id=user.id,
  1312. provider=provider,
  1313. token=token,
  1314. )
  1315. response.set_cookie(
  1316. key="oauth_session_id",
  1317. value=session.id,
  1318. httponly=True,
  1319. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  1320. secure=WEBUI_AUTH_COOKIE_SECURE,
  1321. )
  1322. log.info(
  1323. f"Stored OAuth session server-side for user {user.id}, provider {provider}"
  1324. )
  1325. except Exception as e:
  1326. log.error(f"Failed to store OAuth session server-side: {e}")
  1327. return response