Files

233 lines
7.7 KiB
Go

package authentication
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab2/internal/store"
)
type accountFixture struct {
user dto.UserDTO
hash string
tokenHash string
expiry time.Time
failure error
registerFailure error
saveFailure error
}
// Register captures one synthetic account or a prescribed persistence failure.
func (f *accountFixture) Register(_ context.Context, user dto.UserDTO, hash string) (dto.UserDTO, error) {
f.user = user
f.hash = hash
return user, f.registerFailure
}
// Credentials returns the fixture account and its password encoding.
func (f *accountFixture) Credentials(context.Context, string) (dto.UserDTO, string, error) {
return f.user, f.hash, f.failure
}
// SaveSession captures the digest and absolute expiry without storing the raw token.
func (f *accountFixture) SaveSession(_ context.Context, hash string, _ uuid.UUID, expiry time.Time) error {
f.tokenHash = hash
f.expiry = expiry
return f.saveFailure
}
// SessionUser implements expiry and revocation for the service unit fixture.
func (f *accountFixture) SessionUser(_ context.Context, hash string) (uuid.UUID, error) {
if f.failure != nil {
return uuid.Nil, f.failure
}
if hash != f.tokenHash || !f.expiry.After(time.Now()) {
return uuid.Nil, store.ErrNotFound
}
return f.user.ID, nil
}
// RevokeSession invalidates the fixture digest.
func (f *accountFixture) RevokeSession(context.Context, string) error {
f.tokenHash = ""
return f.failure
}
type passwordFixture struct {
failure error
}
// Hash creates an intentionally noncryptographic encoding for service-only unit tests.
func (f passwordFixture) Hash(password string) (string, error) {
return "fixture:" + password, f.failure
}
// Verify compares only test fixture encodings; production uses Argon2id.
func (passwordFixture) Verify(encoded, password string) bool {
return encoded == "fixture:"+password
}
// authFixture assembles deterministic service boundaries.
func authFixture(t *testing.T) (*Service, *accountFixture) {
t.Helper()
accounts := &accountFixture{user: dto.UserDTO{ID: uuid.New(), Username: "alice"}, hash: "fixture:synthetic-password"}
s, err := New(accounts, passwordFixture{}, time.Hour)
if err != nil {
t.Fatal(err)
}
return s, accounts
}
// TestRegisterValidatesPassword checks contract boundaries without truncation.
func TestRegisterValidatesPassword(t *testing.T) {
cases := []struct {
name string
password string
valid bool
}{
{"short", "short", false},
{"minimum", strings.Repeat("a", 12), true},
{"unicode maximum", strings.Repeat("🔐", 128), true},
{"too long", strings.Repeat("a", 129), false},
{"invalid UTF8", strings.Repeat("a", 12) + "\xff", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, _ := authFixture(t)
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, tc.password)
if (err == nil) != tc.valid {
t.Fatalf("unexpected registration result: %v", err)
}
})
}
}
// TestRegisterConflictMapsToApplicationError verifies uniqueness error translation.
func TestRegisterConflictMapsToApplicationError(t *testing.T) {
s, accounts := authFixture(t)
accounts.registerFailure = store.ErrConflict
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
if !errors.Is(err, service.ErrConflict) {
t.Fatal(err)
}
}
// TestRegisterHashFailurePreservesCause checks KDF failures before persistence.
func TestRegisterHashFailurePreservesCause(t *testing.T) {
s, _ := authFixture(t)
failure := errors.New("KDF unavailable")
s.passwords = passwordFixture{failure: failure}
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
if !errors.Is(err, failure) {
t.Fatal(err)
}
}
// TestLoginPersistsOnlyTokenDigest checks issued entropy, owner and deadline together.
func TestLoginPersistsOnlyTokenDigest(t *testing.T) {
s, accounts := authFixture(t)
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if err != nil {
t.Fatal(err)
}
if session.Token == accounts.tokenHash || len(accounts.tokenHash) != 64 || session.User.ID != accounts.user.ID || !session.ExpiresAt.Equal(accounts.expiry) {
t.Fatal("invalid issued session")
}
id, err := s.Authenticate(t.Context(), session.Token)
if err != nil || id != accounts.user.ID.String() {
t.Fatalf("session does not authenticate its owner: %v", err)
}
}
// TestLoginRejectsCredentials checks independent authentication rejection scenarios.
func TestLoginRejectsCredentials(t *testing.T) {
cases := []struct {
name string
password string
failure error
expected error
}{
{"short password", "short", nil, service.ErrUnauthorized},
{"wrong password", "incorrect-password", nil, service.ErrUnauthorized},
{"missing account", "synthetic-password", store.ErrNotFound, service.ErrUnauthorized},
{"database unavailable", "synthetic-password", context.DeadlineExceeded, context.DeadlineExceeded},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, accounts := authFixture(t)
accounts.failure = tc.failure
_, err := s.Login(t.Context(), "alice", tc.password)
if !errors.Is(err, tc.expected) {
t.Fatalf("expected %v, got %v", tc.expected, err)
}
})
}
}
// TestLoginDoesNotReturnUnpersistedSession checks failure after successful password verification.
func TestLoginDoesNotReturnUnpersistedSession(t *testing.T) {
s, accounts := authFixture(t)
accounts.saveFailure = context.DeadlineExceeded
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if !errors.Is(err, context.DeadlineExceeded) || session.Token != "" {
t.Fatal("unpersisted session escaped")
}
}
// TestAuthenticateRejectsUnknownToken checks malformed and correctly encoded unknown tokens.
func TestAuthenticateRejectsUnknownToken(t *testing.T) {
for _, token := range []string{"", "%%%", strings.Repeat("A", 43)} {
t.Run(token, func(t *testing.T) {
s, _ := authFixture(t)
if _, err := s.Authenticate(t.Context(), token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal(err)
}
})
}
}
// TestAuthenticatePropagatesDatabaseFailure prevents trusting a token during an outage.
func TestAuthenticatePropagatesDatabaseFailure(t *testing.T) {
s, accounts := authFixture(t)
accounts.failure = context.DeadlineExceeded
if _, err := s.Authenticate(t.Context(), strings.Repeat("A", 43)); !errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
}
}
// TestLogoutRevokesIssuedToken checks that the same token cannot be reused.
func TestLogoutRevokesIssuedToken(t *testing.T) {
s, _ := authFixture(t)
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if err != nil {
t.Fatal(err)
}
if err := s.Logout(t.Context(), session.Token); err != nil {
t.Fatal(err)
}
if _, err := s.Authenticate(t.Context(), session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("revoked token authenticated")
}
}
// TestNewRejectsIncompleteDependencies checks constructor validation and KDF startup failure.
func TestNewRejectsIncompleteDependencies(t *testing.T) {
t.Run("missing accounts", func(t *testing.T) {
if _, err := New(nil, passwordFixture{}, time.Hour); err == nil {
t.Fatal("missing accounts accepted")
}
})
t.Run("hash failure", func(t *testing.T) {
if _, err := New(&accountFixture{}, passwordFixture{failure: context.Canceled}, time.Hour); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
})
}