diff --git a/MuxPhp/Utils/Webhooks.php b/MuxPhp/Utils/Webhooks.php new file mode 100644 index 0000000..8666997 --- /dev/null +++ b/MuxPhp/Utils/Webhooks.php @@ -0,0 +1,35 @@ +getRequestBody(); + + // Build a HMAC hash using SHA256 algo, using our webhook secret + $ourSignature = hash_hmac('sha256', $payload, $_ENV['MUX_WEBHOOK_SECRET']); + + // `hash_equals` performs a timing-safe crypto comparison + return hash_equals($ourSignature, $muxHash); + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist index d8fe4df..6ff36a6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,23 +1,18 @@ - - - - ./test/Api - ./test/Model - - - - - ./MuxPhp/Api - ./MuxPhp/Models - - - - - + + + + ./MuxPhp/Api + ./MuxPhp/Models + ./MuxPhp/Utils + + + + + ./test/Utils + + + + + diff --git a/phpunit.xml.dist.bak b/phpunit.xml.dist.bak new file mode 100644 index 0000000..0f7c95b --- /dev/null +++ b/phpunit.xml.dist.bak @@ -0,0 +1,23 @@ + + + + + ./test/Utils + + + + + ./MuxPhp/Api + ./MuxPhp/Models + ./MuxPhp/Utils + + + + + + diff --git a/test/Utils/WebhooksTest.php b/test/Utils/WebhooksTest.php new file mode 100644 index 0000000..dfe7f04 --- /dev/null +++ b/test/Utils/WebhooksTest.php @@ -0,0 +1,54 @@ +assertFalse( + self::$webhooks->isValidSignature('invalid') + ); + } + + public function testSignatureInvalidOnMalformedSignature(): void + { + $this->assertFalse( + self::$webhooks->isValidSignature('invalid,32u4') + ); + } + + public function testSignatureValid(): void + { + $body = json_encode(['hello' => 'world']); + + // Create a stub for the Webhooks class. + $stub = $this->getMockBuilder(MuxPhp\Utils\Webhooks::class) + ->disableOriginalConstructor() + ->setMethods(['getRequestBody']) + ->getMock(); + + // Configure the stub. + $stub->method('getRequestBody')->willReturn($body); + + $time = time(); + $payload = $time . "." . $body; + $signature = hash_hmac('sha256', $payload, $_ENV['MUX_WEBHOOK_SECRET']); + $hash = "t=$time,v1=$signature"; + + $this->assertTrue( + $stub->isValidSignature($hash) + ); + } +} \ No newline at end of file