3 namespace BookStack\Access\Oidc;
5 use GuzzleHttp\Psr7\Request;
6 use Illuminate\Contracts\Cache\Repository;
7 use InvalidArgumentException;
8 use Psr\Http\Client\ClientExceptionInterface;
9 use Psr\Http\Client\ClientInterface;
12 * OpenIdConnectProviderSettings
13 * Acts as a DTO for settings used within the oidc request and token handling.
14 * Performs auto-discovery upon request.
16 class OidcProviderSettings
18 public string $issuer;
19 public string $clientId;
20 public string $clientSecret;
21 public ?string $redirectUri;
22 public ?string $authorizationEndpoint;
23 public ?string $tokenEndpoint;
24 public ?string $endSessionEndpoint;
27 * @var string[]|array[]
29 public ?array $keys = [];
31 public function __construct(array $settings)
33 $this->applySettingsFromArray($settings);
34 $this->validateInitial();
38 * Apply an array of settings to populate setting properties within this class.
40 protected function applySettingsFromArray(array $settingsArray)
42 foreach ($settingsArray as $key => $value) {
43 if (property_exists($this, $key)) {
50 * Validate any core, required properties have been set.
52 * @throws InvalidArgumentException
54 protected function validateInitial()
56 $required = ['clientId', 'clientSecret', 'redirectUri', 'issuer'];
57 foreach ($required as $prop) {
58 if (empty($this->$prop)) {
59 throw new InvalidArgumentException("Missing required configuration \"{$prop}\" value");
63 if (!str_starts_with($this->issuer, 'https://')) {
64 throw new InvalidArgumentException('Issuer value must start with https://');
69 * Perform a full validation on these settings.
71 * @throws InvalidArgumentException
73 public function validate(): void
75 $this->validateInitial();
76 $required = ['keys', 'tokenEndpoint', 'authorizationEndpoint'];
77 foreach ($required as $prop) {
78 if (empty($this->$prop)) {
79 throw new InvalidArgumentException("Missing required configuration \"{$prop}\" value");
85 * Discover and autoload settings from the configured issuer.
87 * @throws OidcIssuerDiscoveryException
89 public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes)
92 $cacheKey = 'oidc-discovery::' . $this->issuer;
93 $discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function () use ($httpClient) {
94 return $this->loadSettingsFromIssuerDiscovery($httpClient);
96 $this->applySettingsFromArray($discoveredSettings);
97 } catch (ClientExceptionInterface $exception) {
98 throw new OidcIssuerDiscoveryException("HTTP request failed during discovery with error: {$exception->getMessage()}");
103 * @throws OidcIssuerDiscoveryException
104 * @throws ClientExceptionInterface
106 protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): array
108 $issuerUrl = rtrim($this->issuer, '/') . '/.well-known/openid-configuration';
109 $request = new Request('GET', $issuerUrl);
110 $response = $httpClient->sendRequest($request);
111 $result = json_decode($response->getBody()->getContents(), true);
113 if (empty($result) || !is_array($result)) {
114 throw new OidcIssuerDiscoveryException("Error discovering provider settings from issuer at URL {$issuerUrl}");
117 if ($result['issuer'] !== $this->issuer) {
118 throw new OidcIssuerDiscoveryException('Unexpected issuer value found on discovery response');
121 $discoveredSettings = [];
123 if (!empty($result['authorization_endpoint'])) {
124 $discoveredSettings['authorizationEndpoint'] = $result['authorization_endpoint'];
127 if (!empty($result['token_endpoint'])) {
128 $discoveredSettings['tokenEndpoint'] = $result['token_endpoint'];
131 if (!empty($result['jwks_uri'])) {
132 $keys = $this->loadKeysFromUri($result['jwks_uri'], $httpClient);
133 $discoveredSettings['keys'] = $this->filterKeys($keys);
136 if (!empty($result['end_session_endpoint'])) {
137 $discoveredSettings['endSessionEndpoint'] = $result['end_session_endpoint'];
140 return $discoveredSettings;
144 * Filter the given JWK keys down to just those we support.
146 protected function filterKeys(array $keys): array
148 return array_filter($keys, function (array $key) {
149 $alg = $key['alg'] ?? 'RS256';
150 $use = $key['use'] ?? 'sig';
152 return $key['kty'] === 'RSA' && $use === 'sig' && $alg === 'RS256';
157 * Return an array of jwks as PHP key=>value arrays.
159 * @throws ClientExceptionInterface
160 * @throws OidcIssuerDiscoveryException
162 protected function loadKeysFromUri(string $uri, ClientInterface $httpClient): array
164 $request = new Request('GET', $uri);
165 $response = $httpClient->sendRequest($request);
166 $result = json_decode($response->getBody()->getContents(), true);
168 if (empty($result) || !is_array($result) || !isset($result['keys'])) {
169 throw new OidcIssuerDiscoveryException('Error reading keys from issuer jwks_uri');
172 return $result['keys'];
176 * Get the settings needed by an OAuth provider, as a key=>value array.
178 public function arrayForProvider(): array
180 $settingKeys = ['clientId', 'clientSecret', 'redirectUri', 'authorizationEndpoint', 'tokenEndpoint'];
182 foreach ($settingKeys as $setting) {
183 $settings[$setting] = $this->$setting;