Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 42cbe33

Browse files
committed
Merge pull request #7058 from matrix-org/babolivier/saml_error_html
* commit '6640460d0': Rephrase default message Hopefully mypy is happy now Attempt at appeasing the gods of mypy Lint Changelog Update sample config SAML2: render a comprehensible error page if something goes wrong
2 parents 42e1eef + 6640460 commit 42cbe33

File tree

7 files changed

+81
-6
lines changed

7 files changed

+81
-6
lines changed

changelog.d/7058.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Render a configurable and comprehensible error page if something goes wrong during the SAML2 authentication process.

docs/sample_config.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1497,6 +1497,13 @@ saml2_config:
14971497
#
14981498
#grandfathered_mxid_source_attribute: upn
14991499

1500+
# Path to a file containing HTML content to serve in case an error happens
1501+
# when the user gets redirected from the SAML IdP back to Synapse.
1502+
# If no file is provided, this defaults to some minimalistic HTML telling the
1503+
# user that something went wrong and they should try authenticating again.
1504+
#
1505+
#error_html_path: /path/to/static/content/saml_error.html
1506+
15001507

15011508

15021509
# Enable CAS for registration and login.

synapse/config/saml2_config.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,18 @@
2727
"synapse.handlers.saml_handler.DefaultSamlMappingProvider"
2828
)
2929

30+
SAML2_ERROR_DEFAULT_HTML = """
31+
<html>
32+
<body>
33+
<p>Oops! Something went wrong</p>
34+
<p>
35+
Try logging in again from your Matrix client and if the problem persists
36+
please contact the server's administrator.
37+
</p>
38+
</body>
39+
</html>
40+
"""
41+
3042

3143
def _dict_merge(merge_dict, into_dict):
3244
"""Do a deep merge of two dicts
@@ -160,6 +172,13 @@ def read_config(self, config, **kwargs):
160172
saml2_config.get("saml_session_lifetime", "5m")
161173
)
162174

175+
if "error_html_path" in config:
176+
self.saml2_error_html_content = self.read_file(
177+
config["error_html_path"], "saml2_config.error_html_path",
178+
)
179+
else:
180+
self.saml2_error_html_content = SAML2_ERROR_DEFAULT_HTML
181+
163182
def _default_saml_config_dict(
164183
self, required_attributes: set, optional_attributes: set
165184
):
@@ -325,6 +344,13 @@ def generate_config_section(self, config_dir_path, server_name, **kwargs):
325344
# The default is 'uid'.
326345
#
327346
#grandfathered_mxid_source_attribute: upn
347+
348+
# Path to a file containing HTML content to serve in case an error happens
349+
# when the user gets redirected from the SAML IdP back to Synapse.
350+
# If no file is provided, this defaults to some minimalistic HTML telling the
351+
# user that something went wrong and they should try authenticating again.
352+
#
353+
#error_html_path: /path/to/static/content/saml_error.html
328354
""" % {
329355
"config_dir_path": config_dir_path
330356
}

