5 use BookStack\Auth\Access\OpenIdConnect\InvalidTokenException;
6 use BookStack\Auth\Access\OpenIdConnect\OpenIdConnectIdToken;
7 use phpseclib3\Crypt\RSA;
10 class OpenIdConnectIdTokenTest extends TestCase
12 public function test_valid_token_passes_validation()
14 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', [
18 $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));
21 public function test_get_claim_returns_value_if_existing()
23 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', []);
27 public function test_get_claim_returns_null_if_not_existing()
29 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', []);
30 $this->assertEquals(null, $token->getClaim('emails'));
33 public function test_get_all_claims_returns_all_payload_claims()
35 $defaultPayload = $this->getDefaultPayload();
36 $token = new OpenIdConnectIdToken($this->idToken($defaultPayload), 'https://auth.example.com', []);
37 $this->assertEquals($defaultPayload, $token->getAllClaims());
40 public function test_token_structure_error_cases()
42 $idToken = $this->idToken();
43 $idTokenExploded = explode('.', $idToken);
45 $messagesAndTokenValues = [
46 ['Could not parse out a valid header within the provided token', ''],
47 ['Could not parse out a valid header within the provided token', 'cat'],
48 ['Could not parse out a valid payload within the provided token', $idTokenExploded[0]],
49 ['Could not parse out a valid payload within the provided token', $idTokenExploded[0] . '.' . 'dog'],
50 ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1]],
51 ['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1] . '.' . '@$%'],
54 foreach ($messagesAndTokenValues as [$message, $tokenValue]) {
55 $token = new OpenIdConnectIdToken($tokenValue, 'https://auth.example.com', []);
58 $token->validate('abc');
59 } catch (\Exception $exception) {
63 $this->assertInstanceOf(InvalidTokenException::class, $err, $message);
64 $this->assertEquals($message, $err->getMessage());
68 public function test_error_thrown_if_token_signature_not_validated_from_no_keys()
70 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', []);
71 $this->expectException(InvalidTokenException::class);
72 $this->expectExceptionMessage('Token signature could not be validated using the provided keys');
73 $token->validate('abc');
76 public function test_error_thrown_if_token_signature_not_validated_from_non_matching_key()
78 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', [
79 array_merge($this->jwkKeyArray(), [
80 'n' => 'iqK-1QkICMf_cusNLpeNnN-bhT0-9WLBvzgwKLALRbrevhdi5ttrLHIQshaSL0DklzfyG2HWRmAnJ9Q7sweEjuRiiqRcSUZbYu8cIv2hLWYu7K_NH67D2WUjl0EnoHEuiVLsZhQe1CmdyLdx087j5nWkd64K49kXRSdxFQUlj8W3NeK3CjMEUdRQ3H4RZzJ4b7uuMiFA29S2ZhMNG20NPbkUVsFL-jiwTd10KSsPT8yBYipI9O7mWsUWt_8KZs1y_vpM_k3SyYihnWpssdzDm1uOZ8U3mzFr1xsLAO718GNUSXk6npSDzLl59HEqa6zs4O9awO2qnSHvcmyELNk31w'
83 $this->expectException(InvalidTokenException::class);
84 $this->expectExceptionMessage('Token signature could not be validated using the provided keys');
85 $token->validate('abc');
88 public function test_error_thrown_if_token_signature_not_validated_from_invalid_key()
90 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', ['url://example.com']);
91 $this->expectException(InvalidTokenException::class);
92 $this->expectExceptionMessage('Token signature could not be validated using the provided keys');
93 $token->validate('abc');
96 public function test_error_thrown_if_token_algorithm_is_not_rs256()
98 $token = new OpenIdConnectIdToken($this->idToken([], ['alg' => 'HS256']), 'https://auth.example.com', []);
99 $this->expectException(InvalidTokenException::class);
100 $this->expectExceptionMessage("Only RS256 signature validation is supported. Token reports using HS256");
101 $token->validate('abc');
104 public function test_token_claim_error_cases()
106 /** @var array<array{0: string: 1: array}> $claimOverridesByErrorMessage */
107 $claimOverridesByErrorMessage = [
108 // 1. iss claim present
109 ['Missing or non-matching token issuer value', ['iss' => null]],
110 // 1. iss claim matches provided issuer
111 ['Missing or non-matching token issuer value', ['iss' => 'https://auth.example.co.uk']],
112 // 2. aud claim present
113 ['Missing token audience value', ['aud' => null]],
114 // 2. aud claim validates all values against those expected (Only expect single)
115 ['Token audience value has 2 values, Expected 1', ['aud' => ['abc', 'def']]],
116 // 2. aud claim matches client id
117 ['Token audience value did not match the expected client_id', ['aud' => 'xxyyzz.aaa.bbccdd.456']],
118 // 4. azp claim matches client id if present
119 ['Token authorized party exists but does not match the expected client_id', ['azp' => 'xxyyzz.aaa.bbccdd.456']],
120 // 5. exp claim present
121 ['Missing token expiration time value', ['exp' => null]],
122 // 5. exp claim not expired
123 ['Token has expired', ['exp' => time() - 360]],
124 // 6. iat claim present
125 ['Missing token issued at time value', ['iat' => null]],
126 // 6. iat claim too far in the future
127 ['Token issue at time is not recent or is invalid', ['iat' => time() + 600]],
128 // 6. iat claim too far in the past
129 ['Token issue at time is not recent or is invalid', ['iat' => time() - 172800]],
131 // Custom: sub is present
132 ['Missing token subject value', ['sub' => null]],
135 foreach ($claimOverridesByErrorMessage as [$message, $overrides]) {
136 $token = new OpenIdConnectIdToken($this->idToken($overrides), 'https://auth.example.com', [
142 $token->validate('xxyyzz.aaa.bbccdd.123');
143 } catch (\Exception $exception) {
147 $this->assertInstanceOf(InvalidTokenException::class, $err, $message);
148 $this->assertEquals($message, $err->getMessage());
152 public function test_keys_can_be_a_local_file_reference_to_pem_key()
155 $testFilePath = 'file://' . stream_get_meta_data($file)['uri'];
156 file_put_contents($testFilePath, $this->pemKey());
157 $token = new OpenIdConnectIdToken($this->idToken(), 'https://auth.example.com', [
161 $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));
162 unlink($testFilePath);
165 protected function getDefaultPayload(): array
168 "sub" => "abc1234def",
169 "name" => "Barry Scott",
172 "iss" => "https://auth.example.com",
173 "aud" => "xxyyzz.aaa.bbccdd.123",
175 "exp" => time() + 720,
176 "jti" => "ID.AaaBBBbbCCCcccDDddddddEEEeeeeee",
178 "idp" => "fghfghgfh546456dfgdfg",
179 "preferred_username" => "xXBazzaXx",
180 "auth_time" => time(),
181 "at_hash" => "sT4jbsdSGy9w12pq3iNYDA",
185 protected function idToken($payloadOverrides = [], $headerOverrides = []): string
187 $payload = array_merge($this->getDefaultPayload(), $payloadOverrides);
188 $header = array_merge([
191 ], $headerOverrides);
193 $top = implode('.', [
194 $this->base64UrlEncode(json_encode($header)),
195 $this->base64UrlEncode(json_encode($payload)),
198 $privateKey = $this->getPrivateKey();
199 $signature = $privateKey->sign($top);
200 return $top . '.' . $this->base64UrlEncode($signature);
203 protected function getPrivateKey()
207 $key = RSA::loadPrivateKey($this->privatePemKey())->withPadding(RSA::SIGNATURE_PKCS1);
213 protected function base64UrlEncode(string $decoded): string
215 return strtr(base64_encode($decoded), '+/', '-_');
218 protected function pemKey(): string
220 return "-----BEGIN PUBLIC KEY-----
221 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqo1OmfNKec5S2zQC4SP9
222 DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvm
223 zXL16c93Obn7G8x8A3ao6yN5qKO5S5+CETqOZfKN/g75Xlz7VsC3igOhgsXnPx6i
224 iM6sbYbk0U/XpFaT84LXKI8VTIPUo7gTeZN1pTET//i9FlzAOzX+xfWBKdOqlEzl
225 +zihMHCZUUvQu99P+o0MDR0lMUT+vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNk
226 WvsLta1+jNUee+8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw
228 -----END PUBLIC KEY-----";
231 protected function privatePemKey(): string
233 return "-----BEGIN PRIVATE KEY-----
234 MIIEvQIBADANBgkqhkiG9w0BAQEF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pVy8y99vwcqO4kOXcmf4O6Y
251 uW6sMsjvOwKBgQDbFtqB+MtsLCSSBF61W6AHHD5tna4H75lG2623yXZF2NanFLF5
252 K6muL9DI3ujtOMQETJJUt9+rWJjLEEsJ/dYa/SV0l7D/LKOEnyuu3JZkkLaTzZzi
253 6qcA2bfhqdCzEKlHV99WjkfV8hNlpex9rLuOPB8JLh7FVONicBGxF/UojQKBgDXs
254 IlYaSuI6utilVKQP0kPtEPOKERc2VS+iRSy8hQGXR3xwwNFQSQm+f+sFCGT6VcSd
255 W0TI+6Fc2xwPj38vP465dTentbKM1E+wdSYW6SMwSfhO6ECDbfJsst5Sr2Kkt1N7
256 9FUkfDLu6GfEfnK/KR1SurZB2u51R7NYyg7EnplvAoGAT0aTtOcck0oYN30g5mdf
257 efqXPwg2wAPYeiec49EbfnteQQKAkqNfJ9K69yE2naf6bw3/5mCBsq/cXeuaBMII
258 ylysUIRBqt2J0kWm2yCpFWR7H+Ilhdx9A7ZLCqYVt8e+vjO/BOI3cQDe2VPOLPSl
259 q/1PY4iJviGKddtmfClH3v4=
260 -----END PRIVATE KEY-----";
263 protected function jwkKeyArray(): array
268 'kid' => '066e52af-8884-4926-801d-032a276f9f2a',
271 'n' => 'qo1OmfNKec5S2zQC4SP9DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvmzXL16c93Obn7G8x8A3ao6yN5qKO5S5-CETqOZfKN_g75Xlz7VsC3igOhgsXnPx6iiM6sbYbk0U_XpFaT84LXKI8VTIPUo7gTeZN1pTET__i9FlzAOzX-xfWBKdOqlEzl-zihMHCZUUvQu99P-o0MDR0lMUT-vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNkWvsLta1-jNUee-8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw3w',