MatrixSynapse/synapse/rest/client/push_rule.py

355 lines
12 KiB
Python
Raw Normal View History

# 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.
2015-02-10 17:30:48 +01:00
from synapse.api.errors import (
2018-07-09 08:09:20 +02:00
NotFoundError,
StoreError,
SynapseError,
UnrecognizedRequestError,
2015-02-10 17:30:48 +01:00
)
2019-06-20 11:32:02 +02:00
from synapse.http.servlet import (
RestServlet,
parse_json_value_from_request,
parse_string,
)
from synapse.push.baserules import BASE_RULE_IDS, NEW_RULE_IDS
2018-07-09 08:09:20 +02:00
from synapse.push.clientformat import format_push_rules_for_user
from synapse.push.rulekinds import PRIORITY_CLASS_MAP
from synapse.rest.client._base import client_patterns
2018-07-09 08:09:20 +02:00
from synapse.storage.push_rule import InconsistentRuleException, RuleNotFoundException
class PushRuleRestServlet(RestServlet):
PATTERNS = client_patterns("/(?P<path>pushrules/.*)$", v1=True)
2015-01-28 15:26:03 +01:00
SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR = (
2019-06-20 11:32:02 +02:00
"Unrecognised request: You probably wanted a trailing slash"
)
2016-03-03 15:57:45 +01:00
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
2016-03-03 15:57:45 +01:00
self.store = hs.get_datastore()
self.notifier = hs.get_notifier()
self._is_worker = hs.config.worker_app is not None
2016-03-03 15:57:45 +01:00
2020-08-06 11:52:26 +02:00
self._users_new_default_push_rules = hs.config.users_new_default_push_rules
2019-12-05 16:53:06 +01:00
async def on_PUT(self, request, path):
if self._is_worker:
raise Exception("Cannot handle PUT /push_rules on worker")
spec = _rule_spec_from_path(path.split("/"))
try:
2015-01-23 18:07:06 +01:00
priority_class = _priority_class_from_spec(spec)
except InvalidRuleException as e:
2018-09-12 12:41:31 +02:00
raise SynapseError(400, str(e))
2019-12-05 16:53:06 +01:00
requester = await self.auth.get_user_by_req(request)
2019-06-20 11:32:02 +02:00
if "/" in spec["rule_id"] or "\\" in spec["rule_id"]:
raise SynapseError(400, "rule_id may not contain slashes")
content = parse_json_value_from_request(request)
2016-03-03 15:57:45 +01:00
user_id = requester.user.to_string()
2019-06-20 11:32:02 +02:00
if "attr" in spec:
2019-12-05 16:53:06 +01:00
await self.set_rule_attr(user_id, spec, content)
2016-03-03 15:57:45 +01:00
self.notify_user(user_id)
return 200, {}
2019-06-20 11:32:02 +02:00
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(
2019-06-20 11:32:02 +02:00
spec["template"], spec["rule_id"], content
)
except InvalidRuleException as e:
2018-09-12 12:41:31 +02:00
raise SynapseError(400, str(e))
before = parse_string(request, "before")
if before:
before = _namespaced_rule_id(spec, before)
after = parse_string(request, "after")
if after:
after = _namespaced_rule_id(spec, after)
try:
2019-12-05 16:53:06 +01:00
await self.store.add_push_rule(
2016-03-03 15:57:45 +01:00
user_id=user_id,
rule_id=_namespaced_rule_id_from_spec(spec),
priority_class=priority_class,
conditions=conditions,
actions=actions,
before=before,
2019-06-20 11:32:02 +02:00
after=after,
)
2016-03-03 15:57:45 +01:00
self.notify_user(user_id)
except InconsistentRuleException as e:
2018-09-12 12:41:31 +02:00
raise SynapseError(400, str(e))
except RuleNotFoundException as e:
2018-09-12 12:41:31 +02:00
raise SynapseError(400, str(e))
return 200, {}
2019-12-05 16:53:06 +01:00
async def on_DELETE(self, request, path):
if self._is_worker:
raise Exception("Cannot handle DELETE /push_rules on worker")
spec = _rule_spec_from_path(path.split("/"))
2015-01-23 18:49:37 +01:00
2019-12-05 16:53:06 +01:00
requester = await self.auth.get_user_by_req(request)
2016-03-03 15:57:45 +01:00
user_id = requester.user.to_string()
2015-01-23 18:49:37 +01:00
namespaced_rule_id = _namespaced_rule_id_from_spec(spec)
2015-01-23 18:49:37 +01:00
try:
2019-12-05 16:53:06 +01:00
await self.store.delete_push_rule(user_id, namespaced_rule_id)
2016-03-03 15:57:45 +01:00
self.notify_user(user_id)
return 200, {}
except StoreError as e:
if e.code == 404:
raise NotFoundError()
else:
raise
2015-01-23 18:49:37 +01:00
2019-12-05 16:53:06 +01:00
async def on_GET(self, request, path):
requester = await self.auth.get_user_by_req(request)
2016-03-03 15:57:45 +01:00
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
2019-12-05 16:53:06 +01:00
rules = await self.store.get_push_rules_for_user(user_id)
rules = format_push_rules_for_user(requester.user, rules)
path = path.split("/")[1:]
if path == []:
# we're a reference impl: pedantry is our job.
2015-01-29 17:10:35 +01:00
raise UnrecognizedRequestError(
PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
)
2019-06-20 11:32:02 +02:00
if path[0] == "":
return 200, rules
2019-06-20 11:32:02 +02:00
elif path[0] == "global":
result = _filter_ruleset_with_path(rules["global"], path[1:])
return 200, result
else:
raise UnrecognizedRequestError()
2016-03-03 15:57:45 +01:00
def notify_user(self, user_id):
stream_id = self.store.get_max_push_rules_stream_id()
2019-06-20 11:32:02 +02:00
self.notifier.on_new_event("push_rules_key", stream_id, users=[user_id])
2016-03-03 15:57:45 +01:00
async def set_rule_attr(self, user_id, spec, val):
if spec["attr"] not in ("enabled", "actions"):
# for the sake of potential future expansion, shouldn't report
# 404 in the case of an unknown request so check it corresponds to
# a known attribute first.
raise UnrecognizedRequestError()
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 NotFoundError("Unknown rule %s" % (namespaced_rule_id,))
2019-06-20 11:32:02 +02:00
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")
return await self.store.set_push_rule_enabled(
user_id, namespaced_rule_id, val, is_default_rule
)
2019-06-20 11:32:02 +02:00
elif spec["attr"] == "actions":
actions = val.get("actions")
_check_actions(actions)
namespaced_rule_id = _namespaced_rule_id_from_spec(spec)
2019-06-20 11:32:02 +02:00
rule_id = spec["rule_id"]
is_default_rule = rule_id.startswith(".")
if is_default_rule:
2020-08-06 11:52:26 +02:00
if user_id in self._users_new_default_push_rules:
rule_ids = NEW_RULE_IDS
else:
rule_ids = BASE_RULE_IDS
if namespaced_rule_id not in rule_ids:
raise SynapseError(404, "Unknown rule %r" % (namespaced_rule_id,))
return await self.store.set_push_rule_actions(
user_id, namespaced_rule_id, actions, is_default_rule
)
else:
raise UnrecognizedRequestError()
2015-03-02 16:58:12 +01:00
def _rule_spec_from_path(path):
2018-12-04 12:44:02 +01:00
"""Turn a sequence of path components into a rule spec
Args:
path (sequence[unicode]): the URL path components.
Returns:
dict: rule spec dict, containing scope/template/rule_id entries,
and possibly attr.
Raises:
UnrecognizedRequestError if the path components cannot be parsed.
"""
if len(path) < 2:
raise UnrecognizedRequestError()
2019-06-20 11:32:02 +02:00
if path[0] != "pushrules":
raise UnrecognizedRequestError()
2018-12-04 12:44:02 +01:00
scope = path[1]
path = path[2:]
2019-06-20 11:32:02 +02:00
if scope != "global":
raise UnrecognizedRequestError()
if len(path) == 0:
raise UnrecognizedRequestError()
2018-12-04 12:44:02 +01:00
template = path[0]
path = path[1:]
if len(path) == 0 or len(path[0]) == 0:
raise UnrecognizedRequestError()
2018-12-04 12:44:02 +01:00
rule_id = path[0]
2019-06-20 11:32:02 +02:00
spec = {"scope": scope, "template": template, "rule_id": rule_id}
path = path[1:]
if len(path) > 0 and len(path[0]) > 0:
2019-06-20 11:32:02 +02:00
spec["attr"] = path[0]
return spec
def _rule_tuple_from_request_object(rule_template, rule_id, req_obj):
2019-06-20 11:32:02 +02:00
if rule_template in ["override", "underride"]:
if "conditions" not in req_obj:
raise InvalidRuleException("Missing 'conditions'")
2019-06-20 11:32:02 +02:00
conditions = req_obj["conditions"]
for c in conditions:
2019-06-20 11:32:02 +02:00
if "kind" not in c:
raise InvalidRuleException("Condition without 'kind'")
2019-06-20 11:32:02 +02:00
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'")
2019-06-20 11:32:02 +02:00
pat = req_obj["pattern"]
2019-06-20 11:32:02 +02:00
conditions = [{"kind": "event_match", "key": "content.body", "pattern": pat}]
else:
raise InvalidRuleException("Unknown rule template: %s" % (rule_template,))
2019-06-20 11:32:02 +02:00
if "actions" not in req_obj:
raise InvalidRuleException("No actions found")
2019-06-20 11:32:02 +02:00
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
2019-06-20 11:32:02 +02:00
elif isinstance(a, dict) and "set_tweak" in a:
pass
else:
raise InvalidRuleException("Unrecognised action")
def _filter_ruleset_with_path(ruleset, path):
if path == []:
2015-01-29 17:10:35 +01:00
raise UnrecognizedRequestError(
PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
)
2019-06-20 11:32:02 +02:00
if path[0] == "":
return ruleset
template_kind = path[0]
if template_kind not in ruleset:
raise UnrecognizedRequestError()
path = path[1:]
if path == []:
2015-01-29 17:10:35 +01:00
raise UnrecognizedRequestError(
PushRuleRestServlet.SLIGHTLY_PEDANTIC_TRAILING_SLASH_ERROR
)
2019-06-20 11:32:02 +02:00
if path[0] == "":
return ruleset[template_kind]
rule_id = path[0]
the_rule = None
for r in ruleset[template_kind]:
2019-06-20 11:32:02 +02:00
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()
2015-01-29 17:10:35 +01:00
2015-01-23 18:07:06 +01:00
def _priority_class_from_spec(spec):
2019-06-20 11:32:02 +02:00
if spec["template"] not in PRIORITY_CLASS_MAP.keys():
raise InvalidRuleException("Unknown template: %s" % (spec["template"]))
pc = PRIORITY_CLASS_MAP[spec["template"]]
2015-01-23 18:07:06 +01:00
return pc
2015-01-29 17:10:35 +01:00
def _namespaced_rule_id_from_spec(spec):
2019-06-20 11:32:02 +02:00
return _namespaced_rule_id(spec, spec["rule_id"])
def _namespaced_rule_id(spec, rule_id):
2019-06-20 11:32:02 +02:00
return "global/%s/%s" % (spec["template"], rule_id)
class InvalidRuleException(Exception):
pass
def register_servlets(hs, http_server):
PushRuleRestServlet(hs).register(http_server)