1
0

oauth.py 23 KB

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