consent_resource.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector 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. import hmac
  16. import logging
  17. from hashlib import sha256
  18. from http import HTTPStatus
  19. from os import path
  20. import jinja2
  21. from jinja2 import TemplateNotFound
  22. from twisted.internet import defer
  23. from synapse.api.errors import NotFoundError, StoreError, SynapseError
  24. from synapse.config import ConfigError
  25. from synapse.http.server import (
  26. DirectServeResource,
  27. finish_request,
  28. wrap_html_request_handler,
  29. )
  30. from synapse.http.servlet import parse_string
  31. from synapse.types import UserID
  32. # language to use for the templates. TODO: figure this out from Accept-Language
  33. TEMPLATE_LANGUAGE = "en"
  34. logger = logging.getLogger(__name__)
  35. # use hmac.compare_digest if we have it (python 2.7.7), else just use equality
  36. if hasattr(hmac, "compare_digest"):
  37. compare_digest = hmac.compare_digest
  38. else:
  39. def compare_digest(a, b):
  40. return a == b
  41. class ConsentResource(DirectServeResource):
  42. """A twisted Resource to display a privacy policy and gather consent to it
  43. When accessed via GET, returns the privacy policy via a template.
  44. When accessed via POST, records the user's consent in the database and
  45. displays a success page.
  46. The config should include a template_dir setting which contains templates
  47. for the HTML. The directory should contain one subdirectory per language
  48. (eg, 'en', 'fr'), and each language directory should contain the policy
  49. document (named as '<version>.html') and a success page (success.html).
  50. Both forms take a set of parameters from the browser. For the POST form,
  51. these are normally sent as form parameters (but may be query-params); for
  52. GET requests they must be query params. These are:
  53. u: the complete mxid, or the localpart of the user giving their
  54. consent. Required for both GET (where it is used as an input to the
  55. template) and for POST (where it is used to find the row in the db
  56. to update).
  57. h: hmac_sha256(secret, u), where 'secret' is the privacy_secret in the
  58. config file. If it doesn't match, the request is 403ed.
  59. v: the version of the privacy policy being agreed to.
  60. For GET: optional, and defaults to whatever was set in the config
  61. file. Used to choose the version of the policy to pick from the
  62. templates directory.
  63. For POST: required; gives the value to be recorded in the database
  64. against the user.
  65. """
  66. def __init__(self, hs):
  67. """
  68. Args:
  69. hs (synapse.server.HomeServer): homeserver
  70. """
  71. super().__init__()
  72. self.hs = hs
  73. self.store = hs.get_datastore()
  74. self.registration_handler = hs.get_registration_handler()
  75. # this is required by the request_handler wrapper
  76. self.clock = hs.get_clock()
  77. self._default_consent_version = hs.config.user_consent_version
  78. if self._default_consent_version is None:
  79. raise ConfigError(
  80. "Consent resource is enabled but user_consent section is "
  81. "missing in config file."
  82. )
  83. consent_template_directory = hs.config.user_consent_template_dir
  84. loader = jinja2.FileSystemLoader(consent_template_directory)
  85. self._jinja_env = jinja2.Environment(
  86. loader=loader, autoescape=jinja2.select_autoescape(["html", "htm", "xml"])
  87. )
  88. if hs.config.form_secret is None:
  89. raise ConfigError(
  90. "Consent resource is enabled but form_secret is not set in "
  91. "config file. It should be set to an arbitrary secret string."
  92. )
  93. self._hmac_secret = hs.config.form_secret.encode("utf-8")
  94. @wrap_html_request_handler
  95. async def _async_render_GET(self, request):
  96. """
  97. Args:
  98. request (twisted.web.http.Request):
  99. """
  100. version = parse_string(request, "v", default=self._default_consent_version)
  101. username = parse_string(request, "u", required=False, default="")
  102. userhmac = None
  103. has_consented = False
  104. public_version = username == ""
  105. if not public_version:
  106. userhmac_bytes = parse_string(request, "h", required=True, encoding=None)
  107. self._check_hash(username, userhmac_bytes)
  108. if username.startswith("@"):
  109. qualified_user_id = username
  110. else:
  111. qualified_user_id = UserID(username, self.hs.hostname).to_string()
  112. u = await defer.maybeDeferred(self.store.get_user_by_id, qualified_user_id)
  113. if u is None:
  114. raise NotFoundError("Unknown user")
  115. has_consented = u["consent_version"] == version
  116. userhmac = userhmac_bytes.decode("ascii")
  117. try:
  118. self._render_template(
  119. request,
  120. "%s.html" % (version,),
  121. user=username,
  122. userhmac=userhmac,
  123. version=version,
  124. has_consented=has_consented,
  125. public_version=public_version,
  126. )
  127. except TemplateNotFound:
  128. raise NotFoundError("Unknown policy version")
  129. @wrap_html_request_handler
  130. async def _async_render_POST(self, request):
  131. """
  132. Args:
  133. request (twisted.web.http.Request):
  134. """
  135. version = parse_string(request, "v", required=True)
  136. username = parse_string(request, "u", required=True)
  137. userhmac = parse_string(request, "h", required=True, encoding=None)
  138. self._check_hash(username, userhmac)
  139. if username.startswith("@"):
  140. qualified_user_id = username
  141. else:
  142. qualified_user_id = UserID(username, self.hs.hostname).to_string()
  143. try:
  144. await self.store.user_set_consent_version(qualified_user_id, version)
  145. except StoreError as e:
  146. if e.code != 404:
  147. raise
  148. raise NotFoundError("Unknown user")
  149. await self.registration_handler.post_consent_actions(qualified_user_id)
  150. try:
  151. self._render_template(request, "success.html")
  152. except TemplateNotFound:
  153. raise NotFoundError("success.html not found")
  154. def _render_template(self, request, template_name, **template_args):
  155. # get_template checks for ".." so we don't need to worry too much
  156. # about path traversal here.
  157. template_html = self._jinja_env.get_template(
  158. path.join(TEMPLATE_LANGUAGE, template_name)
  159. )
  160. html_bytes = template_html.render(**template_args).encode("utf8")
  161. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  162. request.setHeader(b"Content-Length", b"%i" % len(html_bytes))
  163. request.write(html_bytes)
  164. finish_request(request)
  165. def _check_hash(self, userid, userhmac):
  166. """
  167. Args:
  168. userid (unicode):
  169. userhmac (bytes):
  170. Raises:
  171. SynapseError if the hash doesn't match
  172. """
  173. want_mac = (
  174. hmac.new(
  175. key=self._hmac_secret, msg=userid.encode("utf-8"), digestmod=sha256
  176. )
  177. .hexdigest()
  178. .encode("ascii")
  179. )
  180. if not compare_digest(want_mac, userhmac):
  181. raise SynapseError(HTTPStatus.FORBIDDEN, "HMAC incorrect")