httpUtilTest.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. declare(strict_types=1);
  3. use PHPUnit\Framework\Attributes\DataProvider;
  4. /**
  5. * Tests for FreshRSS_http_Util
  6. */
  7. final class httpUtilTest extends \PHPUnit\Framework\TestCase {
  8. #[DataProvider('provideUrlsIgnoringHttps')]
  9. public function test_compareUrlIgnoringHttps(string $url1, string $url2, bool $expected): void {
  10. self::assertEquals($expected, FreshRSS_http_Util::compareUrlIgnoringHttps($url1, $url2) === 0);
  11. }
  12. #[DataProvider('provideCurlProxyValues')]
  13. public function test_sanitizeCurlParamsRejectsMalformedProxy(string $proxy, bool $shouldSurvive): void {
  14. $sanitized = FreshRSS_http_Util::sanitizeCurlParams([CURLOPT_PROXY => $proxy, CURLOPT_PROXYTYPE => CURLPROXY_HTTP]);
  15. if ($shouldSurvive) {
  16. self::assertSame($proxy, $sanitized[CURLOPT_PROXY] ?? null);
  17. } else {
  18. self::assertArrayNotHasKey(CURLOPT_PROXY, $sanitized);
  19. }
  20. }
  21. /** @return array<string,array{string,bool}> */
  22. public static function provideCurlProxyValues(): array {
  23. return [
  24. // A second `://` would otherwise be reduced by a greedy scheme-strip to this
  25. // trailing "decoy" host for the allowlist/DNS-pinning check, while cURL still
  26. // received the original, unstripped value as CURLOPT_PROXY.
  27. 'rejects scheme-prefixed decoy host' => ['http://127.0.0.1:8080/://8.8.8.8', false],
  28. 'rejects scheme-less decoy host' => ['127.0.0.1:8080/://198.51.100.10', false],
  29. // The scheme comes from CURLOPT_PROXYTYPE, not the value itself -- a scheme-containing
  30. // value is rejected outright rather than normalised.
  31. 'rejects a value carrying its own scheme' => ['http://proxy.example.com:3128', false],
  32. // cURL treats "host:port/path" as a Unix domain socket for SOCKS proxies and ignores the
  33. // port, so an allowlisted host:port could otherwise be smuggled into connecting to an
  34. // arbitrary local socket.
  35. 'rejects a SOCKS Unix-domain-socket path' => ['localhost:9050/path/to.sock', false],
  36. // Certain characters complicate normalizing of proxy URLs, so they're disallowed.
  37. 'rejects a query delimiter' => ['127.0.0.1?:6379', false],
  38. 'rejects a fragment delimiter' => ['127.0.0.1#:6379', false],
  39. 'rejects a query hiding a decoy host' => ['127.0.0.1?@10.0.0.1:80', false],
  40. 'rejects a fragment hiding a decoy host' => ['8.8.8.8#@127.0.0.1', false],
  41. 'rejects a backslash' => ['127.0.0.1\\@8.8.8.8:80', false],
  42. 'rejects a space' => ['127.0.0.1 :80', false],
  43. 'rejects a tab' => ["127.0.0.1\t:80", false],
  44. 'rejects a newline' => ["127.0.0.1\n:80", false],
  45. 'accepts percent-encoded credentials' => ['user:p%3Fss%23w%40rd@proxy.example.com:3128', true],
  46. 'accepts bare host:port' => ['127.0.0.1:8080', true],
  47. 'accepts hostname:port' => ['proxy.example.com:3128', true],
  48. 'accepts host:port with credentials' => ['user:pass@203.0.113.5:1080', true],
  49. 'accepts an IPv6 proxy' => ['[::1]:8080', true],
  50. ];
  51. }
  52. /**
  53. * @param array<int,mixed> $options
  54. * @param array<int,mixed> $expected
  55. */
  56. #[DataProvider('provideProxyOptions')]
  57. public function test_normalizeProxyOptions(array $options, array $expected): void {
  58. self::assertEquals($expected, FreshRSS_http_Util::normalizeProxyOptions($options));
  59. }
  60. /** @return array<string,array{array<int,mixed>,array<int,mixed>}> */
  61. public static function provideProxyOptions(): array {
  62. return [
  63. 'CURLOPT_PROXYPORT is added' => [
  64. [CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTP, CURLOPT_PROXYPORT => 3128],
  65. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  66. 'port in CURLOPT_PROXY wins' => [
  67. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYPORT => 4000],
  68. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  69. 'scheme in system config' => [
  70. [CURLOPT_PROXY => 'http://proxy.internal:3128/'],
  71. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  72. 'scheme wins over type' => [
  73. [CURLOPT_PROXY => 'socks5h://user:pass@proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTP],
  74. [CURLOPT_PROXY => 'user:pass@proxy.internal:1080', CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5_HOSTNAME]],
  75. 'scheme with CURLOPT_PROXYPORT' => [
  76. [CURLOPT_PROXY => 'http://proxy.internal', CURLOPT_PROXYPORT => 3128],
  77. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  78. 'scheme in uppercase' => [
  79. [CURLOPT_PROXY => 'HTTP://proxy.internal:3128'],
  80. [CURLOPT_PROXY => 'proxy.internal:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  81. 'HTTPS scheme' => [
  82. [CURLOPT_PROXY => 'https://proxy.internal'],
  83. [CURLOPT_PROXY => 'proxy.internal:443', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS]],
  84. 'unsupported scheme is left as is' => [
  85. [CURLOPT_PROXY => 'ftp://proxy.internal:3128'],
  86. [CURLOPT_PROXY => 'ftp://proxy.internal:3128']],
  87. 'default port for HTTPS' => [
  88. [CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS],
  89. [CURLOPT_PROXY => 'proxy.internal:443', CURLOPT_PROXYTYPE => CURLPROXY_HTTPS]],
  90. 'IPv6 without port' => [
  91. [CURLOPT_PROXY => '[::1]', CURLOPT_PROXYPORT => 3128],
  92. [CURLOPT_PROXY => '[::1]:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  93. 'IPv6 with port' => [
  94. [CURLOPT_PROXY => '[::1]:3128'],
  95. [CURLOPT_PROXY => '[::1]:3128', CURLOPT_PROXYTYPE => CURLPROXY_HTTP]],
  96. 'invalid value is left as is' => [
  97. [CURLOPT_PROXY => 'http://127.0.0.1:8080/://8.8.8.8'],
  98. [CURLOPT_PROXY => 'http://127.0.0.1:8080/://8.8.8.8']],
  99. 'query is left as is' => [
  100. [CURLOPT_PROXY => '127.0.0.1?:6379'],
  101. [CURLOPT_PROXY => '127.0.0.1?:6379']],
  102. 'fragment is left as is' => [
  103. [CURLOPT_PROXY => 'http://127.0.0.1#:6379'],
  104. [CURLOPT_PROXY => 'http://127.0.0.1#:6379']],
  105. 'proxy disabled' => [
  106. [CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => -1],
  107. [CURLOPT_PROXY => 'proxy.internal', CURLOPT_PROXYTYPE => -1]],
  108. 'no proxy' => [[CURLOPT_PROXYPORT => 3128], [CURLOPT_PROXYPORT => 3128]],
  109. ];
  110. }
  111. /** An ambiguous feed proxy must be rejected by sanitization, before the port check of `getCurlResolveInfo()`. */
  112. #[DataProvider('provideAmbiguousFeedProxies')]
  113. public function test_feedProxyIsNotAmbiguousForAllowlistCheck(string $proxy): void {
  114. putenv('INTERNAL_HOST_ALLOWLIST=127.0.0.1:80');
  115. try {
  116. $options = FreshRSS_http_Util::normalizeProxyOptions(
  117. FreshRSS_http_Util::sanitizeCurlParams([CURLOPT_PROXY => $proxy, CURLOPT_PROXYTYPE => CURLPROXY_HTTP]));
  118. self::assertArrayNotHasKey(CURLOPT_PROXY, $options);
  119. self::assertArrayNotHasKey(CURLOPT_PROXYTYPE, $options);
  120. } finally {
  121. putenv('INTERNAL_HOST_ALLOWLIST');
  122. }
  123. }
  124. /** @return array<string,array{string}> */
  125. public static function provideAmbiguousFeedProxies(): array {
  126. return [
  127. 'query with port' => ['127.0.0.1?:6379'],
  128. 'fragment with port' => ['127.0.0.1#:6379'],
  129. 'query without port' => ['127.0.0.1?'],
  130. 'fragment without port' => ['127.0.0.1#'],
  131. 'query then credentials' => ['10.0.0.1?@:6379'],
  132. ];
  133. }
  134. public function test_proxyPortIsUsedByAllowlistCheck(): void {
  135. putenv('INTERNAL_HOST_ALLOWLIST=127.0.0.1:3128');
  136. $options = FreshRSS_http_Util::normalizeProxyOptions([CURLOPT_PROXY => '127.0.0.1', CURLOPT_PROXYPORT => 3128]);
  137. self::assertIsString($options[CURLOPT_PROXY]);
  138. self::assertSame([], FreshRSS_http_Util::getCurlResolveInfo('http://' . $options[CURLOPT_PROXY]));
  139. putenv('INTERNAL_HOST_ALLOWLIST');
  140. }
  141. #[DataProvider('provideUrlsForCheckUrl')]
  142. public function test_checkUrl(string $url, string|false $expected): void {
  143. self::assertSame($expected, FreshRSS_http_Util::checkUrl($url));
  144. }
  145. /** @return Traversable<string,array{string,string|false}> */
  146. public static function provideUrlsForCheckUrl(): Traversable {
  147. yield 'plain' => ['https://example.net/feed?a=1&amp;b=2', 'https://example.net/feed?a=1&amp;b=2'];
  148. yield 'underscore' => ['https://ex_ample.net/', 'https://ex_ample.net/'];
  149. yield 'IPv6' => ['https://[2001:db8::1]/feed', 'https://[2001:db8::1]/feed'];
  150. if (function_exists('idn_to_ascii')) {
  151. yield 'IDN' => ['https://bücher.example/feed', 'https://xn--bcher-kva.example/feed'];
  152. yield 'IDN with ideographic full stop' => ['https://日本語。example/', 'https://xn--wgv71a119e.example/'];
  153. }
  154. // IDNA (UTS #46) maps fullwidth punctuation to ASCII: must not produce characters absent from the (possibly HTML-encoded) input
  155. yield 'fullwidth markup in host' => ['https://example.net/"><b>', false];
  156. yield 'fullwidth path and query in host' => ['https://example.net/path?a=1&b=2', false];
  157. yield 'fullwidth userinfo in host' => ['https://example.net@example.org/', false];
  158. }
  159. #[\Override]
  160. protected function tearDown(): void {
  161. FreshRSS_Context::initSystem(reload: true); // Restore the default internal host allowlist
  162. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  163. $resolveOk->setValue(null, []); // Restore the default empty cache
  164. }
  165. #[DataProvider('provideUrlsForRetryAfter')]
  166. public function test_getRetryAfterFile(string $url1, string $url2, bool $sameFile): void {
  167. $getRetryAfterFile = new ReflectionMethod(FreshRSS_http_Util::class, 'getRetryAfterFile');
  168. self::assertSame($sameFile, $getRetryAfterFile->invoke(null, $url1, '') === $getRetryAfterFile->invoke(null, $url2, ''));
  169. }
  170. /** @return array<string,array{string,string,bool}> */
  171. public static function provideUrlsForRetryAfter(): array {
  172. return [
  173. // A public server waits as a whole, per port
  174. 'public server' => ['https://198.51.100.7/feed1', 'https://198.51.100.7/feed2?a=1&b=2', true],
  175. 'public server, other port' => ['https://198.51.100.7/feed', 'https://198.51.100.7:8443/feed', false],
  176. // A server on a local network waits URL by URL
  177. 'local IP address' => ['http://192.168.1.2/feed1', 'http://192.168.1.2/feed2', false],
  178. 'local domain' => ['http://rss-bridge.lan/?bridge=A', 'http://rss-bridge.lan/?bridge=B', false],
  179. 'local, same URL' => ['http://192.168.1.2/feed', 'http://192.168.1.2/feed', true],
  180. ];
  181. }
  182. #[DataProvider('provideUtf8Html')]
  183. public function test_enforceHtmlBase_keepsUtf8InScripts(string $html): void {
  184. $enforceHtmlBase = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHtmlBase');
  185. $result = $enforceHtmlBase->invoke(null, $html, 'https://example.net/page');
  186. self::assertIsString($result);
  187. self::assertStringContainsString('<base href="https://example.net/page">', $result);
  188. self::assertStringContainsString('<script type="application/json">{"title":"Café’s menu — 日本"}</script>', $result);
  189. if (str_starts_with($html, "\xEF\xBB\xBF")) {
  190. self::assertStringStartsWith("\xEF\xBB\xBF", $result);
  191. }
  192. }
  193. /** @return Traversable<string,array{string}> */
  194. public static function provideUtf8Html(): Traversable {
  195. $head = '<html><head><title>T</title></head>';
  196. $body = '<body><p>Café’s menu — 日本</p><script type="application/json">{"title":"Café’s menu — 日本"}</script></body></html>';
  197. yield 'meta charset' => ['<!DOCTYPE html><html><head><meta charset="utf-8"><title>T</title></head>' . $body];
  198. yield 'byte order mark' => ["\xEF\xBB\xBF" . '<!DOCTYPE html>' . $head . $body];
  199. yield 'byte order mark, late <html>' => ["\xEF\xBB\xBF" . '<!DOCTYPE html>' . str_repeat('<!-- padding -->', 40) . $head . $body];
  200. yield 'meta http-equiv' => ['<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>T</title></head>' . $body];
  201. }
  202. /** @return Traversable<string,array{string,string,string}> */
  203. public static function provideLegacyCharsets(): Traversable {
  204. $isoUtf8 = 'M' . "\xC3\xBC" . 'llerstra' . "\xC3\x9F" . 'e';
  205. yield 'iso-8859-1, meta charset' => ['iso-8859-1',
  206. '<!DOCTYPE html><html><head><meta charset="iso-8859-1"></head>' .
  207. '<body><p>M' . "\xFC" . 'llerstra' . "\xDF" . 'e</p></body></html>', $isoUtf8];
  208. // A Windows-1252 body whose quotes differ from the ISO-8859-1 mapping
  209. yield 'windows-1252, smart quotes' => ['windows-1252',
  210. '<!DOCTYPE html><html><head><meta charset="windows-1252"></head>' .
  211. '<body><p>' . "\x93" . 'quoted' . "\x94" . '</p></body></html>', "\xE2\x80\x9C" . 'quoted' . "\xE2\x80\x9D"];
  212. }
  213. // Legacy charsets declared over HTTP must be converted to UTF-8 and not just left
  214. // to the HTML parser, because `saveHTML()` serialises extracted fragments according
  215. // to the encoding of the document, and downstream steps expecting UTF-8 would
  216. // therefore fail on the remaining Windows-1252 bytes (e.g. full-content fetching, issue #9648).
  217. #[DataProvider('provideLegacyCharsets')]
  218. public function test_enforceHttpEncoding_convertsLegacyCharsetsToUtf8(string $httpCharset, string $html, string $expectedUtf8Text): void {
  219. $enforceHttpEncoding = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHttpEncoding');
  220. $result = $enforceHttpEncoding->invoke(null, $html, 'text/html; charset=' . $httpCharset);
  221. self::assertIsString($result);
  222. // The HTTP-declared encoding is enforced by prefixing a Unicode byte order mark
  223. self::assertStringStartsWith("\xEF\xBB\xBF", $result);
  224. self::assertStringContainsString($expectedUtf8Text, $result);
  225. // The obsolete charset declaration is removed, so that the now UTF-8 bytes are not re-read with the declared legacy charset
  226. self::assertStringNotContainsString('<meta', $result);
  227. }
  228. public function test_enforceHttpEncoding_legacyCharset_fragmentSerialization(): void {
  229. $html = '<!DOCTYPE html><html><head><meta charset="iso-8859-1"></head><body><div class="artikel">' .
  230. '<p>Gr' . "\xF6" . 'nemeyer, oft w' . "\xFC" . 'tend</p></div></body></html>';
  231. $enforceHttpEncoding = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHttpEncoding');
  232. $html = $enforceHttpEncoding->invoke(null, $html, 'text/html; charset=iso-8859-1');
  233. self::assertIsString($html);
  234. // Extract a fragment the way done when fetching the full content of an article
  235. $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
  236. $node = $doc->querySelector('div.artikel>p');
  237. self::assertNotNull($node);
  238. self::assertSame('Gr' . "\xC3\xB6" . 'nemeyer, oft w' . "\xC3\xBC" . 'tend', $node->textContent);
  239. $fragment = $doc->saveHTML($node);
  240. // The serialised fragment must remain valid UTF-8 and not be corrupted to U+FFFD replacement characters
  241. self::assertStringContainsString('Gr' . "\xC3\xB6" . 'nemeyer, oft w' . "\xC3\xBC" . 'tend', $fragment);
  242. self::assertStringNotContainsString("\xEF\xBF\xBD", $fragment);
  243. }
  244. public function test_enforceHttpEncoding_usAsciiHttpCharset_unchanged(): void {
  245. $enforceHttpEncoding = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHttpEncoding');
  246. $html = '<p>abcdef</p>';
  247. self::assertSame($html, $enforceHttpEncoding->invoke(null, $html, 'text/html; charset=US-ASCII'));
  248. }
  249. public function test_enforceHttpEncoding_noHttpCharsetLeavesLegacyHtmlUnchanged(): void {
  250. $enforceHttpEncoding = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHttpEncoding');
  251. $html = '<!DOCTYPE html><html><head><meta charset="iso-8859-1"></head><body><p>M' . "\xFC" . 'ller</p></body></html>';
  252. // Without an HTTP-declared charset, a legacy-declared body is left untouched, for the HTML parser to handle it
  253. self::assertSame($html, $enforceHttpEncoding->invoke(null, $html, 'text/html'));
  254. }
  255. public function test_enforceHttpEncoding_utf8HttpCharsetPrefixesByteOrderMark(): void {
  256. $enforceHttpEncoding = new ReflectionMethod(FreshRSS_http_Util::class, 'enforceHttpEncoding');
  257. $html = '<p>M' . "\xC3\xBC" . 'ller</p>';
  258. self::assertSame("\xEF\xBB\xBF" . $html, $enforceHttpEncoding->invoke(null, $html, 'text/html; charset=utf-8'));
  259. }
  260. #[DataProvider('provideCidrRanges')]
  261. public function test_checkCIDR(string $ip, string $range, bool $expected): void {
  262. $checkCIDR = new ReflectionMethod(FreshRSS_http_Util::class, 'checkCIDR');
  263. self::assertEquals($expected, $checkCIDR->invoke(null, $ip, $range));
  264. }
  265. /** @return list<array{string,string,bool}> */
  266. public static function provideCidrRanges(): array {
  267. return [
  268. // A range without a subnet is a single address
  269. ['192.168.1.1', '192.168.1.1', true],
  270. ['192.168.1.2', '192.168.1.1', false],
  271. ['2001:db8::1', '2001:db8::1', true],
  272. ['2001:db8::2', '2001:db8::1', false],
  273. // An explicit subnet keeps working
  274. ['192.168.1.1', '192.168.1.1/32', true],
  275. ['192.168.1.42', '192.168.1.0/24', true],
  276. ['192.168.2.42', '192.168.1.0/24', false],
  277. ['192.168.1.1', '0.0.0.0/0', true],
  278. ['2001:db8::1', '2001:db8::/32', true],
  279. // Invalid input is still rejected
  280. ['192.168.1.1', '', false],
  281. ['192.168.1.1', '192.168.1.1/', false],
  282. ['192.168.1.1', '192.168.1.1/33', false],
  283. ['192.168.1.1', '192.168.1.1/abc', false],
  284. ['192.168.1.1', 'gateway.localdomain', false],
  285. ['192.168.1.1', '2001:db8::1', false],
  286. ['not-an-ip', '192.168.1.1', false],
  287. ];
  288. }
  289. /** @return list<array{string,string,bool}> */
  290. public static function provideUrlsIgnoringHttps(): array {
  291. return [
  292. // Only the scheme differs → equal
  293. ['http://www.blogger.com/feeds/1/posts', 'https://www.blogger.com/feeds/1/posts', true],
  294. ['https://example.net/feed.xml?a=1&b=2', 'http://example.net/feed.xml?a=1&b=2', true],
  295. ['HTTP://Example.net/Feed', 'https://Example.net/Feed', true],
  296. ['HTTPS://Example.net/Feed', 'http://Example.net/Feed', true],
  297. // Fully identical → equal
  298. ['https://example.net/feed', 'https://example.net/feed', true],
  299. ['', '', true],
  300. // Path differs → not equal (scheme-only tolerance must not hide real mismatches)
  301. ['http://example.net/a', 'https://example.net/b', false],
  302. // Trailing slash is a path difference → not equal
  303. ['http://example.net/', 'https://example.net', false],
  304. // Host differs → not equal
  305. ['http://a.example.net/feed', 'https://b.example.net/feed', false],
  306. // Query differs → not equal
  307. ['https://example.net/feed?a=1', 'http://example.net/feed?a=2', false],
  308. // Non-http(s) schemes are compared as-is
  309. ['ftp://example.net/feed', 'https://example.net/feed', false],
  310. ];
  311. }
  312. public function test_getCurlResolveInfoAcceptsPublicNat64Address(): void {
  313. FreshRSS_Context::initSystem();
  314. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  315. $resolveOk->setValue(null, [
  316. 'example.test' => [
  317. '192.0.66.96',
  318. '64:ff9b::c000:4260',
  319. ],
  320. ]);
  321. self::assertSame(
  322. ['example.test:443:192.0.66.96,[64:ff9b::c000:4260]'],
  323. FreshRSS_http_Util::getCurlResolveInfo('https://example.test/feed')
  324. );
  325. }
  326. #[DataProvider('providePrivateSubnets')]
  327. public function test_getCurlResolveInfoRejectsPrivateSubnets(string $ip): void {
  328. FreshRSS_Context::initSystem();
  329. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  330. $resolveOk->setValue(null, ['example.test' => [$ip]]);
  331. self::assertNull(FreshRSS_http_Util::getCurlResolveInfo('https://example.test/feed'));
  332. }
  333. /** @return array<string,array{string}> */
  334. public static function providePrivateSubnets(): array {
  335. return [
  336. // One example per range, ensuring FILTER_FLAG_GLOBAL_RANGE and custom checks are sufficient
  337. '0.0.0.0/8' => ['0.0.0.5'], // RFC5735
  338. '3fff::/20' => ['3fff::1'], // RFC9637 (Documentation)
  339. '5f00::/16' => ['5f00::1'], // RFC9602 (SRv6 SIDs)
  340. '10.0.0.0/8' => ['10.0.0.5'], // RFC1918
  341. '64:ff9b:1::/48' => ['64:ff9b:1::c000:4260'], // RFC8215 (Local-Use IPv4/IPv6 Translation Prefix)
  342. '64:ff9b::/96' => ['64:ff9b::a9fe:a9fe'], // RFC6052 (IPv4/IPv6 Translator, NAT64)
  343. '100.64.0.0/10' => ['100.64.5.5'], // RFC6598 (Shared Address Space of Carrier-Grade NAT)
  344. '100:0:0:1::/64' => ['100:0:0:1::1'], // RFC9780 (Dummy IPv6 Prefix)
  345. '127.0.0.0/8' => ['127.0.0.1'], // RFC1700 (Loopback)
  346. '169.254.0.0/16' => ['169.254.5.5'], // RFC3927
  347. '172.16.0.0/12' => ['172.16.5.5'], // RFC1918
  348. '192.0.0.0/24' => ['192.0.0.170'], // RFC6890 (IETF Protocol Assignments)
  349. '192.0.2.0/24' => ['192.0.2.1'], // RFC5737 (TEST-NET-1)
  350. '192.88.99.0/24' => ['192.88.99.1'], // RFC7526 (deprecated 6to4 anycast)
  351. '192.168.0.0/16' => ['192.168.1.5'], // RFC1918
  352. '198.18.0.0/15' => ['198.18.0.1'], // RFC2544 (Benchmarking)
  353. '198.18.0.0/15 upper' => ['198.19.255.255'],
  354. '198.51.100.0/24' => ['198.51.100.1'], // RFC5737 (TEST-NET-2)
  355. '203.0.113.0/24' => ['203.0.113.1'], // RFC5737 (TEST-NET-3)
  356. '224.0.0.0/4' => ['224.0.0.1'], // RFC1112 (IPv4 multicast)
  357. '224.0.0.0/4 upper' => ['239.255.255.255'],
  358. '240.0.0.0/4' => ['240.0.0.5'], // RFC1112
  359. '2001::/32' => ['2001::1'], // RFC4380 (Teredo)
  360. '2002::/16' => ['2002::1'], // RFC3056 (6to4)
  361. '2002::/16 upper' => ['2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff'],
  362. '::/128' => ['::'], // Unspecified address
  363. '::1/128' => ['::1'], // Loopback
  364. '::ffff:0:0/96' => ['::ffff:10.0.0.5'], // IPv4 translations
  365. 'fc00::/7' => ['fc00::5'], // Unique Local Address
  366. 'fe80::/10' => ['fe80::5'], // Link Local Address
  367. 'fec0::/10' => ['fec0::1'], // RFC3879 (deprecated site-local)
  368. 'fec0::/10 upper' => ['feff::1'],
  369. 'ff00::/8' => ['ff02::1'], // RFC4291 (IPv6 multicast)
  370. ];
  371. }
  372. #[DataProvider('providePublicAddresses')]
  373. public function test_getCurlResolveInfoAcceptsPublicAddresses(string $ip): void {
  374. FreshRSS_Context::initSystem();
  375. $url = str_contains($ip, ':') ? "https://[$ip]/feed" : "https://$ip/feed";
  376. self::assertSame([], FreshRSS_http_Util::getCurlResolveInfo($url));
  377. }
  378. /** @return array<string,array{string}> */
  379. public static function providePublicAddresses(): array {
  380. return [
  381. 'public IPv4 alternate' => ['1.1.1.1'],
  382. 'public IPv4' => ['8.8.8.8'],
  383. 'below deprecated 6to4 anycast' => ['192.88.98.1'],
  384. 'above deprecated 6to4 anycast' => ['192.88.100.1'],
  385. 'below IPv4 multicast' => ['223.255.255.255'],
  386. 'public IPv6' => ['2001:4860:4860::8888'],
  387. 'outside 6to4' => ['2003::1'],
  388. 'outside documentation prefix' => ['3fff:1000::1'],
  389. 'outside SRv6 prefix' => ['5f01::1'],
  390. 'outside dummy IPv6 prefix' => ['100:0:0:2::1'],
  391. 'public NAT64' => ['64:ff9b::c000:4260'], // RFC6052 embedding 192.0.66.96
  392. ];
  393. }
  394. /** cURL would rewrite these hosts, and contact another name or address than the one checked and pinned */
  395. #[DataProvider('provideHostsRewrittenByCurl')]
  396. public function test_getCurlResolveInfoRejectsHostsRewrittenByCurl(string $host): void {
  397. FreshRSS_Context::initSystem();
  398. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  399. $resolveOk->setValue(null, [strtolower($host) => ['192.0.66.96']]);
  400. self::assertFalse(FreshRSS_http_Util::getCurlResolveInfo("http://$host/feed"));
  401. self::assertFalse(FreshRSS_http_Util::getCurlResolveInfo("socks5h://$host:1080"));
  402. }
  403. /** @return array<string,array{string}> */
  404. public static function provideHostsRewrittenByCurl(): array {
  405. return [
  406. 'percent-encoded underscore' => ['a%5F.example.test'], // cURL resolves a_.example.test
  407. 'percent-encoded UTF-8' => ['%C3%A9.example.test'], // cURL resolves xn--9ca.example.test
  408. 'non-ASCII' => ['é.example.test'], // cURL resolves xn--9ca.example.test
  409. 'IPv4 as one number' => ['2130706433'], // cURL connects to 127.0.0.1
  410. 'IPv4 as hexadecimal' => ['0x7f.1'], // cURL connects to 127.0.0.1
  411. 'IPv4 as octal' => ['0177.0.0.1'], // cURL connects to 127.0.0.1
  412. 'IPv4 with fewer parts' => ['127.1'], // cURL connects to 127.0.0.1
  413. ];
  414. }
  415. /** Ordinary host names are still resolved and pinned as written */
  416. public function test_getCurlResolveInfoAcceptsHostsUsedAsWrittenByCurl(): void {
  417. FreshRSS_Context::initSystem();
  418. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  419. foreach (['a_b-c.example.test', 'xn--9ca.example.test', '1.example.test', 'example.7z', 'example.test.'] as $host) {
  420. $resolveOk->setValue(null, [$host => ['192.0.66.96']]);
  421. self::assertSame(["$host:80:192.0.66.96"], FreshRSS_http_Util::getCurlResolveInfo("http://$host/feed"));
  422. }
  423. }
  424. /** Socks schemes default to port 1080, and an IP address proxy produces no resolve entry */
  425. public function test_getCurlResolveInfoForProxyAddress(): void {
  426. FreshRSS_Context::initSystem();
  427. // A proxy on a private address is rejected by default
  428. self::assertNull(FreshRSS_http_Util::getCurlResolveInfo('socks5h://127.0.0.1:1080'));
  429. // Once the proxy is allowlisted, no resolve override is needed for an IP address
  430. FreshRSS_Context::systemConf()->internal_host_allowlist = ['127.0.0.1:1080'];
  431. self::assertSame([], FreshRSS_http_Util::getCurlResolveInfo('socks5h://127.0.0.1:1080'));
  432. // Other proxy ports need their own entry
  433. FreshRSS_Context::systemConf()->internal_host_allowlist = ['127.0.0.1:8080'];
  434. self::assertNull(FreshRSS_http_Util::getCurlResolveInfo('socks5h://127.0.0.1:1080'));
  435. self::assertSame([], FreshRSS_http_Util::getCurlResolveInfo('https://127.0.0.1:8080'));
  436. }
  437. /** For a hostname proxy, the resolved IP of the proxy is pinned with a resolve entry, to prevent DNS rebinding */
  438. public function test_getCurlResolveInfoForProxyHostname(): void {
  439. FreshRSS_Context::initSystem();
  440. $resolveOk = new ReflectionProperty(FreshRSS_http_Util::class, 'resolve_ok');
  441. $resolveOk->setValue(null, ['proxy.example.test' => ['198.51.100.7']]);
  442. FreshRSS_Context::systemConf()->internal_host_allowlist = ['198.51.100.7:1080'];
  443. self::assertSame(
  444. ['proxy.example.test:1080:198.51.100.7'],
  445. FreshRSS_http_Util::getCurlResolveInfo('socks5h://proxy.example.test:1080')
  446. );
  447. // Applications must not emit resolve entries for an address that is not guaranteed public.
  448. // TEST-NET-2 is a reserved range, so without an allowlist entry, no entry is produced.
  449. FreshRSS_Context::systemConf()->internal_host_allowlist = [];
  450. self::assertNull(FreshRSS_http_Util::getCurlResolveInfo('socks5h://proxy.example.test:1080'));
  451. // A genuinely public address produces an entry without allowlisting
  452. $resolveOk->setValue(null, ['public-proxy.example.test' => ['8.8.8.8']]);
  453. self::assertSame(
  454. ['public-proxy.example.test:1080:8.8.8.8'],
  455. FreshRSS_http_Util::getCurlResolveInfo('socks5h://public-proxy.example.test:1080')
  456. );
  457. // A proxy resolving to a private address is rejected unless allowlisted
  458. $resolveOk->setValue(null, ['proxy.example.test' => ['192.168.1.1']]);
  459. self::assertNull(FreshRSS_http_Util::getCurlResolveInfo('socks5h://proxy.example.test:1080'));
  460. FreshRSS_Context::systemConf()->internal_host_allowlist = ['192.168.1.1:1080'];
  461. self::assertSame(
  462. ['proxy.example.test:1080:192.168.1.1'],
  463. FreshRSS_http_Util::getCurlResolveInfo('socks5h://proxy.example.test:1080')
  464. );
  465. }
  466. }