diff --git a/src/Common/Utils.php b/src/Common/Utils.php index f0517a0..aab1330 100644 --- a/src/Common/Utils.php +++ b/src/Common/Utils.php @@ -10,7 +10,7 @@ public static function generateRandomString($length = 10) $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; + $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; } @@ -22,16 +22,11 @@ public static function generateRandomString($length = 10) */ public static function generateUuid(): string { - return sprintf( - '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), - mt_rand(0, 0x0fff) | 0x4000, - mt_rand(0, 0x3fff) | 0x8000, - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), - mt_rand(0, 0xffff) - ); + // RFC 4122 v4 from a CSPRNG: these values become payment idempotency and + // lookup keys, so they must be unguessable (rand()/mt_rand() are not). + $data = random_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } } diff --git a/src/Gateway/IvoryCost/Mono/MonoGateway.php b/src/Gateway/IvoryCost/Mono/MonoGateway.php index 73a87c0..96421ed 100644 --- a/src/Gateway/IvoryCost/Mono/MonoGateway.php +++ b/src/Gateway/IvoryCost/Mono/MonoGateway.php @@ -61,7 +61,7 @@ public function payment(array $params) $amount = $params['amount']; $phone = $params['phone_number']; - $reference = $params['reference'] ?? uniqid('momo_'); + $reference = $params['reference'] ?? 'momo_' . bin2hex(random_bytes(8)); $currency = $params['currency'] ?? 'XOF'; return $payment->requestToPay([ diff --git a/src/Gateway/IvoryCost/Orange/OrangeTokenGenerator.php b/src/Gateway/IvoryCost/Orange/OrangeTokenGenerator.php index d39b3ee..6a242f3 100644 --- a/src/Gateway/IvoryCost/Orange/OrangeTokenGenerator.php +++ b/src/Gateway/IvoryCost/Orange/OrangeTokenGenerator.php @@ -76,6 +76,12 @@ public function getToken() */ public function setUrl(string $url) { + // Basic-auth credentials are POSTed to this URL, so never allow a + // cleartext endpoint. + if (stripos($url, 'https://') !== 0) { + throw new \InvalidArgumentException('The Orange token endpoint must use HTTPS.'); + } + $this->get_token_url = $url; } @@ -87,6 +93,12 @@ public function setUrl(string $url) */ public function setTokenGeneratorEndpoint(string $url) { + // Basic-auth credentials are POSTed to this URL, so never allow a + // cleartext endpoint. + if (stripos($url, 'https://') !== 0) { + throw new \InvalidArgumentException('The Orange token endpoint must use HTTPS.'); + } + $this->get_token_url = $url; } diff --git a/src/Shared/Wave/WaveClient.php b/src/Shared/Wave/WaveClient.php index 0b5d73e..e49767b 100644 --- a/src/Shared/Wave/WaveClient.php +++ b/src/Shared/Wave/WaveClient.php @@ -97,7 +97,7 @@ public function createCheckoutSession(array $data, ?string $idempotencyKey = nul public function retrieveCheckoutSession(string $sessionId): WaveCheckoutSession { try { - $response = $this->http->get("/v1/checkout/sessions/{$sessionId}"); + $response = $this->http->get("/v1/checkout/sessions/" . rawurlencode($sessionId)); $content = $response->getBody()->getContents(); $sessionData = json_decode($content, true); @@ -217,7 +217,7 @@ public function searchCheckoutSessions(string $clientReference): array public function refundCheckoutSession(string $sessionId): bool { try { - $response = $this->http->post("/v1/checkout/sessions/{$sessionId}/refund"); + $response = $this->http->post("/v1/checkout/sessions/" . rawurlencode($sessionId) . "/refund"); return $response->getStatusCode() === 200; } catch (\GuzzleHttp\Exception\ClientException $e) { return $this->handleClientException($e); @@ -246,7 +246,7 @@ public function refundCheckoutSession(string $sessionId): bool public function expireCheckoutSession(string $sessionId): bool { try { - $response = $this->http->post("/v1/checkout/sessions/{$sessionId}/expire"); + $response = $this->http->post("/v1/checkout/sessions/" . rawurlencode($sessionId) . "/expire"); return $response->getStatusCode() === 200; } catch (\GuzzleHttp\Exception\ClientException $e) { return $this->handleClientException($e); diff --git a/src/Support/TransactionLogger.php b/src/Support/TransactionLogger.php index 4970b16..4625076 100644 --- a/src/Support/TransactionLogger.php +++ b/src/Support/TransactionLogger.php @@ -41,7 +41,7 @@ public function __construct(string $logPath = '', bool $enabled = true) $this->enabled = $enabled; if ($this->enabled && !file_exists($this->logPath)) { - mkdir($this->logPath, 0755, true); + mkdir($this->logPath, 0700, true); } } @@ -53,6 +53,28 @@ public function __construct(string $logPath = '', bool $enabled = true) * @param array $context * @return void */ + /** + * Recursively mask secret-bearing keys so credentials in gateway + * responses are never written to the log files. + * + * @param array $data + * @return array + */ + private function redact(array $data): array + { + $sensitive = '/(key|secret|passwo?r?d|token|authorization|signature|apikey|credential|private|cvv|pin)/i'; + + foreach ($data as $k => $v) { + if (is_string($k) && preg_match($sensitive, $k)) { + $data[$k] = '[REDACTED]'; + } elseif (is_array($v)) { + $data[$k] = $this->redact($v); + } + } + + return $data; + } + public function log(string $level, string $message, array $context = []): void { if (!$this->enabled) { @@ -63,7 +85,7 @@ public function log(string $level, string $message, array $context = []): void 'timestamp' => date('Y-m-d H:i:s'), 'level' => $level, 'message' => $message, - 'context' => $context, + 'context' => $this->redact($context), ]; $filename = $this->logPath . '/payment_' . date('Y-m-d') . '.log'; diff --git a/src/Webhook/WebhookHandler.php b/src/Webhook/WebhookHandler.php index 1c56644..6a1c44c 100644 --- a/src/Webhook/WebhookHandler.php +++ b/src/Webhook/WebhookHandler.php @@ -43,10 +43,20 @@ public function __construct(string $provider, string $secret) * @return WebhookEvent * @throws PaymentException */ - public function handle(array $payload, ?string $signature = null): WebhookEvent + public function handle(array $payload, ?string $signature = null, ?string $rawBody = null): WebhookEvent { - // Validate signature if provided - if ($signature && !$this->validateSignature($payload, $signature)) { + // The signature is mandatory. An unsigned webhook must never be trusted, + // otherwise anyone can POST a forged "payment success" event (fraud). + if (!is_string($signature) || $signature === '') { + throw new PaymentException('Missing webhook signature', 401); + } + + // Verify against the exact bytes the provider signed when the raw body + // is available; re-encoding the decoded array changes key order and + // escaping and would never match a real gateway signature. + $signed = $rawBody ?? $payload; + + if (!$this->validateSignature($signed, $signature)) { throw new PaymentException('Invalid webhook signature', 401); } @@ -60,10 +70,14 @@ public function handle(array $payload, ?string $signature = null): WebhookEvent * @param string $signature * @return bool */ - public function validateSignature(array $payload, string $signature): bool + public function validateSignature(string|array $signed, string $signature): bool { - $expectedSignature = hash_hmac('sha256', json_encode($payload), $this->secret); - + // Prefer the raw request body (string); fall back to canonical JSON for + // callers that only have the decoded array. + $message = is_array($signed) ? json_encode($signed) : $signed; + + $expectedSignature = hash_hmac('sha256', (string) $message, $this->secret); + return hash_equals($expectedSignature, $signature); } @@ -79,6 +93,7 @@ public static function parseRequest(): array return [ 'payload' => $data ?? [], + 'raw' => $body, 'signature' => $_SERVER['HTTP_X_SIGNATURE'] ?? $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? null, 'headers' => getallheaders(), ]; diff --git a/tests/WebhookHandlerTest.php b/tests/WebhookHandlerTest.php index 99f4ef8..21c7d17 100644 --- a/tests/WebhookHandlerTest.php +++ b/tests/WebhookHandlerTest.php @@ -26,13 +26,23 @@ public function testHandleValidWebhook() 'amount' => 1000, ]; - $event = $this->handler->handle($payload); - + $signature = hash_hmac('sha256', json_encode($payload), $this->secret); + + $event = $this->handler->handle($payload, $signature); + $this->assertInstanceOf(WebhookEvent::class, $event); $this->assertEquals('orange', $event->getProvider()); $this->assertEquals('TX-123', $event->getTransactionId()); } + public function testMissingSignatureIsRejected() + { + $this->expectException(PaymentException::class); + + // An unsigned webhook must be refused, not trusted. + $this->handler->handle(['event' => 'payment.success', 'status' => 'paid', 'amount' => 100000]); + } + public function testValidateSignature() { $payload = ['test' => 'data'];