Debian Codegraph @

lib/3rdParty/composer/duosecurity/duo_universal_php/tests/ClientTest.php

raw symbols SCIP
1 <?php declare(strict_types=1);
2 namespace Duo\Tests;
3
4 use \Firebase\JWT\JWT;
5 use \Firebase\JWT\Key;
6 use Duo\DuoUniversal\Client;
7 use Duo\DuoUniversal\DuoException;
8 use PHPUnit\Framework\TestCase;
9
10 final class ClientTest extends TestCase
11 {
12 public $username = "user";
13 public $bad_username = "baduser";
14 public $code = "abcdefghijkl";
15 public $bad_expiration = 1234567;
16 public $nonce = "deadbeefdeadbeefdeadbeef";
17 public $bad_nonce = "beefdeadbeefdeadbeef";
18 public $client_id = "12345678901234567890";
19 public $client_secret = "1234567890123456789012345678901234567890";
20 public $api_host = "api-123456.duo.com";
21 public $redirect_url = "https://redirect_example.com";
22 public $url_enc_redirect_url = "https%3A%2F%2Fredirect_example.com";
23 public $bad_client_id = "1234567890123456789";
24 public $long_client_secret = "1234567890123456789012345678901234567890000";
25 public $bad_client_secret = "1111111111111111111111111111111111111111";
26 public $bad_api_host = 123456;
27 public $good_http_request = ["response" => ["timestamp" => 1607009339],
28 "stat" => "OK"];
29 public $bad_http_request = ["message" => "invalid_client",
30 "code" => 40002,
31 "timestamp" => 1607014550,
32 "message_detail" => "Failed to verify signature.",
33 "stat" => "FAIL"];
34 public $missing_stat_health_check = ["response" => ["timestamp" => 1607009339]];
35 public $missing_message_health_check = ["stat" => "Fail"];
36 public $good_state = "deadbeefdeadbeefdeadbeefdeadbeefdead";
37 public $short_state = "deadbeefdeadbeefdeadb";
38 public $bad_http_request_exception = "invalid_client: Failed to verify signature.";
39 public $expected_good_http_request = array("response" => array("timestamp" => 1607009339),
40 "stat" => "OK");
41
42 /**
43 * Pads the client secret to meet minimum key length requirements for HS512.
44 *
45 * Note: This reimplements the logic from Client::getPaddedSecret() for testing purposes.
46 * The real implementation is tested through integration tests like testTokenExchangeSuccess().
47 * testPaddedSecretMatchesImplementation() verifies this reimplementation stays in sync.
48 */
49 private function getPaddedSecret(): string
50 {
51 return str_pad($this->client_secret, Client::HS512_MIN_KEY_LENGTH, "\0");
52 }
53
54 protected function setUp(): void
55 {
56 // null is the default behavior and signifies that JWT will use the real current timestamp
57 JWT::$timestamp = null;
58 }
59
60 /**
61 * Create Client
62 */
63 public function createGoodClient(): Client
64 {
65 return new Client(
66 $this->client_id,
67 $this->client_secret,
68 $this->api_host,
69 $this->redirect_url
70 );
71 }
72
73 /**
74 * Create Client with mocked out makeHttpsCall() to return $result
75 *
76 * @param array $result The data makeHttpsCall will return when running test
77 * @param string $bad_client_secret (Optional) Use bad client secret to create client
78 */
79 public function createClientMockHttp(array $result, string $bad_client_secret = '')
80 {
81 $client_secret = $bad_client_secret ? $bad_client_secret : $this->client_secret;
82 $client = $this->getMockBuilder(Client::class)
83 ->setConstructorArgs([$this->client_id, $client_secret, $this->api_host, $this->redirect_url])
84 ->setMethods(['makeHttpsCall'])
85 ->getMock();
86 $client->method('makeHttpsCall')
87 ->will($this->returnValue($result));
88 return $client;
89 }
90
91 /**
92 * Creates and signs jwt to be used for id_token in createTokenResult.
93 *
94 * @param string|null $remove_index Removes entry in $payload
95 * @param array<string, string> $change_val Changes entry for key to new value in $payload
96 *
97 * @return string encoded JWT
98 */
99 public function createIdToken(?string $remove_index = null, array $change_val = []): string
100 {
101 $date = new \DateTime();
102 $current_date = $date->getTimestamp();
103 $payload = ["exp" => $current_date + Client::JWT_EXPIRATION,
104 "iat" => $current_date,
105 "iss" => "https://" . $this->api_host . Client::TOKEN_ENDPOINT,
106 "aud" => $this->client_id,
107 "preferred_username" => $this->username,
108 "nonce" => $this->nonce
109 ];
110 if ($remove_index) {
111 unset($payload[$remove_index]);
112 }
113 if ($change_val) {
114 $payload[key($change_val)] = $change_val[key($change_val)];
115 }
116 return JWT::encode($payload, $this->getPaddedSecret(), Client::SIG_ALGORITHM);
117 }
118
119 /**
120 * Create token result returned From Duo after exchange with code.
121 *
122 * @param string $id_token A signed JWT
123 *
124 * @return array An array containing the token data
125 */
126 public function createTokenResult(string $id_token = ''): array
127 {
128 if (!$id_token) {
129 $id_token = $this->createIdToken();
130 }
131 return ["id_token" => $id_token,
132 "access_token" => "90101112",
133 "expires_in" => "1234567890",
134 "token_type" => "Bearer"];
135 }
136
137 /**
138 * Test that the test's getPaddedSecret() reimplementation matches the real Client implementation.
139 * This ensures the test helper stays in sync with the actual implementation.
140 */
141 public function testPaddedSecretMatchesImplementation(): void
142 {
143 $client = $this->createGoodClient();
144
145 // Create a JWT using the Client's internal getPaddedSecret() (via createAuthUrl)
146 $auth_url = $client->createAuthUrl($this->username, $this->good_state);
147
148 // Extract the JWT from the URL
149 $query_str = parse_url($auth_url, PHP_URL_QUERY);
150 parse_str($query_str, $query_params);
151 $token = $query_params["request"];
152
153 // Try to decode it using the test's getPaddedSecret()
154 // If the signatures don't match, this will throw SignatureInvalidException
155 $jwt_key = new Key($this->getPaddedSecret(), Client::SIG_ALGORITHM);
156 $decoded = JWT::decode($token, $jwt_key);
157
158 // Verify the decoded token contains expected data
159 $this->assertEquals($this->username, $decoded->duo_uname);
160 }
161
162 /**
163 * Test that creating a client with proper inputs does not throw an error.
164 */
165 public function testClientGood(): void
166 {
167 $client = $this->createGoodClient();
168 $this->assertInstanceOf(Client::class, $client);
169 }
170
171 /**
172 * Test that an invalid client_id will cause the Client to throw a DuoException
173 */
174 public function testClientBadClientId(): void
175 {
176 $this->expectException(DuoException::class);
177 $this->expectExceptionMessage(Client::INVALID_CLIENT_ID_ERROR);
178 $client = new Client(
179 $this->bad_client_id,
180 $this->client_secret,
181 $this->api_host,
182 $this->redirect_url
183 );
184 }
185
186 /**
187 * Test that an invalid client_secret
188 * will cause the Client to throw a DuoException
189 */
190 public function testClientBadClientSecret(): void
191 {
192 $this->expectException(DuoException::class);
193 $this->expectExceptionMessage(Client::INVALID_CLIENT_SECRET_ERROR);
194 $client = new Client(
195 $this->client_id,
196 $this->long_client_secret,
197 $this->api_host,
198 $this->redirect_url
199 );
200 }
201
202 /**
203 * Test that generateState does not return the same
204 * string twice.
205 */
206 public function testGenerateState(): void
207 {
208 $client = $this->createGoodClient();
209 $string_1 = $client->generateState();
210 $this->assertNotEquals(
211 $string_1,
212 $client->generateState()
213 );
214 }
215
216 /**
217 * Test that a successful health check returns a successful result.
218 */
219 public function testHealthCheckGood(): void
220 {
221 $client = $this->createClientMockHttp($this->good_http_request);
222 $result = $client->healthCheck();
223 $this->assertEquals($this->expected_good_http_request, $result);
224 }
225
226 /**
227 * Test that a failed connection to Duo throws a FAILED_CONNECTION exception.
228 */
229 public function testHealthCheckConnectionFail(): void
230 {
231 $this->expectException(DuoException::class);
232 $this->expectExceptionMessage(Client::FAILED_CONNECTION);
233 $client = $this->getMockBuilder(Client::class)
234 ->setConstructorArgs([$this->client_id, $this->client_secret, $this->api_host, $this->redirect_url])
235 ->setMethods(['makeHttpsCall'])
236 ->getMock();
237 $client->method('makeHttpsCall')
238 ->will($this->throwException(new DuoException(Client::FAILED_CONNECTION)));
239 $client->healthCheck();
240 }
241
242 /**
243 * Test that when Duo is down the client throws an error
244 */
245 public function testHealthCheckBadSig(): void
246 {
247 $this->expectException(DuoException::class);
248 $this->expectExceptionMessage($this->bad_http_request_exception);
249 $client = $this->createClientMockHttp($this->bad_http_request);
250 $client->healthCheck();
251 }
252
253 /**
254 * Test that if the health check response is missing stat then the client throws an error.
255 */
256 public function testHealthCheckMissingStat(): void
257 {
258 $this->expectException(DuoException::class);
259 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
260 $client = $this->createClientMockHttp($this->missing_stat_health_check);
261 $client->healthCheck();
262 }
263
264 /**
265 * Test that if the health check failed and the response is malformed then the client throws an error.
266 */
267 public function testHealthCheckMissingMessage(): void
268 {
269 $this->expectException(DuoException::class);
270 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
271 $client = $this->createClientMockHttp($this->missing_message_health_check);
272 $client->healthCheck();
273 }
274
275 /**
276 * @dataProvider providerMissingResponseField
277 */
278 public function testMissingResponseField($missing_field): void
279 {
280 $result = $this->createTokenResult();
281 unset($result[$missing_field]);
282 $this->expectException(DuoException::class);
283 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
284 $client = $this->createClientMockHttp($result);
285 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
286 }
287
288 /**
289 * Provides a list of missing fields for the response when hitting the TOKEN_ENDPOINT.
290 */
291 public function providerMissingResponseField(): array
292 {
293 return [
294 ["token_type"],
295 ["access_token"],
296 ["expires_in"],
297 ["id_token"]
298 ];
299 }
300 /**
301 * Test bad token_type in response during token exchange throws an error.
302 */
303 public function testTokenExchangeBadTokenType(): void
304 {
305 $result_good = $this->createTokenResult();
306 $result = str_replace('Bearer', 'BadTokenType', $result_good);
307 $this->expectException(DuoException::class);
308 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
309 $client = $this->createClientMockHttp($result);
310 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
311 }
312
313 /**
314 * Test bad nonce in id_token during token exchange throws an error.
315 */
316 public function testTokenExchangeBadNonce(): void
317 {
318 $payload = $this->createIdToken("nonce");
319 $result = $this->createTokenResult($payload);
320 $this->expectException(DuoException::class);
321 $this->expectExceptionMessage(Client::NONCE_ERROR);
322 $client = $this->createClientMockHttp($result);
323 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username, $this->bad_nonce);
324 }
325
326 /**
327 * Test bad JWT signature for id_token during token exchange throws an error.
328 */
329 public function testTokenExchangeBadSig(): void
330 {
331 $result = $this->createTokenResult();
332 $this->expectException(DuoException::class);
333 $this->expectExceptionMessage(Client::JWT_DECODE_ERROR);
334 $client = $this->createClientMockHttp($result, $this->bad_client_secret);
335 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
336 }
337
338 /**
339 * Test expired id_token during token exchange throws an error.
340 */
341 public function testTokenExchangeExpired(): void
342 {
343 $expired = ["exp" => $this->bad_expiration];
344 $payload = $this->createIdToken(null, $expired);
345 $result = $this->createTokenResult($payload);
346 $this->expectException(DuoException::class);
347 $this->expectExceptionMessage(Client::JWT_DECODE_ERROR);
348 $client = $this->createClientMockHttp($result);
349 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
350 }
351
352 /**
353 * Test clock skew more than leeway throws an error.
354 */
355 public function testTokenExchangeLargeClockSkew(): void
356 {
357 // Simulate a clock skew (greater than the leeway) by feeding JWT a slightly different timestamp.
358 JWT::$timestamp = time() - Client::JWT_LEEWAY * 2;
359
360 $payload = $this->createIdToken();
361 $result = $this->createTokenResult($payload);
362 $this->expectException(DuoException::class);
363 $this->expectExceptionMessage(Client::JWT_DECODE_ERROR);
364 $client = $this->createClientMockHttp($result);
365 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
366 }
367
368 /**
369 * Test clock skew less than leeway is successful.
370 */
371 public function testTokenExchangeSmallClockSkew(): void
372 {
373 // Simulate a clock skew (smaller than the leeway) by feeding JWT a slightly different timestamp.
374 JWT::$timestamp = time() - Client::JWT_LEEWAY / 2;
375
376 $payload = $this->createIdToken();
377 $result = $this->createTokenResult($payload);
378 $client = $this->createClientMockHttp($result);
379 $token = $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
380 $this->assertEquals($this->username, $token['preferred_username']);
381 }
382
383 /**
384 * @dataProvider providerMissingField
385 */
386 public function testMissingField(string $missing_field, string $expected_response): void
387 {
388 $payload = $this->createIdToken($missing_field);
389 $result = $this->createTokenResult($payload);
390 $this->expectException(DuoException::class);
391 $this->expectExceptionMessage($expected_response);
392 $client = $this->createClientMockHttp($result);
393 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username, $this->nonce);
394 }
395
396 /**
397 * Provides a list of missing fields and expected expections
398 * for the id_token in the response when hitting the TOKEN_ENDPOINT.
399 */
400 public function providerMissingField(): array
401 {
402 return [
403 [ "exp", Client::MALFORMED_RESPONSE],
404 [ "iat", Client::MALFORMED_RESPONSE],
405 [ "iss", Client::MALFORMED_RESPONSE],
406 [ "aud", Client::MALFORMED_RESPONSE],
407 [ "nonce", Client::NONCE_ERROR],
408 [ "preferred_username", Client::USERNAME_ERROR ]
409 ];
410 }
411
412 /**
413 * Test bad iss in id_token during token exchange throws an error.
414 */
415 public function testTokenExchangeBadIss(): void
416 {
417 $bad_iss = ["iss" => "https://" . $this->bad_api_host . Client::TOKEN_ENDPOINT];
418 $payload = $this->createIdToken(null, $bad_iss);
419 $result = $this->createTokenResult($payload);
420 $this->expectException(DuoException::class);
421 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
422 $client = $this->createClientMockHttp($result);
423 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
424 }
425
426 /**
427 * Test bad aud in id_token during token exchange throws an error.
428 */
429 public function testTokenExchangeBadAud(): void
430 {
431 $bad_aud = ["aud" => $this->bad_client_id];
432 $payload = $this->createIdToken(null, $bad_aud);
433 $result = $this->createTokenResult($payload);
434 $this->expectException(DuoException::class);
435 $this->expectExceptionMessage(Client::MALFORMED_RESPONSE);
436 $client = $this->createClientMockHttp($result);
437 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
438 }
439
440 /**
441 * Test wrong preferred_username in id_token during token exchange throws an error.
442 */
443 public function testTokenExchangeBadUsername(): void
444 {
445 $bad_aud = ["preferred_username" => $this->bad_username];
446 $payload = $this->createIdToken(null, $bad_aud);
447 $result = $this->createTokenResult($payload);
448 $this->expectException(DuoException::class);
449 $this->expectExceptionMessage(Client::USERNAME_ERROR);
450 $client = $this->createClientMockHttp($result);
451 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
452 }
453
454 /**
455 * Test a successful token exchange.
456 */
457 public function testTokenExchangeSuccess(): void
458 {
459 $id_token = $this->createIdToken();
460 $result = $this->createTokenResult($id_token);
461 $jwt_key = new Key($this->getPaddedSecret(), Client::SIG_ALGORITHM);
462 $expected_result_obj = JWT::decode($id_token, $jwt_key);
463 $expected_result = json_decode(json_encode($expected_result_obj), true);
464 $client = $this->createClientMockHttp($result);
465 $exchange_result = $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
466 $this->assertEquals($expected_result, $exchange_result);
467 }
468
469 /**
470 * @dataProvider providerState
471 */
472 public function testCreateAuthUrlState(string $state): void
473 {
474 $this->expectException(DuoException::class);
475 $this->expectExceptionMessage(Client::DUO_STATE_ERROR);
476 $client = $this->createGoodClient();
477 $client->createAuthUrl($this->username, $state);
478 }
479
480 /**
481 * Provides a list of invalid states for createAuthUrl
482 */
483 public function providerState(): array
484 {
485 $long_state = str_repeat("a", Client::MAX_STATE_LENGTH + 1);
486 return [
487 [$this->short_state],
488 [$long_state]
489 ];
490 }
491
492 /**
493 * Test that by default we request the duo_code parameter in our JWT
494 */
495 public function testDuoCodeDefaultTrue(): void
496 {
497 $client = new Client(
498 $this->client_id,
499 $this->client_secret,
500 $this->api_host,
501 $this->redirect_url
502 );
503 $auth_url = $client->createAuthUrl($this->username, $this->good_state);
504 $jwt = $this->decodeJWTFromURL($auth_url);
505 $this->assertTrue($jwt["use_duo_code_attribute"]);
506 }
507
508 /**
509 * Test that passing false to constructor causes our JWT not request use_duo_code_attribute
510 */
511 public function testDuoCodeSetFalse(): void
512 {
513 $client = new Client(
514 $this->client_id,
515 $this->client_secret,
516 $this->api_host,
517 $this->redirect_url,
518 false
519 );
520 $auth_url = $client->createAuthUrl($this->username, $this->good_state);
521 $jwt = $this->decodeJWTFromURL($auth_url);
522 $this->assertFalse($jwt["use_duo_code_attribute"]);
523 }
524
525 /**
526 * Helper to decode a JWT from a URL
527 */
528 public function decodeJWTFromURL(string $url): array
529 {
530 $query_str = parse_url($url, PHP_URL_QUERY);
531 parse_str($query_str, $query_params);
532 $token = $query_params["request"];
533 $jwt_key = new Key($this->getPaddedSecret(), Client::SIG_ALGORITHM);
534 $result_obj = JWT::decode($token, $jwt_key);
535 return json_decode(json_encode($result_obj), true);
536 }
537
538 /**
539 * Test a successful createAuthUrl returns a good uri.
540 */
541 public function testCreateAuthUrlSuccess(): void
542 {
543 $client = $this->createGoodClient();
544 $duo_uri = $client->createAuthUrl($this->username, $this->good_state);
545 $expected_client_id = "client_id=" . $this->client_id;
546 $expected_redir_uri = "redirect_uri=" . $this->url_enc_redirect_url;
547
548 $this->assertStringContainsString($expected_client_id, $duo_uri);
549 $this->assertStringContainsString("response_type=code", $duo_uri);
550 $this->assertStringContainsString("scope=openid", $duo_uri);
551 $this->assertStringContainsString($expected_redir_uri, $duo_uri);
552 }
553
554 /**
555 * Test that the user agent extension can be set and is included in requests.
556 */
557 public function testAppendToUserAgent(): void
558 {
559 $custom_extension = "MyApp/1.0.0";
560 $id_token = $this->createIdToken();
561 $result = $this->createTokenResult($id_token);
562
563 // Mock the client to capture the user agent sent in HTTP requests
564 $client = $this->getMockBuilder(Client::class)
565 ->setConstructorArgs([$this->client_id, $this->client_secret, $this->api_host, $this->redirect_url])
566 ->setMethods(['makeHttpsCall'])
567 ->getMock();
568
569 // Set up the mock to capture the user agent parameter
570 $captured_user_agent = null;
571 $client->method('makeHttpsCall')
572 ->willReturnCallback(function ($endpoint, $request, $user_agent = null) use (&$captured_user_agent, $result) {
573 $captured_user_agent = $user_agent;
574 return $result;
575 });
576
577 // Append custom user agent extension
578 $client->appendToUserAgent($custom_extension);
579
580 // Make a call that uses the user agent
581 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
582
583 // Verify the user agent includes our custom extension
584 $this->assertNotNull($captured_user_agent);
585 $this->assertStringContainsString($custom_extension, $captured_user_agent);
586 $this->assertStringContainsString(Client::USER_AGENT, $captured_user_agent);
587 $this->assertStringContainsString("php/" . phpversion(), $captured_user_agent);
588 }
589
590 /**
591 * Test that user agent works correctly without any extension.
592 */
593 public function testUserAgentWithoutExtension(): void
594 {
595 $id_token = $this->createIdToken();
596 $result = $this->createTokenResult($id_token);
597
598 // Mock the client to capture the user agent sent in HTTP requests
599 $client = $this->getMockBuilder(Client::class)
600 ->setConstructorArgs([$this->client_id, $this->client_secret, $this->api_host, $this->redirect_url])
601 ->setMethods(['makeHttpsCall'])
602 ->getMock();
603
604 // Set up the mock to capture the user agent parameter
605 $captured_user_agent = null;
606 $client->method('makeHttpsCall')
607 ->willReturnCallback(function ($endpoint, $request, $user_agent = null) use (&$captured_user_agent, $result) {
608 $captured_user_agent = $user_agent;
609 return $result;
610 });
611
612 // Make a call without setting any custom user agent extension
613 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
614
615 // Verify the user agent contains default information but no custom extension
616 $this->assertNotNull($captured_user_agent);
617 $this->assertStringContainsString(Client::USER_AGENT, $captured_user_agent);
618 $this->assertStringContainsString("php/" . phpversion(), $captured_user_agent);
619 $this->assertStringContainsString(php_uname(), $captured_user_agent);
620 }
621
622 /**
623 * Test that empty user agent extension is handled correctly.
624 */
625 public function testAppendToUserAgentEmpty(): void
626 {
627 $id_token = $this->createIdToken();
628 $result = $this->createTokenResult($id_token);
629
630 // Mock the client to capture the user agent sent in HTTP requests
631 $client = $this->getMockBuilder(Client::class)
632 ->setConstructorArgs([$this->client_id, $this->client_secret, $this->api_host, $this->redirect_url])
633 ->setMethods(['makeHttpsCall'])
634 ->getMock();
635
636 // Set up the mock to capture the user agent parameter
637 $captured_user_agent = null;
638 $client->method('makeHttpsCall')
639 ->willReturnCallback(function ($endpoint, $request, $user_agent = null) use (&$captured_user_agent, $result) {
640 $captured_user_agent = $user_agent;
641 return $result;
642 });
643
644 // Append empty user agent extension
645 $client->appendToUserAgent("");
646
647 // Make a call
648 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
649
650 // Verify the user agent contains default information but no trailing space
651 $this->assertNotNull($captured_user_agent);
652 $this->assertStringContainsString(Client::USER_AGENT, $captured_user_agent);
653 $this->assertStringContainsString("php/" . phpversion(), $captured_user_agent);
654 $this->assertStringContainsString(php_uname(), $captured_user_agent);
655 // Ensure no trailing spaces from empty extension
656 $expected_base = Client::USER_AGENT . " php/" . phpversion() . " " . php_uname();
657 $this->assertEquals($expected_base, $captured_user_agent);
658 }
659
660 /**
661 * Test that whitespace-only user agent extension is handled correctly.
662 */
663 public function testAppendToUserAgentWhitespace(): void
664 {
665 $id_token = $this->createIdToken();
666 $result = $this->createTokenResult($id_token);
667
668 // Mock the client to capture the user agent sent in HTTP requests
669 $client = $this->getMockBuilder(Client::class)
670 ->setConstructorArgs([$this->client_id, $this->client_secret, $this->api_host, $this->redirect_url])
671 ->setMethods(['makeHttpsCall'])
672 ->getMock();
673
674 // Set up the mock to capture the user agent parameter
675 $captured_user_agent = null;
676 $client->method('makeHttpsCall')
677 ->willReturnCallback(function ($endpoint, $request, $user_agent = null) use (&$captured_user_agent, $result) {
678 $captured_user_agent = $user_agent;
679 return $result;
680 });
681
682 // Append whitespace-only user agent extension
683 $client->appendToUserAgent(" ");
684
685 // Make a call
686 $client->exchangeAuthorizationCodeFor2FAResult($this->code, $this->username);
687
688 // Verify the user agent contains default information but no extra whitespace
689 $this->assertNotNull($captured_user_agent);
690 $expected_base = Client::USER_AGENT . " php/" . phpversion() . " " . php_uname();
691 $this->assertEquals($expected_base, $captured_user_agent);
692 }
693 }