From 231afe464aa9d5313de29ff569a1e2fea842fcb5 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Mon, 22 Sep 2014 13:42:52 +0100 Subject: [PATCH 01/18] Add a deletions table --- synapse/storage/schema/delta/v4.sql | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 synapse/storage/schema/delta/v4.sql diff --git a/synapse/storage/schema/delta/v4.sql b/synapse/storage/schema/delta/v4.sql new file mode 100644 index 000000000..1652ef292 --- /dev/null +++ b/synapse/storage/schema/delta/v4.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS deletions ( + event_id TEXT NOT NULL, + deletes TEXT NOT NULL, + CONSTRAINT ev_uniq UNIQUE (event_id) +); From 78af6bbb981c41e5509c99454deb7205c31bf964 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Tue, 23 Sep 2014 15:28:32 +0100 Subject: [PATCH 02/18] Add m.room.deletion. If an event is deleted it will be returned to clients 'pruned', i.e. all client specified keys will be removed. --- synapse/api/events/__init__.py | 6 +++-- synapse/api/events/factory.py | 4 ++- synapse/api/events/room.py | 9 +++++++ synapse/rest/room.py | 38 ++++++++++++++++++++++++++++- synapse/storage/__init__.py | 29 +++++++++++++++++++--- synapse/storage/_base.py | 30 ++++++++++++++++++++--- synapse/storage/roommember.py | 13 +++++++--- synapse/storage/schema/delta/v4.sql | 6 +++-- synapse/storage/stream.py | 30 +++++++++++++++++++---- 9 files changed, 144 insertions(+), 21 deletions(-) diff --git a/synapse/api/events/__init__.py b/synapse/api/events/__init__.py index 0cee19685..910c990b3 100644 --- a/synapse/api/events/__init__.py +++ b/synapse/api/events/__init__.py @@ -22,7 +22,7 @@ def serialize_event(hs, e): if not isinstance(e, SynapseEvent): return e - d = e.get_dict() + d = {k: v for k, v in e.get_dict().items() if v is not None or v is not False} if "age_ts" in d: d["age"] = int(hs.get_clock().time_msec()) - d["age_ts"] del d["age_ts"] @@ -58,17 +58,19 @@ class SynapseEvent(JsonEncodedObject): "required_power_level", "age_ts", "prev_content", + "prev_state", + "pruned", ] internal_keys = [ "is_state", "prev_events", - "prev_state", "depth", "destinations", "origin", "outlier", "power_level", + "deleted", ] required_keys = [ diff --git a/synapse/api/events/factory.py b/synapse/api/events/factory.py index d3d96d73e..c65ea8372 100644 --- a/synapse/api/events/factory.py +++ b/synapse/api/events/factory.py @@ -17,7 +17,8 @@ from synapse.api.events.room import ( RoomTopicEvent, MessageEvent, RoomMemberEvent, FeedbackEvent, InviteJoinEvent, RoomConfigEvent, RoomNameEvent, GenericEvent, RoomPowerLevelsEvent, RoomJoinRulesEvent, RoomOpsPowerLevelsEvent, - RoomCreateEvent, RoomAddStateLevelEvent, RoomSendEventLevelEvent + RoomCreateEvent, RoomAddStateLevelEvent, RoomSendEventLevelEvent, + RoomDeletionEvent, ) from synapse.util.stringutils import random_string @@ -39,6 +40,7 @@ class EventFactory(object): RoomAddStateLevelEvent, RoomSendEventLevelEvent, RoomOpsPowerLevelsEvent, + RoomDeletionEvent, ] def __init__(self, hs): diff --git a/synapse/api/events/room.py b/synapse/api/events/room.py index 3a4dbc58c..986139555 100644 --- a/synapse/api/events/room.py +++ b/synapse/api/events/room.py @@ -180,3 +180,12 @@ class RoomAliasesEvent(SynapseStateEvent): def get_content_template(self): return {} + + +class RoomDeletionEvent(SynapseEvent): + TYPE = "m.room.deletion" + + valid_keys = SynapseEvent.valid_keys + ["deletes"] + + def get_content_template(self): + return {} diff --git a/synapse/rest/room.py b/synapse/rest/room.py index ecb1e346d..85a1d2eae 100644 --- a/synapse/rest/room.py +++ b/synapse/rest/room.py @@ -19,7 +19,7 @@ from twisted.internet import defer from base import RestServlet, client_path_pattern from synapse.api.errors import SynapseError, Codes from synapse.streams.config import PaginationConfig -from synapse.api.events.room import RoomMemberEvent +from synapse.api.events.room import RoomMemberEvent, RoomDeletionEvent from synapse.api.constants import Membership import json @@ -430,6 +430,41 @@ class RoomMembershipRestServlet(RestServlet): self.txns.store_client_transaction(request, txn_id, response) defer.returnValue(response) +class RoomDeleteEventRestServlet(RestServlet): + def register(self, http_server): + PATTERN = ("/rooms/(?P[^/]*)/delete/(?P[^/]*)") + register_txn_path(self, PATTERN, http_server) + + @defer.inlineCallbacks + def on_POST(self, request, room_id, event_id): + user = yield self.auth.get_user_by_req(request) + content = _parse_json(request) + + event = self.event_factory.create_event( + etype=RoomDeletionEvent.TYPE, + room_id=urllib.unquote(room_id), + user_id=user.to_string(), + content=content, + deletes=event_id, + ) + + msg_handler = self.handlers.message_handler + yield msg_handler.send_message(event) + + defer.returnValue((200, {"event_id": event.event_id})) + + @defer.inlineCallbacks + def on_PUT(self, request, room_id, event_id, txn_id): + try: + defer.returnValue(self.txns.get_client_transaction(request, txn_id)) + except KeyError: + pass + + response = yield self.on_POST(request, room_id, event_id) + + self.txns.store_client_transaction(request, txn_id, response) + defer.returnValue(response) + def _parse_json(request): try: @@ -485,3 +520,4 @@ def register_servlets(hs, http_server): PublicRoomListRestServlet(hs).register(http_server) RoomStateRestServlet(hs).register(http_server) RoomInitialSyncRestServlet(hs).register(http_server) + RoomDeleteEventRestServlet(hs).register(http_server) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index 66658f672..672ed6971 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -24,6 +24,7 @@ from synapse.api.events.room import ( RoomAddStateLevelEvent, RoomSendEventLevelEvent, RoomOpsPowerLevelsEvent, + RoomDeletionEvent, ) from synapse.util.logutils import log_function @@ -61,7 +62,7 @@ SCHEMAS = [ # Remember to update this number every time an incompatible change is made to # database schema files, so the users will be informed on server restarts. -SCHEMA_VERSION = 3 +SCHEMA_VERSION = 4 class _RollbackButIsFineException(Exception): @@ -182,6 +183,8 @@ class DataStore(RoomMemberStore, RoomStore, self._store_send_event_level(txn, event) elif event.type == RoomOpsPowerLevelsEvent.TYPE: self._store_ops_level(txn, event) + elif event.type == RoomDeletionEvent.TYPE: + self._store_deletion(txn, event) vals = { "topological_ordering": event.depth, @@ -203,7 +206,7 @@ class DataStore(RoomMemberStore, RoomStore, unrec = { k: v for k, v in event.get_full_dict().items() - if k not in vals.keys() + if k not in vals.keys() and k is not "deleted" } vals["unrecognized_keys"] = json.dumps(unrec) @@ -241,14 +244,32 @@ class DataStore(RoomMemberStore, RoomStore, } ) + def _store_deletion(self, txn, event): + event_id = event.event_id + deletes = event.deletes + + # We check if this new delete deletes an old delete or has been + # deleted by a previous delete that we received out of order. + sql = "SELECT * FROM deletions WHERE event_id = ? OR deletes = ?" + txn.execute(sql, (deletes, event_id)) + + if txn.fetchall(): + sql = "DELETE FROM deletions WHERE event_id = ? OR deletes = ?" + txn.execute(sql, (deletes, event_id, )) + else: + sql = "INSERT INTO deletions (event_id, deletes) VALUES (?,?)" + txn.execute(sql, (event_id, deletes)) + @defer.inlineCallbacks def get_current_state(self, room_id, event_type=None, state_key=""): sql = ( - "SELECT e.* FROM events as e " + "SELECT e.*, (%(deleted)s) AS deleted FROM events as e " "INNER JOIN current_state_events as c ON e.event_id = c.event_id " "INNER JOIN state_events as s ON e.event_id = s.event_id " "WHERE c.room_id = ? " - ) + ) % { + "deleted": "e.event_id IN (SELECT deletes FROM deletions)", + } if event_type: sql += " AND s.type = ? AND s.state_key = ? " diff --git a/synapse/storage/_base.py b/synapse/storage/_base.py index 76ed7d06f..3aa610c85 100644 --- a/synapse/storage/_base.py +++ b/synapse/storage/_base.py @@ -17,6 +17,7 @@ import logging from twisted.internet import defer from synapse.api.errors import StoreError +from synapse.api.events.utils import prune_event from synapse.util.logutils import log_function import collections @@ -345,7 +346,7 @@ class SQLBaseStore(object): return self.runInteraction(func) def _parse_event_from_row(self, row_dict): - d = copy.deepcopy({k: v for k, v in row_dict.items() if v}) + d = copy.deepcopy({k: v for k, v in row_dict.items()}) d.pop("stream_ordering", None) d.pop("topological_ordering", None) @@ -373,8 +374,8 @@ class SQLBaseStore(object): sql = "SELECT * FROM events WHERE event_id = ?" for ev in events: - if hasattr(ev, "prev_state"): - # Load previous state_content. + if hasattr(ev, "prev_state"): + # Load previous state_content. # TODO: Should we be pulling this out above? cursor = txn.execute(sql, (ev.prev_state,)) prevs = self.cursor_to_dict(cursor) @@ -382,8 +383,31 @@ class SQLBaseStore(object): prev = self._parse_event_from_row(prevs[0]) ev.prev_content = prev.content + if not hasattr(ev, "deleted"): + logger.debug("Doesn't have deleted key: %s", ev) + ev.deleted = self._has_been_deleted_txn(txn, ev) + + if ev.deleted: + # Get the deletion event. + sql = "SELECT * FROM events WHERE event_id = ?" + txn.execute(sql, (ev.deleted,)) + + del_evs = self._parse_events_txn( + txn, self.cursor_to_dict(txn) + ) + + if del_evs: + prune_event(ev) + ev.pruned = del_evs[0] + return events + def _has_been_deleted_txn(self, txn, event): + sql = "SELECT * FROM deletions WHERE deletes = ?" + txn.execute(sql, (event.event_id,)) + return len(txn.fetchall()) > 0 + + class Table(object): """ A base class used to store information about a particular table. """ diff --git a/synapse/storage/roommember.py b/synapse/storage/roommember.py index 04b4067d0..97222da57 100644 --- a/synapse/storage/roommember.py +++ b/synapse/storage/roommember.py @@ -182,14 +182,21 @@ class RoomMemberStore(SQLBaseStore): ) def _get_members_query_txn(self, txn, where_clause, where_values): + del_sql = ( + "SELECT event_id FROM deletions WHERE deletes = e.event_id" + ) + sql = ( - "SELECT e.* FROM events as e " + "SELECT e.*, (%(deleted)s) AS deleted FROM events as e " "INNER JOIN room_memberships as m " "ON e.event_id = m.event_id " "INNER JOIN current_state_events as c " "ON m.event_id = c.event_id " - "WHERE %s " - ) % (where_clause,) + "WHERE %(where)s " + ) % { + "deleted": del_sql, + "where": where_clause, + } txn.execute(sql, where_values) rows = self.cursor_to_dict(txn) diff --git a/synapse/storage/schema/delta/v4.sql b/synapse/storage/schema/delta/v4.sql index 1652ef292..2e2635317 100644 --- a/synapse/storage/schema/delta/v4.sql +++ b/synapse/storage/schema/delta/v4.sql @@ -1,5 +1,7 @@ CREATE TABLE IF NOT EXISTS deletions ( event_id TEXT NOT NULL, - deletes TEXT NOT NULL, - CONSTRAINT ev_uniq UNIQUE (event_id) + deletes TEXT NOT NULL ); + +CREATE INDEX IF NOT EXISTS deletions_event_id ON deletions (event_id); +CREATE INDEX IF NOT EXISTS deletions_deletes ON deletions (deletes); diff --git a/synapse/storage/stream.py b/synapse/storage/stream.py index a76fecf24..aaac0aae3 100644 --- a/synapse/storage/stream.py +++ b/synapse/storage/stream.py @@ -157,6 +157,10 @@ class StreamStore(SQLBaseStore): "WHERE m.user_id = ? " ) + del_sql = ( + "SELECT event_id FROM deletions WHERE deletes = e.event_id" + ) + if limit: limit = max(limit, MAX_STREAM_SIZE) else: @@ -171,13 +175,14 @@ class StreamStore(SQLBaseStore): return sql = ( - "SELECT * FROM events as e WHERE " + "SELECT *, (%(deleted)s) AS deleted FROM events AS e WHERE " "((room_id IN (%(current)s)) OR " "(event_id IN (%(invites)s))) " "AND e.stream_ordering > ? AND e.stream_ordering <= ? " "AND e.outlier = 0 " "ORDER BY stream_ordering ASC LIMIT %(limit)d " ) % { + "deleted": del_sql, "current": current_room_membership_sql, "invites": membership_sql, "limit": limit @@ -224,11 +229,20 @@ class StreamStore(SQLBaseStore): else: limit_str = "" + del_sql = ( + "SELECT event_id FROM deletions WHERE deletes = events.event_id" + ) + sql = ( - "SELECT * FROM events " + "SELECT *, (%(deleted)s) AS deleted FROM events " "WHERE outlier = 0 AND room_id = ? AND %(bounds)s " "ORDER BY topological_ordering %(order)s, stream_ordering %(order)s %(limit)s " - ) % {"bounds": bounds, "order": order, "limit": limit_str} + ) % { + "deleted": del_sql, + "bounds": bounds, + "order": order, + "limit": limit_str + } rows = yield self._execute_and_decode( sql, @@ -257,11 +271,17 @@ class StreamStore(SQLBaseStore): with_feedback=False): # TODO (erikj): Handle compressed feedback + del_sql = ( + "SELECT event_id FROM deletions WHERE deletes = events.event_id" + ) + sql = ( - "SELECT * FROM events " + "SELECT *, (%(deleted)s) AS deleted FROM events " "WHERE room_id = ? AND stream_ordering <= ? " "ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ? " - ) + ) % { + "deleted": del_sql, + } rows = yield self._execute_and_decode( sql, From b99f6eb904c9614aacd3532196be410341d0640b Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Tue, 23 Sep 2014 15:29:27 +0100 Subject: [PATCH 03/18] Make sure we don't persist the 'pruned' key --- synapse/storage/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index 672ed6971..46d420b63 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -206,7 +206,7 @@ class DataStore(RoomMemberStore, RoomStore, unrec = { k: v for k, v in event.get_full_dict().items() - if k not in vals.keys() and k is not "deleted" + if k not in vals.keys() and k not in ["deleted", "pruned"] } vals["unrecognized_keys"] = json.dumps(unrec) From 932b376b4e3d1992268274f25e2343f6e81d93f8 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Tue, 23 Sep 2014 15:37:32 +0100 Subject: [PATCH 04/18] Add prune_event method --- synapse/api/events/utils.py | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 synapse/api/events/utils.py diff --git a/synapse/api/events/utils.py b/synapse/api/events/utils.py new file mode 100644 index 000000000..dfefb2662 --- /dev/null +++ b/synapse/api/events/utils.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Copyright 2014 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 .room import RoomMemberEvent + +def prune_event(event): + """ Prunes the given event of all keys we don't know about or think could + potentially be dodgy. + + This is used when we "delete" an event. We want to remove all fields that + the user has specified, but we do want to keep necessary information like + type, state_key etc. + """ + + # Remove all extraneous fields. + event.unrecognized_keys = {} + + if event.type == RoomMemberEvent.TYPE: + new_content = { + "membership": event.content["membership"] + } + else: + new_content = {} + + event.content = new_content + + return event From bc250a6afa68b7584f3b7b3aacb919df406da75a Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Tue, 23 Sep 2014 17:36:17 +0100 Subject: [PATCH 05/18] SYN-12: Implement auth for deletion by adding a 'delete_level' on the ops levels event SYN-12 # comment Auth has been added. --- synapse/api/auth.py | 34 ++++++++++++++++++++++++++--- synapse/handlers/room.py | 1 + synapse/storage/room.py | 10 ++++++--- synapse/storage/schema/delta/v4.sql | 4 ++++ 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/synapse/api/auth.py b/synapse/api/auth.py index 8f32191b5..fb14d9a2b 100644 --- a/synapse/api/auth.py +++ b/synapse/api/auth.py @@ -19,7 +19,9 @@ from twisted.internet import defer from synapse.api.constants import Membership, JoinRules from synapse.api.errors import AuthError, StoreError, Codes, SynapseError -from synapse.api.events.room import RoomMemberEvent, RoomPowerLevelsEvent +from synapse.api.events.room import ( + RoomMemberEvent, RoomPowerLevelsEvent, RoomDeletionEvent, +) from synapse.util.logutils import log_function import logging @@ -70,6 +72,9 @@ class Auth(object): if event.type == RoomPowerLevelsEvent.TYPE: yield self._check_power_levels(event) + if event.type == RoomDeletionEvent.TYPE: + yield self._check_deletion(event) + defer.returnValue(True) else: raise AuthError(500, "Unknown event: %s" % event) @@ -170,7 +175,7 @@ class Auth(object): event.room_id, event.user_id, ) - _, kick_level = yield self.store.get_ops_levels(event.room_id) + _, kick_level, _ = yield self.store.get_ops_levels(event.room_id) if kick_level: kick_level = int(kick_level) @@ -187,7 +192,7 @@ class Auth(object): event.user_id, ) - ban_level, _ = yield self.store.get_ops_levels(event.room_id) + ban_level, _, _ = yield self.store.get_ops_levels(event.room_id) if ban_level: ban_level = int(ban_level) @@ -321,6 +326,29 @@ class Auth(object): "You don't have permission to change that state" ) + @defer.inlineCallbacks + def _check_deletion(self, event): + user_level = yield self.store.get_power_level( + event.room_id, + event.user_id, + ) + + if user_level: + user_level = int(user_level) + else: + user_level = 0 + + _, _, delete_level = yield self.store.get_ops_levels(event.room_id) + + if not delete_level: + delete_level = 50 + + if user_level < delete_level: + raise AuthError( + 403, + "You don't have permission to delete events" + ) + @defer.inlineCallbacks def _check_power_levels(self, event): for k, v in event.content.items(): diff --git a/synapse/handlers/room.py b/synapse/handlers/room.py index 5bc128043..18597c694 100644 --- a/synapse/handlers/room.py +++ b/synapse/handlers/room.py @@ -255,6 +255,7 @@ class RoomCreationHandler(BaseHandler): etype=RoomOpsPowerLevelsEvent.TYPE, ban_level=50, kick_level=50, + delete_level=50, ) return [ diff --git a/synapse/storage/room.py b/synapse/storage/room.py index 5adf8cdf1..b1239a0f1 100644 --- a/synapse/storage/room.py +++ b/synapse/storage/room.py @@ -27,7 +27,7 @@ import logging logger = logging.getLogger(__name__) -OpsLevel = collections.namedtuple("OpsLevel", ("ban_level", "kick_level")) +OpsLevel = collections.namedtuple("OpsLevel", ("ban_level", "kick_level", "delete_level")) class RoomStore(SQLBaseStore): @@ -189,7 +189,8 @@ class RoomStore(SQLBaseStore): def _get_ops_levels(self, txn, room_id): sql = ( - "SELECT ban_level, kick_level FROM room_ops_levels as r " + "SELECT ban_level, kick_level, delete_level " + "FROM room_ops_levels as r " "INNER JOIN current_state_events as c " "ON r.event_id = c.event_id " "WHERE c.room_id = ? " @@ -198,7 +199,7 @@ class RoomStore(SQLBaseStore): rows = txn.execute(sql, (room_id,)).fetchall() if len(rows) == 1: - return OpsLevel(rows[0][0], rows[0][1]) + return OpsLevel(rows[0][0], rows[0][1], rows[0][2]) else: return OpsLevel(None, None) @@ -326,6 +327,9 @@ class RoomStore(SQLBaseStore): if "ban_level" in event.content: content["ban_level"] = event.content["ban_level"] + if "delete_level" in event.content: + content["delete_level"] = event.content["delete_level"] + self._simple_insert_txn( txn, "room_ops_levels", diff --git a/synapse/storage/schema/delta/v4.sql b/synapse/storage/schema/delta/v4.sql index 2e2635317..fc8bb5ad8 100644 --- a/synapse/storage/schema/delta/v4.sql +++ b/synapse/storage/schema/delta/v4.sql @@ -5,3 +5,7 @@ CREATE TABLE IF NOT EXISTS deletions ( CREATE INDEX IF NOT EXISTS deletions_event_id ON deletions (event_id); CREATE INDEX IF NOT EXISTS deletions_deletes ON deletions (deletes); + +ALTER TABLE room_ops_levels ADD COLUMN delete_level INTEGER; + +PRAGMA user_version = 4; From efea61dc507e1e02f3ac17417bd735a9d750bd12 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Tue, 23 Sep 2014 17:40:58 +0100 Subject: [PATCH 06/18] Rename 'pruned' to 'pruned_because' --- synapse/api/events/__init__.py | 2 +- synapse/storage/__init__.py | 2 +- synapse/storage/_base.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/synapse/api/events/__init__.py b/synapse/api/events/__init__.py index 910c990b3..d68629209 100644 --- a/synapse/api/events/__init__.py +++ b/synapse/api/events/__init__.py @@ -59,7 +59,7 @@ class SynapseEvent(JsonEncodedObject): "age_ts", "prev_content", "prev_state", - "pruned", + "pruned_because", ] internal_keys = [ diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index 46d420b63..ac8ee89ab 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -206,7 +206,7 @@ class DataStore(RoomMemberStore, RoomStore, unrec = { k: v for k, v in event.get_full_dict().items() - if k not in vals.keys() and k not in ["deleted", "pruned"] + if k not in vals.keys() and k not in ["deleted", "pruned_because"] } vals["unrecognized_keys"] = json.dumps(unrec) diff --git a/synapse/storage/_base.py b/synapse/storage/_base.py index 3aa610c85..d64119a47 100644 --- a/synapse/storage/_base.py +++ b/synapse/storage/_base.py @@ -398,7 +398,7 @@ class SQLBaseStore(object): if del_evs: prune_event(ev) - ev.pruned = del_evs[0] + ev.pruned_because = del_evs[0] return events From 4354590a69d2a9b8cfb0dd1e1bc677c118e68be4 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 11:06:41 +0100 Subject: [PATCH 07/18] Add v4 deltas to current sql. --- synapse/storage/__init__.py | 1 + synapse/storage/schema/deletions.sql | 7 +++++++ synapse/storage/schema/im.sql | 3 ++- 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 synapse/storage/schema/deletions.sql diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index ac8ee89ab..4e8a54c8f 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -57,6 +57,7 @@ SCHEMAS = [ "presence", "im", "room_aliases", + "deletions", ] diff --git a/synapse/storage/schema/deletions.sql b/synapse/storage/schema/deletions.sql new file mode 100644 index 000000000..2e2635317 --- /dev/null +++ b/synapse/storage/schema/deletions.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS deletions ( + event_id TEXT NOT NULL, + deletes TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS deletions_event_id ON deletions (event_id); +CREATE INDEX IF NOT EXISTS deletions_deletes ON deletions (deletes); diff --git a/synapse/storage/schema/im.sql b/synapse/storage/schema/im.sql index 6ffea5131..649d54b81 100644 --- a/synapse/storage/schema/im.sql +++ b/synapse/storage/schema/im.sql @@ -150,7 +150,8 @@ CREATE TABLE IF NOT EXISTS room_ops_levels( event_id TEXT NOT NULL, room_id TEXT NOT NULL, ban_level INTEGER, - kick_level INTEGER + kick_level INTEGER, + delete_level INTEGER ); CREATE INDEX IF NOT EXISTS room_ops_levels_event_id ON room_ops_levels(event_id); From 3d2cca67620e630ba17dc14f8b7b92ff0fa92774 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 11:17:43 +0100 Subject: [PATCH 08/18] Fix test. --- tests/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/utils.py b/tests/utils.py index bc5d35e56..bb8e9964d 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -262,7 +262,7 @@ class MemoryDataStore(object): return defer.succeed("invite") def get_ops_levels(self, room_id): - return defer.succeed((5, 5)) + return defer.succeed((5, 5, 5)) def _format_call(args, kwargs): From 4e79b09dd97a1dda6b1ea87325302b95feb0a23e Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 11:37:06 +0100 Subject: [PATCH 09/18] Fill out the prune_event method. --- synapse/api/events/utils.py | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/synapse/api/events/utils.py b/synapse/api/events/utils.py index dfefb2662..3d8b9a1db 100644 --- a/synapse/api/events/utils.py +++ b/synapse/api/events/utils.py @@ -13,7 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .room import RoomMemberEvent +from .room import ( + RoomMemberEvent, RoomJoinRulesEvent, RoomPowerLevelsEvent, + RoomAddStateLevelEvent, RoomSendEventLevelEvent, RoomOpsPowerLevelsEvent, + RoomAliasesEvent, RoomCreateEvent, +) def prune_event(event): """ Prunes the given event of all keys we don't know about or think could @@ -27,12 +31,33 @@ def prune_event(event): # Remove all extraneous fields. event.unrecognized_keys = {} + new_content = {} + + def add_fields(*fields): + for field in fields: + if field in event.content: + new_content[field] = event.content[field] + if event.type == RoomMemberEvent.TYPE: - new_content = { - "membership": event.content["membership"] - } - else: - new_content = {} + add_fields("membership") + elif event.type == RoomCreateEvent.TYPE: + add_fields("creator") + elif event.type == RoomJoinRulesEvent.TYPE: + add_fields("join_rule") + elif event.type == RoomPowerLevelsEvent.TYPE: + # TODO: Actually check these are valid user_ids etc. + add_fields("default") + for k, v in event.content.items(): + if k.startswith("@") and isinstance(v, (int, long)): + new_content[k] = v + elif event.type == RoomAddStateLevelEvent.TYPE: + add_fields("level") + elif event.type == RoomSendEventLevelEvent.TYPE: + add_fields("level") + elif event.type == RoomOpsPowerLevelsEvent.TYPE: + add_fields("kick_level", "ban_level", "delete_level") + elif event.type == RoomAliasesEvent.TYPE: + add_fields("aliases") event.content = new_content From 1e6c5b205c95c1f6941688c13a15314100a8470d Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 13:29:20 +0100 Subject: [PATCH 10/18] Fix bug where we didn't correctly pull out the event_id of the deletion --- synapse/storage/__init__.py | 6 +++++- synapse/storage/_base.py | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index 4e8a54c8f..0d57073aa 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -263,13 +263,17 @@ class DataStore(RoomMemberStore, RoomStore, @defer.inlineCallbacks def get_current_state(self, room_id, event_type=None, state_key=""): + del_sql = ( + "SELECT event_id FROM deletions WHERE deletes = e.event_id" + ) + sql = ( "SELECT e.*, (%(deleted)s) AS deleted FROM events as e " "INNER JOIN current_state_events as c ON e.event_id = c.event_id " "INNER JOIN state_events as s ON e.event_id = s.event_id " "WHERE c.room_id = ? " ) % { - "deleted": "e.event_id IN (SELECT deletes FROM deletions)", + "deleted": del_sql, } if event_type: diff --git a/synapse/storage/_base.py b/synapse/storage/_base.py index d64119a47..444e7628d 100644 --- a/synapse/storage/_base.py +++ b/synapse/storage/_base.py @@ -403,9 +403,10 @@ class SQLBaseStore(object): return events def _has_been_deleted_txn(self, txn, event): - sql = "SELECT * FROM deletions WHERE deletes = ?" + sql = "SELECT event_id FROM deletions WHERE deletes = ?" txn.execute(sql, (event.event_id,)) - return len(txn.fetchall()) > 0 + result = txn.fetchone() + return result[0] if result else None class Table(object): From 7d9a84a445729e94b5f5aa445965b4e164442c7c Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 14:18:08 +0100 Subject: [PATCH 11/18] Make deleting deletes not undelete --- synapse/storage/__init__.py | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index 0d57073aa..accb4359b 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -246,20 +246,10 @@ class DataStore(RoomMemberStore, RoomStore, ) def _store_deletion(self, txn, event): - event_id = event.event_id - deletes = event.deletes - - # We check if this new delete deletes an old delete or has been - # deleted by a previous delete that we received out of order. - sql = "SELECT * FROM deletions WHERE event_id = ? OR deletes = ?" - txn.execute(sql, (deletes, event_id)) - - if txn.fetchall(): - sql = "DELETE FROM deletions WHERE event_id = ? OR deletes = ?" - txn.execute(sql, (deletes, event_id, )) - else: - sql = "INSERT INTO deletions (event_id, deletes) VALUES (?,?)" - txn.execute(sql, (event_id, deletes)) + txn.execute( + "INSERT INTO deletions (event_id, deletes) VALUES (?,?) OR IGNORE", + (event.event_id, event.deletes) + ) @defer.inlineCallbacks def get_current_state(self, room_id, event_type=None, state_key=""): From 70899d3ab29cd57301fb135130c940f312bfe482 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Wed, 24 Sep 2014 15:27:59 +0100 Subject: [PATCH 12/18] Rename deletions to redactions --- synapse/api/auth.py | 18 +++++++++--------- synapse/api/events/__init__.py | 4 ++-- synapse/api/events/factory.py | 4 ++-- synapse/api/events/room.py | 6 +++--- synapse/api/events/utils.py | 4 ++-- synapse/handlers/room.py | 2 +- synapse/rest/room.py | 12 ++++++------ synapse/storage/__init__.py | 23 ++++++++++++----------- synapse/storage/_base.py | 18 +++++++++--------- synapse/storage/room.py | 8 ++++---- synapse/storage/roommember.py | 6 +++--- synapse/storage/schema/deletions.sql | 7 ------- synapse/storage/schema/delta/v4.sql | 11 ++++++----- synapse/storage/schema/im.sql | 2 +- synapse/storage/schema/redactions.sql | 8 ++++++++ synapse/storage/stream.py | 18 +++++++++--------- 16 files changed, 77 insertions(+), 74 deletions(-) delete mode 100644 synapse/storage/schema/deletions.sql create mode 100644 synapse/storage/schema/redactions.sql diff --git a/synapse/api/auth.py b/synapse/api/auth.py index fb14d9a2b..9c65d47fb 100644 --- a/synapse/api/auth.py +++ b/synapse/api/auth.py @@ -20,7 +20,7 @@ from twisted.internet import defer from synapse.api.constants import Membership, JoinRules from synapse.api.errors import AuthError, StoreError, Codes, SynapseError from synapse.api.events.room import ( - RoomMemberEvent, RoomPowerLevelsEvent, RoomDeletionEvent, + RoomMemberEvent, RoomPowerLevelsEvent, RoomRedactionEvent, ) from synapse.util.logutils import log_function @@ -72,8 +72,8 @@ class Auth(object): if event.type == RoomPowerLevelsEvent.TYPE: yield self._check_power_levels(event) - if event.type == RoomDeletionEvent.TYPE: - yield self._check_deletion(event) + if event.type == RoomRedactionEvent.TYPE: + yield self._check_redaction(event) defer.returnValue(True) else: @@ -327,7 +327,7 @@ class Auth(object): ) @defer.inlineCallbacks - def _check_deletion(self, event): + def _check_redaction(self, event): user_level = yield self.store.get_power_level( event.room_id, event.user_id, @@ -338,15 +338,15 @@ class Auth(object): else: user_level = 0 - _, _, delete_level = yield self.store.get_ops_levels(event.room_id) + _, _, redact_level = yield self.store.get_ops_levels(event.room_id) - if not delete_level: - delete_level = 50 + if not redact_level: + redact_level = 50 - if user_level < delete_level: + if user_level < redact_level: raise AuthError( 403, - "You don't have permission to delete events" + "You don't have permission to redact events" ) @defer.inlineCallbacks diff --git a/synapse/api/events/__init__.py b/synapse/api/events/__init__.py index d68629209..0ceb703c7 100644 --- a/synapse/api/events/__init__.py +++ b/synapse/api/events/__init__.py @@ -59,7 +59,7 @@ class SynapseEvent(JsonEncodedObject): "age_ts", "prev_content", "prev_state", - "pruned_because", + "redacted_because", ] internal_keys = [ @@ -70,7 +70,7 @@ class SynapseEvent(JsonEncodedObject): "origin", "outlier", "power_level", - "deleted", + "redacted", ] required_keys = [ diff --git a/synapse/api/events/factory.py b/synapse/api/events/factory.py index c65ea8372..0d94850ce 100644 --- a/synapse/api/events/factory.py +++ b/synapse/api/events/factory.py @@ -18,7 +18,7 @@ from synapse.api.events.room import ( InviteJoinEvent, RoomConfigEvent, RoomNameEvent, GenericEvent, RoomPowerLevelsEvent, RoomJoinRulesEvent, RoomOpsPowerLevelsEvent, RoomCreateEvent, RoomAddStateLevelEvent, RoomSendEventLevelEvent, - RoomDeletionEvent, + RoomRedactionEvent, ) from synapse.util.stringutils import random_string @@ -40,7 +40,7 @@ class EventFactory(object): RoomAddStateLevelEvent, RoomSendEventLevelEvent, RoomOpsPowerLevelsEvent, - RoomDeletionEvent, + RoomRedactionEvent, ] def __init__(self, hs): diff --git a/synapse/api/events/room.py b/synapse/api/events/room.py index 986139555..cd936074f 100644 --- a/synapse/api/events/room.py +++ b/synapse/api/events/room.py @@ -182,10 +182,10 @@ class RoomAliasesEvent(SynapseStateEvent): return {} -class RoomDeletionEvent(SynapseEvent): - TYPE = "m.room.deletion" +class RoomRedactionEvent(SynapseEvent): + TYPE = "m.room.redaction" - valid_keys = SynapseEvent.valid_keys + ["deletes"] + valid_keys = SynapseEvent.valid_keys + ["redacts"] def get_content_template(self): return {} diff --git a/synapse/api/events/utils.py b/synapse/api/events/utils.py index 3d8b9a1db..c3a32be8c 100644 --- a/synapse/api/events/utils.py +++ b/synapse/api/events/utils.py @@ -23,7 +23,7 @@ def prune_event(event): """ Prunes the given event of all keys we don't know about or think could potentially be dodgy. - This is used when we "delete" an event. We want to remove all fields that + This is used when we "redact" an event. We want to remove all fields that the user has specified, but we do want to keep necessary information like type, state_key etc. """ @@ -55,7 +55,7 @@ def prune_event(event): elif event.type == RoomSendEventLevelEvent.TYPE: add_fields("level") elif event.type == RoomOpsPowerLevelsEvent.TYPE: - add_fields("kick_level", "ban_level", "delete_level") + add_fields("kick_level", "ban_level", "redact_level") elif event.type == RoomAliasesEvent.TYPE: add_fields("aliases") diff --git a/synapse/handlers/room.py b/synapse/handlers/room.py index 18597c694..b7a9d77ca 100644 --- a/synapse/handlers/room.py +++ b/synapse/handlers/room.py @@ -255,7 +255,7 @@ class RoomCreationHandler(BaseHandler): etype=RoomOpsPowerLevelsEvent.TYPE, ban_level=50, kick_level=50, - delete_level=50, + redact_level=50, ) return [ diff --git a/synapse/rest/room.py b/synapse/rest/room.py index 85a1d2eae..399084ae2 100644 --- a/synapse/rest/room.py +++ b/synapse/rest/room.py @@ -19,7 +19,7 @@ from twisted.internet import defer from base import RestServlet, client_path_pattern from synapse.api.errors import SynapseError, Codes from synapse.streams.config import PaginationConfig -from synapse.api.events.room import RoomMemberEvent, RoomDeletionEvent +from synapse.api.events.room import RoomMemberEvent, RoomRedactionEvent from synapse.api.constants import Membership import json @@ -430,9 +430,9 @@ class RoomMembershipRestServlet(RestServlet): self.txns.store_client_transaction(request, txn_id, response) defer.returnValue(response) -class RoomDeleteEventRestServlet(RestServlet): +class RoomRedactEventRestServlet(RestServlet): def register(self, http_server): - PATTERN = ("/rooms/(?P[^/]*)/delete/(?P[^/]*)") + PATTERN = ("/rooms/(?P[^/]*)/redact/(?P[^/]*)") register_txn_path(self, PATTERN, http_server) @defer.inlineCallbacks @@ -441,11 +441,11 @@ class RoomDeleteEventRestServlet(RestServlet): content = _parse_json(request) event = self.event_factory.create_event( - etype=RoomDeletionEvent.TYPE, + etype=RoomRedactionEvent.TYPE, room_id=urllib.unquote(room_id), user_id=user.to_string(), content=content, - deletes=event_id, + redacts=event_id, ) msg_handler = self.handlers.message_handler @@ -520,4 +520,4 @@ def register_servlets(hs, http_server): PublicRoomListRestServlet(hs).register(http_server) RoomStateRestServlet(hs).register(http_server) RoomInitialSyncRestServlet(hs).register(http_server) - RoomDeleteEventRestServlet(hs).register(http_server) + RoomRedactEventRestServlet(hs).register(http_server) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index accb4359b..fcf8b4d18 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -24,7 +24,7 @@ from synapse.api.events.room import ( RoomAddStateLevelEvent, RoomSendEventLevelEvent, RoomOpsPowerLevelsEvent, - RoomDeletionEvent, + RoomRedactionEvent, ) from synapse.util.logutils import log_function @@ -57,7 +57,7 @@ SCHEMAS = [ "presence", "im", "room_aliases", - "deletions", + "redactions", ] @@ -184,8 +184,8 @@ class DataStore(RoomMemberStore, RoomStore, self._store_send_event_level(txn, event) elif event.type == RoomOpsPowerLevelsEvent.TYPE: self._store_ops_level(txn, event) - elif event.type == RoomDeletionEvent.TYPE: - self._store_deletion(txn, event) + elif event.type == RoomRedactionEvent.TYPE: + self._store_redaction(txn, event) vals = { "topological_ordering": event.depth, @@ -207,7 +207,7 @@ class DataStore(RoomMemberStore, RoomStore, unrec = { k: v for k, v in event.get_full_dict().items() - if k not in vals.keys() and k not in ["deleted", "pruned_because"] + if k not in vals.keys() and k not in ["redacted", "redacted_because"] } vals["unrecognized_keys"] = json.dumps(unrec) @@ -245,25 +245,26 @@ class DataStore(RoomMemberStore, RoomStore, } ) - def _store_deletion(self, txn, event): + def _store_redaction(self, txn, event): txn.execute( - "INSERT INTO deletions (event_id, deletes) VALUES (?,?) OR IGNORE", - (event.event_id, event.deletes) + "INSERT OR IGNORE INTO redactions " + "(event_id, redacts) VALUES (?,?)", + (event.event_id, event.redacts) ) @defer.inlineCallbacks def get_current_state(self, room_id, event_type=None, state_key=""): del_sql = ( - "SELECT event_id FROM deletions WHERE deletes = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id" ) sql = ( - "SELECT e.*, (%(deleted)s) AS deleted FROM events as e " + "SELECT e.*, (%(redacted)s) AS redacted FROM events as e " "INNER JOIN current_state_events as c ON e.event_id = c.event_id " "INNER JOIN state_events as s ON e.event_id = s.event_id " "WHERE c.room_id = ? " ) % { - "deleted": del_sql, + "redacted": del_sql, } if event_type: diff --git a/synapse/storage/_base.py b/synapse/storage/_base.py index 444e7628d..889de2bed 100644 --- a/synapse/storage/_base.py +++ b/synapse/storage/_base.py @@ -383,14 +383,14 @@ class SQLBaseStore(object): prev = self._parse_event_from_row(prevs[0]) ev.prev_content = prev.content - if not hasattr(ev, "deleted"): - logger.debug("Doesn't have deleted key: %s", ev) - ev.deleted = self._has_been_deleted_txn(txn, ev) + if not hasattr(ev, "redacted"): + logger.debug("Doesn't have redacted key: %s", ev) + ev.redacted = self._has_been_redacted_txn(txn, ev) - if ev.deleted: - # Get the deletion event. + if ev.redacted: + # Get the redaction event. sql = "SELECT * FROM events WHERE event_id = ?" - txn.execute(sql, (ev.deleted,)) + txn.execute(sql, (ev.redacted,)) del_evs = self._parse_events_txn( txn, self.cursor_to_dict(txn) @@ -398,12 +398,12 @@ class SQLBaseStore(object): if del_evs: prune_event(ev) - ev.pruned_because = del_evs[0] + ev.redacted_because = del_evs[0] return events - def _has_been_deleted_txn(self, txn, event): - sql = "SELECT event_id FROM deletions WHERE deletes = ?" + def _has_been_redacted_txn(self, txn, event): + sql = "SELECT event_id FROM redactions WHERE redacts = ?" txn.execute(sql, (event.event_id,)) result = txn.fetchone() return result[0] if result else None diff --git a/synapse/storage/room.py b/synapse/storage/room.py index b1239a0f1..8cd46334c 100644 --- a/synapse/storage/room.py +++ b/synapse/storage/room.py @@ -27,7 +27,7 @@ import logging logger = logging.getLogger(__name__) -OpsLevel = collections.namedtuple("OpsLevel", ("ban_level", "kick_level", "delete_level")) +OpsLevel = collections.namedtuple("OpsLevel", ("ban_level", "kick_level", "redact_level")) class RoomStore(SQLBaseStore): @@ -189,7 +189,7 @@ class RoomStore(SQLBaseStore): def _get_ops_levels(self, txn, room_id): sql = ( - "SELECT ban_level, kick_level, delete_level " + "SELECT ban_level, kick_level, redact_level " "FROM room_ops_levels as r " "INNER JOIN current_state_events as c " "ON r.event_id = c.event_id " @@ -327,8 +327,8 @@ class RoomStore(SQLBaseStore): if "ban_level" in event.content: content["ban_level"] = event.content["ban_level"] - if "delete_level" in event.content: - content["delete_level"] = event.content["delete_level"] + if "redact_level" in event.content: + content["redact_level"] = event.content["redact_level"] self._simple_insert_txn( txn, diff --git a/synapse/storage/roommember.py b/synapse/storage/roommember.py index 97222da57..84c462330 100644 --- a/synapse/storage/roommember.py +++ b/synapse/storage/roommember.py @@ -183,18 +183,18 @@ class RoomMemberStore(SQLBaseStore): def _get_members_query_txn(self, txn, where_clause, where_values): del_sql = ( - "SELECT event_id FROM deletions WHERE deletes = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id" ) sql = ( - "SELECT e.*, (%(deleted)s) AS deleted FROM events as e " + "SELECT e.*, (%(redacted)s) AS redacted FROM events as e " "INNER JOIN room_memberships as m " "ON e.event_id = m.event_id " "INNER JOIN current_state_events as c " "ON m.event_id = c.event_id " "WHERE %(where)s " ) % { - "deleted": del_sql, + "redacted": del_sql, "where": where_clause, } diff --git a/synapse/storage/schema/deletions.sql b/synapse/storage/schema/deletions.sql deleted file mode 100644 index 2e2635317..000000000 --- a/synapse/storage/schema/deletions.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE IF NOT EXISTS deletions ( - event_id TEXT NOT NULL, - deletes TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS deletions_event_id ON deletions (event_id); -CREATE INDEX IF NOT EXISTS deletions_deletes ON deletions (deletes); diff --git a/synapse/storage/schema/delta/v4.sql b/synapse/storage/schema/delta/v4.sql index fc8bb5ad8..25d2ead45 100644 --- a/synapse/storage/schema/delta/v4.sql +++ b/synapse/storage/schema/delta/v4.sql @@ -1,11 +1,12 @@ -CREATE TABLE IF NOT EXISTS deletions ( +CREATE TABLE IF NOT EXISTS redactions ( event_id TEXT NOT NULL, - deletes TEXT NOT NULL + redacts TEXT NOT NULL, + CONSTRAINT ev_uniq UNIQUE (event_id) ); -CREATE INDEX IF NOT EXISTS deletions_event_id ON deletions (event_id); -CREATE INDEX IF NOT EXISTS deletions_deletes ON deletions (deletes); +CREATE INDEX IF NOT EXISTS redactions_event_id ON redactions (event_id); +CREATE INDEX IF NOT EXISTS redactions_redacts ON redactions (redacts); -ALTER TABLE room_ops_levels ADD COLUMN delete_level INTEGER; +ALTER TABLE room_ops_levels ADD COLUMN redact_level INTEGER; PRAGMA user_version = 4; diff --git a/synapse/storage/schema/im.sql b/synapse/storage/schema/im.sql index 649d54b81..3aa83f5c8 100644 --- a/synapse/storage/schema/im.sql +++ b/synapse/storage/schema/im.sql @@ -151,7 +151,7 @@ CREATE TABLE IF NOT EXISTS room_ops_levels( room_id TEXT NOT NULL, ban_level INTEGER, kick_level INTEGER, - delete_level INTEGER + redact_level INTEGER ); CREATE INDEX IF NOT EXISTS room_ops_levels_event_id ON room_ops_levels(event_id); diff --git a/synapse/storage/schema/redactions.sql b/synapse/storage/schema/redactions.sql new file mode 100644 index 000000000..4c2829d05 --- /dev/null +++ b/synapse/storage/schema/redactions.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS redactions ( + event_id TEXT NOT NULL, + redacts TEXT NOT NULL, + CONSTRAINT ev_uniq UNIQUE (event_id) +); + +CREATE INDEX IF NOT EXISTS redactions_event_id ON redactions (event_id); +CREATE INDEX IF NOT EXISTS redactions_redacts ON redactions (redacts); diff --git a/synapse/storage/stream.py b/synapse/storage/stream.py index aaac0aae3..91baa1831 100644 --- a/synapse/storage/stream.py +++ b/synapse/storage/stream.py @@ -158,7 +158,7 @@ class StreamStore(SQLBaseStore): ) del_sql = ( - "SELECT event_id FROM deletions WHERE deletes = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id" ) if limit: @@ -175,14 +175,14 @@ class StreamStore(SQLBaseStore): return sql = ( - "SELECT *, (%(deleted)s) AS deleted FROM events AS e WHERE " + "SELECT *, (%(redacted)s) AS redacted FROM events AS e WHERE " "((room_id IN (%(current)s)) OR " "(event_id IN (%(invites)s))) " "AND e.stream_ordering > ? AND e.stream_ordering <= ? " "AND e.outlier = 0 " "ORDER BY stream_ordering ASC LIMIT %(limit)d " ) % { - "deleted": del_sql, + "redacted": del_sql, "current": current_room_membership_sql, "invites": membership_sql, "limit": limit @@ -230,15 +230,15 @@ class StreamStore(SQLBaseStore): limit_str = "" del_sql = ( - "SELECT event_id FROM deletions WHERE deletes = events.event_id" + "SELECT event_id FROM redactions WHERE redacts = events.event_id" ) sql = ( - "SELECT *, (%(deleted)s) AS deleted FROM events " + "SELECT *, (%(redacted)s) AS redacted FROM events " "WHERE outlier = 0 AND room_id = ? AND %(bounds)s " "ORDER BY topological_ordering %(order)s, stream_ordering %(order)s %(limit)s " ) % { - "deleted": del_sql, + "redacted": del_sql, "bounds": bounds, "order": order, "limit": limit_str @@ -272,15 +272,15 @@ class StreamStore(SQLBaseStore): # TODO (erikj): Handle compressed feedback del_sql = ( - "SELECT event_id FROM deletions WHERE deletes = events.event_id" + "SELECT event_id FROM redactions WHERE redacts = events.event_id" ) sql = ( - "SELECT *, (%(deleted)s) AS deleted FROM events " + "SELECT *, (%(redacted)s) AS redacted FROM events " "WHERE room_id = ? AND stream_ordering <= ? " "ORDER BY topological_ordering DESC, stream_ordering DESC LIMIT ? " ) % { - "deleted": del_sql, + "redacted": del_sql, } rows = yield self._execute_and_decode( From 2721f5ccc931d7092e076d26e44ca01cb3e6a5a7 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 10:02:20 +0100 Subject: [PATCH 13/18] Add test for redactions --- tests/storage/test_redaction.py | 181 ++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 tests/storage/test_redaction.py diff --git a/tests/storage/test_redaction.py b/tests/storage/test_redaction.py new file mode 100644 index 000000000..2406597c3 --- /dev/null +++ b/tests/storage/test_redaction.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# Copyright 2014 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 tests import unittest +from twisted.internet import defer + +from synapse.server import HomeServer +from synapse.api.constants import Membership +from synapse.api.events.room import ( + RoomMemberEvent, MessageEvent, RoomRedactionEvent, +) + +from tests.utils import SQLiteMemoryDbPool + + +class StreamStoreTestCase(unittest.TestCase): + + @defer.inlineCallbacks + def setUp(self): + db_pool = SQLiteMemoryDbPool() + yield db_pool.prepare() + + hs = HomeServer( + "test", + db_pool=db_pool, + ) + + self.store = hs.get_datastore() + self.event_factory = hs.get_event_factory() + + self.u_alice = hs.parse_userid("@alice:test") + + self.room1 = hs.parse_roomid("!abc123:test") + + self.depth = 1 + + @defer.inlineCallbacks + def inject_room_member(self, room, user, membership, prev_state=None): + self.depth += 1 + + event = self.event_factory.create_event( + etype=RoomMemberEvent.TYPE, + user_id=user.to_string(), + state_key=user.to_string(), + room_id=room.to_string(), + membership=membership, + content={"membership": membership}, + depth=self.depth, + ) + + if prev_state: + event.prev_state = prev_state + + # Have to create a join event using the eventfactory + yield self.store.persist_event( + event + ) + + defer.returnValue(event) + + @defer.inlineCallbacks + def inject_message(self, room, user, body): + self.depth += 1 + + event = self.event_factory.create_event( + etype=MessageEvent.TYPE, + user_id=user.to_string(), + room_id=room.to_string(), + content={"body": body, "msgtype": u"message"}, + depth=self.depth, + ) + + yield self.store.persist_event( + event + ) + + defer.returnValue(event) + + @defer.inlineCallbacks + def inject_redaction(self, room, event_id, user, reason): + event = self.event_factory.create_event( + etype=RoomRedactionEvent.TYPE, + user_id=user.to_string(), + room_id=room.to_string(), + content={"reason": reason}, + depth=self.depth, + redacts=event_id, + ) + + yield self.store.persist_event( + event + ) + + defer.returnValue(event) + + @defer.inlineCallbacks + def test_redact(self): + yield self.inject_room_member( + self.room1, self.u_alice, Membership.JOIN + ) + + start = yield self.store.get_room_events_max_id() + + msg_event = yield self.inject_message(self.room1, self.u_alice, u"t") + + end = yield self.store.get_room_events_max_id() + + results, _ = yield self.store.get_room_events_stream( + self.u_alice.to_string(), + start, + end, + None, # Is currently ignored + ) + + self.assertEqual(1, len(results)) + + # Check event has not been redacted: + event = results[0] + + self.assertObjectHasAttributes( + { + "type": MessageEvent.TYPE, + "user_id": self.u_alice.to_string(), + "content": {"body": "t", "msgtype": "message"}, + }, + event, + ) + + self.assertFalse(hasattr(event, "redacted_because")) + + # Redact event + reason = "Because I said so" + yield self.inject_redaction( + self.room1, msg_event.event_id, self.u_alice, reason + ) + + results, _ = yield self.store.get_room_events_stream( + self.u_alice.to_string(), + start, + end, + None, # Is currently ignored + ) + + self.assertEqual(1, len(results)) + + # Check redaction + + event = results[0] + + self.assertObjectHasAttributes( + { + "type": MessageEvent.TYPE, + "user_id": self.u_alice.to_string(), + "content": {}, + }, + event, + ) + + self.assertTrue(hasattr(event, "redacted_because")) + + self.assertObjectHasAttributes( + { + "type": RoomRedactionEvent.TYPE, + "user_id": self.u_alice.to_string(), + "content": {"reason": reason}, + }, + event.redacted_because, + ) From 24e4c484681b7e1538a3812b91b949430b898b26 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 10:19:11 +0100 Subject: [PATCH 14/18] More tests. --- tests/storage/test_redaction.py | 83 ++++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/tests/storage/test_redaction.py b/tests/storage/test_redaction.py index 2406597c3..966deb365 100644 --- a/tests/storage/test_redaction.py +++ b/tests/storage/test_redaction.py @@ -42,13 +42,15 @@ class StreamStoreTestCase(unittest.TestCase): self.event_factory = hs.get_event_factory() self.u_alice = hs.parse_userid("@alice:test") + self.u_bob = hs.parse_userid("@bob:test") self.room1 = hs.parse_roomid("!abc123:test") self.depth = 1 @defer.inlineCallbacks - def inject_room_member(self, room, user, membership, prev_state=None): + def inject_room_member(self, room, user, membership, prev_state=None, + extra_content={}): self.depth += 1 event = self.event_factory.create_event( @@ -61,6 +63,8 @@ class StreamStoreTestCase(unittest.TestCase): depth=self.depth, ) + event.content.update(extra_content) + if prev_state: event.prev_state = prev_state @@ -179,3 +183,80 @@ class StreamStoreTestCase(unittest.TestCase): }, event.redacted_because, ) + + @defer.inlineCallbacks + def test_redact_join(self): + yield self.inject_room_member( + self.room1, self.u_alice, Membership.JOIN + ) + + start = yield self.store.get_room_events_max_id() + + msg_event = yield self.inject_room_member( + self.room1, self.u_bob, Membership.JOIN, + extra_content={"blue": "red"}, + ) + + end = yield self.store.get_room_events_max_id() + + results, _ = yield self.store.get_room_events_stream( + self.u_alice.to_string(), + start, + end, + None, # Is currently ignored + ) + + self.assertEqual(1, len(results)) + + # Check event has not been redacted: + event = results[0] + + self.assertObjectHasAttributes( + { + "type": RoomMemberEvent.TYPE, + "user_id": self.u_bob.to_string(), + "content": {"membership": Membership.JOIN, "blue": "red"}, + }, + event, + ) + + self.assertFalse(hasattr(event, "redacted_because")) + + # Redact event + reason = "Because I said so" + yield self.inject_redaction( + self.room1, msg_event.event_id, self.u_alice, reason + ) + + results, _ = yield self.store.get_room_events_stream( + self.u_alice.to_string(), + start, + end, + None, # Is currently ignored + ) + + self.assertEqual(1, len(results)) + + # Check redaction + + event = results[0] + + self.assertObjectHasAttributes( + { + "type": RoomMemberEvent.TYPE, + "user_id": self.u_bob.to_string(), + "content": {"membership": Membership.JOIN}, + }, + event, + ) + + self.assertTrue(hasattr(event, "redacted_because")) + + self.assertObjectHasAttributes( + { + "type": RoomRedactionEvent.TYPE, + "user_id": self.u_alice.to_string(), + "content": {"reason": reason}, + }, + event.redacted_because, + ) From c818aa13eb47c9d30da26645850a2af2672edf68 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 15:51:21 +0100 Subject: [PATCH 15/18] Add LIMIT to scalar subquery --- synapse/storage/__init__.py | 3 ++- synapse/storage/roommember.py | 3 ++- synapse/storage/stream.py | 9 ++++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/synapse/storage/__init__.py b/synapse/storage/__init__.py index fcf8b4d18..38f5ec0ac 100644 --- a/synapse/storage/__init__.py +++ b/synapse/storage/__init__.py @@ -255,7 +255,8 @@ class DataStore(RoomMemberStore, RoomStore, @defer.inlineCallbacks def get_current_state(self, room_id, event_type=None, state_key=""): del_sql = ( - "SELECT event_id FROM redactions WHERE redacts = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id " + "LIMIT 1" ) sql = ( diff --git a/synapse/storage/roommember.py b/synapse/storage/roommember.py index 84c462330..958e73059 100644 --- a/synapse/storage/roommember.py +++ b/synapse/storage/roommember.py @@ -183,7 +183,8 @@ class RoomMemberStore(SQLBaseStore): def _get_members_query_txn(self, txn, where_clause, where_values): del_sql = ( - "SELECT event_id FROM redactions WHERE redacts = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id " + "LIMIT 1" ) sql = ( diff --git a/synapse/storage/stream.py b/synapse/storage/stream.py index 91baa1831..d61f90993 100644 --- a/synapse/storage/stream.py +++ b/synapse/storage/stream.py @@ -158,7 +158,8 @@ class StreamStore(SQLBaseStore): ) del_sql = ( - "SELECT event_id FROM redactions WHERE redacts = e.event_id" + "SELECT event_id FROM redactions WHERE redacts = e.event_id " + "LIMIT 1" ) if limit: @@ -230,7 +231,8 @@ class StreamStore(SQLBaseStore): limit_str = "" del_sql = ( - "SELECT event_id FROM redactions WHERE redacts = events.event_id" + "SELECT event_id FROM redactions WHERE redacts = events.event_id " + "LIMIT 1" ) sql = ( @@ -272,7 +274,8 @@ class StreamStore(SQLBaseStore): # TODO (erikj): Handle compressed feedback del_sql = ( - "SELECT event_id FROM redactions WHERE redacts = events.event_id" + "SELECT event_id FROM redactions WHERE redacts = events.event_id " + "LIMIT 1" ) sql = ( From 72e80dbe0e00d64896ed007d4a7b605ffdc0ed46 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 15:52:23 +0100 Subject: [PATCH 16/18] Rename redaction test case to something helpful --- tests/storage/test_redaction.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/storage/test_redaction.py b/tests/storage/test_redaction.py index 966deb365..dae1641ea 100644 --- a/tests/storage/test_redaction.py +++ b/tests/storage/test_redaction.py @@ -26,7 +26,7 @@ from synapse.api.events.room import ( from tests.utils import SQLiteMemoryDbPool -class StreamStoreTestCase(unittest.TestCase): +class RedactionTestCase(unittest.TestCase): @defer.inlineCallbacks def setUp(self): From 69ddec65895d33a25dbaa5991462e32442dbe6e5 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 16:49:02 +0100 Subject: [PATCH 17/18] Don't strip of False values from events when serializing --- synapse/api/events/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/synapse/api/events/__init__.py b/synapse/api/events/__init__.py index 0ceb703c7..db6dff576 100644 --- a/synapse/api/events/__init__.py +++ b/synapse/api/events/__init__.py @@ -22,7 +22,7 @@ def serialize_event(hs, e): if not isinstance(e, SynapseEvent): return e - d = {k: v for k, v in e.get_dict().items() if v is not None or v is not False} + d = {k: v for k, v in e.get_dict().items() if v is not None} if "age_ts" in d: d["age"] = int(hs.get_clock().time_msec()) - d["age_ts"] del d["age_ts"] From dcadfbbd4a829a097c49c7b919a9429c3ca05de5 Mon Sep 17 00:00:00 2001 From: Erik Johnston Date: Thu, 25 Sep 2014 16:59:26 +0100 Subject: [PATCH 18/18] Don't strip out null's in serialized events, as that is not need anymore and it's not in the spec (yet) --- synapse/api/events/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/synapse/api/events/__init__.py b/synapse/api/events/__init__.py index db6dff576..f66fea290 100644 --- a/synapse/api/events/__init__.py +++ b/synapse/api/events/__init__.py @@ -22,7 +22,8 @@ def serialize_event(hs, e): if not isinstance(e, SynapseEvent): return e - d = {k: v for k, v in e.get_dict().items() if v is not None} + # Should this strip out None's? + d = {k: v for k, v in e.get_dict().items()} if "age_ts" in d: d["age"] = int(hs.get_clock().time_msec()) - d["age_ts"] del d["age_ts"]