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