summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/Token/SsoTokenProvider.php
blob: 7d8f4b4056188da87a0fb43c6cbce6f5cbacd6a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
namespace Aws\Token;

use Aws\Exception\TokenException;
use GuzzleHttp\Promise;

/**
 * Token that comes from the SSO provider
 */
class SsoTokenProvider implements RefreshableTokenProviderInterface
{
    use ParsesIniTrait;

    const ENV_PROFILE = 'AWS_PROFILE';

    private $ssoProfileName;
    private $filename;
    private $ssoOidcClient;

    /**
     * Constructs a new SSO token object, with the specified AWS
     * token
     *
     * @param string $token   Security token to use
     * @param int    $expires UNIX timestamp for when the token expires
     */
    public function __construct($ssoProfileName, $filename = null, $ssoOidcClient = null) {
        $profileName = getenv(self::ENV_PROFILE) ?: 'default';
        $this->ssoProfileName = !empty($ssoProfileName) ? $ssoProfileName : $profileName;
        $this->filename =  !empty($filename)
            ? $filename :
            self::getHomeDir() . '/.aws/config';
        $this->ssoOidcClient = $ssoOidcClient;
    }

    /*
     * Loads cached sso credentials
     *
     * @return PromiseInterface
     */
    public function __invoke()
    {
        return Promise\Coroutine::of(function () {
            if (!@is_readable($this->filename)) {
                throw new TokenException("Cannot read token from $this->filename");
            }
            $profiles = self::loadProfiles($this->filename);
            if (!isset($profiles[$this->ssoProfileName])) {
                throw new TokenException("Profile {$this->ssoProfileName} does not exist in {$this->filename}.");
            }
            $ssoProfile = $profiles[$this->ssoProfileName];
            if (empty($ssoProfile['sso_session'])) {
                throw new TokenException(
                    "Profile {$this->ssoProfileName} in {$this->filename} must contain an sso_session."
                );
            }

            $sessionProfileName = 'sso-session ' . $ssoProfile['sso_session'];
            if (empty($profiles[$sessionProfileName])) {
                throw new TokenException(
                    "Profile {$this->ssoProfileName} does not exist in {$this->filename}"
                );
            }

            $sessionProfileData = $profiles[$sessionProfileName];
            if (empty($sessionProfileData['sso_start_url'])
                || empty($sessionProfileData['sso_region'])
            ) {
                throw new TokenException(
                    "Profile {$this->ssoProfileName} in {$this->filename} must contain the following keys: "
                    . "sso_start_url and sso_region."
                );
            }

            $tokenLocation = self::getTokenLocation($ssoProfile['sso_session']);
            if (!@is_readable($tokenLocation)) {
                throw new TokenException("Unable to read token file at $tokenLocation");
            }
            $tokenData = $this->getTokenData($tokenLocation);
            $this->validateTokenData($tokenLocation, $tokenData);
            yield new SsoToken(
                $tokenData['accessToken'],
                $tokenData['expiresAt'],
                isset($tokenData['refreshToken']) ? $tokenData['refreshToken'] : null,
                isset($tokenData['clientId']) ? $tokenData['clientId'] : null,
                isset($tokenData['clientSecret']) ? $tokenData['clientSecret'] : null,
                isset($tokenData['registrationExpiresAt']) ? $tokenData['registrationExpiresAt'] : null,
                isset($tokenData['region']) ? $tokenData['region'] : null,
                isset($tokenData['startUrl']) ? $tokenData['startUrl'] : null
            );
        });
    }

    /**
     * Refreshes the token
     * @return mixed|null
     */
    public function refresh() {
        try {
            //try to reload from disk
            $token = $this();
            if (
                $token instanceof SsoToken
                && !$token->shouldAttemptRefresh()
            ) {
                return $token;
            }
        } finally {
            //if reload from disk fails, try refreshing
            $tokenLocation = self::getTokenLocation($this->ssoProfileName);
            $tokenData = $this->getTokenData($tokenLocation);
            if (
                empty($this->ssoOidcClient)
                || empty($tokenData['startUrl'])
            ) {
                throw new TokenException(
                    "Cannot refresh this token without an 'ssooidcClient' "
                    . "and a 'start_url'"
                );
            }
            $response = $this->ssoOidcClient->createToken([
                'clientId' => $tokenData['clientId'],
                'clientSecret' => $tokenData['clientSecret'],
                'grantType' => 'refresh_token', // REQUIRED
                'refreshToken' => $tokenData['refreshToken'],
            ]);
            if ($response['@metadata']['statusCode'] == 200) {
                $tokenData['accessToken'] = $response['accessToken'];
                $tokenData['expiresAt'] = time () + $response['expiresIn'];
                $tokenData['refreshToken'] = $response['refreshToken'];
                $token = new SsoToken(
                    $tokenData['accessToken'],
                    $tokenData['expiresAt'],
                    $tokenData['refreshToken'],
                    isset($tokenData['clientId']) ? $tokenData['clientId'] : null,
                    isset($tokenData['clientSecret']) ? $tokenData['clientSecret'] : null,
                    isset($tokenData['registrationExpiresAt']) ? $tokenData['registrationExpiresAt'] : null,
                    isset($tokenData['region']) ? $tokenData['region'] : null,
                    isset($tokenData['startUrl']) ? $tokenData['startUrl'] : null                );

                $this->writeNewTokenDataToDisk($tokenData, $tokenLocation);

                return $token;
            }
        }
    }

    public function shouldAttemptRefresh()
    {
        $tokenLocation = self::getTokenLocation($this->ssoProfileName);
        $tokenData = $this->getTokenData($tokenLocation);
        return strtotime("-10 minutes") >= strtotime($tokenData['expiresAt']);
    }

    /**
     * @param $sso_session
     * @return string
     */
    public static function getTokenLocation($sso_session)
    {
        return self::getHomeDir()
            . '/.aws/sso/cache/'
            . utf8_encode(sha1($sso_session))
            . ".json";
    }

    /**
     * @param $tokenLocation
     * @return array
     */
    function getTokenData($tokenLocation)
    {
        return json_decode(file_get_contents($tokenLocation), true);
    }

    /**
     * @param $tokenData
     * @param $tokenLocation
     * @return mixed
     */
    private function validateTokenData($tokenLocation, $tokenData)
    {
        if (empty($tokenData['accessToken']) || empty($tokenData['expiresAt'])) {
            throw new TokenException(
                "Token file at {$tokenLocation} must contain an access token and an expiration"
            );
        }

        try {
            $expiration = strtotime($tokenData['expiresAt']);
        } catch (\Exception $e) {
            throw new TokenException("Cached SSO token returned an invalid expiration");
        }
        if ($expiration > time()) {
            throw new TokenException("Cached SSO token returned an expired token");
        }
        return $tokenData;
    }

    /**
     * @param array $tokenData
     * @param string $tokenLocation
     * @return void
     */
    private function writeNewTokenDataToDisk(array $tokenData, $tokenLocation)
    {
        $tokenData['expiresAt'] = gmdate(
            'Y-m-d\TH:i:s\Z',
            $tokenData['expiresAt']
        );
        file_put_contents($tokenLocation, json_encode(array_filter($tokenData)));
    }
}