Applied latest styles changes from style CI

This commit is contained in:
Dan Brown 2021-10-16 16:01:59 +01:00
parent 263384cf99
commit 6e325de226
No known key found for this signature in database
GPG Key ID: 46D9F943C24A2EF9
23 changed files with 177 additions and 147 deletions

View File

@ -285,6 +285,7 @@ class LdapService
} }
$userGroups = $this->groupFilter($user); $userGroups = $this->groupFilter($user);
return $this->getGroupsRecursive($userGroups, []); return $this->getGroupsRecursive($userGroups, []);
} }

View File

@ -12,6 +12,7 @@ class OidcAccessToken extends AccessToken
* *
* @param array $options An array of options returned by the service provider * @param array $options An array of options returned by the service provider
* in the access token request. The `access_token` option is required. * in the access token request. The `access_token` option is required.
*
* @throws InvalidArgumentException if `access_token` is not provided in `$options`. * @throws InvalidArgumentException if `access_token` is not provided in `$options`.
*/ */
public function __construct(array $options = []) public function __construct(array $options = [])
@ -20,7 +21,6 @@ class OidcAccessToken extends AccessToken
$this->validate($options); $this->validate($options);
} }
/** /**
* Validate this access token response for OIDC. * Validate this access token response for OIDC.
* As per https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK. * As per https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.
@ -50,5 +50,4 @@ class OidcAccessToken extends AccessToken
{ {
return $this->getValues()['id_token']; return $this->getValues()['id_token'];
} }
} }

View File

@ -60,6 +60,7 @@ class OidcIdToken
{ {
$json = $this->base64UrlDecode($part) ?: '{}'; $json = $this->base64UrlDecode($part) ?: '{}';
$decoded = json_decode($json, true); $decoded = json_decode($json, true);
return is_array($decoded) ? $decoded : []; return is_array($decoded) ? $decoded : [];
} }
@ -74,6 +75,7 @@ class OidcIdToken
/** /**
* Validate all possible parts of the id token. * Validate all possible parts of the id token.
*
* @throws OidcInvalidTokenException * @throws OidcInvalidTokenException
*/ */
public function validate(string $clientId): bool public function validate(string $clientId): bool
@ -81,12 +83,14 @@ class OidcIdToken
$this->validateTokenStructure(); $this->validateTokenStructure();
$this->validateTokenSignature(); $this->validateTokenSignature();
$this->validateTokenClaims($clientId); $this->validateTokenClaims($clientId);
return true; return true;
} }
/** /**
* Fetch a specific claim from this token. * Fetch a specific claim from this token.
* Returns null if it is null or does not exist. * Returns null if it is null or does not exist.
*
* @return mixed|null * @return mixed|null
*/ */
public function getClaim(string $claim) public function getClaim(string $claim)
@ -104,7 +108,8 @@ class OidcIdToken
/** /**
* Validate the structure of the given token and ensure we have the required pieces. * Validate the structure of the given token and ensure we have the required pieces.
* As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2 * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
*
* @throws OidcInvalidTokenException * @throws OidcInvalidTokenException
*/ */
protected function validateTokenStructure(): void protected function validateTokenStructure(): void
@ -116,12 +121,13 @@ class OidcIdToken
} }
if (empty($this->signature) || !is_string($this->signature)) { if (empty($this->signature) || !is_string($this->signature)) {
throw new OidcInvalidTokenException("Could not parse out a valid signature within the provided token"); throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
} }
} }
/** /**
* Validate the signature of the given token and ensure it validates against the provided key. * Validate the signature of the given token and ensure it validates against the provided key.
*
* @throws OidcInvalidTokenException * @throws OidcInvalidTokenException
*/ */
protected function validateTokenSignature(): void protected function validateTokenSignature(): void
@ -130,7 +136,7 @@ class OidcIdToken
throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}"); throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
} }
$parsedKeys = array_map(function($key) { $parsedKeys = array_map(function ($key) {
try { try {
return new OidcJwtSigningKey($key); return new OidcJwtSigningKey($key);
} catch (OidcInvalidKeyException $e) { } catch (OidcInvalidKeyException $e) {
@ -153,7 +159,8 @@ class OidcIdToken
/** /**
* Validate the claims of the token. * Validate the claims of the token.
* As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
*
* @throws OidcInvalidTokenException * @throws OidcInvalidTokenException
*/ */
protected function validateTokenClaims(string $clientId): void protected function validateTokenClaims(string $clientId): void
@ -228,5 +235,4 @@ class OidcIdToken
throw new OidcInvalidTokenException('Missing token subject value'); throw new OidcInvalidTokenException('Missing token subject value');
} }
} }
} }

View File

