File: NoPrivateNetworkHttpClientTest.php

package info (click to toggle)
symfony 7.3.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 129,560 kB
  • sloc: php: 1,503,693; xml: 6,816; javascript: 1,043; sh: 586; makefile: 241; pascal: 70
file content (206 lines) | stat: -rw-r--r-- 7,408 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpClient\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\DnsMock;
use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\NoPrivateNetworkHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

class NoPrivateNetworkHttpClientTest extends TestCase
{
    public static function getExcludeIpData(): array
    {
        return [
            // private
            ['0.0.0.1',     null,          true],
            ['169.254.0.1', null,          true],
            ['127.0.0.1',   null,          true],
            ['240.0.0.1',   null,          true],
            ['10.0.0.1',    null,          true],
            ['172.16.0.1',  null,          true],
            ['192.168.0.1', null,          true],
            ['::1',         null,          true],
            ['::ffff:0:1',  null,          true],
            ['fe80::1',     null,          true],
            ['fc00::1',     null,          true],
            ['fd00::1',     null,          true],
            ['10.0.0.1',    '10.0.0.0/24', true],
            ['10.0.0.1',    '10.0.0.1',    true],
            ['fc00::1',     'fc00::1/120', true],
            ['fc00::1',     'fc00::1',     true],

            ['172.16.0.1',  ['10.0.0.0/8', '192.168.0.0/16'], false],
            ['fc00::1',     ['fe80::/10', '::ffff:0:0/96'],   false],

            // public
            ['104.26.14.6',            null,                false],
            ['104.26.14.6',            '104.26.14.0/24',    true],
            ['2606:4700:20::681a:e06', null,                false],
            ['2606:4700:20::681a:e06', '2606:4700:20::/43', true],
        ];
    }

    public static function getExcludeHostData(): iterable
    {
        yield from self::getExcludeIpData();

        // no ipv4/ipv6 at all
        yield ['2606:4700:20::681a:e06', '::/0',      true];
        yield ['104.26.14.6',            '0.0.0.0/0', true];

        // weird scenarios (e.g.: when trying to match ipv4 address on ipv6 subnet)
        yield ['10.0.0.1', 'fc00::/7',   true];
        yield ['fc00::1',  '10.0.0.0/8', true];
    }

    /**
     * @dataProvider getExcludeIpData
     *
     * @group nophpunit11
     * @group dns-sensitive
     */
    public function testExcludeByIp(string $ipAddr, $subnets, bool $mustThrow)
    {
        $host = strtr($ipAddr, '.:', '--');
        DnsMock::withMockedHosts([
            $host => [
                str_contains($ipAddr, ':') ? [
                    'type' => 'AAAA',
                    'ipv6' => '3706:5700:20::ac43:4826',
                ] : [
                    'type' => 'A',
                    'ip' => '105.26.14.6',
                ],
            ],
        ]);

        $content = 'foo';
        $url = \sprintf('http://%s/', $host);

        if ($mustThrow) {
            $this->expectException(TransportException::class);
            $this->expectExceptionMessage(\sprintf('IP "%s" is blocked for "%s".', $ipAddr, $url));
        }

        $previousHttpClient = $this->getMockHttpClient($ipAddr, $content);
        $client = new NoPrivateNetworkHttpClient($previousHttpClient, $subnets);
        $response = $client->request('GET', $url);

        if (!$mustThrow) {
            $this->assertEquals($content, $response->getContent());
            $this->assertEquals(200, $response->getStatusCode());
        }
    }

    /**
     * @dataProvider getExcludeHostData
     *
     * @group nophpunit11
     * @group dns-sensitive
     */
    public function testExcludeByHost(string $ipAddr, $subnets, bool $mustThrow)
    {
        $host = strtr($ipAddr, '.:', '--');
        DnsMock::withMockedHosts([
            $host => [
                str_contains($ipAddr, ':') ? [
                    'type' => 'AAAA',
                    'ipv6' => $ipAddr,
                ] : [
                    'type' => 'A',
                    'ip' => $ipAddr,
                ],
            ],
        ]);

        $content = 'foo';
        $url = \sprintf('http://%s/', $host);

        if ($mustThrow) {
            $this->expectException(TransportException::class);
            $this->expectExceptionMessage(\sprintf('Host "%s" is blocked for "%s".', $host, $url));
        }

        $previousHttpClient = $this->getMockHttpClient($ipAddr, $content);
        $client = new NoPrivateNetworkHttpClient($previousHttpClient, $subnets);
        $response = $client->request('GET', $url);

        if (!$mustThrow) {
            $this->assertEquals($content, $response->getContent());
            $this->assertEquals(200, $response->getStatusCode());
        }
    }

    public function testCustomOnProgressCallback()
    {
        $ipAddr = '104.26.14.6';
        $url = \sprintf('http://%s/', $ipAddr);
        $content = 'foo';

        $executionCount = 0;
        $customCallback = function (int $dlNow, int $dlSize, array $info) use (&$executionCount): void {
            ++$executionCount;
        };

        $previousHttpClient = $this->getMockHttpClient($ipAddr, $content);
        $client = new NoPrivateNetworkHttpClient($previousHttpClient);
        $response = $client->request('GET', $url, ['on_progress' => $customCallback]);

        $this->assertEquals(1, $executionCount);
        $this->assertEquals($content, $response->getContent());
        $this->assertEquals(200, $response->getStatusCode());
    }

    public function testNonCallableOnProgressCallback()
    {
        $ipAddr = '104.26.14.6';
        $url = \sprintf('http://%s/', $ipAddr);
        $customCallback = \sprintf('cb_%s', microtime(true));

        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Option "on_progress" must be callable, "string" given.');

        $client = new NoPrivateNetworkHttpClient(new MockHttpClient());
        $client->request('GET', $url, ['on_progress' => $customCallback]);
    }

    public function testHeadersArePassedOnRedirect()
    {
        $ipAddr = '104.26.14.6';
        $url = \sprintf('http://%s/', $ipAddr);
        $content = 'foo';

        $callback = function ($method, $url, $options) use ($content): MockResponse {
            $this->assertArrayHasKey('headers', $options);
            $this->assertNotContains('content-type: application/json', $options['headers']);
            $this->assertContains('foo: bar', $options['headers']);

            return new MockResponse($content);
        };
        $responses = [
            new MockResponse('', ['http_code' => 302, 'redirect_url' => 'http://104.26.14.7']),
            $callback,
        ];
        $client = new NoPrivateNetworkHttpClient(new MockHttpClient($responses));
        $response = $client->request('POST', $url, ['headers' => ['foo' => 'bar', 'content-type' => 'application/json']]);
        $this->assertEquals($content, $response->getContent());
    }

    private function getMockHttpClient(string $ipAddr, string $content)
    {
        return new MockHttpClient(new MockResponse($content, ['primary_ip' => $ipAddr]));
    }
}