From aef012ed0254c56f82b8698d810c05423d37249e Mon Sep 17 00:00:00 2001 From: Stanislav Chzhen Date: Tue, 26 Aug 2025 13:14:39 +0300 Subject: [PATCH] home: add tests --- internal/home/auth.go | 30 ++++-- internal/home/authhttp.go | 4 +- internal/home/authratelimiter.go | 6 +- internal/home/home.go | 2 +- internal/home/profilehttp.go | 13 ++- internal/home/profilehttp_internal_test.go | 119 +++++++++++++++++++++ 6 files changed, 158 insertions(+), 16 deletions(-) create mode 100644 internal/home/profilehttp_internal_test.go diff --git a/internal/home/auth.go b/internal/home/auth.go index f0e074c0..f586766b 100644 --- a/internal/home/auth.go +++ b/internal/home/auth.go @@ -54,7 +54,7 @@ type authConfig struct { // rateLimiter manages the rate limiting for login attempts. It must not be // nil. - rateLimiter loginRaateLimiter + rateLimiter loginRateLimiter // trustedProxies is a set of subnets considered as trusted. trustedProxies netutil.SubnetSet @@ -75,12 +75,27 @@ type authConfig struct { // auth stores web user information and handles authentication. type auth struct { - logger *slog.Logger - rateLimiter loginRaateLimiter + // logger is used to log the operation of the auth module. + logger *slog.Logger + + // rateLimiter manages rate limiting for login attempts. + rateLimiter loginRateLimiter + + // trustedProxies is a set of subnets considered trusted. trustedProxies netutil.SubnetSet - sessions aghuser.SessionStorage - users aghuser.DB - isGLiNet bool + + // sessions stores web users' sessions. + sessions aghuser.SessionStorage + + // users stores user credentials. + users aghuser.DB + + // isGLiNet indicates whether GLiNet mode is enabled. + isGLiNet bool + + // isUserless indicates that there are no users defined in the configuration + // file. + isUserless bool } // newAuth returns the new properly initialized *auth. @@ -111,6 +126,7 @@ func newAuth(ctx context.Context, conf *authConfig) (a *auth, err error) { sessions: s, users: userDB, isGLiNet: conf.isGLiNet, + isUserless: len(conf.users) == 0, }, nil } @@ -174,6 +190,8 @@ func (a *auth) addUser(ctx context.Context, u *webUser, password string) (err er panic(err) } + a.isUserless = false + a.logger.DebugContext(ctx, "added user", "login", u.Name) return nil diff --git a/internal/home/authhttp.go b/internal/home/authhttp.go index bc8e7068..e5517933 100644 --- a/internal/home/authhttp.go +++ b/internal/home/authhttp.go @@ -320,7 +320,7 @@ type authMiddlewareDefaultConfig struct { logger *slog.Logger // rateLimiter manages the rate limiting for login attempts. - rateLimiter loginRaateLimiter + rateLimiter loginRateLimiter // trustedProxies is a set of subnets considered as trusted. // @@ -340,7 +340,7 @@ type authMiddlewareDefaultConfig struct { // passes it with the context. type authMiddlewareDefault struct { logger *slog.Logger - rateLimiter loginRaateLimiter + rateLimiter loginRateLimiter trustedProxies netutil.SubnetSet sessions aghuser.SessionStorage users aghuser.DB diff --git a/internal/home/authratelimiter.go b/internal/home/authratelimiter.go index 95e8d571..dee88ff1 100644 --- a/internal/home/authratelimiter.go +++ b/internal/home/authratelimiter.go @@ -9,8 +9,8 @@ import ( // cache. const failedAuthTTL = 1 * time.Minute -// loginRaateLimiter is an interface for rate limiting login attempts. -type loginRaateLimiter interface { +// loginRateLimiter is an interface for rate limiting login attempts. +type loginRateLimiter interface { // check returns the duration of time left until a user is unblocked. // A non-positive result indicates that the user is not blocked. check(usrID string) (left time.Duration) @@ -66,7 +66,7 @@ func newAuthRateLimiter(blockDur time.Duration, maxAttempts uint) (ab *authRateL } // type check -var _ loginRaateLimiter = (*authRateLimiter)(nil) +var _ loginRateLimiter = (*authRateLimiter)(nil) // cleanupLocked checks each blocked users removing ones with expired TTL. For // internal use only. diff --git a/internal/home/home.go b/internal/home/home.go index 459474d6..ac180ff7 100644 --- a/internal/home/home.go +++ b/internal/home/home.go @@ -863,7 +863,7 @@ func initUsers( baseLogger *slog.Logger, isGLiNet bool, ) (auth *auth, err error) { - var rateLimiter loginRaateLimiter + var rateLimiter loginRateLimiter if config.AuthAttempts > 0 && config.AuthBlockMin > 0 { blockDur := time.Duration(config.AuthBlockMin) * time.Minute rateLimiter = newAuthRateLimiter(blockDur, config.AuthAttempts) diff --git a/internal/home/profilehttp.go b/internal/home/profilehttp.go index 1a89851a..42392501 100644 --- a/internal/home/profilehttp.go +++ b/internal/home/profilehttp.go @@ -47,10 +47,15 @@ type profileJSON struct { // handleGetProfile is the handler for GET /control/profile endpoint. func (web *webAPI) handleGetProfile(w http.ResponseWriter, r *http.Request) { var name string - u, ok := webUserFromContext(r.Context()) - // There may be no user in the context if the configuration file defines no - // users. - if ok { + + if !(web.auth.isUserless || web.auth.isGLiNet) { + u, ok := webUserFromContext(r.Context()) + if !ok { + w.WriteHeader(http.StatusUnauthorized) + + return + } + name = string(u.Login) } diff --git a/internal/home/profilehttp_internal_test.go b/internal/home/profilehttp_internal_test.go new file mode 100644 index 00000000..56f07d22 --- /dev/null +++ b/internal/home/profilehttp_internal_test.go @@ -0,0 +1,119 @@ +package home + +import ( + "encoding/binary" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/AdguardTeam/AdGuardHome/internal/agh" + "github.com/AdguardTeam/golibs/testutil" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/bcrypt" +) + +func TestWeb_HandleGetProfile(t *testing.T) { + storeGlobals(t) + + const ( + testTTL = 60 + + glTokenFileSuffix = "test" + + userName = "name" + userPassword = "password" + + path = "/control/profile" + ) + + passwordHash, err := bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost) + require.NoError(t, err) + + tempDir := t.TempDir() + glFilePrefix = tempDir + "/gl_token_" + glTokenFile := glFilePrefix + glTokenFileSuffix + + glFileData := make([]byte, 4) + binary.NativeEndian.PutUint32(glFileData, uint32(time.Now().Unix()+testTTL)) + + err = os.WriteFile(glTokenFile, glFileData, 0o644) + require.NoError(t, err) + + sessionsDB := filepath.Join(tempDir, "sessions.db") + + user := &webUser{ + Name: userName, + PasswordHash: string(passwordHash), + } + + auth, err := newAuth(testutil.ContextWithTimeout(t, testTimeout), &authConfig{ + baseLogger: testLogger, + rateLimiter: emptyRateLimiter{}, + trustedProxies: nil, + dbFilename: sessionsDB, + users: nil, + sessionTTL: testTTL * time.Second, + isGLiNet: false, + }) + require.NoError(t, err) + + t.Cleanup(func() { auth.close(testutil.ContextWithTimeout(t, testTimeout)) }) + + globalContext.mux = http.NewServeMux() + + tlsMgr, err := newTLSManager(testutil.ContextWithTimeout(t, testTimeout), &tlsManagerConfig{ + logger: testLogger, + confModifier: agh.EmptyConfigModifier{}, + }) + require.NoError(t, err) + + web, err := initWeb( + testutil.ContextWithTimeout(t, testTimeout), + options{}, + nil, + nil, + testLogger, + tlsMgr, + auth, + agh.EmptyConfigModifier{}, + false, + ) + require.NoError(t, err) + + globalContext.web = web + + mux := auth.middleware().Wrap(globalContext.mux) + + require.True(t, t.Run("userless", func(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, path, nil) + + web.handleGetProfile(w, r) + assert.Equal(t, http.StatusOK, w.Code) + })) + + require.True(t, t.Run("add_user", func(t *testing.T) { + ctx := testutil.ContextWithTimeout(t, testTimeout) + err = auth.addUser(ctx, user, userPassword) + require.NoError(t, err) + + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, path, nil) + + web.handleGetProfile(w, r) + assert.Equal(t, http.StatusUnauthorized, w.Code) + + w = httptest.NewRecorder() + r = httptest.NewRequest(http.MethodGet, path, nil) + + loginCookie := generateAuthCookie(t, mux, userName, userPassword) + r.AddCookie(loginCookie) + + web.handleGetProfile(w, r) + assert.Equal(t, http.StatusUnauthorized, w.Code) + })) +}