@ -4,5 +4,4 @@ namespace BookStack\Auth\Access\Oidc;
class OidcInvalidKeyException extends \Exception class OidcInvalidKeyException extends \Exception
{ {
} }

View File

@ -6,5 +6,4 @@ use Exception;
class OidcInvalidTokenException extends Exception class OidcInvalidTokenException extends Exception
{ {
} }

View File

@ -4,5 +4,4 @@ namespace BookStack\Auth\Access\Oidc;
class OidcIssuerDiscoveryException extends \Exception class OidcIssuerDiscoveryException extends \Exception
{ {
} }

View File

@ -18,15 +18,17 @@ class OidcJwtSigningKey
* Can be created either from a JWK parameter array or local file path to load a certificate from. * Can be created either from a JWK parameter array or local file path to load a certificate from.
* Examples: * Examples:
* 'file:///var/www/cert.pem' * 'file:///var/www/cert.pem'
* ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...'] * ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...'].
*
* @param array|string $jwkOrKeyPath * @param array|string $jwkOrKeyPath
*
* @throws OidcInvalidKeyException * @throws OidcInvalidKeyException
*/ */
public function __construct($jwkOrKeyPath) public function __construct($jwkOrKeyPath)
{ {
if (is_array($jwkOrKeyPath)) { if (is_array($jwkOrKeyPath)) {
$this->loadFromJwkArray($jwkOrKeyPath); $this->loadFromJwkArray($jwkOrKeyPath);
} else if (is_string($jwkOrKeyPath) && strpos($jwkOrKeyPath, 'file://') === 0) { } elseif (is_string($jwkOrKeyPath) && strpos($jwkOrKeyPath, 'file://') === 0) {
$this->loadFromPath($jwkOrKeyPath); $this->loadFromPath($jwkOrKeyPath);
} else { } else {
throw new OidcInvalidKeyException('Unexpected type of key value provided'); throw new OidcInvalidKeyException('Unexpected type of key value provided');
@ -47,7 +49,7 @@ class OidcJwtSigningKey
} }
if (!($this->key instanceof RSA)) { if (!($this->key instanceof RSA)) {
throw new OidcInvalidKeyException("Key loaded from file path is not an RSA key as expected"); throw new OidcInvalidKeyException('Key loaded from file path is not an RSA key as expected');
} }
} }
@ -104,5 +106,4 @@ class OidcJwtSigningKey
{ {
return $this->key->toString('PKCS8'); return $this->key->toString('PKCS8');
} }
} }

View File

@ -30,7 +30,6 @@ class OidcOAuthProvider extends AbstractProvider
*/ */
protected $tokenEndpoint; protected $tokenEndpoint;
/** /**
* Returns the base URL for authorizing a client. * Returns the base URL for authorizing a client.
*/ */
@ -66,7 +65,6 @@ class OidcOAuthProvider extends AbstractProvider
return ['openid', 'profile', 'email']; return ['openid', 'profile', 'email'];
} }
/** /**
* Returns the string that should be used to separate scopes when building * Returns the string that should be used to separate scopes when building
* the URL for requesting an access token. * the URL for requesting an access token.
@ -81,8 +79,10 @@ class OidcOAuthProvider extends AbstractProvider
* *
* @param ResponseInterface $response * @param ResponseInterface $response
* @param array|string $data Parsed response data * @param array|string $data Parsed response data
* @return void *
* @throws IdentityProviderException * @throws IdentityProviderException
*
* @return void
*/ */
protected function checkResponse(ResponseInterface $response, $data) protected function checkResponse(ResponseInterface $response, $data)
{ {
@ -101,6 +101,7 @@ class OidcOAuthProvider extends AbstractProvider
* *
* @param array $response * @param array $response
* @param AccessToken $token * @param AccessToken $token
*
* @return ResourceOwnerInterface * @return ResourceOwnerInterface
*/ */
protected function createResourceOwner(array $response, AccessToken $token) protected function createResourceOwner(array $response, AccessToken $token)
@ -116,12 +117,11 @@ class OidcOAuthProvider extends AbstractProvider
* *
* @param array $response * @param array $response
* @param AbstractGrant $grant * @param AbstractGrant $grant
*
* @return OidcAccessToken * @return OidcAccessToken
*/ */
protected function createAccessToken(array $response, AbstractGrant $grant) protected function createAccessToken(array $response, AbstractGrant $grant)
{ {
return new OidcAccessToken($response); return new OidcAccessToken($response);
} }
} }

View File

