Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Reset and verification links built from APP_BASE_URL (#436)
Murtaza Nasir58057351109d
diff --git a/config/env.email.example b/config/env.email.exampleindex 625d0c99..9ce86910 100644--- a/config/env.email.example+++ b/config/env.email.example@@ -56,11 +56,11 @@ SMTP_FROM_NAME=Speakr################################################################################ External URL where users reach this Speakr instance, with no trailing path.-# Verification and password-reset mail is sent while handling a request, so it-# can work out its own address. Notification mail is sent from a background-# worker with no request to look at, so it cannot. Set this and a "finished-# transcribing" email carries a link straight to the recording; leave it unset-# and the same email is still sent, just without the link.+# Recommended whenever SMTP is configured. Links in verification and+# password-reset mail are built from it; without it, the host is taken from the+# request, which a person asking for a reset link can forge. Notification mail+# is sent from a background worker with no request to look at, so without this+# variable a "finished transcribing" email is sent without a link.# Example: https://speakr.example.com# APP_BASE_URL=diff --git a/docs/admin-guide/email-setup.md b/docs/admin-guide/email-setup.mdindex 8b42821c..24ac64fd 100644--- a/docs/admin-guide/email-setup.md+++ b/docs/admin-guide/email-setup.md@@ -54,7 +54,7 @@ Restart Speakr after updating environment variables.| `SMTP_USE_SSL` | `false` | Use SSL encryption (port 465) || `SMTP_FROM_ADDRESS` | `[email protected]` | Email address shown in "From" field || `SMTP_FROM_NAME` | `Speakr` | Display name shown alongside from address |-| `APP_BASE_URL` | (none) | External URL of this instance, used for links in notification email |+| `APP_BASE_URL` | (none) | External URL of this instance, used for all links in email; recommended whenever SMTP is configured |### Processing Notifications@@ -78,10 +78,13 @@ path:APP_BASE_URL=https://speakr.example.com```-Verification and reset mail work out their own URL because they are sent while-handling a request. A notification is sent from a background worker, which has-no request to look at, so without this variable the mail goes out without a link-to the recording rather than with a broken one.+Links in verification and password-reset mail are built from this address.+Without it, the host is taken from the request, and a request for a reset link+can carry a forged `Host` or `X-Forwarded-Host` header that points the emailed+link at another site. A warning is logged when such a link is sent without+`APP_BASE_URL`. Notification mail is sent from a background worker, which has no+request to look at, so without this variable a notification is sent without a+link to the recording.Note that each recording sends its own message, so a bulk upload of fifty filesproduces fifty emails. The setting is most useful for long recordings the userdiff --git a/src/services/email.py b/src/services/email.pyindex 166794a5..617e2dae 100644--- a/src/services/email.py+++ b/src/services/email.py@@ -338,7 +338,7 @@ def send_verification_email(user) -> bool:db.session.commit()# Build verification URL- verify_url = url_for('auth.verify_email', token=token, _external=True)+ verify_url = _account_link('auth.verify_email', token=token)subject = "Verify your email address - Speakr"@@ -402,7 +402,7 @@ def send_password_reset_email(user) -> bool:db.session.commit()# Build reset URL- reset_url = url_for('auth.reset_password', token=token, _external=True)+ reset_url = _account_link('auth.reset_password', token=token)subject = "Reset your password - Speakr"@@ -531,6 +531,29 @@ def get_app_base_url() -> Optional[str]:return base.rstrip('/') or None+_warned_host_links = False+++def _account_link(endpoint: str, **values) -> str:+ """Absolute link for verification and password-reset mail (#436).++ Built from APP_BASE_URL when it is set. Otherwise the host comes from the+ request, including X-Forwarded-Host, which the person asking for a reset+ link can choose; a warning is logged once so that the variable gets set.+ """+ global _warned_host_links+ base = get_app_base_url()+ if base:+ return base + url_for(endpoint, **values)+ if not _warned_host_links:+ _warned_host_links = True+ logger.warning(+ "APP_BASE_URL is not set, so links in verification and password-reset "+ "email are built from the request's host header. Set APP_BASE_URL to "+ "the address users reach Speakr on.")+ return url_for(endpoint, _external=True, **values)++def _recording_url(recording_id: int) -> Optional[str]:base = get_app_base_url()return f'{base}/recordings/{recording_id}' if base else Nonediff --git a/tests/test_email_link_host.py b/tests/test_email_link_host.pynew file mode 100644index 00000000..05ff4123--- /dev/null+++ b/tests/test_email_link_host.py@@ -0,0 +1,69 @@+"""Links in password-reset and verification mail (#436).++The host of the link came from the request, including X-Forwarded-Host, so a+person asking for somebody else's reset link could point it at their own site+and receive the token when the link was opened. With APP_BASE_URL set, the+links are built from that address whatever the request carries.+"""++import os+from unittest.mock import patch++import pytest++from src.app import app+from src.database import db+from src.models import User+from src.services import email as email_service++FORGED = {'Host': 'attacker.example', 'X-Forwarded-Host': 'attacker.example'}+++def user():+ with app.app_context():+ u = User(username=f'linkhost_{os.getpid()}', email=f'linkhost_{os.getpid()}@example.com', password='x')+ db.session.add(u)+ db.session.commit()+ uid = u.id+ yield uid+ with app.app_context():+ u = db.session.get(User, uid)+ if u:+ db.session.delete(u)+ db.session.commit()+++def _send(sender, uid, base):+ sent = {}++ def capture(to, subject, html_body, text_body=None):+ sent['html'], sent['text'] = html_body, text_body+ return True++ env = {'APP_BASE_URL': base} if base else {}+ with patch.dict(os.environ, env), \+ patch.object(email_service, 'is_smtp_configured', return_value=True), \+ patch.object(email_service, 'is_email_verification_enabled', return_value=True), \+ patch.object(email_service, '_send_email', side_effect=capture), \+ app.test_request_context('/forgot-password', headers=FORGED):+ if not base:+ os.environ.pop('APP_BASE_URL', None)+ assert sender(db.session.get(User, uid))+ return sent++[email protected]('sender', [email_service.send_password_reset_email,+ email_service.send_verification_email])+def test_links_use_app_base_url_not_request_host(user, sender):+ sent = _send(sender, user, 'https://speakr.example.com/')+ for body in (sent['html'], sent['text']):+ assert 'https://speakr.example.com/' in body+ assert 'attacker.example' not in body+++def test_without_app_base_url_a_warning_is_logged(user, caplog):+ email_service._warned_host_links = False+ sent = _send(email_service.send_password_reset_email, user, None)+ assert '/reset-password/' in sent['text']+ assert 'APP_BASE_URL is not set' in caplog.text