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
+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)