Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

SSO: add opt-in SSO_REQUIRE_VERIFIED_EMAIL to block account-takeover via unverified email (default off)

Murtaza Nasir199373357ed3
diff --git a/config/env.sso.example b/config/env.sso.example
index 418c9d64..a44f2b60 100644
--- a/config/env.sso.example
+++ b/config/env.sso.example
@@ -26,6 +26,13 @@ SSO_AUTO_REGISTER=true
# Leave empty to allow all domains (e.g., example.com,company.org).
SSO_ALLOWED_DOMAINS=
+# Require a verified email before an SSO login may link to (or provision) a
+# local account by email address. Default false for backwards compatibility.
+# Enable it when your IdP reliably sends the email_verified claim, to prevent a
+# malicious or misconfigured IdP from taking over an account by asserting its
+# email. Users already linked by SSO subject are unaffected.
+SSO_REQUIRE_VERIFIED_EMAIL=false
+
# Claims used to map user profile fields
SSO_DEFAULT_USERNAME_CLAIM=preferred_username
SSO_DEFAULT_NAME_CLAIM=name
diff --git a/docs/admin-guide/sso-setup.md b/docs/admin-guide/sso-setup.md
index d213fe49..91d0c1b2 100644
--- a/docs/admin-guide/sso-setup.md
+++ b/docs/admin-guide/sso-setup.md
@@ -102,7 +102,9 @@ This is useful for organizations that want to enforce SSO for all users while ke
When a user logs in via SSO with an email that matches an existing Speakr account, the accounts are automatically linked. This is convenient for most setups but relies on trusting your IdP to provide accurate email information.
-For self-hosted deployments where you control both Speakr and the IdP, this is generally not a concern. If you're using an IdP where users can set unverified email addresses, be aware that this could allow account linking without email ownership verification. Consider using `SSO_ALLOWED_DOMAINS` to restrict which email domains can authenticate.
+For self-hosted deployments where you control both Speakr and the IdP, this is generally not a concern. If you're using an IdP where users can set unverified email addresses, be aware that this could allow account linking without email ownership verification.
+
+To close this off, set `SSO_REQUIRE_VERIFIED_EMAIL=true`. When enabled, an SSO login whose `email_verified` claim is not true is refused before the email is used to link to (or provision) a local account, so a malicious or misconfigured IdP cannot take over an account by asserting its address. It accepts the claim as either a boolean or the string `"true"`. Users already linked by SSO subject are unaffected and keep signing in even if the IdP omits the claim. It defaults to `false` for backwards compatibility — only enable it once you've confirmed your IdP reliably sends `email_verified`, since IdPs that omit it will otherwise have all email-bearing logins rejected. You can also use `SSO_ALLOWED_DOMAINS` to restrict which email domains can authenticate.
## Linking existing users
diff --git a/src/auth/sso.py b/src/auth/sso.py
index 36e56015..7cac5eb2 100644
--- a/src/auth/sso.py
+++ b/src/auth/sso.py
@@ -16,6 +16,19 @@ def _str_to_bool(value: str) -> bool:
return str(value or "").lower() == "true"
+def _claim_is_truthy(value) -> bool:
+ """Whether an OIDC claim should be treated as true.
+
+ The spec says ``email_verified`` is a boolean, but some providers send it
+ as a string ("true"/"false"). Accept both.
+ """
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ return value.strip().lower() in ("true", "1", "yes")
+ return bool(value)
+
+
def get_sso_config() -> Dict[str, Optional[str]]:
"""Load SSO configuration from environment variables."""
return {
@@ -30,6 +43,12 @@ def get_sso_config() -> Dict[str, Optional[str]]:
"username_claim": os.environ.get("SSO_DEFAULT_USERNAME_CLAIM", "preferred_username"),
"name_claim": os.environ.get("SSO_DEFAULT_NAME_CLAIM", "name"),
"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")),
}
@@ -127,13 +146,22 @@ def create_or_update_sso_user(userinfo: Dict[str, str]) -> User:
if email and not is_domain_allowed(email):
raise PermissionError("Email domain is not allowed for SSO sign-up")
- # Existing by subject
+ # Existing by subject — already linked, so no email trust is involved.
+ # This path is unaffected by require_verified_email (an already-linked user
+ # keeps logging in even if the IdP omits email_verified).
user = User.query.filter_by(sso_subject=subject).first()
if user:
_update_profile_fields(user, userinfo, name_claim)
db.session.commit()
return user
+ # From here the email claim is used to LINK to an existing local account or
+ # to PROVISION a new one. When require_verified_email is on, refuse an
+ # unverified email so a malicious/misconfigured IdP can't take over an
+ # account (or provision under someone else's address) by asserting it.
+ if email and cfg["require_verified_email"] and not _claim_is_truthy(userinfo.get("email_verified")):
+ raise PermissionError("SSO email address is not verified")
+
# Existing by email: attach SSO
if email:
existing_email_user = User.query.filter_by(email=email).first()
diff --git a/tests/test_sso.py b/tests/test_sso.py
index 94cb9c5d..8fd2a0f2 100644
--- a/tests/test_sso.py
+++ b/tests/test_sso.py
@@ -42,6 +42,7 @@ _SSO_ENV_KEYS = [
"SSO_DISCOVERY_URL", "SSO_REDIRECT_URI", "SSO_AUTO_REGISTER",
"SSO_ALLOWED_DOMAINS", "SSO_DEFAULT_USERNAME_CLAIM",
"SSO_DEFAULT_NAME_CLAIM", "SSO_DISABLE_PASSWORD_LOGIN",
+ "SSO_REQUIRE_VERIFIED_EMAIL",
]
@@ -420,5 +421,96 @@ def test_no_email_uses_placeholder(cleanup_users):
assert user.email == f"{sub}@placeholder.local"
+# ---------------------------------------------------------------------------
+# SSO_REQUIRE_VERIFIED_EMAIL (opt-in; default off = backwards compatible)
+# ---------------------------------------------------------------------------
+
[email protected]("value,expected", [
+ (True, True), (False, False),
+ ("true", True), ("True", True), ("1", True), ("yes", True),
+ ("false", False), ("no", False), ("", False), (None, False), (0, False),
+])
+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."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL=None):
+ existing = _mk_user(cleanup_users, email="[email protected]")
+ assert existing.sso_subject is None
+ sub = "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
+
+
+def test_require_verified_email_on_rejects_unverified_link(cleanup_users):
+ """Flag on: linking to an existing account by an UNVERIFIED email is refused
+ (the account-takeover vector), and the existing account is left untouched."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL="true"):
+ existing = _mk_user(cleanup_users, email="[email protected]")
+ sub = "sub-" + uuid.uuid4().hex[:10]
+ for claims in (
+ {"sub": sub, "email": "[email protected]"}, # absent
+ {"sub": sub, "email": "[email protected]", "email_verified": False},
+ {"sub": sub, "email": "[email protected]", "email_verified": "false"},
+ ):
+ with pytest.raises(PermissionError):
+ sso.create_or_update_sso_user(claims)
+ db.session.expire_all()
+ # The existing account was NOT hijacked.
+ refreshed = User.query.get(existing.id)
+ assert refreshed.sso_subject is None
+
+
+def test_require_verified_email_on_allows_verified_link(cleanup_users):
+ """Flag on + email_verified true (bool or string): linking proceeds."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL="true"):
+ existing = _mk_user(cleanup_users, email="[email protected]")
+ sub = "sub-" + uuid.uuid4().hex[:10]
+ user = sso.create_or_update_sso_user(
+ {"sub": sub, "email": "[email protected]", "email_verified": True}
+ )
+ _track(cleanup_users, user)
+ assert user.id == existing.id
+ assert user.sso_subject == sub
+
+
+def test_require_verified_email_on_rejects_new_user_with_unverified_email(cleanup_users):
+ """Flag on: provisioning a NEW account with an unverified email is refused
+ too (no account is created)."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL="true"):
+ sub = "sub-" + uuid.uuid4().hex[:10]
+ email = uuid.uuid4().hex[:10] + "@example.com"
+ with pytest.raises(PermissionError):
+ sso.create_or_update_sso_user({"sub": sub, "email": email, "email_verified": False})
+ assert User.query.filter_by(sso_subject=sub).first() is None
+
+
+def test_require_verified_email_on_does_not_affect_already_linked_subject(cleanup_users):
+ """Flag on: a user already linked by subject keeps logging in even if the
+ IdP omits email_verified (no email trust is involved on that path)."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL="true"):
+ sub = "sub-" + uuid.uuid4().hex[:10]
+ linked = _mk_user(cleanup_users, email="[email protected]", sso_subject=sub)
+ user = sso.create_or_update_sso_user({"sub": sub, "email": "[email protected]"})
+ _track(cleanup_users, user)
+ assert user.id == linked.id
+
+
+def test_require_verified_email_on_allows_no_email_claim(cleanup_users):
+ """Flag on: a login with no email claim is unaffected (nothing to verify);
+ a placeholder email is assigned as before."""
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_REQUIRE_VERIFIED_EMAIL="true"):
+ sub = "sub-" + uuid.uuid4().hex[:10]
+ user = sso.create_or_update_sso_user({"sub": sub, "preferred_username": "noemail" + sub[:6]})
+ _track(cleanup_users, user)
+ assert user.email == f"{sub}@placeholder.local"
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))