From a2e4a5e72fabc527676b0f4f9ea8cdb2e93954a1 Mon Sep 17 00:00:00 2001 From: Tom Stark Date: Mon, 17 Aug 2026 15:13:19 +0200 Subject: [PATCH 1/4] feat: mint license-less on the Agreement path Co-Authored-By: Claude Fable 5 --- src/Customer/ContentBlock.php | 2 +- src/Customer/LicenseTokenClient.php | 132 +++++++++---- src/Customer/LicenseXmlParser.php | 9 +- src/Customer/TokenEndpoint.php | 23 +++ src/SupertabConnect.php | 15 +- tests/Customer/LicenseTokenClientTest.php | 225 ++++++++++++++++++++-- tests/Customer/LicenseXmlParserTest.php | 6 +- tests/SupertabConnectTest.php | 62 ++++++ 8 files changed, 414 insertions(+), 60 deletions(-) create mode 100644 src/Customer/TokenEndpoint.php diff --git a/src/Customer/ContentBlock.php b/src/Customer/ContentBlock.php index ae628ab..6cc0fa0 100644 --- a/src/Customer/ContentBlock.php +++ b/src/Customer/ContentBlock.php @@ -8,7 +8,7 @@ final class ContentBlock { public function __construct( public readonly string $urlPattern, - public readonly string $server, + public readonly ?string $server, public readonly string $licenseXml, ) {} } diff --git a/src/Customer/LicenseTokenClient.php b/src/Customer/LicenseTokenClient.php index f330d8d..407cf64 100644 --- a/src/Customer/LicenseTokenClient.php +++ b/src/Customer/LicenseTokenClient.php @@ -9,20 +9,33 @@ final class LicenseTokenClient { + private const DEFAULT_SUPERTAB_BASE_URL = 'https://api-connect.supertab.co'; + private readonly TokenCache $cache; + private readonly string $supertabBaseUrl; + public function __construct( private readonly HttpClientInterface $httpClient, private readonly bool $debug = false, ?TokenCache $cache = null, + string $supertabBaseUrl = self::DEFAULT_SUPERTAB_BASE_URL, ) { $this->cache = $cache ?? new TokenCache; + $this->supertabBaseUrl = rtrim($supertabBaseUrl, '/'); } /** * Obtain a license token for accessing a protected resource. * - * Uses the OAuth2 client_credentials flow via the resource's license.xml. + * Uses the OAuth2 client_credentials flow via the resource's license.xml, + * on one of two lanes: + * - RSL License lane: a block path-matches the resource, so the + * chunk goes to that block's own URN-scoped {server}/token. + * - Agreement lane: nothing matches, so the chunk is omitted and the + * request goes license-less to the generic {supertabBaseUrl}/token, + * where the backend resolves the merchant system from the resource URL + * and the customer's single Active Agreement. * * @throws SupertabConnectException on any failure */ @@ -31,21 +44,15 @@ public function obtainLicenseToken( string $clientSecret, string $resourceUrl, ): string { - // 1. Check cache - $cacheKey = "{$clientId}:{$resourceUrl}"; - $cached = $this->cache->get($cacheKey, $this->debug); - if ($cached !== null) { - return $cached; - } - - // 2. Fetch license.xml - $xml = $this->fetchLicenseXml($resourceUrl); + // 1. Fetch license.xml from the resource's origin + $origin = $this->buildOrigin($resourceUrl); + $xml = $this->fetchLicenseXml($origin); if ($this->debug) { error_log('[SupertabConnect] Fetched license.xml (' . strlen($xml) . ' chars)'); } - // 3. Parse and match + // 2. Parse and resolve the token endpoint $contentBlocks = LicenseXmlParser::parseContentElements($xml, $this->debug); if ($contentBlocks === []) { @@ -58,26 +65,19 @@ public function obtainLicenseToken( ); } - $matchedContent = ContentMatcher::findBestMatch($contentBlocks, $resourceUrl, $this->debug); - - if ($matchedContent === null) { - if ($this->debug) { - $patterns = implode(', ', array_map(fn (ContentBlock $b) => $b->urlPattern, $contentBlocks)); - error_log("[SupertabConnect] No element matches resource URL: {$resourceUrl}. Available patterns: {$patterns}"); - } - - throw new SupertabConnectException( - "No element in license.xml matches resource URL: {$resourceUrl}" - ); - } + $endpoint = $this->selectTokenEndpoint($contentBlocks, $resourceUrl, $origin); - if ($this->debug) { - error_log("[SupertabConnect] Matched content block for resource URL: {$resourceUrl}"); - error_log("[SupertabConnect] Using license XML: {$matchedContent->licenseXml}"); + // 3. Check cache. Keyed by server + scope: on the matched lane scope is + // the block's urlPattern (token reuse across sibling paths); on the + // Agreement lane scope is the origin (one Agreement token per origin). + $cacheKey = "{$clientId}:{$endpoint->server}:{$endpoint->scope}"; + $cached = $this->cache->get($cacheKey, $this->debug); + if ($cached !== null) { + return $cached; } // 4. Request token - $tokenEndpoint = rtrim($matchedContent->server, '/') . '/token'; + $tokenEndpoint = rtrim($endpoint->server, '/') . '/token'; if ($this->debug) { error_log("[SupertabConnect] Requesting license token from {$tokenEndpoint}"); @@ -87,8 +87,8 @@ public function obtainLicenseToken( $tokenEndpoint, $clientId, $clientSecret, - $matchedContent->licenseXml, - $matchedContent->urlPattern, + $endpoint->licenseXml, + $resourceUrl, ); // 5. Cache token @@ -98,11 +98,53 @@ public function obtainLicenseToken( } /** - * Fetch license.xml from the resource URL's origin. + * Resolve where to mint, decoupled from whether the live license.xml still + * grants the resource. * - * @throws SupertabConnectException + * A path-matching server-bearing block gives the RSL License + * lane: mint against that block's URN-scoped server with its + * chunk. Anything else falls through to the Agreement lane, where the + * backend resolves the merchant system from the resource URL and the + * customer's single Active Agreement, so a diverged license.xml cannot + * veto the mint. + * + * @param list $contentBlocks + */ + private function selectTokenEndpoint(array $contentBlocks, string $resourceUrl, string $origin): TokenEndpoint + { + $serverBlocks = array_values(array_filter($contentBlocks, fn (ContentBlock $b) => $b->server !== null)); + $matched = ContentMatcher::findBestMatch($serverBlocks, $resourceUrl, $this->debug); + + if ($matched !== null && $matched->server !== null) { + if ($this->debug) { + error_log("[SupertabConnect] Matched content block for resource URL: {$resourceUrl}"); + } + + return new TokenEndpoint( + server: $matched->server, + scope: $matched->urlPattern, + matched: true, + licenseXml: $matched->licenseXml, + ); + } + + if ($this->debug) { + $patterns = implode(', ', array_map(fn (ContentBlock $b) => $b->urlPattern, $serverBlocks)); + error_log( + "[SupertabConnect] No element matches resource URL: {$resourceUrl} (patterns: {$patterns}). " + . "Minting license-less against {$this->supertabBaseUrl}; the backend resolves the Agreement." + ); + } + + return new TokenEndpoint(server: $this->supertabBaseUrl, scope: $origin, matched: false); + } + + /** + * Derive the origin (scheme://host[:port]) from the resource URL. + * + * @throws SupertabConnectException when the URL has no origin */ - private function fetchLicenseXml(string $resourceUrl): string + private function buildOrigin(string $resourceUrl): string { $parsed = parse_url($resourceUrl); if ($parsed === false || ! isset($parsed['scheme'], $parsed['host'])) { @@ -114,6 +156,16 @@ private function fetchLicenseXml(string $resourceUrl): string $origin .= ':' . $parsed['port']; } + return $origin; + } + + /** + * Fetch license.xml from the given origin. + * + * @throws SupertabConnectException + */ + private function fetchLicenseXml(string $origin): string + { $licenseXmlUrl = $origin . '/license.xml'; try { @@ -152,14 +204,22 @@ private function requestToken( string $tokenEndpoint, string $clientId, string $clientSecret, - string $licenseXml, + ?string $licenseXml, string $resource, ): string { - $body = http_build_query([ + $params = [ 'grant_type' => 'client_credentials', - 'license' => $licenseXml, 'resource' => $resource, - ]); + ]; + + // Only send the live chunk when a public block + // actually matched; on the Agreement lane the backend mints from the + // Agreement's pinned snapshot instead. + if ($licenseXml !== null) { + $params['license'] = $licenseXml; + } + + $body = http_build_query($params); $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded', diff --git a/src/Customer/LicenseXmlParser.php b/src/Customer/LicenseXmlParser.php index 3a31431..2aec544 100644 --- a/src/Customer/LicenseXmlParser.php +++ b/src/Customer/LicenseXmlParser.php @@ -11,9 +11,11 @@ final class LicenseXmlParser * * Each valid element must have: * - A `url` attribute (the URL pattern) - * - A `server` attribute (the token endpoint base) * - A nested `` element (preserved as raw XML) * + * The `server` attribute (the token endpoint base) is optional; blocks + * without one are kept with a null server and never mint directly. + * * @return list */ public static function parseContentElements(string $xml, bool $debug = false): array @@ -70,16 +72,15 @@ public static function parseContentElements(string $xml, bool $debug = false): a ? $licenseNode->asXML() : null; - if ($url !== null && $url !== '' && $server !== null && $server !== '' && $licenseXml !== null && $licenseXml !== false) { + if ($url !== null && $url !== '' && $licenseXml !== null && $licenseXml !== false) { $contentBlocks[] = new ContentBlock( urlPattern: $url, - server: $server, + server: ($server !== null && $server !== '') ? $server : null, licenseXml: $licenseXml, ); } elseif ($debug) { $missing = array_filter([ ($url === null || $url === '') ? 'url' : null, - ($server === null || $server === '') ? 'server' : null, ($licenseXml === null || $licenseXml === false) ? '' : null, ]); error_log("[SupertabConnect] Skipping element #{$elementCount}: missing " . implode(', ', $missing)); diff --git a/src/Customer/TokenEndpoint.php b/src/Customer/TokenEndpoint.php new file mode 100644 index 0000000..f40ca04 --- /dev/null +++ b/src/Customer/TokenEndpoint.php @@ -0,0 +1,23 @@ + block path-matched: mint + * against its URN-scoped server with its chunk) over the Agreement + * lane (nothing matched: mint license-less against the generic Supertab API + * base, where the backend resolves the customer's Active Agreement). + */ +final class TokenEndpoint +{ + public function __construct( + public readonly string $server, + public readonly string $scope, + public readonly bool $matched, + public readonly ?string $licenseXml = null, + ) {} +} diff --git a/src/SupertabConnect.php b/src/SupertabConnect.php index 3fc38b2..47336d6 100644 --- a/src/SupertabConnect.php +++ b/src/SupertabConnect.php @@ -329,8 +329,17 @@ public static function fetchLicenseXml( /** * Obtain a license token for accessing a protected resource. * - * Uses the OAuth2 client_credentials flow via the resource's license.xml. - * Does not require a SupertabConnect instance. + * Uses the OAuth2 client_credentials flow via the resource's license.xml, + * on one of two lanes: + * - RSL License lane: a block path-matches the resource, so the + * chunk goes to that block's own URN-scoped {server}/token. + * - Agreement lane: nothing matches, so the chunk is omitted and the + * request goes license-less to the generic {baseUrl}/token, where the + * backend resolves the merchant system from the resource URL and the + * customer's single Active Agreement. + * + * Does not require a SupertabConnect instance. $baseUrl overrides the + * Supertab API base for this call only; it defaults to getBaseUrl(). * * @throws SupertabConnectException on any failure */ @@ -340,10 +349,12 @@ public static function obtainLicenseToken( string $resourceUrl, bool $debug = false, ?HttpClientInterface $httpClient = null, + ?string $baseUrl = null, ): string { $client = new LicenseTokenClient( httpClient: $httpClient ?? new HttpClient, debug: $debug, + supertabBaseUrl: $baseUrl ?? self::$baseUrl, ); return $client->obtainLicenseToken($clientId, $clientSecret, $resourceUrl); diff --git a/tests/Customer/LicenseTokenClientTest.php b/tests/Customer/LicenseTokenClientTest.php index 1fc04f1..84e3899 100644 --- a/tests/Customer/LicenseTokenClientTest.php +++ b/tests/Customer/LicenseTokenClientTest.php @@ -37,6 +37,24 @@ final class LicenseTokenClientTest extends TestCase +XML; + + private const NON_MATCHING_XML = <<<'XML' + + + + + + +XML; + + private const SERVERLESS_XML = <<<'XML' + + + + + + XML; public function test_obtains_token_successfully(): void @@ -60,8 +78,9 @@ public function test_returns_cached_token_on_second_call(): void $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); $httpClient = $this->createMock(HttpClientInterface::class); - // GET for license.xml should be called exactly once - $httpClient->expects($this->once()) + // license.xml is fetched per call (the cache key needs the resolved + // lane), but the token itself is minted exactly once + $httpClient->expects($this->exactly(2)) ->method('get') ->willReturn(['statusCode' => 200, 'body' => self::LICENSE_XML]); $httpClient->expects($this->once()) @@ -107,27 +126,203 @@ public function test_throws_when_no_content_elements(): void $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); } - public function test_throws_when_no_matching_content(): void + public function test_mints_license_less_when_no_content_matches(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::NON_MATCHING_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $token = $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + + $this->assertSame($fakeToken, $token); + $this->assertCount(1, $posts); + $this->assertSame('https://api-connect.supertab.co/token', $posts[0]['url']); + + parse_str($posts[0]['body'], $params); + $this->assertSame('client_credentials', $params['grant_type']); + $this->assertSame(self::RESOURCE_URL, $params['resource']); + $this->assertArrayNotHasKey('license', $params); + } + + public function test_agreement_lane_uses_configured_base_url(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::NON_MATCHING_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient, supertabBaseUrl: 'http://api-connect.test/'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + + $this->assertCount(1, $posts); + $this->assertSame('http://api-connect.test/token', $posts[0]['url']); + } + + public function test_mints_license_less_when_no_content_block_has_server(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::SERVERLESS_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $token = $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + + $this->assertSame($fakeToken, $token); + $this->assertCount(1, $posts); + $this->assertSame('https://api-connect.supertab.co/token', $posts[0]['url']); + + parse_str($posts[0]['body'], $params); + $this->assertArrayNotHasKey('license', $params); + } + + public function test_shares_agreement_token_across_resources_on_same_origin(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::NON_MATCHING_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/news/bar'); + + // Both fall to the Agreement lane (scope = origin): single mint, second call cached. + $this->assertCount(1, $posts); + } + + public function test_does_not_share_agreement_tokens_across_origins(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::NON_MATCHING_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://site-a.example/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://site-b.example/article/foo'); + + // Agreement-lane tokens are scoped per origin: two origins, two mints. + $this->assertCount(2, $posts); + } + + public function test_reuses_matched_token_across_sibling_paths(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::LICENSE_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/article/bar'); + + // Both resources match the same block (scope = its urlPattern): one mint. + $this->assertCount(1, $posts); + } + + public function test_lanes_use_distinct_cache_keys(): void { $xml = <<<'XML' - - - + + + + + XML; + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; $httpClient = $this->createMock(HttpClientInterface::class); $httpClient->method('get') ->willReturn(['statusCode' => 200, 'body' => $xml]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://127.0.0.1:7676/premium/foo'); + + // Matched lane and Agreement lane on the same origin mint separately. + $this->assertCount(2, $posts); + $this->assertSame('http://127.0.0.1:8787/token', $posts[0]['url']); + $this->assertSame('https://api-connect.supertab.co/token', $posts[1]['url']); + + parse_str($posts[0]['body'], $matchedParams); + parse_str($posts[1]['body'], $agreementParams); + $this->assertArrayHasKey('license', $matchedParams); + $this->assertArrayNotHasKey('license', $agreementParams); + } + + public function test_throws_when_resource_url_has_no_origin(): void + { + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->expects($this->never())->method('get'); + $httpClient->expects($this->never())->method('post'); $client = new LicenseTokenClient($httpClient); $this->expectException(SupertabConnectException::class); - $this->expectExceptionMessage('No element in license.xml matches resource URL'); + $this->expectExceptionMessage('Invalid resource URL'); - $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'not-a-url'); } public function test_throws_on_token_endpoint_failure(): void @@ -227,7 +422,7 @@ public function test_sends_correct_form_body(): void $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); } - public function test_uses_url_pattern_as_resource_param(): void + public function test_matched_lane_sends_raw_resource_url_and_license_chunk(): void { $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); @@ -237,12 +432,13 @@ public function test_uses_url_pattern_as_resource_param(): void $httpClient->expects($this->once()) ->method('post') ->with( - $this->anything(), + $this->equalTo('http://127.0.0.1:8787/token'), $this->callback(function (string $body) { parse_str($body, $params); - // Resource should be the URL pattern from license.xml, not the original resource URL - return ($params['resource'] ?? null) === 'http://127.0.0.1:7676/*'; + // Resource is the raw resource URL, not the matched urlPattern + return ($params['resource'] ?? null) === self::RESOURCE_URL + && str_contains($params['license'] ?? '', 'anything(), ) @@ -252,7 +448,7 @@ public function test_uses_url_pattern_as_resource_param(): void $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); } - public function test_uses_path_only_url_pattern_as_resource_param(): void + public function test_path_only_matched_lane_sends_raw_resource_url(): void { $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); @@ -266,8 +462,7 @@ public function test_uses_path_only_url_pattern_as_resource_param(): void $this->callback(function (string $body) { parse_str($body, $params); - // Path-only pattern should be sent as-is - return ($params['resource'] ?? null) === '/*'; + return ($params['resource'] ?? null) === self::RESOURCE_URL; }), $this->anything(), ) diff --git a/tests/Customer/LicenseXmlParserTest.php b/tests/Customer/LicenseXmlParserTest.php index 969983e..718d36e 100644 --- a/tests/Customer/LicenseXmlParserTest.php +++ b/tests/Customer/LicenseXmlParserTest.php @@ -91,7 +91,7 @@ public function test_skips_content_missing_url_attribute(): void $this->assertCount(0, $blocks); } - public function test_skips_content_missing_server_attribute(): void + public function test_keeps_content_missing_server_attribute_with_null_server(): void { $xml = <<<'XML' @@ -104,7 +104,9 @@ public function test_skips_content_missing_server_attribute(): void $blocks = LicenseXmlParser::parseContentElements($xml); - $this->assertCount(0, $blocks); + $this->assertCount(1, $blocks); + $this->assertSame('http://example.com/*', $blocks[0]->urlPattern); + $this->assertNull($blocks[0]->server); } public function test_returns_empty_array_for_no_content_elements(): void diff --git a/tests/SupertabConnectTest.php b/tests/SupertabConnectTest.php index 754b925..7f359e3 100644 --- a/tests/SupertabConnectTest.php +++ b/tests/SupertabConnectTest.php @@ -62,6 +62,68 @@ public function test_set_and_get_base_url(): void $this->assertSame('https://custom.example.com', SupertabConnect::getBaseUrl()); } + public function test_static_obtain_license_token_defaults_agreement_lane_to_configured_base_url(): void + { + SupertabConnect::setBaseUrl('http://configured.test'); + $posts = []; + + SupertabConnect::obtainLicenseToken( + clientId: 'client', + clientSecret: 'secret', + resourceUrl: 'http://127.0.0.1:7676/article/foo', + httpClient: $this->createLicenseTokenHttpClient($posts), + ); + + $this->assertCount(1, $posts); + $this->assertSame('http://configured.test/token', $posts[0]['url']); + } + + public function test_static_obtain_license_token_accepts_base_url_override(): void + { + $posts = []; + + SupertabConnect::obtainLicenseToken( + clientId: 'client', + clientSecret: 'secret', + resourceUrl: 'http://127.0.0.1:7676/article/foo', + httpClient: $this->createLicenseTokenHttpClient($posts), + baseUrl: 'http://override.test/', + ); + + $this->assertCount(1, $posts); + $this->assertSame('http://override.test/token', $posts[0]['url']); + } + + /** + * HTTP client stub whose license.xml matches nothing, so the mint takes the + * Agreement lane; captures every token POST into $posts. + * + * @param list $posts + */ + private function createLicenseTokenHttpClient(array &$posts): HttpClientInterface + { + $xml = <<<'XML' + + + + + + +XML; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => $xml]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => 'token'])]; + }); + + return $httpClient; + } + public function test_constructor_base_url_sets_base_url(): void { new SupertabConnect( From e9b1fbbd404510044b00e4b2fc051b65377e4838 Mon Sep 17 00:00:00 2001 From: Tom Stark Date: Mon, 17 Aug 2026 15:59:33 +0200 Subject: [PATCH 2/4] fix: prefer Supertab-hosted matches and canonicalize origins Co-Authored-By: Claude Fable 5 --- README.md | 19 +++- src/Customer/LicenseTokenClient.php | 63 ++++++++++-- tests/Customer/LicenseTokenClientTest.php | 112 ++++++++++++++++++++++ 3 files changed, 182 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2cc5a9c..4ea2f09 100644 --- a/README.md +++ b/README.md @@ -285,15 +285,26 @@ Obtains a license token for accessing a protected resource using the OAuth2 `cli | `resourceUrl` | `string` | Yes | — | Full URL of the protected resource | | `debug` | `bool` | No | `false` | Emit debug logs | | `httpClient` | `?HttpClientInterface` | No | `null` | Inject a custom HTTP client | +| `baseUrl` | `?string` | No | `null` | Per-call Supertab API host override (defaults to `getBaseUrl()`) | **Returns:** `string` (the access token). Throws `SupertabConnectException` on failure. -The SDK handles the full RSL flow automatically: +The SDK handles the full flow automatically: 1. Fetches `{origin}/license.xml` from the resource URL -2. Parses content blocks and finds the best matching URL pattern (exact > path pattern > wildcard by specificity) -3. POSTs to the token endpoint using OAuth2 `client_credentials` -4. Caches the token in memory (keyed by `clientId:resourceUrl`, reused until 30s before expiry) +2. Parses content blocks and picks where to mint, on one of two lanes: + - **RSL License lane** — a `` block path-matches the resource + (exact > path pattern > wildcard by specificity; matches hosted on the + Supertab API host are preferred over other providers). The block's + `` chunk is sent to that block's own `{server}/token`. + - **Agreement lane** — nothing matches, so the request goes license-less to + the generic `{baseUrl}/token`, where the backend resolves the merchant + system from the resource URL and the customer's single Active Agreement. +3. POSTs to the token endpoint using OAuth2 `client_credentials`, with + `resource` carrying the raw resource URL +4. Caches the token in memory (keyed by client ID, token server and scope — + the block's URL pattern on the matched lane, the resource origin on the + Agreement lane — reused until 30s before expiry) ### `SupertabConnect::setBaseUrl()` (static) diff --git a/src/Customer/LicenseTokenClient.php b/src/Customer/LicenseTokenClient.php index 407cf64..b3559de 100644 --- a/src/Customer/LicenseTokenClient.php +++ b/src/Customer/LicenseTokenClient.php @@ -103,17 +103,22 @@ public function obtainLicenseToken( * * A path-matching server-bearing block gives the RSL License * lane: mint against that block's URN-scoped server with its - * chunk. Anything else falls through to the Agreement lane, where the - * backend resolves the merchant system from the resource URL and the - * customer's single Active Agreement, so a diverged license.xml cannot - * veto the mint. + * chunk. Matches hosted on the configured Supertab API host are preferred + * over matches from other providers, so a multi-provider license.xml never + * routes credentials to a third party when a Supertab block also matches. + * Anything else falls through to the Agreement lane, where the backend + * resolves the merchant system from the resource URL and the customer's + * single Active Agreement, so a diverged license.xml cannot veto the mint. * * @param list $contentBlocks */ private function selectTokenEndpoint(array $contentBlocks, string $resourceUrl, string $origin): TokenEndpoint { $serverBlocks = array_values(array_filter($contentBlocks, fn (ContentBlock $b) => $b->server !== null)); - $matched = ContentMatcher::findBestMatch($serverBlocks, $resourceUrl, $this->debug); + $supertabBlocks = array_values(array_filter($serverBlocks, fn (ContentBlock $b) => $this->isSupertabServer($b->server))); + + $matched = ContentMatcher::findBestMatch($supertabBlocks, $resourceUrl, $this->debug) + ?? ContentMatcher::findBestMatch($serverBlocks, $resourceUrl, $this->debug); if ($matched !== null && $matched->server !== null) { if ($this->debug) { @@ -140,7 +145,23 @@ private function selectTokenEndpoint(array $contentBlocks, string $resourceUrl, } /** - * Derive the origin (scheme://host[:port]) from the resource URL. + * True when the server's host matches the configured Supertab API base host. + */ + private function isSupertabServer(?string $server): bool + { + if ($server === null) { + return false; + } + + $serverHost = self::canonicalHost($server); + + return $serverHost !== null && $serverHost === self::canonicalHost($this->supertabBaseUrl); + } + + /** + * Derive the canonical origin (scheme://host[:port], lowercased, default + * port stripped) from the resource URL, mirroring the WHATWG URL origin + * the TypeScript SDK uses. * * @throws SupertabConnectException when the URL has no origin */ @@ -151,14 +172,40 @@ private function buildOrigin(string $resourceUrl): string throw new SupertabConnectException("Invalid resource URL: {$resourceUrl}"); } - $origin = $parsed['scheme'] . '://' . $parsed['host']; - if (isset($parsed['port'])) { + $scheme = strtolower($parsed['scheme']); + $origin = $scheme . '://' . strtolower($parsed['host']); + if (isset($parsed['port']) && ! self::isDefaultPort($scheme, $parsed['port'])) { $origin .= ':' . $parsed['port']; } return $origin; } + /** + * The host (host[:port], lowercased, default port stripped) of a URL, or + * null when the URL has none. Mirrors the WHATWG URL host. + */ + private static function canonicalHost(string $url): ?string + { + $parsed = parse_url($url); + if ($parsed === false || ! isset($parsed['host'])) { + return null; + } + + $scheme = isset($parsed['scheme']) ? strtolower($parsed['scheme']) : ''; + $host = strtolower($parsed['host']); + if (isset($parsed['port']) && ! self::isDefaultPort($scheme, $parsed['port'])) { + $host .= ':' . $parsed['port']; + } + + return $host; + } + + private static function isDefaultPort(string $scheme, int $port): bool + { + return ($scheme === 'https' && $port === 443) || ($scheme === 'http' && $port === 80); + } + /** * Fetch license.xml from the given origin. * diff --git a/tests/Customer/LicenseTokenClientTest.php b/tests/Customer/LicenseTokenClientTest.php index 84e3899..1fe284d 100644 --- a/tests/Customer/LicenseTokenClientTest.php +++ b/tests/Customer/LicenseTokenClientTest.php @@ -311,6 +311,118 @@ public function test_lanes_use_distinct_cache_keys(): void $this->assertArrayNotHasKey('license', $agreementParams); } + public function test_prefers_supertab_hosted_block_over_more_specific_third_party_match(): void + { + // The third-party block is more specific, but credentials and the + // license chunk must go to the configured Supertab host when a + // Supertab-hosted block also matches. + $xml = <<<'XML' + + + + + + + + + +XML; + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => $xml]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient, supertabBaseUrl: 'http://api-connect.test'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + + $this->assertCount(1, $posts); + $this->assertSame('http://api-connect.test/urn:sys:123/token', $posts[0]['url']); + } + + public function test_falls_back_to_third_party_match_when_no_supertab_block_matches(): void + { + // LICENSE_XML's server (127.0.0.1:8787) is not the configured Supertab + // host, so the best match among all providers wins. + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::LICENSE_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient, supertabBaseUrl: 'http://api-connect.test'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, self::RESOURCE_URL); + + $this->assertCount(1, $posts); + $this->assertSame('http://127.0.0.1:8787/token', $posts[0]['url']); + } + + public function test_canonicalizes_default_port_in_agreement_scope_and_license_fetch(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $gets = []; + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturnCallback(function (string $url) use (&$gets) { + $gets[] = $url; + + return ['statusCode' => 200, 'body' => self::NON_MATCHING_XML]; + }); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'https://example.com/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'https://example.com:443/article/bar'); + + // Same origin either way: one Agreement mint, canonical license.xml URL. + $this->assertCount(1, $posts); + $this->assertSame(['https://example.com/license.xml', 'https://example.com/license.xml'], $gets); + } + + public function test_keeps_non_default_port_in_agreement_scope(): void + { + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => self::NON_MATCHING_XML]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'https://example.com/article/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'https://example.com:8443/article/foo'); + + // Distinct origins: two mints. + $this->assertCount(2, $posts); + } + public function test_throws_when_resource_url_has_no_origin(): void { $httpClient = $this->createMock(HttpClientInterface::class); From 54bf64d31cc96097c7f45ea811388d2cdb103192 Mon Sep 17 00:00:00 2001 From: Tom Stark Date: Tue, 18 Aug 2026 09:48:59 +0200 Subject: [PATCH 3/4] fix: canonicalize URLs for matching and share the facade token cache Co-Authored-By: Claude Fable 5 --- src/Customer/ContentMatcher.php | 30 ++---- src/Customer/LicenseTokenClient.php | 43 +------- src/Customer/UrlCanonicalizer.php | 120 ++++++++++++++++++++++ src/SupertabConnect.php | 10 ++ tests/Customer/ContentMatcherTest.php | 64 ++++++++++++ tests/Customer/LicenseTokenClientTest.php | 35 +++++++ tests/SupertabConnectTest.php | 42 ++++++++ 7 files changed, 285 insertions(+), 59 deletions(-) create mode 100644 src/Customer/UrlCanonicalizer.php diff --git a/src/Customer/ContentMatcher.php b/src/Customer/ContentMatcher.php index 980be10..224c509 100644 --- a/src/Customer/ContentMatcher.php +++ b/src/Customer/ContentMatcher.php @@ -10,7 +10,10 @@ final class ContentMatcher * Find the best matching content block for the given resource URL. * * Matching rules: - * 1. Host (including port) must match exactly + * 1. Canonical host (including non-default port) must match exactly; + * hosts are compared via UrlCanonicalizer (lowercased, punycoded, + * default ports stripped) and dot segments in paths are resolved, + * mirroring the WHATWG URL parsing the TypeScript SDK gets for free * 2. Exact path match returns immediately (highest priority) * 3. Robots.txt-style pattern matching via scorePathPattern(): * - `*` matches zero or more characters (including `/`) @@ -32,8 +35,8 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl, return null; } - $host = self::extractHost($parsed); - $path = $parsed['path'] ?? '/'; + $host = UrlCanonicalizer::canonicalHostFromParts($parsed); + $path = UrlCanonicalizer::resolveDotSegments($parsed['path'] ?? '/'); if ($debug) { error_log("[SupertabConnect] Matching resource URL: {$resourceUrl} (host={$host}, path={$path})"); @@ -53,8 +56,8 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl, } if (isset($patternParsed['host'])) { - // Absolute URL pattern: host must match - $patternHost = self::extractHost($patternParsed); + // Absolute URL pattern: canonical host must match + $patternHost = UrlCanonicalizer::canonicalHostFromParts($patternParsed); if ($patternHost !== $host) { if ($debug) { @@ -64,7 +67,7 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl, continue; } - $patternPath = $patternParsed['path'] ?? '/'; + $patternPath = UrlCanonicalizer::resolveDotSegments($patternParsed['path'] ?? '/'); } else { // Path-only pattern: must start with `/` and have no scheme. // Rejects malformed absolute URLs like "https:/content/*". @@ -153,19 +156,4 @@ public static function scorePathPattern(string $pattern, string $path): int return -1; } - - /** - * Extract the host string including port. - * - * @param array $parsed - */ - private static function extractHost(array $parsed): string - { - $host = (string) $parsed['host']; - if (isset($parsed['port'])) { - $host .= ':' . $parsed['port']; - } - - return $host; - } } diff --git a/src/Customer/LicenseTokenClient.php b/src/Customer/LicenseTokenClient.php index b3559de..f2d31fd 100644 --- a/src/Customer/LicenseTokenClient.php +++ b/src/Customer/LicenseTokenClient.php @@ -153,59 +153,26 @@ private function isSupertabServer(?string $server): bool return false; } - $serverHost = self::canonicalHost($server); + $serverHost = UrlCanonicalizer::canonicalHost($server); - return $serverHost !== null && $serverHost === self::canonicalHost($this->supertabBaseUrl); + return $serverHost !== null && $serverHost === UrlCanonicalizer::canonicalHost($this->supertabBaseUrl); } /** - * Derive the canonical origin (scheme://host[:port], lowercased, default - * port stripped) from the resource URL, mirroring the WHATWG URL origin - * the TypeScript SDK uses. + * Derive the canonical origin from the resource URL. * * @throws SupertabConnectException when the URL has no origin */ private function buildOrigin(string $resourceUrl): string { - $parsed = parse_url($resourceUrl); - if ($parsed === false || ! isset($parsed['scheme'], $parsed['host'])) { + $origin = UrlCanonicalizer::canonicalOrigin($resourceUrl); + if ($origin === null) { throw new SupertabConnectException("Invalid resource URL: {$resourceUrl}"); } - $scheme = strtolower($parsed['scheme']); - $origin = $scheme . '://' . strtolower($parsed['host']); - if (isset($parsed['port']) && ! self::isDefaultPort($scheme, $parsed['port'])) { - $origin .= ':' . $parsed['port']; - } - return $origin; } - /** - * The host (host[:port], lowercased, default port stripped) of a URL, or - * null when the URL has none. Mirrors the WHATWG URL host. - */ - private static function canonicalHost(string $url): ?string - { - $parsed = parse_url($url); - if ($parsed === false || ! isset($parsed['host'])) { - return null; - } - - $scheme = isset($parsed['scheme']) ? strtolower($parsed['scheme']) : ''; - $host = strtolower($parsed['host']); - if (isset($parsed['port']) && ! self::isDefaultPort($scheme, $parsed['port'])) { - $host .= ':' . $parsed['port']; - } - - return $host; - } - - private static function isDefaultPort(string $scheme, int $port): bool - { - return ($scheme === 'https' && $port === 443) || ($scheme === 'http' && $port === 80); - } - /** * Fetch license.xml from the given origin. * diff --git a/src/Customer/UrlCanonicalizer.php b/src/Customer/UrlCanonicalizer.php new file mode 100644 index 0000000..42cff12 --- /dev/null +++ b/src/Customer/UrlCanonicalizer.php @@ -0,0 +1,120 @@ + $segment) { + $normalized = strtolower(str_ireplace('%2e', '.', $segment)); + + if ($normalized === '..') { + if (count($output) > 1) { + array_pop($output); + } + if ($i === $lastIndex) { + $output[] = ''; + } + } elseif ($normalized === '.') { + if ($i === $lastIndex) { + $output[] = ''; + } + } else { + $output[] = $segment; + } + } + + return implode('/', $output); + } + + /** + * Lowercase the host and punycode non-ASCII (IDN) hosts when ext-intl is + * available; without intl the lowercased host is used as-is. + */ + private static function asciiHost(string $host): string + { + $host = strtolower($host); + + if (function_exists('idn_to_ascii') && preg_match('/[^\x00-\x7F]/', $host) === 1) { + $ascii = idn_to_ascii($host); + if ($ascii !== false) { + return $ascii; + } + } + + return $host; + } + + private static function isDefaultPort(string $scheme, int $port): bool + { + return ($scheme === 'https' && $port === 443) || ($scheme === 'http' && $port === 80); + } +} diff --git a/src/SupertabConnect.php b/src/SupertabConnect.php index 47336d6..164edd5 100644 --- a/src/SupertabConnect.php +++ b/src/SupertabConnect.php @@ -16,6 +16,7 @@ use Supertab\Connect\Bot\BotDetectorInterface; use Supertab\Connect\Cache\CacheInterface; use Supertab\Connect\Customer\LicenseTokenClient; +use Supertab\Connect\Customer\TokenCache; use Supertab\Connect\Enum\EnforcementMode; use Supertab\Connect\Enum\LicenseTokenInvalidReason; use Supertab\Connect\Event\EventRecorder; @@ -50,6 +51,13 @@ final class SupertabConnect private static ?self $instance = null; + /** + * Token cache shared across static obtainLicenseToken() calls, which each + * construct a fresh LicenseTokenClient. Mirrors the TS SDK's module-level + * cache; reset via resetInstance(). + */ + private static ?TokenCache $licenseTokenCache = null; + private readonly LicenseTokenVerifier $verifier; private readonly StatusChallengeVerifier $statusVerifier; @@ -199,6 +207,7 @@ private function shouldForceSyncAnalytics(): bool public static function resetInstance(): void { self::$instance = null; + self::$licenseTokenCache = null; } /** @@ -354,6 +363,7 @@ public static function obtainLicenseToken( $client = new LicenseTokenClient( httpClient: $httpClient ?? new HttpClient, debug: $debug, + cache: self::$licenseTokenCache ??= new TokenCache, supertabBaseUrl: $baseUrl ?? self::$baseUrl, ); diff --git a/tests/Customer/ContentMatcherTest.php b/tests/Customer/ContentMatcherTest.php index 1620f3f..7d3704d 100644 --- a/tests/Customer/ContentMatcherTest.php +++ b/tests/Customer/ContentMatcherTest.php @@ -34,6 +34,70 @@ protected function setUp(): void ]; } + public function test_matches_uppercase_host_and_default_port_in_resource(): void + { + $blocks = [$this->block('https://example.com/premium')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://EXAMPLE.COM:443/premium'); + + $this->assertNotNull($result); + } + + public function test_matches_uppercase_host_and_default_port_in_pattern(): void + { + $blocks = [$this->block('https://EXAMPLE.com:443/premium')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://example.com/premium'); + + $this->assertNotNull($result); + } + + public function test_resolves_dot_segments_in_resource_path(): void + { + $blocks = [$this->block('https://example.com/premium')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://example.com/a/../premium'); + + $this->assertNotNull($result); + } + + public function test_resolves_percent_encoded_dot_segments_in_resource_path(): void + { + $blocks = [$this->block('https://example.com/premium')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://example.com/%2e%2e/premium'); + + $this->assertNotNull($result); + } + + public function test_resolves_dot_segments_in_pattern_path(): void + { + $blocks = [$this->block('https://example.com/a/../premium')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://example.com/premium'); + + $this->assertNotNull($result); + } + + #[\PHPUnit\Framework\Attributes\RequiresPhpExtension('intl')] + public function test_matches_idn_host_against_punycode_pattern(): void + { + $blocks = [$this->block('https://xn--bcher-kva.example/*')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://bücher.example/book'); + + $this->assertNotNull($result); + } + + private function block(string $urlPattern): ContentBlock + { + return new ContentBlock( + urlPattern: $urlPattern, + server: 'http://127.0.0.1:8787', + licenseXml: '', + ); + } + public function test_exact_path_match_wins(): void { $result = ContentMatcher::findBestMatch($this->blocks, 'http://127.0.0.1:7676/article/'); diff --git a/tests/Customer/LicenseTokenClientTest.php b/tests/Customer/LicenseTokenClientTest.php index 1fe284d..f583fcf 100644 --- a/tests/Customer/LicenseTokenClientTest.php +++ b/tests/Customer/LicenseTokenClientTest.php @@ -400,6 +400,41 @@ public function test_canonicalizes_default_port_in_agreement_scope_and_license_f $this->assertSame(['https://example.com/license.xml', 'https://example.com/license.xml'], $gets); } + public function test_canonicalized_resource_url_still_takes_matched_lane(): void + { + // Uppercase host and explicit default port must not push a licensed + // resource onto the Agreement lane. + $xml = <<<'XML' + + + + + + +XML; + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => $xml]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'HTTP://EXAMPLE.COM:80/article/foo'); + + $this->assertCount(1, $posts); + $this->assertSame('http://127.0.0.1:8787/token', $posts[0]['url']); + + parse_str($posts[0]['body'], $params); + $this->assertArrayHasKey('license', $params); + } + public function test_keeps_non_default_port_in_agreement_scope(): void { $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); diff --git a/tests/SupertabConnectTest.php b/tests/SupertabConnectTest.php index 7f359e3..00e8636 100644 --- a/tests/SupertabConnectTest.php +++ b/tests/SupertabConnectTest.php @@ -94,6 +94,48 @@ public function test_static_obtain_license_token_accepts_base_url_override(): vo $this->assertSame('http://override.test/token', $posts[0]['url']); } + public function test_static_obtain_license_token_shares_token_cache_across_calls(): void + { + // The facade constructs a fresh LicenseTokenClient per call; the token + // cache must survive that, mirroring the TS SDK's module-level cache. + $xml = <<<'XML' + + + + + + +XML; + $b64 = fn (array $data) => rtrim(strtr(base64_encode((string) json_encode($data)), '+/', '-_'), '='); + $jwt = $b64(['alg' => 'ES256', 'typ' => 'JWT']) . '.' . $b64(['exp' => time() + 3600]) . '.sig'; + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturn(['statusCode' => 200, 'body' => $xml]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $jwt) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $jwt])]; + }); + + SupertabConnect::obtainLicenseToken( + clientId: 'client', + clientSecret: 'secret', + resourceUrl: 'http://127.0.0.1:7676/article/foo', + httpClient: $httpClient, + ); + SupertabConnect::obtainLicenseToken( + clientId: 'client', + clientSecret: 'secret', + resourceUrl: 'http://127.0.0.1:7676/article/bar', + httpClient: $httpClient, + ); + + $this->assertCount(1, $posts); + } + /** * HTTP client stub whose license.xml matches nothing, so the mint takes the * Agreement lane; captures every token POST into $posts. From 33ce0d3473af0f1eb4f4979fe28383bdd0c7e8e3 Mon Sep 17 00:00:00 2001 From: Tom Stark Date: Tue, 18 Aug 2026 10:27:01 +0200 Subject: [PATCH 4/4] fix: punycode IDN hosts before parsing and normalize server slashes Co-Authored-By: Claude Fable 5 --- src/Customer/ContentMatcher.php | 13 +++- src/Customer/LicenseTokenClient.php | 9 ++- src/Customer/UrlCanonicalizer.php | 75 ++++++++++++++--------- tests/Customer/ContentMatcherTest.php | 13 ++++ tests/Customer/LicenseTokenClientTest.php | 44 +++++++++++++ 5 files changed, 121 insertions(+), 33 deletions(-) diff --git a/src/Customer/ContentMatcher.php b/src/Customer/ContentMatcher.php index 224c509..8ca6dee 100644 --- a/src/Customer/ContentMatcher.php +++ b/src/Customer/ContentMatcher.php @@ -35,7 +35,16 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl, return null; } - $host = UrlCanonicalizer::canonicalHostFromParts($parsed); + // Canonicalize from the raw string: parse_url() corrupts some IDN hosts. + $host = UrlCanonicalizer::canonicalHost($resourceUrl); + if ($host === null) { + if ($debug) { + error_log("[SupertabConnect] Cannot canonicalize resource URL host: {$resourceUrl}"); + } + + return null; + } + $path = UrlCanonicalizer::resolveDotSegments($parsed['path'] ?? '/'); if ($debug) { @@ -57,7 +66,7 @@ public static function findBestMatch(array $contentBlocks, string $resourceUrl, if (isset($patternParsed['host'])) { // Absolute URL pattern: canonical host must match - $patternHost = UrlCanonicalizer::canonicalHostFromParts($patternParsed); + $patternHost = UrlCanonicalizer::canonicalHost($block->urlPattern); if ($patternHost !== $host) { if ($debug) { diff --git a/src/Customer/LicenseTokenClient.php b/src/Customer/LicenseTokenClient.php index f2d31fd..2692dc0 100644 --- a/src/Customer/LicenseTokenClient.php +++ b/src/Customer/LicenseTokenClient.php @@ -76,8 +76,9 @@ public function obtainLicenseToken( return $cached; } - // 4. Request token - $tokenEndpoint = rtrim($endpoint->server, '/') . '/token'; + // 4. Request token (both lanes construct TokenEndpoint with a + // normalized, trailing-slash-free server) + $tokenEndpoint = $endpoint->server . '/token'; if ($this->debug) { error_log("[SupertabConnect] Requesting license token from {$tokenEndpoint}"); @@ -125,8 +126,10 @@ private function selectTokenEndpoint(array $contentBlocks, string $resourceUrl, error_log("[SupertabConnect] Matched content block for resource URL: {$resourceUrl}"); } + // Normalized once here so the cache key and the token URL agree + // even when license.xml writes the server with a trailing slash. return new TokenEndpoint( - server: $matched->server, + server: rtrim($matched->server, '/'), scope: $matched->urlPattern, matched: true, licenseXml: $matched->licenseXml, diff --git a/src/Customer/UrlCanonicalizer.php b/src/Customer/UrlCanonicalizer.php index 42cff12..fe2e386 100644 --- a/src/Customer/UrlCanonicalizer.php +++ b/src/Customer/UrlCanonicalizer.php @@ -10,6 +10,11 @@ * hosts are lowercased and punycoded (when ext-intl is available), default * ports are stripped, and dot segments (including their percent-encoded * forms) are resolved. + * + * IDN hosts are punycoded on the raw URL string BEFORE parse_url() runs: + * parse_url() corrupts UTF-8 hosts whose continuation bytes fall in the + * 0x80-0x9F range (e.g. the 0x9F in "ß" comes back as "_"), so punycoding + * a parsed host is too late. */ final class UrlCanonicalizer { @@ -19,7 +24,7 @@ final class UrlCanonicalizer */ public static function canonicalOrigin(string $url): ?string { - $parsed = parse_url($url); + $parsed = parse_url(self::punycodeUrlHost($url)); if ($parsed === false || ! isset($parsed['scheme'], $parsed['host'])) { return null; } @@ -33,7 +38,7 @@ public static function canonicalOrigin(string $url): ?string */ public static function canonicalHost(string $url): ?string { - $parsed = parse_url($url); + $parsed = parse_url(self::punycodeUrlHost($url)); if ($parsed === false || ! isset($parsed['host'])) { return null; } @@ -41,23 +46,6 @@ public static function canonicalHost(string $url): ?string return self::canonicalHostFromParts($parsed); } - /** - * The canonical host from an already-parsed URL. - * - * @param array{scheme?: string, host: string, port?: int} $parsed - */ - public static function canonicalHostFromParts(array $parsed): string - { - $host = self::asciiHost((string) $parsed['host']); - $scheme = isset($parsed['scheme']) ? strtolower((string) $parsed['scheme']) : ''; - - if (isset($parsed['port']) && ! self::isDefaultPort($scheme, (int) $parsed['port'])) { - $host .= ':' . $parsed['port']; - } - - return $host; - } - /** * Resolve "." and ".." segments (and their percent-encoded forms) in an * absolute path, per the WHATWG URL path parser. ".." never pops above @@ -96,18 +84,49 @@ public static function resolveDotSegments(string $path): string } /** - * Lowercase the host and punycode non-ASCII (IDN) hosts when ext-intl is - * available; without intl the lowercased host is used as-is. + * Punycode a non-ASCII host inside the raw URL string, before any + * parse_url() call. Uses nontransitional UTS46 processing, matching the + * WHATWG domain-to-ASCII operation (so "faß.de" becomes "xn--fa-hia.de", + * never "fass.de", regardless of the environment's ICU defaults). + * Without ext-intl, or when conversion fails, the URL is returned as-is. */ - private static function asciiHost(string $host): string + private static function punycodeUrlHost(string $url): string { - $host = strtolower($host); + if (preg_match('/[^\x00-\x7F]/', $url) !== 1 || ! function_exists('idn_to_ascii')) { + return $url; + } - if (function_exists('idn_to_ascii') && preg_match('/[^\x00-\x7F]/', $host) === 1) { - $ascii = idn_to_ascii($host); - if ($ascii !== false) { - return $ascii; - } + $replaced = preg_replace_callback( + '~^([a-z][a-z0-9+.\-]*://(?:[^/?#]*@)?)([^/?#:]+)~i', + function (array $matches): string { + if (preg_match('/[^\x00-\x7F]/', $matches[2]) !== 1) { + return $matches[0]; + } + + $ascii = idn_to_ascii($matches[2], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); + + return $ascii === false ? $matches[0] : $matches[1] . $ascii; + }, + $url, + ); + + return $replaced ?? $url; + } + + /** + * The canonical host from an already-parsed URL. The host must already be + * ASCII (see punycodeUrlHost); it is lowercased and the default port for + * the scheme is stripped. + * + * @param array{scheme?: string, host: string, port?: int} $parsed + */ + private static function canonicalHostFromParts(array $parsed): string + { + $host = strtolower((string) $parsed['host']); + $scheme = isset($parsed['scheme']) ? strtolower((string) $parsed['scheme']) : ''; + + if (isset($parsed['port']) && ! self::isDefaultPort($scheme, (int) $parsed['port'])) { + $host .= ':' . $parsed['port']; } return $host; diff --git a/tests/Customer/ContentMatcherTest.php b/tests/Customer/ContentMatcherTest.php index 7d3704d..07b0643 100644 --- a/tests/Customer/ContentMatcherTest.php +++ b/tests/Customer/ContentMatcherTest.php @@ -89,6 +89,19 @@ public function test_matches_idn_host_against_punycode_pattern(): void $this->assertNotNull($result); } + #[\PHPUnit\Framework\Attributes\RequiresPhpExtension('intl')] + public function test_punycodes_idn_deviation_characters_nontransitionally(): void + { + // WHATWG domain-to-ASCII is nontransitional: faß.de → xn--fa-hia.de, + // never fass.de. Pins the explicit IDNA flags against ICU defaults + // that vary across environments. + $blocks = [$this->block('https://xn--fa-hia.de/*')]; + + $result = ContentMatcher::findBestMatch($blocks, 'https://faß.de/book'); + + $this->assertNotNull($result); + } + private function block(string $urlPattern): ContentBlock { return new ContentBlock( diff --git a/tests/Customer/LicenseTokenClientTest.php b/tests/Customer/LicenseTokenClientTest.php index f583fcf..6812755 100644 --- a/tests/Customer/LicenseTokenClientTest.php +++ b/tests/Customer/LicenseTokenClientTest.php @@ -458,6 +458,50 @@ public function test_keeps_non_default_port_in_agreement_scope(): void $this->assertCount(2, $posts); } + public function test_normalizes_trailing_slash_server_for_endpoint_and_cache_key(): void + { + // Same effective server written with and without a trailing slash on + // two origins, same path-only pattern: one cache entry, one mint. + $xmlWithSlash = <<<'XML' + + + + + + +XML; + $xmlWithoutSlash = <<<'XML' + + + + + + +XML; + $fakeToken = $this->createFakeJwt(['exp' => time() + 3600]); + $posts = []; + + $httpClient = $this->createMock(HttpClientInterface::class); + $httpClient->method('get') + ->willReturnCallback(fn (string $url) => [ + 'statusCode' => 200, + 'body' => str_contains($url, 'site-a') ? $xmlWithSlash : $xmlWithoutSlash, + ]); + $httpClient->method('post') + ->willReturnCallback(function (string $url, string $body) use (&$posts, $fakeToken) { + $posts[] = ['url' => $url, 'body' => $body]; + + return ['statusCode' => 200, 'body' => json_encode(['access_token' => $fakeToken])]; + }); + + $client = new LicenseTokenClient($httpClient); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://site-a.example/articles/foo'); + $client->obtainLicenseToken(self::CLIENT_ID, self::CLIENT_SECRET, 'http://site-b.example/articles/bar'); + + $this->assertCount(1, $posts); + $this->assertSame('http://127.0.0.1:8787/token', $posts[0]['url']); + } + public function test_throws_when_resource_url_has_no_origin(): void { $httpClient = $this->createMock(HttpClientInterface::class);