Skip to content

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

Python

Reach the SSO provider through a refresh page so form-action does not block sign-in (#496)

Murtaza Nasir0717ee7b8ab1
diff --git a/src/api/auth.py b/src/api/auth.py
index 3826d6a9..26bd0495 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -9,7 +9,8 @@ import hmac
import os
import re
import mimetypes
-from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, session, current_app
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, session, current_app, make_response
+from markupsafe import escape
from flask_login import login_user, logout_user, login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
@@ -341,7 +342,25 @@ def sso_login():
# "Remember me" on the sign-in page, as for a password sign-in (#437)
session['sso_remember'] = request.args.get('remember') == '1'
- return oauth.sso.authorize_redirect(redirect_uri=get_sso_config().get('redirect_uri'))
+ return _leave_for_provider(oauth.sso.authorize_redirect(redirect_uri=get_sso_config().get('redirect_uri')))
+
+
+def _leave_for_provider(provider_redirect):
+ """Send the browser on to the identity provider from a page, not with a 302.
+
+ The sign-in and link buttons are forms, and browsers apply the CSP
+ form-action directive to every redirect that follows a form submission,
+ so a 302 to the provider is blocked by form-action 'self' (#496).
+ """
+ location = escape(provider_redirect.headers['Location'])
+ label = escape(translate('authPages.signInWith', provider=get_sso_config().get('provider_name') or 'SSO'))
+ response = make_response(
+ '<!doctype html><html><head><meta charset="utf-8">'
+ f'<meta http-equiv="refresh" content="0;url={location}"></head>'
+ f'<body><a href="{location}">{label}</a></body></html>'
+ )
+ response.headers['Cache-Control'] = 'no-store'
+ return response
@auth_bp.route('/auth/sso/callback')
diff --git a/tests/test_cov_auth.py b/tests/test_cov_auth.py
index 226e2a70..16a5d764 100644
--- a/tests/test_cov_auth.py
+++ b/tests/test_cov_auth.py
@@ -22,6 +22,7 @@ import sys
import uuid
import contextlib
from unittest import mock
+from flask import redirect
import pytest
@@ -690,7 +691,7 @@ def test_sso_login_does_not_store_unsafe_next(cleanup_users):
# persisted to session['sso_next'] (it would be honoured after the
# IdP round-trip). Both an absolute and a scheme-relative target.
oauth = mock.MagicMock()
- oauth.sso.authorize_redirect.return_value = 'redirecting' # valid view return
+ oauth.sso.authorize_redirect.return_value = redirect("https://idp.example/authorize")
with _sso_on(), mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth):
for evil in ('http://evil.com', '//evil.com'):
client = app.test_client()
@@ -704,7 +705,7 @@ def test_sso_login_does_not_store_unsafe_next(cleanup_users):
def test_sso_login_stores_safe_next(cleanup_users):
# The safe-path companion: a local relative target IS stored.
oauth = mock.MagicMock()
- oauth.sso.authorize_redirect.return_value = 'redirecting'
+ oauth.sso.authorize_redirect.return_value = redirect("https://idp.example/authorize")
with _sso_on(), mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth):
client = app.test_client()
resp = client.get('/auth/sso/login', query_string={'next': '/recordings'})
@@ -832,7 +833,7 @@ def test_sso_login_uses_cached_client_without_reinit():
# short-circuit and init_sso_client must NOT be called. The `or`->`and`
# mutation would call init_sso_client (and use ITS return value instead).
oauth = mock.MagicMock()
- oauth.sso.authorize_redirect.return_value = 'redirecting'
+ oauth.sso.authorize_redirect.return_value = redirect("https://idp.example/authorize")
with _sso_enabled_with_config(), \
mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth), \
mock.patch.object(auth_mod, 'init_sso_client') as init_mock:
@@ -848,7 +849,7 @@ def test_sso_login_inits_client_when_none_cached():
# client is used. Under `or`->`and`, `None and init_sso_client(...)`
# short-circuits, init is never called, and the route bails to /login.
oauth = mock.MagicMock()
- oauth.sso.authorize_redirect.return_value = 'redirecting'
+ oauth.sso.authorize_redirect.return_value = redirect("https://idp.example/authorize")
with _sso_enabled_with_config(), \
mock.patch.object(auth_mod, 'get_sso_client', return_value=None), \
mock.patch.object(auth_mod, 'init_sso_client', return_value=oauth) as init_mock:
diff --git a/tests/test_sso_remember.py b/tests/test_sso_remember.py
index 4d16c591..887fddc2 100644
--- a/tests/test_sso_remember.py
+++ b/tests/test_sso_remember.py
@@ -35,7 +35,7 @@ def _sign_in(query):
patch("src.api.auth.create_or_update_sso_user",
side_effect=lambda info: db.session.get(User, uid)):
start = client.get("/auth/sso/login" + query)
- assert start.status_code == 302
+ assert start.status_code == 200
done = client.get("/auth/sso/callback")
assert done.status_code == 302
return done.headers.getlist("Set-Cookie")
@@ -62,3 +62,24 @@ def test_sign_in_page_offers_remember_me_with_sso():
with patch("src.api.auth.is_sso_enabled", return_value=True):
html = app.test_client().get("/login").get_data(as_text=True)
assert 'name="remember" value="1"' in html
+
+
+def test_sso_sign_in_leaves_for_the_provider_from_a_page():
+ """The provider is reached through a refresh page, because form-action 'self'
+ blocks a 302 to another origin after the sign-in form is submitted (#496)."""
+ client = app.test_client()
+ oauth = MagicMock()
+ oauth.sso.authorize_redirect.side_effect = lambda **kw: redirect(
+ "https://idp.example/authorize?client_id=c&state=s")
+ with patch("src.api.auth.is_sso_enabled", return_value=True), \
+ patch("src.api.auth.get_sso_client", return_value=oauth), \
+ patch("src.api.auth.get_sso_config",
+ return_value={"redirect_uri": "http://localhost/cb", "provider_name": "Test IdP"}):
+ response = client.get("/auth/sso/login")
+ body = response.get_data(as_text=True)
+ assert response.status_code == 200
+ assert "Location" not in response.headers
+ assert response.headers["Cache-Control"] == "no-store"
+ url = "https://idp.example/authorize?client_id=c&amp;state=s"
+ assert f'<meta http-equiv="refresh" content="0;url={url}">' in body
+ assert f'<a href="{url}">Sign in with Test IdP</a>' in body