|
| 1 | +# Copyright 2021 The Matrix.org Foundation C.I.C. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import json |
| 15 | +import re |
| 16 | +from typing import Any, Dict, Iterable, List, Pattern |
| 17 | +from urllib import parse as urlparse |
| 18 | + |
| 19 | +import attr |
| 20 | +import pkg_resources |
| 21 | + |
| 22 | +from synapse.types import JsonDict |
| 23 | + |
| 24 | +from ._base import Config, ConfigError |
| 25 | +from ._util import validate_config |
| 26 | + |
| 27 | + |
| 28 | +@attr.s(slots=True, frozen=True, auto_attribs=True) |
| 29 | +class OEmbedEndpointConfig: |
| 30 | + # The API endpoint to fetch. |
| 31 | + api_endpoint: str |
| 32 | + # The patterns to match. |
| 33 | + url_patterns: List[Pattern] |
| 34 | + |
| 35 | + |
| 36 | +class OembedConfig(Config): |
| 37 | + """oEmbed Configuration""" |
| 38 | + |
| 39 | + section = "oembed" |
| 40 | + |
| 41 | + def read_config(self, config, **kwargs): |
| 42 | + oembed_config: Dict[str, Any] = config.get("oembed") or {} |
| 43 | + |
| 44 | + # A list of patterns which will be used. |
| 45 | + self.oembed_patterns: List[OEmbedEndpointConfig] = list( |
| 46 | + self._parse_and_validate_providers(oembed_config) |
| 47 | + ) |
| 48 | + |
| 49 | + def _parse_and_validate_providers( |
| 50 | + self, oembed_config: dict |
| 51 | + ) -> Iterable[OEmbedEndpointConfig]: |
| 52 | + """Extract and parse the oEmbed providers from the given JSON file. |
| 53 | +
|
| 54 | + Returns a generator which yields the OidcProviderConfig objects |
| 55 | + """ |
| 56 | + # Whether to use the packaged providers.json file. |
| 57 | + if not oembed_config.get("disable_default_providers") or False: |
| 58 | + providers = json.load( |
| 59 | + pkg_resources.resource_stream("synapse", "res/providers.json") |
| 60 | + ) |
| 61 | + yield from self._parse_and_validate_provider( |
| 62 | + providers, config_path=("oembed",) |
| 63 | + ) |
| 64 | + |
| 65 | + # The JSON files which includes additional provider information. |
| 66 | + for i, file in enumerate(oembed_config.get("additional_providers") or []): |
| 67 | + # TODO Error checking. |
| 68 | + with open(file) as f: |
| 69 | + providers = json.load(f) |
| 70 | + |
| 71 | + yield from self._parse_and_validate_provider( |
| 72 | + providers, |
| 73 | + config_path=( |
| 74 | + "oembed", |
| 75 | + "additional_providers", |
| 76 | + f"<item {i}>", |
| 77 | + ), |
| 78 | + ) |
| 79 | + |
| 80 | + def _parse_and_validate_provider( |
| 81 | + self, providers: List[JsonDict], config_path: Iterable[str] |
| 82 | + ) -> Iterable[OEmbedEndpointConfig]: |
| 83 | + # Ensure it is the proper form. |
| 84 | + validate_config( |
| 85 | + _OEMBED_PROVIDER_SCHEMA, |
| 86 | + providers, |
| 87 | + config_path=config_path, |
| 88 | + ) |
| 89 | + |
| 90 | + # Parse it and yield each result. |
| 91 | + for provider in providers: |
| 92 | + # Each provider might have multiple API endpoints, each which |
| 93 | + # might have multiple patterns to match. |
| 94 | + for endpoint in provider["endpoints"]: |
| 95 | + api_endpoint = endpoint["url"] |
| 96 | + patterns = [ |
| 97 | + self._glob_to_pattern(glob, config_path) |
| 98 | + for glob in endpoint["schemes"] |
| 99 | + ] |
| 100 | + yield OEmbedEndpointConfig(api_endpoint, patterns) |
| 101 | + |
| 102 | + def _glob_to_pattern(self, glob: str, config_path: Iterable[str]) -> Pattern: |
| 103 | + """ |
| 104 | + Convert the glob into a sane regular expression to match against. The |
| 105 | + rules followed will be slightly different for the domain portion vs. |
| 106 | + the rest. |
| 107 | +
|
| 108 | + 1. The scheme must be one of HTTP / HTTPS (and have no globs). |
| 109 | + 2. The domain can have globs, but we limit it to characters that can |
| 110 | + reasonably be a domain part. |
| 111 | + TODO: This does not attempt to handle Unicode domain names. |
| 112 | + TODO: The domain should not allow wildcard TLDs. |
| 113 | + 3. Other parts allow a glob to be any one, or more, characters. |
| 114 | + """ |
| 115 | + results = urlparse.urlparse(glob) |
| 116 | + |
| 117 | + # Ensure the scheme does not have wildcards (and is a sane scheme). |
| 118 | + if results.scheme not in {"http", "https"}: |
| 119 | + raise ConfigError(f"Insecure oEmbed scheme: {results.scheme}", config_path) |
| 120 | + |
| 121 | + pattern = urlparse.urlunparse( |
| 122 | + [ |
| 123 | + results.scheme, |
| 124 | + re.escape(results.netloc).replace("\\*", "[a-zA-Z0-9_-]+"), |
| 125 | + ] |
| 126 | + + [re.escape(part).replace("\\*", ".+") for part in results[2:]] |
| 127 | + ) |
| 128 | + return re.compile(pattern) |
| 129 | + |
| 130 | + def generate_config_section(self, **kwargs): |
| 131 | + return """\ |
| 132 | + # oEmbed allows for easier embedding content from a website. It can be |
| 133 | + # used for generating URLs previews of services which support it. |
| 134 | + # |
| 135 | + oembed: |
| 136 | + # A default list of oEmbed providers is included with Synapse. |
| 137 | + # |
| 138 | + # Uncomment the following to disable using these default oEmbed URLs. |
| 139 | + # Defaults to 'false'. |
| 140 | + # |
| 141 | + #disable_default_providers: true |
| 142 | +
|
| 143 | + # Additional files with oEmbed configuration (each should be in the |
| 144 | + # form of providers.json). |
| 145 | + # |
| 146 | + # By default, this list is empty (so only the default providers.json |
| 147 | + # is used). |
| 148 | + # |
| 149 | + #additional_providers: |
| 150 | + # - oembed/my_providers.json |
| 151 | + """ |
| 152 | + |
| 153 | + |
| 154 | +_OEMBED_PROVIDER_SCHEMA = { |
| 155 | + "type": "array", |
| 156 | + "items": { |
| 157 | + "type": "object", |
| 158 | + "properties": { |
| 159 | + "provider_name": {"type": "string"}, |
| 160 | + "provider_url": {"type": "string"}, |
| 161 | + "endpoints": { |
| 162 | + "type": "array", |
| 163 | + "items": { |
| 164 | + "type": "object", |
| 165 | + "properties": { |
| 166 | + "schemes": { |
| 167 | + "type": "array", |
| 168 | + "items": {"type": "string"}, |
| 169 | + }, |
| 170 | + "url": {"type": "string"}, |
| 171 | + "formats": {"type": "array", "items": {"type": "string"}}, |
| 172 | + "discovery": {"type": "boolean"}, |
| 173 | + }, |
| 174 | + "required": ["schemes", "url"], |
| 175 | + }, |
| 176 | + }, |
| 177 | + }, |
| 178 | + "required": ["provider_name", "provider_url", "endpoints"], |
| 179 | + }, |
| 180 | +} |
0 commit comments