Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement helper for webhook signature verification #53

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
35 changes: 35 additions & 0 deletions MuxPhp/Utils/Webhooks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace MuxPhp\Utils;

class Webhooks
{
public function getRequestBody()
{
return file_get_contents('php://input');
}

public function isValidSignature(string $signature = '') : bool {
// Split the signature based on ','.
// Format is 't=[timestamp],v1=[hash]'
$muxSigArray = explode(',', $signature);

// Make sure we have at least 2 items in the array.
if(empty($muxSigArray) || empty($muxSigArray[0]) || empty($muxSigArray[1])) {
return false;
}

// Strip the first occurence of 't=' and 'v1=' from both strings
$muxTimestamp = preg_replace('/t=/', '', $muxSigArray[0], 1);
$muxHash = preg_replace('/v1=/', '', $muxSigArray[1], 1);

// Create a payload of the timestamp from the Mux signature and the request body with a '.' in-between
$payload = $muxTimestamp . "." . $this->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);
}
}
37 changes: 16 additions & 21 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="tests">
<directory>./test/Api</directory>
<directory>./test/Model</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./MuxPhp/Api</directory>
<directory suffix=".php">./MuxPhp/Models</directory>
</whitelist>
</filter>
<php>
<ini name="error_reporting" value="E_ALL" />
</php>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="./vendor/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./MuxPhp/Api</directory>
<directory suffix=".php">./MuxPhp/Models</directory>
<directory suffix=".php">./MuxPhp/Utils</directory>
</include>
</coverage>
<testsuites>
<testsuite name="tests">
<directory>./test/Utils</directory>
</testsuite>
</testsuites>
<php>
<ini name="error_reporting" value="E_ALL"/>
</php>
</phpunit>
23 changes: 23 additions & 0 deletions phpunit.xml.dist.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="tests">
<directory>./test/Utils</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./MuxPhp/Api</directory>
<directory suffix=".php">./MuxPhp/Models</directory>
<directory suffix=".php">./MuxPhp/Utils</directory>
</whitelist>
</filter>
<php>
<ini name="error_reporting" value="E_ALL" />
</php>
</phpunit>
54 changes: 54 additions & 0 deletions test/Utils/WebhooksTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class WebhooksTest extends TestCase
{
public static $webhooks;

/**
* @beforeClass
*/
public static function setUpSomeSharedFixtures(): void
{
$secret = 'abc';
$_ENV['MUX_WEBHOOK_SECRET'] = $secret;
self::$webhooks = new MuxPhp\Utils\Webhooks;
}

public function testSignatureInvalidInvalidSignature(): void
{
$this->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)
);
}
}