summary refs log tree commit diff
path: root/synapse/rest/client/v1/push_rule.py
blob: cf68725ca154fd3127b516b278fe8d272906a691 (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# -*- coding: utf-8 -*-
# Copyright 2014-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 twisted.internet import defer

from synapse.api.errors import (
    SynapseError, Codes, UnrecognizedRequestError, NotFoundError, StoreError
)
from .base import ClientV1RestServlet, client_path_patterns
from synapse.storage.push_rule import (
    InconsistentRuleException, RuleNotFoundException
)
from synapse.push.baserules import list_with_base_rules, BASE_RULE_IDS
from synapse.push.rulekinds import (
    PRIORITY_CLASS_MAP, PRIORITY_CLASS_INVERSE_MAP
)

import copy
import simplejson as json


class PushRuleRestServlet(ClientV1RestServlet):
    PATTERNS = client_path_patterns("/pushrules/.*$")
    SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR = (
        "Unrecognised request: You probably wanted a trailing slash")

    def __init__(self, hs):
        super(PushRuleRestServlet, self).__init__(hs)
        self.store = hs.get_datastore()
        self.notifier = hs.get_notifier()

    @defer.inlineCallbacks
    def on_PUT(self, request):
        spec = _rule_spec_from_path(request.postpath)
        try:
            priority_class = _priority_class_from_spec(spec)
        except InvalidRuleException as e:
            raise SynapseError(400, e.message)

        requester = yield self.auth.get_user_by_req(request)

        if '/' in spec['rule_id'] or '\\' in spec['rule_id']:
            raise SynapseError(400, "rule_id may not contain slashes")

        content = _parse_json(request)

        user_id = requester.user.to_string()

        if 'attr' in spec:
            yield self.set_rule_attr(user_id, spec, content)
            self.notify_user(user_id)
            defer.returnValue((200, {}))

        if spec['rule_id'].startswith('.'):
            # Rule ids starting with '.' are reserved for server default rules.
            raise SynapseError(400, "cannot add new rule_ids that start with '.'")

        try:
            (conditions, actions) = _rule_tuple_from_request_object(
                spec['template'],
                spec['rule_id'],
                content,
            )
        except InvalidRuleException as e:
            raise SynapseError(400, e.message)

        before = request.args.get("before", None)
        if before:
            before = _namespaced_rule_id(spec, before[0])

        after = request.args.get("after", None)
        if after:
            after = _namespaced_rule_id(spec, after[0])

        try:
            yield self.store.add_push_rule(
                user_id=user_id,
                rule_id=_namespaced_rule_id_from_spec(spec),
                priority_class=priority_class,
                conditions=conditions,
                actions=actions,
                before=before,
                after=after
            )
            self.notify_user(user_id)
        except InconsistentRuleException as e:
            raise SynapseError(400, e.message)
        except RuleNotFoundException as e:
            raise SynapseError(400, e.message)

        defer.returnValue((200, {}))

    @defer.inlineCallbacks
    def on_DELETE(self, request):
        spec = _rule_spec_from_path(request.postpath)

        requester = yield self.auth.get_user_by_req(request)
        user_id = requester.user.to_string()

        namespaced_rule_id = _namespaced_rule_id_from_spec(spec)

        try:
            yield self.store.delete_push_rule(
                user_id, namespaced_rule_id
            )
            self.notify_user(user_id)
            defer.returnValue((200, {}))
        except StoreError as e:
            if e.code == 404:
                raise NotFoundError()
            else:
                raise

    @defer.inlineCallbacks
    def on_GET(self, request):
        requester = yield self.auth.get_user_by_req(request)
        user_id = requester.user.to_string()

        # we build up the full structure and then decide which bits of it
        # to send which means doing unnecessary work sometimes but is
        # is probably not going to make a whole lot of difference
        rawrules = yield self.store.get_push_rules_for_user(user_id)

        ruleslist = []
        for rawrule in rawrules:
            rule = dict(rawrule)
            rule["conditions"] = json.loads(rawrule["conditions"])
            rule["actions"] = json.loads(rawrule["actions"])
            ruleslist.append(rule)

        # We're going to be mutating this a lot, so do a deep copy
        ruleslist = copy.deepcopy(list_with_base_rules(ruleslist))

        rules = {'global': {}, 'device': {}}

        rules['global'] = _add_empty_priority_class_arrays(rules['global'])

        enabled_map = yield self.store.get_push_rules_enabled_for_user(user_id)

        for r in ruleslist:
            rulearray = None

            template_name = _priority_class_to_template_name(r['priority_class'])

            # Remove internal stuff.
            for c in r["conditions"]:
                c.pop("_id", None)

                pattern_type = c.pop("pattern_type", None)
                if pattern_type == "user_id":
                    c["pattern"] = user_id
                elif pattern_type == "user_localpart":
                    c["pattern"] = requester.user.localpart

            rulearray = rules['global'][template_name]

            template_rule = _rule_to_template(r)
            if template_rule:
                if r['rule_id'] in enabled_map:
                    template_rule['enabled'] = enabled_map[r['rule_id']]
                elif 'enabled' in r:
                    template_rule['enabled'] = r['enabled']
                else:
                    template_rule['enabled'] = True
                rulearray.append(template_rule)

        path = request.postpath[1:]

        if path == []:
            # we're a reference impl: pedantry is our job.
            raise UnrecognizedRequestError(
                PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
            )

        if path[0] == '':
            defer.returnValue((200, rules))
        elif path[0] == 'global':
            path = path[1:]
            result = _filter_ruleset_with_path(rules['global'], path)
            defer.returnValue((200, result))
        else:
            raise UnrecognizedRequestError()

    def on_OPTIONS(self, _):
        return 200, {}

    def notify_user(self, user_id):
        stream_id = self.store.get_push_rules_stream_token()
        self.notifier.on_new_event(
            "push_rules_key", stream_id, users=[user_id]
        )

    def set_rule_attr(self, user_id, spec, val):
        if spec['attr'] == 'enabled':
            if isinstance(val, dict) and "enabled" in val:
                val = val["enabled"]
            if not isinstance(val, bool):
                # Legacy fallback
                # This should *actually* take a dict, but many clients pass
                # bools directly, so let's not break them.
                raise SynapseError(400, "Value for 'enabled' must be boolean")
            namespaced_rule_id = _namespaced_rule_id_from_spec(spec)
            return self.store.set_push_rule_enabled(
                user_id, namespaced_rule_id, val
            )
        elif spec['attr'] == 'actions':
            actions = val.get('actions')
            _check_actions(actions)
            namespaced_rule_id = _namespaced_rule_id_from_spec(spec)
            rule_id = spec['rule_id']
            is_default_rule = rule_id.startswith(".")
            if is_default_rule:
                if namespaced_rule_id not in BASE_RULE_IDS:
                    raise SynapseError(404, "Unknown rule %r" % (namespaced_rule_id,))
            return self.store.set_push_rule_actions(
                user_id, namespaced_rule_id, actions, is_default_rule
            )
        else:
            raise UnrecognizedRequestError()


def _rule_spec_from_path(path):
    if len(path) < 2:
        raise UnrecognizedRequestError()
    if path[0] != 'pushrules':
        raise UnrecognizedRequestError()

    scope = path[1]
    path = path[2:]
    if scope != 'global':
        raise UnrecognizedRequestError()

    if len(path) == 0:
        raise UnrecognizedRequestError()

    template = path[0]
    path = path[1:]

    if len(path) == 0 or len(path[0]) == 0:
        raise UnrecognizedRequestError()

    rule_id = path[0]

    spec = {
        'scope': scope,
        'template': template,
        'rule_id': rule_id
    }

    path = path[1:]

    if len(path) > 0 and len(path[0]) > 0:
        spec['attr'] = path[0]

    return spec


def _rule_tuple_from_request_object(rule_template, rule_id, req_obj):
    if rule_template in ['override', 'underride']:
        if 'conditions' not in req_obj:
            raise InvalidRuleException("Missing 'conditions'")
        conditions = req_obj['conditions']
        for c in conditions:
            if 'kind' not in c:
                raise InvalidRuleException("Condition without 'kind'")
    elif rule_template == 'room':
        conditions = [{
            'kind': 'event_match',
            'key': 'room_id',
            'pattern': rule_id
        }]
    elif rule_template == 'sender':
        conditions = [{
            'kind': 'event_match',
            'key': 'user_id',
            'pattern': rule_id
        }]
    elif rule_template == 'content':
        if 'pattern' not in req_obj:
            raise InvalidRuleException("Content rule missing 'pattern'")
        pat = req_obj['pattern']

        conditions = [{
            'kind': 'event_match',
            'key': 'content.body',
            'pattern': pat
        }]
    else:
        raise InvalidRuleException("Unknown rule template: %s" % (rule_template,))

    if 'actions' not in req_obj:
        raise InvalidRuleException("No actions found")
    actions = req_obj['actions']

    _check_actions(actions)

    return conditions, actions


def _check_actions(actions):
    if not isinstance(actions, list):
        raise InvalidRuleException("No actions found")

    for a in actions:
        if a in ['notify', 'dont_notify', 'coalesce']:
            pass
        elif isinstance(a, dict) and 'set_tweak' in a:
            pass
        else:
            raise InvalidRuleException("Unrecognised action")


def _add_empty_priority_class_arrays(d):
    for pc in PRIORITY_CLASS_MAP.keys():
        d[pc] = []
    return d


def _filter_ruleset_with_path(ruleset, path):
    if path == []:
        raise UnrecognizedRequestError(
            PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
        )

    if path[0] == '':
        return ruleset
    template_kind = path[0]
    if template_kind not in ruleset:
        raise UnrecognizedRequestError()
    path = path[1:]
    if path == []:
        raise UnrecognizedRequestError(
            PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
        )
    if path[0] == '':
        return ruleset[template_kind]
    rule_id = path[0]

    the_rule = None
    for r in ruleset[template_kind]:
        if r['rule_id'] == rule_id:
            the_rule = r
    if the_rule is None:
        raise NotFoundError

    path = path[1:]
    if len(path) == 0:
        return the_rule

    attr = path[0]
    if attr in the_rule:
        # Make sure we return a JSON object as the attribute may be a
        # JSON value.
        return {attr: the_rule[attr]}
    else:
        raise UnrecognizedRequestError()


def _priority_class_from_spec(spec):
    if spec['template'] not in PRIORITY_CLASS_MAP.keys():
        raise InvalidRuleException("Unknown template: %s" % (spec['template']))
    pc = PRIORITY_CLASS_MAP[spec['template']]

    return pc


def _priority_class_to_template_name(pc):
    return PRIORITY_CLASS_INVERSE_MAP[pc]


def _rule_to_template(rule):
    unscoped_rule_id = None
    if 'rule_id' in rule:
        unscoped_rule_id = _rule_id_from_namespaced(rule['rule_id'])

    template_name = _priority_class_to_template_name(rule['priority_class'])
    if template_name in ['override', 'underride']:
        templaterule = {k: rule[k] for k in ["conditions", "actions"]}
    elif template_name in ["sender", "room"]:
        templaterule = {'actions': rule['actions']}
        unscoped_rule_id = rule['conditions'][0]['pattern']
    elif template_name == 'content':
        if len(rule["conditions"]) != 1:
            return None
        thecond = rule["conditions"][0]
        if "pattern" not in thecond:
            return None
        templaterule = {'actions': rule['actions']}
        templaterule["pattern"] = thecond["pattern"]

    if unscoped_rule_id:
            templaterule['rule_id'] = unscoped_rule_id
    if 'default' in rule:
        templaterule['default'] = rule['default']
    return templaterule


def _namespaced_rule_id_from_spec(spec):
    return _namespaced_rule_id(spec, spec['rule_id'])


def _namespaced_rule_id(spec, rule_id):
    return "global/%s/%s" % (spec['template'], rule_id)


def _rule_id_from_namespaced(in_rule_id):
    return in_rule_id.split('/')[-1]


class InvalidRuleException(Exception):
    pass


# XXX: C+ped from rest/room.py - surely this should be common?
def _parse_json(request):
    try:
        content = json.loads(request.content.read())
        return content
    except ValueError:
        raise SynapseError(400, "Content not JSON.", errcode=Codes.NOT_JSON)


def register_servlets(hs, http_server):
    PushRuleRestServlet(hs).register(http_server)