summary refs log tree commit diff
diff options
context:
space:
mode:
authorBrendan Abolivier <babolivier@matrix.org>2020-03-10 18:42:15 +0000
committerGitHub <noreply@github.com>2020-03-10 18:42:15 +0000
commit6640460d054e8f4444046a34bdf638921b31c01e (patch)
tree065818deeadd4d46e0f14ba1023fd68b5aaf7dba
parentMerge pull request #7055 from matrix-org/babolivier/get_time_of_last_push_act... (diff)
parentRephrase default message (diff)
downloadsynapse-6640460d054e8f4444046a34bdf638921b31c01e.tar.xz
Merge pull request #7058 from matrix-org/babolivier/saml_error_html
SAML2: render a comprehensible error page if something goes wrong
-rw-r--r--changelog.d/7058.feature1
-rw-r--r--docs/sample_config.yaml7
-rw-r--r--synapse/config/saml2_config.py26
-rw-r--r--synapse/handlers/saml_handler.py20
-rw-r--r--synapse/logging/context.py5
-rw-r--r--synapse/rest/saml2/response_resource.py18
-rw-r--r--synapse/storage/database.py10
7 files changed, 81 insertions, 6 deletions
diff --git a/changelog.d/7058.feature b/changelog.d/7058.feature
new file mode 100644
index 0000000000..53ea485e03
--- /dev/null
+++ b/changelog.d/7058.feature
@@ -0,0 +1 @@
+Render a configurable and comprehensible error page if something goes wrong during the SAML2 authentication process.
diff --git a/docs/sample_config.yaml b/docs/sample_config.yaml
index 6f6f6fd54b..01957a90dd 100644
--- a/docs/sample_config.yaml
+++ b/docs/sample_config.yaml
@@ -1347,6 +1347,13 @@ saml2_config:
   #
   #grandfathered_mxid_source_attribute: upn
 
+  # Path to a file containing HTML content to serve in case an error happens
+  # when the user gets redirected from the SAML IdP back to Synapse.
+  # If no file is provided, this defaults to some minimalistic HTML telling the
+  # user that something went wrong and they should try authenticating again.
+  #
+  #error_html_path: /path/to/static/content/saml_error.html
+
 
 
 # Enable CAS for registration and login.
diff --git a/synapse/config/saml2_config.py b/synapse/config/saml2_config.py
index 423c158b11..07895c4315 100644
--- a/synapse/config/saml2_config.py
+++ b/synapse/config/saml2_config.py
@@ -27,6 +27,18 @@ DEFAULT_USER_MAPPING_PROVIDER = (
     "synapse.handlers.saml_handler.DefaultSamlMappingProvider"
 )
 
+SAML2_ERROR_DEFAULT_HTML = """
+<html>
+    <body>
+        <p>Oops! Something went wrong</p>
+        <p>
+            Try logging in again from your Matrix client and if the problem persists
+            please contact the server's administrator.
+        </p>
+    </body>
+</html>
+"""
+
 
 def _dict_merge(merge_dict, into_dict):
     """Do a deep merge of two dicts
@@ -160,6 +172,13 @@ class SAML2Config(Config):
             saml2_config.get("saml_session_lifetime", "5m")
         )
 
+        if "error_html_path" in config:
+            self.saml2_error_html_content = self.read_file(
+                config["error_html_path"], "saml2_config.error_html_path",
+            )
+        else:
+            self.saml2_error_html_content = SAML2_ERROR_DEFAULT_HTML
+
     def _default_saml_config_dict(
         self, required_attributes: set, optional_attributes: set
     ):
@@ -325,6 +344,13 @@ class SAML2Config(Config):
           # The default is 'uid'.
           #
           #grandfathered_mxid_source_attribute: upn
+
+          # Path to a file containing HTML content to serve in case an error happens
+          # when the user gets redirected from the SAML IdP back to Synapse.
+          # If no file is provided, this defaults to some minimalistic HTML telling the
+          # user that something went wrong and they should try authenticating again.
+          #
+          #error_html_path: /path/to/static/content/saml_error.html
         """ % {
             "config_dir_path": config_dir_path
         }
diff --git a/synapse/handlers/saml_handler.py b/synapse/handlers/saml_handler.py
index 9406753393..72c109981b 100644
--- a/synapse/handlers/saml_handler.py
+++ b/synapse/handlers/saml_handler.py
@@ -23,6 +23,7 @@ from saml2.client import Saml2Client
 
 from synapse.api.errors import SynapseError
 from synapse.config import ConfigError