@ -70,6 +70,7 @@ class OidcProviderSettings
/** /**
* Validate any core, required properties have been set. * Validate any core, required properties have been set.
*
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
protected function validateInitial() protected function validateInitial()
@ -82,12 +83,13 @@ class OidcProviderSettings
} }
if (strpos($this->issuer, 'https://') !== 0) { if (strpos($this->issuer, 'https://') !== 0) {
throw new InvalidArgumentException("Issuer value must start with https://"); throw new InvalidArgumentException('Issuer value must start with https://');
} }
} }
/** /**
* Perform a full validation on these settings. * Perform a full validation on these settings.
*
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function validate(): void public function validate(): void
@ -103,13 +105,14 @@ class OidcProviderSettings
/** /**
* Discover and autoload settings from the configured issuer. * Discover and autoload settings from the configured issuer.
*
* @throws OidcIssuerDiscoveryException * @throws OidcIssuerDiscoveryException
*/ */
public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes) public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes)
{ {
try { try {
$cacheKey = 'oidc-discovery::' . $this->issuer; $cacheKey = 'oidc-discovery::' . $this->issuer;
$discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function() use ($httpClient) { $discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function () use ($httpClient) {
return $this->loadSettingsFromIssuerDiscovery($httpClient); return $this->loadSettingsFromIssuerDiscovery($httpClient);
}); });
$this->applySettingsFromArray($discoveredSettings); $this->applySettingsFromArray($discoveredSettings);
@ -134,7 +137,7 @@ class OidcProviderSettings
} }
if ($result['issuer'] !== $this->issuer) { if ($result['issuer'] !== $this->issuer) {
throw new OidcIssuerDiscoveryException("Unexpected issuer value found on discovery response"); throw new OidcIssuerDiscoveryException('Unexpected issuer value found on discovery response');
} }
$discoveredSettings = []; $discoveredSettings = [];
@ -160,13 +163,14 @@ class OidcProviderSettings
*/ */
protected function filterKeys(array $keys): array protected function filterKeys(array $keys): array
{ {
return array_filter($keys, function(array $key) { return array_filter($keys, function (array $key) {
return $key['kty'] === 'RSA' && $key['use'] === 'sig' && $key['alg'] === 'RS256'; return $key['kty'] === 'RSA' && $key['use'] === 'sig' && $key['alg'] === 'RS256';
}); });
} }
/** /**
* Return an array of jwks as PHP key=>value arrays. * Return an array of jwks as PHP key=>value arrays.
*
* @throws ClientExceptionInterface * @throws ClientExceptionInterface
* @throws OidcIssuerDiscoveryException * @throws OidcIssuerDiscoveryException
*/ */
@ -177,7 +181,7 @@ class OidcProviderSettings
$result = json_decode($response->getBody()->getContents(), true); $result = json_decode($response->getBody()->getContents(), true);
if (empty($result) || !is_array($result) || !isset($result['keys'])) { if (empty($result) || !is_array($result) || !isset($result['keys'])) {
throw new OidcIssuerDiscoveryException("Error reading keys from issuer jwks_uri"); throw new OidcIssuerDiscoveryException('Error reading keys from issuer jwks_uri');
} }
return $result['keys']; return $result['keys'];
@ -193,6 +197,7 @@ class OidcProviderSettings
foreach ($settingKeys as $setting) { foreach ($settingKeys as $setting) {
$settings[$setting] = $this->$setting; $settings[$setting] = $this->$setting;
} }
return $settings; return $settings;
} }
} }

View File

