-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleHMACAuthClient.php
293 lines (205 loc) · 6.83 KB
/
SimpleHMACAuthClient.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
/*
Client.php
Simple HMAC Auth
Jesse T Youngblood
11/27/18
*/
class SimpleHMACAuthClient {
public $host = 'localhost';
public $ssl = true;
public $port = 443;
public $algorithm = 'sha256';
private $apiKey;
private $secret;
public function __construct($apiKey, $secret) {
if (!isset($apiKey)) {
throw new AuthenticationException('Missing \'apiKey\'.');
}
if (!isset($secret)) {
// All requests will be sent unsigned.
}
$this->apiKey = $apiKey;
$this->secret = $secret;
}
private function sign($secret = '', $algorithm, $method = 'GET', $uri = '/', $queryString = '', $headers = array(), $data = null) {
$string = $this->stringForRequest($method, $uri, $queryString, $headers, $data);
$signature = hash_hmac($algorithm, $string, $secret);
//log($string);
//log($signature);
return $signature;
}
private function stringForRequest($method = 'GET', $uri = '/', $queryString = '', $headers = array(), $data = '') {
$method = strtoupper($method);
if ($data === null) {
$data = '';
}
// Only sign these headers, no more
$headersWhitelist = array(
'authorization',
'date',
'content-length',
'content-type'
);
// Create a new list of headers, with the keys all lower case. Do this before sorting them, to make sure we don't bork the sort.
$newHeaders = array();
foreach ($headers as $key => $value) {
if (array_search($key, $headersWhitelist) === false) {
continue;
}
if ($key === 'content-length' && $headers[$key] === '0') {
return;
}
$newHeaders[strtolower($key)] = trim($headers[$key]);
}
// Sort the array by key
ksort($newHeaders);
$headerString = '';
$count = 0;
foreach ($newHeaders as $key => $value) {
$headerString .= $key . ':' . trim($value);
$count++;
if ($count !== count($newHeaders)) {
$headerString .= "\n";
}
}
if ($data === null) {
$data = '';
}
$dataHash = hash('sha256', $data);
/*
The string format is:
method + \n
URL + \n
Alphabetically sorted query string with individually escaped keys and values + \n
Alphabetically sorted headers with lower case keys each on their own line
sha256 hash of data, or blank string if data is not included
*/
$string = '';
$string .= $method . "\n";
$string .= $uri . "\n";
$string .= $queryString . "\n";
$string .= $headerString . "\n";
$string .= $dataHash;
return $string;
}
public function call($method, $uri, $query = null, $body = null) {
$path = $uri;
$input = null;
if ($body !== null) {
try {
$input = json_encode($body);
} catch (Exception $e) {
throw new AuthenticationException('Could not serialize input data: ' . $e->getMessage());
}
if (function_exists('json_last_error') && json_last_error() !== JSON_ERROR_NONE) {
throw new AuthenticationException('Could not serialize input data: ' . json_last_error_msg());
}
}
$queryString = '';
if ($query !== null) {
$count = 0;
foreach ($query as $key => $value) {
if ($count !== 0) {
$queryString .= '&';
}
try {
$queryString .= rawurlencode($key) . '=' . rawurlencode(json_encode($value));
} catch (Exception $e) {
throw new AuthenticationException('Could not serialize input data: ' . $e->getMessage());
}
if (function_exists('json_last_error') && json_last_error() !== JSON_ERROR_NONE) {
throw new AuthenticationException('Could not serialize parameter: ' . $key . ': ' . json_last_error_msg());
}
$count++;
}
}
$headers = array(
'date' => gmdate('D, d M Y H:i:s T'),
'authorization' => 'api-key ' . $this->apiKey
);
if ($input !== null) {
$headers['content-type'] = 'application/json';
$headers['content-length'] = strlen($input);
}
if ($this->secret) {
$signature = $this->sign($this->secret, $this->algorithm, $method, $path, $queryString, $headers, $input);
$headers['signature'] = 'simple-hmac-auth ' . $this->algorithm . ' ' . $signature;
}
$http = 'https';
if ($this->ssl === false) {
$http = 'http';
}
$url = $http . '://' . $this->host . ':' . $this->port . $path;
if ($queryString !== '') {
$url .= '?' . $queryString;
}
$headersArray = array();
foreach ($headers as $key => $value) {
array_push($headersArray, $key . ':' . $value);
}
$ch = curl_init();
if ($input !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 7.5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headersArray);
//log('Making request: ' . $method . ' ' . $url . ' Headers: "' . json_encode($headersArray) . '" and data: "' . $input . '"');
$data = curl_exec($ch);
$errorNumber = curl_errno($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error || $errorNumber) {
$message = 'Error while communicating with server';
if ($error) {
$message .= ': ' . $error;
}
if ($errorNumber) {
$message .= ' (' . $errorNumber . ')';
}
throw new AuthenticationException($message);
}
// Parse the response
$error = null;
$code = null;
$object = null;
try {
$object = json_decode($data, true);
} catch (Exception $e) {
throw new AuthenticationException('Error interpreting server response: ' . $e->getMessage() . ': "' . $data . '"');
}
if (function_exists('json_last_error') && json_last_error()) {
$error = 'Error interpreting server response: ' . json_last_error_msg() . ': "' . $data . '"';
} else if (isset($object['error'])) {
if (isset($object['error']['message'])) {
$error = $object['error']['message'];
}
if (isset($object['error']['code'])) {
$code = $object['error']['code'];
}
}
if ($httpCode !== 200 && $error) {
throw new AuthenticationException($error, $code);
} else if ($httpCode !== 200) {
throw new AuthenticationException('An error has occured', $httpCode);
}
return $object;
}
}
// Exception codes can be strings as well as numbers
class AuthenticationException extends Exception {
public $code = null;
public $message = '';
public function __construct($message, $code = null) {
parent::__construct($message);
if ($code !== null) {
$this->code = $code;
}
}
}
?>