diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index efa68af5c..b6edf4bc3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -78,3 +78,18 @@ jobs: run: | composer require friendsofphp/php-cs-fixer:^3.0 vendor/bin/php-cs-fixer fix --dry-run --diff + + staticanalysis: + runs-on: ubuntu-latest + name: PHPStan Static Analysis + steps: + - uses: actions/checkout@v2 + - name: Install PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + - name: Run Script + run: | + composer install + composer global require phpstan/phpstan + ~/.composer/vendor/bin/phpstan analyse diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 000000000..3b5a41278 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,10 @@ +parameters: + treatPhpDocTypesAsCertain: false + level: 7 + paths: + - src + featureToggles: + disableRuntimeReflectionProvider: true + excludePaths: + - src/HttpHandler/Guzzle5HttpHandler.php + - src/Cache/Item.php diff --git a/src/AccessToken.php b/src/AccessToken.php index f1aed1d20..d91e0093b 100644 --- a/src/AccessToken.php +++ b/src/AccessToken.php @@ -82,20 +82,22 @@ public function __construct( * accepted. By default, the id token must have been issued to this OAuth2 client. * * @param string $token The JSON Web Token to be verified. - * @param array $options [optional] Configuration options. - * @param string $options.audience The indended recipient of the token. - * @param string $options.issuer The intended issuer of the token. - * @param string $options.cacheKey The cache key of the cached certs. Defaults to + * @param array $options [optional] { + * Configuration options. + * @type string $audience The indended recipient of the token. + * @type string $issuer The intended issuer of the token. + * @type string $cacheKey The cache key of the cached certs. Defaults to * the sha1 of $certsLocation if provided, otherwise is set to * "federated_signon_certs_v3". - * @param string $options.certsLocation The location (remote or local) from which + * @type string $certsLocation The location (remote or local) from which * to retrieve certificates, if not cached. This value should only be * provided in limited circumstances in which you are sure of the * behavior. - * @param bool $options.throwException Whether the function should throw an + * @type bool $throwException Whether the function should throw an * exception if the verification fails. This is useful for * determining the reason verification failed. - * @return array|bool the token payload, if successful, or false if not. + * } + * @return array|false the token payload, if successful, or false if not. * @throws InvalidArgumentException If certs could not be retrieved from a local file. * @throws InvalidArgumentException If received certs are in an invalid format. * @throws InvalidArgumentException If the cert alg is not supported. @@ -134,12 +136,10 @@ public function verify($token, array $options = []) return $this->verifyRs256($token, $certs, $audience, $issuer); } return $this->verifyEs256($token, $certs, $audience, $issuer); - } catch (ExpiredException $e) { // firebase/php-jwt 3+ - } catch (\ExpiredException $e) { // firebase/php-jwt 2 - } catch (SignatureInvalidException $e) { // firebase/php-jwt 3+ - } catch (\SignatureInvalidException $e) { // firebase/php-jwt 2 + } catch (ExpiredException $e) { // firebase/php-jwt 5+ + } catch (SignatureInvalidException $e) { // firebase/php-jwt 5+ } catch (InvalidTokenException $e) { // simplejwt - } catch (DomainException $e) { + } catch (DomainException $e) { // @phpstan-ignore-line } catch (InvalidArgumentException $e) { } catch (UnexpectedValueException $e) { } @@ -155,7 +155,7 @@ public function verify($token, array $options = []) * Identifies the expected algorithm to verify by looking at the "alg" key * of the provided certs. * - * @param array $certs Certificate array according to the JWK spec (see + * @param array $certs Certificate array according to the JWK spec (see * https://tools.ietf.org/html/rfc7517). * @return string The expected algorithm, such as "ES256" or "RS256". */ @@ -183,13 +183,13 @@ private function determineAlg(array $certs) * Verifies an ES256-signed JWT. * * @param string $token The JSON Web Token to be verified. - * @param array $certs Certificate array according to the JWK spec (see + * @param array $certs Certificate array according to the JWK spec (see * https://tools.ietf.org/html/rfc7517). * @param string|null $audience If set, returns false if the provided * audience does not match the "aud" claim on the JWT. * @param string|null $issuer If set, returns false if the provided * issuer does not match the "iss" claim on the JWT. - * @return array|bool the token payload, if successful, or false if not. + * @return array the token payload, if successful, or false if not. */ private function verifyEs256($token, array $certs, $audience = null, $issuer = null) { @@ -223,13 +223,13 @@ private function verifyEs256($token, array $certs, $audience = null, $issuer = n * Verifies an RS256-signed JWT. * * @param string $token The JSON Web Token to be verified. - * @param array $certs Certificate array according to the JWK spec (see + * @param array $certs Certificate array according to the JWK spec (see * https://tools.ietf.org/html/rfc7517). * @param string|null $audience If set, returns false if the provided * audience does not match the "aud" claim on the JWT. * @param string|null $issuer If set, returns false if the provided * issuer does not match the "iss" claim on the JWT. - * @return array|bool the token payload, if successful, or false if not. + * @return array the token payload, if successful, or false if not. */ private function verifyRs256($token, array $certs, $audience = null, $issuer = null) { @@ -286,8 +286,8 @@ private function verifyRs256($token, array $certs, $audience = null, $issuer = n * Revoke an OAuth2 access token or refresh token. This method will revoke the current access * token, if a token isn't provided. * - * @param string|array $token The token (access token or a refresh token) that should be revoked. - * @param array $options [optional] Configuration options. + * @param string|array $token The token (access token or a refresh token) that should be revoked. + * @param array $options [optional] Configuration options. * @return bool Returns True if the revocation was successful, otherwise False. */ public function revoke($token, array $options = []) @@ -320,14 +320,14 @@ public function revoke($token, array $options = []) * * @param string $location The location from which to retrieve certs. * @param string $cacheKey The key under which to cache the retrieved certs. - * @param array $options [optional] Configuration options. - * @return array + * @param array $options [optional] Configuration options. + * @return array * @throws InvalidArgumentException If received certs are in an invalid format. */ private function getCerts($location, $cacheKey, array $options = []) { $cacheItem = $this->cache->getItem($cacheKey); - $certs = $cacheItem ? $cacheItem->get() : null; + $certs = $cacheItem ? $cacheItem->get() : null; // @phpstan-ignore-line $gotNewCerts = false; if (!$certs) { @@ -361,9 +361,9 @@ private function getCerts($location, $cacheKey, array $options = []) /** * Retrieve and cache a certificates file. * - * @param $url string location - * @param array $options [optional] Configuration options. - * @return array certificates + * @param string $url location + * @param array $options [optional] Configuration options. + * @return array certificates * @throws InvalidArgumentException If certs could not be retrieved from a local file. * @throws RuntimeException If certs could not be retrieved from a remote location. */ @@ -378,7 +378,7 @@ private function retrieveCertsFromLocation($url, array $options = []) )); } - return json_decode(file_get_contents($url), true); + return json_decode((string) file_get_contents($url), true); } $httpHandler = $this->httpHandler; @@ -394,6 +394,9 @@ private function retrieveCertsFromLocation($url, array $options = []) ), $response->getStatusCode()); } + /** + * @return void + */ private function checkAndInitializePhpsec() { // @codeCoverageIgnoreStart @@ -405,10 +408,13 @@ private function checkAndInitializePhpsec() $this->setPhpsecConstants(); } + /** + * @return void + */ private function checkSimpleJwt() { // @codeCoverageIgnoreStart - if (!class_exists('SimpleJWT\JWT')) { + if (!class_exists(SimpleJwt::class)) { throw new RuntimeException('Please require kelvinmo/simplejwt ^0.2 to use this utility.'); } // @codeCoverageIgnoreEnd @@ -422,6 +428,8 @@ private function checkSimpleJwt() * @see phpseclib/Math/BigInteger * @see https://github.com/GoogleCloudPlatform/getting-started-php/issues/85 * @codeCoverageIgnore + * + * @return void */ private function setPhpsecConstants() { @@ -439,24 +447,23 @@ private function setPhpsecConstants() * Provide a hook to mock calls to the JWT static methods. * * @param string $method - * @param array $args + * @param array $args * @return mixed */ protected function callJwtStatic($method, array $args = []) { - $class = 'Firebase\JWT\JWT'; - return call_user_func_array([$class, $method], $args); + return call_user_func_array([JWT::class, $method], $args); // @phpstan-ignore-line } /** * Provide a hook to mock calls to the JWT static methods. * - * @param array $args + * @param array $args * @return mixed */ protected function callSimpleJwtDecode(array $args = []) { - return call_user_func_array(['SimpleJWT\JWT', 'decode'], $args); + return call_user_func_array([SimpleJwt::class, 'decode'], $args); } /** diff --git a/src/ApplicationDefaultCredentials.php b/src/ApplicationDefaultCredentials.php index af67f182f..15783d1af 100644 --- a/src/ApplicationDefaultCredentials.php +++ b/src/ApplicationDefaultCredentials.php @@ -70,22 +70,24 @@ class ApplicationDefaultCredentials { /** + * @deprecated + * * Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface * implementation to use in this environment. * * If supplied, $scope is used to in creating the credentials instance if * this does not fallback to the compute engine defaults. * - * @param string|array scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return AuthTokenSubscriber * @throws DomainException if no implementation can be obtained. */ - public static function getSubscriber( + public static function getSubscriber(// @phpstan-ignore-line $scope = null, callable $httpHandler = null, array $cacheConfig = null, @@ -93,6 +95,7 @@ public static function getSubscriber( ) { $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache); + /** @phpstan-ignore-next-line */ return new AuthTokenSubscriber($creds, $httpHandler); } @@ -103,10 +106,10 @@ public static function getSubscriber( * If supplied, $scope is used to in creating the credentials instance if * this does not fallback to the compute engine defaults. * - * @param string|array scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @param string $quotaProject specifies a project to bill for access @@ -130,19 +133,19 @@ public static function getMiddleware( * Obtains the default FetchAuthTokenInterface implementation to use * in this environment. * - * @param string|array $scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @param string $quotaProject specifies a project to bill for access * charges associated with the request. - * @param string|array $defaultScope The default scope to use if no + * @param string|string[] $defaultScope The default scope to use if no * user-defined scopes exist, expressed either as an Array or as a * space-delimited string. * - * @return CredentialsLoader + * @return FetchAuthTokenInterface * @throws DomainException if no implementation can be obtained. */ public static function getCredentials( @@ -201,7 +204,7 @@ public static function getCredentials( * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return AuthTokenMiddleware @@ -228,7 +231,7 @@ public static function getIdTokenMiddleware( * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. * @return ProxyAuthTokenMiddleware @@ -252,10 +255,10 @@ public static function getProxyIdTokenMiddleware( * * @param string $targetAudience The audience for the ID token. * @param callable $httpHandler callback which delivers psr7 request - * @param array $cacheConfig configuration for the cache when it's present + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache A cache implementation, may be * provided if you have one already available for use. - * @return CredentialsLoader + * @return FetchAuthTokenInterface * @throws DomainException if no implementation can be obtained. * @throws InvalidArgumentException if JSON "type" key is invalid */ @@ -305,6 +308,9 @@ public static function getIdTokenCredentials( return $creds; } + /** + * @return string + */ private static function notFound() { $msg = 'Could not load the default credentials. Browse to '; @@ -315,6 +321,12 @@ private static function notFound() return $msg; } + /** + * @param callable $httpHandler + * @param array $cacheConfig + * @param CacheItemPoolInterface $cache + * @return bool + */ private static function onGce( callable $httpHandler = null, array $cacheConfig = null, diff --git a/src/Cache/Item.php b/src/Cache/Item.php index 5d8ab7ecd..61536e541 100644 --- a/src/Cache/Item.php +++ b/src/Cache/Item.php @@ -17,7 +17,11 @@ namespace Google\Auth\Cache; +use DateTime; +use DateTimeInterface; +use DateTimeZone; use Psr\Cache\CacheItemInterface; +use TypeError; /** * A cache item. @@ -35,7 +39,7 @@ final class Item implements CacheItemInterface private $value; /** - * @var \DateTime|null + * @var DateTimeInterface|null */ private $expiration; @@ -106,18 +110,13 @@ public function expiresAt($expiration) return $this; } - $implementationMessage = interface_exists('DateTimeInterface') - ? 'implement interface DateTimeInterface' - : 'be an instance of DateTime'; - $error = sprintf( - 'Argument 1 passed to %s::expiresAt() must %s, %s given', + 'Argument 1 passed to %s::expiresAt() must implement interface DateTimeInterface, %s given', get_class($this), - $implementationMessage, gettype($expiration) ); - $this->handleError($error); + throw new TypeError($error); } /** @@ -136,27 +135,12 @@ public function expiresAfter($time) 'instance of DateInterval or of the type integer, %s given'; $error = sprintf($message, get_class($this), gettype($time)); - $this->handleError($error); + throw new TypeError($error); } return $this; } - /** - * Handles an error. - * - * @param string $error - * @throws \TypeError - */ - private function handleError($error) - { - if (class_exists('TypeError')) { - throw new \TypeError($error); - } - - trigger_error($error, E_USER_ERROR); - } - /** * Determines if an expiration is valid based on the rules defined by PSR6. * @@ -169,15 +153,18 @@ private function isValidExpiration($expiration) return true; } - if ($expiration instanceof \DateTimeInterface) { + if ($expiration instanceof DateTimeInterface) { return true; } return false; } + /** + * @return DateTime + */ protected function currentTime() { - return new \DateTime('now', new \DateTimeZone('UTC')); + return new DateTime('now', new DateTimeZone('UTC')); } } diff --git a/src/Cache/MemoryCacheItemPool.php b/src/Cache/MemoryCacheItemPool.php index a02e39030..2c7a9d574 100644 --- a/src/Cache/MemoryCacheItemPool.php +++ b/src/Cache/MemoryCacheItemPool.php @@ -38,18 +38,17 @@ final class MemoryCacheItemPool implements CacheItemPoolInterface /** * {@inheritdoc} * - * @return CacheItemInterface - * The corresponding Cache Item. + * @return CacheItemInterface The corresponding Cache Item. */ public function getItem($key): CacheItemInterface { - return current($this->getItems([$key])); + return current($this->getItems([$key])); // @phpstan-ignore-line } /** * {@inheritdoc} * - * @return iterable + * @return iterable * A traversable collection of Cache Items keyed by the cache keys of * each item. A Cache item will be returned for each key, even if that * key is not found. However, if no keys are specified then an empty diff --git a/src/Cache/SysVCacheItemPool.php b/src/Cache/SysVCacheItemPool.php index c552d8d2e..5ceb955ec 100644 --- a/src/Cache/SysVCacheItemPool.php +++ b/src/Cache/SysVCacheItemPool.php @@ -36,7 +36,9 @@ class SysVCacheItemPool implements CacheItemPoolInterface const DEFAULT_PERM = 0600; - /** @var int */ + /** + * @var int + */ private $sysvKey; /** @@ -50,11 +52,11 @@ class SysVCacheItemPool implements CacheItemPoolInterface private $deferredItems; /** - * @var array + * @var array */ private $options; - /* + /** * @var bool */ private $hasLoadedItems = false; @@ -62,15 +64,14 @@ class SysVCacheItemPool implements CacheItemPoolInterface /** * Create a SystemV shared memory based CacheItemPool. * - * @param array $options [optional] Configuration options. - * @param int $options.variableKey The variable key for getting the data from - * the shared memory. **Defaults to** 1. - * @param $options.proj string The project identifier for ftok. This needs to - * be a one character string. **Defaults to** 'A'. - * @param $options.memsize int The memory size in bytes for shm_attach. - * **Defaults to** 10000. - * @param $options.perm int The permission for shm_attach. **Defaults to** - * 0600. + * @param array $options { + * [optional] Configuration options. + * + * @type int $variableKey The variable key for getting the data from the shared memory. **Defaults to** 1. + * @type string $proj The project identifier for ftok. This needs to be a one character string. **Defaults to** 'A'. + * @type int $memsize The memory size in bytes for shm_attach. **Defaults to** 10000. + * @type int $perm The permission for shm_attach. **Defaults to** 0600. + * } */ public function __construct($options = []) { @@ -90,14 +91,19 @@ public function __construct($options = []) $this->sysvKey = ftok(__FILE__, $this->options['proj']); } + /** + * @param mixed $key + * @return CacheItemInterface + */ public function getItem($key): CacheItemInterface { $this->loadItems(); - return current($this->getItems([$key])); + return current($this->getItems([$key])); // @phpstan-ignore-line } /** - * {@inheritdoc} + * @param array $keys + * @return iterable */ public function getItems(array $keys = []): iterable { diff --git a/src/Cache/TypedItem.php b/src/Cache/TypedItem.php index 7ad071068..72e9223b3 100644 --- a/src/Cache/TypedItem.php +++ b/src/Cache/TypedItem.php @@ -30,9 +30,9 @@ final class TypedItem implements CacheItemInterface private mixed $value; /** - * @var \DateTime|null + * @var \DateTimeInterface|null */ - private ?\DateTime $expiration; + private ?\DateTimeInterface $expiration; /** * @var bool @@ -103,18 +103,13 @@ public function expiresAt($expiration): static return $this; } - $implementationMessage = interface_exists('DateTimeInterface') - ? 'implement interface DateTimeInterface' - : 'be an instance of DateTime'; - $error = sprintf( - 'Argument 1 passed to %s::expiresAt() must %s, %s given', + 'Argument 1 passed to %s::expiresAt() must implement interface DateTimeInterface, %s given', get_class($this), - $implementationMessage, gettype($expiration) ); - $this->handleError($error); + throw new \TypeError($error); } /** @@ -133,25 +128,10 @@ public function expiresAfter($time): static 'instance of DateInterval or of the type integer, %s given'; $error = sprintf($message, get_class($this), gettype($time)); - $this->handleError($error); - } - - return $this; - } - - /** - * Handles an error. - * - * @param string $error - * @throws \TypeError - */ - private function handleError($error) - { - if (class_exists('TypeError')) { throw new \TypeError($error); } - trigger_error($error, \E_USER_ERROR); + return $this; } /** @@ -173,13 +153,12 @@ private function isValidExpiration($expiration) return true; } - if ($expiration instanceof \DateTime) { - return true; - } - return false; } + /** + * @return \DateTime + */ protected function currentTime() { return new \DateTime('now', new \DateTimeZone('UTC')); diff --git a/src/CacheTrait.php b/src/CacheTrait.php index 217ce8e2c..2ef829095 100644 --- a/src/CacheTrait.php +++ b/src/CacheTrait.php @@ -17,23 +17,42 @@ namespace Google\Auth; +use Psr\Cache\CacheItemPoolInterface; + trait CacheTrait { + /** + * @var int + */ private $maxKeyLength = 64; + /** + * @var array + */ + private $cacheConfig; + + /** + * @var ?CacheItemPoolInterface + */ + private $cache; + /** * Gets the cached value if it is present in the cache when that is * available. + * + * @param mixed $k + * + * @return mixed */ private function getCachedValue($k) { if (is_null($this->cache)) { - return; + return null; } $key = $this->getFullCacheKey($k); if (is_null($key)) { - return; + return null; } $cacheItem = $this->cache->getItem($key); @@ -44,16 +63,20 @@ private function getCachedValue($k) /** * Saves the value in the cache when that is available. + * + * @param mixed $k + * @param mixed $v + * @return mixed */ private function setCachedValue($k, $v) { if (is_null($this->cache)) { - return; + return null; } $key = $this->getFullCacheKey($k); if (is_null($key)) { - return; + return null; } $cacheItem = $this->cache->getItem($key); @@ -62,10 +85,14 @@ private function setCachedValue($k, $v) return $this->cache->save($cacheItem); } + /** + * @param null|string $key + * @return null|string + */ private function getFullCacheKey($key) { if (is_null($key)) { - return; + return null; } $key = $this->cacheConfig['prefix'] . $key; diff --git a/src/Credentials/AppIdentityCredentials.php b/src/Credentials/AppIdentityCredentials.php index 829344d03..db29438ab 100644 --- a/src/Credentials/AppIdentityCredentials.php +++ b/src/Credentials/AppIdentityCredentials.php @@ -28,6 +28,8 @@ use Google\Auth\SignBlobInterface; /** + * @deprecated + * * AppIdentityCredentials supports authorization on Google App Engine. * * It can be used to authorize requests using the AuthTokenMiddleware or @@ -61,14 +63,14 @@ class AppIdentityCredentials extends CredentialsLoader implements /** * Result of fetchAuthToken. * - * @var array + * @var array */ protected $lastReceivedToken; /** * Array of OAuth2 scopes to be requested. * - * @var array + * @var string[] */ private $scope; @@ -78,11 +80,11 @@ class AppIdentityCredentials extends CredentialsLoader implements private $clientName; /** - * @param array $scope One or more scopes. + * @param string|string[] $scope One or more scopes. */ - public function __construct($scope = array()) + public function __construct($scope = []) { - $this->scope = $scope; + $this->scope = is_array($scope) ? $scope : explode(' ', (string) $scope); } /** @@ -115,10 +117,12 @@ public static function onAppEngine() * the GuzzleHttp\ClientInterface instance passed in will not be used. * * @param callable $httpHandler callback which delivers psr7 request - * @return array A set of auth related metadata, containing the following - * keys: - * - access_token (string) - * - expiration_time (string) + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type string $expiration_time + * } */ public function fetchAuthToken(callable $httpHandler = null) { @@ -128,10 +132,8 @@ public function fetchAuthToken(callable $httpHandler = null) return []; } - // AppIdentityService expects an array when multiple scopes are supplied - $scope = is_array($this->scope) ? $this->scope : explode(' ', $this->scope); - - $token = AppIdentityService::getAccessToken($scope); + /** @phpstan-ignore-next-line */ + $token = AppIdentityService::getAccessToken($this->scope); $this->lastReceivedToken = $token; return $token; @@ -150,6 +152,7 @@ public function signBlob($stringToSign, $forceOpenSsl = false) { $this->checkAppEngineContext(); + /** @phpstan-ignore-next-line */ return base64_encode(AppIdentityService::signForApp($stringToSign)['signature']); } @@ -161,7 +164,7 @@ public function signBlob($stringToSign, $forceOpenSsl = false) * @param callable $httpHandler Not used by this type. * @return string|null */ - public function getProjectId(callable $httpHander = null) + public function getProjectId(callable $httpHandler = null) { try { $this->checkAppEngineContext(); @@ -169,6 +172,7 @@ public function getProjectId(callable $httpHander = null) return null; } + /** @phpstan-ignore-next-line */ return AppIdentityService::getApplicationId(); } @@ -186,6 +190,7 @@ public function getClientName(callable $httpHandler = null) $this->checkAppEngineContext(); if (!$this->clientName) { + /** @phpstan-ignore-next-line */ $this->clientName = AppIdentityService::getServiceAccountName(); } @@ -193,7 +198,7 @@ public function getClientName(callable $httpHandler = null) } /** - * @return array|null + * @return array{access_token:string,expires_at:int}|null */ public function getLastReceivedToken() { @@ -218,6 +223,9 @@ public function getCacheKey() return ''; } + /** + * @return void + */ private function checkAppEngineContext() { if (!self::onAppEngine() || !class_exists('google\appengine\api\app_identity\AppIdentityService')) { diff --git a/src/Credentials/GCECredentials.php b/src/Credentials/GCECredentials.php index c97e5d80f..c0442e7e0 100644 --- a/src/Credentials/GCECredentials.php +++ b/src/Credentials/GCECredentials.php @@ -126,6 +126,8 @@ class GCECredentials extends CredentialsLoader implements /** * Result of fetchAuthToken. + * + * @var array */ protected $lastReceivedToken; @@ -166,7 +168,7 @@ class GCECredentials extends CredentialsLoader implements /** * @param Iam $iam [optional] An IAM instance. - * @param string|array $scope [optional] the scope of the access request, + * @param string|string[] $scope [optional] the scope of the access request, * expressed either as an array or as a space-delimited string. * @param string $targetAudience [optional] The audience for the ID token. * @param string $quotaProject [optional] Specifies a project to bill for access @@ -297,7 +299,7 @@ private static function getProjectIdUri() */ public static function onAppEngineFlexible() { - return substr(getenv('GAE_INSTANCE'), 0, 4) === 'aef-'; + return substr((string) getenv('GAE_INSTANCE'), 0, 4) === 'aef-'; } /** @@ -351,15 +353,14 @@ public static function onGce(callable $httpHandler = null) * * @param callable $httpHandler callback which delivers psr7 request * - * @return array A set of auth related metadata, based on the token type. - * - * Access tokens have the following keys: - * - access_token (string) - * - expires_in (int) - * - token_type (string) - * ID tokens have the following keys: - * - id_token (string) + * @return array { + * A set of auth related metadata, based on the token type. * + * @type string $access_token for access tokens + * @type int $expires_in for access tokens + * @type string $token_type for access tokens + * @type string $id_token for ID tokens + * } * @throws \Exception */ public function fetchAuthToken(callable $httpHandler = null) @@ -402,7 +403,7 @@ public function getCacheKey() } /** - * @return array|null + * @return array{access_token:string,expires_at:int}|null */ public function getLastReceivedToken() { diff --git a/src/Credentials/IAMCredentials.php b/src/Credentials/IAMCredentials.php index 5f055d842..344bffdb5 100644 --- a/src/Credentials/IAMCredentials.php +++ b/src/Credentials/IAMCredentials.php @@ -36,8 +36,8 @@ class IAMCredentials private $token; /** - * @param $selector string the IAM selector - * @param $token string the IAM token + * @param string $selector the IAM selector + * @param string $token the IAM token */ public function __construct($selector, $token) { @@ -59,7 +59,7 @@ public function __construct($selector, $token) /** * export a callback function which updates runtime metadata. * - * @return array updateMetadata function + * @return callable updateMetadata function */ public function getUpdateMetadataFunc() { @@ -69,13 +69,13 @@ public function getUpdateMetadataFunc() /** * Updates metadata with the appropriate header metadata. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $unusedAuthUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request * Note: this param is unused here, only included here for * consistency with other credentials class * - * @return array updated metadata hashmap + * @return array updated metadata hashmap */ public function updateMetadata( $metadata, diff --git a/src/Credentials/InsecureCredentials.php b/src/Credentials/InsecureCredentials.php index dae894fab..9b9e24b11 100644 --- a/src/Credentials/InsecureCredentials.php +++ b/src/Credentials/InsecureCredentials.php @@ -27,7 +27,7 @@ class InsecureCredentials implements FetchAuthTokenInterface { /** - * @var array + * @var array{access_token:string} */ private $token = [ 'access_token' => '' @@ -37,9 +37,7 @@ class InsecureCredentials implements FetchAuthTokenInterface * Fetches the auth token. In this case it returns an empty string. * * @param callable $httpHandler - * @return array A set of auth related metadata, containing the following - * keys: - * - access_token (string) + * @return array{access_token:string} A set of auth related metadata */ public function fetchAuthToken(callable $httpHandler = null) { @@ -61,7 +59,7 @@ public function getCacheKey() * Fetches the last received token. In this case, it returns the same empty string * auth token. * - * @return array + * @return array{access_token:string} */ public function getLastReceivedToken() { diff --git a/src/Credentials/ServiceAccountCredentials.php b/src/Credentials/ServiceAccountCredentials.php index da972497e..ac3fd51dd 100644 --- a/src/Credentials/ServiceAccountCredentials.php +++ b/src/Credentials/ServiceAccountCredentials.php @@ -79,22 +79,22 @@ class ServiceAccountCredentials extends CredentialsLoader implements */ protected $quotaProject; - /* + /** * @var string|null */ protected $projectId; - /* - * @var array|null + /** + * @var array|null */ private $lastReceivedJwtAccessToken; - /* + /** * @var bool */ private $useJwtAccessWithScope = false; - /* + /** * @var ServiceAccountJwtAccessCredentials|null */ private $jwtAccessCredentials; @@ -102,9 +102,9 @@ class ServiceAccountCredentials extends CredentialsLoader implements /** * Create a new ServiceAccountCredentials. * - * @param string|array $scope the scope of the access request, expressed + * @param string|string[]|null $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. - * @param string|array $jsonKey JSON credential file path or JSON credentials + * @param string|array $jsonKey JSON credential file path or JSON credentials * as an associative array * @param string $sub an email address account to impersonate, in situations when * the service account has been delegated domain wide access. @@ -121,7 +121,7 @@ public function __construct( throw new \InvalidArgumentException('file does not exist'); } $jsonKeyStream = file_get_contents($jsonKey); - if (!$jsonKey = json_decode($jsonKeyStream, true)) { + if (!$jsonKey = json_decode((string) $jsonKeyStream, true)) { throw new \LogicException('invalid json for auth config'); } } @@ -169,6 +169,8 @@ public function __construct( * even when only scopes are supplied. Otherwise, * ServiceAccountJwtAccessCredentials is only called when no scopes and an * authUrl (audience) is suppled. + * + * @return void */ public function useJwtAccessWithScope() { @@ -178,11 +180,13 @@ public function useJwtAccessWithScope() /** * @param callable $httpHandler * - * @return array A set of auth related metadata, containing the following - * keys: - * - access_token (string) - * - expires_in (int) - * - token_type (string) + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_in + * @type string $token_type + * } */ public function fetchAuthToken(callable $httpHandler = null) { @@ -215,7 +219,7 @@ public function getCacheKey() } /** - * @return array + * @return array */ public function getLastReceivedToken() { @@ -242,10 +246,10 @@ public function getProjectId(callable $httpHandler = null) /** * Updates metadata with the authorization token. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request - * @return array updated metadata hashmap + * @return array updated metadata hashmap */ public function updateMetadata( $metadata, @@ -273,14 +277,17 @@ public function updateMetadata( return $updatedMetadata; } + /** + * @return ServiceAccountJwtAccessCredentials + */ private function createJwtAccessCredentials() { if (!$this->jwtAccessCredentials) { // Create credentials for self-signing a JWT (JwtAccess) - $credJson = array( + $credJson = [ 'private_key' => $this->auth->getSigningKey(), 'client_email' => $this->auth->getIssuer(), - ); + ]; $this->jwtAccessCredentials = new ServiceAccountJwtAccessCredentials( $credJson, $this->auth->getScope() @@ -293,6 +300,7 @@ private function createJwtAccessCredentials() /** * @param string $sub an email address account to impersonate, in situations when * the service account has been delegated domain wide access. + * @return void */ public function setSub($sub) { @@ -322,13 +330,16 @@ public function getQuotaProject() return $this->quotaProject; } + /** + * @return bool + */ private function useSelfSignedJwt() { // If claims are set, this call is for "id_tokens" if ($this->auth->getAdditionalClaims()) { return false; } - + // When true, ServiceAccountCredentials will always use JwtAccess for access tokens if ($this->useJwtAccessWithScope) { return true; diff --git a/src/Credentials/ServiceAccountJwtAccessCredentials.php b/src/Credentials/ServiceAccountJwtAccessCredentials.php index 6f5c28a8c..737229c15 100644 --- a/src/Credentials/ServiceAccountJwtAccessCredentials.php +++ b/src/Credentials/ServiceAccountJwtAccessCredentials.php @@ -49,15 +49,22 @@ class ServiceAccountJwtAccessCredentials extends CredentialsLoader implements /** * The quota project associated with the JSON credentials + * + * @var string */ protected $quotaProject; + /** + * @var string + */ + public $projectId; + /** * Create a new ServiceAccountJwtAccessCredentials. * - * @param string|array $jsonKey JSON credential file path or JSON credentials + * @param string|array $jsonKey JSON credential file path or JSON credentials * as an associative array - * @param string|array $scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. */ public function __construct($jsonKey, $scope = null) @@ -67,7 +74,7 @@ public function __construct($jsonKey, $scope = null) throw new \InvalidArgumentException('file does not exist'); } $jsonKeyStream = file_get_contents($jsonKey); - if (!$jsonKey = json_decode($jsonKeyStream, true)) { + if (!$jsonKey = json_decode((string) $jsonKeyStream, true)) { throw new \LogicException('invalid json for auth config'); } } @@ -100,10 +107,10 @@ public function __construct($jsonKey, $scope = null) /** * Updates metadata with the authorization token. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request - * @return array updated metadata hashmap + * @return array updated metadata hashmap */ public function updateMetadata( $metadata, @@ -125,9 +132,7 @@ public function updateMetadata( * * @param callable $httpHandler * - * @return array|void A set of auth related metadata, containing the - * following keys: - * - access_token (string) + * @return null|array{access_token:string} A set of auth related metadata */ public function fetchAuthToken(callable $httpHandler = null) { @@ -148,7 +153,7 @@ public function fetchAuthToken(callable $httpHandler = null) // Set the self-signed access token in OAuth2 for getLastReceivedToken $this->auth->setAccessToken($access_token); - return array('access_token' => $access_token); + return ['access_token' => $access_token]; } /** @@ -160,7 +165,7 @@ public function getCacheKey() } /** - * @return array + * @return array */ public function getLastReceivedToken() { diff --git a/src/Credentials/UserRefreshCredentials.php b/src/Credentials/UserRefreshCredentials.php index b17ce5fcd..dc009dd22 100644 --- a/src/Credentials/UserRefreshCredentials.php +++ b/src/Credentials/UserRefreshCredentials.php @@ -43,15 +43,17 @@ class UserRefreshCredentials extends CredentialsLoader implements GetQuotaProjec /** * The quota project associated with the JSON credentials + * + * @var string */ protected $quotaProject; /** * Create a new UserRefreshCredentials. * - * @param string|array $scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. - * @param string|array $jsonKey JSON credential file path or JSON credentials + * @param string|array $jsonKey JSON credential file path or JSON credentials * as an associative array */ public function __construct( @@ -62,8 +64,8 @@ public function __construct( if (!file_exists($jsonKey)) { throw new \InvalidArgumentException('file does not exist'); } - $jsonKeyStream = file_get_contents($jsonKey); - if (!$jsonKey = json_decode($jsonKeyStream, true)) { + $json = file_get_contents($jsonKey); + if (!$jsonKey = json_decode((string) $json, true)) { throw new \LogicException('invalid json for auth config'); } } @@ -97,13 +99,15 @@ public function __construct( /** * @param callable $httpHandler * - * @return array A set of auth related metadata, containing the following - * keys: - * - access_token (string) - * - expires_in (int) - * - scope (string) - * - token_type (string) - * - id_token (string) + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_in + * @type string $scope + * @type string $token_type + * @type string $id_token + * } */ public function fetchAuthToken(callable $httpHandler = null) { @@ -119,7 +123,7 @@ public function getCacheKey() } /** - * @return array + * @return array */ public function getLastReceivedToken() { diff --git a/src/CredentialsLoader.php b/src/CredentialsLoader.php index c0c3c72ba..01fe2f8ee 100644 --- a/src/CredentialsLoader.php +++ b/src/CredentialsLoader.php @@ -20,7 +20,6 @@ use Google\Auth\Credentials\InsecureCredentials; use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\Credentials\UserRefreshCredentials; -use GuzzleHttp\ClientInterface; use RuntimeException; use UnexpectedValueException; @@ -60,24 +59,6 @@ private static function isOnWindows() return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; } - /** - * Returns the currently available major Guzzle version. - * - * @return int - */ - private static function getGuzzleMajorVersion() - { - if (defined('GuzzleHttp\ClientInterface::MAJOR_VERSION')) { - return ClientInterface::MAJOR_VERSION; - } - - if (defined('GuzzleHttp\ClientInterface::VERSION')) { - return (int) substr(ClientInterface::VERSION, 0, 1); - } - - throw new \Exception('Version not supported'); - } - /** * Load a JSON key from the path specified in the environment. * @@ -85,20 +66,20 @@ private static function getGuzzleMajorVersion() * variable GOOGLE_APPLICATION_CREDENTIALS. Return null if * GOOGLE_APPLICATION_CREDENTIALS is not specified. * - * @return array|null JSON key | null + * @return array|null JSON key | null */ public static function fromEnv() { $path = getenv(self::ENV_VAR); if (empty($path)) { - return; + return null; } if (!file_exists($path)) { $cause = 'file ' . $path . ' does not exist'; throw new \DomainException(self::unableToReadEnv($cause)); } $jsonKey = file_get_contents($path); - return json_decode($jsonKey, true); + return json_decode((string) $jsonKey, true); } /** @@ -111,7 +92,7 @@ public static function fromEnv() * * If the file does not exist, this returns null. * - * @return array|null JSON key | null + * @return array|null JSON key | null */ public static function fromWellKnownFile() { @@ -123,19 +104,19 @@ public static function fromWellKnownFile() $path[] = self::WELL_KNOWN_PATH; $path = implode(DIRECTORY_SEPARATOR, $path); if (!file_exists($path)) { - return; + return null; } $jsonKey = file_get_contents($path); - return json_decode($jsonKey, true); + return json_decode((string) $jsonKey, true); } /** * Create a new Credentials instance. * - * @param string|array $scope the scope of the access request, expressed + * @param string|string[] $scope the scope of the access request, expressed * either as an Array or as a space-delimited String. - * @param array $jsonKey the JSON credentials. - * @param string|array $defaultScope The default scope to use if no + * @param array $jsonKey the JSON credentials. + * @param string|string[] $defaultScope The default scope to use if no * user-defined scopes exist, expressed either as an Array or as a * space-delimited string. * @@ -167,7 +148,7 @@ public static function makeCredentials( * Create an authorized HTTP Client from an instance of FetchAuthTokenInterface. * * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token - * @param array $httpClientOptions (optional) Array of request options to apply. + * @param array $httpClientOptions (optional) Array of request options to apply. * @param callable $httpHandler (optional) http client to fetch the token. * @param callable $tokenCallback (optional) function to be called when a new token is fetched. * @return \GuzzleHttp\Client @@ -178,18 +159,6 @@ public static function makeHttpClient( callable $httpHandler = null, callable $tokenCallback = null ) { - if (self::getGuzzleMajorVersion() === 5) { - $client = new \GuzzleHttp\Client($httpClientOptions); - $client->setDefaultOption('auth', 'google_auth'); - $subscriber = new Subscriber\AuthTokenSubscriber( - $fetcher, - $httpHandler, - $tokenCallback - ); - $client->getEmitter()->attach($subscriber); - return $client; - } - $middleware = new Middleware\AuthTokenMiddleware( $fetcher, $httpHandler, @@ -217,7 +186,7 @@ public static function makeInsecureCredentials() /** * export a callback function which updates runtime metadata. * - * @return array updateMetadata function + * @return callable updateMetadata function * @deprecated */ public function getUpdateMetadataFunc() @@ -228,10 +197,10 @@ public function getUpdateMetadataFunc() /** * Updates metadata with the authorization token. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request - * @return array updated metadata hashmap + * @return array updated metadata hashmap */ public function updateMetadata( $metadata, @@ -288,6 +257,9 @@ public static function shouldLoadClientCertSource() return filter_var(getenv(self::MTLS_CERT_ENV_VAR), FILTER_VALIDATE_BOOLEAN); } + /** + * @return array{cert_provider_command:string[]}|null + */ private static function loadDefaultClientCertSourceFile() { $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME'; @@ -296,7 +268,7 @@ private static function loadDefaultClientCertSourceFile() return null; } $jsonKey = file_get_contents($path); - $clientCertSourceJson = json_decode($jsonKey, true); + $clientCertSourceJson = json_decode((string) $jsonKey, true); if (!$clientCertSourceJson) { throw new UnexpectedValueException('Invalid client cert source JSON'); } diff --git a/src/FetchAuthTokenCache.php b/src/FetchAuthTokenCache.php index 7b0258432..0f870977f 100644 --- a/src/FetchAuthTokenCache.php +++ b/src/FetchAuthTokenCache.php @@ -37,19 +37,9 @@ class FetchAuthTokenCache implements */ private $fetcher; - /** - * @var array - */ - private $cacheConfig; - - /** - * @var CacheItemPoolInterface - */ - private $cache; - /** * @param FetchAuthTokenInterface $fetcher A credentials fetcher - * @param array $cacheConfig Configuration for the cache + * @param array $cacheConfig Configuration for the cache * @param CacheItemPoolInterface $cache */ public function __construct( @@ -72,7 +62,7 @@ public function __construct( * from the supplied fetcher. * * @param callable $httpHandler callback which delivers psr7 request - * @return array the response + * @return array the response * @throws \Exception */ public function fetchAuthToken(callable $httpHandler = null) @@ -97,7 +87,7 @@ public function getCacheKey() } /** - * @return array|null + * @return array|null */ public function getLastReceivedToken() { @@ -118,7 +108,7 @@ public function getClientName(callable $httpHandler = null) 'Google\Auth\SignBlobInterface' ); } - + return $this->fetcher->getClientName($httpHandler); } @@ -164,6 +154,8 @@ public function getQuotaProject() if ($this->fetcher instanceof GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } + + return null; } /* @@ -189,10 +181,10 @@ public function getProjectId(callable $httpHandler = null) /** * Updates metadata with the authorization token. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request - * @return array updated metadata hashmap + * @return array updated metadata hashmap * @throws \RuntimeException If the fetcher does not implement * `Google\Auth\UpdateMetadataInterface`. */ @@ -233,6 +225,10 @@ public function updateMetadata( return $newMetadata; } + /** + * @param string|null $authUri + * @return array|null + */ private function fetchAuthTokenFromCache($authUri = null) { // Use the cached value if its available. @@ -263,6 +259,11 @@ private function fetchAuthTokenFromCache($authUri = null) return null; } + /** + * @param array $authToken + * @param string|null $authUri + * @return void + */ private function saveAuthTokenInCache($authToken, $authUri = null) { if (isset($authToken['access_token']) || diff --git a/src/FetchAuthTokenInterface.php b/src/FetchAuthTokenInterface.php index 4bf4d27ff..64659550b 100644 --- a/src/FetchAuthTokenInterface.php +++ b/src/FetchAuthTokenInterface.php @@ -26,7 +26,7 @@ interface FetchAuthTokenInterface * Fetches the auth tokens based on the current state. * * @param callable $httpHandler callback which delivers psr7 request - * @return array a hash of auth tokens + * @return array a hash of auth tokens */ public function fetchAuthToken(callable $httpHandler = null); @@ -43,11 +43,11 @@ public function getCacheKey(); * Returns an associative array with the token and * expiration time. * - * @return null|array { - * The last received access token. + * @return null|array { + * The last received access token. * - * @var string $access_token The access token string. - * @var int $expires_at The time the token expires as a UNIX timestamp. + * @type string $access_token The access token string. + * @type int $expires_at The time the token expires as a UNIX timestamp. * } */ public function getLastReceivedToken(); diff --git a/src/GCECache.php b/src/GCECache.php index 82123ecd5..804abdbe2 100644 --- a/src/GCECache.php +++ b/src/GCECache.php @@ -42,17 +42,7 @@ class GCECache use CacheTrait; /** - * @var array - */ - private $cacheConfig; - - /** - * @var CacheItemPoolInterface - */ - private $cache; - - /** - * @param array $cacheConfig Configuration for the cache + * @param array $cacheConfig Configuration for the cache * @param CacheItemPoolInterface $cache */ public function __construct( diff --git a/src/HttpHandler/Guzzle5HttpHandler.php b/src/HttpHandler/Guzzle5HttpHandler.php index 18ba02775..1eff0d1ab 100644 --- a/src/HttpHandler/Guzzle5HttpHandler.php +++ b/src/HttpHandler/Guzzle5HttpHandler.php @@ -25,6 +25,9 @@ use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +/** + * @deprecated + */ class Guzzle5HttpHandler { /** diff --git a/src/HttpHandler/Guzzle6HttpHandler.php b/src/HttpHandler/Guzzle6HttpHandler.php index aaa7b4385..53a8865fd 100644 --- a/src/HttpHandler/Guzzle6HttpHandler.php +++ b/src/HttpHandler/Guzzle6HttpHandler.php @@ -39,7 +39,7 @@ public function __construct(ClientInterface $client) * Accepts a PSR-7 request and an array of options and returns a PSR-7 response. * * @param RequestInterface $request - * @param array $options + * @param array $options * @return ResponseInterface */ public function __invoke(RequestInterface $request, array $options = []) @@ -51,7 +51,7 @@ public function __invoke(RequestInterface $request, array $options = []) * Accepts a PSR-7 request and an array of options and returns a PromiseInterface * * @param RequestInterface $request - * @param array $options + * @param array $options * * @return \GuzzleHttp\Promise\PromiseInterface */ diff --git a/src/HttpHandler/HttpHandlerFactory.php b/src/HttpHandler/HttpHandlerFactory.php index 41ccde878..d92419de0 100644 --- a/src/HttpHandler/HttpHandlerFactory.php +++ b/src/HttpHandler/HttpHandlerFactory.php @@ -36,6 +36,7 @@ public static function build(ClientInterface $client = null) if (defined('GuzzleHttp\ClientInterface::MAJOR_VERSION')) { $version = ClientInterface::MAJOR_VERSION; } elseif (defined('GuzzleHttp\ClientInterface::VERSION')) { + /** @phpstan-ignore-next-line */ $version = (int) substr(ClientInterface::VERSION, 0, 1); } diff --git a/src/Iam.php b/src/Iam.php index ede722c10..943ecf2d6 100644 --- a/src/Iam.php +++ b/src/Iam.php @@ -57,7 +57,7 @@ public function __construct(callable $httpHandler = null) * @param string $email The service account email. * @param string $accessToken An access token from the service account. * @param string $stringToSign The string to be signed. - * @param array $delegates [optional] A list of service account emails to + * @param array $delegates [optional] A list of service account emails to * add to the delegate chain. If omitted, the value of `$email` will * be used. * @return string The signed string, base64-encoded. diff --git a/src/Middleware/AuthTokenMiddleware.php b/src/Middleware/AuthTokenMiddleware.php index 02bb1744c..07bcdfdd5 100644 --- a/src/Middleware/AuthTokenMiddleware.php +++ b/src/Middleware/AuthTokenMiddleware.php @@ -35,7 +35,7 @@ class AuthTokenMiddleware { /** - * @var callback + * @var callable */ private $httpHandler; @@ -45,7 +45,7 @@ class AuthTokenMiddleware private $fetcher; /** - * @var callable + * @var ?callable */ private $tokenCallback; @@ -115,7 +115,7 @@ public function __invoke(callable $handler) /** * Call fetcher to fetch the token. * - * @return string + * @return string|null */ private function fetchToken() { @@ -137,12 +137,19 @@ private function fetchToken() if (array_key_exists('id_token', $auth_tokens)) { return $auth_tokens['id_token']; } + + return null; } + /** + * @return string|null + */ private function getQuotaProject() { if ($this->fetcher instanceof GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } + + return null; } } diff --git a/src/Middleware/ProxyAuthTokenMiddleware.php b/src/Middleware/ProxyAuthTokenMiddleware.php index a1e81c4e2..0f9ee429f 100644 --- a/src/Middleware/ProxyAuthTokenMiddleware.php +++ b/src/Middleware/ProxyAuthTokenMiddleware.php @@ -35,7 +35,7 @@ class ProxyAuthTokenMiddleware { /** - * @var callback + * @var callable */ private $httpHandler; @@ -45,7 +45,7 @@ class ProxyAuthTokenMiddleware private $fetcher; /** - * @var callable + * @var ?callable */ private $tokenCallback; @@ -115,7 +115,7 @@ public function __invoke(callable $handler) /** * Call fetcher to fetch the token. * - * @return string + * @return string|null */ private function fetchToken() { @@ -137,12 +137,19 @@ private function fetchToken() if (array_key_exists('id_token', $auth_tokens)) { return $auth_tokens['id_token']; } + + return null; } + /** + * @return string|null; + */ private function getQuotaProject() { if ($this->fetcher instanceof GetQuotaProjectInterface) { return $this->fetcher->getQuotaProject(); } + + return null; } } diff --git a/src/Middleware/ScopedAccessTokenMiddleware.php b/src/Middleware/ScopedAccessTokenMiddleware.php index ecbb6596b..8bb1d7a0b 100644 --- a/src/Middleware/ScopedAccessTokenMiddleware.php +++ b/src/Middleware/ScopedAccessTokenMiddleware.php @@ -39,23 +39,13 @@ class ScopedAccessTokenMiddleware const DEFAULT_CACHE_LIFETIME = 1500; - /** - * @var CacheItemPoolInterface - */ - private $cache; - - /** - * @var array configuration - */ - private $cacheConfig; - /** * @var callable */ private $tokenFunc; /** - * @var array|string + * @var array|string */ private $scopes; @@ -63,8 +53,8 @@ class ScopedAccessTokenMiddleware * Creates a new ScopedAccessTokenMiddleware. * * @param callable $tokenFunc a token generator function - * @param array|string $scopes the token authentication scopes - * @param array $cacheConfig configuration for the cache when it's present + * @param array|string $scopes the token authentication scopes + * @param array $cacheConfig configuration for the cache when it's present * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface */ public function __construct( diff --git a/src/Middleware/SimpleMiddleware.php b/src/Middleware/SimpleMiddleware.php index bc913c1b4..69404304f 100644 --- a/src/Middleware/SimpleMiddleware.php +++ b/src/Middleware/SimpleMiddleware.php @@ -29,7 +29,7 @@ class SimpleMiddleware { /** - * @var array + * @var array */ private $config; @@ -39,7 +39,7 @@ class SimpleMiddleware * The configuration array expects one option * - key: required, otherwise InvalidArgumentException is thrown * - * @param array $config Configuration array + * @param array $config Configuration array */ public function __construct(array $config) { diff --git a/src/OAuth2.php b/src/OAuth2.php index 5b6b4ec74..e9404412f 100644 --- a/src/OAuth2.php +++ b/src/OAuth2.php @@ -43,6 +43,8 @@ class OAuth2 implements FetchAuthTokenInterface /** * TODO: determine known methods from the keys of JWT::methods. + * + * @var array */ public static $knownSigningAlgorithms = array( 'HS256', @@ -54,7 +56,7 @@ class OAuth2 implements FetchAuthTokenInterface /** * The well known grant types. * - * @var array + * @var array */ public static $knownGrantTypes = array( 'authorization_code', @@ -68,7 +70,7 @@ class OAuth2 implements FetchAuthTokenInterface * The authorization server's HTTP endpoint capable of * authenticating the end-user and obtaining authorization. * - * @var UriInterface + * @var ?UriInterface */ private $authorizationUri; @@ -84,7 +86,7 @@ class OAuth2 implements FetchAuthTokenInterface /** * The redirection URI used in the initial request. * - * @var string + * @var ?string */ private $redirectUri; @@ -107,14 +109,14 @@ class OAuth2 implements FetchAuthTokenInterface /** * The resource owner's username. * - * @var string + * @var ?string */ private $username; /** * The resource owner's password. * - * @var string + * @var ?string */ private $password; @@ -122,7 +124,7 @@ class OAuth2 implements FetchAuthTokenInterface * The scope of the access request, expressed either as an Array or as a * space-delimited string. * - * @var array + * @var ?array */ private $scope; @@ -138,14 +140,14 @@ class OAuth2 implements FetchAuthTokenInterface * * Only used by the authorization code access grant type. * - * @var string + * @var ?string */ private $code; /** * The issuer ID when using assertion profile. * - * @var string + * @var ?string */ private $issuer; @@ -173,7 +175,7 @@ class OAuth2 implements FetchAuthTokenInterface /** * The signing key when using assertion profile. * - * @var string + * @var ?string */ private $signingKey; @@ -187,14 +189,14 @@ class OAuth2 implements FetchAuthTokenInterface /** * The signing algorithm when using an assertion profile. * - * @var string + * @var ?string */ private $signingAlgorithm; /** * The refresh token associated with the access token to be refreshed. * - * @var string + * @var ?string */ private $refreshToken; @@ -215,7 +217,7 @@ class OAuth2 implements FetchAuthTokenInterface /** * The lifetime in seconds of the current access token. * - * @var int + * @var ?int */ private $expiresIn; @@ -223,7 +225,7 @@ class OAuth2 implements FetchAuthTokenInterface * The expiration time of the access token as a number of seconds since the * unix epoch. * - * @var int + * @var ?int */ private $expiresAt; @@ -231,26 +233,30 @@ class OAuth2 implements FetchAuthTokenInterface * The issue time of the access token as a number of seconds since the unix * epoch. * - * @var int + * @var ?int */ private $issuedAt; /** * The current grant type. * - * @var string + * @var ?string */ private $grantType; /** * When using an extension grant type, this is the set of parameters used by * that extension. + * + * @var array */ private $extensionParams; /** * When using the toJwt function, these claims will be added to the JWT * payload. + * + * @var array */ private $additionalClaims; @@ -320,7 +326,7 @@ class OAuth2 implements FetchAuthTokenInterface * When using an extension grant type, this is the set of parameters used * by that extension. * - * @param array $config Configuration array + * @param array $config Configuration array */ public function __construct(array $config) { @@ -380,14 +386,14 @@ public function __construct(array $config) * `\InvalidArgumentException`. * * @param string $publicKey The public key to use to authenticate the token - * @param array $allowed_algs List of supported verification algorithms + * @param array $allowed_algs List of supported verification algorithms * @throws \DomainException if the token is missing an audience. * @throws \DomainException if the audience does not match the one set in * the OAuth2 class instance. * @throws \UnexpectedValueException If the token is invalid - * @throws SignatureInvalidException If the signature is invalid. - * @throws BeforeValidException If the token is not yet valid. - * @throws ExpiredException If the token has expired. + * @throws \Firebase\JWT\SignatureInvalidException If the signature is invalid. + * @throws \Firebase\JWT\BeforeValidException If the token is not yet valid. + * @throws \Firebase\JWT\ExpiredException If the token has expired. * @return null|object */ public function verifyIdToken($publicKey = null, $allowed_algs = array()) @@ -411,7 +417,7 @@ public function verifyIdToken($publicKey = null, $allowed_algs = array()) /** * Obtains the encoded jwt from the instance data. * - * @param array $config array optional configuration parameters + * @param array $config array optional configuration parameters * @return string */ public function toJwt(array $config = []) @@ -525,7 +531,7 @@ public function generateCredentialsRequest() * Fetches the auth tokens based on the current state. * * @param callable $httpHandler callback which delivers psr7 request - * @return array the response + * @return array the response */ public function fetchAuthToken(callable $httpHandler = null) { @@ -545,7 +551,7 @@ public function fetchAuthToken(callable $httpHandler = null) * * The key is derived from the scopes. * - * @return string a key that may be used to cache the auth token. + * @return ?string a key that may be used to cache the auth token. */ public function getCacheKey() { @@ -565,7 +571,7 @@ public function getCacheKey() * Parses the fetched tokens. * * @param ResponseInterface $resp the response. - * @return array the tokens parsed from the response body. + * @return array the tokens parsed from the response body. * @throws \Exception */ public function parseTokenResponse(ResponseInterface $resp) @@ -600,7 +606,7 @@ public function parseTokenResponse(ResponseInterface $resp) * ]); * ``` * - * @param array $config + * @param array $config * The configuration parameters related to the token. * * - refresh_token @@ -621,6 +627,7 @@ public function parseTokenResponse(ResponseInterface $resp) * * - issued_at * The timestamp that the token was issued at. + * @return void */ public function updateToken(array $config) { @@ -654,7 +661,7 @@ public function updateToken(array $config) /** * Builds the authorization Uri that the user should be redirected to. * - * @param array $config configuration options that customize the return url + * @param array $config configuration options that customize the return url * @return UriInterface the authorization Url. * @throws InvalidArgumentException */ @@ -712,6 +719,7 @@ public function buildFullAuthorizationUri(array $config = []) * the end-user and obtaining authorization. * * @param string $uri + * @return void */ public function setAuthorizationUri($uri) { @@ -722,7 +730,7 @@ public function setAuthorizationUri($uri) * Gets the authorization server's HTTP endpoint capable of authenticating * the end-user and obtaining authorization. * - * @return UriInterface + * @return ?UriInterface */ public function getAuthorizationUri() { @@ -733,7 +741,7 @@ public function getAuthorizationUri() * Gets the authorization server's HTTP endpoint capable of issuing tokens * and refreshing expired tokens. * - * @return string + * @return ?UriInterface */ public function getTokenCredentialUri() { @@ -745,6 +753,7 @@ public function getTokenCredentialUri() * and refreshing expired tokens. * * @param string $uri + * @return void */ public function setTokenCredentialUri($uri) { @@ -754,7 +763,7 @@ public function setTokenCredentialUri($uri) /** * Gets the redirection URI used in the initial request. * - * @return string + * @return ?string */ public function getRedirectUri() { @@ -764,7 +773,8 @@ public function getRedirectUri() /** * Sets the redirection URI used in the initial request. * - * @param string $uri + * @param ?string $uri + * @return void */ public function setRedirectUri($uri) { @@ -789,7 +799,7 @@ public function setRedirectUri($uri) /** * Gets the scope of the access requests as a space-delimited String. * - * @return string + * @return ?string */ public function getScope() { @@ -804,7 +814,8 @@ public function getScope() * Sets the scope of the access request, expressed either as an Array or as * a space-delimited String. * - * @param string|array $scope + * @param string|array|null $scope + * @return void * @throws InvalidArgumentException */ public function setScope($scope) @@ -833,7 +844,7 @@ public function setScope($scope) /** * Gets the current grant type. * - * @return string + * @return ?string */ public function getGrantType() { @@ -865,7 +876,8 @@ public function getGrantType() /** * Sets the current grant type. * - * @param $grantType + * @param string $grantType + * @return void * @throws InvalidArgumentException */ public function setGrantType($grantType) @@ -897,6 +909,7 @@ public function getState() * Sets an arbitrary string designed to allow the client to maintain state. * * @param string $state + * @return void */ public function setState($state) { @@ -905,6 +918,8 @@ public function setState($state) /** * Gets the authorization code issued to this client. + * + * @return string */ public function getCode() { @@ -915,6 +930,7 @@ public function getCode() * Sets the authorization code issued to this client. * * @param string $code + * @return void */ public function setCode($code) { @@ -923,6 +939,8 @@ public function setCode($code) /** * Gets the resource owner's username. + * + * @return string */ public function getUsername() { @@ -933,6 +951,7 @@ public function getUsername() * Sets the resource owner's username. * * @param string $username + * @return void */ public function setUsername($username) { @@ -941,6 +960,8 @@ public function setUsername($username) /** * Gets the resource owner's password. + * + * @return string */ public function getPassword() { @@ -950,7 +971,8 @@ public function getPassword() /** * Sets the resource owner's password. * - * @param $password + * @param string $password + * @return void */ public function setPassword($password) { @@ -960,6 +982,8 @@ public function setPassword($password) /** * Sets a unique identifier issued to the client to identify itself to the * authorization server. + * + * @return string */ public function getClientId() { @@ -970,7 +994,8 @@ public function getClientId() * Sets a unique identifier issued to the client to identify itself to the * authorization server. * - * @param $clientId + * @param string $clientId + * @return void */ public function setClientId($clientId) { @@ -980,6 +1005,8 @@ public function setClientId($clientId) /** * Gets a shared symmetric secret issued by the authorization server, which * is used to authenticate the client. + * + * @return string */ public function getClientSecret() { @@ -990,7 +1017,8 @@ public function getClientSecret() * Sets a shared symmetric secret issued by the authorization server, which * is used to authenticate the client. * - * @param $clientSecret + * @param string $clientSecret + * @return void */ public function setClientSecret($clientSecret) { @@ -999,6 +1027,8 @@ public function setClientSecret($clientSecret) /** * Gets the Issuer ID when using assertion profile. + * + * @return ?string */ public function getIssuer() { @@ -1009,6 +1039,7 @@ public function getIssuer() * Sets the Issuer ID when using assertion profile. * * @param string $issuer + * @return void */ public function setIssuer($issuer) { @@ -1017,6 +1048,8 @@ public function setIssuer($issuer) /** * Gets the target sub when issuing assertions. + * + * @return ?string */ public function getSub() { @@ -1027,6 +1060,7 @@ public function getSub() * Sets the target sub when issuing assertions. * * @param string $sub + * @return void */ public function setSub($sub) { @@ -1035,6 +1069,8 @@ public function setSub($sub) /** * Gets the target audience when issuing assertions. + * + * @return ?string */ public function getAudience() { @@ -1045,6 +1081,7 @@ public function getAudience() * Sets the target audience when issuing assertions. * * @param string $audience + * @return void */ public function setAudience($audience) { @@ -1053,6 +1090,8 @@ public function setAudience($audience) /** * Gets the signing key when using an assertion profile. + * + * @return ?string */ public function getSigningKey() { @@ -1063,6 +1102,7 @@ public function getSigningKey() * Sets the signing key when using an assertion profile. * * @param string $signingKey + * @return void */ public function setSigningKey($signingKey) { @@ -1072,7 +1112,7 @@ public function setSigningKey($signingKey) /** * Gets the signing key id when using an assertion profile. * - * @return string + * @return ?string */ public function getSigningKeyId() { @@ -1083,6 +1123,7 @@ public function getSigningKeyId() * Sets the signing key id when using an assertion profile. * * @param string $signingKeyId + * @return void */ public function setSigningKeyId($signingKeyId) { @@ -1092,7 +1133,7 @@ public function setSigningKeyId($signingKeyId) /** * Gets the signing algorithm when using an assertion profile. * - * @return string + * @return ?string */ public function getSigningAlgorithm() { @@ -1102,7 +1143,8 @@ public function getSigningAlgorithm() /** * Sets the signing algorithm when using an assertion profile. * - * @param string $signingAlgorithm + * @param ?string $signingAlgorithm + * @return void */ public function setSigningAlgorithm($signingAlgorithm) { @@ -1118,6 +1160,8 @@ public function setSigningAlgorithm($signingAlgorithm) /** * Gets the set of parameters used by extension when using an extension * grant type. + * + * @return array */ public function getExtensionParams() { @@ -1128,7 +1172,8 @@ public function getExtensionParams() * Sets the set of parameters used by extension when using an extension * grant type. * - * @param $extensionParams + * @param array $extensionParams + * @return void */ public function setExtensionParams($extensionParams) { @@ -1137,6 +1182,8 @@ public function setExtensionParams($extensionParams) /** * Gets the number of seconds assertions are valid for. + * + * @return int */ public function getExpiry() { @@ -1147,6 +1194,7 @@ public function getExpiry() * Sets the number of seconds assertions are valid for. * * @param int $expiry + * @return void */ public function setExpiry($expiry) { @@ -1155,6 +1203,8 @@ public function setExpiry($expiry) /** * Gets the lifetime of the access token in seconds. + * + * @return int */ public function getExpiresIn() { @@ -1164,7 +1214,8 @@ public function getExpiresIn() /** * Sets the lifetime of the access token in seconds. * - * @param int $expiresIn + * @param ?int $expiresIn + * @return void */ public function setExpiresIn($expiresIn) { @@ -1180,7 +1231,7 @@ public function setExpiresIn($expiresIn) /** * Gets the time the current access token expires at. * - * @return int + * @return ?int */ public function getExpiresAt() { @@ -1212,6 +1263,7 @@ public function isExpired() * Sets the time the current access token expires at. * * @param int $expiresAt + * @return void */ public function setExpiresAt($expiresAt) { @@ -1220,6 +1272,8 @@ public function setExpiresAt($expiresAt) /** * Gets the time the current access token was issued at. + * + * @return ?int */ public function getIssuedAt() { @@ -1230,6 +1284,7 @@ public function getIssuedAt() * Sets the time the current access token was issued at. * * @param int $issuedAt + * @return void */ public function setIssuedAt($issuedAt) { @@ -1238,6 +1293,8 @@ public function setIssuedAt($issuedAt) /** * Gets the current access token. + * + * @return ?string */ public function getAccessToken() { @@ -1248,6 +1305,7 @@ public function getAccessToken() * Sets the current access token. * * @param string $accessToken + * @return void */ public function setAccessToken($accessToken) { @@ -1256,6 +1314,8 @@ public function setAccessToken($accessToken) /** * Gets the current ID token. + * + * @return ?string */ public function getIdToken() { @@ -1265,7 +1325,8 @@ public function getIdToken() /** * Sets the current ID token. * - * @param $idToken + * @param string $idToken + * @return void */ public function setIdToken($idToken) { @@ -1274,6 +1335,8 @@ public function setIdToken($idToken) /** * Gets the refresh token associated with the current access token. + * + * @return ?string */ public function getRefreshToken() { @@ -1283,7 +1346,8 @@ public function getRefreshToken() /** * Sets the refresh token associated with the current access token. * - * @param $refreshToken + * @param string $refreshToken + * @return void */ public function setRefreshToken($refreshToken) { @@ -1293,7 +1357,8 @@ public function setRefreshToken($refreshToken) /** * Sets additional claims to be included in the JWT token * - * @param array $additionalClaims + * @param array $additionalClaims + * @return void */ public function setAdditionalClaims(array $additionalClaims) { @@ -1303,7 +1368,7 @@ public function setAdditionalClaims(array $additionalClaims) /** * Gets the additional claims to be included in the JWT token. * - * @return array + * @return array */ public function getAdditionalClaims() { @@ -1313,7 +1378,7 @@ public function getAdditionalClaims() /** * The expiration of the last received token. * - * @return array|null + * @return array|null */ public function getLastReceivedToken() { @@ -1362,13 +1427,13 @@ public function getClientName(callable $httpHandler = null) /** * @todo handle uri as array * - * @param string $uri + * @param ?string $uri * @return null|UriInterface */ private function coerceUri($uri) { if (is_null($uri)) { - return; + return null; } return Utils::uriFor($uri); @@ -1376,8 +1441,8 @@ private function coerceUri($uri) /** * @param string $idToken - * @param string|array|null $publicKey - * @param array $allowedAlgs + * @param string|array|null $publicKey + * @param array $allowedAlgs * @return object */ private function jwtDecode($idToken, $publicKey, $allowedAlgs) @@ -1385,6 +1450,13 @@ private function jwtDecode($idToken, $publicKey, $allowedAlgs) return JWT::decode($idToken, $publicKey, $allowedAlgs); } + /** + * @param array $assertion + * @param string $signingKey + * @param string $signingAlgorithm + * @param string $signingKeyId + * @return string + */ private function jwtEncode($assertion, $signingKey, $signingAlgorithm, $signingKeyId = null) { return JWT::encode( @@ -1410,8 +1482,8 @@ private function isAbsoluteUri($uri) } /** - * @param array $params - * @return array + * @param array $params + * @return array */ private function addClientCredentials(&$params) { diff --git a/src/UpdateMetadataInterface.php b/src/UpdateMetadataInterface.php index d28b75c5f..6d2e7d5d5 100644 --- a/src/UpdateMetadataInterface.php +++ b/src/UpdateMetadataInterface.php @@ -28,10 +28,10 @@ interface UpdateMetadataInterface /** * Updates metadata with the authorization token. * - * @param array $metadata metadata hashmap + * @param array $metadata metadata hashmap * @param string $authUri optional auth uri * @param callable $httpHandler callback which delivers psr7 request - * @return array updated metadata hashmap + * @return array updated metadata hashmap */ public function updateMetadata( $metadata, diff --git a/tests/CacheTraitTest.php b/tests/CacheTraitTest.php index ac93eb5de..5c02eca76 100644 --- a/tests/CacheTraitTest.php +++ b/tests/CacheTraitTest.php @@ -171,9 +171,6 @@ class CacheTraitImplementation { use CacheTrait; - private $cache; - private $cacheConfig; - public function __construct(array $config = []) { $this->key = array_key_exists('key', $config) ? $config['key'] : 'key';