oauth.py 24 KB

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