oauth.py 19 KB

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