@@ -485,4 +485,70 @@ public function testIdTokenWithAuthTokenMiddleware()
485485
486486 $ this ->assertEquals (1 , $ requestCount );
487487 }
488+
489+ /**
490+ * @dataProvider provideScopePrecedence
491+ */
492+ public function testScopePrecedence (
493+ string |array |null $ userScope ,
494+ string |array |null $ jsonKeyScope ,
495+ string |null $ defaultScope ,
496+ string |array $ expectedScope
497+ ) {
498+ $ jsonKey = self ::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON ;
499+ $ jsonKey ['scopes ' ] = $ jsonKeyScope ;
500+ $ credentials = new ImpersonatedServiceAccountCredentials (
501+ scope: $ userScope ,
502+ jsonKey: $ jsonKey ,
503+ defaultScope: $ defaultScope ,
504+ );
505+
506+ $ scopeProp = (new ReflectionClass ($ credentials ))->getProperty ('targetScope ' );
507+ $ this ->assertEquals ($ expectedScope , $ scopeProp ->getValue ($ credentials ));
508+ }
509+
510+ public function testScopePrecedenceWithNoJsonKey ()
511+ {
512+ $ defaultScope = 'a-default-scope ' ;
513+ $ jsonKey = self ::SERVICE_ACCOUNT_TO_SERVICE_ACCOUNT_JSON ;
514+ $ credentials = new ImpersonatedServiceAccountCredentials (
515+ scope: null ,
516+ jsonKey: $ jsonKey ,
517+ defaultScope: $ defaultScope ,
518+ );
519+
520+ $ scopeProp = (new ReflectionClass ($ credentials ))->getProperty ('targetScope ' );
521+ $ this ->assertEquals ($ defaultScope , $ scopeProp ->getValue ($ credentials ));
522+ }
523+
524+ public function provideScopePrecedence ()
525+ {
526+ $ userScope = 'a-user-scope ' ;
527+ $ jsonKeyScope = 'a-json-key-scope ' ;
528+ $ defaultScope = 'a-default-scope ' ;
529+ return [
530+ // User scope always takes precendence
531+ [$ userScope , $ jsonKeyScope , $ defaultScope , 'expectedScope ' => $ userScope ],
532+ [$ userScope , null , $ defaultScope , 'expectedScope ' => $ userScope ],
533+ [$ userScope , $ jsonKeyScope , null , 'expectedScope ' => $ userScope ],
534+ [$ userScope , null , null , 'expectedScope ' => $ userScope ],
535+
536+ // JSON Key Scope is next
537+ [null , $ jsonKeyScope , $ defaultScope , 'expectedScope ' => $ jsonKeyScope ],
538+ [null , $ jsonKeyScope , null , 'expectedScope ' => $ jsonKeyScope ],
539+
540+ // Default Scope is last
541+ [null , null , $ defaultScope , 'expectedScope ' => $ defaultScope ],
542+ // JSON Key scope is exists but is an empty array, still return default
543+ [null , [], $ defaultScope , 'expectedScope ' => $ defaultScope ],
544+
545+ // No scope is empty array
546+ [null , null , null , 'expectedScope ' => []],
547+
548+ // Test empty strings and arrays
549+ ['' , $ jsonKeyScope , null , 'expectedScope ' => $ jsonKeyScope ],
550+ [[], $ jsonKeyScope , null , 'expectedScope ' => $ jsonKeyScope ],
551+ [[], '' , $ defaultScope , 'expectedScope ' => $ defaultScope ],
552+ ];
553+ }
488554}
0 commit comments