oauth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import base64
  2. import logging
  3. import mimetypes
  4. import sys
  5. import uuid
  6. import json
  7. import aiohttp
  8. from authlib.integrations.starlette_client import OAuth
  9. from authlib.oidc.core import UserInfo
  10. from fastapi import (
  11. HTTPException,
  12. status,
  13. )
  14. from starlette.responses import RedirectResponse
  15. from open_webui.models.auths import Auths
  16. from open_webui.models.users import Users
  17. from open_webui.models.groups import Groups, GroupModel, GroupUpdateForm, GroupForm
  18. from open_webui.config import (
  19. DEFAULT_USER_ROLE,
  20. ENABLE_OAUTH_SIGNUP,
  21. OAUTH_MERGE_ACCOUNTS_BY_EMAIL,
  22. OAUTH_PROVIDERS,
  23. ENABLE_OAUTH_ROLE_MANAGEMENT,
  24. ENABLE_OAUTH_GROUP_MANAGEMENT,
  25. ENABLE_OAUTH_GROUP_CREATION,
  26. OAUTH_BLOCKED_GROUPS,
  27. OAUTH_ROLES_CLAIM,
  28. OAUTH_GROUPS_CLAIM,
  29. OAUTH_EMAIL_CLAIM,
  30. OAUTH_PICTURE_CLAIM,
  31. OAUTH_USERNAME_CLAIM,
  32. OAUTH_ALLOWED_ROLES,
  33. OAUTH_ADMIN_ROLES,
  34. OAUTH_ALLOWED_DOMAINS,
  35. OAUTH_UPDATE_PICTURE_ON_LOGIN,
  36. WEBHOOK_URL,
  37. JWT_EXPIRES_IN,
  38. AppConfig,
  39. )
  40. from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
  41. from open_webui.env import (
  42. AIOHTTP_CLIENT_SESSION_SSL,
  43. WEBUI_NAME,
  44. WEBUI_AUTH_COOKIE_SAME_SITE,
  45. WEBUI_AUTH_COOKIE_SECURE,
  46. )
  47. from open_webui.utils.misc import parse_duration
  48. from open_webui.utils.auth import get_password_hash, create_token
  49. from open_webui.utils.webhook import post_webhook
  50. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  51. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  52. log = logging.getLogger(__name__)
  53. log.setLevel(SRC_LOG_LEVELS["OAUTH"])
  54. auth_manager_config = AppConfig()
  55. auth_manager_config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
  56. auth_manager_config.ENABLE_OAUTH_SIGNUP = ENABLE_OAUTH_SIGNUP
  57. auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL = OAUTH_MERGE_ACCOUNTS_BY_EMAIL
  58. auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT = ENABLE_OAUTH_ROLE_MANAGEMENT
  59. auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT = ENABLE_OAUTH_GROUP_MANAGEMENT
  60. auth_manager_config.ENABLE_OAUTH_GROUP_CREATION = ENABLE_OAUTH_GROUP_CREATION
  61. auth_manager_config.OAUTH_BLOCKED_GROUPS = OAUTH_BLOCKED_GROUPS
  62. auth_manager_config.OAUTH_ROLES_CLAIM = OAUTH_ROLES_CLAIM
  63. auth_manager_config.OAUTH_GROUPS_CLAIM = OAUTH_GROUPS_CLAIM
  64. auth_manager_config.OAUTH_EMAIL_CLAIM = OAUTH_EMAIL_CLAIM
  65. auth_manager_config.OAUTH_PICTURE_CLAIM = OAUTH_PICTURE_CLAIM
  66. auth_manager_config.OAUTH_USERNAME_CLAIM = OAUTH_USERNAME_CLAIM
  67. auth_manager_config.OAUTH_ALLOWED_ROLES = OAUTH_ALLOWED_ROLES
  68. auth_manager_config.OAUTH_ADMIN_ROLES = OAUTH_ADMIN_ROLES
  69. auth_manager_config.OAUTH_ALLOWED_DOMAINS = OAUTH_ALLOWED_DOMAINS
  70. auth_manager_config.WEBHOOK_URL = WEBHOOK_URL
  71. auth_manager_config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
  72. auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN = OAUTH_UPDATE_PICTURE_ON_LOGIN
  73. class OAuthManager:
  74. def __init__(self, app):
  75. self.oauth = OAuth()
  76. self.app = app
  77. for _, provider_config in OAUTH_PROVIDERS.items():
  78. provider_config["register"](self.oauth)
  79. def get_client(self, provider_name):
  80. return self.oauth.create_client(provider_name)
  81. def get_user_role(self, user, user_data):
  82. user_count = Users.get_num_users()
  83. if user and user_count == 1:
  84. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  85. log.debug("Assigning the only user the admin role")
  86. return "admin"
  87. if not user and user_count == 0:
  88. # If there are no users, assign the role "admin", as the first user will be an admin
  89. log.debug("Assigning the first user the admin role")
  90. return "admin"
  91. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  92. log.debug("Running OAUTH Role management")
  93. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  94. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  95. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  96. oauth_roles = []
  97. # Default/fallback role if no matching roles are found
  98. role = auth_manager_config.DEFAULT_USER_ROLE
  99. # Next block extracts the roles from the user data, accepting nested claims of any depth
  100. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  101. claim_data = user_data
  102. nested_claims = oauth_claim.split(".")
  103. for nested_claim in nested_claims:
  104. claim_data = claim_data.get(nested_claim, {})
  105. oauth_roles = claim_data if isinstance(claim_data, list) else []
  106. log.debug(f"Oauth Roles claim: {oauth_claim}")
  107. log.debug(f"User roles from oauth: {oauth_roles}")
  108. log.debug(f"Accepted user roles: {oauth_allowed_roles}")
  109. log.debug(f"Accepted admin roles: {oauth_admin_roles}")
  110. # If any roles are found, check if they match the allowed or admin roles
  111. if oauth_roles:
  112. # If role management is enabled, and matching roles are provided, use the roles
  113. for allowed_role in oauth_allowed_roles:
  114. # If the user has any of the allowed roles, assign the role "user"
  115. if allowed_role in oauth_roles:
  116. log.debug("Assigned user the user role")
  117. role = "user"
  118. break
  119. for admin_role in oauth_admin_roles:
  120. # If the user has any of the admin roles, assign the role "admin"
  121. if admin_role in oauth_roles:
  122. log.debug("Assigned user the admin role")
  123. role = "admin"
  124. break
  125. else:
  126. if not user:
  127. # If role management is disabled, use the default role for new users
  128. role = auth_manager_config.DEFAULT_USER_ROLE
  129. else:
  130. # If role management is disabled, use the existing role for existing users
  131. role = user.role
  132. return role
  133. def update_user_groups(self, user, user_data, default_permissions):
  134. log.debug("Running OAUTH Group management")
  135. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  136. try:
  137. blocked_groups = json.loads(auth_manager_config.OAUTH_BLOCKED_GROUPS)
  138. except Exception as e:
  139. log.exception(f"Error loading OAUTH_BLOCKED_GROUPS: {e}")
  140. blocked_groups = []
  141. user_oauth_groups = []
  142. # Nested claim search for groups claim
  143. if oauth_claim:
  144. claim_data = user_data
  145. nested_claims = oauth_claim.split(".")
  146. for nested_claim in nested_claims:
  147. claim_data = claim_data.get(nested_claim, {})
  148. if isinstance(claim_data, list):
  149. user_oauth_groups = claim_data
  150. elif isinstance(claim_data, str):
  151. user_oauth_groups = [claim_data]
  152. else:
  153. user_oauth_groups = []
  154. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  155. all_available_groups: list[GroupModel] = Groups.get_groups()
  156. # Create groups if they don't exist and creation is enabled
  157. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  158. log.debug("Checking for missing groups to create...")
  159. all_group_names = {g.name for g in all_available_groups}
  160. groups_created = False
  161. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  162. admin_user = Users.get_super_admin_user()
  163. creator_id = admin_user.id if admin_user else user.id
  164. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  165. for group_name in user_oauth_groups:
  166. if group_name not in all_group_names:
  167. log.info(
  168. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  169. )
  170. try:
  171. new_group_form = GroupForm(
  172. name=group_name,
  173. description=f"Group '{group_name}' created automatically via OAuth.",
  174. permissions=default_permissions, # Use default permissions from function args
  175. user_ids=[], # Start with no users, user will be added later by subsequent logic
  176. )
  177. # Use determined creator ID (admin or fallback to current user)
  178. created_group = Groups.insert_new_group(
  179. creator_id, new_group_form
  180. )
  181. if created_group:
  182. log.info(
  183. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  184. )
  185. groups_created = True
  186. # Add to local set to prevent duplicate creation attempts in this run
  187. all_group_names.add(group_name)
  188. else:
  189. log.error(
  190. f"Failed to create group '{group_name}' via OAuth."
  191. )
  192. except Exception as e:
  193. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  194. # Refresh the list of all available groups if any were created
  195. if groups_created:
  196. all_available_groups = Groups.get_groups()
  197. log.debug("Refreshed list of all available groups after creation.")
  198. log.debug(f"Oauth Groups claim: {oauth_claim}")
  199. log.debug(f"User oauth groups: {user_oauth_groups}")
  200. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  201. log.debug(
  202. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  203. )
  204. # Remove groups that user is no longer a part of
  205. for group_model in user_current_groups:
  206. if (
  207. user_oauth_groups
  208. and group_model.name not in user_oauth_groups
  209. and group_model.name not in blocked_groups
  210. ):
  211. # Remove group from user
  212. log.debug(
  213. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  214. )
  215. user_ids = group_model.user_ids
  216. user_ids = [i for i in user_ids if i != user.id]
  217. # In case a group is created, but perms are never assigned to the group by hitting "save"
  218. group_permissions = group_model.permissions
  219. if not group_permissions:
  220. group_permissions = default_permissions
  221. update_form = GroupUpdateForm(
  222. name=group_model.name,
  223. description=group_model.description,
  224. permissions=group_permissions,
  225. user_ids=user_ids,
  226. )
  227. Groups.update_group_by_id(
  228. id=group_model.id, form_data=update_form, overwrite=False
  229. )
  230. # Add user to new groups
  231. for group_model in all_available_groups:
  232. if (
  233. user_oauth_groups
  234. and group_model.name in user_oauth_groups
  235. and not any(gm.name == group_model.name for gm in user_current_groups)
  236. and group_model.name not in blocked_groups
  237. ):
  238. # Add user to group
  239. log.debug(
  240. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  241. )
  242. user_ids = group_model.user_ids
  243. user_ids.append(user.id)
  244. # In case a group is created, but perms are never assigned to the group by hitting "save"
  245. group_permissions = group_model.permissions
  246. if not group_permissions:
  247. group_permissions = default_permissions
  248. update_form = GroupUpdateForm(
  249. name=group_model.name,
  250. description=group_model.description,
  251. permissions=group_permissions,
  252. user_ids=user_ids,
  253. )
  254. Groups.update_group_by_id(
  255. id=group_model.id, form_data=update_form, overwrite=False
  256. )
  257. async def _process_picture_url(
  258. self, picture_url: str, access_token: str = None
  259. ) -> str:
  260. """Process a picture URL and return a base64 encoded data URL.
  261. Args:
  262. picture_url: The URL of the picture to process
  263. access_token: Optional OAuth access token for authenticated requests
  264. Returns:
  265. A data URL containing the base64 encoded picture, or "/user.png" if processing fails
  266. """
  267. if not picture_url:
  268. return "/user.png"
  269. try:
  270. get_kwargs = {}
  271. if access_token:
  272. get_kwargs["headers"] = {
  273. "Authorization": f"Bearer {access_token}",
  274. }
  275. async with aiohttp.ClientSession(trust_env=True) as session:
  276. async with session.get(
  277. picture_url, **get_kwargs, ssl=AIOHTTP_CLIENT_SESSION_SSL
  278. ) as resp:
  279. if resp.ok:
  280. picture = await resp.read()
  281. base64_encoded_picture = base64.b64encode(picture).decode(
  282. "utf-8"
  283. )
  284. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  285. if guessed_mime_type is None:
  286. guessed_mime_type = "image/jpeg"
  287. return (
  288. f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  289. )
  290. else:
  291. log.warning(
  292. f"Failed to fetch profile picture from {picture_url}"
  293. )
  294. return "/user.png"
  295. except Exception as e:
  296. log.error(f"Error processing profile picture '{picture_url}': {e}")
  297. return "/user.png"
  298. async def handle_login(self, request, provider):
  299. if provider not in OAUTH_PROVIDERS:
  300. raise HTTPException(404)
  301. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  302. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  303. "oauth_callback", provider=provider
  304. )
  305. client = self.get_client(provider)
  306. if client is None:
  307. raise HTTPException(404)
  308. return await client.authorize_redirect(request, redirect_uri)
  309. async def handle_callback(self, request, provider, response):
  310. if provider not in OAUTH_PROVIDERS:
  311. raise HTTPException(404)
  312. client = self.get_client(provider)
  313. try:
  314. token = await client.authorize_access_token(request)
  315. except Exception as e:
  316. log.warning(f"OAuth callback error: {e}")
  317. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  318. user_data: UserInfo = token.get("userinfo")
  319. if not user_data or auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data:
  320. user_data: UserInfo = await client.userinfo(token=token)
  321. if not user_data:
  322. log.warning(f"OAuth callback failed, user data is missing: {token}")
  323. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  324. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  325. if not sub:
  326. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  327. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  328. provider_sub = f"{provider}@{sub}"
  329. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  330. email = user_data.get(email_claim, "")
  331. # We currently mandate that email addresses are provided
  332. if not email:
  333. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  334. if provider == "github":
  335. try:
  336. access_token = token.get("access_token")
  337. headers = {"Authorization": f"Bearer {access_token}"}
  338. async with aiohttp.ClientSession(trust_env=True) as session:
  339. async with session.get(
  340. "https://api.github.com/user/emails",
  341. headers=headers,
  342. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  343. ) as resp:
  344. if resp.ok:
  345. emails = await resp.json()
  346. # use the primary email as the user's email
  347. primary_email = next(
  348. (e["email"] for e in emails if e.get("primary")),
  349. None,
  350. )
  351. if primary_email:
  352. email = primary_email
  353. else:
  354. log.warning(
  355. "No primary email found in GitHub response"
  356. )
  357. raise HTTPException(
  358. 400, detail=ERROR_MESSAGES.INVALID_CRED
  359. )
  360. else:
  361. log.warning("Failed to fetch GitHub email")
  362. raise HTTPException(
  363. 400, detail=ERROR_MESSAGES.INVALID_CRED
  364. )
  365. except Exception as e:
  366. log.warning(f"Error fetching GitHub email: {e}")
  367. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  368. else:
  369. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  370. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  371. email = email.lower()
  372. if (
  373. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  374. and email.split("@")[-1] not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  375. ):
  376. log.warning(
  377. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  378. )
  379. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  380. # Check if the user exists
  381. user = Users.get_user_by_oauth_sub(provider_sub)
  382. if not user:
  383. # If the user does not exist, check if merging is enabled
  384. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  385. # Check if the user exists by email
  386. user = Users.get_user_by_email(email)
  387. if user:
  388. # Update the user with the new oauth sub
  389. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  390. if user:
  391. determined_role = self.get_user_role(user, user_data)
  392. if user.role != determined_role:
  393. Users.update_user_role_by_id(user.id, determined_role)
  394. # Update profile picture if enabled and different from current
  395. if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
  396. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  397. if picture_claim:
  398. new_picture_url = user_data.get(
  399. picture_claim, OAUTH_PROVIDERS[provider].get("picture_url", "")
  400. )
  401. processed_picture_url = await self._process_picture_url(
  402. new_picture_url, token.get("access_token")
  403. )
  404. if processed_picture_url != user.profile_image_url:
  405. Users.update_user_profile_image_url_by_id(
  406. user.id, processed_picture_url
  407. )
  408. log.debug(f"Updated profile picture for user {user.email}")
  409. if not user:
  410. # If the user does not exist, check if signups are enabled
  411. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  412. # Check if an existing user with the same email already exists
  413. existing_user = Users.get_user_by_email(email)
  414. if existing_user:
  415. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  416. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  417. if picture_claim:
  418. picture_url = user_data.get(
  419. picture_claim, OAUTH_PROVIDERS[provider].get("picture_url", "")
  420. )
  421. picture_url = await self._process_picture_url(
  422. picture_url, token.get("access_token")
  423. )
  424. else:
  425. picture_url = "/user.png"
  426. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  427. name = user_data.get(username_claim)
  428. if not name:
  429. log.warning("Username claim is missing, using email as name")
  430. name = email
  431. role = self.get_user_role(None, user_data)
  432. user = Auths.insert_new_auth(
  433. email=email,
  434. password=get_password_hash(
  435. str(uuid.uuid4())
  436. ), # Random password, not used
  437. name=name,
  438. profile_image_url=picture_url,
  439. role=role,
  440. oauth_sub=provider_sub,
  441. )
  442. if auth_manager_config.WEBHOOK_URL:
  443. post_webhook(
  444. WEBUI_NAME,
  445. auth_manager_config.WEBHOOK_URL,
  446. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  447. {
  448. "action": "signup",
  449. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  450. "user": user.model_dump_json(exclude_none=True),
  451. },
  452. )
  453. else:
  454. raise HTTPException(
  455. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  456. )
  457. jwt_token = create_token(
  458. data={"id": user.id},
  459. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  460. )
  461. if auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT and user.role != "admin":
  462. self.update_user_groups(
  463. user=user,
  464. user_data=user_data,
  465. default_permissions=request.app.state.config.USER_PERMISSIONS,
  466. )
  467. # Set the cookie token
  468. response.set_cookie(
  469. key="token",
  470. value=jwt_token,
  471. httponly=False, # Required for frontend access
  472. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  473. secure=WEBUI_AUTH_COOKIE_SECURE,
  474. )
  475. if ENABLE_OAUTH_SIGNUP.value:
  476. oauth_id_token = token.get("id_token")
  477. response.set_cookie(
  478. key="oauth_id_token",
  479. value=oauth_id_token,
  480. httponly=True,
  481. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  482. secure=WEBUI_AUTH_COOKIE_SECURE,
  483. )
  484. # Redirect back to the frontend with the JWT token
  485. redirect_base_url = str(request.app.state.config.WEBUI_URL or request.base_url)
  486. if redirect_base_url.endswith("/"):
  487. redirect_base_url = redirect_base_url[:-1]
  488. redirect_url = f"{redirect_base_url}/auth"
  489. return RedirectResponse(url=redirect_url, headers=response.headers)