-
Notifications
You must be signed in to change notification settings - Fork 3
First cut of the module #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ea5b37f
First cut of the module
babolivier 1661ad3
Doc + actually register the callback
babolivier abf108f
Lint
babolivier de7f4a7
Lint
babolivier ae10d27
Use new on_threepid_bind callback
babolivier ee7166d
Removed unused imports
babolivier 4e6c891
Include protocol scheme in config option
babolivier e241956
Lint
babolivier e983567
Fix docs
babolivier b003a49
Apply suggestions from code review
babolivier b318966
Fix black
babolivier 816156a
Merge branch 'babolivier/init' of github.com:matrix-org/synapse-bind-…
babolivier File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| # Copyright 2022 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. | ||
| import logging | ||
| from typing import Any, Dict | ||
|
|
||
| import attr | ||
| from synapse.module_api import ModuleApi | ||
| from synapse.module_api.errors import ConfigError | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @attr.s(auto_attribs=True, frozen=True) | ||
| class SydentBinderConfig: | ||
| sydent_host: str | ||
| use_https: bool = False | ||
|
|
||
|
|
||
| class SydentBinder: | ||
| def __init__(self, config: SydentBinderConfig, api: ModuleApi) -> None: | ||
| # Keep a reference to the config and Module API | ||
| self._api = api | ||
| self._config = config | ||
|
|
||
| self._http_client = api.http_client | ||
|
|
||
| protocol = "https" if config.use_https else "http" | ||
| self._sydent_bind_url = ( | ||
| f"{protocol}://{config.sydent_host}/_matrix/identity/internal/bind" | ||
| ) | ||
|
|
||
| self._api.register_account_validity_callbacks( | ||
| on_user_registration=self.on_register, | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def parse_config(config: Dict[str, Any]) -> SydentBinderConfig: | ||
| if "sydent_host" not in config or not isinstance(config["sydent_host"], str): | ||
| raise ConfigError("sydent_host needs to be a string") | ||
|
|
||
| return SydentBinderConfig(**config) | ||
|
|
||
| async def on_register(self, user_id: str) -> None: | ||
| """Binds the 3PID on registration.""" | ||
| # Get the list of 3PIDs for this user. | ||
| threepids = await self._api.get_threepids_for_user(user_id) | ||
babolivier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| for threepid in threepids: | ||
| body = { | ||
| "address": threepid["address"], | ||
| "medium": threepid["medium"], | ||
| "mxid": user_id, | ||
| } | ||
|
|
||
| # Bind the threepid | ||
| try: | ||
| await self._http_client.post_json_get_json(self._sydent_bind_url, body) | ||
| except Exception as e: | ||
| # If there was an error, the IS is likely unreachable, so don't try again. | ||
| logger.exception( | ||
| "Failed to bind 3PID %s to identity server at %s: %s", | ||
| threepid, | ||
| self._sydent_bind_url, | ||
| e, | ||
| ) | ||
| return | ||
|
|
||
| # Store the association, so we can use this to unbind later. | ||
| await self._api.store_remote_3pid_association( | ||
| user_id, | ||
| threepid["medium"], | ||
| threepid["address"], | ||
| self._config.sydent_host, | ||
| ) | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| from asyncio import Future | ||
| from typing import Any, Awaitable, Dict, List, TypeVar | ||
| from unittest.mock import Mock | ||
|
|
||
| from synapse.module_api import ModuleApi | ||
|
|
||
| from synapse_bind_sydent import SydentBinder | ||
|
|
||
| TV = TypeVar("TV") | ||
|
|
||
|
|
||
| def make_awaitable(result: TV) -> Awaitable[TV]: | ||
| """ | ||
| Makes an awaitable, suitable for mocking an `async` function. | ||
| This function is copied from Synapse's test code. | ||
| """ | ||
| future = Future() # type: ignore | ||
| future.set_result(result) | ||
| return future | ||
|
|
||
|
|
||
| def create_module( | ||
| user_threepids: List[Dict[str, Any]], http_mock: Mock | ||
| ) -> SydentBinder: | ||
| # Create a mock based on the ModuleApi spec, but override some mocked functions | ||
| # because some capabilities are needed for running the tests. | ||
| module_api = Mock(spec=ModuleApi) | ||
| module_api.get_threepids_for_user = Mock( | ||
| return_value=make_awaitable(user_threepids) | ||
| ) | ||
| module_api.store_remote_3pid_association = Mock(return_value=make_awaitable(None)) | ||
| module_api.http_client = http_mock | ||
|
|
||
| # If necessary, give parse_config some configuration to parse. | ||
| config = SydentBinder.parse_config({"sydent_host": "test"}) | ||
|
|
||
| return SydentBinder(config, module_api) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| # Copyright 2022 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. | ||
| from typing import Any | ||
| from unittest.mock import Mock | ||
|
|
||
| import aiounittest | ||
|
|
||
| from tests import create_module, make_awaitable | ||
|
|
||
|
|
||
| class SydentBinderTestCase(aiounittest.AsyncTestCase): | ||
| async def test_no_assoc(self) -> None: | ||
| """Tests that the right function calls are made when the newly registered user has | ||
| no 3PID associated. | ||
| """ | ||
| http_client = Mock() | ||
| http_client.post_json_get_json = Mock(return_value=make_awaitable(None)) | ||
|
|
||
| module = create_module( | ||
| user_threepids=[], | ||
| http_mock=http_client, | ||
| ) | ||
|
|
||
| await module.on_register("@jdoe:matrix.org") | ||
|
|
||
| self.assertEqual(http_client.post_json_get_json.call_count, 0) | ||
|
|
||
| store_remote_3pid_association: Mock = module._api.store_remote_3pid_association # type: ignore[assignment] | ||
| self.assertEqual(store_remote_3pid_association.call_count, 0) | ||
|
|
||
| async def test_single_assoc(self) -> None: | ||
| """Tests that the right function calls are made when the newly registered user has | ||
| a single 3PID associated. | ||
| """ | ||
| http_client = Mock() | ||
| http_client.post_json_get_json = Mock(return_value=make_awaitable(None)) | ||
|
|
||
| address = "[email protected]" | ||
| medium = "email" | ||
| user_id = "@jdoe:example.com" | ||
|
|
||
| module = create_module( | ||
| user_threepids=[ | ||
| { | ||
| "medium": medium, | ||
| "address": address, | ||
| } | ||
| ], | ||
| http_mock=http_client, | ||
| ) | ||
|
|
||
| await module.on_register(user_id) | ||
|
|
||
| self.assertEqual(http_client.post_json_get_json.call_count, 1) | ||
| args = http_client.post_json_get_json.call_args[0] | ||
| self.assertEqual( | ||
| args[1], {"address": address, "medium": medium, "mxid": user_id} | ||
| ) | ||
|
|
||
| store_remote_3pid_association: Mock = module._api.store_remote_3pid_association # type: ignore[assignment] | ||
| self.assertEqual(store_remote_3pid_association.call_count, 1) | ||
| args = store_remote_3pid_association.call_args[0] | ||
| self.assertEqual(args, (user_id, medium, address, "test")) | ||
|
|
||
| async def test_multiple_assoc(self) -> None: | ||
| """Tests that the right function calls are made when the newly registered user has | ||
| multiple 3PIDs associated. | ||
| """ | ||
| http_client = Mock() | ||
| http_client.post_json_get_json = Mock(return_value=make_awaitable(None)) | ||
|
|
||
| assocs = [ | ||
| {"medium": "email", "address": "[email protected]"}, | ||
| {"medium": "email", "address": "[email protected]"}, | ||
| {"medium": "msisdn", "address": "0000000"}, | ||
| ] | ||
| user_id = "@jdoe:matrix.org" | ||
|
|
||
| module = create_module(user_threepids=assocs, http_mock=http_client) | ||
|
|
||
| await module.on_register(user_id) | ||
|
|
||
| self.assertEqual(http_client.post_json_get_json.call_count, len(assocs)) | ||
| args = http_client.post_json_get_json.call_args[0] | ||
| self.assertEqual( | ||
| args[1], | ||
| { | ||
| "address": assocs[-1]["address"], | ||
| "medium": assocs[-1]["medium"], | ||
| "mxid": user_id, | ||
| }, | ||
| ) | ||
|
|
||
| store_remote_3pid_association: Mock = module._api.store_remote_3pid_association # type: ignore[assignment] | ||
| self.assertEqual(store_remote_3pid_association.call_count, len(assocs)) | ||
| args = store_remote_3pid_association.call_args[0] | ||
| self.assertEqual( | ||
| args, (user_id, assocs[-1]["medium"], assocs[-1]["address"], "test") | ||
| ) | ||
|
|
||
| async def test_network_error(self) -> None: | ||
| """Tests that the process is aborted right away if an error was raised when trying | ||
| to bind a 3PID.""" | ||
|
|
||
| async def post_json_get_json(*args: Any, **kwargs: Any) -> None: | ||
| raise RuntimeError("oh no") | ||
|
|
||
| http_client = Mock() | ||
| http_client.post_json_get_json = Mock(side_effect=post_json_get_json) | ||
|
|
||
| assocs = [ | ||
| {"medium": "email", "address": "[email protected]"}, | ||
| {"medium": "email", "address": "[email protected]"}, | ||
| {"medium": "msisdn", "address": "0000000"}, | ||
| ] | ||
|
|
||
| module = create_module(user_threepids=assocs, http_mock=http_client) | ||
|
|
||
| await module.on_register("@jdoe:matrix.org") | ||
|
|
||
| self.assertEqual(http_client.post_json_get_json.call_count, 1) | ||
|
|
||
| store_remote_3pid_association: Mock = module._api.store_remote_3pid_association # type: ignore[assignment] | ||
| self.assertEqual(store_remote_3pid_association.call_count, 0) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.