forked from ovh/php-ovh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiTest.php
465 lines (392 loc) · 17.8 KB
/
ApiTest.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
# Copyright (c) 2013-2017, OVH SAS.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of OVH SAS nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Ovh\tests;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use Ovh\Api;
use Ovh\Exceptions\InvalidParameterException;
use PHPUnit\Framework\TestCase;
# Mock values
const MOCK_APPLICATION_KEY = "TDPKJdwZwAQPwKX2";
const MOCK_APPLICATION_SECRET = "9ufkBmLaTQ9nz5yMUlg79taH0GNnzDjk";
const MOCK_CONSUMER_KEY = "5mBuy6SUQcRw2ZUxg0cG68BoDKpED4KY";
const MOCK_TIME = '1457018875';
class MockClient extends Client
{
public $calls = [];
public function __construct(...$responses)
{
$mock = new MockHandler($responses);
$history = Middleware::history($this->calls);
$handlerStack = HandlerStack::create($mock);
$handlerStack->push($history);
parent::__construct(['handler' => $handlerStack]);
}
}
/**
* Test Api class
*
* @package Ovh
* @category Ovh
*/
class ApiTest extends TestCase
{
/**
* Get private and protected property to unit test it
*
* @param string $name
*
* @return \ReflectionProperty
*/
protected static function getPrivateProperty($name)
{
$class = new \ReflectionClass('Ovh\Api');
$property = $class->getProperty($name);
$property->setAccessible(true);
return $property;
}
/**
* Test missing $application_key
*/
public function testMissingApplicationKey()
{
$this->expectException(InvalidParameterException::class);
$this->expectExceptionMessage('Application key parameter is empty');
$api = new Api(null, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, new MockClient());
$api->get('/me');
}
/**
* Test missing $application_secret
*/
public function testMissingApplicationSecret()
{
$this->expectException(InvalidParameterException::class);
$this->expectExceptionMessage('Application secret parameter is empty');
$api = new Api(MOCK_APPLICATION_KEY, null, 'ovh-eu', MOCK_CONSUMER_KEY, new MockClient());
$api->get('/me');
}
/**
* Test we don't check Application Key for unauthenticated call
*/
public function testNoCheckAppKeyForUnauthCall()
{
$client = new MockClient(new Response(200, [], '{}'));
$api = new Api(null, null, 'ovh-eu', null, $client);
$api->get("/me", null, null, false);
$calls = $client->calls;
$this->assertCount(1, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/me', $req->getUri()->__toString());
$this->assertSame('', $req->getHeaderLine('X-Ovh-Application'));
}
/**
* Test missing $api_endpoint
*/
public function testMissingApiEndpoint()
{
$this->expectException(InvalidParameterException::class);
$this->expectExceptionMessage('Endpoint parameter is empty');
new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, null, MOCK_CONSUMER_KEY, new MockClient());
}
/**
* Test bad $api_endpoint
*/
public function testBadApiEndpoint()
{
$this->expectException(InvalidParameterException::class);
$this->expectExceptionMessage('Unknown provided endpoint');
new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'i_am_invalid', MOCK_CONSUMER_KEY, new MockClient());
}
/**
* Test creating Client if none is provided
*/
public function testClientCreation()
{
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY);
$this->assertInstanceOf('\\GuzzleHttp\\Client', $api->getHttpClient());
}
/**
* Test the compute of time delta
*/
public function testTimeDeltaCompute()
{
$client = new MockClient(
new Response(200, [], time() - 10),
new Response(200, [], '{}'),
);
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get("/me");
$property = self::getPrivateProperty('time_delta');
$time_delta = $property->getValue($api);
$this->assertSame('-10', $time_delta);
$calls = $client->calls;
$this->assertCount(2, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/time', $req->getUri()->__toString());
$req = $calls[1]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/me', $req->getUri()->__toString());
}
/**
* Test if consumer key is replaced
*/
public function testIfConsumerKeyIsReplace()
{
$client = new MockClient(
new Response(200, [], MOCK_TIME),
new Response(
200,
['Content-Type' => 'application/json; charset=utf-8'],
'{"validationUrl":"https://api.ovh.com/login/?credentialToken=token","consumerKey":"consumer_remote","state":"pendingValidation"}'
),
);
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$this->assertNotEquals('consumer_remote', $api->getConsumerKey());
$credentials = $api->requestCredentials(['method' => 'GET', 'path' => '/*']);
$this->assertSame('consumer_remote', $api->getConsumerKey());
$calls = $client->calls;
$this->assertCount(2, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/time', $req->getUri()->__toString());
$req = $calls[1]['request'];
$this->assertSame('POST', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/credential', $req->getUri()->__toString());
}
/**
* Test invalid applicationKey
*/
public function testInvalidApplicationKey()
{
$error = '{"class":"Client::Forbidden","message":"Invalid application key"}';
$this->expectException(ClientException::class);
$this->expectExceptionCode(403);
$this->expectExceptionMessage($error);
$client = new MockClient(new Response(403, ['Content-Type' => 'application/json; charset=utf-8'], $error));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->requestCredentials(['method' => 'GET', 'path' => '/*']);
}
/**
* Test invalid rights
*/
public function testInvalidRight()
{
$error = '{"message": "Invalid credentials"}';
$this->expectException(ClientException::class);
$this->expectExceptionCode(403);
$this->expectExceptionMessage($error);
$client = new MockClient(new Response(403, ['Content-Type' => 'application/json; charset=utf-8'], $error));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get('/me', null, null, false);
}
public function testGetConsumerKey()
{
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY);
$this->assertSame(MOCK_CONSUMER_KEY, $api->getConsumerKey());
}
/**
* Test GET query args
*/
public function testGetQueryArgs()
{
$client = new MockClient(new Response(200, [], '{}'));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get('/me/api/credential?applicationId=49', ['status' => 'pendingValidation'], null, false);
$calls = $client->calls;
$this->assertCount(1, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/me/api/credential?applicationId=49&status=pendingValidation', $req->getUri()->__toString());
}
/**
* Test GET overlapping query args
*/
public function testGetOverlappingQueryArgs()
{
$client = new MockClient(new Response(200, [], '{}'));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get('/me/api/credential?applicationId=49&status=pendingValidation', ['status' => 'expired', 'test' => "success"], null, false);
$calls = $client->calls;
$this->assertCount(1, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/me/api/credential?applicationId=49&status=expired&test=success', $req->getUri()->__toString());
}
/**
* Test GET boolean query args
*/
public function testGetBooleanQueryArgs()
{
$client = new MockClient(new Response(200, [], '{}'));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get('/me/api/credential', ['dryRun' => true, 'notDryRun' => false], null, false);
$calls = $client->calls;
$this->assertCount(1, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/me/api/credential?dryRun=true¬DryRun=false', $req->getUri()->__toString());
}
/**
* Test valid provided endpoint
*/
public function testProvidedUrl()
{
foreach ([
['endpoint' => 'http://api.ovh.com/1.0', 'expectedUrl' => 'http://api.ovh.com/1.0'],
['endpoint' => 'https://api.ovh.com/1.0', 'expectedUrl' => 'https://api.ovh.com/1.0'],
['endpoint' => 'ovh-eu', 'expectedUrl' => 'https://eu.api.ovh.com/1.0'],
] as $test) {
$client = new MockClient(new Response(200, [], '{}'));
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, $test['endpoint'], MOCK_CONSUMER_KEY, $client);
$api->get('/me/api/credential', null, null, false);
$calls = $client->calls;
$this->assertCount(1, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame($test['expectedUrl'] . '/me/api/credential', $req->getUri()->__toString());
}
}
/**
* Test missing header X-OVH-Application on requestCredentials
*/
public function testMissingOvhApplicationHeaderOnRequestCredentials()
{
$client = new MockClient(
new Response(200, [], MOCK_TIME),
new Response(200, [], '{"validationUrl":"https://api.ovh.com/login/?credentialToken=token","consumerKey":"consumer_remote","state":"pendingValidation"}'),
);
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->requestCredentials([]);
$calls = $client->calls;
$this->assertCount(2, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/time', $req->getUri()->__toString());
$req = $calls[1]['request'];
$this->assertSame('POST', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/credential', $req->getUri()->__toString());
$this->assertSame(MOCK_APPLICATION_KEY, $req->getHeaderLine('X-Ovh-Application'));
$this->assertSame(MOCK_CONSUMER_KEY, $req->getHeaderLine('X-Ovh-Consumer'));
$this->assertSame(MOCK_TIME, $req->getHeaderLine('X-Ovh-Timestamp'));
}
public function testCallSignature()
{
// GET /auth/time
$mocks = [new Response(200, [], MOCK_TIME)];
// (GET,POST,PUT,DELETE) x (/auth,/unauth)
for ($i = 0; $i < 8; $i++) {
$mocks[] = new Response(200, [], '{}');
}
$client = new MockClient(...$mocks);
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$body = ["a" => "b", "c" => "d"];
// Authenticated calls
$api->get('/auth');
$api->post('/auth', $body);
$api->put('/auth', $body);
$api->delete('/auth');
// Unauth calls
$api->get('/unauth', null, null, false);
$api->post('/unauth', $body, null, false);
$api->put('/unauth', $body, null, false);
$api->delete('/unauth', null, null, false);
$calls = $client->calls;
$this->assertCount(9, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/time', $req->getUri()->__toString());
foreach ([
1 => ['method' => 'GET', 'sig' => '$1$e9556054b6309771395efa467c22e627407461ad'],
2 => ['method' => 'POST', 'sig' => '$1$ec2fb5c7a81f64723c77d2e5b609ae6f58a84fc1'],
3 => ['method' => 'PUT', 'sig' => '$1$8a75a9e7c8e7296c9dbeda6a2a735eb6bd58ec4b'],
4 => ['method' => 'DELETE', 'sig' => '$1$a1eecd00b3b02b6cf5708b84b9ff42059a950d85'],
] as $i => $test) {
$req = $calls[$i]['request'];
$this->assertSame($test['method'], $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth', $req->getUri()->__toString());
$this->assertSame(MOCK_APPLICATION_KEY, $req->getHeaderLine('X-Ovh-Application'));
$this->assertSame(MOCK_CONSUMER_KEY, $req->getHeaderLine('X-Ovh-Consumer'));
$this->assertSame(MOCK_TIME, $req->getHeaderLine('X-Ovh-Timestamp'));
$this->assertSame($test['sig'], $req->getHeaderLine('X-Ovh-Signature'));
if ($test['method'] == 'POST' || $test['method'] == 'PUT') {
$this->assertSame('application/json; charset=utf-8', $req->getHeaderLine('Content-Type'));
}
}
foreach (['GET', 'POST', 'PUT', 'DELETE'] as $i => $method) {
$req = $calls[$i + 5]['request'];
$this->assertSame($method, $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/unauth', $req->getUri()->__toString());
$this->assertSame(MOCK_APPLICATION_KEY, $req->getHeaderLine('X-Ovh-Application'));
$this->assertNotTrue($req->hasHeader('X-Ovh-Consumer'));
$this->assertNotTrue($req->hasHeader('X-Ovh-Timestamp'));
$this->assertNotTrue($req->hasHeader('X-Ovh-Signature'));
if ($method == 'POST' || $method == 'PUT') {
$this->assertSame('application/json; charset=utf-8', $req->getHeaderLine('Content-Type'));
}
}
}
public function testVersionInUrl()
{
// GET /auth/time
$mocks = [new Response(200, [], MOCK_TIME)];
// GET) x (/1.0/call,/v1/call,/v2/call)
for ($i = 0; $i < 3; $i++) {
$mocks[] = new Response(200, [], '{}');
}
$client = new MockClient(...$mocks);
$api = new Api(MOCK_APPLICATION_KEY, MOCK_APPLICATION_SECRET, 'ovh-eu', MOCK_CONSUMER_KEY, $client);
$api->get('/call');
$api->get('/v1/call');
$api->get('/v2/call');
$calls = $client->calls;
$this->assertCount(4, $calls);
$req = $calls[0]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/1.0/auth/time', $req->getUri()->__toString());
foreach ([
1 => ['path' => '1.0/call', 'sig' => '$1$7f2db49253edfc41891023fcd1a54cf61db05fbb'],
2 => ['path' => 'v1/call', 'sig' => '$1$e6e7906d385eb28adcbfbe6b66c1528a42d741ad'],
3 => ['path' => 'v2/call', 'sig' => '$1$bb63b132a6f84ad5433d0c534d48d3f7c3804285'],
] as $i => $test) {
$req = $calls[$i]['request'];
$this->assertSame('GET', $req->getMethod());
$this->assertSame('https://eu.api.ovh.com/' . $test['path'], $req->getUri()->__toString());
$this->assertSame(MOCK_APPLICATION_KEY, $req->getHeaderLine('X-Ovh-Application'));
$this->assertSame(MOCK_CONSUMER_KEY, $req->getHeaderLine('X-Ovh-Consumer'));
$this->assertSame(MOCK_TIME, $req->getHeaderLine('X-Ovh-Timestamp'));
$this->assertSame($test['sig'], $req->getHeaderLine('X-Ovh-Signature'));
}
}
}