oauth.py 22 KB

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