Skip to content

Commit 89fb17f

Browse files
Only send authentication to the origin of the base URL (#904)
1 parent 45bac88 commit 89fb17f

8 files changed

Lines changed: 241 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [12.1.1] - UPCOMING
9+
10+
* Fix authentication headers being sent to origins other than the base URL (GHSA-9hx4-j425-r37q)
11+
* Stop authenticating requests redirected from an `http` base URL to `https`
12+
* Disable redirect following in Symfony's `Psr18Client` and `HttplugClient`
13+
814
## [12.1.0] - 2026-05-06
915

1016
* Add PHP 8.5 support

‎composer.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@
4343
},
4444
"require-dev": {
4545
"bamarni/composer-bin-plugin": "^1.8.2",
46-
"guzzlehttp/guzzle": "^7.9.2"
46+
"guzzlehttp/guzzle": "^7.9.2",
47+
"symfony/http-client": "^6.4 || ^7.0 || ^8.0"
4748
},
4849
"autoload": {
4950
"psr-4": {

‎phpstan-baseline.neon‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ parameters:
4242
count: 3
4343
path: src/Api/RepositoryFiles.php
4444

45+
-
46+
message: '#^Call to function method_exists\(\) with Symfony\\Component\\HttpClient\\HttplugClient\|Symfony\\Component\\HttpClient\\Psr18Client and ''withOptions'' will always evaluate to true\.$#'
47+
identifier: function.alreadyNarrowedType
48+
count: 1
49+
path: src/HttpClient/Builder.php
50+
4551
-
4652
message: '#^Parameter \#1 \$message of static method Gitlab\\HttpClient\\Message\\ResponseMediator\:\:getMessageAsString\(\) expects array, mixed given\.$#'
4753
identifier: argument.type

‎src/Client.php‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
use Psr\Http\Client\ClientInterface;
6464
use Psr\Http\Message\ResponseInterface;
6565
use Psr\Http\Message\StreamFactoryInterface;
66+
use Psr\Http\Message\UriInterface;
6667

6768
/**
6869
* Simple API wrapper for Gitlab.
@@ -108,11 +109,14 @@ class Client
108109

109110
private readonly Builder $httpClientBuilder;
110111
private readonly History $responseHistory;
112+
private UriInterface $url;
113+
private ?Authentication $authentication = null;
111114

112115
public function __construct(?Builder $httpClientBuilder = null)
113116
{
114117
$this->httpClientBuilder = $builder = $httpClientBuilder ?? new Builder();
115118
$this->responseHistory = new History();
119+
$this->url = $builder->getUriFactory()->createUri(self::BASE_URL);
116120

117121
$builder->addPlugin(new ExceptionThrower());
118122
$builder->addPlugin(new HistoryPlugin($this->responseHistory));
@@ -327,16 +331,26 @@ public function wiki(): Wiki
327331
*/
328332
public function authenticate(#[\SensitiveParameter] string $token, string $authMethod, ?string $sudo = null): void
329333
{
334+
$this->authentication = new Authentication($authMethod, $token, $sudo, $this->url);
335+
330336
$this->getHttpClientBuilder()->removePlugin(Authentication::class);
331-
$this->getHttpClientBuilder()->addPlugin(new Authentication($authMethod, $token, $sudo));
337+
$this->getHttpClientBuilder()->addPlugin($this->authentication);
332338
}
333339

334340
public function setUrl(string $url): void
335341
{
336-
$uri = $this->getHttpClientBuilder()->getUriFactory()->createUri($url);
342+
$this->url = $this->getHttpClientBuilder()->getUriFactory()->createUri($url);
337343

338344
$this->getHttpClientBuilder()->removePlugin(AddHostPlugin::class);
339-
$this->getHttpClientBuilder()->addPlugin(new AddHostPlugin($uri));
345+
$this->getHttpClientBuilder()->addPlugin(new AddHostPlugin($this->url));
346+
347+
if (null !== $this->authentication) {
348+
$this->authentication = $this->authentication->withUrl($this->url);
349+
350+
// the authentication plugin must run after the host plugin
351+
$this->getHttpClientBuilder()->removePlugin(Authentication::class);
352+
$this->getHttpClientBuilder()->addPlugin($this->authentication);
353+
}
340354
}
341355

342356
/**

‎src/HttpClient/Builder.php‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
use Psr\Http\Message\RequestFactoryInterface;
2828
use Psr\Http\Message\StreamFactoryInterface;
2929
use Psr\Http\Message\UriFactoryInterface;
30+
use Symfony\Component\HttpClient\HttplugClient;
31+
use Symfony\Component\HttpClient\Psr18Client;
3032

3133
/**
3234
* The HTTP client builder class.
@@ -58,7 +60,7 @@ public function __construct(
5860
?StreamFactoryInterface $streamFactory = null,
5961
?UriFactoryInterface $uriFactory = null
6062
) {
61-
$this->httpClient = $httpClient ?? Psr18ClientDiscovery::find();
63+
$this->httpClient = self::withoutRedirects($httpClient ?? Psr18ClientDiscovery::find());
6264
$this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory();
6365
$this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();
6466
$this->uriFactory = $uriFactory ?? Psr17FactoryDiscovery::findUriFactory();
@@ -153,4 +155,13 @@ public function removeCache(): void
153155
$this->cachePlugin = null;
154156
$this->pluginClient = null;
155157
}
158+
159+
private static function withoutRedirects(ClientInterface $httpClient): ClientInterface
160+
{
161+
if (($httpClient instanceof Psr18Client || $httpClient instanceof HttplugClient) && \method_exists($httpClient, 'withOptions')) {
162+
return $httpClient->withOptions(['max_redirects' => 0]);
163+
}
164+
165+
return $httpClient;
166+
}
156167
}

‎src/HttpClient/Plugin/Authentication.php‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use Http\Promise\Promise;
2121
use Psr\Http\Message\RequestInterface;
2222
use Psr\Http\Message\ResponseInterface;
23+
use Psr\Http\Message\UriInterface;
2324

2425
/**
2526
* Add authentication to the request.
@@ -36,9 +37,20 @@ final class Authentication implements Plugin
3637
*/
3738
private readonly array $headers;
3839

39-
public function __construct(string $method, #[\SensitiveParameter] string $token, ?string $sudo = null)
40+
private UriInterface $url;
41+
42+
public function __construct(string $method, #[\SensitiveParameter] string $token, ?string $sudo, UriInterface $url)
4043
{
4144
$this->headers = self::buildHeaders($method, $token, $sudo);
45+
$this->url = $url;
46+
}
47+
48+
public function withUrl(UriInterface $url): self
49+
{
50+
$plugin = clone $this;
51+
$plugin->url = $url;
52+
53+
return $plugin;
4254
}
4355

4456
/**
@@ -48,13 +60,34 @@ public function __construct(string $method, #[\SensitiveParameter] string $token
4860
*/
4961
public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
5062
{
63+
$sameOrigin = self::isSameOrigin($request->getUri(), $this->url);
64+
$credential = (string) \array_key_first($this->headers);
65+
$carried = $request->getHeaderLine($credential) === $this->headers[$credential];
66+
5167
foreach ($this->headers as $header => $value) {
52-
$request = $request->withHeader($header, $value);
68+
if ($sameOrigin) {
69+
$request = $request->withHeader($header, $value);
70+
} elseif ($carried && $request->getHeaderLine($header) === $value) {
71+
// a redirected request already carries it
72+
$request = $request->withoutHeader($header);
73+
}
5374
}
5475

5576
return $next($request);
5677
}
5778

79+
private static function isSameOrigin(UriInterface $a, UriInterface $b): bool
80+
{
81+
return 0 === \strcasecmp($a->getScheme(), $b->getScheme())
82+
&& 0 === \strcasecmp($a->getHost(), $b->getHost())
83+
&& self::getPort($a) === self::getPort($b);
84+
}
85+
86+
private static function getPort(UriInterface $uri): ?int
87+
{
88+
return $uri->getPort() ?? ['http' => 80, 'https' => 443][\strtolower($uri->getScheme())] ?? null;
89+
}
90+
5891
/**
5992
* Build the headers to be attached to the request.
6093
*

‎tests/ClientTest.php‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,12 @@
1515
namespace Gitlab\Tests;
1616

1717
use Gitlab\Client;
18+
use GuzzleHttp\Psr7\Response;
1819
use Http\Client\Common\HttpMethodsClient;
20+
use PHPUnit\Framework\Attributes\DataProvider;
1921
use PHPUnit\Framework\TestCase;
22+
use Psr\Http\Client\ClientInterface;
23+
use Psr\Http\Message\RequestInterface;
2024

2125
class ClientTest extends TestCase
2226
{
@@ -27,4 +31,127 @@ public function testCreateClient(): void
2731
$this->assertInstanceOf(Client::class, $client);
2832
$this->assertInstanceOf(HttpMethodsClient::class, $client->getHttpClient());
2933
}
34+
35+
public static function authenticationProvider(): array
36+
{
37+
return [
38+
Client::AUTH_HTTP_TOKEN => [Client::AUTH_HTTP_TOKEN, 'PRIVATE-TOKEN', 'my-token'],
39+
Client::AUTH_HTTP_JOB_TOKEN => [Client::AUTH_HTTP_JOB_TOKEN, 'JOB-TOKEN', 'my-token'],
40+
Client::AUTH_OAUTH_TOKEN => [Client::AUTH_OAUTH_TOKEN, 'Authorization', 'Bearer my-token'],
41+
];
42+
}
43+
44+
#[DataProvider('authenticationProvider')]
45+
public function testAuthenticationIsSentToTheBaseUrl(string $method, string $header, string $value): void
46+
{
47+
$requests = [];
48+
49+
$client = Client::createWithHttpClient($this->createHttpClient($requests));
50+
$client->authenticate('my-token', $method, 'my-user');
51+
$client->getHttpClient()->get('/api/v4/user');
52+
$client->getHttpClient()->get('https://GitLab.com:443/api/v4/projects?page=2');
53+
54+
$this->assertCount(2, $requests);
55+
56+
foreach ($requests as $request) {
57+
$this->assertSame($value, $request->getHeaderLine($header));
58+
$this->assertSame('my-user', $request->getHeaderLine('SUDO'));
59+
}
60+
}
61+
62+
public function testAuthenticationIsNotSentToOtherOrigins(): void
63+
{
64+
$requests = [];
65+
66+
$client = Client::createWithHttpClient($this->createHttpClient($requests));
67+
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN, 'my-user');
68+
$client->getHttpClient()->get('https://about.gitlab.com/api/v4/user');
69+
$client->getHttpClient()->get('http://gitlab.com/api/v4/user');
70+
$client->getHttpClient()->get('https://gitlab.com:8443/api/v4/user');
71+
$client->getHttpClient()->get('https://gitlab.com.example.com/api/v4/user');
72+
73+
$this->assertCount(4, $requests);
74+
75+
foreach ($requests as $request) {
76+
$this->assertFalse($request->hasHeader('PRIVATE-TOKEN'), (string) $request->getUri());
77+
$this->assertFalse($request->hasHeader('SUDO'), (string) $request->getUri());
78+
}
79+
}
80+
81+
#[DataProvider('authenticationProvider')]
82+
public function testAuthenticationIsRemovedFromRequestsToOtherOrigins(string $method, string $header, string $value): void
83+
{
84+
$requests = [];
85+
86+
$client = Client::createWithHttpClient($this->createHttpClient($requests));
87+
$client->authenticate('my-token', $method, 'my-user');
88+
$client->getHttpClient()->get('https://gitlab.example.com/api/v4/user', [$header => $value, 'SUDO' => 'my-user']);
89+
$client->getHttpClient()->get('https://gitlab.example.com/api/v4/user', [$header => 'other-token', 'SUDO' => 'my-user']);
90+
91+
$this->assertFalse($requests[0]->hasHeader($header));
92+
$this->assertFalse($requests[0]->hasHeader('SUDO'));
93+
$this->assertSame('other-token', $requests[1]->getHeaderLine($header));
94+
$this->assertSame('my-user', $requests[1]->getHeaderLine('SUDO'));
95+
}
96+
97+
public function testAuthenticationFollowsTheBaseUrl(): void
98+
{
99+
$requests = [];
100+
101+
$client = Client::createWithHttpClient($this->createHttpClient($requests));
102+
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN);
103+
$client->setUrl('https://gitlab.example.com');
104+
$client->getHttpClient()->get('/api/v4/user');
105+
$client->getHttpClient()->get('https://gitlab.com/api/v4/user');
106+
107+
$this->assertSame('gitlab.example.com', $requests[0]->getUri()->getHost());
108+
$this->assertSame('my-token', $requests[0]->getHeaderLine('PRIVATE-TOKEN'));
109+
$this->assertFalse($requests[1]->hasHeader('PRIVATE-TOKEN'));
110+
}
111+
112+
public function testAuthenticationIsSentToTheBaseUrlOnRedirect(): void
113+
{
114+
$requests = [];
115+
116+
$client = Client::createWithHttpClient($this->createHttpClient($requests, new Response(302, ['Location' => 'https://gitlab.com/api/v4/projects/2'])));
117+
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN);
118+
$client->getHttpClient()->get('/api/v4/projects/1');
119+
120+
$this->assertSame('/api/v4/projects/2', $requests[1]->getUri()->getPath());
121+
$this->assertSame('my-token', $requests[1]->getHeaderLine('PRIVATE-TOKEN'));
122+
}
123+
124+
#[DataProvider('authenticationProvider')]
125+
public function testAuthenticationIsNotSentToOtherOriginsOnRedirect(string $method, string $header, string $value): void
126+
{
127+
$requests = [];
128+
129+
$client = Client::createWithHttpClient($this->createHttpClient($requests, new Response(302, ['Location' => 'https://storage.example.com/artifacts.zip?Signature=abc'])));
130+
$client->authenticate('my-token', $method, 'my-user');
131+
$client->jobs()->artifacts(1, 2);
132+
133+
$this->assertSame($value, $requests[0]->getHeaderLine($header));
134+
$this->assertSame('my-user', $requests[0]->getHeaderLine('SUDO'));
135+
$this->assertSame('storage.example.com', $requests[1]->getUri()->getHost());
136+
$this->assertFalse($requests[1]->hasHeader($header));
137+
$this->assertFalse($requests[1]->hasHeader('SUDO'));
138+
}
139+
140+
/**
141+
* @param RequestInterface[] $requests
142+
*/
143+
private function createHttpClient(array &$requests, Response ...$responses): ClientInterface
144+
{
145+
$httpClient = $this->createMock(ClientInterface::class);
146+
$httpClient
147+
->expects($this->any())
148+
->method('sendRequest')
149+
->willReturnCallback(static function (RequestInterface $request) use (&$requests, &$responses): Response {
150+
$requests[] = $request;
151+
152+
return \array_shift($responses) ?? new Response();
153+
});
154+
155+
return $httpClient;
156+
}
30157
}

‎tests/HttpClient/BuilderTest.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
use Psr\Http\Client\ClientInterface;
2323
use Psr\Http\Message\RequestFactoryInterface;
2424
use Psr\Http\Message\StreamFactoryInterface;
25+
use Symfony\Component\HttpClient\HttplugClient;
26+
use Symfony\Component\HttpClient\MockHttpClient;
27+
use Symfony\Component\HttpClient\Psr18Client;
28+
use Symfony\Component\HttpClient\Response\MockResponse;
2529

2630
/**
2731
* @author Fabien Bourigault <bourigaultfabien@gmail.com>
@@ -65,6 +69,38 @@ public function testHttpClientShouldBeAnHttpMethodsClient(): void
6569
$this->assertInstanceOf(HttpMethodsClientInterface::class, $this->subject->getHttpClient());
6670
}
6771

72+
public function testSymfonyPsr18ClientShouldNotFollowRedirects(): void
73+
{
74+
$maxRedirects = null;
75+
76+
$httpClient = new MockHttpClient(static function (string $method, string $url, array $options) use (&$maxRedirects): MockResponse {
77+
$maxRedirects = $options['max_redirects'];
78+
79+
return new MockResponse();
80+
});
81+
82+
$builder = new Builder(new Psr18Client($httpClient));
83+
$builder->getHttpClient()->get('https://gitlab.com/api/v4/version');
84+
85+
$this->assertSame(0, $maxRedirects);
86+
}
87+
88+
public function testSymfonyHttplugClientShouldNotFollowRedirects(): void
89+
{
90+
$maxRedirects = null;
91+
92+
$httpClient = new MockHttpClient(static function (string $method, string $url, array $options) use (&$maxRedirects): MockResponse {
93+
$maxRedirects = $options['max_redirects'];
94+
95+
return new MockResponse();
96+
});
97+
98+
$builder = new Builder(new HttplugClient($httpClient));
99+
$builder->getHttpClient()->get('https://gitlab.com/api/v4/version');
100+
101+
$this->assertSame(0, $maxRedirects);
102+
}
103+
68104
public function testStreamFactoryShouldBeAStreamFactory(): void
69105
{
70106
$this->assertInstanceOf(StreamFactoryInterface::class, $this->subject->getStreamFactory());

0 commit comments

Comments
 (0)