summary refs log tree commit diff
path: root/tests/replication/test_account_validity.py
blob: 408eb266b962107d0cca9ff2b2827fb04d89c6c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# 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 Optional, cast

from twisted.internet.defer import ensureDeferred

import synapse
from synapse.module_api import DatabasePool, LoggingTransaction, ModuleApi, cached
from synapse.server import HomeServer

from tests.replication._base import BaseMultiWorkerStreamTestCase
from tests.server import ThreadedMemoryReactorClock, make_request

logger = logging.getLogger(__name__)


class MockAccountValidityStore:
    def __init__(
        self,
        api: ModuleApi,
    ):
        self._api = api

    async def create_db(self):
        def create_table_txn(txn: LoggingTransaction):
            txn.execute(
                """
                CREATE TABLE IF NOT EXISTS mock_account_validity(
                    user_id TEXT PRIMARY KEY,
                    expired BOOLEAN NOT NULL
                )
                """,
                (),
            )

        await self._api.run_db_interaction(
            "account_validity_create_table",
            create_table_txn,
        )

    @cached()
    async def is_user_expired(self, user_id: str) -> Optional[bool]:
        def get_expiration_for_user_txn(txn: LoggingTransaction):
            return DatabasePool.simple_select_one_onecol_txn(
                txn=txn,
                table="mock_account_validity",
                keyvalues={"user_id": user_id},
                retcol="expired",
                allow_none=True,
            )

        return await self._api.run_db_interaction(
            "get_expiration_for_user",
            get_expiration_for_user_txn,
        )

    async def on_user_registration(self, user_id: str) -> None:
        def add_valid_user_txn(txn: LoggingTransaction):
            txn.execute(
                "INSERT INTO mock_account_validity (user_id, expired) VALUES (?, ?)",
                (user_id, False),
            )

        await self._api.run_db_interaction(
            "account_validity_add_valid_user",
            add_valid_user_txn,
        )

    async def set_expired(self, user_id: str, expired: bool = True) -> None:
        def set_expired_user_txn(txn: LoggingTransaction):
            txn.execute(
                "UPDATE mock_account_validity SET expired = ? WHERE user_id = ?",
                (
                    expired,
                    user_id,
                ),
            )

            txn.call_after(self.is_user_expired.invalidate, (user_id,))

        await self._api.run_db_interaction(
            "account_validity_set_expired_user",
            set_expired_user_txn,
        )


class MockAccountValidity:
    def __init__(
        self,
        config,
        api: ModuleApi,
    ):
        self._api = api

        self._store = MockAccountValidityStore(api)

        ensureDeferred(self._store.create_db())
        cast(ThreadedMemoryReactorClock, api._hs.get_reactor()).pump([0.0])

        self._api.register_account_validity_callbacks(
            is_user_expired=self.is_user_expired,
            on_user_registration=self.on_user_registration,
        )

    async def is_user_expired(self, user_id: str) -> Optional[bool]:
        return await self._store.is_user_expired(user_id)

    async def on_user_registration(self, user_id: str) -> None:
        await self._store.on_user_registration(user_id)


class WorkerAccountValidityTestCase(BaseMultiWorkerStreamTestCase):
    servlets = [
        synapse.rest.admin.register_servlets,
        synapse.rest.client.account.register_servlets,
        synapse.rest.client.login.register_servlets,
        synapse.rest.client.register.register_servlets,
    ]

    def default_config(self):
        config = super().default_config()

        config["modules"] = [
            {
                "module": __name__ + ".MockAccountValidity",
            }
        ]

        return config

    def make_homeserver(self, reactor, clock):
        hs = super().make_homeserver(reactor, clock)
        module_api = hs.get_module_api()
        for module, config in hs.config.modules.loaded_modules:
            self.module = module(config=config, api=module_api)
            logger.info("Loaded module %s", self.module)
        return hs

    def make_worker_hs(
        self, worker_app: str, extra_config: Optional[dict] = None, **kwargs
    ) -> HomeServer:
        hs = super().make_worker_hs(worker_app, extra_config=extra_config)
        module_api = hs.get_module_api()
        for module, config in hs.config.modules.loaded_modules:
            # Do not store the module in self here since we want to expire the user
            # from the main worker and see if it get properly replicated to the other one.
            module(config=config, api=module_api)
            logger.info("Loaded module %s", self.module)
        return hs

    def _create_and_check_user(self):
        self.register_user("user", "pass")
        user_id = "@user:test"
        token = self.login("user", "pass")

        channel = self.make_request(
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )

        self.assertEqual(channel.code, 200)
        self.assertEqual(channel.json_body["user_id"], user_id)

        return user_id, token

    def test_account_validity(self):
        user_id, token = self._create_and_check_user()

        self.get_success_or_raise(self.module._store.set_expired(user_id))

        channel = self.make_request(
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )
        self.assertEqual(channel.code, 403)

        self.get_success_or_raise(self.module._store.set_expired(user_id, False))

        channel = self.make_request(
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )
        self.assertEqual(channel.code, 200)

    def test_account_validity_with_worker_and_cache(self):
        worker_hs = self.make_worker_hs("synapse.app.generic_worker")
        worker_site = self._hs_to_site[worker_hs]

        user_id, token = self._create_and_check_user()

        # check than the user is valid on the other worker too
        channel = make_request(
            self.reactor,
            worker_site,
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )
        self.assertEqual(channel.code, 200)

        # Expires user on the main worker, and check its state on the other worker
        self.get_success_or_raise(self.module._store.set_expired(user_id))

        channel = make_request(
            self.reactor,
            worker_site,
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )
        self.assertEqual(channel.code, 403)

        # Un-expires user on the main worker, and check its state on the other worker
        self.get_success_or_raise(self.module._store.set_expired(user_id, False))

        channel = make_request(
            self.reactor,
            worker_site,
            "GET",
            "/_matrix/client/v3/account/whoami",
            access_token=token,
        )
        self.assertEqual(channel.code, 200)