diff --git a/README.md b/README.md index 39c9ecc6..66b950eb 100644 --- a/README.md +++ b/README.md @@ -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/`. A +`User-Agent` value supplied in the constructor's `headers` is appended, regardless +of header-name casing: `upcloud-php-api/ 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, diff --git a/fern/sdk/README.md b/fern/sdk/README.md index 39c9ecc6..66b950eb 100644 --- a/fern/sdk/README.md +++ b/fern/sdk/README.md @@ -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/`. A +`User-Agent` value supplied in the constructor's `headers` is appended, regardless +of header-name casing: `upcloud-php-api/ 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, diff --git a/fern/sdk/src/UpcloudClient.php b/fern/sdk/src/UpcloudClient.php index c2433cbc..49f61465 100644 --- a/fern/sdk/src/UpcloudClient.php +++ b/fern/sdk/src/UpcloudClient.php @@ -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, diff --git a/fern/sdk/tests/Core/Client/UserAgentTest.php b/fern/sdk/tests/Core/Client/UserAgentTest.php new file mode 100644 index 00000000..0306e05b --- /dev/null +++ b/fern/sdk/tests/Core/Client/UserAgentTest.php @@ -0,0 +1,180 @@ +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 + */ + 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 + */ + 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 + */ + 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 $headers + * @param array $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; + } +} diff --git a/generator/scripts/generate.sh b/generator/scripts/generate.sh index b2ee0616..fd3a463e 100755 --- a/generator/scripts/generate.sh +++ b/generator/scripts/generate.sh @@ -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." \ No newline at end of file diff --git a/generator/scripts/patch_generated_user_agent.py b/generator/scripts/patch_generated_user_agent.py new file mode 100644 index 00000000..e79b25f9 --- /dev/null +++ b/generator/scripts/patch_generated_user_agent.py @@ -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 ", 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()) diff --git a/generator/tests/test_patch_generated_user_agent.py b/generator/tests/test_patch_generated_user_agent.py new file mode 100644 index 00000000..10185120 --- /dev/null +++ b/generator/tests/test_patch_generated_user_agent.py @@ -0,0 +1,185 @@ +import importlib.util +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + + +REPOSITORY_ROOT = Path(__file__).parents[2] +PATCH_SCRIPT = REPOSITORY_ROOT / "generator" / "scripts" / "patch_generated_user_agent.py" + +CLIENT_SOURCE = """ "******", + 'X-Fern-Language' => 'PHP', + 'X-Fern-SDK-Name' => 'Upcloud', + ]; + + $this->options = $options ?? []; + + $this->options['headers'] = array_merge( + $defaultHeaders, + $this->options['headers'] ?? [], + ); + } +} +""" + + +def load_patch_module(): + module_spec = importlib.util.spec_from_file_location("patch_generated_user_agent", PATCH_SCRIPT) + if module_spec is None or module_spec.loader is None: + raise RuntimeError(f"Unable to load {PATCH_SCRIPT}") + module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(module) + return module + + +class PatchGeneratedUserAgentTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.patch = load_patch_module() + + def test_adds_user_agent_header_after_sdk_name_header(self): + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text(CLIENT_SOURCE, encoding="utf-8") + + self.assertTrue(self.patch.patch_user_agent(client)) + + source = client.read_text(encoding="utf-8") + self.assertIn("'User-Agent' => 'upcloud-php-api/' . $version", source) + self.assertIn("InstalledVersions::getPrettyVersion('upcloudltd/upcloud-php-api')", source) + self.assertIn("class_exists(\\Composer\\InstalledVersions::class)", source) + self.assertIn("InstalledVersions::isInstalled('upcloudltd/upcloud-php-api')", source) + self.assertIn("preg_match('/^[A-Za-z0-9][A-Za-z0-9.+_-]*$/D', $version)", source) + self.assertIn("strcasecmp($name, 'User-Agent') === 0", source) + self.assertEqual(self.patch.verify_user_agent(client), []) + + def test_freshly_patched_client_is_valid_php(self): + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text(CLIENT_SOURCE, encoding="utf-8") + + self.patch.patch_user_agent(client) + + result = subprocess.run(["php", "-l", str(client)], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_freshly_patched_client_runs_with_appended_application_agent(self): + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text(CLIENT_SOURCE, encoding="utf-8") + self.patch.patch_user_agent(client) + + for value, expected in [ + ("myapp/1.0", "upcloud-php-api/unknown myapp/1.0"), + (" \tmyapp/1.0\t ", "upcloud-php-api/unknown myapp/1.0"), + ("", "upcloud-php-api/unknown"), + (" \t ", "upcloud-php-api/unknown"), + ]: + with self.subTest(value=value): + result = subprocess.run( + [ + "php", "-r", + "require $argv[1];" + "$client = new UpcloudClient('token', " + "['headers' => ['user-agent' => $argv[2]]]);" + "echo json_encode($client->options['headers']);", + str(client), value, + ], + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(json.loads(result.stdout)["User-Agent"], expected) + + def test_patch_reproduces_checked_in_client(self): + checked_in = (REPOSITORY_ROOT / "fern/sdk/src/UpcloudClient.php").read_text(encoding="utf-8") + for block in [ + self.patch.VERSION_LINES + "\n", + self.patch.USER_AGENT_LINE, + self.patch.HEADER_NORMALIZATION, + ]: + self.assertEqual(checked_in.count(block), 1) + unpatched = ( + checked_in.replace(self.patch.VERSION_LINES + "\n", "", 1) + .replace(self.patch.USER_AGENT_LINE, "", 1) + .replace(self.patch.HEADER_NORMALIZATION, self.patch.HEADER_MERGE_BLOCK, 1) + ) + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text(unpatched, encoding="utf-8") + + self.patch.patch_user_agent(client) + + self.assertEqual(client.read_text(encoding="utf-8"), checked_in) + self.assertEqual(self.patch.verify_user_agent(client), []) + + def test_is_idempotent(self): + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text(CLIENT_SOURCE, encoding="utf-8") + + self.patch.patch_user_agent(client) + once = client.read_text(encoding="utf-8") + + self.assertFalse(self.patch.patch_user_agent(client)) + self.assertEqual(client.read_text(encoding="utf-8"), once) + + def test_fails_when_anchor_is_missing(self): + with tempfile.TemporaryDirectory() as directory: + client = Path(directory) / "UpcloudClient.php" + client.write_text("