Coverage for downtify/proxy_config.py: 92%

99 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Application-wide outbound HTTP proxy configuration.""" 

2 

3from __future__ import annotations 

4 

5import importlib.util 

6import os 

7import urllib.request 

8from dataclasses import dataclass 

9from urllib.parse import urlsplit, urlunsplit 

10 

11from loguru import logger 

12 

13_PROXY_SCHEMES = ('http', 'https', 'all') 

14_PROXY_ENV_NAMES = { 

15 scheme: (f'{scheme.upper()}_PROXY', f'{scheme}_proxy') 

16 for scheme in _PROXY_SCHEMES 

17} 

18_LOCAL_BYPASSES = ('localhost', '127.0.0.1', '::1') 

19_TRUE_VALUES = {'1', 'true', 'yes', 'on'} 

20_FALSE_VALUES = {'0', 'false', 'no', 'off'} 

21 

22 

23@dataclass(frozen=True) 

24class OutboundProxyConfig: 

25 proxy_urls: dict[str, str] 

26 strict: bool 

27 bypass_hosts: tuple[str, ...] 

28 

29 

30class ProxyConfigurationError(ValueError): 

31 """The outbound proxy configuration cannot be applied safely.""" 

32 

33 

34_config: OutboundProxyConfig | None = None 

35 

36 

37def _validate_proxy_url( 

38 value: str, *, allow_missing_scheme: bool = False 

39) -> str: 

40 url = value.strip() 

41 if allow_missing_scheme and '://' not in url: 

42 url = f'http://{url}' 

43 try: 

44 parsed = urlsplit(url) 

45 parsed.port 

46 except ValueError as exc: 

47 raise ProxyConfigurationError('Invalid outbound proxy URL') from exc 

48 if ( 

49 parsed.scheme.lower() not in {'http', 'https', 'socks5', 'socks5h'} 

50 or not parsed.hostname 

51 or parsed.path not in {'', '/'} 

52 or parsed.query 

53 or parsed.fragment 

54 ): 

55 raise ProxyConfigurationError( 

56 'Proxy URL must use http, https, socks5 or socks5h and include a host' 

57 ) 

58 return url 

59 

60 

61def _httpx_proxy_url(value: str) -> str: 

62 parsed = urlsplit(value) 

63 if parsed.scheme.lower() != 'socks5h': 

64 return value 

65 return urlunsplit(parsed._replace(scheme='socks5')) 

66 

67 

68def _proxy_environment() -> dict[str, str]: 

69 configured = os.getenv('DOWNTIFY_PROXY', '').strip() 

70 if configured: 

71 proxy = _validate_proxy_url(configured) 

72 return {scheme: proxy for scheme in _PROXY_SCHEMES} 

73 

74 raw = urllib.request.getproxies() 

75 return { 

76 scheme: _validate_proxy_url(raw[scheme], allow_missing_scheme=True) 

77 for scheme in _PROXY_SCHEMES 

78 if raw.get(scheme) 

79 } 

80 

81 

82def _strict_mode() -> bool: 

83 value = os.getenv('DOWNTIFY_PROXY_STRICT', '').strip().lower() 

84 if not value: 

85 return False 

86 if value in _TRUE_VALUES: 

87 return True 

88 if value in _FALSE_VALUES: 

89 return False 

90 raise ProxyConfigurationError( 

91 'DOWNTIFY_PROXY_STRICT must be a boolean value' 

92 ) 

93 

94 

95def _bypass_hosts(proxy_urls: dict[str, str], strict: bool) -> tuple[str, ...]: 

96 existing = urllib.request.getproxies().get('no', '') 

97 configured = os.getenv('DOWNTIFY_PROXY_BYPASS', '') 

98 hosts = [ 

99 host.strip() 

100 for value in (existing, configured) 

101 for host in value.split(',') 

102 if host.strip() 

103 ] 

104 if '*' in hosts and strict: 

105 raise ProxyConfigurationError( 

106 'Strict proxy mode cannot be combined with NO_PROXY=*' 

107 ) 

108 if proxy_urls: 

109 hosts.extend(_LOCAL_BYPASSES) 

110 return tuple(dict.fromkeys(hosts)) 

111 

112 

113def configure_outbound_proxy() -> OutboundProxyConfig: 

114 """Validate settings and configure standard proxy-aware HTTP clients.""" 

115 

116 global _config 

117 proxy_urls = _proxy_environment() 

118 strict = _strict_mode() 

119 bypass_hosts = _bypass_hosts(proxy_urls, strict) 

120 if strict and not ( 

121 'all' in proxy_urls or {'http', 'https'} <= set(proxy_urls) 

122 ): 

123 raise ProxyConfigurationError( 

124 'Strict proxy mode requires DOWNTIFY_PROXY, ALL_PROXY, or both ' 

125 'HTTP_PROXY and HTTPS_PROXY' 

126 ) 

127 

128 if any( 

129 urlsplit(url).scheme.lower().startswith('socks5') 

130 for url in proxy_urls.values() 

131 ): 

132 missing = [ 

133 package 

134 for package in ('socksio', 'socks') 

135 if importlib.util.find_spec(package) is None 

136 ] 

137 if missing: 

138 raise ProxyConfigurationError( 

139 'SOCKS proxy support is missing: ' + ', '.join(missing) 

140 ) 

141 

142 for scheme, url in proxy_urls.items(): 

143 for name in _PROXY_ENV_NAMES[scheme]: 

144 os.environ[name] = _httpx_proxy_url(url) 

145 if proxy_urls: 

146 no_proxy = ','.join(bypass_hosts) 

147 os.environ['NO_PROXY'] = no_proxy 

148 os.environ['no_proxy'] = no_proxy 

149 

150 _config = OutboundProxyConfig(proxy_urls, strict, bypass_hosts) 

151 if proxy_urls: 

152 routes = ', '.join(scheme.upper() for scheme in proxy_urls) 

153 authorities = sorted({ 

154 urlsplit(url).hostname or '' for url in proxy_urls.values() 

155 }) 

156 logger.info( 

157 'Outbound proxy configured for {} via {} (strict={}, bypass_hosts={})', 

158 routes, 

159 ', '.join(authorities), 

160 strict, 

161 len(bypass_hosts), 

162 ) 

163 elif strict: 

164 raise ProxyConfigurationError( 

165 'Strict proxy mode requires an outbound proxy' 

166 ) 

167 else: 

168 logger.info( 

169 'Outbound proxy is not configured; direct access is allowed' 

170 ) 

171 return _config 

172 

173 

174def outbound_proxy_config() -> OutboundProxyConfig: 

175 return _config if _config is not None else configure_outbound_proxy() 

176 

177 

178def requests_proxies_for_youtube_music() -> dict[str, str | None] | None: 

179 """Requests-format proxy map, retaining socks5h remote-DNS semantics.""" 

180 

181 config = outbound_proxy_config() 

182 if not config.proxy_urls: 

183 return None 

184 if urllib.request.proxy_bypass('music.youtube.com'): 

185 return {'http': None, 'https': None} 

186 proxies: dict[str, str | None] = {} 

187 for scheme in ('http', 'https'): 

188 proxies[scheme] = config.proxy_urls.get( 

189 scheme 

190 ) or config.proxy_urls.get('all') 

191 return proxies