feat(auth): require changing default admin password (#778)

This commit is contained in:
h44z
2026-11-09 19:57:23 +01:00
committed by GitHub
parent 137286d46b
commit 276f120b60
30 changed files with 641 additions and 90 deletions
+7
View File
@@ -6,6 +6,7 @@ import { authStore } from "./stores/auth";
import { securityStore } from "./stores/security";
import { settingsStore } from "@/stores/settings";
import { Notifications } from "@kyvg/vue3-notification";
import DefaultPasswordModal from "@/components/DefaultPasswordModal.vue";
const appGlobal = getCurrentInstance().appContext.config.globalProperties
const auth = authStore()
@@ -197,9 +198,15 @@ const userDisplayName = computed(() => {
</nav>
<div class="container mt-5 flex-shrink-0">
<div class="alert alert-warning mb-4" v-if="auth.IsAuthenticated && auth.DefaultPasswordInUse">
<h4 class="alert-heading"><i class="fa-solid fa-triangle-exclamation me-2"></i>{{ $t('default-password.banner-title') }}</h4>
<p class="mb-0">{{ $t('default-password.banner-message') }}</p>
</div>
<RouterView />
</div>
<DefaultPasswordModal />
<footer class="page-footer mt-auto">
<div class="container mt-5">
<div class="row align-items-center">
@@ -0,0 +1,150 @@
<template>
<Teleport to="#modals">
<div v-if="visible" class="modal-backdrop fade show">
<div class="modal fade show" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" @click.stop="">
<div class="modal-content">
<div class="modal-header bg-warning text-dark">
<h5 class="modal-title">
<i class="fa-solid fa-triangle-exclamation me-2"></i>{{ $t('default-password.modal-title') }}
</h5>
</div>
<div class="modal-body col-md-12">
<div class="alert alert-warning">
<h5 class="alert-heading">{{ $t('default-password.modal-warning-heading') }}</h5>
<p>{{ $t('default-password.modal-warning-text') }}</p>
<hr>
<p class="mb-0 fw-bold">{{ $t('default-password.modal-warning-note') }}</p>
</div>
<form @submit.prevent="updatePassword">
<div class="form-group mb-3">
<label class="form-label" for="default-oldpw">{{ $t('default-password.current-label') }}</label>
<input id="default-oldpw" v-model="pwFormData.OldPassword" class="form-control"
:class="{ 'is-invalid': pwFormData.Password && !pwFormData.OldPassword }" type="password" required>
</div>
<div class="form-group mb-3">
<label class="form-label" for="default-newpw">{{ $t('default-password.new-label') }}</label>
<input id="default-newpw" v-model="pwFormData.Password" class="form-control"
:class="{ 'is-invalid': passwordWeak || passwordSame, 'is-valid': pwFormData.Password !== '' && !passwordWeak && !passwordSame }"
type="password" required>
<div class="invalid-feedback" v-if="passwordWeak">{{ $t('default-password.weak-label') }}</div>
<div class="invalid-feedback" v-else-if="passwordSame">{{ $t('default-password.same-label') }}</div>
</div>
<div class="form-group mb-3">
<label class="form-label" for="default-confirmnewpw">{{ $t('default-password.confirm-label') }}</label>
<input id="default-confirmnewpw" v-model="pwFormData.PasswordRepeat" class="form-control"
:class="{ 'is-invalid': passwordMismatch, 'is-valid': pwFormData.PasswordRepeat !== '' && !passwordMismatch && !passwordWeak && !passwordSame }"
type="password" required>
<div class="invalid-feedback" v-if="passwordMismatch">{{ $t('default-password.mismatch-label') }}</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" :disabled="submitting || !passwordChangeAllowed" @click.prevent="updatePassword">
<i class="fa-solid fa-floppy-disk me-2"></i>{{ $t('default-password.change-button-text') }}
</button>
</div>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<script setup>
import { computed, ref } from "vue";
import { authStore } from "@/stores/auth";
import { profileStore } from "@/stores/profile";
import { settingsStore } from "@/stores/settings";
import { notify } from "@kyvg/vue3-notification";
import { useI18n } from "vue-i18n";
const auth = authStore();
const profile = profileStore();
const settings = settingsStore();
const { t } = useI18n();
const visible = computed(() => auth.IsAuthenticated && auth.DefaultPasswordInUse);
const pwFormData = ref({
OldPassword: 'wgportal-default',
Password: '',
PasswordRepeat: '',
});
const submitting = ref(false);
const minPasswordLength = computed(() => settings.Setting('MinPasswordLength') || 16);
const passwordWeak = computed(() => {
return pwFormData.value.Password && pwFormData.value.Password.length > 0 && pwFormData.value.Password.length < minPasswordLength.value;
});
const passwordMismatch = computed(() => {
return pwFormData.value.PasswordRepeat !== '' && pwFormData.value.Password !== pwFormData.value.PasswordRepeat;
});
const passwordSame = computed(() => {
return pwFormData.value.OldPassword && pwFormData.value.Password && pwFormData.value.OldPassword === pwFormData.value.Password;
});
const passwordChangeAllowed = computed(() => {
return pwFormData.value.Password &&
pwFormData.value.Password.length >= minPasswordLength.value &&
!passwordMismatch.value &&
pwFormData.value.OldPassword &&
pwFormData.value.OldPassword.length > 0 &&
!passwordSame.value;
});
const updatePassword = async () => {
if (!passwordChangeAllowed.value || submitting.value) {
return;
}
submitting.value = true;
try {
await profile.changePassword(pwFormData.value);
auth.SetDefaultPasswordInUse(false);
pwFormData.value.OldPassword = '';
pwFormData.value.Password = '';
pwFormData.value.PasswordRepeat = '';
notify({
title: t('default-password.success-title'),
text: t('default-password.success-text'),
type: 'success',
duration: 5000,
});
await settings.LoadSettings();
await profile.LoadUser();
} catch (e) {
notify({
title: "Failed to update password!",
text: e.toString(),
type: 'error',
});
} finally {
submitting.value = false;
}
};
</script>
<style scoped>
.modal.show {
display: block;
opacity: 1.0;
}
.modal-backdrop {
background-color: rgba(0, 0, 0, 0.7) !important;
z-index: 1055;
}
.modal-backdrop.show {
opacity: 1.0 !important;
}
</style>
+2 -1
View File
@@ -80,7 +80,8 @@ function handleResponse(response) {
if (!response.ok) {
const auth = authStore();
if ([401, 403].includes(response.status) && auth.IsAuthenticated) {
const isDefaultPasswordError = data && data.Message && data.Message.toLowerCase().includes("default admin password");
if ([401, 403].includes(response.status) && auth.IsAuthenticated && !isDefaultPasswordError) {
console.log("unauthorized response received, redirecting to login...");
// handle unauthorized session without clearing return url
auth.HandleUnauthorized();
+8 -1
View File
@@ -8,6 +8,12 @@ let failureCount = 0;
export const websocketWrapper = {
connect() {
const auth = authStore();
if (!auth.IsAuthenticated || auth.DefaultPasswordInUse) {
this.disconnect();
return;
}
if (socket) {
console.log('WebSocket already connected, re-using existing connection.');
return;
@@ -69,7 +75,8 @@ export const websocketWrapper = {
scheduleReconnect() {
if (reconnectTimer) return;
if (!authStore().IsAuthenticated) return; // Don't reconnect if not logged in
const auth = authStore();
if (!auth.IsAuthenticated || auth.DefaultPasswordInUse) return;
reconnectTimer = setInterval(() => {
if (failureCount > 2) {
+17
View File
@@ -32,6 +32,23 @@
"button": "Anmelden",
"button-webauthn": "Passkey verwenden"
},
"default-password": {
"banner-title": "Sicherheitswarnung: Standardpasswort wird verwendet",
"banner-message": "Das Standard-Administratorpasswort ist noch in Verwendung. Solange das Passwort nicht geändert wird, sind keine weiteren Aktionen möglich.",
"modal-title": "Standard-Administratorpasswort ändern",
"modal-warning-heading": "Standardpasswort in Verwendung",
"modal-warning-text": "Das Standard-Administratorpasswort ist derzeit noch in Verwendung. Um Ihre Installation zu schützen, müssen Sie das Passwort jetzt ändern.",
"modal-warning-note": "Hinweis: Solange das Passwort nicht geändert wird, sind keine weiteren Aktionen möglich.",
"current-label": "Aktuelles Passwort",
"new-label": "Neues Passwort",
"confirm-label": "Neues Passwort bestätigen",
"weak-label": "Das Passwort ist zu kurz.",
"mismatch-label": "Passwörter stimmen nicht überein.",
"same-label": "Das neue Passwort muss sich vom aktuellen Passwort unterscheiden.",
"change-button-text": "Passwort ändern",
"success-title": "Passwort geändert!",
"success-text": "Das Passwort wurde erfolgreich geändert. Alle Aktionen sind nun freigeschaltet."
},
"peer-config-download": {
"headline": "VPN-Konfiguration wird heruntergeladen",
"in-progress": "Der Download Ihrer WireGuard-Konfiguration startet automatisch. Bitte warten...",
+17
View File
@@ -32,6 +32,23 @@
"button": "Sign in",
"button-webauthn": "Use Passkey"
},
"default-password": {
"banner-title": "Security Warning: Default Password in Use",
"banner-message": "The default administrator password is still in use. Unless the password gets changed, no further actions are possible.",
"modal-title": "Change Default Administrator Password",
"modal-warning-heading": "Default Password In Use",
"modal-warning-text": "The default administrator password is currently in use. To protect your installation from unauthorized access, you must change the password now.",
"modal-warning-note": "Note: Unless the password gets changed, no further actions are possible.",
"current-label": "Current Password",
"new-label": "New Password",
"confirm-label": "Confirm New Password",
"weak-label": "The password is too short.",
"mismatch-label": "Passwords do not match.",
"same-label": "The new password must be different from the current password.",
"change-button-text": "Change Password",
"success-title": "Password Changed!",
"success-text": "Password changed successfully. All actions are now unlocked."
},
"peer-config-download": {
"headline": "Downloading VPN Configuration",
"in-progress": "Your WireGuard configuration download will start automatically. Please wait...",
+5
View File
@@ -150,6 +150,11 @@ router.beforeEach(async (to) => {
}
}
// Keep restricted views from mounting and loading data until the password is changed.
if (auth.IsAuthenticated && auth.DefaultPasswordInUse && to.path !== '/') {
return { name: 'home', replace: true }
}
// redirect to returnUrl if already authenticated and accessing login page
if (to.path === '/login' && auth.IsAuthenticated) {
const returnUrl = auth.ReturnUrl
+22 -2
View File
@@ -17,6 +17,7 @@ export const authStore = defineStore('auth',{
fetching: false,
sessionChecked: false,
sessionPromise: null,
defaultPasswordInUse: JSON.parse(localStorage.getItem('user'))?.DefaultPasswordInUse || false,
}),
getters: {
UserIdentifier: (state) => state.user?.Identifier || 'unknown',
@@ -24,6 +25,7 @@ export const authStore = defineStore('auth',{
LoginProviders: (state) => state.providers,
IsAuthenticated: (state) => state.user != null,
IsAdmin: (state) => state.user?.IsAdmin || false,
DefaultPasswordInUse: (state) => state.defaultPasswordInUse || false,
ReturnUrl: (state) => state.returnUrl || '/',
IsWebAuthnEnabled: (state) => {
if (state.webAuthnCredentials) {
@@ -317,17 +319,32 @@ export const authStore = defineStore('auth',{
return Promise.reject(new Error("login failed"))
})
},
SetDefaultPasswordInUse(inUse) {
this.defaultPasswordInUse = inUse;
if (this.user) {
this.user.DefaultPasswordInUse = inUse;
localStorage.setItem('user', JSON.stringify(this.user));
if (inUse) {
websocketWrapper.disconnect();
} else {
websocketWrapper.connect();
}
}
},
// -- internal setters
setUserInfo(userInfo) {
// store user details and jwt in local storage to keep user logged in between page refreshes
if (userInfo && (userInfo.Identifier || userInfo.UserIdentifier)) {
const defaultPw = !!userInfo['DefaultPasswordInUse'];
this.defaultPasswordInUse = defaultPw;
if ('UserIdentifier' in userInfo && userInfo.UserIdentifier) { // session object
this.user = {
Identifier: userInfo['UserIdentifier'],
Firstname: userInfo['UserFirstname'] || '',
Lastname: userInfo['UserLastname'] || '',
Email: userInfo['UserEmail'] || '',
IsAdmin: userInfo['IsAdmin'] || false
IsAdmin: userInfo['IsAdmin'] || false,
DefaultPasswordInUse: defaultPw
}
} else if ('Identifier' in userInfo && userInfo.Identifier) { // user object
this.user = {
@@ -335,13 +352,16 @@ export const authStore = defineStore('auth',{
Firstname: userInfo['Firstname'] || '',
Lastname: userInfo['Lastname'] || '',
Email: userInfo['Email'] || '',
IsAdmin: userInfo['IsAdmin'] || false
IsAdmin: userInfo['IsAdmin'] || false,
DefaultPasswordInUse: defaultPw
}
} else {
this.user = null
this.defaultPasswordInUse = false
}
} else {
this.user = null
this.defaultPasswordInUse = false
}
if (this.user) {
+28 -10
View File
@@ -42,11 +42,20 @@ const login = async function () {
const dest = returnUrl.value && returnUrl.value !== '/login' ? returnUrl.value : (auth.ReturnUrl || '/')
auth.Login(username.value, password.value)
.then(uid => {
notify({
title: "Logged in",
text: "Authentication succeeded!",
type: 'success',
});
if (auth.DefaultPasswordInUse) {
notify({
title: "Default Password in Use!",
text: "Please change the default administrator password immediately. Unless the password gets changed, no further actions are possible.",
type: 'warn',
duration: 10000,
});
} else {
notify({
title: "Logged in",
text: "Authentication succeeded!",
type: 'success',
});
}
loggingIn.value = false;
settings.LoadSettings(); // reload full settings
auth.ResetReturnUrl();
@@ -71,11 +80,20 @@ const loginWebAuthn = async function () {
const dest = returnUrl.value && returnUrl.value !== '/login' ? returnUrl.value : (auth.ReturnUrl || '/')
auth.LoginWebAuthn()
.then(uid => {
notify({
title: "Logged in",
text: "Authentication succeeded!",
type: 'success',
});
if (auth.DefaultPasswordInUse) {
notify({
title: "Default Password in Use!",
text: "Please change the default administrator password immediately. Unless the password gets changed, no further actions are possible.",
type: 'warn',
duration: 10000,
});
} else {
notify({
title: "Logged in",
text: "Authentication succeeded!",
type: 'success',
});
}
loggingIn.value = false;
settings.LoadSettings(); // reload full settings
auth.ResetReturnUrl();
+2 -1
View File
@@ -57,6 +57,7 @@ const passwordChangeAllowed = computed(() => {
const updatePassword = async () => {
try {
await profile.changePassword(pwFormData.value);
auth.SetDefaultPasswordInUse(false);
pwFormData.value.OldPassword = '';
pwFormData.value.Password = '';
@@ -85,7 +86,7 @@ const updatePassword = async () => {
<p class="lead">{{ $t('settings.abstract') }}</p>
<div class="card border-secondary p-5 mt-5" v-if="profile.user.Source === 'db'">
<div class="card border-secondary p-5 mt-5" v-if="profile.user.AuthSources?.includes('db')">
<h2 class="display-7">{{ $t('settings.password.headline') }}</h2>
<p class="lead">{{ $t('settings.password.abstract') }}</p>
<hr class="my-4">
+2
View File
@@ -101,6 +101,8 @@ type Authenticator interface {
UserIdMatch(idParameter string) func(next http.Handler) http.Handler
// InfoOnly only add user info to the request context. No login check is performed.
InfoOnly() func(next http.Handler) http.Handler
// RequireNonDefaultPassword prohibits actions if the default admin password is still in use.
RequireNonDefaultPassword() func(next http.Handler) http.Handler
}
type Session interface {
@@ -42,6 +42,7 @@ func (e AuditEndpoint) GetName() string {
func (e AuditEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/audit")
apiGroup.Use(e.authenticator.LoggedIn(ScopeAdmin))
apiGroup.Use(e.authenticator.RequireNonDefaultPassword())
apiGroup.HandleFunc("GET /entries", e.handleEntriesGet())
}
@@ -29,6 +29,8 @@ type AuthenticationService interface {
OauthLoginStep2(ctx context.Context, providerId, nonce, code, codeVerifier string) (*domain.User, string, error)
// OauthProviderLogoutUrl returns an IdP logout URL for the given provider if supported.
OauthProviderLogoutUrl(providerId, idTokenHint, postLogoutRedirectUri string) (string, bool)
// IsDefaultPasswordInUse checks if the default admin password is still in use.
IsDefaultPasswordInUse(ctx context.Context) bool
}
type WebAuthnService interface {
@@ -114,16 +116,13 @@ func (e AuthEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup.HandleFunc("POST /webauthn/login/start", e.handleWebAuthnLoginStart())
apiGroup.HandleFunc("POST /webauthn/login/finish", e.handleWebAuthnLoginFinish())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("GET /webauthn/credentials",
e.handleWebAuthnCredentialsGet())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("POST /webauthn/register/start",
e.handleWebAuthnRegisterStart())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("POST /webauthn/register/finish",
e.handleWebAuthnRegisterFinish())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("DELETE /webauthn/credential/{id}",
e.handleWebAuthnCredentialsDelete())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("PUT /webauthn/credential/{id}",
e.handleWebAuthnCredentialsPut())
authenticatedApiGroup := apiGroup.With(e.authenticator.LoggedIn(), e.authenticator.RequireNonDefaultPassword())
authenticatedApiGroup.HandleFunc("GET /webauthn/credentials", e.handleWebAuthnCredentialsGet())
authenticatedApiGroup.HandleFunc("POST /webauthn/register/start", e.handleWebAuthnRegisterStart())
authenticatedApiGroup.HandleFunc("POST /webauthn/register/finish", e.handleWebAuthnRegisterFinish())
authenticatedApiGroup.HandleFunc("DELETE /webauthn/credential/{id}", e.handleWebAuthnCredentialsDelete())
authenticatedApiGroup.HandleFunc("PUT /webauthn/credential/{id}", e.handleWebAuthnCredentialsPut())
apiGroup.HandleFunc("POST /login", e.handleLoginPost())
apiGroup.With(e.authenticator.LoggedIn()).HandleFunc("POST /logout", e.handleLogoutPost())
@@ -174,13 +173,19 @@ func (e AuthEndpoint) handleSessionInfoGet() http.HandlerFunc {
email = &e
}
isDefault := false
if e.authService != nil {
isDefault = e.authService.IsDefaultPasswordInUse(r.Context())
}
respond.JSON(w, http.StatusOK, model.SessionInfo{
LoggedIn: currentSession.LoggedIn,
IsAdmin: currentSession.IsAdmin,
UserIdentifier: loggedInUid,
UserFirstname: firstname,
UserLastname: lastname,
UserEmail: email,
LoggedIn: currentSession.LoggedIn,
IsAdmin: currentSession.IsAdmin,
UserIdentifier: loggedInUid,
UserFirstname: firstname,
UserLastname: lastname,
UserEmail: email,
DefaultPasswordInUse: isDefault,
})
}
}
@@ -345,7 +350,7 @@ func (e AuthEndpoint) handleOauthCallbackGet() http.HandlerFunc {
if returnUrl != nil {
redirectToReturn("success")
} else {
respond.JSON(w, http.StatusOK, user)
respond.JSON(w, http.StatusOK, model.NewUser(user, false))
}
}
}
@@ -362,6 +367,9 @@ func (e AuthEndpoint) setAuthenticatedUser(r *http.Request, user *domain.User, o
currentSession.Firstname = user.Firstname
currentSession.Lastname = user.Lastname
currentSession.Email = user.Email
if e.authService != nil {
currentSession.DefaultPasswordInUse = e.authService.IsDefaultPasswordInUse(r.Context())
}
currentSession.OauthState = ""
currentSession.OauthNonce = ""
@@ -407,7 +415,7 @@ func (e AuthEndpoint) handleLoginPost() http.HandlerFunc {
e.setAuthenticatedUser(r, user, "", "")
respond.JSON(w, http.StatusOK, user)
respond.JSON(w, http.StatusOK, model.NewUser(user, false))
}
}
@@ -142,6 +142,9 @@ func (d dummyAuthService) OauthLoginStep2(_ context.Context, _, _, _, _ string)
func (d dummyAuthService) OauthProviderLogoutUrl(_, _, _ string) (string, bool) {
return "", false
}
func (d dummyAuthService) IsDefaultPasswordInUse(_ context.Context) bool {
return false
}
type dummyValidator struct{}
@@ -65,6 +65,7 @@ func (e InterfaceEndpoint) GetName() string {
func (e InterfaceEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/interface")
apiGroup.Use(e.authenticator.LoggedIn(ScopeAdmin))
apiGroup.Use(e.authenticator.RequireNonDefaultPassword())
apiGroup.HandleFunc("GET /prepare", e.handlePrepareGet())
apiGroup.HandleFunc("GET /all", e.handleAllGet())
@@ -76,6 +76,7 @@ func (e PeerEndpoint) GetName() string {
func (e PeerEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/peer")
apiGroup.Use(e.authenticator.LoggedIn())
apiGroup.Use(e.authenticator.RequireNonDefaultPassword())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /iface/{iface}/all", e.handleAllGet())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /iface/{iface}/stats", e.handleStatsGet())
@@ -27,7 +27,10 @@ func (e TestEndpoint) GetName() string {
func (e TestEndpoint) RegisterRoutes(g *routegroup.Bundle) {
g.HandleFunc("GET /now", e.handleCurrentTimeGet())
g.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /hostname", e.handleHostnameGet())
g.With(
e.authenticator.LoggedIn(ScopeAdmin),
e.authenticator.RequireNonDefaultPassword(),
).HandleFunc("GET /hostname", e.handleHostnameGet())
}
// handleCurrentTimeGet represents the GET endpoint that responds the current time
+14 -14
View File
@@ -72,23 +72,23 @@ func (e UserEndpoint) RegisterRoutes(g *routegroup.Bundle) {
apiGroup := g.Mount("/user")
apiGroup.Use(e.authenticator.LoggedIn())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("GET /all", e.handleAllGet())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("GET /all", e.handleAllGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}", e.handleSingleGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("PUT /{id}", e.handleUpdatePut())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("DELETE /{id}", e.handleDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /new", e.handleCreatePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/peers", e.handlePeersGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/stats", e.handleStatsGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("GET /{id}/interfaces", e.handleInterfacesGet())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/enable", e.handleApiEnablePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/api/disable", e.handleApiDisablePost())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("PUT /{id}", e.handleUpdatePut())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("DELETE /{id}", e.handleDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /new", e.handleCreatePost())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("GET /{id}/peers", e.handlePeersGet())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("GET /{id}/stats", e.handleStatsGet())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("GET /{id}/interfaces", e.handleInterfacesGet())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /{id}/api/enable", e.handleApiEnablePost())
apiGroup.With(e.authenticator.UserIdMatch("id"), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /{id}/api/disable", e.handleApiDisablePost())
apiGroup.With(e.authenticator.UserIdMatch("id")).HandleFunc("POST /{id}/change-password",
e.handleChangePasswordPost())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /bulk-delete", e.handleBulkDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /bulk-enable", e.handleBulkEnable())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /bulk-disable", e.handleBulkDisable())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /bulk-lock", e.handleBulkLock())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin)).HandleFunc("POST /bulk-unlock", e.handleBulkUnlock())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /bulk-delete", e.handleBulkDelete())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /bulk-enable", e.handleBulkEnable())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /bulk-disable", e.handleBulkDisable())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /bulk-lock", e.handleBulkLock())
apiGroup.With(e.authenticator.LoggedIn(ScopeAdmin), e.authenticator.RequireNonDefaultPassword()).HandleFunc("POST /bulk-unlock", e.handleBulkUnlock())
}
// handleAllGet returns a gorm Handler function.
@@ -68,7 +68,7 @@ func (e *WebsocketEndpoint) GetName() string {
}
func (e *WebsocketEndpoint) RegisterRoutes(g *routegroup.Bundle) {
g.With(e.authenticator.LoggedIn()).HandleFunc("GET /ws", e.handleWebsocket())
g.With(e.authenticator.LoggedIn(), e.authenticator.RequireNonDefaultPassword()).HandleFunc("GET /ws", e.handleWebsocket())
}
// StartBackgroundJobs starts background jobs like the expired peers check.
@@ -19,6 +19,7 @@ const (
type UserAuthenticator interface {
IsUserValid(ctx context.Context, id domain.UserIdentifier) bool
IsDefaultPasswordInUse(ctx context.Context) bool
}
type AuthenticationHandler struct {
@@ -126,6 +127,21 @@ func (h AuthenticationHandler) UserIdMatch(idParameter string) func(next http.Ha
}
}
// RequireNonDefaultPassword prohibits actions if the default admin password is still in use.
func (h AuthenticationHandler) RequireNonDefaultPassword() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h.authenticator.IsDefaultPasswordInUse(r.Context()) {
respond.JSON(w, http.StatusForbidden,
model.Error{Code: http.StatusForbidden, Message: "default admin password must be changed first"})
return
}
next.ServeHTTP(w, r)
})
}
}
func UserHasScopes(session SessionData, scopes ...Scope) bool {
// No scopes give, so the check should succeed
if len(scopes) == 0 {
@@ -0,0 +1,82 @@
package handlers
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/h44z/wg-portal/internal/domain"
)
type stubV0UserAuthenticator struct {
valid bool
defaultPasswordInUse bool
}
func (s stubV0UserAuthenticator) IsUserValid(_ context.Context, _ domain.UserIdentifier) bool {
return s.valid
}
func (s stubV0UserAuthenticator) IsDefaultPasswordInUse(_ context.Context) bool {
return s.defaultPasswordInUse
}
func TestAuthenticationHandler_RequireNonDefaultPassword(t *testing.T) {
session := &testSession{data: SessionData{
LoggedIn: true,
IsAdmin: true,
UserIdentifier: "admin@wgportal.local",
}}
t.Run("rejects when default password is in use", func(t *testing.T) {
handler := NewAuthenticationHandler(stubV0UserAuthenticator{valid: true, defaultPasswordInUse: true}, session)
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/api/v0/interface/all", nil)
res := httptest.NewRecorder()
handler.RequireNonDefaultPassword()(next).ServeHTTP(res, req)
if res.Code != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, res.Code)
}
if nextCalled {
t.Fatal("expected downstream handler not to be called")
}
if !strings.Contains(res.Body.String(), "default admin password must be changed first") {
t.Fatalf("expected error message to mention default admin password, got %q", res.Body.String())
}
})
t.Run("allows when default password is not in use", func(t *testing.T) {
handler := NewAuthenticationHandler(stubV0UserAuthenticator{valid: true, defaultPasswordInUse: false}, session)
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/api/v0/interface/all", nil)
res := httptest.NewRecorder()
handler.RequireNonDefaultPassword()(next).ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d", http.StatusOK, res.Code)
}
if !nextCalled {
t.Fatal("expected downstream handler to be called")
}
})
}
+15 -12
View File
@@ -26,6 +26,8 @@ type SessionData struct {
Lastname string
Email string
DefaultPasswordInUse bool
OauthState string
OauthNonce string
OauthCodeVerifier string
@@ -81,17 +83,18 @@ func (s *SessionWrapper) DestroyData(ctx context.Context) {
func (s *SessionWrapper) defaultSessionData() SessionData {
return SessionData{
LoggedIn: false,
IsAdmin: false,
UserIdentifier: "",
Firstname: "",
Lastname: "",
Email: "",
OauthState: "",
OauthNonce: "",
OauthCodeVerifier: "",
OauthProvider: "",
OauthReturnTo: "",
OauthIdToken: "",
LoggedIn: false,
IsAdmin: false,
UserIdentifier: "",
Firstname: "",
Lastname: "",
Email: "",
DefaultPasswordInUse: false,
OauthState: "",
OauthNonce: "",
OauthCodeVerifier: "",
OauthProvider: "",
OauthReturnTo: "",
OauthIdToken: "",
}
}
@@ -32,12 +32,13 @@ func NewLoginProviderInfos(src []domain.LoginProviderInfo) []LoginProviderInfo {
}
type SessionInfo struct {
LoggedIn bool `json:"LoggedIn"`
IsAdmin bool `json:"IsAdmin,omitempty"`
UserIdentifier *string `json:"UserIdentifier,omitempty"`
UserFirstname *string `json:"UserFirstname,omitempty"`
UserLastname *string `json:"UserLastname,omitempty"`
UserEmail *string `json:"UserEmail,omitempty"`
LoggedIn bool `json:"LoggedIn"`
IsAdmin bool `json:"IsAdmin,omitempty"`
UserIdentifier *string `json:"UserIdentifier,omitempty"`
UserFirstname *string `json:"UserFirstname,omitempty"`
UserLastname *string `json:"UserLastname,omitempty"`
UserEmail *string `json:"UserEmail,omitempty"`
DefaultPasswordInUse bool `json:"DefaultPasswordInUse"`
}
type OauthInitiationResponse struct {
+23 -20
View File
@@ -4,6 +4,7 @@ import (
"time"
"github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
@@ -19,11 +20,12 @@ type User struct {
Department string `json:"Department"`
Notes string `json:"Notes"`
Password string `json:"Password,omitempty"`
Disabled bool `json:"Disabled"` // if this field is set, the user is disabled
DisabledReason string `json:"DisabledReason"` // the reason why the user has been disabled
Locked bool `json:"Locked"` // if this field is set, the user is locked
LockedReason string `json:"LockedReason"` // the reason why the user has been locked
Password string `json:"Password,omitempty"`
DefaultPasswordInUse bool `json:"DefaultPasswordInUse"`
Disabled bool `json:"Disabled"` // if this field is set, the user is disabled
DisabledReason string `json:"DisabledReason"` // the reason why the user has been disabled
Locked bool `json:"Locked"` // if this field is set, the user is locked
LockedReason string `json:"LockedReason"` // the reason why the user has been locked
ApiToken string `json:"ApiToken"`
ApiTokenCreated *time.Time `json:"ApiTokenCreated,omitempty"`
@@ -43,21 +45,22 @@ func NewUser(src *domain.User, exposeCreds bool) *User {
AuthSources: internal.Map(src.Authentications, func(authentication domain.UserAuthentication) string {
return string(authentication.Source)
}),
IsAdmin: src.IsAdmin,
Firstname: src.Firstname,
Lastname: src.Lastname,
Phone: src.Phone,
Department: src.Department,
Notes: src.Notes,
Password: "", // never fill password
Disabled: src.IsDisabled(),
DisabledReason: src.DisabledReason,
Locked: src.IsLocked(),
LockedReason: src.LockedReason,
ApiToken: "", // by default, do not expose API token
ApiTokenCreated: src.ApiTokenCreated,
ApiEnabled: src.IsApiEnabled(),
PersistLocalChanges: src.PersistLocalChanges,
IsAdmin: src.IsAdmin,
Firstname: src.Firstname,
Lastname: src.Lastname,
Phone: src.Phone,
Department: src.Department,
Notes: src.Notes,
Password: "", // never fill password
DefaultPasswordInUse: src.CheckPassword(config.DefaultAdminPassword) == nil,
Disabled: src.IsDisabled(),
DisabledReason: src.DisabledReason,
Locked: src.IsLocked(),
LockedReason: src.LockedReason,
ApiToken: "", // by default, do not expose API token
ApiTokenCreated: src.ApiTokenCreated,
ApiEnabled: src.IsApiEnabled(),
PersistLocalChanges: src.PersistLocalChanges,
PeerCount: src.LinkedPeerCount,
}
@@ -18,6 +18,7 @@ const (
type UserAuthenticator interface {
IsUserValid(ctx context.Context, id domain.UserIdentifier) bool
IsDefaultPasswordInUse(ctx context.Context) bool
}
type UserRepository interface {
@@ -74,6 +75,12 @@ func (h AuthenticationHandler) LoggedIn(scopes ...Scope) func(next http.Handler)
return
}
if h.authenticator.IsDefaultPasswordInUse(r.Context()) {
respond.JSON(w, http.StatusForbidden,
model.Error{Code: http.StatusForbidden, Message: "default admin password must be changed first"})
return
}
if !UserHasScopes(user, scopes...) {
// Abort the request with the appropriate error code
respond.JSON(w, http.StatusForbidden,
@@ -12,13 +12,18 @@ import (
)
type stubUserAuthenticator struct {
valid bool
valid bool
defaultPasswordInUse bool
}
func (s stubUserAuthenticator) IsUserValid(ctx context.Context, id domain.UserIdentifier) bool {
return s.valid
}
func (s stubUserAuthenticator) IsDefaultPasswordInUse(ctx context.Context) bool {
return s.defaultPasswordInUse
}
type stubUserRepository struct {
user *domain.User
err error
@@ -114,3 +119,35 @@ func TestAuthenticationHandler_LoggedInAllowsValidUser(t *testing.T) {
t.Fatal("expected downstream handler to be called")
}
}
func TestAuthenticationHandler_LoggedInRejectsDefaultPassword(t *testing.T) {
user := &domain.User{
Identifier: "test-user",
ApiToken: "token",
}
handler := NewAuthenticationHandler(stubUserAuthenticator{valid: true, defaultPasswordInUse: true}, stubUserRepository{user: user})
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.SetBasicAuth(string(user.Identifier), user.ApiToken)
rr := httptest.NewRecorder()
handler.LoggedIn()(next).ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, rr.Code)
}
if nextCalled {
t.Fatal("expected downstream handler not to be called")
}
if !strings.Contains(rr.Body.String(), "default admin password must be changed first") {
t.Fatalf("expected error message to mention default password, got %q", rr.Body.String())
}
}
+7
View File
@@ -31,6 +31,8 @@ type UserManager interface {
RegisterUser(ctx context.Context, user *domain.User) error
// UpdateUserInternal updates an existing user in the database.
UpdateUserInternal(ctx context.Context, user *domain.User) (*domain.User, error)
// IsDefaultPasswordInUse checks if the default admin password is still in use.
IsDefaultPasswordInUse(ctx context.Context) bool
}
type EventBus interface {
@@ -135,6 +137,11 @@ func NewAuthenticator(cfg *config.Auth, extUrl, basePath string, bus EventBus, u
return a, nil
}
// IsDefaultPasswordInUse checks if the default admin password is still in use.
func (a *Authenticator) IsDefaultPasswordInUse(ctx context.Context) bool {
return a.users.IsDefaultPasswordInUse(ctx)
}
// StartBackgroundJobs starts the background jobs for the authenticator.
// It sets up the external authentication providers (OIDC, OAuth, LDAP) and retries in case of errors.
func (a *Authenticator) StartBackgroundJobs(ctx context.Context) {
+100
View File
@@ -0,0 +1,100 @@
package users
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
)
type mockUserDatabaseRepo struct {
users map[domain.UserIdentifier]*domain.User
}
func (m *mockUserDatabaseRepo) GetUser(_ context.Context, id domain.UserIdentifier) (*domain.User, error) {
u, ok := m.users[id]
if !ok {
return nil, domain.ErrNotFound
}
return u, nil
}
func (m *mockUserDatabaseRepo) GetUserByEmail(_ context.Context, email string) (*domain.User, error) {
for _, u := range m.users {
if u.Email == email {
return u, nil
}
}
return nil, domain.ErrNotFound
}
func (m *mockUserDatabaseRepo) GetUserByWebAuthnCredential(_ context.Context, _ string) (*domain.User, error) {
return nil, domain.ErrNotFound
}
func (m *mockUserDatabaseRepo) GetAllUsers(_ context.Context) ([]domain.User, error) {
res := make([]domain.User, 0, len(m.users))
for _, u := range m.users {
res = append(res, *u)
}
return res, nil
}
func (m *mockUserDatabaseRepo) FindUsers(_ context.Context, _ string) ([]domain.User, error) {
return nil, nil
}
func (m *mockUserDatabaseRepo) SaveUser(_ context.Context, id domain.UserIdentifier, updateFunc func(u *domain.User) (*domain.User, error)) error {
u, ok := m.users[id]
if !ok {
return domain.ErrNotFound
}
updated, err := updateFunc(u)
if err != nil {
return err
}
m.users[id] = updated
return nil
}
func (m *mockUserDatabaseRepo) DeleteUser(_ context.Context, id domain.UserIdentifier) error {
delete(m.users, id)
return nil
}
func TestManager_IsDefaultPasswordInUse(t *testing.T) {
cfg := &config.Config{}
cfg.Core.AdminUser = config.DefaultAdminUser
cfg.Core.AdminPassword = config.DefaultAdminPassword
defaultAdminUser := &domain.User{
Identifier: domain.UserIdentifier(config.DefaultAdminUser),
IsAdmin: true,
Password: domain.PrivateString(config.DefaultAdminPassword),
Authentications: []domain.UserAuthentication{
{Source: domain.UserSourceDatabase},
},
}
require.NoError(t, defaultAdminUser.HashPassword())
repo := &mockUserDatabaseRepo{
users: map[domain.UserIdentifier]*domain.User{
defaultAdminUser.Identifier: defaultAdminUser,
},
}
mgr, err := NewUserManager(cfg, nil, repo, nil, nil)
require.NoError(t, err)
assert.True(t, mgr.IsDefaultPasswordInUse(context.Background()))
// Change admin password to something else
defaultAdminUser.Password = "new-secure-password"
require.NoError(t, defaultAdminUser.HashPassword())
assert.False(t, mgr.IsDefaultPasswordInUse(context.Background()))
}
+28
View File
@@ -281,6 +281,34 @@ func (m Manager) DeactivateApi(ctx context.Context, id domain.UserIdentifier) (*
return user, nil
}
// IsDefaultPasswordInUse checks if the default admin user or any admin user is still using the default password.
func (m Manager) IsDefaultPasswordInUse(ctx context.Context) bool {
adminCtx := domain.SetUserInfo(ctx, domain.SystemAdminContextUserInfo())
adminUserId := domain.UserIdentifier(m.cfg.Core.AdminUser)
if adminUserId == "" {
adminUserId = config.DefaultAdminUser
}
adminUser, err := m.users.GetUser(adminCtx, adminUserId)
if err == nil && adminUser != nil {
if adminUser.CheckPassword(config.DefaultAdminPassword) == nil {
return true
}
}
allUsers, err := m.users.GetAllUsers(adminCtx)
if err == nil {
for _, u := range allUsers {
if u.IsAdmin && u.CheckPassword(config.DefaultAdminPassword) == nil {
return true
}
}
}
return false
}
func (m Manager) validateModifications(ctx context.Context, old, new *domain.User) error {
currentUser := domain.GetUserInfo(ctx)
+7 -2
View File
@@ -12,6 +12,11 @@ import (
"gopkg.in/yaml.v3"
)
const (
DefaultAdminUser = "admin@wgportal.local"
DefaultAdminPassword = "wgportal-default"
)
// Config is the main configuration struct.
type Config struct {
Core struct {
@@ -128,8 +133,8 @@ func defaultConfig() *Config {
cfg := &Config{}
cfg.Core.AdminUserDisabled = getEnvBool("WG_PORTAL_CORE_DISABLE_ADMIN_USER", false)
cfg.Core.AdminUser = getEnvStr("WG_PORTAL_CORE_ADMIN_USER", "admin@wgportal.local")
cfg.Core.AdminPassword = getEnvStr("WG_PORTAL_CORE_ADMIN_PASSWORD", "wgportal-default")
cfg.Core.AdminUser = getEnvStr("WG_PORTAL_CORE_ADMIN_USER", DefaultAdminUser)
cfg.Core.AdminPassword = getEnvStr("WG_PORTAL_CORE_ADMIN_PASSWORD", DefaultAdminPassword)
cfg.Core.AdminApiToken = getEnvStr("WG_PORTAL_CORE_ADMIN_API_TOKEN", "") // by default, the API access is disabled
cfg.Core.ImportExisting = getEnvBool("WG_PORTAL_CORE_IMPORT_EXISTING", true)
cfg.Core.RestoreState = getEnvBool("WG_PORTAL_CORE_RESTORE_STATE", true)