]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Oidc/OidcIdToken.php
Fixed lack of oidc discovery filtering during testing
[bookstack] / app / Auth / Access / Oidc / OidcIdToken.php
1 <?php
2
3 namespace BookStack\Auth\Access\Oidc;
4
5 class OidcIdToken
6 {
7     /**
8      * @var array
9      */
10     protected $header;
11
12     /**
13      * @var array
14      */
15     protected $payload;
16
17     /**
18      * @var string
19      */
20     protected $signature;
21
22     /**
23      * @var array[]|string[]
24      */
25     protected $keys;
26
27     /**
28      * @var string
29      */
30     protected $issuer;
31
32     /**
33      * @var array
34      */
35     protected $tokenParts = [];
36
37     public function __construct(string $token, string $issuer, array $keys)
38     {
39         $this->keys = $keys;
40         $this->issuer = $issuer;
41         $this->parse($token);
42     }
43
44     /**
45      * Parse the token content into its components.
46      */
47     protected function parse(string $token): void
48     {
49         $this->tokenParts = explode('.', $token);
50         $this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
51         $this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
52         $this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
53     }
54
55     /**
56      * Parse a Base64-JSON encoded token part.
57      * Returns the data as a key-value array or empty array upon error.
58      */
59     protected function parseEncodedTokenPart(string $part): array
60     {
61         $json = $this->base64UrlDecode($part) ?: '{}';
62         $decoded = json_decode($json, true);
63         return is_array($decoded) ? $decoded : [];
64     }
65
66     /**
67      * Base64URL decode. Needs some character conversions to be compatible
68      * with PHP's default base64 handling.
69      */
70     protected function base64UrlDecode(string $encoded): string
71     {
72         return base64_decode(strtr($encoded, '-_', '+/'));
73     }
74
75     /**
76      * Validate all possible parts of the id token.
77      * @throws OidcInvalidTokenException
78      */
79     public function validate(string $clientId): bool
80     {
81         $this->validateTokenStructure();
82         $this->validateTokenSignature();
83         $this->validateTokenClaims($clientId);
84         return true;
85     }
86
87     /**
88      * Fetch a specific claim from this token.
89      * Returns null if it is null or does not exist.
90      * @return mixed|null
91      */
92     public function getClaim(string $claim)
93     {
94         return $this->payload[$claim] ?? null;
95     }
96
97     /**
98      * Get all returned claims within the token.
99      */
100     public function getAllClaims(): array
101     {
102         return $this->payload;
103     }
104
105     /**
106      * Validate the structure of the given token and ensure we have the required pieces.
107      * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2
108      * @throws OidcInvalidTokenException
109      */
110     protected function validateTokenStructure(): void
111     {
112         foreach (['header', 'payload'] as $prop) {
113             if (empty($this->$prop) || !is_array($this->$prop)) {
114                 throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
115             }
116         }
117
118         if (empty($this->signature) || !is_string($this->signature)) {
119             throw new OidcInvalidTokenException("Could not parse out a valid signature within the provided token");
120         }
121     }
122
123     /**
124      * Validate the signature of the given token and ensure it validates against the provided key.
125      * @throws OidcInvalidTokenException
126      */
127     protected function validateTokenSignature(): void
128     {
129         if ($this->header['alg'] !== 'RS256') {
130             throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
131         }
132
133         $parsedKeys = array_map(function($key) {
134             try {
135                 return new OidcJwtSigningKey($key);
136             } catch (OidcInvalidKeyException $e) {
137                 throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
138             }
139         }, $this->keys);
140
141         $parsedKeys = array_filter($parsedKeys);
142
143         $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
144         /** @var OidcJwtSigningKey $parsedKey */
145         foreach ($parsedKeys as $parsedKey) {
146             if ($parsedKey->verify($contentToSign, $this->signature)) {
147                 return;
148             }
149         }
150
151         throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
152     }
153
154     /**
155      * Validate the claims of the token.
156      * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
157      * @throws OidcInvalidTokenException
158      */
159     protected function validateTokenClaims(string $clientId): void
160     {
161         // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
162         // MUST exactly match the value of the iss (issuer) Claim.
163         if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
164             throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
165         }
166
167         // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
168         // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
169         // if the ID Token does not list the Client as a valid audience, or if it contains additional
170         // audiences not trusted by the Client.
171         if (empty($this->payload['aud'])) {
172             throw new OidcInvalidTokenException('Missing token audience value');
173         }
174
175         $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
176         if (count($aud) !== 1) {
177             throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1');
178         }
179
180         if ($aud[0] !== $clientId) {
181             throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');
182         }
183
184         // 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
185         // NOTE: Addressed by enforcing a count of 1 above.
186
187         // 4. If an azp (authorized party) Claim is present, the Client SHOULD verify that its client_id
188         // is the Claim Value.
189         if (isset($this->payload['azp']) && $this->payload['azp'] !== $clientId) {
190             throw new OidcInvalidTokenException('Token authorized party exists but does not match the expected client_id');
191         }
192
193         // 5. The current time MUST be before the time represented by the exp Claim
194         // (possibly allowing for some small leeway to account for clock skew).
195         if (empty($this->payload['exp'])) {
196             throw new OidcInvalidTokenException('Missing token expiration time value');
197         }
198
199         $skewSeconds = 120;
200         $now = time();
201         if ($now >= (intval($this->payload['exp']) + $skewSeconds)) {
202             throw new OidcInvalidTokenException('Token has expired');
203         }
204
205         // 6. The iat Claim can be used to reject tokens that were issued too far away from the current time,
206         // limiting the amount of time that nonces need to be stored to prevent attacks.
207         // The acceptable range is Client specific.
208         if (empty($this->payload['iat'])) {
209             throw new OidcInvalidTokenException('Missing token issued at time value');
210         }
211
212         $dayAgo = time() - 86400;
213         $iat = intval($this->payload['iat']);
214         if ($iat > ($now + $skewSeconds) || $iat < $dayAgo) {
215             throw new OidcInvalidTokenException('Token issue at time is not recent or is invalid');
216         }
217
218         // 7. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value is appropriate.
219         // The meaning and processing of acr Claim Values is out of scope for this document.
220         // NOTE: Not used for our case here. acr is not requested.
221
222         // 8. When a max_age request is made, the Client SHOULD check the auth_time Claim value and request
223         // re-authentication if it determines too much time has elapsed since the last End-User authentication.
224         // NOTE: Not used for our case here. A max_age request is not made.
225
226         // Custom: Ensure the "sub" (Subject) Claim exists and has a value.
227         if (empty($this->payload['sub'])) {
228             throw new OidcInvalidTokenException('Missing token subject value');
229         }
230     }
231
232 }