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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ Supported options include `baseUrl`, `timeout` in seconds, `maxRetries`,
additional `headers`, and a custom Guzzle-compatible `client`. The retry limit
defaults to two retries after the initial request.

By default, requests include `User-Agent: upcloud-php-api/<version>`. A
`User-Agent` value supplied in the constructor's `headers` is appended, regardless
of header-name casing: `upcloud-php-api/<version> myapp/1.0`. Empty or
space/tab-only values leave the SDK default unchanged. Per-operation headers can
still override this default; SDK identification is not enforced on every request.
Invalid header values, including CR/LF characters, are rejected by the HTTP
library when building a request, before it is sent.

```php
$client = new UpcloudClient(
token: $token,
Expand Down
8 changes: 8 additions & 0 deletions fern/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ Supported options include `baseUrl`, `timeout` in seconds, `maxRetries`,
additional `headers`, and a custom Guzzle-compatible `client`. The retry limit
defaults to two retries after the initial request.

By default, requests include `User-Agent: upcloud-php-api/<version>`. A
`User-Agent` value supplied in the constructor's `headers` is appended, regardless
of header-name casing: `upcloud-php-api/<version> myapp/1.0`. Empty or
space/tab-only values leave the SDK default unchanged. Per-operation headers can
still override this default; SDK identification is not enforced on every request.
Invalid header values, including CR/LF characters, are rejected by the HTTP
library when building a request, before it is sent.

```php
$client = new UpcloudClient(
token: $token,
Expand Down
25 changes: 21 additions & 4 deletions fern/sdk/src/UpcloudClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,18 +217,35 @@ public function __construct(
string $token,
?array $options = null,
) {
$version = null;
if (class_exists(\Composer\InstalledVersions::class) && \Composer\InstalledVersions::isInstalled('upcloudltd/upcloud-php-api')) {
$version = \Composer\InstalledVersions::getPrettyVersion('upcloudltd/upcloud-php-api');
}
if (!is_string($version) || preg_match('/^[A-Za-z0-9][A-Za-z0-9.+_-]*$/D', $version) !== 1) {
$version = 'unknown';
}

$defaultHeaders = [
'Authorization' => "Bearer $token",
'X-Fern-Language' => 'PHP',
'X-Fern-SDK-Name' => 'Upcloud',
'User-Agent' => 'upcloud-php-api/' . $version,
];

$this->options = $options ?? [];

$this->options['headers'] = array_merge(
$defaultHeaders,
$this->options['headers'] ?? [],
);
$headers = $this->options['headers'] ?? [];
$userAgent = null;
foreach ($headers as $name => $value) {
if (strcasecmp($name, 'User-Agent') === 0) {
$userAgent = trim($value, " \t");
unset($headers[$name]);
}
}
if ($userAgent !== null && $userAgent !== '') {
$defaultHeaders['User-Agent'] .= ' ' . $userAgent;
}
$this->options['headers'] = array_merge($defaultHeaders, $headers);

$this->client = new RawClient(
options: $this->options,
Expand Down
180 changes: 180 additions & 0 deletions fern/sdk/tests/Core/Client/UserAgentTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
<?php

namespace Upcloud\Tests\Core\Client;

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Upcloud\UpcloudClient;

class UserAgentTest extends TestCase
{
private MockHandler $mockHandler;

protected function setUp(): void
{
$this->mockHandler = new MockHandler([new Response(200)]);
}

public function testDefaultUserAgentIsAValidProductToken(): void
{
$request = $this->sendSdkRequest();

$userAgents = $request->getHeader('User-Agent');
$this->assertCount(1, $userAgents);
$this->assertMatchesRegularExpression(
'/^upcloud-php-api\/[A-Za-z0-9][A-Za-z0-9.+_-]*$/D',
$userAgents[0],
);
}

/**
* @dataProvider userAgentHeaderNames
*/
public function testApplicationUserAgentIsAppendedCaseInsensitively(string $name): void
{
$request = $this->sendSdkRequest([$name => 'myapp/1.0']);

$userAgents = $request->getHeader('User-Agent');
$this->assertCount(1, $userAgents);
$this->assertStringStartsWith('upcloud-php-api/', $userAgents[0]);
$this->assertStringEndsWith(' myapp/1.0', $userAgents[0]);
$this->assertMatchesRegularExpression(
'/^upcloud-php-api\/[A-Za-z0-9][A-Za-z0-9.+_-]* myapp\/1\.0$/D',
$userAgents[0],
);
}

/**
* @return array<string, array{string}>
*/
public static function userAgentHeaderNames(): array
{
return [
'canonical' => ['User-Agent'],
'lowercase' => ['user-agent'],
'mixed case' => ['uSeR-aGeNt'],
];
}

/**
* @dataProvider blankUserAgents
*/
public function testBlankApplicationUserAgentLeavesDefaultUnchanged(string $value): void
{
$request = $this->sendSdkRequest(['User-Agent' => $value]);

$userAgents = $request->getHeader('User-Agent');
$this->assertCount(1, $userAgents);
$this->assertMatchesRegularExpression(
'/^upcloud-php-api\/[A-Za-z0-9][A-Za-z0-9.+_-]*$/D',
$userAgents[0],
);
}

/**
* @return array<string, array{string}>
*/
public static function blankUserAgents(): array
{
return [
'empty' => [''],
'spaces' => [' '],
'spaces and tabs' => [" \t "],
];
}

public function testApplicationUserAgentTrimsOnlySurroundingSpacesAndTabs(): void
{
$request = $this->sendSdkRequest(['User-Agent' => " \tmyapp/1.0 plugin/2.0\t "]);

$userAgents = $request->getHeader('User-Agent');
$this->assertCount(1, $userAgents);
$this->assertStringStartsWith('upcloud-php-api/', $userAgents[0]);
$this->assertStringEndsWith(' myapp/1.0 plugin/2.0', $userAgents[0]);
}

public function testLastApplicationUserAgentWinsWithoutDuplicateHeaderValues(): void
{
$request = $this->sendSdkRequest([
'User-Agent' => 'first/1.0',
'user-agent' => 'last/2.0',
]);

$userAgents = $request->getHeader('User-Agent');
$this->assertCount(1, $userAgents);
$this->assertStringEndsWith(' last/2.0', $userAgents[0]);
$this->assertStringNotContainsString('first/1.0', $userAgents[0]);
}

public function testPerOperationUserAgentCanOverrideConstructorDefault(): void
{
$request = $this->sendSdkRequest(
['User-Agent' => 'myapp/1.0'],
['User-Agent' => 'one-off/2.0'],
);

$this->assertSame(['one-off/2.0'], $request->getHeader('User-Agent'));
}

public function testOtherHeadersArePreserved(): void
{
$request = $this->sendSdkRequest(['User-Agent' => 'myapp/1.0', 'X-Custom' => 'value']);

$this->assertSame('value', $request->getHeaderLine('X-Custom'));
$this->assertSame('Upcloud', $request->getHeaderLine('X-Fern-SDK-Name'));
}

/**
* @dataProvider invalidUserAgents
*/
public function testInvalidApplicationUserAgentIsRejectedBeforeSending(string $value): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('is not valid header value.');

try {
$this->sendSdkRequest(['User-Agent' => $value]);
} finally {
$this->assertNull($this->mockHandler->getLastRequest());
}
}

/**
* @return array<string, array{string}>
*/
public static function invalidUserAgents(): array
{
return [
'embedded CR' => ["myapp/1.0\rX-Other: value"],
'embedded LF' => ["myapp/1.0\nX-Other: value"],
'embedded CRLF' => ["myapp/1.0\r\nX-Other: value"],
'leading CRLF' => ["\r\nmyapp/1.0"],
'trailing CRLF' => ["myapp/1.0\r\n"],
'only CRLF' => ["\r\n"],
];
}

/**
* @param array<string, string> $headers
* @param array<string, string> $requestHeaders
*/
private function sendSdkRequest(array $headers = [], array $requestHeaders = []): RequestInterface
{
$httpClient = new Client(['handler' => HandlerStack::create($this->mockHandler)]);
$sdk = new UpcloudClient('test-token', [
'baseUrl' => 'https://api.example.test',
'client' => $httpClient,
'headers' => $headers,
]);
$sdk->ipAddress->deleteIpAddress('192.0.2.10', ['headers' => $requestHeaders]);

$request = $this->mockHandler->getLastRequest();
$this->assertInstanceOf(RequestInterface::class, $request);
return $request;
}
}
3 changes: 3 additions & 0 deletions generator/scripts/generate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,7 @@ cp README.md fern/sdk/README.md
echo "Patching generated PHP for strict null checks..."
python3 generator/scripts/patch_generated_php.py fern/sdk/src

echo "Adding User-Agent default header to the generated client..."
python3 generator/scripts/patch_generated_user_agent.py fern/sdk/src

echo "Generation complete."
102 changes: 102 additions & 0 deletions generator/scripts/patch_generated_user_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Add the User-Agent default header to the generated root client."""

import sys
from pathlib import Path

CLIENT_FILE_NAME = "UpcloudClient.php"
DEFAULT_HEADERS_ANCHOR = " $defaultHeaders = [\n"
ANCHOR = " 'X-Fern-SDK-Name' => 'Upcloud',\n"
VERSION_LINES = (
" $version = null;\n"
" if (class_exists(\\Composer\\InstalledVersions::class) && \\Composer\\InstalledVersions::isInstalled('upcloudltd/upcloud-php-api')) {\n"
" $version = \\Composer\\InstalledVersions::getPrettyVersion('upcloudltd/upcloud-php-api');\n"
" }\n"
" if (!is_string($version) || preg_match('/^[A-Za-z0-9][A-Za-z0-9.+_-]*$/D', $version) !== 1) {\n"
" $version = 'unknown';\n"
" }\n"
)
USER_AGENT_LINE = " 'User-Agent' => 'upcloud-php-api/' . $version,\n"
USER_AGENT_MARKER = "'User-Agent' =>"
HEADER_MERGE_BLOCK = (
" $this->options['headers'] = array_merge(\n"
" $defaultHeaders,\n"
" $this->options['headers'] ?? [],\n"
" );\n"
)
HEADER_NORMALIZATION = (
" $headers = $this->options['headers'] ?? [];\n"
" $userAgent = null;\n"
" foreach ($headers as $name => $value) {\n"
" if (strcasecmp($name, 'User-Agent') === 0) {\n"
' $userAgent = trim($value, " \\t");\n'
" unset($headers[$name]);\n"
" }\n"
" }\n"
" if ($userAgent !== null && $userAgent !== '') {\n"
" $defaultHeaders['User-Agent'] .= ' ' . $userAgent;\n"
" }\n"
" $this->options['headers'] = array_merge($defaultHeaders, $headers);\n"
)
HEADER_NORMALIZATION_MARKER = "$userAgent = null;"


def patch_user_agent(client_file: Path) -> bool:
"""Insert the User-Agent default and case-insensitive application suffix handling."""
source = client_file.read_text(encoding="utf-8")
original = source
if USER_AGENT_MARKER not in source:
if source.count(ANCHOR) != 1:
raise ValueError(f"{client_file}: expected exactly one X-Fern-SDK-Name default header")
if source.count(DEFAULT_HEADERS_ANCHOR) != 1:
raise ValueError(f"{client_file}: expected exactly one default header array")
source = source.replace(DEFAULT_HEADERS_ANCHOR, VERSION_LINES + "\n" + DEFAULT_HEADERS_ANCHOR, 1)
source = source.replace(ANCHOR, ANCHOR + USER_AGENT_LINE, 1)
if HEADER_NORMALIZATION_MARKER not in source:
if source.count(HEADER_MERGE_BLOCK) != 1:
raise ValueError(f"{client_file}: expected exactly one default header merge")
source = source.replace(HEADER_MERGE_BLOCK, HEADER_NORMALIZATION, 1)
if source != original:
client_file.write_text(source, encoding="utf-8")
return True
return False


def verify_user_agent(client_file: Path) -> list[str]:
"""Confirm the User-Agent default, version lookup, and suffix handling are present."""
source = client_file.read_text(encoding="utf-8")
count = source.count(USER_AGENT_MARKER)
if count != 1:
return [f"{client_file}: expected one User-Agent default header, found {count}"]
if source.count(HEADER_NORMALIZATION) != 1:
return [f"{client_file}: User-Agent application suffix handling is missing or outdated"]
if source.count(VERSION_LINES + "\n" + DEFAULT_HEADERS_ANCHOR) != 1:
return [f"{client_file}: User-Agent version lookup must precede the default header array"]
return []


def main() -> int:
if len(sys.argv) != 2:
print("Usage: patch_generated_user_agent.py <generated-src-directory>", file=sys.stderr)
return 2

source_directory = Path(sys.argv[1])
client_file = source_directory / CLIENT_FILE_NAME
if not client_file.is_file():
print(f"ERROR: generated client not found: {client_file}", file=sys.stderr)
return 2

patched = patch_user_agent(client_file)
errors = verify_user_agent(client_file)
if errors:
print("ERROR: verification failed:", file=sys.stderr)
for error in errors:
print(f" {error}", file=sys.stderr)
return 1

print("Added User-Agent default header" if patched else "User-Agent default header already present")
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading