oauth.py 60 KB

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