oauth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. if user and Users.get_num_users() == 1:
  83. # If the user is the only user, assign the role "admin" - actually repairs role for single user on login
  84. log.debug("Assigning the only user the admin role")
  85. return "admin"
  86. if not user and Users.get_num_users() == 0:
  87. # If there are no users, assign the role "admin", as the first user will be an admin
  88. log.debug("Assigning the first user the admin role")
  89. return "admin"
  90. if auth_manager_config.ENABLE_OAUTH_ROLE_MANAGEMENT:
  91. log.debug("Running OAUTH Role management")
  92. oauth_claim = auth_manager_config.OAUTH_ROLES_CLAIM
  93. oauth_allowed_roles = auth_manager_config.OAUTH_ALLOWED_ROLES
  94. oauth_admin_roles = auth_manager_config.OAUTH_ADMIN_ROLES
  95. oauth_roles = []
  96. # Default/fallback role if no matching roles are found
  97. role = auth_manager_config.DEFAULT_USER_ROLE
  98. # Next block extracts the roles from the user data, accepting nested claims of any depth
  99. if oauth_claim and oauth_allowed_roles and oauth_admin_roles:
  100. claim_data = user_data
  101. nested_claims = oauth_claim.split(".")
  102. for nested_claim in nested_claims:
  103. claim_data = claim_data.get(nested_claim, {})
  104. oauth_roles = claim_data if isinstance(claim_data, list) else []
  105. log.debug(f"Oauth Roles claim: {oauth_claim}")
  106. log.debug(f"User roles from oauth: {oauth_roles}")
  107. log.debug(f"Accepted user roles: {oauth_allowed_roles}")
  108. log.debug(f"Accepted admin roles: {oauth_admin_roles}")
  109. # If any roles are found, check if they match the allowed or admin roles
  110. if oauth_roles:
  111. # If role management is enabled, and matching roles are provided, use the roles
  112. for allowed_role in oauth_allowed_roles:
  113. # If the user has any of the allowed roles, assign the role "user"
  114. if allowed_role in oauth_roles:
  115. log.debug("Assigned user the user role")
  116. role = "user"
  117. break
  118. for admin_role in oauth_admin_roles:
  119. # If the user has any of the admin roles, assign the role "admin"
  120. if admin_role in oauth_roles:
  121. log.debug("Assigned user the admin role")
  122. role = "admin"
  123. break
  124. else:
  125. if not user:
  126. # If role management is disabled, use the default role for new users
  127. role = auth_manager_config.DEFAULT_USER_ROLE
  128. else:
  129. # If role management is disabled, use the existing role for existing users
  130. role = user.role
  131. return role
  132. def update_user_groups(self, user, user_data, default_permissions):
  133. log.debug("Running OAUTH Group management")
  134. oauth_claim = auth_manager_config.OAUTH_GROUPS_CLAIM
  135. try:
  136. blocked_groups = json.loads(auth_manager_config.OAUTH_BLOCKED_GROUPS)
  137. except Exception as e:
  138. log.exception(f"Error loading OAUTH_BLOCKED_GROUPS: {e}")
  139. blocked_groups = []
  140. user_oauth_groups = []
  141. # Nested claim search for groups claim
  142. if oauth_claim:
  143. claim_data = user_data
  144. nested_claims = oauth_claim.split(".")
  145. for nested_claim in nested_claims:
  146. claim_data = claim_data.get(nested_claim, {})
  147. if isinstance(claim_data, list):
  148. user_oauth_groups = claim_data
  149. elif isinstance(claim_data, str):
  150. user_oauth_groups = [claim_data]
  151. else:
  152. user_oauth_groups = []
  153. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  154. all_available_groups: list[GroupModel] = Groups.get_groups()
  155. # Create groups if they don't exist and creation is enabled
  156. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  157. log.debug("Checking for missing groups to create...")
  158. all_group_names = {g.name for g in all_available_groups}
  159. groups_created = False
  160. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  161. admin_user = Users.get_super_admin_user()
  162. creator_id = admin_user.id if admin_user else user.id
  163. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  164. for group_name in user_oauth_groups:
  165. if group_name not in all_group_names:
  166. log.info(
  167. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  168. )
  169. try:
  170. new_group_form = GroupForm(
  171. name=group_name,
  172. description=f"Group '{group_name}' created automatically via OAuth.",
  173. permissions=default_permissions, # Use default permissions from function args
  174. user_ids=[], # Start with no users, user will be added later by subsequent logic
  175. )
  176. # Use determined creator ID (admin or fallback to current user)
  177. created_group = Groups.insert_new_group(
  178. creator_id, new_group_form
  179. )
  180. if created_group:
  181. log.info(
  182. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  183. )
  184. groups_created = True
  185. # Add to local set to prevent duplicate creation attempts in this run
  186. all_group_names.add(group_name)
  187. else:
  188. log.error(
  189. f"Failed to create group '{group_name}' via OAuth."
  190. )
  191. except Exception as e:
  192. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  193. # Refresh the list of all available groups if any were created
  194. if groups_created:
  195. all_available_groups = Groups.get_groups()
  196. log.debug("Refreshed list of all available groups after creation.")
  197. log.debug(f"Oauth Groups claim: {oauth_claim}")
  198. log.debug(f"User oauth groups: {user_oauth_groups}")
  199. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  200. log.debug(
  201. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  202. )
  203. # Remove groups that user is no longer a part of
  204. for group_model in user_current_groups:
  205. if (
  206. user_oauth_groups
  207. and group_model.name not in user_oauth_groups
  208. and group_model.name not in blocked_groups
  209. ):
  210. # Remove group from user
  211. log.debug(
  212. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  213. )
  214. user_ids = group_model.user_ids
  215. user_ids = [i for i in user_ids if i != user.id]
  216. # In case a group is created, but perms are never assigned to the group by hitting "save"
  217. group_permissions = group_model.permissions
  218. if not group_permissions:
  219. group_permissions = default_permissions
  220. update_form = GroupUpdateForm(
  221. name=group_model.name,
  222. description=group_model.description,
  223. permissions=group_permissions,
  224. user_ids=user_ids,
  225. )
  226. Groups.update_group_by_id(
  227. id=group_model.id, form_data=update_form, overwrite=False
  228. )
  229. # Add user to new groups
  230. for group_model in all_available_groups:
  231. if (
  232. user_oauth_groups
  233. and group_model.name in user_oauth_groups
  234. and not any(gm.name == group_model.name for gm in user_current_groups)
  235. and group_model.name not in blocked_groups
  236. ):
  237. # Add user to group
  238. log.debug(
  239. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  240. )
  241. user_ids = group_model.user_ids
  242. user_ids.append(user.id)
  243. # In case a group is created, but perms are never assigned to the group by hitting "save"
  244. group_permissions = group_model.permissions
  245. if not group_permissions:
  246. group_permissions = default_permissions
  247. update_form = GroupUpdateForm(
  248. name=group_model.name,
  249. description=group_model.description,
  250. permissions=group_permissions,
  251. user_ids=user_ids,
  252. )
  253. Groups.update_group_by_id(
  254. id=group_model.id, form_data=update_form, overwrite=False
  255. )
  256. async def _process_picture_url(
  257. self, picture_url: str, access_token: str = None
  258. ) -> str:
  259. """Process a picture URL and return a base64 encoded data URL.
  260. Args:
  261. picture_url: The URL of the picture to process
  262. access_token: Optional OAuth access token for authenticated requests
  263. Returns:
  264. A data URL containing the base64 encoded picture, or "/user.png" if processing fails
  265. """
  266. if not picture_url:
  267. return "/user.png"
  268. try:
  269. get_kwargs = {}
  270. if access_token:
  271. get_kwargs["headers"] = {
  272. "Authorization": f"Bearer {access_token}",
  273. }
  274. async with aiohttp.ClientSession(trust_env=True) as session:
  275. async with session.get(
  276. picture_url, **get_kwargs, ssl=AIOHTTP_CLIENT_SESSION_SSL
  277. ) as resp:
  278. if resp.ok:
  279. picture = await resp.read()
  280. base64_encoded_picture = base64.b64encode(picture).decode(
  281. "utf-8"
  282. )
  283. guessed_mime_type = mimetypes.guess_type(picture_url)[0]
  284. if guessed_mime_type is None:
  285. guessed_mime_type = "image/jpeg"
  286. return (
  287. f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  288. )
  289. else:
  290. log.warning(
  291. f"Failed to fetch profile picture from {picture_url}"
  292. )
  293. return "/user.png"
  294. except Exception as e:
  295. log.error(f"Error processing profile picture '{picture_url}': {e}")
  296. return "/user.png"
  297. async def handle_login(self, request, provider):
  298. if provider not in OAUTH_PROVIDERS:
  299. raise HTTPException(404)
  300. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  301. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  302. "oauth_callback", provider=provider
  303. )
  304. client = self.get_client(provider)
  305. if client is None:
  306. raise HTTPException(404)
  307. return await client.authorize_redirect(request, redirect_uri)
  308. async def handle_callback(self, request, provider, response):
  309. if provider not in OAUTH_PROVIDERS:
  310. raise HTTPException(404)
  311. client = self.get_client(provider)
  312. try:
  313. token = await client.authorize_access_token(request)
  314. except Exception as e:
  315. log.warning(f"OAuth callback error: {e}")
  316. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  317. user_data: UserInfo = token.get("userinfo")
  318. if not user_data or auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data:
  319. user_data: UserInfo = await client.userinfo(token=token)
  320. if not user_data:
  321. log.warning(f"OAuth callback failed, user data is missing: {token}")
  322. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  323. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  324. if not sub:
  325. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  326. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  327. provider_sub = f"{provider}@{sub}"
  328. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  329. email = user_data.get(email_claim, "")
  330. # We currently mandate that email addresses are provided
  331. if not email:
  332. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  333. if provider == "github":
  334. try:
  335. access_token = token.get("access_token")
  336. headers = {"Authorization": f"Bearer {access_token}"}
  337. async with aiohttp.ClientSession(trust_env=True) as session:
  338. async with session.get(
  339. "https://api.github.com/user/emails",
  340. headers=headers,
  341. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  342. ) as resp:
  343. if resp.ok:
  344. emails = await resp.json()
  345. # use the primary email as the user's email
  346. primary_email = next(
  347. (e["email"] for e in emails if e.get("primary")),
  348. None,
  349. )
  350. if primary_email:
  351. email = primary_email
  352. else:
  353. log.warning(
  354. "No primary email found in GitHub response"
  355. )
  356. raise HTTPException(
  357. 400, detail=ERROR_MESSAGES.INVALID_CRED
  358. )
  359. else:
  360. log.warning("Failed to fetch GitHub email")
  361. raise HTTPException(
  362. 400, detail=ERROR_MESSAGES.INVALID_CRED
  363. )
  364. except Exception as e:
  365. log.warning(f"Error fetching GitHub email: {e}")
  366. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  367. else:
  368. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  369. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  370. email = email.lower()
  371. if (
  372. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  373. and email.split("@")[-1] not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  374. ):
  375. log.warning(
  376. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  377. )
  378. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  379. # Check if the user exists
  380. user = Users.get_user_by_oauth_sub(provider_sub)
  381. if not user:
  382. # If the user does not exist, check if merging is enabled
  383. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  384. # Check if the user exists by email
  385. user = Users.get_user_by_email(email)
  386. if user:
  387. # Update the user with the new oauth sub
  388. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  389. if user:
  390. determined_role = self.get_user_role(user, user_data)
  391. if user.role != determined_role:
  392. Users.update_user_role_by_id(user.id, determined_role)
  393. # Update profile picture if enabled and different from current
  394. if auth_manager_config.OAUTH_UPDATE_PICTURE_ON_LOGIN:
  395. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  396. if picture_claim:
  397. new_picture_url = user_data.get(
  398. picture_claim, OAUTH_PROVIDERS[provider].get("picture_url", "")
  399. )
  400. processed_picture_url = await self._process_picture_url(
  401. new_picture_url, token.get("access_token")
  402. )
  403. if processed_picture_url != user.profile_image_url:
  404. Users.update_user_profile_image_url_by_id(
  405. user.id, processed_picture_url
  406. )
  407. log.debug(f"Updated profile picture for user {user.email}")
  408. if not user:
  409. user_count = Users.get_num_users()
  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=True, # Ensures the cookie is not accessible via JavaScript
  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#token={jwt_token}"
  489. return RedirectResponse(url=redirect_url, headers=response.headers)