oauth.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. if isinstance(claim_data, list):
  145. user_oauth_groups = claim_data
  146. elif isinstance(claim_data, str):
  147. user_oauth_groups = [claim_data]
  148. else:
  149. user_oauth_groups = []
  150. user_current_groups: list[GroupModel] = Groups.get_groups_by_member_id(user.id)
  151. all_available_groups: list[GroupModel] = Groups.get_groups()
  152. # Create groups if they don't exist and creation is enabled
  153. if auth_manager_config.ENABLE_OAUTH_GROUP_CREATION:
  154. log.debug("Checking for missing groups to create...")
  155. all_group_names = {g.name for g in all_available_groups}
  156. groups_created = False
  157. # Determine creator ID: Prefer admin, fallback to current user if no admin exists
  158. admin_user = Users.get_super_admin_user()
  159. creator_id = admin_user.id if admin_user else user.id
  160. log.debug(f"Using creator ID {creator_id} for potential group creation.")
  161. for group_name in user_oauth_groups:
  162. if group_name not in all_group_names:
  163. log.info(
  164. f"Group '{group_name}' not found via OAuth claim. Creating group..."
  165. )
  166. try:
  167. new_group_form = GroupForm(
  168. name=group_name,
  169. description=f"Group '{group_name}' created automatically via OAuth.",
  170. permissions=default_permissions, # Use default permissions from function args
  171. user_ids=[], # Start with no users, user will be added later by subsequent logic
  172. )
  173. # Use determined creator ID (admin or fallback to current user)
  174. created_group = Groups.insert_new_group(
  175. creator_id, new_group_form
  176. )
  177. if created_group:
  178. log.info(
  179. f"Successfully created group '{group_name}' with ID {created_group.id} using creator ID {creator_id}"
  180. )
  181. groups_created = True
  182. # Add to local set to prevent duplicate creation attempts in this run
  183. all_group_names.add(group_name)
  184. else:
  185. log.error(
  186. f"Failed to create group '{group_name}' via OAuth."
  187. )
  188. except Exception as e:
  189. log.error(f"Error creating group '{group_name}' via OAuth: {e}")
  190. # Refresh the list of all available groups if any were created
  191. if groups_created:
  192. all_available_groups = Groups.get_groups()
  193. log.debug("Refreshed list of all available groups after creation.")
  194. log.debug(f"Oauth Groups claim: {oauth_claim}")
  195. log.debug(f"User oauth groups: {user_oauth_groups}")
  196. log.debug(f"User's current groups: {[g.name for g in user_current_groups]}")
  197. log.debug(
  198. f"All groups available in OpenWebUI: {[g.name for g in all_available_groups]}"
  199. )
  200. # Remove groups that user is no longer a part of
  201. for group_model in user_current_groups:
  202. if (
  203. user_oauth_groups
  204. and group_model.name not in user_oauth_groups
  205. and group_model.name not in blocked_groups
  206. ):
  207. # Remove group from user
  208. log.debug(
  209. f"Removing user from group {group_model.name} as it is no longer in their oauth groups"
  210. )
  211. user_ids = group_model.user_ids
  212. user_ids = [i for i in user_ids if i != user.id]
  213. # In case a group is created, but perms are never assigned to the group by hitting "save"
  214. group_permissions = group_model.permissions
  215. if not group_permissions:
  216. group_permissions = default_permissions
  217. update_form = GroupUpdateForm(
  218. name=group_model.name,
  219. description=group_model.description,
  220. permissions=group_permissions,
  221. user_ids=user_ids,
  222. )
  223. Groups.update_group_by_id(
  224. id=group_model.id, form_data=update_form, overwrite=False
  225. )
  226. # Add user to new groups
  227. for group_model in all_available_groups:
  228. if (
  229. user_oauth_groups
  230. and group_model.name in user_oauth_groups
  231. and not any(gm.name == group_model.name for gm in user_current_groups)
  232. and group_model.name not in blocked_groups
  233. ):
  234. # Add user to group
  235. log.debug(
  236. f"Adding user to group {group_model.name} as it was found in their oauth groups"
  237. )
  238. user_ids = group_model.user_ids
  239. user_ids.append(user.id)
  240. # In case a group is created, but perms are never assigned to the group by hitting "save"
  241. group_permissions = group_model.permissions
  242. if not group_permissions:
  243. group_permissions = default_permissions
  244. update_form = GroupUpdateForm(
  245. name=group_model.name,
  246. description=group_model.description,
  247. permissions=group_permissions,
  248. user_ids=user_ids,
  249. )
  250. Groups.update_group_by_id(
  251. id=group_model.id, form_data=update_form, overwrite=False
  252. )
  253. async def handle_login(self, request, provider):
  254. if provider not in OAUTH_PROVIDERS:
  255. raise HTTPException(404)
  256. # If the provider has a custom redirect URL, use that, otherwise automatically generate one
  257. redirect_uri = OAUTH_PROVIDERS[provider].get("redirect_uri") or request.url_for(
  258. "oauth_callback", provider=provider
  259. )
  260. client = self.get_client(provider)
  261. if client is None:
  262. raise HTTPException(404)
  263. return await client.authorize_redirect(request, redirect_uri)
  264. async def handle_callback(self, request, provider, response):
  265. if provider not in OAUTH_PROVIDERS:
  266. raise HTTPException(404)
  267. client = self.get_client(provider)
  268. try:
  269. token = await client.authorize_access_token(request)
  270. except Exception as e:
  271. log.warning(f"OAuth callback error: {e}")
  272. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  273. user_data: UserInfo = token.get("userinfo")
  274. if not user_data or auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data:
  275. user_data: UserInfo = await client.userinfo(token=token)
  276. if not user_data:
  277. log.warning(f"OAuth callback failed, user data is missing: {token}")
  278. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  279. sub = user_data.get(OAUTH_PROVIDERS[provider].get("sub_claim", "sub"))
  280. if not sub:
  281. log.warning(f"OAuth callback failed, sub is missing: {user_data}")
  282. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  283. provider_sub = f"{provider}@{sub}"
  284. email_claim = auth_manager_config.OAUTH_EMAIL_CLAIM
  285. email = user_data.get(email_claim, "")
  286. # We currently mandate that email addresses are provided
  287. if not email:
  288. # If the provider is GitHub,and public email is not provided, we can use the access token to fetch the user's email
  289. if provider == "github":
  290. try:
  291. access_token = token.get("access_token")
  292. headers = {"Authorization": f"Bearer {access_token}"}
  293. async with aiohttp.ClientSession(trust_env=True) as session:
  294. async with session.get(
  295. "https://api.github.com/user/emails", headers=headers
  296. ) as resp:
  297. if resp.ok:
  298. emails = await resp.json()
  299. # use the primary email as the user's email
  300. primary_email = next(
  301. (e["email"] for e in emails if e.get("primary")),
  302. None,
  303. )
  304. if primary_email:
  305. email = primary_email
  306. else:
  307. log.warning(
  308. "No primary email found in GitHub response"
  309. )
  310. raise HTTPException(
  311. 400, detail=ERROR_MESSAGES.INVALID_CRED
  312. )
  313. else:
  314. log.warning("Failed to fetch GitHub email")
  315. raise HTTPException(
  316. 400, detail=ERROR_MESSAGES.INVALID_CRED
  317. )
  318. except Exception as e:
  319. log.warning(f"Error fetching GitHub email: {e}")
  320. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  321. else:
  322. log.warning(f"OAuth callback failed, email is missing: {user_data}")
  323. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  324. email = email.lower()
  325. if (
  326. "*" not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  327. and email.split("@")[-1] not in auth_manager_config.OAUTH_ALLOWED_DOMAINS
  328. ):
  329. log.warning(
  330. f"OAuth callback failed, e-mail domain is not in the list of allowed domains: {user_data}"
  331. )
  332. raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
  333. # Check if the user exists
  334. user = Users.get_user_by_oauth_sub(provider_sub)
  335. if not user:
  336. # If the user does not exist, check if merging is enabled
  337. if auth_manager_config.OAUTH_MERGE_ACCOUNTS_BY_EMAIL:
  338. # Check if the user exists by email
  339. user = Users.get_user_by_email(email)
  340. if user:
  341. # Update the user with the new oauth sub
  342. Users.update_user_oauth_sub_by_id(user.id, provider_sub)
  343. if user:
  344. determined_role = self.get_user_role(user, user_data)
  345. if user.role != determined_role:
  346. Users.update_user_role_by_id(user.id, determined_role)
  347. if not user:
  348. user_count = Users.get_num_users()
  349. # If the user does not exist, check if signups are enabled
  350. if auth_manager_config.ENABLE_OAUTH_SIGNUP:
  351. # Check if an existing user with the same email already exists
  352. existing_user = Users.get_user_by_email(email)
  353. if existing_user:
  354. raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
  355. picture_claim = auth_manager_config.OAUTH_PICTURE_CLAIM
  356. if picture_claim:
  357. picture_url = user_data.get(
  358. picture_claim, OAUTH_PROVIDERS[provider].get("picture_url", "")
  359. )
  360. if picture_url:
  361. # Download the profile image into a base64 string
  362. try:
  363. access_token = token.get("access_token")
  364. get_kwargs = {}
  365. if access_token:
  366. get_kwargs["headers"] = {
  367. "Authorization": f"Bearer {access_token}",
  368. }
  369. async with aiohttp.ClientSession(trust_env=True) as session:
  370. async with session.get(
  371. picture_url, **get_kwargs
  372. ) as resp:
  373. if resp.ok:
  374. picture = await resp.read()
  375. base64_encoded_picture = base64.b64encode(
  376. picture
  377. ).decode("utf-8")
  378. guessed_mime_type = mimetypes.guess_type(
  379. picture_url
  380. )[0]
  381. if guessed_mime_type is None:
  382. # assume JPG, browsers are tolerant enough of image formats
  383. guessed_mime_type = "image/jpeg"
  384. picture_url = f"data:{guessed_mime_type};base64,{base64_encoded_picture}"
  385. else:
  386. picture_url = "/user.png"
  387. except Exception as e:
  388. log.error(
  389. f"Error downloading profile image '{picture_url}': {e}"
  390. )
  391. picture_url = "/user.png"
  392. if not picture_url:
  393. picture_url = "/user.png"
  394. else:
  395. picture_url = "/user.png"
  396. username_claim = auth_manager_config.OAUTH_USERNAME_CLAIM
  397. name = user_data.get(username_claim)
  398. if not name:
  399. log.warning("Username claim is missing, using email as name")
  400. name = email
  401. role = self.get_user_role(None, user_data)
  402. user = Auths.insert_new_auth(
  403. email=email,
  404. password=get_password_hash(
  405. str(uuid.uuid4())
  406. ), # Random password, not used
  407. name=name,
  408. profile_image_url=picture_url,
  409. role=role,
  410. oauth_sub=provider_sub,
  411. )
  412. if auth_manager_config.WEBHOOK_URL:
  413. post_webhook(
  414. WEBUI_NAME,
  415. auth_manager_config.WEBHOOK_URL,
  416. WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  417. {
  418. "action": "signup",
  419. "message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
  420. "user": user.model_dump_json(exclude_none=True),
  421. },
  422. )
  423. else:
  424. raise HTTPException(
  425. status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
  426. )
  427. jwt_token = create_token(
  428. data={"id": user.id},
  429. expires_delta=parse_duration(auth_manager_config.JWT_EXPIRES_IN),
  430. )
  431. if auth_manager_config.ENABLE_OAUTH_GROUP_MANAGEMENT and user.role != "admin":
  432. self.update_user_groups(
  433. user=user,
  434. user_data=user_data,
  435. default_permissions=request.app.state.config.USER_PERMISSIONS,
  436. )
  437. # Set the cookie token
  438. response.set_cookie(
  439. key="token",
  440. value=jwt_token,
  441. httponly=True, # Ensures the cookie is not accessible via JavaScript
  442. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  443. secure=WEBUI_AUTH_COOKIE_SECURE,
  444. )
  445. if ENABLE_OAUTH_SIGNUP.value:
  446. oauth_id_token = token.get("id_token")
  447. response.set_cookie(
  448. key="oauth_id_token",
  449. value=oauth_id_token,
  450. httponly=True,
  451. samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
  452. secure=WEBUI_AUTH_COOKIE_SECURE,
  453. )
  454. # Redirect back to the frontend with the JWT token
  455. redirect_url = f"{request.base_url}auth#token={jwt_token}"
  456. return RedirectResponse(url=redirect_url, headers=response.headers)