This repository was archived by the owner on Apr 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Fix IP URL previews on Python 3 #4215
Merged
Merged
Changes from 13 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
9e0ae2f
fix
hawkowl 1474953
changelog
hawkowl 31e0fd9
fixes
hawkowl 1520252
fixes
hawkowl ec14bca
fixes
hawkowl 7af04df
fix pep8
hawkowl 606e39b
fix pep8
hawkowl 759169b
add some code coverage to blacklists
hawkowl a2f7ae1
tests
hawkowl a94ca42
Merge remote-tracking branch 'origin/develop' into hawkowl/ip-preview
hawkowl ca82572
fix pep8
hawkowl 4c246c0
Merge remote-tracking branch 'origin/develop' into hawkowl/ip-preview
hawkowl fc1dd48
cleanup
hawkowl c70d2a1
log when we block
hawkowl 5756f64
docstring
hawkowl 0421f0b
docstring
hawkowl e59a5ee
comment
hawkowl 4357b85
Merge remote-tracking branch 'origin/develop' into hawkowl/ip-preview
hawkowl d82e498
fix
hawkowl 1210131
merge in tests
hawkowl 6fade49
fix
hawkowl 168a494
fix
hawkowl 920625f
fix
hawkowl 7d17b47
fix py2
hawkowl 1d40dd5
Merge remote-tracking branch 'origin/develop' into hawkowl/ip-preview
hawkowl 79a5655
fix missing hyperlink
hawkowl aac9bb4
Merge remote-tracking branch 'origin/develop' into hawkowl/ip-preview
hawkowl 34952ce
review comments
hawkowl 9e64ab8
review comments
hawkowl 3b9e190
urllib does what we need here
hawkowl cfa8f6f
Merge branch 'develop' into hawkowl/ip-preview
hawkowl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,4 +9,3 @@ source= | |
|
||
[report] | ||
precision = 2 | ||
ignore_errors = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -57,3 +57,4 @@ env/ | |
|
||
.vscode/ | ||
.ropeproject/ | ||
.coverage.* |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Getting URL previews of IP addresses no longer fails on Python 3. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,13 +26,10 @@ | |
from OpenSSL import SSL | ||
from OpenSSL.SSL import VERIFY_NONE | ||
from twisted.internet import defer, protocol, reactor, ssl | ||
from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS | ||
from twisted.web._newclient import ResponseDone | ||
from twisted.web.client import ( | ||
URI, | ||
Agent, | ||
BrowserLikeRedirectAgent, | ||
ContentDecoderAgent, | ||
GzipDecoder, | ||
HTTPConnectionPool, | ||
PartialDownloadError, | ||
readBody, | ||
|
@@ -42,7 +39,6 @@ | |
|
||
from synapse.api.errors import Codes, HttpResponseException, SynapseError | ||
from synapse.http import cancelled_to_request_timed_out_error, redact_uri | ||
from synapse.http.endpoint import SpiderEndpoint | ||
from synapse.util.async_helpers import timeout_deferred | ||
from synapse.util.caches import CACHE_SIZE_FACTOR | ||
from synapse.util.logcontext import make_deferred_yieldable | ||
|
@@ -59,10 +55,15 @@ class SimpleHttpClient(object): | |
A simple, no-frills HTTP client with methods that wrap up common ways of | ||
using HTTP in Matrix | ||
""" | ||
def __init__(self, hs): | ||
|
||
def __init__(self, hs, treq_args={}, whitelist=None, blacklist=None, _treq=treq): | ||
self.hs = hs | ||
|
||
pool = HTTPConnectionPool(reactor) | ||
self._treq = _treq | ||
self._extra_treq_args = treq_args | ||
self.whitelist = whitelist | ||
self.blacklist = blacklist | ||
|
||
# the pusher makes lots of concurrent SSL connections to sygnal, and | ||
# tends to do so in batches, so we need to allow the pool to keep lots | ||
|
@@ -81,13 +82,30 @@ def __init__(self, hs): | |
) | ||
self.user_agent = hs.version_string | ||
self.clock = hs.get_clock() | ||
self.reactor = hs.get_reactor() | ||
if hs.config.user_agent_suffix: | ||
self.user_agent = "%s %s" % (self.user_agent, hs.config.user_agent_suffix,) | ||
|
||
self.user_agent = self.user_agent.encode('ascii') | ||
|
||
@defer.inlineCallbacks | ||
def request(self, method, uri, data=b'', headers=None): | ||
|
||
# Check our IP whitelists/blacklists before making the request. | ||
if self.blacklist: | ||
split_uri = URI.fromBytes(uri.encode('utf8')) | ||
address = yield self.reactor.resolve(split_uri.host) | ||
hawkowl marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
from netaddr import IPAddress | ||
ip_address = IPAddress(address) | ||
|
||
if ip_address in self.blacklist: | ||
if self.whitelist is None or ip_address not in self.whitelist: | ||
raise SynapseError( | ||
403, "IP address blocked by IP blacklist entry", | ||
Codes.UNKNOWN | ||
) | ||
|
||
# A small wrapper around self.agent.request() so we can easily attach | ||
# counters to it | ||
outgoing_requests_counter.labels(method).inc() | ||
|
@@ -96,8 +114,13 @@ def request(self, method, uri, data=b'', headers=None): | |
logger.info("Sending request %s %s", method, redact_uri(uri)) | ||
|
||
try: | ||
request_deferred = treq.request( | ||
method, uri, agent=self.agent, data=data, headers=headers | ||
request_deferred = self._treq.request( | ||
method, | ||
uri, | ||
agent=self.agent, | ||
data=data, | ||
headers=headers, | ||
**self._extra_treq_args | ||
) | ||
request_deferred = timeout_deferred( | ||
request_deferred, 60, self.hs.get_reactor(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. all these unrelated formatting changes make this a much bigger diff, so make it much harder to review. pleeeease can we keep formatting and functional changes separate in future? |
||
|
@@ -463,57 +486,6 @@ def post_urlencoded_get_raw(self, url, args={}): | |
defer.returnValue(e.response) | ||
|
||
|
||
class SpiderEndpointFactory(object): | ||
def __init__(self, hs): | ||
self.blacklist = hs.config.url_preview_ip_range_blacklist | ||
self.whitelist = hs.config.url_preview_ip_range_whitelist | ||
self.policyForHTTPS = hs.get_http_client_context_factory() | ||
|
||
def endpointForURI(self, uri): | ||
logger.info("Getting endpoint for %s", uri.toBytes()) | ||
|
||
if uri.scheme == b"http": | ||
endpoint_factory = HostnameEndpoint | ||
elif uri.scheme == b"https": | ||
tlsCreator = self.policyForHTTPS.creatorForNetloc(uri.host, uri.port) | ||
|
||
def endpoint_factory(reactor, host, port, **kw): | ||
return wrapClientTLS( | ||
tlsCreator, | ||
HostnameEndpoint(reactor, host, port, **kw)) | ||
else: | ||
logger.warn("Can't get endpoint for unrecognised scheme %s", uri.scheme) | ||
return None | ||
return SpiderEndpoint( | ||
reactor, uri.host, uri.port, self.blacklist, self.whitelist, | ||
endpoint=endpoint_factory, endpoint_kw_args=dict(timeout=15), | ||
) | ||
|
||
|
||
class SpiderHttpClient(SimpleHttpClient): | ||
""" | ||
Separate HTTP client for spidering arbitrary URLs. | ||
Special in that it follows retries and has a UA that looks | ||
like a browser. | ||
|
||
used by the preview_url endpoint in the content repo. | ||
""" | ||
def __init__(self, hs): | ||
SimpleHttpClient.__init__(self, hs) | ||
# clobber the base class's agent and UA: | ||
self.agent = ContentDecoderAgent( | ||
BrowserLikeRedirectAgent( | ||
Agent.usingEndpointFactory( | ||
reactor, | ||
SpiderEndpointFactory(hs) | ||
) | ||
), [(b'gzip', GzipDecoder)] | ||
) | ||
# We could look like Chrome: | ||
# self.user_agent = ("Mozilla/5.0 (%s) (KHTML, like Gecko) | ||
# Chrome Safari" % hs.version_string) | ||
|
||
|
||
def encode_urlencode_args(args): | ||
return {k: encode_urlencode_arg(v) for k, v in args.items()} | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.