+from synapse.http.server import finish_request
 from synapse.http.servlet import parse_string
 from synapse.module_api import ModuleApi
 from synapse.types import (
@@ -73,6 +74,8 @@ class SamlHandler:
         # a lock on the mappings
         self._mapping_lock = Linearizer(name="saml_mapping", clock=self._clock)
 
+        self._error_html_content = hs.config.saml2_error_html_content
+
     def handle_redirect_request(self, client_redirect_url):
         """Handle an incoming request to /login/sso/redirect
 
@@ -114,7 +117,22 @@ class SamlHandler:
         # the dict.
         self.expire_sessions()
 
-        user_id = await self._map_saml_response_to_user(resp_bytes, relay_state)
+        try:
+            user_id = await self._map_saml_response_to_user(resp_bytes, relay_state)
+        except Exception as e:
+            # If decoding the response or mapping it to a user failed, then log the
+            # error and tell the user that something went wrong.
+            logger.error(e)
+
+            request.setResponseCode(400)
+            request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
+            request.setHeader(
+                b"Content-Length", b"%d" % (len(self._error_html_content),)
+            )
+            request.write(self._error_html_content.encode("utf8"))
+            finish_request(request)
+            return
+
         self._auth_handler.complete_sso_login(user_id, request, relay_state)
 
     async def _map_saml_response_to_user(self, resp_bytes, client_redirect_url):
diff --git a/synapse/logging/context.py b/synapse/logging/context.py
index 1eccc0e83f..860b99a4c6 100644
--- a/synapse/logging/context.py
+++ b/synapse/logging/context.py
@@ -210,7 +210,7 @@ class LoggingContext(object):
     class Sentinel(object):
         """Sentinel to represent the root context"""
 
-        __slots__ = ["previous_context", "alive", "request", "scope"]
+        __slots__ = ["previous_context", "alive", "request", "scope", "tag"]
 
         def __init__(self) -> None:
             # Minimal set for compatibility with LoggingContext
@@ -218,6 +218,7 @@ class LoggingContext(object):
             self.alive = None
             self.request = None
             self.scope = None
+            self.tag = None
 
         def __str__(self):
             return "sentinel"
@@ -511,7 +512,7 @@ class PreserveLoggingContext(object):
 
     __slots__ = ["current_context", "new_context", "has_parent"]
 
-    def __init__(self, new_context: Optional[LoggingContext] = None) -> None:
+    def __init__(self, new_context: Optional[LoggingContextOrSentinel] = None) -> None:
         if new_context is None:
             self.new_context = LoggingContext.sentinel  # type: LoggingContextOrSentinel
         else:
diff --git a/synapse/rest/saml2/response_resource.py b/synapse/rest/saml2/response_resource.py
index 69ecc5e4b4..a545c13db7 100644
--- a/synapse/rest/saml2/response_resource.py
+++ b/synapse/rest/saml2/response_resource.py
@@ -14,7 +14,11 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-from synapse.http.server import DirectServeResource, wrap_html_request_handler
+from synapse.http.server import (
+    DirectServeResource,
+    finish_request,
+    wrap_html_request_handler,
+)
 
 
 class SAML2ResponseResource(DirectServeResource):
@@ -24,8 +28,20 @@ class SAML2ResponseResource(DirectServeResource):
 
     def __init__(self, hs):
         super().__init__()
+        self._error_html_content = hs.config.saml2_error_html_content
         self._saml_handler = hs.get_saml_handler()
 
+    async def _async_render_GET(self, request):
+        # We're not expecting any GET request on that resource if everything goes right,
+        # but some IdPs sometimes end up responding with a 302 redirect on this endpoint.
+        # In this case, just tell the user that something went wrong and they should
+        # try to authenticate again.
+        request.setResponseCode(400)
+        request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
+        request.setHeader(b"Content-Length", b"%d" % (len(self._error_html_content),))
+        request.write(self._error_html_content.encode("utf8"))
+        finish_request(request)
+
     @wrap_html_request_handler
     async def _async_render_POST(self, request):
         return await self._saml_handler.handle_saml_response(request)
diff --git a/synapse/storage/database.py b/synapse/storage/database.py
index 609db40616..e61595336c 100644
--- a/synapse/storage/database.py
+++ b/synapse/storage/database.py
@@ -29,7 +29,11 @@ from twisted.internet import defer
 
 from synapse.api.errors import StoreError
 from synapse.config.database import DatabaseConnectionConfig
-from synapse.logging.context import LoggingContext, make_deferred_yieldable
+from synapse.logging.context import (
+    LoggingContext,
+    LoggingContextOrSentinel,
+    make_deferred_yieldable,
+)
 from synapse.metrics.background_process_metrics import run_as_background_process
 from synapse.storage.background_updates import BackgroundUpdater
 from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine, Sqlite3Engine
@@ -543,7 +547,9 @@ class Database(object):
         Returns:
             Deferred: The result of func
         """
-        parent_context = LoggingContext.current_context()
+        parent_context = (
+            LoggingContext.current_context()
+        )  # type: Optional[LoggingContextOrSentinel]
         if parent_context == LoggingContext.sentinel:
             logger.warning(
                 "Starting db connection from sentinel context: metrics will be lost"