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

Commit f78d07b

Browse files
authored
Split out a separate endpoint to complete SSO registration (#9262)
There are going to be a couple of paths to get to the final step of SSO reg, and I want the URL in the browser to consistent. So, let's move the final step onto a separate path, which we redirect to.
1 parent a083aea commit f78d07b

File tree

7 files changed

+145
-26
lines changed

7 files changed

+145
-26
lines changed

changelog.d/9262.feature

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve the user experience of setting up an account via single-sign on.

synapse/app/homeserver.py

+2
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
from synapse.rest.key.v2 import KeyApiV2Resource
6363
from synapse.rest.synapse.client.pick_idp import PickIdpResource
6464
from synapse.rest.synapse.client.pick_username import pick_username_resource
65+
from synapse.rest.synapse.client.sso_register import SsoRegisterResource
6566
from synapse.rest.well_known import WellKnownResource
6667
from synapse.server import HomeServer
6768
from synapse.storage import DataStore
@@ -192,6 +193,7 @@ def _configure_named_resource(self, name, compress=False):
192193
"/_synapse/admin": AdminRestResource(self),
193194
"/_synapse/client/pick_username": pick_username_resource(self),
194195
"/_synapse/client/pick_idp": PickIdpResource(self),
196+
"/_synapse/client/sso_register": SsoRegisterResource(self),
195197
}
196198
)
197199

synapse/handlers/sso.py

+66-15
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,13 @@
2121
from typing_extensions import NoReturn, Protocol
2222

2323
from twisted.web.http import Request
24+
from twisted.web.iweb import IRequest
2425

2526
from synapse.api.constants import LoginType
2627
from synapse.api.errors import Codes, NotFoundError, RedirectException, SynapseError
2728
from synapse.handlers.ui_auth import UIAuthSessionDataConstants
2829
from synapse.http import get_request_user_agent
29-
from synapse.http.server import respond_with_html
30+
from synapse.http.server import respond_with_html, respond_with_redirect
3031
from synapse.http.site import SynapseRequest
3132
from synapse.types import JsonDict, UserID, contains_invalid_mxid_characters
3233
from synapse.util.async_helpers import Linearizer
@@ -141,6 +142,9 @@ class UsernameMappingSession:
141142
# expiry time for the session, in milliseconds
142143
expiry_time_ms = attr.ib(type=int)
143144

145+
# choices made by the user
146+
chosen_localpart = attr.ib(type=Optional[str], default=None)
147+
144148

145149
# the HTTP cookie used to track the mapping session id
146150
USERNAME_MAPPING_SESSION_COOKIE_NAME = b"username_mapping_session"
@@ -647,6 +651,25 @@ async def complete_sso_ui_auth_request(
647651
)
648652
respond_with_html(request, 200, html)
649653

