mirror of
https://github.com/inventree/InvenTree.git
synced 2026-12-03 04:41:52 +00:00
[bug] Fix URL for magic link email (#13415)
* [bug] Fix URL for magic link email Prevent magic links from being spoofed and redirected to a third-party website * fix for unit test
This commit is contained in:
1 parent
b9cc1d1b09
commit
855164e91f
4 files changed
+86
-6
No files matched your search
@@ -1,11 +1,15 @@
|
||||
"""Overrides for allauth and adjacent packages to enforce InvenTree specific auth settings and restirctions."""
|
||||
|
||||
import functools
|
||||
from types import SimpleNamespace
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from django import forms
|
||||
from django.apps import apps
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Group
|
||||
from django.contrib.sites.shortcuts import get_current_site
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import HttpResponseRedirect, JsonResponse
|
||||
from django.urls import URLPattern, URLResolver, reverse
|
||||
@@ -20,7 +24,7 @@ from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
|
||||
from common.settings import get_global_setting
|
||||
from InvenTree.exceptions import log_error
|
||||
|
||||
from .helpers import str2bool
|
||||
from .helpers import build_trusted_absolute_uri, str2bool
|
||||
from .helpers_email import is_email_configured
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
@@ -231,12 +235,30 @@ class RegistrationMixin:
|
||||
return user
|
||||
|
||||
|
||||
def get_trusted_site(request):
|
||||
"""Return the site object used to render outgoing authentication emails.
|
||||
|
||||
allauth uses django.contrib.sites.shortcuts.get_current_site, which falls back to
|
||||
the (client supplied) Host header if the sites framework is not installed.
|
||||
Use SITE_URL instead, if it is configured.
|
||||
"""
|
||||
if settings.SITE_URL and not apps.is_installed('django.contrib.sites'):
|
||||
domain = urlsplit(settings.SITE_URL).netloc
|
||||
return SimpleNamespace(domain=domain, name=domain)
|
||||
|
||||
return get_current_site(request)
|
||||
|
||||
|
||||
class CustomAccountAdapter(RegistrationMixin, DefaultAccountAdapter):
|
||||
"""Override of adapter to use dynamic settings."""
|
||||
|
||||
def send_mail(self, template_prefix, email, context):
|
||||
"""Only send mail if backend configured."""
|
||||
if settings.EMAIL_HOST:
|
||||
# allauth otherwise derives the site name in the email body from the
|
||||
# request Host header (when django.contrib.sites is not installed)
|
||||
context.setdefault('current_site', get_trusted_site(self.request))
|
||||
|
||||
try:
|
||||
result = super().send_mail(template_prefix, email, context)
|
||||
except Exception:
|
||||
@@ -323,6 +345,7 @@ class CustomHeadlessAdapter(DefaultHeadlessAdapter):
|
||||
f'URL name "{urlname}" not found in HEADLESS_FRONTEND_URLS'
|
||||
) # pragma: no cover
|
||||
|
||||
return self.request.build_absolute_uri(
|
||||
f'/{settings.FRONTEND_URL_BASE}/{HEADLESS_FRONTEND_URLS[urlname].format(**kwargs)}'
|
||||
return build_trusted_absolute_uri(
|
||||
self.request,
|
||||
f'/{settings.FRONTEND_URL_BASE}/{HEADLESS_FRONTEND_URLS[urlname].format(**kwargs)}',
|
||||
)
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Optional, TypeVar
|
||||
from urllib.parse import urlsplit
|
||||
from wsgiref.util import FileWrapper
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
@@ -397,6 +398,27 @@ def TestIfImageURL(url):
|
||||
]
|
||||
|
||||
|
||||
def build_trusted_absolute_uri(request, path: str) -> str:
|
||||
"""Build an absolute URL for a link that is sent out of band (e.g. by email).
|
||||
|
||||
The scheme and host are taken from settings.SITE_URL, never from the request,
|
||||
because the Host header is supplied by the client. Trusting it would let an
|
||||
anonymous user get password reset or login links pointing at their own server.
|
||||
|
||||
If SITE_URL is not configured, fall back to the request. In that case the
|
||||
server relies on ALLOWED_HOSTS to reject forged Host headers.
|
||||
|
||||
Arguments:
|
||||
request: The current request (used only if SITE_URL is not set)
|
||||
path: Absolute path (starting with '/') to append to the host
|
||||
"""
|
||||
if site_url := getattr(settings, 'SITE_URL', None):
|
||||
parts = urlsplit(site_url)
|
||||
return f'{parts.scheme}://{parts.netloc}{path}'
|
||||
|
||||
return request.build_absolute_uri(path)
|
||||
|
||||
|
||||
def str2bool(text, test=True) -> bool:
|
||||
"""Test if a string 'looks' like a boolean value.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from rest_framework.generics import GenericAPIView
|
||||
from rest_framework.response import Response
|
||||
|
||||
import InvenTree.version
|
||||
from InvenTree.helpers import build_trusted_absolute_uri
|
||||
from InvenTree.helpers_email import send_email
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
@@ -75,7 +76,6 @@ class GetSimpleLoginView(GenericAPIView):
|
||||
|
||||
def create_link(self, user):
|
||||
"""Create a login link for this user."""
|
||||
link = reverse('sesame-login')
|
||||
link = self.request.build_absolute_uri(link)
|
||||
link = build_trusted_absolute_uri(self.request, reverse('sesame-login'))
|
||||
link += sesame.utils.get_query_string(user)
|
||||
return link
|
||||
@@ -1853,7 +1853,7 @@ class MagicLoginTest(InvenTreeTestCase):
|
||||
self.assertEqual(mail.outbox[0].subject, '[InvenTree] Log in to the app')
|
||||
|
||||
# Check that the token is in the email
|
||||
self.assertIn('http://testserver/api/email/login/', mail.outbox[0].body)
|
||||
self.assertIn(f'{settings.SITE_URL}/api/email/login/', mail.outbox[0].body)
|
||||
token = mail.outbox[0].body.split('/')[-1].split('\n')[0][8:]
|
||||
self.assertEqual(get_user(token), self.user)
|
||||
|
||||
@@ -1879,6 +1879,41 @@ class MagicLoginTest(InvenTreeTestCase):
|
||||
self.assertEqual(resp.data, {'status': 'ok'})
|
||||
self.assertEqual(len(mail.outbox), 0)
|
||||
|
||||
def test_forged_host_header(self):
|
||||
"""Emailed login and password reset links must not use the request Host header.
|
||||
|
||||
With a permissive ALLOWED_HOSTS, an anonymous user could otherwise send a
|
||||
forged Host and have the token mailed inside a link to their own server.
|
||||
"""
|
||||
self.client.logout()
|
||||
site_url = 'https://inventree.example.com'
|
||||
requests = [
|
||||
(reverse('sesame-generate'), '/api/email/login/?sesame='),
|
||||
('/api/auth/v1/auth/password/request', '/web/set-password?key='),
|
||||
]
|
||||
|
||||
# CustomAccountAdapter only sends mail if EMAIL_HOST is configured
|
||||
with self.settings(
|
||||
ALLOWED_HOSTS=['*'],
|
||||
SITE_URL=site_url,
|
||||
EMAIL_HOST='localhost',
|
||||
TESTING_BYPASS_MAILCHECK=True,
|
||||
):
|
||||
for url, path in requests:
|
||||
mail.outbox.clear()
|
||||
resp = self.client.post(
|
||||
url,
|
||||
{'email': self.user.email},
|
||||
content_type='application/json',
|
||||
HTTP_HOST='attacker.example',
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
self.assertEqual(len(mail.outbox), 1)
|
||||
|
||||
body = mail.outbox[0].body
|
||||
self.assertIn(site_url + path, body)
|
||||
self.assertNotIn('attacker.example', body)
|
||||
|
||||
|
||||
class MaintenanceModeTest(InvenTreeTestCase):
|
||||
"""Unit tests for maintenance mode."""
|
||||
|
||||
Reference in new issue
Block a user