|
1 | 1 | import json |
2 | 2 | import logging |
3 | | -import re |
| 3 | +import urllib |
4 | 4 | from http.client import HTTPResponse |
5 | 5 | from ssl import SSLContext |
6 | 6 | from typing import Dict, Union, List, Optional |
7 | 7 | from urllib.error import HTTPError |
8 | | -from urllib.request import Request, urlopen |
| 8 | +from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler |
9 | 9 |
|
10 | 10 | from slack.errors import SlackRequestError |
11 | 11 | from .internal_utils import _build_body, _build_request_headers, _debug_log_response |
@@ -97,22 +97,33 @@ def _perform_http_request( |
97 | 97 | ) |
98 | 98 | try: |
99 | 99 | url = self.url |
| 100 | + opener: Optional[OpenerDirector] = None |
100 | 101 | # for security (BAN-B310) |
101 | 102 | if url.lower().startswith("http"): |
102 | 103 | req = Request( |
103 | 104 | method="POST", url=url, data=body.encode("utf-8"), headers=headers |
104 | 105 | ) |
105 | 106 | if self.proxy is not None: |
106 | | - host = re.sub("^https?://", "", self.proxy) |
107 | | - req.set_proxy(host, "http") |
108 | | - req.set_proxy(host, "https") |
| 107 | + if isinstance(self.proxy, str): |
| 108 | + opener = urllib.request.build_opener( |
| 109 | + ProxyHandler({"http": self.proxy, "https": self.proxy}), |
| 110 | + HTTPSHandler(context=self.ssl), |
| 111 | + ) |
| 112 | + else: |
| 113 | + raise SlackRequestError( |
| 114 | + f"Invalid proxy detected: {self.proxy} must be a str value" |
| 115 | + ) |
109 | 116 | else: |
110 | 117 | raise SlackRequestError(f"Invalid URL detected: {url}") |
111 | 118 |
|
112 | 119 | # NOTE: BAN-B310 is already checked above |
113 | | - resp: HTTPResponse = urlopen( # skipcq: BAN-B310 |
114 | | - req, context=self.ssl, timeout=self.timeout, |
115 | | - ) |
| 120 | + resp: Optional[HTTPResponse] = None |
| 121 | + if opener: |
| 122 | + resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 |
| 123 | + else: |
| 124 | + resp = urlopen( # skipcq: BAN-B310 |
| 125 | + req, context=self.ssl, timeout=self.timeout |
| 126 | + ) |
116 | 127 | charset: str = resp.headers.get_content_charset() or "utf-8" |
117 | 128 | response_body: str = resp.read().decode(charset) |
118 | 129 | resp = WebhookResponse( |
|
0 commit comments