summary refs log tree commit diff
path: root/tests/handlers/test_auth.py
blob: c7efd3822d6f6adf5f9c1f059a6f73d2fae0a9f8 (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
239
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 mock import Mock

import pymacaroons

from twisted.internet import defer

import synapse
import synapse.api.errors
from synapse.api.errors import ResourceLimitError
from synapse.handlers.auth import AuthHandler

from tests import unittest
from tests.test_utils import make_awaitable
from tests.utils import setup_test_homeserver


class AuthHandlers:
    def __init__(self, hs):
        self.auth_handler = AuthHandler(hs)


class AuthTestCase(unittest.TestCase):
    @defer.inlineCallbacks
    def setUp(self):
        self.hs = yield setup_test_homeserver(self.addCleanup, handlers=None)
        self.hs.handlers = AuthHandlers(self.hs)
        self.auth_handler = self.hs.handlers.auth_handler
        self.macaroon_generator = self.hs.get_macaroon_generator()

        # MAU tests
        # AuthBlocking reads from the hs' config on initialization. We need to
        # modify its config instead of the hs'
        self.auth_blocking = self.hs.get_auth()._auth_blocking
        self.auth_blocking._max_mau_value = 50

        self.small_number_of_users = 1
        self.large_number_of_users = 100

    def test_token_is_a_macaroon(self):
        token = self.macaroon_generator.generate_access_token("some_user")
        # Check that we can parse the thing with pymacaroons
        macaroon = pymacaroons.Macaroon.deserialize(token)
        # The most basic of sanity checks
        if "some_user" not in macaroon.inspect():
            self.fail("some_user was not in %s" % macaroon.inspect())

    def test_macaroon_caveats(self):
        self.hs.clock.now = 5000

        token = self.macaroon_generator.generate_access_token("a_user")
        macaroon = pymacaroons.Macaroon.deserialize(token)

        def verify_gen(caveat):
            return caveat == "gen = 1"

        def verify_user(caveat):
            return caveat == "user_id = a_user"

        def verify_type(caveat):
            return caveat == "type = access"

        def verify_nonce(caveat):
            return caveat.startswith("nonce =")

        v = pymacaroons.Verifier()
        v.satisfy_general(verify_gen)
        v.satisfy_general(verify_user)
        v.satisfy_general(verify_type)
        v.satisfy_general(verify_nonce)
        v.verify(macaroon, self.hs.config.macaroon_secret_key)

    @defer.inlineCallbacks
    def test_short_term_login_token_gives_user_id(self):
        self.hs.clock.now = 1000

        token = self.macaroon_generator.generate_short_term_login_token("a_user", 5000)
        user_id = yield defer.ensureDeferred(
            self.auth_handler.validate_short_term_login_token_and_get_user_id(token)
        )
        self.assertEqual("a_user", user_id)

        # when we advance the clock, the token should be rejected
        self.hs.clock.now = 6000
        with self.assertRaises(synapse.api.errors.AuthError):
            yield defer.ensureDeferred(
                self.auth_handler.validate_short_term_login_token_and_get_user_id(token)
            )

    @defer.inlineCallbacks
    def test_short_term_login_token_cannot_replace_user_id(self):
        token = self.macaroon_generator.generate_short_term_login_token("a_user", 5000)
        macaroon = pymacaroons.Macaroon.deserialize(token)

        user_id = yield defer.ensureDeferred(
            self.auth_handler.validate_short_term_login_token_and_get_user_id(
                macaroon.serialize()
            )
        )
        self.assertEqual("a_user", user_id)

        # add another "user_id" caveat, which might allow us to override the
        # user_id.
        macaroon.add_first_party_caveat("user_id = b_user")

        with self.assertRaises(synapse.api.errors.AuthError):
            yield defer.ensureDeferred(
                self.auth_handler.validate_short_term_login_token_and_get_user_id(
                    macaroon.serialize()
                )
            )

    @defer.inlineCallbacks
    def test_mau_limits_disabled(self):
        self.auth_blocking._limit_usage_by_mau = False
        # Ensure does not throw exception
        yield defer.ensureDeferred(
            self.auth_handler.get_access_token_for_user_id(
                "user_a", device_id=None, valid_until_ms=None
            )
        )

        yield defer.ensureDeferred(
            self.auth_handler.validate_short_term_login_token_and_get_user_id(
                self._get_macaroon().serialize()
            )
        )

    @defer.inlineCallbacks
    def test_mau_limits_exceeded_large(self):
        self.auth_blocking._limit_usage_by_mau = True
        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.large_number_of_users)
        )

        with self.assertRaises(ResourceLimitError):
            yield defer.ensureDeferred(
                self.auth_handler.get_access_token_for_user_id(
                    "user_a", device_id=None, valid_until_ms=None
                )
            )

        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.large_number_of_users)
        )
        with self.assertRaises(ResourceLimitError):
            yield defer.ensureDeferred(
                self.auth_handler.validate_short_term_login_token_and_get_user_id(
                    self._get_macaroon().serialize()
                )
            )

    @defer.inlineCallbacks
    def test_mau_limits_parity(self):
        self.auth_blocking._limit_usage_by_mau = True

        # If not in monthly active cohort
        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.auth_blocking._max_mau_value)
        )
        with self.assertRaises(ResourceLimitError):
            yield defer.ensureDeferred(
                self.auth_handler.get_access_token_for_user_id(
                    "user_a", device_id=None, valid_until_ms=None
                )
            )

        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.auth_blocking._max_mau_value)
        )
        with self.assertRaises(ResourceLimitError):
            yield defer.ensureDeferred(
                self.auth_handler.validate_short_term_login_token_and_get_user_id(
                    self._get_macaroon().serialize()
                )
            )
        # If in monthly active cohort
        self.hs.get_datastore().user_last_seen_monthly_active = Mock(
            side_effect=lambda user_id: make_awaitable(self.hs.get_clock().time_msec())
        )
        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.auth_blocking._max_mau_value)
        )
        yield defer.ensureDeferred(
            self.auth_handler.get_access_token_for_user_id(
                "user_a", device_id=None, valid_until_ms=None
            )
        )
        self.hs.get_datastore().user_last_seen_monthly_active = Mock(
            side_effect=lambda user_id: make_awaitable(self.hs.get_clock().time_msec())
        )
        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.auth_blocking._max_mau_value)
        )
        yield defer.ensureDeferred(
            self.auth_handler.validate_short_term_login_token_and_get_user_id(
                self._get_macaroon().serialize()
            )
        )

    @defer.inlineCallbacks
    def test_mau_limits_not_exceeded(self):
        self.auth_blocking._limit_usage_by_mau = True

        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.small_number_of_users)
        )
        # Ensure does not raise exception
        yield defer.ensureDeferred(
            self.auth_handler.get_access_token_for_user_id(
                "user_a", device_id=None, valid_until_ms=None
            )
        )

        self.hs.get_datastore().get_monthly_active_count = Mock(
            side_effect=lambda: make_awaitable(self.small_number_of_users)
        )
        yield defer.ensureDeferred(
            self.auth_handler.validate_short_term_login_token_and_get_user_id(
                self._get_macaroon().serialize()
            )
        )

    def _get_macaroon(self):
        token = self.macaroon_generator.generate_short_term_login_token("user_a", 5000)
        return pymacaroons.Macaroon.deserialize(token)