From 75e21a53fe8804ad235790a85ede116594224f64 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:15:14 +0300 Subject: [PATCH 1/9] test(http-signature): add validation tests --- .../Http/Signature/ValidateSignatureTest.php | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 tests/Http/Signature/ValidateSignatureTest.php diff --git a/tests/Http/Signature/ValidateSignatureTest.php b/tests/Http/Signature/ValidateSignatureTest.php new file mode 100644 index 0000000..77f1b2a --- /dev/null +++ b/tests/Http/Signature/ValidateSignatureTest.php @@ -0,0 +1,176 @@ +keyPair = sodium_crypto_sign_keypair(); + $this->privateKey = sodium_crypto_sign_secretkey($this->keyPair); + $this->keyId = 'gnap-key'; + } + + /** + * Builds a request signed with createHeaders, the way a client of this library would. + */ + private function signedRequest(string $method, ?string $body, array $headers = ['Authorization' => 'GNAP token'], bool $lowercase = true): array + { + $request = [ + 'method' => $method, + 'url' => 'https://example.com/incoming-payments', + 'headers' => $headers, + ]; + if ($body !== null) { + $request['body'] = $body; + } + + $signed = \OpenPayments\Utils\createHeaders([ + 'request' => $request, + 'privateKey' => $this->privateKey, + 'keyId' => $this->keyId, + ]); + + $request['headers'] = array_map('strval', array_merge($headers, $signed)); + if ($lowercase) { + $request['headers'] = array_change_key_case($request['headers'], CASE_LOWER); + } + + return $request; + } + + public function test_round_trip_request_with_body_validates() + { + $request = $this->signedRequest('POST', '{"amount":"1"}'); + + $this->assertTrue(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_round_trip_request_without_body_validates() + { + $request = $this->signedRequest('GET', null); + + $this->assertTrue(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_round_trip_with_original_header_case_validates() + { + $request = $this->signedRequest('POST', '{"amount":"1"}', lowercase: false); + + $this->assertTrue(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_body_zero_string_round_trip() + { + $request = $this->signedRequest('POST', '0'); + + $this->assertStringContainsString('content-digest', $request['headers']['signature-input']); + $this->assertTrue(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_rejects_body_when_content_digest_is_not_covered() + { + $request = $this->signedRequest('POST', '{"amount":"1"}', []); + $request['headers']['signature-input'] = 'sig1=("@method" "@target-uri");keyid="gnap-key";created=1'; + $request['body'] = '{"amount":"999"}'; + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_rejects_body_swap_under_stale_digest() + { + $request = $this->signedRequest('POST', '{"amount":"1"}'); + $request['body'] = '{"amount":"999"}'; + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_non_string_body_returns_false() + { + $request = $this->signedRequest('POST', '{"a":1}'); + $request['body'] = ['a' => 1]; + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_rejects_uncovered_authorization_with_mixed_case_key() + { + $request = $this->signedRequest('GET', null, []); + $request['headers']['Authorization'] = 'GNAP other-token'; + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_verify_content_digest_accepts_matching_digest() + { + $header = \OpenPayments\Utils\createContentDigestHeader('x', ['sha-256', 'sha-512']); + + $this->assertTrue(\OpenPayments\Utils\verifyContentDigest('x', $header)); + } + + public function test_verify_content_digest_rejects_empty_header() + { + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', '')); + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', ' ')); + } + + public function test_verify_content_digest_returns_false_for_unsupported_or_malformed_header() + { + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', 'sha-1=:AAAA:')); + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', 'sha-512=notbytes')); + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', '%%%')); + } + + public function test_verify_content_digest_requires_all_digests_to_match() + { + $good = \OpenPayments\Utils\createContentDigestHeader('x', ['sha-512']); + $bad = \OpenPayments\Utils\createContentDigestHeader('y', ['sha-256']); + + $this->assertFalse(\OpenPayments\Utils\verifyContentDigest('x', "$good, $bad")); + } + + public function test_validate_signature_round_trip_with_jwk() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + + $this->assertTrue(\OpenPayments\Utils\validateSignature($jwk, $this->signedRequest('POST', '{"amount":"1"}'))); + $this->assertTrue(\OpenPayments\Utils\validateSignature($jwk, $this->signedRequest('GET', null))); + } + + public function test_validate_signature_rejects_tampered_body() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + $request['body'] = '{"amount":"999"}'; + + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $request)); + } + + public function test_validate_signature_rejects_other_key() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId); + + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $this->signedRequest('POST', '{"amount":"1"}'))); + } + + public function test_validate_signature_returns_false_for_invalid_input() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + + $badSignature = $request; + $badSignature['headers']['signature'] = 'sig1=AAAA'; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $badSignature)); + + $this->assertFalse(\OpenPayments\Utils\validateSignature(['kty' => 'OKP', 'crv' => 'Ed25519', 'x' => 'short'], $request)); + $this->assertFalse(\OpenPayments\Utils\validateSignature(['kty' => 'EC', 'crv' => 'P-256', 'x' => $jwk['x']], $request)); + } +} From fc744e26754dd42ab03889aeab6dda09e2ad3871 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:15:42 +0300 Subject: [PATCH 2/9] fix(http-signature): fix content digest verification --- lib/Utils/HttpSignature.php | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index e1f4008..c14b7cd 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -6,6 +6,7 @@ use Bakame\Http\StructuredFields\ByteSequence; use Bakame\Http\StructuredFields\Dictionary; +use Bakame\Http\StructuredFields\Item; use SodiumException; /** @@ -445,23 +446,31 @@ function validateSigInputComponents(array $sigInputComponents, array $request): * * @param string $body The message body. * @param string $digestHeader The Content-Digest header value. - * @return bool True if the digest matches; false otherwise. - * - * @throws InvalidArgumentException If the digest header is malformed or contains unsupported algorithms. + * @return bool True if every digest in the header matches; false if any does not match, + * the header is empty or malformed, or it contains an unsupported algorithm. */ function verifyContentDigest(string $body, string $digestHeader): bool { - $dictionary = Dictionary::fromHttpValue($digestHeader); + try { + $dictionary = Dictionary::fromHttpValue($digestHeader); - foreach ($dictionary->getIterator() as $algo => $digest) { - if (! ($digest instanceof ByteSequence)) { - throw new \InvalidArgumentException("Invalid value for digest with algorithm key of '{$algo}'"); + if (count($dictionary) === 0) { + return false; } - $hash = base64_encode(hash(nodeAlgo($algo), $body, true)); - if ($digest->encoded() !== $hash) { - return false; + foreach ($dictionary->getIterator() as $algo => $member) { + $digest = $member instanceof Item ? $member->value() : null; + if (! ($digest instanceof ByteSequence)) { + return false; + } + $hash = base64_encode(hash(nodeAlgo($algo), $body, true)); + + if (! hash_equals($hash, $digest->encoded())) { + return false; + } } + } catch (\InvalidArgumentException $e) { + return false; } return true; From 5f5b6ebbd5d8c71075df8e7d69e4f6a4951866ac Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:16:00 +0300 Subject: [PATCH 3/9] fix(http-signature): fix jwk decoding in validateSignature --- lib/Utils/HttpSignature.php | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index c14b7cd..9852a4e 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -345,10 +345,37 @@ function validateSignature(array $clientKey, array $request): bool return false; } - $publicKey = sodium_crypto_sign_publickey($clientKey['x']); - $data = $challenge; + $publicKey = publicKeyFromJwk($clientKey); + // Accept both "sig1=" and the RFC 9421 byte sequence form "sig1=::". + $signature = base64_decode(trim(str_replace('sig1=', '', $sig), ':'), true); - return sodium_crypto_sign_verify_detached(base64_decode(str_replace('sig1=', '', $sig)), $data, $publicKey); + if ($publicKey === null || $signature === false || strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES) { + return false; + } + + try { + return sodium_crypto_sign_verify_detached($signature, $challenge, $publicKey); + } catch (SodiumException $e) { + return false; + } +} + +/** + * Returns the raw Ed25519 public key from a JWK, or null if the JWK is not a valid Ed25519 key. + */ +function publicKeyFromJwk(array $jwk): ?string +{ + if (($jwk['kty'] ?? null) !== 'OKP' || ($jwk['crv'] ?? null) !== 'Ed25519' || ! is_string($jwk['x'] ?? null)) { + return null; + } + + try { + $publicKey = sodium_base642bin($jwk['x'], SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); + } catch (SodiumException $e) { + return null; + } + + return strlen($publicKey) === SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ? $publicKey : null; } /** From 50bb24de6800088a12d28d063560167c0e04fe95 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:16:27 +0300 Subject: [PATCH 4/9] fix(http-signature): normalize header case and return false on errors --- lib/Utils/HttpSignature.php | 40 ++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index 9852a4e..8162172 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -314,6 +314,7 @@ function createSignatureInput(array $components, string $keyId): string */ function validateSignatureHeaders(array $request): bool { + $request = normalizeHeaders($request); $sig = $request['headers']['signature'] ?? null; $sigInput = $request['headers']['signature-input'] ?? null; if (! $sig || ! $sigInput || ! is_string($sig) || ! is_string($sigInput)) { @@ -337,8 +338,14 @@ function validateSignatureHeaders(array $request): bool */ function validateSignature(array $clientKey, array $request): bool { + $request = normalizeHeaders($request); $sig = $request['headers']['signature'] ?? ''; $sigInput = $request['headers']['signature-input'] ?? ''; + + if (! is_string($sig) || ! is_string($sigInput)) { + return false; + } + $challenge = sigInputToChallenge($sigInput, $request); if ($challenge === null) { @@ -389,6 +396,7 @@ function publicKeyFromJwk(array $jwk): ?string */ function sigInputToChallenge(string $sigInput, array $request): ?string { + $request = normalizeHeaders($request); $sigInputComponents = getSigInputComponents($sigInput); if ($sigInputComponents === null || ! validateSigInputComponents($sigInputComponents, $request)) { @@ -429,6 +437,16 @@ function getSigInputComponents(string $sigInput): ?array return $componentList ? array_map(static fn ($component) => trim($component, '()"'), $componentList) : null; } +/** + * Lowercases header names so lookups do not depend on the caller's casing. + */ +function normalizeHeaders(array $request): array +{ + $request['headers'] = array_change_key_case($request['headers'] ?? [], CASE_LOWER); + + return $request; +} + /** * validateSigInputComponents * @@ -446,18 +464,22 @@ function validateSigInputComponents(array $sigInputComponents, array $request): } } - $hasBody = isset($request['body']) && $request['body'] !== '' && $request['body'] !== null; - // Open Payments / GNAP: when a body is present, content-digest MUST be covered - // and verified. Omitting it previously failed open (body could be swapped). - // Sibling of interledger/open-payments-go#50. - if ($hasBody) { + $request = normalizeHeaders($request); + $body = $request['body'] ?? ''; + $contentDigest = $request['headers']['content-digest'] ?? null; + + if (! is_string($body) || ($contentDigest !== null && ! is_string($contentDigest))) { + return false; + } + + // When a body is present, content-digest must be covered and verified. + if ($body !== '') { $isValidContentDigest = in_array('content-digest', $sigInputComponents, true) && - isset($request['headers']['content-digest'], $request['headers']['content-length'], $request['headers']['content-type']) && - verifyContentDigest($request['body'], $request['headers']['content-digest']); + isset($contentDigest, $request['headers']['content-length'], $request['headers']['content-type']) && + verifyContentDigest($body, $contentDigest); } else { $isValidContentDigest = ! in_array('content-digest', $sigInputComponents, true) || - (isset($request['headers']['content-digest']) && - verifyContentDigest($request['body'] ?? '', $request['headers']['content-digest'])); + ($contentDigest !== null && verifyContentDigest($body, $contentDigest)); } return $isValidContentDigest && From 03bb786d462b9f940deb2ba5fa33b70d1343787d Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:16:40 +0300 Subject: [PATCH 5/9] fix(http-signature): align signer body check with verifier --- lib/Utils/HttpSignature.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index 8162172..97c3abf 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -199,7 +199,7 @@ function createSignatureHeaders(array $options): array if (! empty($request['headers']['Authorization']) || ! empty($request['headers']['authorization'])) { $components[] = 'authorization'; } - if (! empty($request['body'])) { + if (isset($request['body']) && $request['body'] !== '') { $components = array_merge($components, ['content-digest', 'content-length', 'content-type']); } @@ -586,7 +586,7 @@ function createHeaders(array $options): array $privateKey = $options['privateKey']; $keyId = $options['keyId']; - $contentHeaders = isset($request['body']) ? createContentHeaders($request['body']) : []; + $contentHeaders = isset($request['body']) && $request['body'] !== '' ? createContentHeaders($request['body']) : []; if ($contentHeaders) { $request['headers'] = array_merge($request['headers'], $contentHeaders); From 60527c1d6703615f9dbecfa78af8b1ec49ec0aaf Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:17:22 +0300 Subject: [PATCH 6/9] ci: add phpunit, phpstan and lint workflow --- .github/workflows/ci.yml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..93d7219 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + extensions: sodium, bcmath + coverage: none + + - run: composer install --no-interaction --no-progress + + - name: Tests + run: vendor/bin/phpunit tests + + # Scoped to paths that pass today. Widen as the rest is cleaned up. + - name: Static analysis + run: vendor/bin/phpstan analyse lib/Utils --level=1 --no-progress + + - name: Code style + run: vendor/bin/pint --test lib tests/Http tests/DTO tests/Validators From 97ef99d0adf99489e15c4334bd407b14a94a6700 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:17:31 +0300 Subject: [PATCH 7/9] docs: update changelog --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b7a998..49b0ba5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ 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). +## [Unreleased] + +### Fixed +- `validateSigInputComponents` requires `content-digest` to be covered and verified when the request has a body (#9) +- `verifyContentDigest` threw on every valid `Content-Digest` header; it now verifies the digest. It returns `false` for an empty, malformed or unsupported header instead of throwing +- `validateSignature` threw for every JWK; it now decodes the base64url `x` value. It returns `false` for an invalid key or signature, and accepts the RFC 9421 `sig1=::` form +- Signature validators ignore header name case. Before, an uncovered `Authorization` header was not detected +- Signature validators return `false` for a non-string body instead of throwing a `TypeError` +- `createSignatureHeaders` and `createHeaders` now treat the body `"0"` as a body + +### Added +- GitHub Actions CI: PHPUnit, PHPStan and Pint + ## [1.1.0] - 2026-06-13 ### Added From dbeb2d9bf57b4a18c30679a84914c9380924c4d4 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:22:14 +0300 Subject: [PATCH 8/9] fix(http-signature): reject ambiguous signature input and malformed requests --- CHANGELOG.md | 2 + lib/Utils/HttpSignature.php | 46 ++++++++-- .../Http/Signature/ValidateSignatureTest.php | 87 +++++++++++++++++++ 3 files changed, 128 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49b0ba5..df1ed8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Signature validators ignore header name case. Before, an uncovered `Authorization` header was not detected - Signature validators return `false` for a non-string body instead of throwing a `TypeError` - `createSignatureHeaders` and `createHeaders` now treat the body `"0"` as a body +- `createHeaders` no longer adds unsigned `Content-*` headers for an empty-string body +- Signature validators return `false` for header names that differ only by case, header values with line breaks, a `Signature-Input` with more than one `sig1=`, and a missing or non-string `method` or `url` ### Added - GitHub Actions CI: PHPUnit, PHPStan and Pint diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index 97c3abf..2a20fbf 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -315,6 +315,9 @@ function createSignatureInput(array $components, string $keyId): string function validateSignatureHeaders(array $request): bool { $request = normalizeHeaders($request); + if ($request === null) { + return false; + } $sig = $request['headers']['signature'] ?? null; $sigInput = $request['headers']['signature-input'] ?? null; if (! $sig || ! $sigInput || ! is_string($sig) || ! is_string($sigInput)) { @@ -339,6 +342,9 @@ function validateSignatureHeaders(array $request): bool function validateSignature(array $clientKey, array $request): bool { $request = normalizeHeaders($request); + if ($request === null) { + return false; + } $sig = $request['headers']['signature'] ?? ''; $sigInput = $request['headers']['signature-input'] ?? ''; @@ -397,6 +403,10 @@ function publicKeyFromJwk(array $jwk): ?string function sigInputToChallenge(string $sigInput, array $request): ?string { $request = normalizeHeaders($request); + if ($request === null || ! is_string($request['method'] ?? null) || ! is_string($request['url'] ?? null)) { + return null; + } + $sigInputComponents = getSigInputComponents($sigInput); if ($sigInputComponents === null || ! validateSigInputComponents($sigInputComponents, $request)) { @@ -407,15 +417,22 @@ function sigInputToChallenge(string $sigInput, array $request): ?string foreach ($sigInputComponents as $component) { if ($component === '@method') { - $signatureBase .= '"@method": '.strtoupper($request['method'])."\n"; + $value = strtoupper($request['method']); } elseif ($component === '@target-uri') { - $signatureBase .= '"@target-uri": '.$request['url']."\n"; + $value = $request['url']; } else { - $signatureBase .= "\"$component\": ".($request['headers'][$component] ?? '')."\n"; + $value = $request['headers'][$component] ?? ''; + } + + // A line break in a value could inject extra lines into the signature base. + if ((! is_string($value) && ! is_int($value)) || preg_match('/[\r\n]/', (string) $value)) { + return null; } + + $signatureBase .= "\"$component\": $value\n"; } - $signatureBase .= '"@signature-params": '.str_replace('sig1=', '', $request['headers']['signature-input'] ?? ''); + $signatureBase .= '"@signature-params": '.substr($sigInput, strlen('sig1=')); return $signatureBase; } @@ -429,6 +446,11 @@ function sigInputToChallenge(string $sigInput, array $request): ?string */ function getSigInputComponents(string $sigInput): ?array { + // Only a single "sig1" signature is supported. + if (! str_starts_with($sigInput, 'sig1=') || substr_count($sigInput, 'sig1=') !== 1) { + return null; + } + $messageComponents = explode('sig1=', $sigInput)[1] ?? ''; $components = explode(';', $messageComponents)[0] ?? ''; @@ -439,12 +461,19 @@ function getSigInputComponents(string $sigInput): ?array /** * Lowercases header names so lookups do not depend on the caller's casing. + * Returns null if headers is not an array or has names that differ only by case, + * since it is not clear which of those values was signed. */ -function normalizeHeaders(array $request): array +function normalizeHeaders(array $request): ?array { - $request['headers'] = array_change_key_case($request['headers'] ?? [], CASE_LOWER); + $headers = $request['headers'] ?? []; + if (! is_array($headers)) { + return null; + } + + $request['headers'] = array_change_key_case($headers, CASE_LOWER); - return $request; + return count($request['headers']) === count($headers) ? $request : null; } /** @@ -465,6 +494,9 @@ function validateSigInputComponents(array $sigInputComponents, array $request): } $request = normalizeHeaders($request); + if ($request === null) { + return false; + } $body = $request['body'] ?? ''; $contentDigest = $request['headers']['content-digest'] ?? null; diff --git a/tests/Http/Signature/ValidateSignatureTest.php b/tests/Http/Signature/ValidateSignatureTest.php index 77f1b2a..01cd6c8 100644 --- a/tests/Http/Signature/ValidateSignatureTest.php +++ b/tests/Http/Signature/ValidateSignatureTest.php @@ -173,4 +173,91 @@ public function test_validate_signature_returns_false_for_invalid_input() $this->assertFalse(\OpenPayments\Utils\validateSignature(['kty' => 'OKP', 'crv' => 'Ed25519', 'x' => 'short'], $request)); $this->assertFalse(\OpenPayments\Utils\validateSignature(['kty' => 'EC', 'crv' => 'P-256', 'x' => $jwk['x']], $request)); } + + public function test_validate_signature_rejects_tampered_method_url_or_authorization() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + + $tampered = $request; + $tampered['method'] = 'PUT'; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $tampered)); + + $tampered = $request; + $tampered['url'] = 'https://example.com/outgoing-payments'; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $tampered)); + + $tampered = $request; + $tampered['headers']['authorization'] = 'GNAP other-token'; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $tampered)); + } + + public function test_validate_signature_accepts_byte_sequence_form() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + $request['headers']['signature'] = 'sig1=:'.substr($request['headers']['signature'], strlen('sig1=')).':'; + + $this->assertTrue(\OpenPayments\Utils\validateSignature($jwk, $request)); + } + + public function test_rejects_header_names_that_differ_only_by_case() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}', lowercase: false); + $request['headers'] = ['authorization' => 'GNAP other-token'] + $request['headers']; + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $request)); + } + + public function test_rejects_line_break_in_covered_header() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('GET', null, ['Authorization' => "GNAP token\n\"content-type\": text/plain"]); + + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $request)); + } + + public function test_rejects_signature_input_with_more_than_one_label() + { + $request = $this->signedRequest('POST', '{"amount":"1"}'); + $request['headers']['signature-input'] = str_replace('"authorization"', '"authorization"sig1=', $request['headers']['signature-input']); + + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($request)); + } + + public function test_validate_signature_returns_false_for_malformed_request() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + + $noMethod = $request; + unset($noMethod['method']); + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $noMethod)); + + $noUrl = $request; + unset($noUrl['url']); + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $noUrl)); + + $arrayHeader = $request; + $arrayHeader['headers']['authorization'] = ['GNAP token']; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $arrayHeader)); + + $stringHeaders = $request; + $stringHeaders['headers'] = 'not-an-array'; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $stringHeaders)); + $this->assertFalse(\OpenPayments\Utils\validateSignatureHeaders($stringHeaders)); + } + + public function test_create_headers_skips_content_headers_for_empty_body() + { + $headers = \OpenPayments\Utils\createHeaders([ + 'request' => ['method' => 'POST', 'url' => 'https://example.com/incoming-payments', 'headers' => [], 'body' => ''], + 'privateKey' => $this->privateKey, + 'keyId' => $this->keyId, + ]); + + $this->assertSame(['Signature', 'Signature-Input'], array_keys($headers)); + } } From 806b01cf3f34864843a573ec8009f5c9adf14a61 Mon Sep 17 00:00:00 2001 From: Adrian Boros Date: Wed, 7 Oct 2026 10:46:28 +0300 Subject: [PATCH 9/9] fix(http-signature): parse signature value strictly --- lib/Utils/HttpSignature.php | 7 +++++-- tests/Http/Signature/ValidateSignatureTest.php | 12 ++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index 2a20fbf..c4a0549 100644 --- a/lib/Utils/HttpSignature.php +++ b/lib/Utils/HttpSignature.php @@ -359,8 +359,11 @@ function validateSignature(array $clientKey, array $request): bool } $publicKey = publicKeyFromJwk($clientKey); - // Accept both "sig1=" and the RFC 9421 byte sequence form "sig1=::". - $signature = base64_decode(trim(str_replace('sig1=', '', $sig), ':'), true); + // Accept only "sig1=" and the RFC 9421 byte sequence form "sig1=::". + if (! preg_match('/^sig1=(:?)([A-Za-z0-9+\/]+={0,2})\1$/', $sig, $matches)) { + return false; + } + $signature = base64_decode($matches[2], true); if ($publicKey === null || $signature === false || strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES) { return false; diff --git a/tests/Http/Signature/ValidateSignatureTest.php b/tests/Http/Signature/ValidateSignatureTest.php index 01cd6c8..980a295 100644 --- a/tests/Http/Signature/ValidateSignatureTest.php +++ b/tests/Http/Signature/ValidateSignatureTest.php @@ -201,6 +201,18 @@ public function test_validate_signature_accepts_byte_sequence_form() $this->assertTrue(\OpenPayments\Utils\validateSignature($jwk, $request)); } + public function test_validate_signature_rejects_malformed_signature_wrapper() + { + $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey); + $request = $this->signedRequest('POST', '{"amount":"1"}'); + $value = substr($request['headers']['signature'], strlen('sig1=')); + + foreach (["sig1=:$value", "sig1=$value:", "sig1=::$value::", "sig1=sig1=$value", $value, "sig2=:$value:"] as $signature) { + $request['headers']['signature'] = $signature; + $this->assertFalse(\OpenPayments\Utils\validateSignature($jwk, $request), $signature); + } + } + public function test_rejects_header_names_that_differ_only_by_case() { $jwk = \OpenPayments\Utils\generateJwk($this->keyId, $this->privateKey);