validator.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from six import string_types
  16. from synapse.api.constants import EventTypes, Membership
  17. from synapse.api.errors import SynapseError
  18. from synapse.types import EventID, RoomID, UserID
  19. class EventValidator(object):
  20. def validate(self, event):
  21. EventID.from_string(event.event_id)
  22. RoomID.from_string(event.room_id)
  23. required = [
  24. # "auth_events",
  25. "content",
  26. # "hashes",
  27. "origin",
  28. # "prev_events",
  29. "sender",
  30. "type",
  31. ]
  32. for k in required:
  33. if not hasattr(event, k):
  34. raise SynapseError(400, "Event does not have key %s" % (k,))
  35. # Check that the following keys have string values
  36. strings = [
  37. "origin",
  38. "sender",
  39. "type",
  40. ]
  41. if hasattr(event, "state_key"):
  42. strings.append("state_key")
  43. for s in strings:
  44. if not isinstance(getattr(event, s), string_types):
  45. raise SynapseError(400, "Not '%s' a string type" % (s,))
  46. if event.type == EventTypes.Member:
  47. if "membership" not in event.content:
  48. raise SynapseError(400, "Content has not membership key")
  49. if event.content["membership"] not in Membership.LIST:
  50. raise SynapseError(400, "Invalid membership key")
  51. # Check that the following keys have dictionary values
  52. # TODO
  53. # Check that the following keys have the correct format for DAGs
  54. # TODO
  55. def validate_new(self, event):
  56. self.validate(event)
  57. UserID.from_string(event.sender)
  58. if event.type == EventTypes.Message:
  59. strings = [
  60. "body",
  61. "msgtype",
  62. ]
  63. self._ensure_strings(event.content, strings)
  64. elif event.type == EventTypes.Topic:
  65. self._ensure_strings(event.content, ["topic"])
  66. elif event.type == EventTypes.Name:
  67. self._ensure_strings(event.content, ["name"])
  68. def _ensure_strings(self, d, keys):
  69. for s in keys:
  70. if s not in d:
  71. raise SynapseError(400, "'%s' not in content" % (s,))
  72. if not isinstance(d[s], string_types):
  73. raise SynapseError(400, "Not '%s' a string type" % (s,))