2020-11-17 09:46:23 -05:00
|
|
|
# Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2021-01-04 13:13:49 -05:00
|
|
|
import abc
|
2020-11-17 09:46:23 -05:00
|
|
|
import logging
|
2021-02-01 12:30:42 -05:00
|
|
|
from typing import (
|
|
|
|
TYPE_CHECKING,
|
2021-02-11 10:05:15 -05:00
|
|
|
Any,
|
2021-02-01 12:30:42 -05:00
|
|
|
Awaitable,
|
|
|
|
Callable,
|
2021-04-22 11:43:50 -04:00
|
|
|
Collection,
|
2021-02-01 12:30:42 -05:00
|
|
|
Dict,
|
|
|
|
Iterable,
|
2021-02-11 10:05:15 -05:00
|
|
|
List,
|
2021-02-01 12:30:42 -05:00
|
|
|
Mapping,
|
|
|
|
Optional,
|
|
|
|
Set,
|
|
|
|
)
|
2021-01-05 06:25:28 -05:00
|
|
|
from urllib.parse import urlencode
|
2020-11-25 10:04:22 -05:00
|
|
|
|
|
|
|
import attr
|
2021-01-04 13:13:49 -05:00
|
|
|
from typing_extensions import NoReturn, Protocol
|
2020-11-17 09:46:23 -05:00
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
from twisted.web.iweb import IRequest
|
2021-03-01 12:23:46 -05:00
|
|
|
from twisted.web.server import Request
|
2020-12-08 09:03:38 -05:00
|
|
|
|
2021-01-13 06:12:28 -05:00
|
|
|
from synapse.api.constants import LoginType
|
2021-01-27 07:41:24 -05:00
|
|
|
from synapse.api.errors import Codes, NotFoundError, RedirectException, SynapseError
|
2021-02-11 10:05:15 -05:00
|
|
|
from synapse.config.sso import SsoAttributeRequirement
|
2021-08-24 05:17:51 -04:00
|
|
|
from synapse.handlers.register import init_counters_for_auth_provider
|
2021-01-12 13:19:42 -05:00
|
|
|
from synapse.handlers.ui_auth import UIAuthSessionDataConstants
|
2021-01-12 07:34:16 -05:00
|
|
|
from synapse.http import get_request_user_agent
|
2021-02-01 08:15:51 -05:00
|
|
|
from synapse.http.server import respond_with_html, respond_with_redirect
|
2020-12-16 15:01:53 -05:00
|
|
|
from synapse.http.site import SynapseRequest
|
2021-06-21 18:48:57 -04:00
|
|
|
from synapse.types import (
|
|
|
|
JsonDict,
|
|
|
|
UserID,
|
|
|
|
contains_invalid_mxid_characters,
|
|
|
|
create_requester,
|
|
|
|
)
|
2020-12-10 07:43:58 -05:00
|
|
|
from synapse.util.async_helpers import Linearizer
|
2020-12-18 09:19:46 -05:00
|
|
|
from synapse.util.stringutils import random_string
|
2020-11-17 09:46:23 -05:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class MappingException(Exception):
|
2020-12-04 08:25:15 -05:00
|
|
|
"""Used to catch errors when mapping an SSO response to user attributes.
|
|
|
|
|
|
|
|
Note that the msg that is raised is shown to end-users.
|
2020-11-17 09:46:23 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2021-01-04 13:13:49 -05:00
|
|
|
class SsoIdentityProvider(Protocol):
|
|
|
|
"""Abstract base class to be implemented by SSO Identity Providers
|
|
|
|
|
|
|
|
An Identity Provider, or IdP, is an external HTTP service which authenticates a user
|
|
|
|
to say whether they should be allowed to log in, or perform a given action.
|
|
|
|
|
|
|
|
Synapse supports various implementations of IdPs, including OpenID Connect, SAML,
|
|
|
|
and CAS.
|
|
|
|
|
|
|
|
The main entry point is `handle_redirect_request`, which should return a URI to
|
|
|
|
redirect the user's browser to the IdP's authentication page.
|
|
|
|
|
|
|
|
Each IdP should be registered with the SsoHandler via
|
|
|
|
`hs.get_sso_handler().register_identity_provider()`, so that requests to
|
|
|
|
`/_matrix/client/r0/login/sso/redirect` can be correctly dispatched.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@property
|
|
|
|
@abc.abstractmethod
|
|
|
|
def idp_id(self) -> str:
|
|
|
|
"""A unique identifier for this SSO provider
|
|
|
|
|
|
|
|
Eg, "saml", "cas", "github"
|
|
|
|
"""
|
|
|
|
|
2021-01-05 06:25:28 -05:00
|
|
|
@property
|
|
|
|
@abc.abstractmethod
|
|
|
|
def idp_name(self) -> str:
|
|
|
|
"""User-facing name for this provider"""
|
|
|
|
|
2021-01-20 08:15:14 -05:00
|
|
|
@property
|
|
|
|
def idp_icon(self) -> Optional[str]:
|
|
|
|
"""Optional MXC URI for user-facing icon"""
|
|
|
|
return None
|
|
|
|
|
2021-01-27 16:31:45 -05:00
|
|
|
@property
|
|
|
|
def idp_brand(self) -> Optional[str]:
|
|
|
|
"""Optional branding identifier"""
|
|
|
|
return None
|
|
|
|
|
2021-01-04 13:13:49 -05:00
|
|
|
@abc.abstractmethod
|
|
|
|
async def handle_redirect_request(
|
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
client_redirect_url: Optional[bytes],
|
|
|
|
ui_auth_session_id: Optional[str] = None,
|
|
|
|
) -> str:
|
|
|
|
"""Handle an incoming request to /login/sso/redirect
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: the incoming HTTP request
|
|
|
|
client_redirect_url: the URL that we should redirect the
|
|
|
|
client to after login (or None for UI Auth).
|
|
|
|
ui_auth_session_id: The session ID of the ongoing UI Auth (or
|
|
|
|
None if this is a login).
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
URL to redirect to
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
2022-01-13 08:49:28 -05:00
|
|
|
@attr.s(auto_attribs=True)
|
2020-11-25 10:04:22 -05:00
|
|
|
class UserAttributes:
|
2020-12-18 09:19:46 -05:00
|
|
|
# the localpart of the mxid that the mapper has assigned to the user.
|
|
|
|
# if `None`, the mapper has not picked a userid, and the user should be prompted to
|
|
|
|
# enter one.
|
2022-01-13 08:49:28 -05:00
|
|
|
localpart: Optional[str]
|
2022-03-11 08:20:00 -05:00
|
|
|
confirm_localpart: bool = False
|
2022-01-13 08:49:28 -05:00
|
|
|
display_name: Optional[str] = None
|
|
|
|
emails: Collection[str] = attr.Factory(list)
|
2020-11-25 10:04:22 -05:00
|
|
|
|
|
|
|
|
2022-01-13 08:49:28 -05:00
|
|
|
@attr.s(slots=True, auto_attribs=True)
|
2020-12-18 09:19:46 -05:00
|
|
|
class UsernameMappingSession:
|
|
|
|
"""Data we track about SSO sessions"""
|
|
|
|
|
|
|
|
# A unique identifier for this SSO provider, e.g. "oidc" or "saml".
|
2022-01-13 08:49:28 -05:00
|
|
|
auth_provider_id: str
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# user ID on the IdP server
|
2022-01-13 08:49:28 -05:00
|
|
|
remote_user_id: str
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# attributes returned by the ID mapper
|
2022-01-13 08:49:28 -05:00
|
|
|
display_name: Optional[str]
|
|
|
|
emails: Collection[str]
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# An optional dictionary of extra attributes to be provided to the client in the
|
|
|
|
# login response.
|
2022-01-13 08:49:28 -05:00
|
|
|
extra_login_attributes: Optional[JsonDict]
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# where to redirect the client back to
|
2022-01-13 08:49:28 -05:00
|
|
|
client_redirect_url: str
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# expiry time for the session, in milliseconds
|
2022-01-13 08:49:28 -05:00
|
|
|
expiry_time_ms: int
|
2020-12-18 09:19:46 -05:00
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
# choices made by the user
|
2022-01-13 08:49:28 -05:00
|
|
|
chosen_localpart: Optional[str] = None
|
|
|
|
use_display_name: bool = True
|
|
|
|
emails_to_use: Collection[str] = ()
|
|
|
|
terms_accepted_version: Optional[str] = None
|
2021-02-01 08:15:51 -05:00
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# the HTTP cookie used to track the mapping session id
|
|
|
|
USERNAME_MAPPING_SESSION_COOKIE_NAME = b"username_mapping_session"
|
|
|
|
|
|
|
|
|
2020-12-08 09:03:38 -05:00
|
|
|
class SsoHandler:
|
2020-11-25 10:04:22 -05:00
|
|
|
# The number of attempts to ask the mapping provider for when generating an MXID.
|
|
|
|
_MAP_USERNAME_RETRIES = 1000
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
# the time a UsernameMappingSession remains valid for
|
|
|
|
_MAPPING_SESSION_VALIDITY_PERIOD_MS = 15 * 60 * 1000
|
|
|
|
|
2020-11-17 09:46:23 -05:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2020-12-18 09:19:46 -05:00
|
|
|
self._clock = hs.get_clock()
|
2022-02-23 06:04:02 -05:00
|
|
|
self._store = hs.get_datastores().main
|
2020-12-08 09:03:38 -05:00
|
|
|
self._server_name = hs.hostname
|
2020-11-25 10:04:22 -05:00
|
|
|
self._registration_handler = hs.get_registration_handler()
|
2021-01-13 06:12:28 -05:00
|
|
|
self._auth_handler = hs.get_auth_handler()
|
2021-09-24 07:25:21 -04:00
|
|
|
self._error_template = hs.config.sso.sso_error_template
|
|
|
|
self._bad_user_template = hs.config.sso.sso_auth_bad_user_template
|
2021-06-21 18:48:57 -04:00
|
|
|
self._profile_handler = hs.get_profile_handler()
|
2021-01-13 06:12:28 -05:00
|
|
|
|
|
|
|
# The following template is shown after a successful user interactive
|
|
|
|
# authentication session. It tells the user they can close the window.
|
2021-09-24 07:25:21 -04:00
|
|
|
self._sso_auth_success_template = hs.config.sso.sso_auth_success_template
|
2020-11-17 09:46:23 -05:00
|
|
|
|
2021-09-24 07:25:21 -04:00
|
|
|
self._sso_update_profile_information = (
|
|
|
|
hs.config.sso.sso_update_profile_information
|
|
|
|
)
|
2021-06-21 18:48:57 -04:00
|
|
|
|
2020-12-10 07:43:58 -05:00
|
|
|
# a lock on the mappings
|
|
|
|
self._mapping_lock = Linearizer(name="sso_user_mapping", clock=hs.get_clock())
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
# a map from session id to session data
|
2021-07-16 13:22:36 -04:00
|
|
|
self._username_mapping_sessions: Dict[str, UsernameMappingSession] = {}
|
2020-12-18 09:19:46 -05:00
|
|
|
|
2021-01-04 13:13:49 -05:00
|
|
|
# map from idp_id to SsoIdentityProvider
|
2021-07-16 13:22:36 -04:00
|
|
|
self._identity_providers: Dict[str, SsoIdentityProvider] = {}
|
2021-01-04 13:13:49 -05:00
|
|
|
|
2021-02-01 13:37:41 -05:00
|
|
|
self._consent_at_registration = hs.config.consent.user_consent_at_registration
|
|
|
|
|
2021-09-20 08:56:23 -04:00
|
|
|
def register_identity_provider(self, p: SsoIdentityProvider) -> None:
|
2021-01-04 13:13:49 -05:00
|
|
|
p_id = p.idp_id
|
|
|
|
assert p_id not in self._identity_providers
|
|
|
|
self._identity_providers[p_id] = p
|
2021-08-24 05:17:51 -04:00
|
|
|
init_counters_for_auth_provider(p_id)
|
2021-01-04 13:13:49 -05:00
|
|
|
|
2021-01-05 06:25:28 -05:00
|
|
|
def get_identity_providers(self) -> Mapping[str, SsoIdentityProvider]:
|
|
|
|
"""Get the configured identity providers"""
|
|
|
|
return self._identity_providers
|
|
|
|
|
2021-01-12 12:38:03 -05:00
|
|
|
async def get_identity_providers_for_user(
|
|
|
|
self, user_id: str
|
|
|
|
) -> Mapping[str, SsoIdentityProvider]:
|
|
|
|
"""Get the SsoIdentityProviders which a user has used
|
|
|
|
|
|
|
|
Given a user id, get the identity providers that that user has used to log in
|
|
|
|
with in the past (and thus could use to re-identify themselves for UI Auth).
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id: MXID of user to look up
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
a map of idp_id to SsoIdentityProvider
|
|
|
|
"""
|
|
|
|
external_ids = await self._store.get_external_ids_by_user(user_id)
|
|
|
|
|
|
|
|
valid_idps = {}
|
|
|
|
for idp_id, _ in external_ids:
|
|
|
|
idp = self._identity_providers.get(idp_id)
|
|
|
|
if not idp:
|
|
|
|
logger.warning(
|
|
|
|
"User %r has an SSO mapping for IdP %r, but this is no longer "
|
|
|
|
"configured.",
|
|
|
|
user_id,
|
|
|
|
idp_id,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
valid_idps[idp_id] = idp
|
|
|
|
|
|
|
|
return valid_idps
|
|
|
|
|
2020-11-17 09:46:23 -05:00
|
|
|
def render_error(
|
2020-12-18 13:09:45 -05:00
|
|
|
self,
|
|
|
|
request: Request,
|
|
|
|
error: str,
|
|
|
|
error_description: Optional[str] = None,
|
|
|
|
code: int = 400,
|
2020-11-17 09:46:23 -05:00
|
|
|
) -> None:
|
|
|
|
"""Renders the error template and responds with it.
|
|
|
|
|
|
|
|
This is used to show errors to the user. The template of this page can
|
|
|
|
be found under `synapse/res/templates/sso_error.html`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The incoming request from the browser.
|
|
|
|
We'll respond with an HTML page describing the error.
|
|
|
|
error: A technical identifier for this error.
|
|
|
|
error_description: A human-readable description of the error.
|
2020-12-18 13:09:45 -05:00
|
|
|
code: The integer error code (an HTTP response code)
|
2020-11-17 09:46:23 -05:00
|
|
|
"""
|
|
|
|
html = self._error_template.render(
|
|
|
|
error=error, error_description=error_description
|
|
|
|
)
|
2020-12-18 13:09:45 -05:00
|
|
|
respond_with_html(request, code, html)
|
2020-11-17 09:46:23 -05:00
|
|
|
|
2021-01-04 13:13:49 -05:00
|
|
|
async def handle_redirect_request(
|
2021-01-27 07:41:24 -05:00
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
client_redirect_url: bytes,
|
|
|
|
idp_id: Optional[str],
|
2021-01-04 13:13:49 -05:00
|
|
|
) -> str:
|
|
|
|
"""Handle a request to /login/sso/redirect
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: incoming HTTP request
|
|
|
|
client_redirect_url: the URL that we should redirect the
|
|
|
|
client to after login.
|
2021-01-27 07:41:24 -05:00
|
|
|
idp_id: optional identity provider chosen by the client
|
2021-01-04 13:13:49 -05:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
the URI to redirect to
|
|
|
|
"""
|
|
|
|
if not self._identity_providers:
|
|
|
|
raise SynapseError(
|
|
|
|
400, "Homeserver not configured for SSO.", errcode=Codes.UNRECOGNIZED
|
|
|
|
)
|
|
|
|
|
2021-01-27 07:41:24 -05:00
|
|
|
# if the client chose an IdP, use that
|
2021-07-16 13:22:36 -04:00
|
|
|
idp: Optional[SsoIdentityProvider] = None
|
2021-01-27 07:41:24 -05:00
|
|
|
if idp_id:
|
|
|
|
idp = self._identity_providers.get(idp_id)
|
|
|
|
if not idp:
|
|
|
|
raise NotFoundError("Unknown identity provider")
|
|
|
|
|
2021-01-04 13:13:49 -05:00
|
|
|
# if we only have one auth provider, redirect to it directly
|
2021-01-27 07:41:24 -05:00
|
|
|
elif len(self._identity_providers) == 1:
|
|
|
|
idp = next(iter(self._identity_providers.values()))
|
|
|
|
|
|
|
|
if idp:
|
|
|
|
return await idp.handle_redirect_request(request, client_redirect_url)
|
2021-01-04 13:13:49 -05:00
|
|
|
|
2021-01-05 06:25:28 -05:00
|
|
|
# otherwise, redirect to the IDP picker
|
|
|
|
return "/_synapse/client/pick_idp?" + urlencode(
|
|
|
|
(("redirectUrl", client_redirect_url),)
|
|
|
|
)
|
2021-01-04 13:13:49 -05:00
|
|
|
|
2020-11-17 09:46:23 -05:00
|
|
|
async def get_sso_user_by_remote_user_id(
|
|
|
|
self, auth_provider_id: str, remote_user_id: str
|
|
|
|
) -> Optional[str]:
|
|
|
|
"""
|
|
|
|
Maps the user ID of a remote IdP to a mxid for a previously seen user.
|
|
|
|
|
|
|
|
If the user has not been seen yet, this will return None.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
auth_provider_id: A unique identifier for this SSO provider, e.g.
|
|
|
|
"oidc" or "saml".
|
|
|
|
remote_user_id: The user ID according to the remote IdP. This might
|
|
|
|
be an e-mail address, a GUID, or some other form. It must be
|
|
|
|
unique and immutable.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The mxid of a previously seen user.
|
|
|
|
"""
|
2020-11-23 08:45:23 -05:00
|
|
|
logger.debug(
|
2020-11-17 09:46:23 -05:00
|
|
|
"Looking for existing mapping for user %s:%s",
|
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
|
|
|
)
|
2020-11-23 08:45:23 -05:00
|
|
|
|
|
|
|
# Check if we already have a mapping for this user.
|
2020-12-08 09:03:38 -05:00
|
|
|
previously_registered_user_id = await self._store.get_user_by_external_id(
|
2021-02-16 17:32:34 -05:00
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
2020-11-17 09:46:23 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
# A match was found, return the user ID.
|
|
|
|
if previously_registered_user_id is not None:
|
2020-11-23 08:45:23 -05:00
|
|
|
logger.info(
|
|
|
|
"Found existing mapping for IdP '%s' and remote_user_id '%s': %s",
|
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
|
|
|
previously_registered_user_id,
|
|
|
|
)
|
2020-11-17 09:46:23 -05:00
|
|
|
return previously_registered_user_id
|
|
|
|
|
|
|
|
# No match.
|
|
|
|
return None
|
2020-11-25 10:04:22 -05:00
|
|
|
|
2020-12-16 15:01:53 -05:00
|
|
|
async def complete_sso_login_request(
|
2020-11-25 10:04:22 -05:00
|
|
|
self,
|
|
|
|
auth_provider_id: str,
|
|
|
|
remote_user_id: str,
|
2020-12-16 15:01:53 -05:00
|
|
|
request: SynapseRequest,
|
|
|
|
client_redirect_url: str,
|
2020-11-25 10:04:22 -05:00
|
|
|
sso_to_matrix_id_mapper: Callable[[int], Awaitable[UserAttributes]],
|
2021-01-03 11:25:44 -05:00
|
|
|
grandfather_existing_users: Callable[[], Awaitable[Optional[str]]],
|
2020-12-16 15:01:53 -05:00
|
|
|
extra_login_attributes: Optional[JsonDict] = None,
|
2021-12-06 12:43:06 -05:00
|
|
|
auth_provider_session_id: Optional[str] = None,
|
2020-12-16 15:01:53 -05:00
|
|
|
) -> None:
|
2020-11-25 10:04:22 -05:00
|
|
|
"""
|
|
|
|
Given an SSO ID, retrieve the user ID for it and possibly register the user.
|
|
|
|
|
|
|
|
This first checks if the SSO ID has previously been linked to a matrix ID,
|
|
|
|
if it has that matrix ID is returned regardless of the current mapping
|
|
|
|
logic.
|
|
|
|
|
2020-12-02 07:45:42 -05:00
|
|
|
If a callable is provided for grandfathering users, it is called and can
|
|
|
|
potentially return a matrix ID to use. If it does, the SSO ID is linked to
|
|
|
|
this matrix ID for subsequent calls.
|
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
The mapping function is called (potentially multiple times) to generate
|
|
|
|
a localpart for the user.
|
|
|
|
|
|
|
|
If an unused localpart is generated, the user is registered from the
|
|
|
|
given user-agent and IP address and the SSO ID is linked to this matrix
|
|
|
|
ID for subsequent calls.
|
|
|
|
|
2020-12-16 15:01:53 -05:00
|
|
|
Finally, we generate a redirect to the supplied redirect uri, with a login token
|
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
Args:
|
|
|
|
auth_provider_id: A unique identifier for this SSO provider, e.g.
|
|
|
|
"oidc" or "saml".
|
2020-12-16 15:01:53 -05:00
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
remote_user_id: The unique identifier from the SSO provider.
|
2020-12-16 15:01:53 -05:00
|
|
|
|
|
|
|
request: The request to respond to
|
|
|
|
|
|
|
|
client_redirect_url: The redirect URL passed in by the client.
|
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
sso_to_matrix_id_mapper: A callable to generate the user attributes.
|
|
|
|
The only parameter is an integer which represents the amount of
|
|
|
|
times the returned mxid localpart mapping has failed.
|
2020-12-04 08:25:15 -05:00
|
|
|
|
|
|
|
It is expected that the mapper can raise two exceptions, which
|
|
|
|
will get passed through to the caller:
|
|
|
|
|
|
|
|
MappingException if there was a problem mapping the response
|
|
|
|
to the user.
|
|
|
|
RedirectException to redirect to an additional page (e.g.
|
|
|
|
to prompt the user for more information).
|
2020-12-16 15:01:53 -05:00
|
|
|
|
2020-12-02 07:45:42 -05:00
|
|
|
grandfather_existing_users: A callable which can return an previously
|
|
|
|
existing matrix ID. The SSO ID is then linked to the returned
|
|
|
|
matrix ID.
|
2020-11-25 10:04:22 -05:00
|
|
|
|
2020-12-16 15:01:53 -05:00
|
|
|
extra_login_attributes: An optional dictionary of extra
|
|
|
|
attributes to be provided to the client in the login response.
|
2020-11-25 10:04:22 -05:00
|
|
|
|
2021-12-06 12:43:06 -05:00
|
|
|
auth_provider_session_id: An optional session ID from the IdP.
|
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
Raises:
|
|
|
|
MappingException if there was a problem mapping the response to a user.
|
2020-12-04 08:25:15 -05:00
|
|
|
RedirectException: if the mapping provider needs to redirect the user
|
|
|
|
to an additional page. (e.g. to prompt for more information)
|
2020-11-25 10:04:22 -05:00
|
|
|
|
|
|
|
"""
|
2021-02-01 10:50:56 -05:00
|
|
|
new_user = False
|
|
|
|
|
2020-12-10 07:43:58 -05:00
|
|
|
# grab a lock while we try to find a mapping for this user. This seems...
|
|
|
|
# optimistic, especially for implementations that end up redirecting to
|
|
|
|
# interstitial pages.
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._mapping_lock.queue(auth_provider_id):
|
2020-12-10 07:43:58 -05:00
|
|
|
# first of all, check if we already have a mapping for this user
|
2020-12-16 15:01:53 -05:00
|
|
|
user_id = await self.get_sso_user_by_remote_user_id(
|
2021-02-16 17:32:34 -05:00
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
2020-12-10 07:43:58 -05:00
|
|
|
)
|
2020-12-02 07:45:42 -05:00
|
|
|
|
2020-12-10 07:43:58 -05:00
|
|
|
# Check for grandfathering of users.
|
2021-01-03 11:25:44 -05:00
|
|
|
if not user_id:
|
2020-12-16 15:01:53 -05:00
|
|
|
user_id = await grandfather_existing_users()
|
|
|
|
if user_id:
|
2020-12-10 07:43:58 -05:00
|
|
|
# Future logins should also match this user ID.
|
|
|
|
await self._store.record_user_external_id(
|
2020-12-16 15:01:53 -05:00
|
|
|
auth_provider_id, remote_user_id, user_id
|
2020-12-10 07:43:58 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
# Otherwise, generate a new user.
|
2020-12-16 15:01:53 -05:00
|
|
|
if not user_id:
|
|
|
|
attributes = await self._call_attribute_mapper(sso_to_matrix_id_mapper)
|
2020-12-18 09:19:46 -05:00
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
next_step_url = self._get_url_for_next_new_user_step(
|
|
|
|
attributes=attributes
|
|
|
|
)
|
|
|
|
if next_step_url:
|
|
|
|
await self._redirect_to_next_new_user_step(
|
2020-12-18 09:19:46 -05:00
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
|
|
|
attributes,
|
|
|
|
client_redirect_url,
|
2021-09-10 05:36:45 -04:00
|
|
|
next_step_url,
|
2020-12-18 09:19:46 -05:00
|
|
|
extra_login_attributes,
|
|
|
|
)
|
|
|
|
|
2020-12-16 15:01:53 -05:00
|
|
|
user_id = await self._register_mapped_user(
|
|
|
|
attributes,
|
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
2021-01-12 07:34:16 -05:00
|
|
|
get_request_user_agent(request),
|
2022-05-04 14:11:21 -04:00
|
|
|
request.getClientAddress().host,
|
2020-12-16 15:01:53 -05:00
|
|
|
)
|
2021-02-01 10:50:56 -05:00
|
|
|
new_user = True
|
2021-06-21 18:48:57 -04:00
|
|
|
elif self._sso_update_profile_information:
|
|
|
|
attributes = await self._call_attribute_mapper(sso_to_matrix_id_mapper)
|
|
|
|
if attributes.display_name:
|
|
|
|
user_id_obj = UserID.from_string(user_id)
|
|
|
|
profile_display_name = await self._profile_handler.get_displayname(
|
|
|
|
user_id_obj
|
|
|
|
)
|
|
|
|
if profile_display_name != attributes.display_name:
|
|
|
|
requester = create_requester(
|
|
|
|
user_id,
|
|
|
|
authenticated_entity=user_id,
|
|
|
|
)
|
|
|
|
await self._profile_handler.set_displayname(
|
|
|
|
user_id_obj, requester, attributes.display_name, True
|
|
|
|
)
|
2020-12-16 15:01:53 -05:00
|
|
|
|
|
|
|
await self._auth_handler.complete_sso_login(
|
2021-02-01 10:50:56 -05:00
|
|
|
user_id,
|
2021-03-04 09:44:22 -05:00
|
|
|
auth_provider_id,
|
2021-02-01 10:50:56 -05:00
|
|
|
request,
|
|
|
|
client_redirect_url,
|
|
|
|
extra_login_attributes,
|
|
|
|
new_user=new_user,
|
2021-12-06 12:43:06 -05:00
|
|
|
auth_provider_session_id=auth_provider_session_id,
|
2020-12-16 15:01:53 -05:00
|
|
|
)
|
2020-12-10 07:43:58 -05:00
|
|
|
|
|
|
|
async def _call_attribute_mapper(
|
2021-02-16 17:32:34 -05:00
|
|
|
self,
|
|
|
|
sso_to_matrix_id_mapper: Callable[[int], Awaitable[UserAttributes]],
|
2020-12-10 07:43:58 -05:00
|
|
|
) -> UserAttributes:
|
|
|
|
"""Call the attribute mapper function in a loop, until we get a unique userid"""
|
2020-11-25 10:04:22 -05:00
|
|
|
for i in range(self._MAP_USERNAME_RETRIES):
|
|
|
|
try:
|
|
|
|
attributes = await sso_to_matrix_id_mapper(i)
|
2020-12-04 08:25:15 -05:00
|
|
|
except (RedirectException, MappingException):
|
|
|
|
# Mapping providers are allowed to issue a redirect (e.g. to ask
|
|
|
|
# the user for more information) and can issue a mapping exception
|
|
|
|
# if a name cannot be generated.
|
|
|
|
raise
|
2020-11-25 10:04:22 -05:00
|
|
|
except Exception as e:
|
2020-12-04 08:25:15 -05:00
|
|
|
# Any other exception is unexpected.
|
2020-11-25 10:04:22 -05:00
|
|
|
raise MappingException(
|
2020-12-04 08:25:15 -05:00
|
|
|
"Could not extract user attributes from SSO response."
|
|
|
|
) from e
|
2020-11-25 10:04:22 -05:00
|
|
|
|
|
|
|
logger.debug(
|
|
|
|
"Retrieved user attributes from user mapping provider: %r (attempt %d)",
|
|
|
|
attributes,
|
|
|
|
i,
|
|
|
|
)
|
|
|
|
|
|
|
|
if not attributes.localpart:
|
2020-12-18 09:19:46 -05:00
|
|
|
# the mapper has not picked a localpart
|
|
|
|
return attributes
|
2020-11-25 10:04:22 -05:00
|
|
|
|
|
|
|
# Check if this mxid already exists
|
2020-12-08 09:03:38 -05:00
|
|
|
user_id = UserID(attributes.localpart, self._server_name).to_string()
|
|
|
|
if not await self._store.get_users_by_id_case_insensitive(user_id):
|
2020-11-25 10:04:22 -05:00
|
|
|
# This mxid is free
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
# Unable to generate a username in 1000 iterations
|
|
|
|
# Break and return error to the user
|
|
|
|
raise MappingException(
|
|
|
|
"Unable to generate a Matrix ID from the SSO response"
|
|
|
|
)
|
2020-12-10 07:43:58 -05:00
|
|
|
return attributes
|
2020-11-25 10:04:22 -05:00
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
def _get_url_for_next_new_user_step(
|
|
|
|
self,
|
|
|
|
attributes: Optional[UserAttributes] = None,
|
|
|
|
session: Optional[UsernameMappingSession] = None,
|
|
|
|
) -> bytes:
|
|
|
|
"""Returns the URL to redirect to for the next step of new user registration
|
|
|
|
|
|
|
|
Given attributes from the user mapping provider or a UsernameMappingSession,
|
|
|
|
returns the URL to redirect to for the next step of the registration flow.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
attributes: the user attributes returned by the user mapping provider,
|
|
|
|
from before a UsernameMappingSession has begun.
|
|
|
|
|
|
|
|
session: an active UsernameMappingSession, possibly with some of its
|
|
|
|
attributes chosen by the user.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The URL to redirect to, or an empty value if no redirect is necessary
|
|
|
|
"""
|
|
|
|
# Must provide either attributes or session, not both
|
|
|
|
assert (attributes is not None) != (session is not None)
|
|
|
|
|
2022-03-11 08:20:00 -05:00
|
|
|
if (
|
|
|
|
attributes
|
|
|
|
and (attributes.localpart is None or attributes.confirm_localpart is True)
|
|
|
|
) or (session and session.chosen_localpart is None):
|
2021-09-10 05:36:45 -04:00
|
|
|
return b"/_synapse/client/pick_username/account_details"
|
|
|
|
elif self._consent_at_registration and not (
|
|
|
|
session and session.terms_accepted_version
|
|
|
|
):
|
|
|
|
return b"/_synapse/client/new_user_consent"
|
|
|
|
else:
|
|
|
|
return b"/_synapse/client/sso_register" if session else b""
|
|
|
|
|
|
|
|
async def _redirect_to_next_new_user_step(
|
2020-12-18 09:19:46 -05:00
|
|
|
self,
|
|
|
|
auth_provider_id: str,
|
|
|
|
remote_user_id: str,
|
|
|
|
attributes: UserAttributes,
|
|
|
|
client_redirect_url: str,
|
2021-09-10 05:36:45 -04:00
|
|
|
next_step_url: bytes,
|
2020-12-18 09:19:46 -05:00
|
|
|
extra_login_attributes: Optional[JsonDict],
|
|
|
|
) -> NoReturn:
|
|
|
|
"""Creates a UsernameMappingSession and redirects the browser
|
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
Called if the user mapping provider doesn't return complete information for a new user.
|
|
|
|
Raises a RedirectException which redirects the browser to a specified URL.
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
Args:
|
|
|
|
auth_provider_id: A unique identifier for this SSO provider, e.g.
|
|
|
|
"oidc" or "saml".
|
|
|
|
|
|
|
|
remote_user_id: The unique identifier from the SSO provider.
|
|
|
|
|
|
|
|
attributes: the user attributes returned by the user mapping provider.
|
|
|
|
|
|
|
|
client_redirect_url: The redirect URL passed in by the client, which we
|
|
|
|
will eventually redirect back to.
|
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
next_step_url: The URL to redirect to for the next step of the new user flow.
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
extra_login_attributes: An optional dictionary of extra
|
|
|
|
attributes to be provided to the client in the login response.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
RedirectException
|
|
|
|
"""
|
2021-09-10 05:36:45 -04:00
|
|
|
# TODO: If needed, allow using/looking up an existing session here.
|
2020-12-18 09:19:46 -05:00
|
|
|
session_id = random_string(16)
|
|
|
|
now = self._clock.time_msec()
|
|
|
|
session = UsernameMappingSession(
|
|
|
|
auth_provider_id=auth_provider_id,
|
|
|
|
remote_user_id=remote_user_id,
|
|
|
|
display_name=attributes.display_name,
|
|
|
|
emails=attributes.emails,
|
|
|
|
client_redirect_url=client_redirect_url,
|
|
|
|
expiry_time_ms=now + self._MAPPING_SESSION_VALIDITY_PERIOD_MS,
|
|
|
|
extra_login_attributes=extra_login_attributes,
|
2021-09-10 05:36:45 -04:00
|
|
|
# Treat the localpart returned by the user mapping provider as though
|
|
|
|
# it was chosen by the user. If it's None, it must be chosen eventually.
|
|
|
|
chosen_localpart=attributes.localpart,
|
|
|
|
# TODO: Consider letting the user mapping provider specify defaults for
|
|
|
|
# other user-chosen attributes.
|
2020-12-18 09:19:46 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
self._username_mapping_sessions[session_id] = session
|
|
|
|
logger.info("Recorded registration session id %s", session_id)
|
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
# Set the cookie and redirect to the next step
|
|
|
|
e = RedirectException(next_step_url)
|
2020-12-18 09:19:46 -05:00
|
|
|
e.cookies.append(
|
|
|
|
b"%s=%s; path=/"
|
|
|
|
% (USERNAME_MAPPING_SESSION_COOKIE_NAME, session_id.encode("ascii"))
|
|
|
|
)
|
|
|
|
raise e
|
|
|
|
|
2020-12-10 07:43:58 -05:00
|
|
|
async def _register_mapped_user(
|
|
|
|
self,
|
|
|
|
attributes: UserAttributes,
|
|
|
|
auth_provider_id: str,
|
|
|
|
remote_user_id: str,
|
|
|
|
user_agent: str,
|
|
|
|
ip_address: str,
|
|
|
|
) -> str:
|
2020-12-18 09:19:46 -05:00
|
|
|
"""Register a new SSO user.
|
|
|
|
|
|
|
|
This is called once we have successfully mapped the remote user id onto a local
|
|
|
|
user id, one way or another.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
attributes: user attributes returned by the user mapping provider,
|
|
|
|
including a non-empty localpart.
|
|
|
|
|
|
|
|
auth_provider_id: A unique identifier for this SSO provider, e.g.
|
|
|
|
"oidc" or "saml".
|
|
|
|
|
|
|
|
remote_user_id: The unique identifier from the SSO provider.
|
|
|
|
|
|
|
|
user_agent: The user-agent in the HTTP request (used for potential
|
|
|
|
shadow-banning.)
|
|
|
|
|
|
|
|
ip_address: The IP address of the requester (used for potential
|
|
|
|
shadow-banning.)
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
a MappingException if the localpart is invalid.
|
|
|
|
|
|
|
|
a SynapseError with code 400 and errcode Codes.USER_IN_USE if the localpart
|
|
|
|
is already taken.
|
|
|
|
"""
|
|
|
|
|
2020-11-25 10:04:22 -05:00
|
|
|
# Since the localpart is provided via a potentially untrusted module,
|
|
|
|
# ensure the MXID is valid before registering.
|
2020-12-18 09:19:46 -05:00
|
|
|
if not attributes.localpart or contains_invalid_mxid_characters(
|
|
|
|
attributes.localpart
|
|
|
|
):
|
2020-11-25 10:04:22 -05:00
|
|
|
raise MappingException("localpart is invalid: %s" % (attributes.localpart,))
|
|
|
|
|
|
|
|
logger.debug("Mapped SSO user to local part %s", attributes.localpart)
|
|
|
|
registered_user_id = await self._registration_handler.register_user(
|
|
|
|
localpart=attributes.localpart,
|
|
|
|
default_display_name=attributes.display_name,
|
|
|
|
bind_emails=attributes.emails,
|
|
|
|
user_agent_ips=[(user_agent, ip_address)],
|
2021-03-04 11:39:27 -05:00
|
|
|
auth_provider_id=auth_provider_id,
|
2020-11-25 10:04:22 -05:00
|
|
|
)
|
|
|
|
|
2020-12-08 09:03:38 -05:00
|
|
|
await self._store.record_user_external_id(
|
2020-11-25 10:04:22 -05:00
|
|
|
auth_provider_id, remote_user_id, registered_user_id
|
|
|
|
)
|
|
|
|
return registered_user_id
|
2020-12-08 09:03:38 -05:00
|
|
|
|
|
|
|
async def complete_sso_ui_auth_request(
|
|
|
|
self,
|
|
|
|
auth_provider_id: str,
|
|
|
|
remote_user_id: str,
|
|
|
|
ui_auth_session_id: str,
|
|
|
|
request: Request,
|
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Given an SSO ID, retrieve the user ID for it and complete UIA.
|
|
|
|
|
|
|
|
Note that this requires that the user is mapped in the "user_external_ids"
|
|
|
|
table. This will be the case if they have ever logged in via SAML or OIDC in
|
|
|
|
recentish synapse versions, but may not be for older users.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
auth_provider_id: A unique identifier for this SSO provider, e.g.
|
|
|
|
"oidc" or "saml".
|
|
|
|
remote_user_id: The unique identifier from the SSO provider.
|
|
|
|
ui_auth_session_id: The ID of the user-interactive auth session.
|
|
|
|
request: The request to complete.
|
|
|
|
"""
|
|
|
|
|
|
|
|
user_id = await self.get_sso_user_by_remote_user_id(
|
2021-02-16 17:32:34 -05:00
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
2020-12-08 09:03:38 -05:00
|
|
|
)
|
|
|
|
|
2021-07-16 13:22:36 -04:00
|
|
|
user_id_to_verify: str = await self._auth_handler.get_session_data(
|
2021-01-12 13:19:42 -05:00
|
|
|
ui_auth_session_id, UIAuthSessionDataConstants.REQUEST_USER_ID
|
2021-07-16 13:22:36 -04:00
|
|
|
)
|
2021-01-12 13:19:42 -05:00
|
|
|
|
2020-12-08 09:03:38 -05:00
|
|
|
if not user_id:
|
|
|
|
logger.warning(
|
|
|
|
"Remote user %s/%s has not previously logged in here: UIA will fail",
|
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
|
|
|
)
|
2021-01-12 13:19:42 -05:00
|
|
|
elif user_id != user_id_to_verify:
|
|
|
|
logger.warning(
|
|
|
|
"Remote user %s/%s mapped onto incorrect user %s: UIA will fail",
|
|
|
|
auth_provider_id,
|
|
|
|
remote_user_id,
|
|
|
|
user_id,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
# success!
|
2021-01-13 06:12:28 -05:00
|
|
|
# Mark the stage of the authentication as successful.
|
|
|
|
await self._store.mark_ui_auth_stage_complete(
|
|
|
|
ui_auth_session_id, LoginType.SSO, user_id
|
2021-01-12 13:19:42 -05:00
|
|
|
)
|
2021-01-13 06:12:28 -05:00
|
|
|
|
|
|
|
# Render the HTML confirmation page and return.
|
|
|
|
html = self._sso_auth_success_template
|
|
|
|
respond_with_html(request, 200, html)
|
2021-01-12 13:19:42 -05:00
|
|
|
return
|
|
|
|
|
|
|
|
# the user_id didn't match: mark the stage of the authentication as unsuccessful
|
|
|
|
await self._store.mark_ui_auth_stage_complete(
|
|
|
|
ui_auth_session_id, LoginType.SSO, ""
|
|
|
|
)
|
2020-12-08 09:03:38 -05:00
|
|
|
|
2021-01-12 13:19:42 -05:00
|
|
|
# render an error page.
|
|
|
|
html = self._bad_user_template.render(
|
2021-02-16 17:32:34 -05:00
|
|
|
server_name=self._server_name,
|
|
|
|
user_id_to_verify=user_id_to_verify,
|
2020-12-08 09:03:38 -05:00
|
|
|
)
|
2021-01-12 13:19:42 -05:00
|
|
|
respond_with_html(request, 200, html)
|
2020-12-18 09:19:46 -05:00
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
def get_mapping_session(self, session_id: str) -> UsernameMappingSession:
|
|
|
|
"""Look up the given username mapping session
|
|
|
|
|
|
|
|
If it is not found, raises a SynapseError with an http code of 400
|
|
|
|
|
|
|
|
Args:
|
|
|
|
session_id: session to look up
|
|
|
|
Returns:
|
|
|
|
active mapping session
|
|
|
|
Raises:
|
|
|
|
SynapseError if the session is not found/has expired
|
|
|
|
"""
|
|
|
|
self._expire_old_sessions()
|
|
|
|
session = self._username_mapping_sessions.get(session_id)
|
|
|
|
if session:
|
|
|
|
return session
|
|
|
|
logger.info("Couldn't find session id %s", session_id)
|
|
|
|
raise SynapseError(400, "unknown session")
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
async def check_username_availability(
|
2021-02-16 17:32:34 -05:00
|
|
|
self,
|
|
|
|
localpart: str,
|
|
|
|
session_id: str,
|
2020-12-18 09:19:46 -05:00
|
|
|
) -> bool:
|
|
|
|
"""Handle an "is username available" callback check
|
|
|
|
|
|
|
|
Args:
|
|
|
|
localpart: desired localpart
|
|
|
|
session_id: the session id for the username picker
|
|
|
|
Returns:
|
|
|
|
True if the username is available
|
|
|
|
Raises:
|
|
|
|
SynapseError if the localpart is invalid or the session is unknown
|
|
|
|
"""
|
|
|
|
|
|
|
|
# make sure that there is a valid mapping session, to stop people dictionary-
|
|
|
|
# scanning for accounts
|
2021-02-01 08:15:51 -05:00
|
|
|
self.get_mapping_session(session_id)
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
logger.info(
|
|
|
|
"[session %s] Checking for availability of username %s",
|
|
|
|
session_id,
|
|
|
|
localpart,
|
|
|
|
)
|
|
|
|
|
|
|
|
if contains_invalid_mxid_characters(localpart):
|
|
|
|
raise SynapseError(400, "localpart is invalid: %s" % (localpart,))
|
|
|
|
user_id = UserID(localpart, self._server_name).to_string()
|
|
|
|
user_infos = await self._store.get_users_by_id_case_insensitive(user_id)
|
|
|
|
|
|
|
|
logger.info("[session %s] users: %s", session_id, user_infos)
|
|
|
|
return not user_infos
|
|
|
|
|
|
|
|
async def handle_submit_username_request(
|
2021-02-01 12:30:42 -05:00
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
session_id: str,
|
|
|
|
localpart: str,
|
|
|
|
use_display_name: bool,
|
|
|
|
emails_to_use: Iterable[str],
|
2020-12-18 09:19:46 -05:00
|
|
|
) -> None:
|
|
|
|
"""Handle a request to the username-picker 'submit' endpoint
|
|
|
|
|
|
|
|
Will serve an HTTP response to the request.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: HTTP request
|
|
|
|
localpart: localpart requested by the user
|
|
|
|
session_id: ID of the username mapping session, extracted from a cookie
|
2021-02-01 12:30:42 -05:00
|
|
|
use_display_name: whether the user wants to use the suggested display name
|
|
|
|
emails_to_use: emails that the user would like to use
|
2020-12-18 09:19:46 -05:00
|
|
|
"""
|
2021-02-03 11:13:09 -05:00
|
|
|
try:
|
|
|
|
session = self.get_mapping_session(session_id)
|
|
|
|
except SynapseError as e:
|
|
|
|
self.render_error(request, "bad_session", e.msg, code=e.code)
|
|
|
|
return
|
2021-02-01 08:15:51 -05:00
|
|
|
|
|
|
|
# update the session with the user's choices
|
|
|
|
session.chosen_localpart = localpart
|
2021-02-01 12:30:42 -05:00
|
|
|
session.use_display_name = use_display_name
|
|
|
|
|
|
|
|
emails_from_idp = set(session.emails)
|
2021-07-16 13:22:36 -04:00
|
|
|
filtered_emails: Set[str] = set()
|
2021-02-01 12:30:42 -05:00
|
|
|
|
|
|
|
# we iterate through the list rather than just building a set conjunction, so
|
|
|
|
# that we can log attempts to use unknown addresses
|
|
|
|
for email in emails_to_use:
|
|
|
|
if email in emails_from_idp:
|
|
|
|
filtered_emails.add(email)
|
|
|
|
else:
|
|
|
|
logger.warning(
|
|
|
|
"[session %s] ignoring user request to use unknown email address %r",
|
|
|
|
session_id,
|
|
|
|
email,
|
|
|
|
)
|
|
|
|
session.emails_to_use = filtered_emails
|
2021-02-01 08:15:51 -05:00
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
respond_with_redirect(
|
|
|
|
request, self._get_url_for_next_new_user_step(session=session)
|
|
|
|
)
|
2021-02-01 13:37:41 -05:00
|
|
|
|
|
|
|
async def handle_terms_accepted(
|
|
|
|
self, request: Request, session_id: str, terms_version: str
|
2021-09-20 08:56:23 -04:00
|
|
|
) -> None:
|
2021-02-01 13:37:41 -05:00
|
|
|
"""Handle a request to the new-user 'consent' endpoint
|
|
|
|
|
|
|
|
Will serve an HTTP response to the request.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: HTTP request
|
|
|
|
session_id: ID of the username mapping session, extracted from a cookie
|
|
|
|
terms_version: the version of the terms which the user viewed and consented
|
|
|
|
to
|
|
|
|
"""
|
|
|
|
logger.info(
|
|
|
|
"[session %s] User consented to terms version %s",
|
|
|
|
session_id,
|
|
|
|
terms_version,
|
|
|
|
)
|
2021-02-03 11:13:09 -05:00
|
|
|
try:
|
|
|
|
session = self.get_mapping_session(session_id)
|
|
|
|
except SynapseError as e:
|
|
|
|
self.render_error(request, "bad_session", e.msg, code=e.code)
|
|
|
|
return
|
|
|
|
|
2021-02-01 13:37:41 -05:00
|
|
|
session.terms_accepted_version = terms_version
|
|
|
|
|
2021-09-10 05:36:45 -04:00
|
|
|
respond_with_redirect(
|
|
|
|
request, self._get_url_for_next_new_user_step(session=session)
|
|
|
|
)
|
2021-02-01 08:15:51 -05:00
|
|
|
|
|
|
|
async def register_sso_user(self, request: Request, session_id: str) -> None:
|
|
|
|
"""Called once we have all the info we need to register a new user.
|
2020-12-18 09:19:46 -05:00
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
Does so and serves an HTTP response
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: HTTP request
|
|
|
|
session_id: ID of the username mapping session, extracted from a cookie
|
|
|
|
"""
|
2021-02-03 11:13:09 -05:00
|
|
|
try:
|
|
|
|
session = self.get_mapping_session(session_id)
|
|
|
|
except SynapseError as e:
|
|
|
|
self.render_error(request, "bad_session", e.msg, code=e.code)
|
|
|
|
return
|
2021-02-01 08:15:51 -05:00
|
|
|
|
|
|
|
logger.info(
|
|
|
|
"[session %s] Registering localpart %s",
|
|
|
|
session_id,
|
|
|
|
session.chosen_localpart,
|
|
|
|
)
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
attributes = UserAttributes(
|
2021-02-16 17:32:34 -05:00
|
|
|
localpart=session.chosen_localpart,
|
|
|
|
emails=session.emails_to_use,
|
2020-12-18 09:19:46 -05:00
|
|
|
)
|
|
|
|
|
2021-02-01 12:30:42 -05:00
|
|
|
if session.use_display_name:
|
|
|
|
attributes.display_name = session.display_name
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
# the following will raise a 400 error if the username has been taken in the
|
|
|
|
# meantime.
|
|
|
|
user_id = await self._register_mapped_user(
|
|
|
|
attributes,
|
|
|
|
session.auth_provider_id,
|
|
|
|
session.remote_user_id,
|
2021-01-12 07:34:16 -05:00
|
|
|
get_request_user_agent(request),
|
2022-05-04 14:11:21 -04:00
|
|
|
request.getClientAddress().host,
|
2020-12-18 09:19:46 -05:00
|
|
|
)
|
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
logger.info(
|
|
|
|
"[session %s] Registered userid %s with attributes %s",
|
|
|
|
session_id,
|
|
|
|
user_id,
|
|
|
|
attributes,
|
|
|
|
)
|
2020-12-18 09:19:46 -05:00
|
|
|
|
|
|
|
# delete the mapping session and the cookie
|
|
|
|
del self._username_mapping_sessions[session_id]
|
|
|
|
|
|
|
|
# delete the cookie
|
|
|
|
request.addCookie(
|
|
|
|
USERNAME_MAPPING_SESSION_COOKIE_NAME,
|
|
|
|
b"",
|
|
|
|
expires=b"Thu, 01 Jan 1970 00:00:00 GMT",
|
|
|
|
path=b"/",
|
|
|
|
)
|
|
|
|
|
2021-02-01 13:37:41 -05:00
|
|
|
auth_result = {}
|
|
|
|
if session.terms_accepted_version:
|
|
|
|
# TODO: make this less awful.
|
|
|
|
auth_result[LoginType.TERMS] = True
|
|
|
|
|
|
|
|
await self._registration_handler.post_registration_actions(
|
|
|
|
user_id, auth_result, access_token=None
|
|
|
|
)
|
|
|
|
|
2020-12-18 09:19:46 -05:00
|
|
|
await self._auth_handler.complete_sso_login(
|
|
|
|
user_id,
|
2021-03-04 09:44:22 -05:00
|
|
|
session.auth_provider_id,
|
2020-12-18 09:19:46 -05:00
|
|
|
request,
|
|
|
|
session.client_redirect_url,
|
|
|
|
session.extra_login_attributes,
|
2021-02-01 10:50:56 -05:00
|
|
|
new_user=True,
|
2020-12-18 09:19:46 -05:00
|
|
|
)
|
|
|
|
|
2021-09-20 08:56:23 -04:00
|
|
|
def _expire_old_sessions(self) -> None:
|
2020-12-18 09:19:46 -05:00
|
|
|
to_expire = []
|
|
|
|
now = int(self._clock.time_msec())
|
|
|
|
|
|
|
|
for session_id, session in self._username_mapping_sessions.items():
|
|
|
|
if session.expiry_time_ms <= now:
|
|
|
|
to_expire.append(session_id)
|
|
|
|
|
|
|
|
for session_id in to_expire:
|
|
|
|
logger.info("Expiring mapping session %s", session_id)
|
|
|
|
del self._username_mapping_sessions[session_id]
|
2021-02-01 08:15:51 -05:00
|
|
|
|
2021-02-11 10:05:15 -05:00
|
|
|
def check_required_attributes(
|
|
|
|
self,
|
|
|
|
request: SynapseRequest,
|
|
|
|
attributes: Mapping[str, List[Any]],
|
|
|
|
attribute_requirements: Iterable[SsoAttributeRequirement],
|
|
|
|
) -> bool:
|
|
|
|
"""
|
|
|
|
Confirm that the required attributes were present in the SSO response.
|
|
|
|
|
|
|
|
If all requirements are met, this will return True.
|
|
|
|
|
|
|
|
If any requirement is not met, then the request will be finalized by
|
|
|
|
showing an error page to the user and False will be returned.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The request to (potentially) respond to.
|
|
|
|
attributes: The attributes from the SSO IdP.
|
|
|
|
attribute_requirements: The requirements that attributes must meet.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
True if all requirements are met, False if any attribute fails to
|
|
|
|
meet the requirement.
|
|
|
|
|
|
|
|
"""
|
|
|
|
# Ensure that the attributes of the logged in user meet the required
|
|
|
|
# attributes.
|
|
|
|
for requirement in attribute_requirements:
|
|
|
|
if not _check_attribute_requirement(attributes, requirement):
|
|
|
|
self.render_error(
|
|
|
|
request, "unauthorised", "You are not authorised to log in here."
|
|
|
|
)
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2021-02-01 08:15:51 -05:00
|
|
|
|
|
|
|
def get_username_mapping_session_cookie_from_request(request: IRequest) -> str:
|
|
|
|
"""Extract the session ID from the cookie
|
|
|
|
|
|
|
|
Raises a SynapseError if the cookie isn't found
|
|
|
|
"""
|
|
|
|
session_id = request.getCookie(USERNAME_MAPPING_SESSION_COOKIE_NAME)
|
|
|
|
if not session_id:
|
|
|
|
raise SynapseError(code=400, msg="missing session_id")
|
|
|
|
return session_id.decode("ascii", errors="replace")
|
2021-02-11 10:05:15 -05:00
|
|
|
|
|
|
|
|
|
|
|
def _check_attribute_requirement(
|
|
|
|
attributes: Mapping[str, List[Any]], req: SsoAttributeRequirement
|
|
|
|
) -> bool:
|
|
|
|
"""Check if SSO attributes meet the proper requirements.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
attributes: A mapping of attributes to an iterable of one or more values.
|
|
|
|
requirement: The configured requirement to check.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
True if the required attribute was found and had a proper value.
|
|
|
|
"""
|
|
|
|
if req.attribute not in attributes:
|
|
|
|
logger.info("SSO attribute missing: %s", req.attribute)
|
|
|
|
return False
|
|
|
|
|
|
|
|
# If the requirement is None, the attribute existing is enough.
|
|
|
|
if req.value is None:
|
|
|
|
return True
|
|
|
|
|
|
|
|
values = attributes[req.attribute]
|
|
|
|
if req.value in values:
|
|
|
|
return True
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
"SSO attribute %s did not match required value '%s' (was '%s')",
|
|
|
|
req.attribute,
|
|
|
|
req.value,
|
|
|
|
values,
|
|
|
|
)
|
|
|
|
return False
|