@ -1,5 +1,8 @@
<?php namespace BookStack\Auth\Access\Oidc; <?php
namespace BookStack\Auth\Access\Oidc;
use function auth;
use BookStack\Auth\Access\LoginService; use BookStack\Auth\Access\LoginService;
use BookStack\Auth\Access\RegistrationService; use BookStack\Auth\Access\RegistrationService;
use BookStack\Auth\User; use BookStack\Auth\User;
@ -7,13 +10,12 @@ use BookStack\Exceptions\JsonDebugException;
use BookStack\Exceptions\OpenIdConnectException; use BookStack\Exceptions\OpenIdConnectException;
use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Exceptions\StoppedAuthenticationException;
use BookStack\Exceptions\UserRegistrationException; use BookStack\Exceptions\UserRegistrationException;
use function config;
use Exception; use Exception;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider; use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface as HttpClient; use Psr\Http\Client\ClientInterface as HttpClient;
use function auth;
use function config;
use function trans; use function trans;
use function url; use function url;
@ -39,12 +41,14 @@ class OidcService
/** /**
* Initiate an authorization flow. * Initiate an authorization flow.
*
* @return array{url: string, state: string} * @return array{url: string, state: string}
*/ */
public function login(): array public function login(): array
{ {
$settings = $this->getProviderSettings(); $settings = $this->getProviderSettings();
$provider = $this->getProvider($settings); $provider = $this->getProvider($settings);
return [ return [
'url' => $provider->getAuthorizationUrl(), 'url' => $provider->getAuthorizationUrl(),
'state' => $provider->getState(), 'state' => $provider->getState(),
@ -56,6 +60,7 @@ class OidcService
* return the matching, or new if registration active, user matched to * return the matching, or new if registration active, user matched to
* the authorization server. * the authorization server.
* Returns null if not authenticated. * Returns null if not authenticated.
*
* @throws Exception * @throws Exception
* @throws ClientExceptionInterface * @throws ClientExceptionInterface
*/ */
@ -115,7 +120,7 @@ class OidcService
} }
/** /**
* Calculate the display name * Calculate the display name.
*/ */
protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
{ {
@ -138,11 +143,13 @@ class OidcService
/** /**
* Extract the details of a user from an ID token. * Extract the details of a user from an ID token.
*
* @return array{name: string, email: string, external_id: string} * @return array{name: string, email: string, external_id: string}
*/ */
protected function getUserDetails(OidcIdToken $token): array protected function getUserDetails(OidcIdToken $token): array
{ {
$id = $token->getClaim('sub'); $id = $token->getClaim('sub');
return [ return [
'external_id' => $id, 'external_id' => $id,
'email' => $token->getClaim('email'), 'email' => $token->getClaim('email'),
@ -153,6 +160,7 @@ class OidcService
/** /**
* Processes a received access token for a user. Login the user when * Processes a received access token for a user. Login the user when
* they exist, optionally registering them automatically. * they exist, optionally registering them automatically.
*
* @throws OpenIdConnectException * @throws OpenIdConnectException
* @throws JsonDebugException * @throws JsonDebugException
* @throws UserRegistrationException * @throws UserRegistrationException
@ -189,7 +197,9 @@ class OidcService
} }
$user = $this->registrationService->findOrRegister( $user = $this->registrationService->findOrRegister(
$userDetails['name'], $userDetails['email'], $userDetails['external_id'] $userDetails['name'],
$userDetails['email'],
$userDetails['external_id']
); );
if ($user === null) { if ($user === null) {
@ -197,6 +207,7 @@ class OidcService
} }
$this->loginService->login($user, 'oidc'); $this->loginService->login($user, 'oidc');
return $user; return $user;
} }

View File

@ -54,6 +54,7 @@ class RegistrationService
/** /**
* Attempt to find a user in the system otherwise register them as a new * Attempt to find a user in the system otherwise register them as a new
* user. For use with external auth systems since password is auto-generated. * user. For use with external auth systems since password is auto-generated.
*
* @throws UserRegistrationException * @throws UserRegistrationException
*/ */
public function findOrRegister(string $name, string $email, string $externalId): User public function findOrRegister(string $name, string $email, string $externalId): User

View File

@ -31,8 +31,7 @@ class Saml2Service
RegistrationService $registrationService, RegistrationService $registrationService,
LoginService $loginService, LoginService $loginService,
GroupSyncService $groupSyncService GroupSyncService $groupSyncService
) ) {
{
$this->config = config('saml2'); $this->config = config('saml2');
$this->registrationService = $registrationService; $this->registrationService = $registrationService;
$this->loginService = $loginService; $this->loginService = $loginService;
@ -263,6 +262,7 @@ class Saml2Service
/** /**
* Extract the details of a user from a SAML response. * Extract the details of a user from a SAML response.
*
* @return array{external_id: string, name: string, email: string, saml_id: string} * @return array{external_id: string, name: string, email: string, saml_id: string}
*/ */
protected function getUserDetails(string $samlID, $samlAttributes): array protected function getUserDetails(string $samlID, $samlAttributes): array
@ -359,7 +359,9 @@ class Saml2Service
} }
$user = $this->registrationService->findOrRegister( $user = $this->registrationService->findOrRegister(
$userDetails['name'], $userDetails['email'], $userDetails['external_id'] $userDetails['name'],
$userDetails['email'],
$userDetails['external_id']
); );
if ($user === null) { if ($user === null) {

View File

@ -1,6 +1,7 @@
<?php namespace BookStack\Exceptions; <?php
namespace BookStack\Exceptions;
class OpenIdConnectException extends NotifyException class OpenIdConnectException extends NotifyException
{ {
} }

View File

@ -8,7 +8,6 @@ use Illuminate\Http\Request;
class OidcController extends Controller class OidcController extends Controller
{ {
protected $oidcService; protected $oidcService;
/** /**
@ -42,10 +41,12 @@ class OidcController extends Controller
if ($storedState !== $responseState) { if ($storedState !== $responseState) {
$this->showErrorNotification(trans('errors.oidc_fail_authed', ['system' => config('oidc.name')])); $this->showErrorNotification(trans('errors.oidc_fail_authed', ['system' => config('oidc.name')]));
return redirect('/login'); return redirect('/login');
} }
$this->oidcService->processAuthorizeResponse($request->query('code')); $this->oidcService->processAuthorizeResponse($request->query('code'));
return redirect()->intended(); return redirect()->intended();
} }
} }

View File

@ -22,8 +22,8 @@ use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View; use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Laravel\Socialite\Contracts\Factory as SocialiteFactory; use Laravel\Socialite\Contracts\Factory as SocialiteFactory;
use Whoops\Handler\HandlerInterface;
use Psr\Http\Client\ClientInterface as HttpClientInterface; use Psr\Http\Client\ClientInterface as HttpClientInterface;
use Whoops\Handler\HandlerInterface;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
@ -85,7 +85,7 @@ class AppServiceProvider extends ServiceProvider
return new CspService(); return new CspService();
}); });
$this->app->bind(HttpClientInterface::class, function($app) { $this->app->bind(HttpClientInterface::class, function ($app) {
return new Client([ return new Client([
'timeout' => 3, 'timeout' => 3,
]); ]);

View File

@ -4,8 +4,8 @@ namespace BookStack\Providers;
use BookStack\Api\ApiTokenGuard; use BookStack\Api\ApiTokenGuard;
use BookStack\Auth\Access\ExternalBaseUserProvider; use BookStack\Auth\Access\ExternalBaseUserProvider;
use BookStack\Auth\Access\Guards\LdapSessionGuard;
use BookStack\Auth\Access\Guards\AsyncExternalBaseSessionGuard; use BookStack\Auth\Access\Guards\AsyncExternalBaseSessionGuard;
use BookStack\Auth\Access\Guards\LdapSessionGuard;
use BookStack\Auth\Access\LdapService; use BookStack\Auth\Access\LdapService;
use BookStack\Auth\Access\LoginService; use BookStack\Auth\Access\LoginService;
use BookStack\Auth\Access\RegistrationService; use BookStack\Auth\Access\RegistrationService;

View File

@ -1,7 +1,8 @@
<?php namespace Tests\Auth; <?php
namespace Tests\Auth;
use BookStack\Actions\ActivityType; use BookStack\Actions\ActivityType;
use BookStack\Auth\Access\Oidc\OidcService;
use BookStack\Auth\User; use BookStack\Auth\User;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
@ -131,7 +132,7 @@ class OidcTest extends TestCase
$transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([ $transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([
'email' => 'benny@example.com', 'email' => 'benny@example.com',
'sub' => 'benny1010101' 'sub' => 'benny1010101',
])]); ])]);
// Callback from auth provider // Callback from auth provider
@ -148,7 +149,6 @@ class OidcTest extends TestCase
$this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody()); $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
$this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody()); $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
$this->assertTrue(auth()->check()); $this->assertTrue(auth()->check());
$this->assertDatabaseHas('users', [ $this->assertDatabaseHas('users', [
'email' => 'benny@example.com', 'email' => 'benny@example.com',
@ -176,15 +176,15 @@ class OidcTest extends TestCase
$resp = $this->runLogin([ $resp = $this->runLogin([
'email' => 'benny@example.com', 'email' => 'benny@example.com',
'sub' => 'benny505' 'sub' => 'benny505',
]); ]);
$resp->assertStatus(200); $resp->assertStatus(200);
$resp->assertJson([ $resp->assertJson([
'email' => 'benny@example.com', 'email' => 'benny@example.com',
'sub' => 'benny505', 'sub' => 'benny505',
"iss" => OidcJwtHelper::defaultIssuer(), 'iss' => OidcJwtHelper::defaultIssuer(),
"aud" => OidcJwtHelper::defaultClientId(), 'aud' => OidcJwtHelper::defaultClientId(),
]); ]);
$this->assertFalse(auth()->check()); $this->assertFalse(auth()->check());
} }
@ -193,7 +193,7 @@ class OidcTest extends TestCase
{ {
$this->runLogin([ $this->runLogin([
'email' => '', 'email' => '',
'sub' => 'benny505' 'sub' => 'benny505',
]); ]);
$this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system'); $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
@ -205,7 +205,7 @@ class OidcTest extends TestCase
$this->runLogin([ $this->runLogin([
'email' => 'benny@example.com', 'email' => 'benny@example.com',
'sub' => 'benny505' 'sub' => 'benny505',
]); ]);
$this->assertSessionError('Already logged in'); $this->assertSessionError('Already logged in');
@ -221,7 +221,7 @@ class OidcTest extends TestCase
$this->runLogin([ $this->runLogin([
'email' => 'benny@example.com', 'email' => 'benny@example.com',
'sub' => 'benny505' 'sub' => 'benny505',
]); ]);
$this->assertTrue(auth()->check()); $this->assertTrue(auth()->check());
@ -238,7 +238,7 @@ class OidcTest extends TestCase
$this->runLogin([ $this->runLogin([
'email' => $editor->email, 'email' => $editor->email,
'sub' => 'benny505' 'sub' => 'benny505',
]); ]);
$this->assertSessionError('A user with the email ' . $editor->email . ' already exists but with different credentials.'); $this->assertSessionError('A user with the email ' . $editor->email . ' already exists but with different credentials.');
@ -300,7 +300,7 @@ class OidcTest extends TestCase
$this->getAutoDiscoveryResponse(), $this->getAutoDiscoveryResponse(),
$this->getJwksResponse(), $this->getJwksResponse(),
$this->getAutoDiscoveryResponse([ $this->getAutoDiscoveryResponse([
'issuer' => 'https://auto.example.com' 'issuer' => 'https://auto.example.com',
]), ]),
$this->getJwksResponse(), $this->getJwksResponse(),
]); ]);
@ -343,12 +343,12 @@ class OidcTest extends TestCase
return new Response(200, [ return new Response(200, [
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store', 'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache' 'Pragma' => 'no-cache',
], json_encode(array_merge([ ], json_encode(array_merge([
'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token', 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize', 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys', 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
'issuer' => OidcJwtHelper::defaultIssuer() 'issuer' => OidcJwtHelper::defaultIssuer(),
], $responseOverrides))); ], $responseOverrides)));
} }
@ -357,11 +357,11 @@ class OidcTest extends TestCase
return new Response(200, [ return new Response(200, [
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store', 'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache' 'Pragma' => 'no-cache',
], json_encode([ ], json_encode([
'keys' => [ 'keys' => [
OidcJwtHelper::publicJwkKeyArray() OidcJwtHelper::publicJwkKeyArray(),
] ],
])); ]));
} }
@ -370,12 +370,12 @@ class OidcTest extends TestCase
return new Response(200, [ return new Response(200, [
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store', 'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache' 'Pragma' => 'no-cache',
], json_encode([ ], json_encode([
'access_token' => 'abc123', 'access_token' => 'abc123',
'token_type' => 'Bearer', 'token_type' => 'Bearer',
'expires_in' => 3600, 'expires_in' => 3600,
'id_token' => OidcJwtHelper::idToken($claimOverrides) 'id_token' => OidcJwtHelper::idToken($claimOverrides),
])); ]));
} }
} }

View File

@ -12,31 +12,31 @@ class OidcJwtHelper
{ {
public static function defaultIssuer(): string public static function defaultIssuer(): string
{ {
return "https://auth.example.com"; return 'https://auth.example.com';
} }
public static function defaultClientId(): string public static function defaultClientId(): string
{ {
return "xxyyzz.aaa.bbccdd.123"; return 'xxyyzz.aaa.bbccdd.123';
} }
public static function defaultPayload(): array public static function defaultPayload(): array
{ {
return [ return [
"sub" => "abc1234def", 'sub' => 'abc1234def',
"name" => "Barry Scott", 'name' => 'Barry Scott',
"email" => "bscott@example.com", 'email' => 'bscott@example.com',
"ver" => 1, 'ver' => 1,
"iss" => static::defaultIssuer(), 'iss' => static::defaultIssuer(),
"aud" => static::defaultClientId(), 'aud' => static::defaultClientId(),
"iat" => time(), 'iat' => time(),
"exp" => time() + 720, 'exp' => time() + 720,
"jti" => "ID.AaaBBBbbCCCcccDDddddddEEEeeeeee", 'jti' => 'ID.AaaBBBbbCCCcccDDddddddEEEeeeeee',
"amr" => ["pwd"], 'amr' => ['pwd'],
"idp" => "fghfghgfh546456dfgdfg", 'idp' => 'fghfghgfh546456dfgdfg',
"preferred_username" => "xXBazzaXx", 'preferred_username' => 'xXBazzaXx',
"auth_time" => time(), 'auth_time' => time(),
"at_hash" => "sT4jbsdSGy9w12pq3iNYDA", 'at_hash' => 'sT4jbsdSGy9w12pq3iNYDA',
]; ];
} }
@ -55,6 +55,7 @@ class OidcJwtHelper
$privateKey = static::privateKeyInstance(); $privateKey = static::privateKeyInstance();
$signature = $privateKey->sign($top); $signature = $privateKey->sign($top);
return $top . '.' . static::base64UrlEncode($signature); return $top . '.' . static::base64UrlEncode($signature);
} }
@ -75,7 +76,7 @@ class OidcJwtHelper
public static function publicPemKey(): string public static function publicPemKey(): string
{ {
return "-----BEGIN PUBLIC KEY----- return '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqo1OmfNKec5S2zQC4SP9 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqo1OmfNKec5S2zQC4SP9
DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvm DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvm
zXL16c93Obn7G8x8A3ao6yN5qKO5S5+CETqOZfKN/g75Xlz7VsC3igOhgsXnPx6i zXL16c93Obn7G8x8A3ao6yN5qKO5S5+CETqOZfKN/g75Xlz7VsC3igOhgsXnPx6i
@ -83,12 +84,12 @@ iM6sbYbk0U/XpFaT84LXKI8VTIPUo7gTeZN1pTET//i9FlzAOzX+xfWBKdOqlEzl
+zihMHCZUUvQu99P+o0MDR0lMUT+vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNk +zihMHCZUUvQu99P+o0MDR0lMUT+vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNk
WvsLta1+jNUee+8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw WvsLta1+jNUee+8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw
3wIDAQAB 3wIDAQAB
-----END PUBLIC KEY-----"; -----END PUBLIC KEY-----';
} }
public static function privatePemKey(): string public static function privatePemKey(): string
{ {
return "-----BEGIN PRIVATE KEY----- return '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqjU6Z80p5zlLb MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqjU6Z80p5zlLb
NALhI/0Ose5RHRWAKLqipwYRHPvOo7fqGqTcDdHdoKAmQSN+ducy6zNFEqzjk1te NALhI/0Ose5RHRWAKLqipwYRHPvOo7fqGqTcDdHdoKAmQSN+ducy6zNFEqzjk1te
g6n2m+bNcvXpz3c5ufsbzHwDdqjrI3moo7lLn4IROo5l8o3+DvleXPtWwLeKA6GC g6n2m+bNcvXpz3c5ufsbzHwDdqjrI3moo7lLn4IROo5l8o3+DvleXPtWwLeKA6GC
@ -115,7 +116,7 @@ W0TI+6Fc2xwPj38vP465dTentbKM1E+wdSYW6SMwSfhO6ECDbfJsst5Sr2Kkt1N7
efqXPwg2wAPYeiec49EbfnteQQKAkqNfJ9K69yE2naf6bw3/5mCBsq/cXeuaBMII efqXPwg2wAPYeiec49EbfnteQQKAkqNfJ9K69yE2naf6bw3/5mCBsq/cXeuaBMII
ylysUIRBqt2J0kWm2yCpFWR7H+Ilhdx9A7ZLCqYVt8e+vjO/BOI3cQDe2VPOLPSl ylysUIRBqt2J0kWm2yCpFWR7H+Ilhdx9A7ZLCqYVt8e+vjO/BOI3cQDe2VPOLPSl
q/1PY4iJviGKddtmfClH3v4= q/1PY4iJviGKddtmfClH3v4=
-----END PRIVATE KEY-----"; -----END PRIVATE KEY-----';
} }
public static function publicJwkKeyArray(): array public static function publicJwkKeyArray(): array

View File

@ -252,6 +252,7 @@ trait SharedTestHelpers
/** /**
* Mock the http client used in BookStack. * Mock the http client used in BookStack.
* Returns a reference to the container which holds all history of http transactions. * Returns a reference to the container which holds all history of http transactions.
*
* @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
*/ */
protected function &mockHttpClient(array $responses = []): array protected function &mockHttpClient(array $responses = []): array
@ -262,6 +263,7 @@ trait SharedTestHelpers
$handlerStack = new HandlerStack($mock); $handlerStack = new HandlerStack($mock);
$handlerStack->push($history); $handlerStack->push($history);
$this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]); $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
return $container; return $container;
} }

View File

@ -2,8 +2,8 @@
namespace Tests\Unit; namespace Tests\Unit;
use BookStack\Auth\Access\Oidc\OidcInvalidTokenException;
use BookStack\Auth\Access\Oidc\OidcIdToken; use BookStack\Auth\Access\Oidc\OidcIdToken;
use BookStack\Auth\Access\Oidc\OidcInvalidTokenException;
use Tests\Helpers\OidcJwtHelper; use Tests\Helpers\OidcJwtHelper;
use Tests\TestCase; use Tests\TestCase;
@ -12,7 +12,7 @@ class OidcIdTokenTest extends TestCase
public function test_valid_token_passes_validation() public function test_valid_token_passes_validation()
{ {
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
OidcJwtHelper::publicJwkKeyArray() OidcJwtHelper::publicJwkKeyArray(),
]); ]);
$this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123')); $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));
@ -54,6 +54,7 @@ class OidcIdTokenTest extends TestCase
foreach ($messagesAndTokenValues as [$message, $tokenValue]) { foreach ($messagesAndTokenValues as [$message, $tokenValue]) {
$token = new OidcIdToken($tokenValue, OidcJwtHelper::defaultIssuer(), []); $token = new OidcIdToken($tokenValue, OidcJwtHelper::defaultIssuer(), []);
$err = null; $err = null;
try { try {
$token->validate('abc'); $token->validate('abc');
} catch (\Exception $exception) { } catch (\Exception $exception) {
@ -77,8 +78,8 @@ class OidcIdTokenTest extends TestCase
{ {
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
array_merge(OidcJwtHelper::publicJwkKeyArray(), [ array_merge(OidcJwtHelper::publicJwkKeyArray(), [
'n' => 'iqK-1QkICMf_cusNLpeNnN-bhT0-9WLBvzgwKLALRbrevhdi5ttrLHIQshaSL0DklzfyG2HWRmAnJ9Q7sweEjuRiiqRcSUZbYu8cIv2hLWYu7K_NH67D2WUjl0EnoHEuiVLsZhQe1CmdyLdx087j5nWkd64K49kXRSdxFQUlj8W3NeK3CjMEUdRQ3H4RZzJ4b7uuMiFA29S2ZhMNG20NPbkUVsFL-jiwTd10KSsPT8yBYipI9O7mWsUWt_8KZs1y_vpM_k3SyYihnWpssdzDm1uOZ8U3mzFr1xsLAO718GNUSXk6npSDzLl59HEqa6zs4O9awO2qnSHvcmyELNk31w' 'n' => 'iqK-1QkICMf_cusNLpeNnN-bhT0-9WLBvzgwKLALRbrevhdi5ttrLHIQshaSL0DklzfyG2HWRmAnJ9Q7sweEjuRiiqRcSUZbYu8cIv2hLWYu7K_NH67D2WUjl0EnoHEuiVLsZhQe1CmdyLdx087j5nWkd64K49kXRSdxFQUlj8W3NeK3CjMEUdRQ3H4RZzJ4b7uuMiFA29S2ZhMNG20NPbkUVsFL-jiwTd10KSsPT8yBYipI9O7mWsUWt_8KZs1y_vpM_k3SyYihnWpssdzDm1uOZ8U3mzFr1xsLAO718GNUSXk6npSDzLl59HEqa6zs4O9awO2qnSHvcmyELNk31w',
]) ]),
]); ]);
$this->expectException(OidcInvalidTokenException::class); $this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage('Token signature could not be validated using the provided keys'); $this->expectExceptionMessage('Token signature could not be validated using the provided keys');
@ -97,7 +98,7 @@ class OidcIdTokenTest extends TestCase
{ {
$token = new OidcIdToken(OidcJwtHelper::idToken([], ['alg' => 'HS256']), OidcJwtHelper::defaultIssuer(), []); $token = new OidcIdToken(OidcJwtHelper::idToken([], ['alg' => 'HS256']), OidcJwtHelper::defaultIssuer(), []);
$this->expectException(OidcInvalidTokenException::class); $this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage("Only RS256 signature validation is supported. Token reports using HS256"); $this->expectExceptionMessage('Only RS256 signature validation is supported. Token reports using HS256');
$token->validate('abc'); $token->validate('abc');
} }
@ -134,10 +135,11 @@ class OidcIdTokenTest extends TestCase
foreach ($claimOverridesByErrorMessage as [$message, $overrides]) { foreach ($claimOverridesByErrorMessage as [$message, $overrides]) {
$token = new OidcIdToken(OidcJwtHelper::idToken($overrides), OidcJwtHelper::defaultIssuer(), [ $token = new OidcIdToken(OidcJwtHelper::idToken($overrides), OidcJwtHelper::defaultIssuer(), [
OidcJwtHelper::publicJwkKeyArray() OidcJwtHelper::publicJwkKeyArray(),
]); ]);
$err = null; $err = null;
try { try {
$token->validate('xxyyzz.aaa.bbccdd.123'); $token->validate('xxyyzz.aaa.bbccdd.123');
} catch (\Exception $exception) { } catch (\Exception $exception) {
@ -155,7 +157,7 @@ class OidcIdTokenTest extends TestCase
$testFilePath = 'file://' . stream_get_meta_data($file)['uri']; $testFilePath = 'file://' . stream_get_meta_data($file)['uri'];
file_put_contents($testFilePath, OidcJwtHelper::publicPemKey()); file_put_contents($testFilePath, OidcJwtHelper::publicPemKey());
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [ $token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
$testFilePath $testFilePath,
]); ]);
$this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123')); $this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));