Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `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`
- Signature validators check the `created` and `expires` parameters. They return `false` when `created` is missing, older than `maxAge` (default 300 seconds) or more than `clockSkew` (default 60 seconds) in the future, or when `expires` is in the past. This limits replay of old signatures. Pass `['maxAge' => ..., 'clockSkew' => ..., 'now' => ...]` as the last argument to change the limits
- `validateSignature` returns `false` when the `keyid` parameter does not match the JWK `kid`
- Signature validators require `content-length` and `content-type` to be signed when the request has a body. Before, they only had to be present
- The signer reads `Authorization` and `Content-Type` with any name case. Before, it only read `Authorization` or `authorization`, and only `Content-Type`
- `createHeaders` ignores caller `Content-*` headers with other name cases when it signs, so only the generated values are signed
- The signer throws when header names differ only by case, because it is not clear which value to sign
- `ApiClient` merges headers without regard to name case. The `Authorization`, `Host` and signature headers it sets replace caller headers with the same name in another case, so each header is sent once
- `Signature-Input` is read by one strict parser: components must be quoted lowercase names, parameter values must be integers or strings without escapes, and a parameter must not repeat. A signature with `expires` is valid only before `expires`, and `expires` must not be before `created`
- Signature validators throw `InvalidArgumentException` when `maxAge`, `clockSkew` or `now` is not a non-negative integer
- The signer throws for a key ID with a quote, a backslash or a character outside printable ASCII, because it would change the `Signature-Input` header

