Skip to content

Add .env variable to disable basic login and WebAuthn login #3382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,13 @@ TRUSTED_PROXIES=null
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

# Disable Basic Auth. This means that the only way to authenticate is via the API token or Oauth.
# This should only be toggled AFTER having set up the admin account and bound the Oauth client.
# DISABLE_BASIC_AUTH=false

# Disable WebAuthn. This means that the only way to authenticate is via the API token, Basic Auth or Oauth.
# DISABLE_WEBAUTHN=false

# Oauth token data
# XXX_REDIRECT_URI should be left as default unless you know exactly what you do.

Expand Down
2 changes: 2 additions & 0 deletions app/Actions/Diagnostics/Errors.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use App\Actions\Diagnostics\Pipes\Checks\AdminUserExistsCheck;
use App\Actions\Diagnostics\Pipes\Checks\AppUrlMatchCheck;
use App\Actions\Diagnostics\Pipes\Checks\AuthDisabledCheck;
use App\Actions\Diagnostics\Pipes\Checks\BasicPermissionCheck;
use App\Actions\Diagnostics\Pipes\Checks\CachePasswordCheck;
use App\Actions\Diagnostics\Pipes\Checks\CacheTemporaryUrlCheck;
Expand Down Expand Up @@ -44,6 +45,7 @@ class Errors
*/
private array $pipes = [
AdminUserExistsCheck::class,
AuthDisabledCheck::class,
BasicPermissionCheck::class,
ConfigSanityCheck::class,
DBSupportCheck::class,
Expand Down
85 changes: 85 additions & 0 deletions app/Actions/Diagnostics/Pipes/Checks/AuthDisabledCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Actions\Diagnostics\Pipes\Checks;

use App\Contracts\DiagnosticPipe;
use App\DTO\DiagnosticData;
use App\Models\User;
use App\Providers\AuthServiceProvider;
use Illuminate\Support\Facades\Schema;

class AuthDisabledCheck implements DiagnosticPipe
{
public const INFO = 'You need to enable at least one authentication method to be able to use Lychee...';

/**
* {@inheritDoc}
*/
public function handle(array &$data, \Closure $next): array
{
if (!Schema::hasTable('users') || !Schema::hasTable('oauth_credentials') || !Schema::hasTable('webauthn_credentials')) {
// @codeCoverageIgnoreStart
return $next($data);
// @codeCoverageIgnoreEnd
}

if (AuthServiceProvider::isBasicAuthEnabled()) {
// If basic auth is enabled, we do not need to check for Oauth or WebAuthn
// as they are optional and can be used in addition to basic auth.
return $next($data);
}
// From now on, we assume that basic auth is disabled.

if (!AuthServiceProvider::isWebAuthnEnabled() && !AuthServiceProvider::isOauthEnabled()) {
$data[] = DiagnosticData::error('All authentication methods are disabled. Really?', self::class, [self::INFO]);

return $next($data);
}

$number_admin_with_oauth = AuthServiceProvider::isOauthEnabled() ? $this->oauthChecks($data) : 0;
$number_admin_with_webauthn = AuthServiceProvider::isWebAuthnEnabled() ? $this->webauthnCheck($data) : 0;
if (($number_admin_with_oauth === 0 && AuthServiceProvider::isOauthEnabled()) &&
($number_admin_with_webauthn === 0 && AuthServiceProvider::isWebAuthnEnabled())
) {
$data[] = DiagnosticData::error('Basic auth is disabled and there are no admin user with Oauth or WebAuthn enabled.', self::class, [self::INFO]);
}

return $next($data);
}

/**
* @param DiagnosticData[] &$data
*
* @return int
*/
private function oauthChecks(array &$data): int
{
$number_admin_with_oauth = User::query()->has('oauthCredentials')->where('may_administrate', '=', true)->count();
if (!AuthServiceProvider::isWebAuthnEnabled() && $number_admin_with_oauth === 0) {
$data[] = DiagnosticData::error('Basic auth and Webauthn are disabled and there are no admin user with Oauth enabled.', self::class, [self::INFO]);
}

return $number_admin_with_oauth;
}

/**
* @param DiagnosticData[] &$data
*
* @return int
*/
private function webauthnCheck(array &$data): int
{
$number_admin_with_webauthn = User::query()->has('webAuthnCredentials')->where('may_administrate', '=', true)->count();
if (!AuthServiceProvider::isOauthEnabled() && $number_admin_with_webauthn === 0) {
$data[] = DiagnosticData::error('Basic auth is disabled and there are no admin user with WebAuthn enabled.', self::class, [self::INFO]);
}

return $number_admin_with_webauthn;
}
}
24 changes: 24 additions & 0 deletions app/Exceptions/BasicAuthDisabledExecption.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Exceptions;

use Symfony\Component\HttpFoundation\Response;

/**
* BasicAuthDisabledExecption.
*
* Returns status code 403 (Forbidden) to an HTTP client.
*/
class BasicAuthDisabledExecption extends BaseLycheeException
{
public function __construct()
{
parent::__construct(Response::HTTP_FORBIDDEN, 'Basic Auth is disabled by configuration', null);
}
}
24 changes: 24 additions & 0 deletions app/Exceptions/WebAuthnDisabledExecption.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Exceptions;

use Symfony\Component\HttpFoundation\Response;

/**
* WebAuthnDisabledExecption.
*
* Returns status code 403 (Forbidden) to an HTTP client.
*/
class WebAuthnDisabledExecption extends BaseLycheeException
{
public function __construct()
{
parent::__construct(Response::HTTP_FORBIDDEN, 'WebAuthn is disabled by configuration', null);
}
}
27 changes: 6 additions & 21 deletions app/Http/Controllers/OauthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

namespace App\Http\Controllers;

use App\Actions\Oauth\Oauth as OauthAction;
use App\Actions\Oauth\Oauth;
use App\Enum\CacheTag;
use App\Enum\OauthProvidersType;
use App\Events\TaggedRouteCacheUpdated;
Expand All @@ -19,6 +19,7 @@
use App\Http\Resources\Oauth\OauthRegistrationData;
use App\Models\OauthCredential;
use App\Models\User;
use App\Providers\AuthServiceProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Controller;
use Illuminate\Routing\Redirector;
Expand All @@ -32,7 +33,7 @@
class OauthController extends Controller
{
public function __construct(
private OauthAction $oauth,
private Oauth $oauth,
) {
}

Expand Down Expand Up @@ -99,7 +100,7 @@ public function register(string $provider)
}

$provider_enum = $this->oauth->validateProviderOrDie($provider);
Session::put($provider_enum->value, OauthAction::OAUTH_REGISTER);
Session::put($provider_enum->value, Oauth::OAUTH_REGISTER);

TaggedRouteCacheUpdated::dispatch(CacheTag::USER);

Expand Down Expand Up @@ -136,12 +137,7 @@ public function listForUser(OauthListRequest $request): array

$credentials = $user->oauthCredentials()->get();

foreach (OauthProvidersType::cases() as $provider) {
$client_id = config('services.' . $provider->value . '.client_id');
if ($client_id === null || $client_id === '') {
continue;
}

foreach (AuthServiceProvider::getAvailableOauthProviders() as $provider) {
// We create a signed route for 5 minutes
$route = URL::signedRoute(
name: 'oauth-register',
Expand All @@ -166,17 +162,6 @@ public function listForUser(OauthListRequest $request): array
*/
public function listProviders(): array
{
$oauth_available = [];

foreach (OauthProvidersType::cases() as $oauth_provider) {
$client_id = config('services.' . $oauth_provider->value . '.client_id');
if ($client_id === null || $client_id === '') {
continue;
}

$oauth_available[] = $oauth_provider;
}

return $oauth_available;
return AuthServiceProvider::getAvailableOauthProviders();
}
}
21 changes: 21 additions & 0 deletions app/Http/Controllers/WebAuthn/WebAuthnLoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
namespace App\Http\Controllers\WebAuthn;

use App\Exceptions\UnauthenticatedException;
use App\Exceptions\WebAuthnDisabledExecption;
use App\Models\User;
use App\Providers\AuthServiceProvider;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Routing\Controller;
Expand All @@ -31,6 +33,8 @@ class WebAuthnLoginController extends Controller
*/
public function options(AssertionRequest $request): Responsable
{
$this->checkEnabled();

/** @phpstan-ignore staticMethod.dynamicCall */
$fields = $request->validate([
'user_id' => 'sometimes|int',
Expand All @@ -54,6 +58,8 @@ public function options(AssertionRequest $request): Responsable
*/
public function login(AssertedRequest $request, AssertionValidator $validator): void
{
$this->checkEnabled();

$credentials = $request->validated();

if (!$this->isSignedChallenge($credentials)) {
Expand Down Expand Up @@ -110,4 +116,19 @@ public function retrieveByCredentials(array $credentials): User|null

return $user;
}

/**
* Validate whether the WebAuthn is enabled in the configuration.
* If not throw an exception with status code 403 (Forbidden).
*
* @return void
*
* @throws WebAuthnDisabledExecption
*/
private function checkEnabled(): void
{
if (AuthServiceProvider::isWebAuthnEnabled() === false) {
throw new WebAuthnDisabledExecption();
}
}
}
32 changes: 13 additions & 19 deletions app/Http/Requests/Profile/UpdateProfileRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use App\Http\Requests\Traits\HasPasswordTrait;
use App\Models\User;
use App\Policies\UserPolicy;
use App\Providers\AuthServiceProvider;
use App\Rules\CurrentPasswordRule;
use App\Rules\PasswordRule;
use App\Rules\UsernameRule;
Expand All @@ -23,7 +24,6 @@ class UpdateProfileRequest extends BaseApiRequest implements HasPassword
{
use HasPasswordTrait;

protected string $old_password;
protected ?string $username = null;
protected ?string $email = null;

Expand All @@ -40,6 +40,12 @@ public function authorize(): bool
*/
public function rules(): array
{
if (!AuthServiceProvider::isBasicAuthEnabled()) {
return [
RequestAttribute::EMAIL_ATTRIBUTE => ['present', 'nullable', 'email:rfc', 'max:100'],
];
}

return [
RequestAttribute::USERNAME_ATTRIBUTE => ['required', new UsernameRule(true)],
RequestAttribute::PASSWORD_ATTRIBUTE => ['sometimes', 'confirmed', new PasswordRule(false)],
Expand All @@ -53,27 +59,15 @@ public function rules(): array
*/
protected function processValidatedValues(array $values, array $files): void
{
$this->password = $values[RequestAttribute::PASSWORD_ATTRIBUTE] ?? null;
$this->old_password = $values[RequestAttribute::OLD_PASSWORD_ATTRIBUTE];

$this->username = trim($values[RequestAttribute::USERNAME_ATTRIBUTE]);
$this->username = $this->username === '' ? null : $this->username;

$this->email = trim($values[RequestAttribute::EMAIL_ATTRIBUTE] ?? '');
$this->email = $this->email === '' ? null : $this->email;
}

/**
* Returns the previous password.
*
* See {@link HasPasswordTrait::password()} for an explanation of the
* semantic difference between the return values `null` and `''`.
*
* @return string|null
*/
public function oldPassword(): ?string
{
return $this->old_password;
if (AuthServiceProvider::isBasicAuthEnabled()) {
// If basic auth is enabled, we require the username.
$this->password = $values[RequestAttribute::PASSWORD_ATTRIBUTE] ?? null;
$this->username = trim($values[RequestAttribute::USERNAME_ATTRIBUTE] ?? '');
$this->username = $this->username === '' ? null : $this->username;
}
}

/**
Expand Down
4 changes: 3 additions & 1 deletion app/Http/Requests/Session/LoginRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
use App\Contracts\Http\Requests\HasPassword;
use App\Contracts\Http\Requests\HasUsername;
use App\Contracts\Http\Requests\RequestAttribute;
use App\Exceptions\BasicAuthDisabledExecption;
use App\Http\Requests\BaseApiRequest;
use App\Http\Requests\Traits\HasPasswordTrait;
use App\Http\Requests\Traits\HasUsernameTrait;
use App\Providers\AuthServiceProvider;
use App\Rules\PasswordRule;
use App\Rules\UsernameRule;

Expand All @@ -27,7 +29,7 @@ class LoginRequest extends BaseApiRequest implements HasUsername, HasPassword
*/
public function authorize(): bool
{
return true;
return AuthServiceProvider::isBasicAuthEnabled() || throw new BasicAuthDisabledExecption();
}

/**
Expand Down
5 changes: 5 additions & 0 deletions app/Http/Resources/GalleryConfigs/InitConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use App\Enum\ThumbAlbumSubtitleType;
use App\Enum\ThumbOverlayVisibilityType;
use App\Models\Configs;
use App\Providers\AuthServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use LycheeVerify\Verify;
Expand Down Expand Up @@ -89,6 +90,8 @@ class InitConfig extends Data
// Live Metrics settings
public bool $is_live_metrics_enabled;

public bool $is_basic_auth_enabled = true;
public bool $is_webauthn_enabled = true;
// User registration enabled
public bool $is_registration_enabled;

Expand Down Expand Up @@ -145,6 +148,8 @@ public function __construct()
$this->title = Configs::getValueAsString('site_title');
$this->dropbox_api_key = Auth::user()?->may_administrate === true ? Configs::getValueAsString('dropbox_key') : 'disabled';

$this->is_basic_auth_enabled = AuthServiceProvider::isBasicAuthEnabled();
$this->is_webauthn_enabled = AuthServiceProvider::isWebAuthnEnabled();
// User registration enabled
$this->is_registration_enabled = Configs::getValueAsBool('user_registration_enabled');

Expand Down
Loading