synapse/handlers/saml_handler.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from synapse.api.errors import SynapseError
2525
from synapse.config import ConfigError
26+
from synapse.http.server import finish_request
2627
from synapse.http.servlet import parse_string
2728
from synapse.module_api import ModuleApi
2829
from synapse.types import (
@@ -73,6 +74,8 @@ def __init__(self, hs):
7374
# a lock on the mappings
7475
self._mapping_lock = Linearizer(name="saml_mapping", clock=self._clock)
7576

77+
self._error_html_content = hs.config.saml2_error_html_content
78+
7679
def handle_redirect_request(self, client_redirect_url):
7780
"""Handle an incoming request to /login/sso/redirect
7881
@@ -114,7 +117,22 @@ async def handle_saml_response(self, request):
114117
# the dict.
115118
self.expire_sessions()
116119

117-
user_id = await self._map_saml_response_to_user(resp_bytes, relay_state)
120+
try:
121+
user_id = await self._map_saml_response_to_user(resp_bytes, relay_state)
122+
except Exception as e:
123+
# If decoding the response or mapping it to a user failed, then log the
124+
# error and tell the user that something went wrong.
125+
logger.error(e)
126+
127+
request.setResponseCode(400)
128+
request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
129+
request.setHeader(
130+
b"Content-Length", b"%d" % (len(self._error_html_content),)
131+
)
132+
request.write(self._error_html_content.encode("utf8"))
133+
finish_request(request)
134+
return
135+
118136
self._auth_handler.complete_sso_login(user_id, request, relay_state)
119137

120138
async def _map_saml_response_to_user(self, resp_bytes, client_redirect_url):

synapse/logging/context.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,14 +210,15 @@ class LoggingContext(object):
210210
class Sentinel(object):
211211
"""Sentinel to represent the root context"""
212212

213-
__slots__ = ["previous_context", "alive", "request", "scope"]
213+
__slots__ = ["previous_context", "alive", "request", "scope", "tag"]
214214

215215
def __init__(self) -> None:
216216
# Minimal set for compatibility with LoggingContext
217217
self.previous_context = None
218218
self.alive = None
219219
self.request = None
220220
self.scope = None
221+
self.tag = None
221222

222223
def __str__(self):
223224
return "sentinel"
@@ -511,7 +512,7 @@ class PreserveLoggingContext(object):
511512

512513
__slots__ = ["current_context", "new_context", "has_parent"]
513514

514-
def __init__(self, new_context: Optional[LoggingContext] = None) -> None:
515+
def __init__(self, new_context: Optional[LoggingContextOrSentinel] = None) -> None:
515516
if new_context is None:
516517
self.new_context = LoggingContext.sentinel # type: LoggingContextOrSentinel
517518
else:

synapse/rest/saml2/response_resource.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
from synapse.http.server import DirectServeResource, wrap_html_request_handler
17+
from synapse.http.server import (
18+
DirectServeResource,
19+
finish_request,
20+
wrap_html_request_handler,
21+
)
1822

1923

2024
class SAML2ResponseResource(DirectServeResource):
@@ -24,8 +28,20 @@ class SAML2ResponseResource(DirectServeResource):
2428

2529
def __init__(self, hs):
2630
super().__init__()
31+
self._error_html_content = hs.config.saml2_error_html_content
2732
self._saml_handler = hs.get_saml_handler()
2833

34+
async def _async_render_GET(self, request):
35+
# We're not expecting any GET request on that resource if everything goes right,
36+
# but some IdPs sometimes end up responding with a 302 redirect on this endpoint.
37+
# In this case, just tell the user that something went wrong and they should
38+
# try to authenticate again.
39+
request.setResponseCode(400)
40+
request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
41+
request.setHeader(b"Content-Length", b"%d" % (len(self._error_html_content),))
42+
request.write(self._error_html_content.encode("utf8"))
43+
finish_request(request)
44+
2945
@wrap_html_request_handler
3046
async def _async_render_POST(self, request):
3147
return await self._saml_handler.handle_saml_response(request)

synapse/storage/database.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929

3030
from synapse.api.errors import StoreError
3131
from synapse.config.database import DatabaseConnectionConfig
32-
from synapse.logging.context import LoggingContext, make_deferred_yieldable
32+
from synapse.logging.context import (
33+
LoggingContext,
34+
LoggingContextOrSentinel,
35+
make_deferred_yieldable,
36+
)
3337
from synapse.metrics.background_process_metrics import run_as_background_process
3438
from synapse.storage.background_updates import BackgroundUpdater
3539
from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine, Sqlite3Engine
@@ -543,7 +547,9 @@ def runWithConnection(self, func: Callable, *args: Any, **kwargs: Any):
543547
Returns:
544548
Deferred: The result of func
545549
"""
546-
parent_context = LoggingContext.current_context()
550+
parent_context = (
551+
LoggingContext.current_context()
552+
) # type: Optional[LoggingContextOrSentinel]
547553
if parent_context == LoggingContext.sentinel:
548554
logger.warning(
549555
"Starting db connection from sentinel context: metrics will be lost"

0 commit comments

Comments
 (0)