Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ Then alter your homeserver configuration, adding to your `modules` configuration
modules:
- module: synapse_bind_sydent.SydentBinder
config:
# TODO: Complete this section with an example for your module
# The hostname (or IP address) of the Sydent instance to bind to. Must be reachable
# by Synapse.
# Required.
sydent_host: example.com
# Whether to use HTTPS when sending a request to Sydent.
# Optional, defaults to false.
use_https: false
```


Expand Down Expand Up @@ -74,13 +80,3 @@ Synapse developers (assuming a Unix-like shell):
```shell
git push origin tag v$version
```

7. If applicable:
Create a *release*, based on the tag you just pushed, on GitHub or GitLab.

8. If applicable:
Create a source distribution and upload it to PyPI:
```shell
python -m build
twine upload dist/synapse_bind_sydent-$version*
```
85 changes: 85 additions & 0 deletions synapse_bind_sydent/__init__.py
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)

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 added synapse_bind_sydent/py.typed
Empty file.
37 changes: 37 additions & 0 deletions tests/__init__.py
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)
135 changes: 135 additions & 0 deletions tests/test_binder.py
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)