/var/www/hkosl.com/littleark/webadmin/libraies/google/apiclient/tests/Google/ClientTest.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
<?php
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

use GuzzleHttp\Client;
use 
GuzzleHttp\Event\RequestEvents;
use 
Psr\Http\Message\Request;

class 
Google_ClientTest extends BaseTest
{
  public function 
testClientConstructor()
  {
    
$this->assertInstanceOf('Google_Client'$this->getClient());
  }

  public function 
testSignAppKey()
  {
    
$client $this->getClient();
    
$client->setDeveloperKey('devKey');

    
$http = new Client();
    
$client->authorize($http);

    
$this->checkAuthHandler($http'Simple');
  }

  private function 
checkAuthHandler($http$className)
  {
    if (
$this->isGuzzle6()) {
      
$stack $http->getConfig('handler');
      
$class = new ReflectionClass(get_class($stack));
      
$property $class->getProperty('stack');
      
$property->setAccessible(true);
      
$middlewares $property->getValue($stack);
      
$middleware array_pop($middlewares);

      if (
is_null($className)) {
        
// only the default middlewares have been added
        
$this->assertEquals(3count($middlewares));
      } else {
        
$authClass sprintf('Google\Auth\Middleware\%sMiddleware'$className);
        
$this->assertInstanceOf($authClass$middleware[0]);
      }
    } else {
      
$listeners $http->getEmitter()->listeners('before');

      if (
is_null($className)) {
        
$this->assertEquals(0count($listeners));
      } else {
        
$authClass sprintf('Google\Auth\Subscriber\%sSubscriber'$className);
        
$this->assertEquals(1count($listeners));
        
$this->assertEquals(2count($listeners[0]));
        
$this->assertInstanceOf($authClass$listeners[0][0]);
      }
    }
  }

  private function 
checkCredentials($http$fetcherClass$sub null)
  {
    if (
$this->isGuzzle6()) {
      
$stack $http->getConfig('handler');
      
$class = new ReflectionClass(get_class($stack));
      
$property $class->getProperty('stack');
      
$property->setAccessible(true);
      
$middlewares $property->getValue($stack); // Works
      
$middleware array_pop($middlewares);
      
$auth $middleware[0];
    } else {
      
// access the protected $fetcher property
      
$listeners $http->getEmitter()->listeners('before');
      
$auth $listeners[0][0];
    }

    
$class = new ReflectionClass(get_class($auth));
    
$property $class->getProperty('fetcher');
    
$property->setAccessible(true);
    
$cacheFetcher $property->getValue($auth);
    
$this->assertInstanceOf('Google\Auth\FetchAuthTokenCache'$cacheFetcher);

    
$class = new ReflectionClass(get_class($cacheFetcher));
    
$property $class->getProperty('fetcher');
    
$property->setAccessible(true);
    
$fetcher $property->getValue($cacheFetcher);
    
$this->assertInstanceOf($fetcherClass$fetcher);

    if (
$sub) {
      
// access the protected $auth property
      
$class = new ReflectionClass(get_class($fetcher));
      
$property $class->getProperty('auth');
      
$property->setAccessible(true);
      
$auth $property->getValue($fetcher);

      
$this->assertEquals($sub$auth->getSub());
    }
  }

  public function 
testSignAccessToken()
  {
    
$client $this->getClient();

    
$http = new Client();
    
$client->setAccessToken([
      
'access_token' => 'test_token',
      
'expires_in'   => 3600,
      
'created'      => time(),
    ]);
    
$client->setScopes('test_scope');
    
$client->authorize($http);

    
$this->checkAuthHandler($http'ScopedAccessToken');
  }

  public function 
testCreateAuthUrl()
  {
    
$client $this->getClient();

    
$client->setClientId('clientId1');
    
$client->setClientSecret('clientSecret1');
    
$client->setRedirectUri('http://localhost');
    
$client->setDeveloperKey('devKey');
    
$client->setState('xyz');
    
$client->setAccessType('offline');
    
$client->setApprovalPrompt('force');
    
$client->setRequestVisibleActions('http://foo');
    
$client->setLoginHint('bob@example.org');

    
$authUrl $client->createAuthUrl("http://googleapis.com/scope/foo");
    
$expected "https://accounts.google.com/o/oauth2/auth"
        
"?response_type=code"
        
"&access_type=offline"
        
"&client_id=clientId1"
        
"&redirect_uri=http%3A%2F%2Flocalhost"
        
"&state=xyz"
        
"&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo"
        
"&approval_prompt=force"
        
"&login_hint=bob%40example.org";

    
$this->assertEquals($expected$authUrl);

    
// Again with a blank login hint (should remove all traces from authUrl)
    
$client->setLoginHint('');
    
$client->setHostedDomain('example.com');
    
$client->setOpenIdRealm('example.com');
    
$client->setPrompt('select_account');
    
$client->setIncludeGrantedScopes(true);
    
$authUrl $client->createAuthUrl("http://googleapis.com/scope/foo");
    
$expected "https://accounts.google.com/o/oauth2/auth"
        
"?response_type=code"
        
"&access_type=offline"
        
"&client_id=clientId1"
        
"&redirect_uri=http%3A%2F%2Flocalhost"
        
"&state=xyz"
        
"&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo"
        
"&hd=example.com"
        
"&include_granted_scopes=true"
        
"&openid.realm=example.com"
        
"&prompt=select_account";

    
$this->assertEquals($expected$authUrl);
  }

  public function 
testPrepareNoScopes()
  {
    
$client = new Google_Client();

    
$scopes $client->prepareScopes();
    
$this->assertEquals(null$scopes);
  }

  public function 
testNoAuthIsNull()
  {
    
$client = new Google_Client();

    
$this->assertNull($client->getAccessToken());
  }

  public function 
testPrepareService()
  {
    
$client = new Google_Client();
    
$client->setScopes(array("scope1""scope2"));
    
$scopes $client->prepareScopes();
    
$this->assertEquals("scope1 scope2"$scopes);

    
$client->setScopes(array("""scope2"));
    
$scopes $client->prepareScopes();
    
$this->assertEquals(" scope2"$scopes);

    
$client->setScopes("scope2");
    
$client->addScope("scope3");
    
$client->addScope(array("scope4""scope5"));
    
$scopes $client->prepareScopes();
    
$this->assertEquals("scope2 scope3 scope4 scope5"$scopes);

    
$client->setClientId('test1');
    
$client->setRedirectUri('http://localhost/');
    
$client->setState('xyz');
    
$client->setScopes(array("http://test.com""scope2"));
    
$scopes $client->prepareScopes();
    
$this->assertEquals("http://test.com scope2"$scopes);
    
$this->assertEquals(
        
''
        
'https://accounts.google.com/o/oauth2/auth'
        
'?response_type=code'
        
'&access_type=online'
        
'&client_id=test1'
        
'&redirect_uri=http%3A%2F%2Flocalhost%2F'
        
'&state=xyz'
        
'&scope=http%3A%2F%2Ftest.com%20scope2'
        
'&approval_prompt=auto',

        
$client->createAuthUrl()
    );

    
$response $this->getMock('Psr\Http\Message\ResponseInterface');
    
$response->expects($this->once())
      ->
method('getBody')
      ->
will($this->returnValue($this->getMock('Psr\Http\Message\StreamInterface')));
    
$http $this->getMock('GuzzleHttp\ClientInterface');
    
$http->expects($this->once())
      ->
method('send')
      ->
will($this->returnValue($response));

    if (
$this->isGuzzle5()) {
      
$guzzle5Request = new GuzzleHttp\Message\Request('POST''/');
      
$http->expects($this->once())
        ->
method('createRequest')
        ->
will($this->returnValue($guzzle5Request));
    }


    
$client->setHttpClient($http);
    
$dr_service = new Google_Service_Drive($client);
    
$this->assertInstanceOf('Google_Model'$dr_service->files->listFiles());
  }

  public function 
testDefaultLogger()
  {
    
$client = new Google_Client();
    
$logger $client->getLogger();
    
$this->assertInstanceOf('Monolog\Logger'$logger);
    
$handler $logger->popHandler();
    
$this->assertInstanceOf('Monolog\Handler\StreamHandler'$handler);
  }

  public function 
testDefaultLoggerAppEngine()
  {
    
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
    
$client = new Google_Client();
    
$logger $client->getLogger();
    
$handler $logger->popHandler();
    unset(
$_SERVER['SERVER_SOFTWARE']);

    
$this->assertInstanceOf('Monolog\Logger'$logger);
    
$this->assertInstanceOf('Monolog\Handler\SyslogHandler'$handler);
  }

  public function 
testSettersGetters()
  {
    
$client = new Google_Client();
    
$client->setClientId("client1");
    
$client->setClientSecret('client1secret');
    
$client->setState('1');
    
$client->setApprovalPrompt('force');
    
$client->setAccessType('offline');

    
$client->setRedirectUri('localhost');
    
$client->setConfig('application_name''me');
    
$client->setCache($this->getMock('Psr\Cache\CacheItemPoolInterface'));
    
$this->assertEquals('object'gettype($client->getCache()));

    try {
      
$client->setAccessToken(null);
      
$this->fail('Should have thrown an Exception.');
    } catch (
InvalidArgumentException $e) {
      
$this->assertEquals('invalid json token'$e->getMessage());
    }

    
$token = array('access_token' => 'token');
    
$client->setAccessToken($token);
    
$this->assertEquals($token$client->getAccessToken());
  }

  public function 
testAppEngineStreamHandlerConfig()
  {
    
$this->onlyGuzzle5();

    
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
    
$client = new Google_Client();

    
// check Stream Handler is used
    
$http $client->getHttpClient();
    
$class = new ReflectionClass(get_class($http));
    
$property $class->getProperty('fsm');
    
$property->setAccessible(true);
    
$fsm $property->getValue($http);

    
$class = new ReflectionClass(get_class($fsm));
    
$property $class->getProperty('handler');
    
$property->setAccessible(true);
    
$handler $property->getValue($fsm);

    
$this->assertInstanceOf('GuzzleHttp\Ring\Client\StreamHandler'$handler);

    unset(
$_SERVER['SERVER_SOFTWARE']);
  }

  public function 
testAppEngineVerifyConfig()
  {
    
$this->onlyGuzzle5();

    
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
    
$client = new Google_Client();

    
$this->assertEquals(
      
'/etc/ca-certificates.crt',
      
$client->getHttpClient()->getDefaultOption('verify')
    );

    unset(
$_SERVER['SERVER_SOFTWARE']);
  }

  public function 
testJsonConfig()
  {
    
// Device config
    
$client = new Google_Client();
    
$device =
    
'{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"'.
    
':"N0aHCBT1qX1VAcF5J1pJAn6S","token_uri":"https://accounts.google.com/o/oauth2/token",'.
    
'"client_email":"","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url"'.
    
':"","client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":'.
    
'"https://www.googleapis.com/oauth2/v1/certs"}}';
    
$dObj json_decode($devicetrue);
    
$client->setAuthConfig($dObj);
    
$this->assertEquals($client->getClientId(), $dObj['installed']['client_id']);
    
$this->assertEquals($client->getClientSecret(), $dObj['installed']['client_secret']);
    
$this->assertEquals($client->getRedirectUri(), $dObj['installed']['redirect_uris'][0]);

    
// Web config
    
$client = new Google_Client();
    
$web '{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' .
      
':"lpoubuib8bj-Fmke_YhhyHGgXc","token_uri":"https://accounts.google.com/o/oauth2/token"' .
      
',"client_email":"123456789@developer.gserviceaccount.com","client_x509_cert_url":'.
      
'"https://www.googleapis.com/robot/v1/metadata/x509/123456789@developer.gserviceaccount.com"'.
      
',"client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":'.
      
'"https://www.googleapis.com/oauth2/v1/certs"}}';
    
$wObj json_decode($webtrue);
    
$client->setAuthConfig($wObj);
    
$this->assertEquals($client->getClientId(), $wObj['web']['client_id']);
    
$this->assertEquals($client->getClientSecret(), $wObj['web']['client_secret']);
    
$this->assertEquals($client->getRedirectUri(), '');
  }

  public function 
testIniConfig()
  {
    
$config parse_ini_file($this->testDir "/config/test.ini");
    
$client = new Google_Client($config);

    
$this->assertEquals('My Test application'$client->getConfig('application_name'));
    
$this->assertEquals(
        
'gjfiwnGinpena3',
        
$client->getClientSecret()
    );
  }

  public function 
testNoAuth()
  {
    
/** @var $noAuth Google_Auth_Simple */
    
$client = new Google_Client();
    
$client->setDeveloperKey(null);

    
// unset application credentials
    
$GOOGLE_APPLICATION_CREDENTIALS getenv('GOOGLE_APPLICATION_CREDENTIALS');
    
$HOME getenv('HOME');
    
putenv('GOOGLE_APPLICATION_CREDENTIALS=');
    
putenv('HOME='.sys_get_temp_dir());
    
$http = new Client();
    
$client->authorize($http);

    
putenv("GOOGLE_APPLICATION_CREDENTIALS=$GOOGLE_APPLICATION_CREDENTIALS");
    
putenv("HOME=$HOME");
    
$this->checkAuthHandler($httpnull);
  }

  public function 
testApplicationDefaultCredentials()
  {
    
$this->checkServiceAccountCredentials();
    
$credentialsFile getenv('GOOGLE_APPLICATION_CREDENTIALS');

    
$client = new Google_Client();
    
$client->setAuthConfig($credentialsFile);

    
$http = new Client();
    
$client->authorize($http);

    
$this->checkAuthHandler($http'AuthToken');
    
$this->checkCredentials($http'Google\Auth\Credentials\ServiceAccountCredentials');
  }

  public function 
testApplicationDefaultCredentialsWithSubject()
  {
    
$this->checkServiceAccountCredentials();
    
$credentialsFile getenv('GOOGLE_APPLICATION_CREDENTIALS');

    
$sub 'sub123';
    
$client = new Google_Client();
    
$client->setAuthConfig($credentialsFile);
    
$client->setSubject($sub);

    
$http = new Client();
    
$client->authorize($http);

    
$this->checkAuthHandler($http'AuthToken');
    
$this->checkCredentials($http'Google\Auth\Credentials\ServiceAccountCredentials'$sub);
  }

  
/**
   * Test that the ID token is properly refreshed.
   */
  
public function testRefreshTokenSetsValues()
  {
    
$token json_encode(array(
        
'access_token' => 'xyz',
        
'id_token' => 'ID_TOKEN',
    ));
    
$postBody $this->getMock('Psr\Http\Message\StreamInterface');
    
$postBody->expects($this->once())
      ->
method('__toString')
      ->
will($this->returnValue($token));
    
$response $this->getMock('Psr\Http\Message\ResponseInterface');
    
$response->expects($this->once())
      ->
method('getBody')
      ->
will($this->returnValue($postBody));
    
$http $this->getMock('GuzzleHttp\ClientInterface');
    
$http->expects($this->once())
      ->
method('send')
      ->
will($this->returnValue($response));

    if (
$this->isGuzzle5()) {
      
$guzzle5Request = new GuzzleHttp\Message\Request('POST''/', ['body' => $token]);
      
$http->expects($this->once())
        ->
method('createRequest')
        ->
will($this->returnValue($guzzle5Request));
    }

    
$client $this->getClient();
    
$client->setHttpClient($http);
    
$client->fetchAccessTokenWithRefreshToken("REFRESH_TOKEN");
    
$token $client->getAccessToken();
    
$this->assertEquals($token['id_token'], "ID_TOKEN");
  }

  
/**
   * Test fetching an access token with assertion credentials
   * using "useApplicationDefaultCredentials"
   */
  
public function testFetchAccessTokenWithAssertionFromEnv()
  {
    
$this->checkServiceAccountCredentials();

    
$client $this->getClient();
    
$client->useApplicationDefaultCredentials();
    
$token $client->fetchAccessTokenWithAssertion();

    
$this->assertNotNull($token);
    
$this->assertArrayHasKey('access_token'$token);
  }

  
/**
   * Test fetching an access token with assertion credentials
   * using "setAuthConfig"
   */
  
public function testFetchAccessTokenWithAssertionFromFile()
  {
    
$this->checkServiceAccountCredentials();

    
$client $this->getClient();
    
$client->setAuthConfig(getenv('GOOGLE_APPLICATION_CREDENTIALS'));
    
$token $client->fetchAccessTokenWithAssertion();

    
$this->assertNotNull($token);
    
$this->assertArrayHasKey('access_token'$token);
  }

  
/**
   * Test fetching an access token with assertion credentials
   * using "setAuthConfig" and "setSubject" but with user credentials
   */
  
public function testBadSubjectThrowsException()
  {
    
$this->checkServiceAccountCredentials();

    
$client $this->getClient();
    
$client->useApplicationDefaultCredentials();
    
$client->setSubject('bad-subject');

    
$authHandler Google_AuthHandler_AuthHandlerFactory::build();

    
// make this method public for testing purposes
    
$method = new ReflectionMethod($authHandler'createAuthHttp');
    
$method->setAccessible(true);
    
$authHttp $method->invoke($authHandler$client->getHttpClient());

    try {
      
$token $client->fetchAccessTokenWithAssertion($authHttp);
      
$this->fail('no exception thrown');
    } catch (
GuzzleHttp\Exception\ClientException $e) {
      
$response $e->getResponse();
      
$this->assertContains('Invalid impersonation prn email address', (string) $response->getBody());
    }
  }

  public function 
testTokenCallback()
  {
    
$this->onlyPhp55AndAbove();
    
$this->checkToken();

    
$client $this->getClient();
    
$accessToken $client->getAccessToken();

    if (!isset(
$accessToken['refresh_token'])) {
      
$this->markTestSkipped('Refresh Token required');
    }

    
// make the auth library think the token is expired
    
$accessToken['expires_in'] = 0;
    
$cache $client->getCache();
    
$path sys_get_temp_dir().'/google-api-php-client-tests-'.time();
    
$client->setCache($this->getCache($path));
    
$client->setAccessToken($accessToken);

    
// create the callback function
    
$phpunit $this;
    
$called false;
    
$callback = function ($key$value) use ($client$cache$phpunit, &$called) {
      
// go back to the previous cache
      
$client->setCache($cache);

      
// assert the expected keys and values
      
$phpunit->assertContains('https---www.googleapis.com-auth-'$key);
      
$phpunit->assertNotNull($value);
      
$called true;
    };

    
// set the token callback to the client
    
$client->setTokenCallback($callback);

    
// make a silly request to obtain a new token
    
$http $client->authorize();
    
$http->get('https://www.googleapis.com/books/v1/volumes?q=Voltaire');
    
$newToken $client->getAccessToken();

    
// go back to the previous cache
    // (in case callback wasn't called)
    
$client->setCache($cache);

    
$this->assertTrue($called);
  }
}