### Added
- GitHub Actions CI: PHPUnit, PHPStan and Pint
Expand Down
31 changes: 23 additions & 8 deletions lib/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ public function request(string $method, string $endpoint, array $data = [], arra
if (! empty($jsonBody)) {
$options['body'] = $jsonBody;
}
$headers = array_merge([
$headers = self::mergeHeaders([
'Content-Length' => strlen($jsonBody),
], $headers);
$options['headers'] = array_merge($this->getDefaultHeaders(), $headers);
$options['headers'] = self::mergeHeaders($this->getDefaultHeaders(), $headers);

if (strtoupper($method) === 'GET' && count($data) > 0) {
$endpoint = $endpoint.'?'.http_build_query($data);
Expand All @@ -53,7 +53,7 @@ public function request(string $method, string $endpoint, array $data = [], arra
// Generate and add HTTP Signature headers
if ($this->privateKey && $this->keyId && ($method == 'POST' || $this->accessToken)) {
$signatureHeaders = $this->generateHttpSignature($method, $endpoint, $jsonBody, $options['headers']);
$options['headers'] = array_merge($options['headers'], $signatureHeaders);
$options['headers'] = self::mergeHeaders($options['headers'], $signatureHeaders);
}

$response = $httpClient->request($method, $endpoint, $options);
Expand All @@ -78,12 +78,12 @@ public function request(string $method, string $endpoint, array $data = [], arra

public function generateHttpSignature($method, $url, $jsonBody, $defaultHeaders)
{
$headers = $defaultHeaders;
$headers = self::mergeHeaders([], $defaultHeaders);
if ($this->accessToken) {
$headers['Authorization'] = "GNAP {$this->accessToken}";
$headers = self::mergeHeaders($headers, ['Authorization' => "GNAP {$this->accessToken}"]);
}
$parse = parse_url($url);
$headers['Host'] = $parse['host'];
$headers = self::mergeHeaders($headers, ['Host' => $parse['host']]);

$requestArr = [
'method' => $method,
Expand All @@ -96,8 +96,23 @@ public function generateHttpSignature($method, $url, $jsonBody, $defaultHeaders)
'privateKey' => base64_decode($this->privateKey),
'keyId' => $this->keyId,
]);
foreach ($result as $key => $value) {
$headers[$key] = $value;

return self::mergeHeaders($headers, $result);
}

/**
* Merges headers without regard to name case. A value in $override replaces
* any header in $headers with the same name in another case.
*/
private static function mergeHeaders(array $headers, array $override): array
{
foreach ($override as $name => $value) {
foreach (array_keys($headers) as $existing) {
if (strcasecmp((string) $existing, (string) $name) === 0) {
unset($headers[$existing]);
}
}
$headers[$name] = $value;
}

return $headers;
Expand Down
132 changes: 116 additions & 16 deletions lib/Utils/HttpSignature.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,21 @@ function createSignatureHeaders(array $options): array
$privateKey = $options['privateKey'];
$keyId = $options['keyId'];

if (! isset($request['method'], $request['url'], $request['headers']) || empty($keyId)) {
if (! isset($request['method'], $request['url'], $request['headers']) || ! is_array($request['headers']) || empty($keyId)) {
throw new \Exception('Invalid signing options');
}
// keyid is a quoted string in Signature-Input, so a quote or backslash would change the header.
if (! is_string($keyId) || preg_match('/[^\x20-\x7e]|["\\\\]/', $keyId)) {
throw new \Exception('Invalid key ID');
}
$headers = array_change_key_case($request['headers'], CASE_LOWER);
if (count($headers) !== count($request['headers'])) {
throw new \Exception('Header names must not differ only by case');
}
$request['headers'] = $headers;

$components = ['@method', '@target-uri'];
if (! empty($request['headers']['Authorization']) || ! empty($request['headers']['authorization'])) {
if (! empty($request['headers']['authorization'])) {
$components[] = 'authorization';
}
if (isset($request['body']) && $request['body'] !== '') {
Expand Down Expand Up @@ -265,7 +274,7 @@ function prepareSigningData(array $request, array $components): string
$dataToSign .= '"@target-uri": '.$request['url']."\n";
break;
case 'authorization':
$authorization = $request['headers']['authorization'] ?? $request['headers']['Authorization'] ?? '';
$authorization = $request['headers']['authorization'] ?? '';
$dataToSign .= "\"authorization\": $authorization\n";
break;
case 'content-digest':
Expand All @@ -277,7 +286,7 @@ function prepareSigningData(array $request, array $components): string
$dataToSign .= "\"content-length\": $contentLength\n";
break;
case 'content-type':
$contentType = $request['headers']['Content-Type'] ?? 'application/octet-stream';
$contentType = $request['headers']['content-type'] ?? 'application/octet-stream';
$dataToSign .= "\"content-type\": $contentType\n";
break;
default:
Expand Down Expand Up @@ -312,7 +321,7 @@ function createSignatureInput(array $components, string $keyId): string
*
* @param mixed $request
*/
function validateSignatureHeaders(array $request): bool
function validateSignatureHeaders(array $request, array $options = []): bool
{
$request = normalizeHeaders($request);
if ($request === null) {
Expand All @@ -325,8 +334,11 @@ function validateSignatureHeaders(array $request): bool
}

$sigInputComponents = getSigInputComponents($sigInput);
$params = getSigInputParams($sigInput);

return $sigInputComponents !== null &&
$params !== null &&
validateSigInputTime($params, $options) &&
validateSigInputComponents($sigInputComponents, $request);
}

Expand All @@ -339,7 +351,7 @@ function validateSignatureHeaders(array $request): bool
* @param mixed $clientKey
* @param mixed $request
*/
function validateSignature(array $clientKey, array $request): bool
function validateSignature(array $clientKey, array $request, array $options = []): bool
{
$request = normalizeHeaders($request);
if ($request === null) {
Expand All @@ -352,6 +364,15 @@ function validateSignature(array $clientKey, array $request): bool
return false;
}

$params = getSigInputParams($sigInput);
// The signature must be made with the key in $clientKey.
if ($params === null ||
! is_string($clientKey['kid'] ?? null) ||
($params['keyid'] ?? null) !== $clientKey['kid'] ||
! validateSigInputTime($params, $options)) {
return false;
}

$challenge = sigInputToChallenge($sigInput, $request);

if ($challenge === null) {
Expand Down Expand Up @@ -441,25 +462,98 @@ function sigInputToChallenge(string $sigInput, array $request): ?string
}

/**
* getSigInputComponents
* Parses the "sig1" Signature-Input, for example
* `sig1=("@method" "@target-uri");keyid="key-1";created=1700000000`.
*
* Parses and cleans up the components in signature-input, removing any special characters
* Components must be quoted lowercase names. Parameter values must be integers or
* strings without escapes. Returns null for any other input, for more than one label,
* or for a repeated parameter.
*
* @param mixed $sigInput
* @return array{components: string[], params: array<string, string|int>}|null
*/
function getSigInputComponents(string $sigInput): ?array
function parseSigInput(string $sigInput): ?array
{
// Only a single "sig1" signature is supported.
if (! str_starts_with($sigInput, 'sig1=') || substr_count($sigInput, 'sig1=') !== 1) {
if (substr_count($sigInput, 'sig1=') !== 1) {
return null;
}

$component = '"[a-z0-9@_.-]+"';
$param = '; *([a-z*][a-z0-9_.*-]*)=(?:"([\x20\x21\x23-\x5b\x5d-\x7e]*)"|(-?\d{1,15}))';
if (! preg_match('/^sig1=\(((?:'.$component.')(?: '.$component.')*)?\)((?:'.$param.')*)\z/', $sigInput, $matches)) {
return null;
}

$messageComponents = explode('sig1=', $sigInput)[1] ?? '';
$components = ($matches[1] ?? '') === '' ? [] : array_map(
static fn ($name) => trim($name, '"'),
explode(' ', $matches[1])
);

$components = explode(';', $messageComponents)[0] ?? '';
$componentList = explode(' ', $components);
preg_match_all('/'.$param.'/', $matches[2] ?? '', $pairs, PREG_SET_ORDER);
$params = [];
foreach ($pairs as $pair) {
if (array_key_exists($pair[1], $params)) {
return null;
}
$params[$pair[1]] = isset($pair[3]) && $pair[3] !== '' ? (int) $pair[3] : $pair[2];
}

return ['components' => $components, 'params' => $params];
}

/**
* getSigInputComponents
*
* Returns the component names of the "sig1" Signature-Input, or null if it is malformed.
*/
function getSigInputComponents(string $sigInput): ?array
{
return parseSigInput($sigInput)['components'] ?? null;
}

/**
* Returns the parameters of the "sig1" Signature-Input.
* Returns null if the Signature-Input is malformed or `created` is missing.
*
* @return array<string, string|int>|null
*/
function getSigInputParams(string $sigInput): ?array
{
$params = parseSigInput($sigInput)['params'] ?? null;

return is_int($params['created'] ?? null) ? $params : null;
}

/**
* Checks the `created` and `expires` signature parameters, to limit replay of old signatures.
*
* Options:
* - `maxAge`: seconds a signature is valid after `created` (default 300)
* - `clockSkew`: seconds `created` may be in the future (default 60)
* - `now`: current Unix time (default `time()`)
*
* @throws \InvalidArgumentException if an option is not a non-negative integer
*/
function validateSigInputTime(array $params, array $options = []): bool
{
$now = $options['now'] ?? time();
$maxAge = $options['maxAge'] ?? 300;
$clockSkew = $options['clockSkew'] ?? 60;
foreach (['now' => $now, 'maxAge' => $maxAge, 'clockSkew' => $clockSkew] as $name => $value) {
if (! is_int($value) || $value < 0) {
throw new \InvalidArgumentException("Signature option $name must be a non-negative integer");
}
}

$created = $params['created'] ?? null;
$expires = $params['expires'] ?? null;

if (! is_int($created) || $created > $now + $clockSkew || $now - $created > $maxAge) {
return false;
}

return $componentList ? array_map(static fn ($component) => trim($component, '()"'), $componentList) : null;
// The signature is not valid at or after `expires`.
return $expires === null || (is_int($expires) && $expires > $now && $expires >= $created);
}

/**
Expand Down Expand Up @@ -509,7 +603,7 @@ function validateSigInputComponents(array $sigInputComponents, array $request):

// When a body is present, content-digest must be covered and verified.
if ($body !== '') {
$isValidContentDigest = in_array('content-digest', $sigInputComponents, true) &&
$isValidContentDigest = ! array_diff(['content-digest', 'content-length', 'content-type'], $sigInputComponents) &&
isset($contentDigest, $request['headers']['content-length'], $request['headers']['content-type']) &&
verifyContentDigest($body, $contentDigest);
} else {
Expand Down Expand Up @@ -624,6 +718,12 @@ function createHeaders(array $options): array
$contentHeaders = isset($request['body']) && $request['body'] !== '' ? createContentHeaders($request['body']) : [];

if ($contentHeaders) {
// Drop caller content headers with other name cases, so only the generated values are signed.
$request['headers'] = array_filter(
$request['headers'],
static fn ($name) => ! in_array(strtolower((string) $name), ['content-digest', 'content-length', 'content-type'], true),
ARRAY_FILTER_USE_KEY
);
$request['headers'] = array_merge($request['headers'], $contentHeaders);
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Http/ApiClientHeadersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

use OpenPayments\ApiClient;
use PHPUnit\Framework\TestCase;

class ApiClientHeadersTest extends TestCase
{
public function test_signature_headers_replace_caller_headers_with_other_name_case(): void
{
$privateKey = sodium_crypto_sign_secretkey(sodium_crypto_sign_keypair());
$client = new ApiClient(base64_encode($privateKey), 'gnap-key', 'token');

$headers = $client->generateHttpSignature('POST', 'https://example.com/incoming-payments', '{"a":1}', [
'authorization' => 'GNAP other',
'host' => 'other.example.com',
'content-type' => 'text/plain',
'Accept' => 'application/json',
]);

$names = array_map('strtolower', array_keys($headers));
$this->assertSame(count($names), count(array_unique($names)));
$this->assertSame('GNAP token', $headers['Authorization']);
$this->assertSame('example.com', $headers['Host']);
$this->assertSame('application/json', $headers['Content-Type']);

$jwk = \OpenPayments\Utils\generateJwk('gnap-key', $privateKey);
$this->assertTrue(\OpenPayments\Utils\validateSignature($jwk, [
'method' => 'POST',
'url' => 'https://example.com/incoming-payments',
'headers' => array_map('strval', $headers),
'body' => '{"a":1}',
]));
}
}
Loading
Loading