-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
83 lines (67 loc) · 2.62 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
// Fetch the signing secret from the environment
$secret = getenv('CONTENTFUL_SIGNING_SECRET');
function fetchAllHeaders() {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($name, 5)))))] = $value;
}
}
// Add Content-Type if it is not prefixed with 'HTTP_'
if (isset($_SERVER['CONTENT_TYPE'])) {
$headers['Content-Type'] = $_SERVER['CONTENT_TYPE'];
}
return $headers;
}
// Verify the request
function verifyRequest($secret, $method, $path, $headers, $body) {
$signature = $headers['X-Contentful-Signature'] ?? null;
$signedHeaders = isset($headers['X-Contentful-Signed-Headers']) ? explode(',', $headers['X-Contentful-Signed-Headers']) : [];
if (!$signature || empty($signedHeaders)) {
error_log("Missing required headers.");
return false;
}
// Build the canonical string
$canonicalString = buildCanonicalString($method, $path, $headers, $signedHeaders, $body);
// Generate the signature
$generatedSignature = calculateSignature($secret, $canonicalString);
return hash_equals($generatedSignature, $signature);
}
// Build the canonical string
function buildCanonicalString($method, $path, $headers, $signedHeaders, $body) {
$headersString = [];
foreach ($signedHeaders as $header) {
$headerKey = strtolower(trim($header));
$headerValue = '';
// Check if the header exists in any case format
foreach ($headers as $key => $value) {
if (strtolower($key) === $headerKey) {
$headerValue = $value;
break;
}
}
$headersString[] = "$headerKey:" . trim($headerValue);
}
$headersString = implode(';', $headersString);
return "$method\n$path\n$headersString\n$body";
}
// Calculate the HMAC SHA256 signature
function calculateSignature($secret, $canonicalString) {
return hash_hmac('sha256', $canonicalString, $secret);
}
// Handle the POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];
$body = file_get_contents('php://input');
$headers = fetchAllHeaders();
if (verifyRequest($secret, $method, $path, $headers, $body)) {
header('Content-Type: application/json');
echo json_encode(['message' => 'Hello, World!']);
} else {
header('HTTP/1.1 403 Forbidden');
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid signature']);
}
}