654+
def get_mapping_session(self, session_id: str) -> UsernameMappingSession:
655+
"""Look up the given username mapping session
656+
657+
If it is not found, raises a SynapseError with an http code of 400
658+
659+
Args:
660+
session_id: session to look up
661+
Returns:
662+
active mapping session
663+
Raises:
664+
SynapseError if the session is not found/has expired
665+
"""
666+
self._expire_old_sessions()
667+
session = self._username_mapping_sessions.get(session_id)
668+
if session:
669+
return session
670+
logger.info("Couldn't find session id %s", session_id)
671+
raise SynapseError(400, "unknown session")
672+
650673
async def check_username_availability(
651674
self, localpart: str, session_id: str,
652675
) -> bool:
@@ -663,12 +686,7 @@ async def check_username_availability(
663686

664687
# make sure that there is a valid mapping session, to stop people dictionary-
665688
# scanning for accounts
666-
667-
self._expire_old_sessions()
668-
session = self._username_mapping_sessions.get(session_id)
669-
if not session:
670-
logger.info("Couldn't find session id %s", session_id)
671-
raise SynapseError(400, "unknown session")
689+
self.get_mapping_session(session_id)
672690

673691
logger.info(
674692
"[session %s] Checking for availability of username %s",
@@ -696,16 +714,33 @@ async def handle_submit_username_request(
696714
localpart: localpart requested by the user
697715
session_id: ID of the username mapping session, extracted from a cookie
698716
"""
699-
self._expire_old_sessions()
700-
session = self._username_mapping_sessions.get(session_id)
701-
if not session:
702-
logger.info("Couldn't find session id %s", session_id)
703-
raise SynapseError(400, "unknown session")
717+
session = self.get_mapping_session(session_id)
718+
719+
# update the session with the user's choices
720+
session.chosen_localpart = localpart
721+
722+
# we're done; now we can register the user
723+
respond_with_redirect(request, b"/_synapse/client/sso_register")
724+
725+
async def register_sso_user(self, request: Request, session_id: str) -> None:
726+
"""Called once we have all the info we need to register a new user.
704727
705-
logger.info("[session %s] Registering localpart %s", session_id, localpart)
728+
Does so and serves an HTTP response
729+
730+
Args:
731+
request: HTTP request
732+
session_id: ID of the username mapping session, extracted from a cookie
733+
"""
734+
session = self.get_mapping_session(session_id)
735+
736+
logger.info(
737+
"[session %s] Registering localpart %s",
738+
session_id,
739+
session.chosen_localpart,
740+
)
706741

707742
attributes = UserAttributes(
708-
localpart=localpart,
743+
localpart=session.chosen_localpart,
709744
display_name=session.display_name,
710745
emails=session.emails,
711746
)
@@ -720,7 +755,12 @@ async def handle_submit_username_request(
720755
request.getClientIP(),
721756
)
722757

723-
logger.info("[session %s] Registered userid %s", session_id, user_id)
758+
logger.info(
759+
"[session %s] Registered userid %s with attributes %s",
760+
session_id,
761+
user_id,
762+
attributes,
763+
)
724764

725765
# delete the mapping session and the cookie
726766
del self._username_mapping_sessions[session_id]
@@ -751,3 +791,14 @@ def _expire_old_sessions(self):
751791
for session_id in to_expire:
752792
logger.info("Expiring mapping session %s", session_id)
753793
del self._username_mapping_sessions[session_id]
794+
795+
796+
def get_username_mapping_session_cookie_from_request(request: IRequest) -> str:
797+
"""Extract the session ID from the cookie
798+
799+
Raises a SynapseError if the cookie isn't found
800+
"""
801+
session_id = request.getCookie(USERNAME_MAPPING_SESSION_COOKIE_NAME)
802+
if not session_id:
803+
raise SynapseError(code=400, msg="missing session_id")
804+
return session_id.decode("ascii", errors="replace")

synapse/http/server.py

+7
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,13 @@ def set_clickjacking_protection_headers(request: Request):
761761
request.setHeader(b"Content-Security-Policy", b"frame-ancestors 'none';")
762762

763763

764+
def respond_with_redirect(request: Request, url: bytes) -> None:
765+
"""Write a 302 response to the request, if it is still alive."""
766+
logger.debug("Redirect to %s", url.decode("utf-8"))
767+
request.redirect(url)
768+
finish_request(request)
769+
770+
764771
def finish_request(request: Request):
765772
""" Finish writing the response to the request.
766773

synapse/rest/synapse/client/pick_username.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15+
1516
from typing import TYPE_CHECKING
1617

1718
import pkg_resources
@@ -20,8 +21,7 @@
2021
from twisted.web.resource import Resource
2122
from twisted.web.static import File
2223

23-
from synapse.api.errors import SynapseError
24-
from synapse.handlers.sso import USERNAME_MAPPING_SESSION_COOKIE_NAME
24+
from synapse.handlers.sso import get_username_mapping_session_cookie_from_request
2525
from synapse.http.server import DirectServeHtmlResource, DirectServeJsonResource
2626
from synapse.http.servlet import parse_string
2727
from synapse.http.site import SynapseRequest
@@ -61,12 +61,10 @@ def __init__(self, hs: "HomeServer"):
6161
async def _async_render_GET(self, request: Request):
6262
localpart = parse_string(request, "username", required=True)
6363

64-
session_id = request.getCookie(USERNAME_MAPPING_SESSION_COOKIE_NAME)
65-
if not session_id:
66-
raise SynapseError(code=400, msg="missing session_id")
64+
session_id = get_username_mapping_session_cookie_from_request(request)
6765

6866
is_available = await self._sso_handler.check_username_availability(
69-
localpart, session_id.decode("ascii", errors="replace")
67+
localpart, session_id
7068
)
7169
return 200, {"available": is_available}
7270

@@ -79,10 +77,8 @@ def __init__(self, hs: "HomeServer"):
7977
async def _async_render_POST(self, request: SynapseRequest):
8078
localpart = parse_string(request, "username", required=True)
8179

82-
session_id = request.getCookie(USERNAME_MAPPING_SESSION_COOKIE_NAME)
83-
if not session_id:
84-
raise SynapseError(code=400, msg="missing session_id")
80+
session_id = get_username_mapping_session_cookie_from_request(request)
8581

8682
await self._sso_handler.handle_submit_username_request(
87-
request, localpart, session_id.decode("ascii", errors="replace")
83+
request, localpart, session_id
8884
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
import logging
17+
from typing import TYPE_CHECKING
18+
19+
from twisted.web.http import Request
20+
21+
from synapse.api.errors import SynapseError
22+
from synapse.handlers.sso import get_username_mapping_session_cookie_from_request
23+
from synapse.http.server import DirectServeHtmlResource
24+
25+
if TYPE_CHECKING:
26+
from synapse.server import HomeServer
27+
28+
logger = logging.getLogger(__name__)
29+
30+
31+
class SsoRegisterResource(DirectServeHtmlResource):
32+
"""A resource which completes SSO registration
33+
34+
This resource gets mounted at /_synapse/client/sso_register, and is shown
35+
after we collect username and/or consent for a new SSO user. It (finally) registers
36+
the user, and confirms redirect to the client
37+
"""
38+
39+
def __init__(self, hs: "HomeServer"):
40+
super().__init__()
41+
self._sso_handler = hs.get_sso_handler()
42+
43+
async def _async_render_GET(self, request: Request) -> None:
44+
try:
45+
session_id = get_username_mapping_session_cookie_from_request(request)
46+
except SynapseError as e:
47+
logger.warning("Error fetching session cookie: %s", e)
48+
self._sso_handler.render_error(request, "bad_session", e.msg, code=e.code)
49+
return
50+
await self._sso_handler.register_sso_user(request, session_id)

tests/rest/client/v1/test_login.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from synapse.rest.client.v2_alpha.account import WhoamiRestServlet
3232
from synapse.rest.synapse.client.pick_idp import PickIdpResource
3333
from synapse.rest.synapse.client.pick_username import pick_username_resource
34+
from synapse.rest.synapse.client.sso_register import SsoRegisterResource
3435
from synapse.types import create_requester
3536

3637
from tests import unittest
@@ -1215,6 +1216,7 @@ def create_resource_dict(self) -> Dict[str, Resource]:
12151216

12161217
d = super().create_resource_dict()
12171218
d["/_synapse/client/pick_username"] = pick_username_resource(self.hs)
1219+
d["/_synapse/client/sso_register"] = SsoRegisterResource(self.hs)
12181220
d["/_synapse/oidc"] = OIDCResource(self.hs)
12191221
return d
12201222

@@ -1253,7 +1255,7 @@ def test_username_picker(self):
12531255
self.assertApproximates(session.expiry_time_ms, expected_expiry, tolerance=1000)
12541256

12551257
# Now, submit a username to the username picker, which should serve a redirect
1256-
# back to the client
1258+
# to the completion page
12571259
submit_path = picker_url + "/submit"
12581260
content = urlencode({b"username": b"bobby"}).encode("utf8")
12591261
chan = self.make_request(
@@ -1270,6 +1272,16 @@ def test_username_picker(self):
12701272
)
12711273
self.assertEqual(chan.code, 302, chan.result)
12721274
location_headers = chan.headers.getRawHeaders("Location")
1275+
1276+
# send a request to the completion page, which should 302 to the client redirectUrl
1277+
chan = self.make_request(
1278+
"GET",
1279+
path=location_headers[0],
1280+
custom_headers=[("Cookie", "username_mapping_session=" + session_id)],
1281+
)
1282+
self.assertEqual(chan.code, 302, chan.result)
1283+
location_headers = chan.headers.getRawHeaders("Location")
1284+
12731285
# ensure that the returned location matches the requested redirect URL
12741286
path, query = location_headers[0].split("?", 1)
12751287
self.assertEqual(path, "https://x")

0 commit comments

Comments
 (0)