Skip to content

Commit

Permalink
SP-1024 Implementing IPN HMAC Verification
Browse files Browse the repository at this point in the history
  • Loading branch information
m-kwiatkowski committed Nov 28, 2024
1 parent 73875bb commit 6fc1382
Show file tree
Hide file tree
Showing 13 changed files with 435 additions and 98 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

final class BaseUpdateInvoiceValidator implements UpdateInvoiceValidator
{
public function execute(?array $data, ?BitPayInvoice $bitPayInvoice): void
public function execute(?array $data, ?BitPayInvoice $bitPayInvoice, array $headers): void
{
if (!$data) {
throw new ValidationFailed('Missing data');
Expand Down
58 changes: 58 additions & 0 deletions app/Features/Invoice/UpdateInvoice/BitPaySignatureValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace App\Features\Invoice\UpdateInvoice;

use App\Shared\Exceptions\SignatureVerificationFailed;
use App\Features\Shared\Configuration\BitPayConfigurationInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

final class BitPaySignatureValidator
{
public const MISSING_SIGNATURE_MESSAGE = 'Missing signature header';
public const INVALID_SIGNATURE_MESSAGE = 'Invalid signature';
public const MISSING_TOKEN_MESSAGE = 'Invalid BitPay configuration - missing token';

private BitPayConfigurationInterface $bitpayConfiguration;
private LoggerInterface $logger;
public function __construct(
BitPayConfigurationInterface $bitpayConfiguration,
LoggerInterface $logger
) {
$this->bitpayConfiguration = $bitpayConfiguration;
$this->logger = $logger;
}

public function execute(array $data, array $headers): void
{
$token = $this->bitpayConfiguration->getToken();

if (!$token) {
throw new RuntimeException(self::MISSING_TOKEN_MESSAGE);
}

$sigHeader = $headers['x-signature'][0] ?? null;

if (!$sigHeader) {
throw new SignatureVerificationFailed(self::MISSING_SIGNATURE_MESSAGE);
}

$hmac = base64_encode(hash_hmac(
'sha256',
json_encode($data),
$token,
true
));

$this->logger->info('HMAC', [
'hmac' => $hmac,
'sigHeader' => $sigHeader,
]);

if ($sigHeader !== $hmac) {
throw new SignatureVerificationFailed(self::INVALID_SIGNATURE_MESSAGE);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace App\Features\Invoice\UpdateInvoice;

interface BitPaySignatureValidatorInterface
{
/**
* Validates the BitPay signature against the provided data and headers
*
* @param array $data The payload data to validate
* @param array $headers The headers containing the signature - x-signature
*
* @throws \App\Shared\Exceptions\ValidationFailed When signature is missing or invalid
* @throws \RuntimeException When BitPay token is missing
*/
public function execute(array $data, array $headers): void;
}
14 changes: 10 additions & 4 deletions app/Features/Invoice/UpdateInvoice/UpdateInvoiceIpnValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,23 @@ final class UpdateInvoiceIpnValidator implements UpdateInvoiceValidator

private UpdateInvoiceValidator $updateInvoiceValidator;
private Logger $logger;
private BitPaySignatureValidator $bitPaySignatureValidator;

public function __construct(UpdateInvoiceValidator $updateInvoiceValidator, Logger $logger)
{
public function __construct(
UpdateInvoiceValidator $updateInvoiceValidator,
Logger $logger,
BitPaySignatureValidator $bitPaySignatureValidator
) {
$this->updateInvoiceValidator = $updateInvoiceValidator;
$this->logger = $logger;
$this->bitPaySignatureValidator = $bitPaySignatureValidator;
}

public function execute(?array $data, ?BitPayInvoice $bitPayInvoice): void
public function execute(?array $data, ?BitPayInvoice $bitPayInvoice, ?array $headers): void
{
try {
$this->updateInvoiceValidator->execute($data, $bitPayInvoice);
$this->bitPaySignatureValidator->execute($data, $headers);
$this->updateInvoiceValidator->execute($data, $bitPayInvoice, $headers);

if (!$bitPayInvoice) {
throw new ValidationFailed(self::MISSING_BITPAY_MESSAGE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use App\Models\Invoice\InvoicePayment;
use App\Models\Invoice\InvoicePaymentCurrency;
use App\Models\Invoice\InvoiceRepositoryInterface;

use App\Shared\Exceptions\SignatureVerificationFailed;
class UpdateInvoiceUsingBitPayIpn
{
private InvoiceRepositoryInterface $invoiceRepository;
Expand Down Expand Up @@ -45,7 +45,7 @@ public function __construct(
$this->bitPayConfiguration = $bitPayConfiguration;
}

public function execute(string $uuid, array $data): void
public function execute(string $uuid, array $data, array $headers): void
{
$invoice = $this->invoiceRepository->findOneByUuid($uuid);
if (!$invoice) {
Expand All @@ -54,18 +54,21 @@ public function execute(string $uuid, array $data): void

try {
$client = $this->bitPayClientFactory->create();

$bitPayInvoice = $client->getInvoice(
$invoice->getBitpayId(),
$this->bitPayConfiguration->getFacade(),
$this->bitPayConfiguration->isSignRequest()
);

$updateInvoiceData = $this->bitPayUpdateMapper->execute($data)->toArray();
$this->updateInvoiceValidator->execute($data, $bitPayInvoice);
$this->updateInvoiceValidator->execute($data, $bitPayInvoice, $headers);

$this->updateInvoice($invoice, $updateInvoiceData);

$this->sendUpdateInvoiceNotification->execute($invoice, $data['event'] ?? null);
} catch (SignatureVerificationFailed $e) {
throw $e;
} catch (\Exception | \TypeError $e) {
$this->logger->error('INVOICE_UPDATE_FAIL', 'Failed to update invoice', [
'id' => $invoice->id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ interface UpdateInvoiceValidator
/**
* @throws ValidationFailed
*/
public function execute(?array $data, ?BitPayInvoice $bitPayInvoice): void;
public function execute(?array $data, ?BitPayInvoice $bitPayInvoice, array $headers): void;
}
11 changes: 7 additions & 4 deletions app/Http/Controllers/Invoice/UpdateInvoiceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Shared\Exceptions\SignatureVerificationFailed;

class UpdateInvoiceController extends Controller
{
Expand All @@ -30,17 +31,19 @@ public function execute(Request $request, string $uuid): Response
{
$this->logger->info('IPN_RECEIVED', 'Received IPN', $request->request->all());

/** @var array $data */
$data = $request->request->get('data');
$event = $request->request->get('event');
$payload = json_decode($request->getContent(), true);
$data = $payload['data'];
$event = $payload['event'];

$data['uuid'] = $uuid;
$data['event'] = $event['name'] ?? null;

try {
$this->updateInvoice->execute($uuid, $data);
$this->updateInvoice->execute($uuid, $data, $request->headers->all());
} catch (MissingInvoice $e) {
return response(null, Response::HTTP_NOT_FOUND);
} catch (SignatureVerificationFailed $e) {
return response($e->getMessage(), Response::HTTP_UNAUTHORIZED);
} catch (\Exception $e) {
return response('Unable to process update', Response::HTTP_BAD_REQUEST);
}
Expand Down
10 changes: 9 additions & 1 deletion app/Infrastructure/Laravel/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use App\Features\Invoice\UpdateInvoice\SendUpdateInvoiceEventStream;
use App\Features\Invoice\UpdateInvoice\UpdateInvoiceIpnValidator;
use App\Features\Invoice\UpdateInvoice\UpdateInvoiceValidator;
use App\Features\Invoice\UpdateInvoice\BitPaySignatureValidator;
use App\Features\Invoice\UpdateInvoice\BitPaySignatureValidatorInterface;
use App\Features\Shared\Logger;
use App\Features\Shared\SseConfiguration;
use App\Features\Shared\UrlProvider;
Expand Down Expand Up @@ -87,12 +89,18 @@ function () {
SseMercureConfiguration::class
);

$this->app->bind(
BitPaySignatureValidatorInterface::class,
BitPaySignatureValidator::class
);

$this->app->bind(
UpdateInvoiceIpnValidator::class,
function () {
return new UpdateInvoiceIpnValidator(
$this->app->make(BaseUpdateInvoiceValidator::class),
$this->app->make(Logger::class)
$this->app->make(Logger::class),
$this->app->make(BitPaySignatureValidator::class)
);
}
);
Expand Down
13 changes: 13 additions & 0 deletions app/Shared/Exceptions/SignatureVerificationFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

/**
* Copyright (c) 2019 BitPay
**/

declare(strict_types=1);

namespace App\Shared\Exceptions;

class SignatureVerificationFailed extends \RuntimeException
{
}
1 change: 0 additions & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,3 @@
Route::post('/invoices', [CreateInvoiceController::class, 'execute'])->name('createInvoice');
Route::get('/invoices/{id}', [GetInvoiceViewController::class, 'execute'])->name('invoiceView');
Route::post('/invoices/{uuid}', [UpdateInvoiceController::class, 'execute'])->name('updateInvoice');

Loading

0 comments on commit 6fc1382

Please sign in to comment.