Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Add a module API to allow modules to edit push rule actions (#12406)
Browse files Browse the repository at this point in the history
Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
  • Loading branch information
babolivier and richvdh authored Apr 27, 2022
1 parent d743b25 commit 5ef673d
Show file tree
Hide file tree
Showing 8 changed files with 319 additions and 104 deletions.
1 change: 1 addition & 0 deletions changelog.d/12406.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add a module API to allow modules to change actions for existing push rules of local users.
138 changes: 138 additions & 0 deletions synapse/handlers/push_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# 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 TYPE_CHECKING, List, Optional, Union

import attr

from synapse.api.errors import SynapseError, UnrecognizedRequestError
from synapse.push.baserules import BASE_RULE_IDS
from synapse.storage.push_rule import RuleNotFoundException
from synapse.types import JsonDict

if TYPE_CHECKING:
from synapse.server import HomeServer


@attr.s(slots=True, frozen=True, auto_attribs=True)
class RuleSpec:
scope: str
template: str
rule_id: str
attr: Optional[str]


class PushRulesHandler:
"""A class to handle changes in push rules for users."""

def __init__(self, hs: "HomeServer"):
self._notifier = hs.get_notifier()
self._main_store = hs.get_datastores().main

async def set_rule_attr(
self, user_id: str, spec: RuleSpec, val: Union[bool, JsonDict]
) -> None:
"""Set an attribute (enabled or actions) on an existing push rule.
Notifies listeners (e.g. sync handler) of the change.
Args:
user_id: the user for which to modify the push rule.
spec: the spec of the push rule to modify.
val: the value to change the attribute to.
Raises:
RuleNotFoundException if the rule being modified doesn't exist.
SynapseError(400) if the value is malformed.
UnrecognizedRequestError if the attribute to change is unknown.
InvalidRuleException if we're trying to change the actions on a rule but
the provided actions aren't compliant with the spec.
"""
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 = f"global/{spec.template}/{spec.rule_id}"
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 RuleNotFoundException("Unknown rule %r" % (namespaced_rule_id,))
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")
await self._main_store.set_push_rule_enabled(
user_id, namespaced_rule_id, val, is_default_rule
)
elif spec.attr == "actions":
if not isinstance(val, dict):
raise SynapseError(400, "Value must be a dict")
actions = val.get("actions")
if not isinstance(actions, list):
raise SynapseError(400, "Value for 'actions' must be dict")
check_actions(actions)
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 RuleNotFoundException(
"Unknown rule %r" % (namespaced_rule_id,)
)
await self._main_store.set_push_rule_actions(
user_id, namespaced_rule_id, actions, is_default_rule
)
else:
raise UnrecognizedRequestError()

self.notify_user(user_id)

def notify_user(self, user_id: str) -> None:
"""Notify listeners about a push rule change.
Args:
user_id: the user ID the change is for.
"""
stream_id = self._main_store.get_max_push_rules_stream_id()
self._notifier.on_new_event("push_rules_key", stream_id, users=[user_id])


def check_actions(actions: List[Union[str, JsonDict]]) -> None:
"""Check if the given actions are spec compliant.
Args:
actions: the actions to check.
Raises:
InvalidRuleException if the rules aren't compliant with the spec.
"""
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 %s" % a)


class InvalidRuleException(Exception):
pass
64 changes: 64 additions & 0 deletions synapse/module_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
ON_LOGGED_OUT_CALLBACK,
AuthHandler,
)
from synapse.handlers.push_rules import RuleSpec, check_actions
from synapse.http.client import SimpleHttpClient
from synapse.http.server import (
DirectServeHtmlResource,
Expand Down Expand Up @@ -195,6 +196,7 @@ def __init__(self, hs: "HomeServer", auth_handler: AuthHandler) -> None:
self._clock: Clock = hs.get_clock()
self._registration_handler = hs.get_registration_handler()
self._send_email_handler = hs.get_send_email_handler()
self._push_rules_handler = hs.get_push_rules_handler()
self.custom_template_dir = hs.config.server.custom_template_directory

try:
Expand Down Expand Up @@ -1352,6 +1354,68 @@ async def store_remote_3pid_association(
"""
await self._store.add_user_bound_threepid(user_id, medium, address, id_server)

def check_push_rule_actions(
self, actions: List[Union[str, Dict[str, str]]]
) -> None:
"""Checks if the given push rule actions are valid according to the Matrix
specification.
See https://spec.matrix.org/v1.2/client-server-api/#actions for the list of valid
actions.
Added in Synapse v1.58.0.
Args:
actions: the actions to check.
Raises:
synapse.module_api.errors.InvalidRuleException if the actions are invalid.
"""
check_actions(actions)

async def set_push_rule_action(
self,
user_id: str,
scope: str,
kind: str,
rule_id: str,
actions: List[Union[str, Dict[str, str]]],
) -> None:
"""Changes the actions of an existing push rule for the given user.
See https://spec.matrix.org/v1.2/client-server-api/#push-rules for more
information about push rules and their syntax.
Can only be called on the main process.
Added in Synapse v1.58.0.
Args:
user_id: the user for which to change the push rule's actions.
scope: the push rule's scope, currently only "global" is allowed.
kind: the push rule's kind.
rule_id: the push rule's identifier.
actions: the actions to run when the rule's conditions match.
Raises:
RuntimeError if this method is called on a worker or `scope` is invalid.
synapse.module_api.errors.RuleNotFoundException if the rule being modified
can't be found.
synapse.module_api.errors.InvalidRuleException if the actions are invalid.
"""
if self.worker_app is not None:
raise RuntimeError("module tried to change push rule actions on a worker")

if scope != "global":
raise RuntimeError(
"invalid scope %s, only 'global' is currently allowed" % scope
)

spec = RuleSpec(scope, kind, rule_id, "actions")
await self._push_rules_handler.set_rule_attr(
user_id, spec, {"actions": actions}
)


class PublicRoomListManager:
"""Contains methods for adding to, removing from and querying whether a room
Expand Down
4 changes: 4 additions & 0 deletions synapse/module_api/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@
SynapseError,
)
from synapse.config._base import ConfigError
from synapse.handlers.push_rules import InvalidRuleException
from synapse.storage.push_rule import RuleNotFoundException

__all__ = [
"InvalidClientCredentialsError",
"RedirectException",
"SynapseError",
"ConfigError",
"InvalidRuleException",
"RuleNotFoundException",
]
Loading

0 comments on commit 5ef673d

Please sign in to comment.