Skip to content

Commit

Permalink
Merge pull request cronofy#108 from cronofy/hmac-validation
Browse files Browse the repository at this point in the history
HMAC validation added
  • Loading branch information
Grajo authored Jul 1, 2021
2 parents 89d621d + 3a61acf commit 223bfe2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Cronofy.php
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,30 @@ public function executeBatch(Batch $batch): BatchResult
return $result;
}

public function hmacValid($hmac_header, $body)
{
/* Verifies a HMAC from a push notification using the client secret.
String hmac_header: A String containing comma-separated values
describing HMACs of the notification taken from the Cronofy-HMAC-SHA256 header.
String body: A String of the body of the notification.
Returns true if one of the HMAC provided matches the one calculated using the
client secret, otherwise false.
*/

if ($hmac_header == null || empty($hmac_header)) {
return false;
}

$digest = hash_hmac('sha256', $body, $this->clientSecret);
$calculated = base64_encode($digest);
$hmac_list = explode(',', $hmac_header);

return in_array($calculated, $hmac_list);
}

private function convertBatchRequestsToArray(BatchRequest ...$requests): array
{
$requestMapper = function (BatchRequest $request) {
Expand Down
31 changes: 31 additions & 0 deletions tests/CronofyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -708,4 +708,35 @@ public function testDeleteAvailablePeriod()
]);
$this->assertNotNull($actual);
}

public function testHmacValidation()
{
$cronofy = new Cronofy([
"client_id" => "clientId",
"client_secret" => "clientSecret",
"access_token" => "accessToken",
"refresh_token" => "refreshToken",
"http_client" => null,
]);

$body = '{"example":"well-known"}';

$actual = $cronofy->hmacValid("NDJlMWE1YzcxYjJjMzQzNmIxNTIzNzdhNDU4ZTMwYzQ2N2ZlZTRhMGViOWE4NmNjOWEzOTA2NDBmYjQxZGQ2NA==", $body);
$this->assertTrue($actual);

$actual = $cronofy->hmacValid("something-else", $body);
$this->assertFalse($actual);

$actual = $cronofy->hmacValid("something-else,NDJlMWE1YzcxYjJjMzQzNmIxNTIzNzdhNDU4ZTMwYzQ2N2ZlZTRhMGViOWE4NmNjOWEzOTA2NDBmYjQxZGQ2NA==,something-else2", $body);
$this->assertTrue($actual);

$actual = $cronofy->hmacValid("something-else,something-else2", $body);
$this->assertFalse($actual);

$actual = $cronofy->hmacValid(null, $body);
$this->assertFalse($actual);

$actual = $cronofy->hmacValid("", $body);
$this->assertFalse($actual);
}
}

0 comments on commit 223bfe2

Please sign in to comment.