• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

plank / laravel-mediable / 44983390593

22 Nov 2026 04:04AM UTC coverage: 93.187% (-0.4%) from 93.58%
44983390593

Pull #405

github

frasmage
rework redirect walking

validate redirects and establish stream from the same connection

add remote_url_timeout configuration
Pull Request #405: rework redirect walking

61 of 76 new or added lines in 2 files covered. (80.26%)

1655 of 1776 relevant lines covered (93.19%)

160.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.46
/src/SourceAdapters/RemoteUrlAdapter.php
1
<?php
2
declare(strict_types=1);
3

4
namespace Plank\Mediable\SourceAdapters;
5

6
use GuzzleHttp\Psr7\Utils;
7
use Plank\Mediable\Exceptions\MediaUpload\ConfigurationException;
8
use Plank\Mediable\Helpers\Stream;
9
use Psr\Http\Message\StreamInterface;
10

11
/**
12
 * URL Adapter.
13
 *
14
 * Adapts a string representing a URL
15
 */
16
class RemoteUrlAdapter extends StreamAdapter
17
{
18
    private Stream $streamHelper;
19
    protected string $url;
20

21
    public function __construct(string $source)
22
    {
23
        $this->url = $source;
102 ✔
24
        try {
25
            $stream = $this->connect($source, config('mediable.max_remote_url_redirects'));
102 ✔
26
        } catch (\RuntimeException $e) {
84 ✔
27
            throw ConfigurationException::invalidSource(
6 ✔
28
                "Failed to connect to URL: {$e->getMessage()}",
6 ✔
29
                $e
6 ✔
30
            );
6 ✔
31
        }
32
        parent::__construct(
36 ✔
33
            $stream
36 ✔
34
        );
36 ✔
35
    }
36

37
    private function connect(string $url, int $maxRedirects): StreamInterface
38
    {
39
        if (config('mediable.validate_remote_url_redirects', true)) {
102 ✔
40
            return $this->walkRedirects($url, $maxRedirects);
102 ✔
41
        }
42

43
        // validate initial URL then blindly follow redirects
NEW
44
        $this->validateUrl($url);
×
NEW
45
        return Utils::streamFor(Utils::tryFopen($url, 'rb'));
×
46
    }
47

48
    private function walkRedirects(string $url, int $maxRedirects): StreamInterface
49
    {
50
        $this->validateUrl($url);
102 ✔
51

52
        $options = [
60 ✔
53
            'http' => [
60 ✔
54
                'method' => 'GET',
60 ✔
55
                'max_redirects' => 0,     // Stop PHP from following Location headers
60 ✔
56
                'ignore_errors' => true,  // Keep the stream open on 3xx/4xx/5xx responses
60 ✔
57
            ],
60 ✔
58
        ];
60 ✔
59
        $timeout = config('mediable.remote_url_timeout');
60 ✔
60
        if ($timeout !== null) {
60 ✔
61
            $options['http']['timeout'] = (float) $timeout;
6 ✔
62
        }
63
        $context = stream_context_create($options);
60 ✔
64
        $handle = Stream::tryFopen($url, 'rb', false, $context);
60 ✔
65

66
        if (!$handle) {
54 ✔
NEW
67
            throw ConfigurationException::invalidSource(
×
NEW
68
                "Failed to connect to URL: failed to connect to remote resource."
×
NEW
69
            );
×
70
        }
71
        // Inspect response headers (including the 'Location' header if redirected)
72
        $headers = stream_get_meta_data($handle)['wrapper_data'] ?? [];
54 ✔
73

74
        // extract status code
75
        preg_match('/HTTP\/\S+\s+(\d{3})/', $headers[0] ?? '', $matches);
54 ✔
76
        $statusCode = isset($matches[1]) ? (int)$matches[1] : null;
54 ✔
77

78
        // handle error codes
79
        if ($statusCode >= 400) {
54 ✔
80
            fclose($handle);
6 ✔
81
            throw ConfigurationException::invalidSource(
6 ✔
82
                "Failed to connect to URL: received $statusCode response code."
6 ✔
83
            );
6 ✔
84
        }
85

86
        // Handle redirect codes (301, 302, 303, 307, 308)
87
        if ($statusCode >= 300) {
48 ✔
88
            fclose($handle);
12 ✔
89
            // 2. Find the Location header (case-insensitive)
90
            $redirectUrl = null;
12 ✔
91
            foreach ($headers as $header) {
12 ✔
92
                if (stripos($header, 'Location:') === 0) {
12 ✔
93
                    $redirectUrl = trim(substr($header, 9));
12 ✔
94
                    break;
12 ✔
95
                }
96
            }
97
            if (empty($redirectUrl)) {
12 ✔
NEW
98
                throw ConfigurationException::invalidSource(
×
NEW
99
                    "Failed to connect to URL: remote URL received $statusCode response code, but no Location header."
×
NEW
100
                );
×
101
            }
102
            if ($maxRedirects < 1) {
12 ✔
103
                throw ConfigurationException::invalidSource(
6 ✔
104
                    'Too many redirects for a remote URL.'
6 ✔
105
                );
6 ✔
106
            }
107
            // Resolve relative paths if the redirect header isn't an absolute URL
108
            if (!str_contains($redirectUrl, '://')) {
12 ✔
109
                $parts = parse_url($url);
6 ✔
110
                $redirectUrl = $parts['scheme'] . '://' . $parts['host'] . '/' . ltrim(
6 ✔
111
                    $redirectUrl,
6 ✔
112
                    '/'
6 ✔
113
                );
6 ✔
114
            }
115
            return $this->walkRedirects($redirectUrl, $maxRedirects - 1);
12 ✔
116
        }
117

118
        return Utils::streamFor($handle);
36 ✔
119
    }
120

121
    private function validateUrl(string $url): void
122
    {
123
        $allowedSchemes = (array) config('mediable.allowed_remote_schemes', ['https']);
102 ✔
124
        $parsed = parse_url($url);
102 ✔
125
        $scheme = $parsed['scheme'] ?? '';
102 ✔
126
        $host = $parsed['host'] ?? '';
102 ✔
127
        if (empty($host) || empty($scheme)) {
102 ✔
128
            throw ConfigurationException::invalidSource(
×
129
                'Remote URL must include a valid scheme and host.'
×
130
            );
×
131
        }
132

133
        if (!empty($allowedSchemes) && !in_array($scheme, $allowedSchemes, true)) {
102 ✔
134
            throw ConfigurationException::invalidSource(
12 ✔
135
                "Remote URL scheme '{$parsed['scheme']}' is not allowed."
12 ✔
136
            );
12 ✔
137
        }
138

139
        $allowedHosts = (array) config('mediable.allowed_remote_hosts', []);
96 ✔
140
        if (!empty($allowedHosts)) {
96 ✔
141
            $matched = false;
24 ✔
142
            foreach ($allowedHosts as $allowedHost) {
24 ✔
143
                if (fnmatch(strtolower($allowedHost), strtolower($host))) {
24 ✔
144
                    $matched = true;
24 ✔
145
                    break;
24 ✔
146
                }
147
            }
148
            if (!$matched) {
24 ✔
149
                throw ConfigurationException::invalidSource(
18 ✔
150
                    'Remote URL host is not in the allowlist.'
18 ✔
151
                );
18 ✔
152
            }
153
        } else {
154
            // If no allowed hosts are specified, automatically prevent private IPs
155
            $ip = gethostbyname($host);
72 ✔
156
            $isPublic = filter_var(
72 ✔
157
                $ip,
72 ✔
158
                FILTER_VALIDATE_IP,
72 ✔
159
                FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
72 ✔
160
            );
72 ✔
161
            if (!$isPublic) {
72 ✔
162
                throw ConfigurationException::invalidSource(
36 ✔
163
                    'Private IP ranges are not permitted for remote URLs.'
36 ✔
164
                );
36 ✔
165
            }
166
        }
167
    }
168

169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function path(): ?string
173
    {
174
        return $this->url;
×
175
    }
176

177
    /**
178
     * {@inheritdoc}
179
     */
180
    public function filename(): ?string
181
    {
182
        return pathinfo(
6 ✔
183
            parse_url($this->url, PHP_URL_PATH),
6 ✔
184
            PATHINFO_FILENAME
6 ✔
185
        ) ?: null;
6 ✔
186
    }
187

188
    /**
189
     * {@inheritdoc}
190
     */
191
    public function extension(): ?string
192
    {
193
        return pathinfo(
6 ✔
194
            parse_url($this->url, PHP_URL_PATH),
6 ✔
195
            PATHINFO_EXTENSION
6 ✔
196
        ) ?: null;
6 ✔
197
    }
198
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc