1# Copyright 2014-2016 OpenMarket Ltd
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
16"""Contains the URL paths to prefix various aspects of the server with. """
17import hmac
18from hashlib import sha256
19from urllib.parse import urlencode
20
21from synapse.config import ConfigError
22from synapse.config.homeserver import HomeServerConfig
23
24SYNAPSE_CLIENT_API_PREFIX = "/_synapse/client"
25CLIENT_API_PREFIX = "/_matrix/client"
26FEDERATION_PREFIX = "/_matrix/federation"
27FEDERATION_V1_PREFIX = FEDERATION_PREFIX + "/v1"
28FEDERATION_V2_PREFIX = FEDERATION_PREFIX + "/v2"
29FEDERATION_UNSTABLE_PREFIX = FEDERATION_PREFIX + "/unstable"
30STATIC_PREFIX = "/_matrix/static"
31WEB_CLIENT_PREFIX = "/_matrix/client"
32SERVER_KEY_V2_PREFIX = "/_matrix/key/v2"
33MEDIA_R0_PREFIX = "/_matrix/media/r0"
34MEDIA_V3_PREFIX = "/_matrix/media/v3"
35LEGACY_MEDIA_PREFIX = "/_matrix/media/v1"
36
37
38class ConsentURIBuilder:
39    def __init__(self, hs_config: HomeServerConfig):
40        if hs_config.key.form_secret is None:
41            raise ConfigError("form_secret not set in config")
42        self._hmac_secret = hs_config.key.form_secret.encode("utf-8")
43        self._public_baseurl = hs_config.server.public_baseurl
44
45    def build_user_consent_uri(self, user_id: str) -> str:
46        """Build a URI which we can give to the user to do their privacy
47        policy consent
48
49        Args:
50            user_id: mxid or username of user
51
52        Returns
53            The URI where the user can do consent
54        """
55        mac = hmac.new(
56            key=self._hmac_secret, msg=user_id.encode("ascii"), digestmod=sha256
57        ).hexdigest()
58        consent_uri = "%s_matrix/consent?%s" % (
59            self._public_baseurl,
60            urlencode({"u": user_id, "h": mac}),
61        )
62        return consent_uri
63