Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.55% covered (success)
94.55%
52 / 55
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
CredentialsFileTokenProvider
94.55% covered (success)
94.55%
52 / 55
75.00% covered (warning)
75.00%
3 / 4
18.05
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getAccessToken
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 loadCredentials
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
8
 fetchToken
81.25% covered (warning)
81.25%
13 / 16
0.00% covered (danger)
0.00%
0 / 1
5.16
1<?php
2
3namespace MediaWiki\Extension\PageViewInfoGA;
4
5use Exception;
6use Google\Auth\CredentialsLoader;
7use Google\Auth\FetchAuthTokenInterface;
8use Google\Auth\HttpHandler\HttpHandlerFactory;
9use MediaWiki\Http\HttpRequestFactory;
10use MediaWiki\Json\FormatJson;
11use Psr\Log\LoggerAwareInterface;
12use Psr\Log\LoggerAwareTrait;
13use Psr\Log\NullLogger;
14use StatusValue;
15use Wikimedia\ObjectCache\BagOStuff;
16use Wikimedia\Timestamp\ConvertibleTimestamp;
17
18/**
19 * Gets access tokens with google/auth from a JSON credentials file, such as a service account key or
20 * a Workload Identity Federation configuration from `gcloud iam workload-identity-pools create-cred-config`.
21 * The file is read on the first token request, so a bad file fails only that request.
22 */
23class CredentialsFileTokenProvider implements LoggerAwareInterface {
24    use LoggerAwareTrait;
25
26    /** Stop using a cached token this long before it expires */
27    private const EXPIRY_MARGIN = 300;
28    /** Seconds to wait for a Google endpoint or a URL credential source */
29    private const TIMEOUT = 5;
30    private const CONNECT_TIMEOUT = 2;
31    /** Lets a federated token call the IAM Credentials API to impersonate a service account */
32    private const CLOUD_PLATFORM_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
33
34    /** @var callable Sends a PSR-7 request and returns the response, as google/auth expects */
35    private $httpHandler;
36
37    private ?FetchAuthTokenInterface $credentials = null;
38
39    /**
40     * @param HttpRequestFactory $httpRequestFactory
41     * @param BagOStuff $cache
42     * @param string $credentialsFile
43     * @param string $scope
44     * @param callable|null $httpHandler For tests; the default is core's Guzzle client
45     */
46    public function __construct(
47        HttpRequestFactory $httpRequestFactory,
48        private readonly BagOStuff $cache,
49        private readonly string $credentialsFile,
50        private readonly string $scope,
51        ?callable $httpHandler = null
52    ) {
53        $this->logger = new NullLogger();
54        $this->httpHandler = $httpHandler ?? HttpHandlerFactory::build( $httpRequestFactory->createGuzzleClient( [
55            'timeout' => self::TIMEOUT,
56            'connect_timeout' => self::CONNECT_TIMEOUT,
57        ] ) );
58    }
59
60    /**
61     * @return StatusValue With the access token as its value when OK
62     */
63    public function getAccessToken(): StatusValue {
64        if ( $this->credentials === null ) {
65            $problem = $this->loadCredentials();
66            if ( $problem !== null ) {
67                // The file is named in the log only, as API modules show the status to readers
68                $this->logger->error( 'Unusable Google credentials in {file}: {problem}', [
69                    'file' => $this->credentialsFile,
70                    'problem' => $problem,
71                ] );
72                return StatusValue::newFatal( 'pageviewinfoga-error-credentials' );
73            }
74        }
75        $credentials = $this->credentials;
76
77        // Set by the callback when the cache has no token
78        $status = null;
79        $token = $this->cache->getWithSetCallback(
80            $this->cache->makeKey( 'pageviewinfoga-token', sha1( $credentials->getCacheKey() . "\n" . $this->scope ) ),
81            BagOStuff::TTL_HOUR,
82            function ( &$ttl ) use ( $credentials, &$status ) {
83                $status = $this->fetchToken( $credentials, $ttl );
84                // Nothing is cached when this is false
85                return $status->isOK() ? $status->getValue() : false;
86            }
87        );
88        return $status ?? StatusValue::newGood( $token );
89    }
90
91    /**
92     * @return string|null What makes the file unusable, or null once $this->credentials is set
93     */
94    private function loadCredentials(): ?string {
95        $file = $this->credentialsFile;
96        if ( !is_file( $file ) || !is_readable( $file ) ) {
97            return 'not a readable file';
98        }
99        $status = FormatJson::parse( (string)file_get_contents( $file ), FormatJson::FORCE_ASSOC );
100        if ( !$status->isOK() || !is_array( $status->getValue() ) ) {
101            return 'not a JSON object';
102        }
103        $json = $status->getValue();
104        $scope = $this->scope;
105        // google/auth asks STS for the same scopes as the impersonated token, and without
106        // cloud-platform the STS token is refused by the IAM Credentials API
107        if ( ( $json['type'] ?? null ) === 'external_account' &&
108            isset( $json['service_account_impersonation_url'] )
109        ) {
110            $scope = [ self::CLOUD_PLATFORM_SCOPE, $this->scope ];
111        }
112        try {
113            $this->credentials = CredentialsLoader::makeCredentials( $scope, $json );
114        } catch ( Exception $e ) {
115            return $e->getMessage();
116        }
117        return null;
118    }
119
120    /**
121     * @param FetchAuthTokenInterface $credentials
122     * @param int &$ttl Set to how long the token can be cached
123     * @return StatusValue With the access token as its value when OK
124     */
125    private function fetchToken( FetchAuthTokenInterface $credentials, &$ttl ): StatusValue {
126        try {
127            $token = $credentials->fetchAuthToken( $this->httpHandler );
128        } catch ( Exception $e ) {
129            // Such as invalid_grant for a disabled key or a skewed clock, a denied impersonation, or a
130            // missing subject token file
131            // The message only: a trace's arguments could hold the key or a token
132            $this->logger->error( 'Failed getting an access token for Google Analytics: {error}', [
133                'error' => $e->getMessage(),
134            ] );
135            return StatusValue::newFatal( 'pvi-invalidresponse' );
136        }
137        if ( !is_string( $token['access_token'] ?? null ) ) {
138            $this->logger->error( 'Google returned no access token' );
139            return StatusValue::newFatal( 'pvi-invalidresponse' );
140        }
141
142        // Impersonated service accounts give expires_at, the rest expires_in
143        $lifetime = isset( $token['expires_at'] ) ?
144            (int)$token['expires_at'] - (int)ConvertibleTimestamp::time() :
145            (int)( $token['expires_in'] ?? 0 );
146        $ttl = $lifetime - self::EXPIRY_MARGIN;
147        if ( $ttl < 1 ) {
148            // A TTL of 0 would cache the token forever, and a negative one stores nothing
149            $ttl = -1;
150        }
151        return StatusValue::newGood( $token['access_token'] );
152    }
153}