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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b7a998..df1ed8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ 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 +- `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 + ## [1.1.0] - 2026-06-13 ### Added diff --git a/lib/Utils/HttpSignature.php b/lib/Utils/HttpSignature.php index e1f4008..c4a0549 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; /** @@ -198,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']); } @@ -313,6 +314,10 @@ 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)) { @@ -336,18 +341,57 @@ 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'] ?? ''; + + if (! is_string($sig) || ! is_string($sigInput)) { + return false; + } + $challenge = sigInputToChallenge($sigInput, $request); if ($challenge === null) { return false; } - $publicKey = sodium_crypto_sign_publickey($clientKey['x']); - $data = $challenge; + $publicKey = publicKeyFromJwk($clientKey); + // 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; + } + + 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 sodium_crypto_sign_verify_detached(base64_decode(str_replace('sig1=', '', $sig)), $data, $publicKey); + return strlen($publicKey) === SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ? $publicKey : null; } /** @@ -361,6 +405,11 @@ function validateSignature(array $clientKey, array $request): bool */ 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)) { @@ -371,15 +420,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; } @@ -393,6 +449,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] ?? ''; @@ -401,6 +462,23 @@ 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. + * 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 +{ + $headers = $request['headers'] ?? []; + if (! is_array($headers)) { + return null; + } + + $request['headers'] = array_change_key_case($headers, CASE_LOWER); + + return count($request['headers']) === count($headers) ? $request : null; +} + /** * validateSigInputComponents * @@ -418,18 +496,25 @@ 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); + if ($request === null) { + return false; + } + $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 && @@ -445,23 +530,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; @@ -528,7 +621,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); diff --git a/tests/Http/Signature/ValidateSignatureTest.php b/tests/Http/Signature/ValidateSignatureTest.php new file mode 100644 index 0000000..980a295 --- /dev/null +++ b/tests/Http/Signature/ValidateSignatureTest.php @@ -0,0 +1,275 @@ +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)); + } + + 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_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); + $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)); + } +}