Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [12.1.1] - UPCOMING

* Fix authentication headers being sent to origins other than the base URL (GHSA-9hx4-j425-r37q)
* Stop authenticating requests redirected from an `http` base URL to `https`
* Disable redirect following in Symfony's `Psr18Client` and `HttplugClient`

## [12.1.0] - 2026-05-06

* Add PHP 8.5 support
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"guzzlehttp/guzzle": "^7.9.2"
"guzzlehttp/guzzle": "^7.9.2",
"symfony/http-client": "^6.4 || ^7.0 || ^8.0"
},
"autoload": {
"psr-4": {
Expand Down
6 changes: 6 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ parameters:
count: 3
path: src/Api/RepositoryFiles.php

-
message: '#^Call to function method_exists\(\) with Symfony\\Component\\HttpClient\\HttplugClient\|Symfony\\Component\\HttpClient\\Psr18Client and ''withOptions'' will always evaluate to true\.$#'
identifier: function.alreadyNarrowedType
count: 1
path: src/HttpClient/Builder.php

-
message: '#^Parameter \#1 \$message of static method Gitlab\\HttpClient\\Message\\ResponseMediator\:\:getMessageAsString\(\) expects array, mixed given\.$#'
identifier: argument.type
Expand Down
20 changes: 17 additions & 3 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriInterface;

/**
* Simple API wrapper for Gitlab.
Expand Down Expand Up @@ -108,11 +109,14 @@ class Client

private readonly Builder $httpClientBuilder;
private readonly History $responseHistory;
private UriInterface $url;
private ?Authentication $authentication = null;

public function __construct(?Builder $httpClientBuilder = null)
{
$this->httpClientBuilder = $builder = $httpClientBuilder ?? new Builder();
$this->responseHistory = new History();
$this->url = $builder->getUriFactory()->createUri(self::BASE_URL);

$builder->addPlugin(new ExceptionThrower());
$builder->addPlugin(new HistoryPlugin($this->responseHistory));
Expand Down Expand Up @@ -327,16 +331,26 @@ public function wiki(): Wiki
*/
public function authenticate(#[\SensitiveParameter] string $token, string $authMethod, ?string $sudo = null): void
{
$this->authentication = new Authentication($authMethod, $token, $sudo, $this->url);

$this->getHttpClientBuilder()->removePlugin(Authentication::class);
$this->getHttpClientBuilder()->addPlugin(new Authentication($authMethod, $token, $sudo));
$this->getHttpClientBuilder()->addPlugin($this->authentication);
}

public function setUrl(string $url): void
{
$uri = $this->getHttpClientBuilder()->getUriFactory()->createUri($url);
$this->url = $this->getHttpClientBuilder()->getUriFactory()->createUri($url);

$this->getHttpClientBuilder()->removePlugin(AddHostPlugin::class);
$this->getHttpClientBuilder()->addPlugin(new AddHostPlugin($uri));
$this->getHttpClientBuilder()->addPlugin(new AddHostPlugin($this->url));

if (null !== $this->authentication) {
$this->authentication = $this->authentication->withUrl($this->url);

// the authentication plugin must run after the host plugin
$this->getHttpClientBuilder()->removePlugin(Authentication::class);
$this->getHttpClientBuilder()->addPlugin($this->authentication);
}
}

/**
Expand Down
13 changes: 12 additions & 1 deletion src/HttpClient/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Symfony\Component\HttpClient\HttplugClient;
use Symfony\Component\HttpClient\Psr18Client;

/**
* The HTTP client builder class.
Expand Down Expand Up @@ -58,7 +60,7 @@ public function __construct(
?StreamFactoryInterface $streamFactory = null,
?UriFactoryInterface $uriFactory = null
) {
$this->httpClient = $httpClient ?? Psr18ClientDiscovery::find();
$this->httpClient = self::withoutRedirects($httpClient ?? Psr18ClientDiscovery::find());
$this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory();
$this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();
$this->uriFactory = $uriFactory ?? Psr17FactoryDiscovery::findUriFactory();
Expand Down Expand Up @@ -153,4 +155,13 @@ public function removeCache(): void
$this->cachePlugin = null;
$this->pluginClient = null;
}

private static function withoutRedirects(ClientInterface $httpClient): ClientInterface
{
if (($httpClient instanceof Psr18Client || $httpClient instanceof HttplugClient) && \method_exists($httpClient, 'withOptions')) {
return $httpClient->withOptions(['max_redirects' => 0]);
}

return $httpClient;
}
}
37 changes: 35 additions & 2 deletions src/HttpClient/Plugin/Authentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

/**
* Add authentication to the request.
Expand All @@ -36,9 +37,20 @@ final class Authentication implements Plugin
*/
private readonly array $headers;

public function __construct(string $method, #[\SensitiveParameter] string $token, ?string $sudo = null)
private UriInterface $url;

public function __construct(string $method, #[\SensitiveParameter] string $token, ?string $sudo, UriInterface $url)
{
$this->headers = self::buildHeaders($method, $token, $sudo);
$this->url = $url;
}

public function withUrl(UriInterface $url): self
{
$plugin = clone $this;
$plugin->url = $url;

return $plugin;
}

/**
Expand All @@ -48,13 +60,34 @@ public function __construct(string $method, #[\SensitiveParameter] string $token
*/
public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
{
$sameOrigin = self::isSameOrigin($request->getUri(), $this->url);
$credential = (string) \array_key_first($this->headers);
$carried = $request->getHeaderLine($credential) === $this->headers[$credential];

foreach ($this->headers as $header => $value) {
$request = $request->withHeader($header, $value);
if ($sameOrigin) {
$request = $request->withHeader($header, $value);
} elseif ($carried && $request->getHeaderLine($header) === $value) {
// a redirected request already carries it
$request = $request->withoutHeader($header);
}
}

return $next($request);
}

private static function isSameOrigin(UriInterface $a, UriInterface $b): bool
{
return 0 === \strcasecmp($a->getScheme(), $b->getScheme())
&& 0 === \strcasecmp($a->getHost(), $b->getHost())
&& self::getPort($a) === self::getPort($b);
}

private static function getPort(UriInterface $uri): ?int
{
return $uri->getPort() ?? ['http' => 80, 'https' => 443][\strtolower($uri->getScheme())] ?? null;
}

/**
* Build the headers to be attached to the request.
*
Expand Down
127 changes: 127 additions & 0 deletions tests/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@
namespace Gitlab\Tests;

use Gitlab\Client;
use GuzzleHttp\Psr7\Response;
use Http\Client\Common\HttpMethodsClient;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;

class ClientTest extends TestCase
{
Expand All @@ -27,4 +31,127 @@ public function testCreateClient(): void
$this->assertInstanceOf(Client::class, $client);
$this->assertInstanceOf(HttpMethodsClient::class, $client->getHttpClient());
}

public static function authenticationProvider(): array
{
return [
Client::AUTH_HTTP_TOKEN => [Client::AUTH_HTTP_TOKEN, 'PRIVATE-TOKEN', 'my-token'],
Client::AUTH_HTTP_JOB_TOKEN => [Client::AUTH_HTTP_JOB_TOKEN, 'JOB-TOKEN', 'my-token'],
Client::AUTH_OAUTH_TOKEN => [Client::AUTH_OAUTH_TOKEN, 'Authorization', 'Bearer my-token'],
];
}

#[DataProvider('authenticationProvider')]
public function testAuthenticationIsSentToTheBaseUrl(string $method, string $header, string $value): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests));
$client->authenticate('my-token', $method, 'my-user');
$client->getHttpClient()->get('/api/v4/user');
$client->getHttpClient()->get('https://GitLab.com:443/api/v4/projects?page=2');

$this->assertCount(2, $requests);

foreach ($requests as $request) {
$this->assertSame($value, $request->getHeaderLine($header));
$this->assertSame('my-user', $request->getHeaderLine('SUDO'));
}
}

public function testAuthenticationIsNotSentToOtherOrigins(): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests));
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN, 'my-user');
$client->getHttpClient()->get('https://about.gitlab.com/api/v4/user');
$client->getHttpClient()->get('http://gitlab.com/api/v4/user');
$client->getHttpClient()->get('https://gitlab.com:8443/api/v4/user');
$client->getHttpClient()->get('https://gitlab.com.example.com/api/v4/user');

$this->assertCount(4, $requests);

foreach ($requests as $request) {
$this->assertFalse($request->hasHeader('PRIVATE-TOKEN'), (string) $request->getUri());
$this->assertFalse($request->hasHeader('SUDO'), (string) $request->getUri());
}
}

#[DataProvider('authenticationProvider')]
public function testAuthenticationIsRemovedFromRequestsToOtherOrigins(string $method, string $header, string $value): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests));
$client->authenticate('my-token', $method, 'my-user');
$client->getHttpClient()->get('https://gitlab.example.com/api/v4/user', [$header => $value, 'SUDO' => 'my-user']);
$client->getHttpClient()->get('https://gitlab.example.com/api/v4/user', [$header => 'other-token', 'SUDO' => 'my-user']);

$this->assertFalse($requests[0]->hasHeader($header));
$this->assertFalse($requests[0]->hasHeader('SUDO'));
$this->assertSame('other-token', $requests[1]->getHeaderLine($header));
$this->assertSame('my-user', $requests[1]->getHeaderLine('SUDO'));
}

public function testAuthenticationFollowsTheBaseUrl(): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests));
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN);
$client->setUrl('https://gitlab.example.com');
$client->getHttpClient()->get('/api/v4/user');
$client->getHttpClient()->get('https://gitlab.com/api/v4/user');

$this->assertSame('gitlab.example.com', $requests[0]->getUri()->getHost());
$this->assertSame('my-token', $requests[0]->getHeaderLine('PRIVATE-TOKEN'));
$this->assertFalse($requests[1]->hasHeader('PRIVATE-TOKEN'));
}

public function testAuthenticationIsSentToTheBaseUrlOnRedirect(): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests, new Response(302, ['Location' => 'https://gitlab.com/api/v4/projects/2'])));
$client->authenticate('my-token', Client::AUTH_HTTP_TOKEN);
$client->getHttpClient()->get('/api/v4/projects/1');

$this->assertSame('/api/v4/projects/2', $requests[1]->getUri()->getPath());
$this->assertSame('my-token', $requests[1]->getHeaderLine('PRIVATE-TOKEN'));
}

#[DataProvider('authenticationProvider')]
public function testAuthenticationIsNotSentToOtherOriginsOnRedirect(string $method, string $header, string $value): void
{
$requests = [];

$client = Client::createWithHttpClient($this->createHttpClient($requests, new Response(302, ['Location' => 'https://storage.example.com/artifacts.zip?Signature=abc'])));
$client->authenticate('my-token', $method, 'my-user');
$client->jobs()->artifacts(1, 2);

$this->assertSame($value, $requests[0]->getHeaderLine($header));
$this->assertSame('my-user', $requests[0]->getHeaderLine('SUDO'));
$this->assertSame('storage.example.com', $requests[1]->getUri()->getHost());
$this->assertFalse($requests[1]->hasHeader($header));
$this->assertFalse($requests[1]->hasHeader('SUDO'));
}

/**
* @param RequestInterface[] $requests
*/
private function createHttpClient(array &$requests, Response ...$responses): ClientInterface
{
$httpClient = $this->createMock(ClientInterface::class);
$httpClient
->expects($this->any())
->method('sendRequest')
->willReturnCallback(static function (RequestInterface $request) use (&$requests, &$responses): Response {
$requests[] = $request;

return \array_shift($responses) ?? new Response();
});

return $httpClient;
}
}
36 changes: 36 additions & 0 deletions tests/HttpClient/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Symfony\Component\HttpClient\HttplugClient;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpClient\Response\MockResponse;

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

public function testSymfonyPsr18ClientShouldNotFollowRedirects(): void
{
$maxRedirects = null;

$httpClient = new MockHttpClient(static function (string $method, string $url, array $options) use (&$maxRedirects): MockResponse {
$maxRedirects = $options['max_redirects'];

return new MockResponse();
});

$builder = new Builder(new Psr18Client($httpClient));
$builder->getHttpClient()->get('https://gitlab.com/api/v4/version');

$this->assertSame(0, $maxRedirects);
}

public function testSymfonyHttplugClientShouldNotFollowRedirects(): void
{
$maxRedirects = null;

$httpClient = new MockHttpClient(static function (string $method, string $url, array $options) use (&$maxRedirects): MockResponse {
$maxRedirects = $options['max_redirects'];

return new MockResponse();
});

$builder = new Builder(new HttplugClient($httpClient));
$builder->getHttpClient()->get('https://gitlab.com/api/v4/version');

$this->assertSame(0, $maxRedirects);
}

public function testStreamFactoryShouldBeAStreamFactory(): void
{
$this->assertInstanceOf(StreamFactoryInterface::class, $this->subject->getStreamFactory());
Expand Down