Files
mtusi2026lab3/internal/auth/service_test.go
T

157 lines
5.0 KiB
Go

package auth_test
import (
"context"
"encoding/base64"
"errors"
"strings"
"testing"
"time"
"messenger/internal/auth"
authstore "messenger/internal/auth/store"
"messenger/internal/platform/apperr"
"messenger/internal/user"
userstore "messenger/internal/user/store"
)
const pw = "correct-horse-battery"
type fixture struct {
ctx context.Context
svc *auth.Service
alice user.User
}
// newFixture wires the real users service and session store over empty
// databases and registers alice.
func newFixture(t *testing.T, ttl time.Duration) fixture {
t.Helper()
db.Reset(t)
kv.Reset(t)
ctx := context.Background()
users := user.NewService(userstore.NewUsers(db.Pool))
alice, err := users.Register(ctx, "alice", "Алиса", pw)
if err != nil {
t.Fatal(err)
}
return fixture{ctx: ctx, svc: auth.NewService(users, authstore.NewSessions(kv.Client), ttl), alice: alice}
}
func TestLoginIssuesOpaqueTokenBackedByStoredSession(t *testing.T) {
f := newFixture(t, time.Hour)
before := time.Now()
issued, err := f.svc.Login(f.ctx, "alice", pw)
after := time.Now()
if err != nil {
t.Fatalf("Login: %v", err)
}
raw, err := base64.RawURLEncoding.DecodeString(issued.Token)
if err != nil || len(raw) != 32 {
t.Fatalf("token %q must be 32 random bytes in base64url, got %d bytes, %v", issued.Token, len(raw), err)
}
if strings.Contains(issued.Token, f.alice.ID.String()) || strings.Contains(issued.Token, "alice") {
t.Fatal("token must not carry the identity")
}
if issued.User != f.alice {
t.Fatalf("User = %+v, want alice", issued.User)
}
if issued.ExpiresAt.Before(before.Add(time.Hour).Add(-time.Millisecond)) || issued.ExpiresAt.After(after.Add(time.Hour)) {
t.Fatalf("ExpiresAt = %v, want login time + 1h", issued.ExpiresAt)
}
key := "session:" + auth.HashToken(issued.Token)
owner, err := kv.Client.Get(f.ctx, key).Result()
if err != nil || owner != f.alice.ID.String() {
t.Fatalf("stored owner = %q, %v; want alice", owner, err)
}
expireAt, err := kv.Client.PExpireTime(f.ctx, key).Result()
if err != nil || expireAt != time.Duration(issued.ExpiresAt.UnixMilli())*time.Millisecond {
t.Fatalf("store expiry = %v, %v; want the absolute ExpiresAt %d ms", expireAt, err, issued.ExpiresAt.UnixMilli())
}
keys, err := kv.Client.Keys(f.ctx, "*").Result()
if err != nil {
t.Fatal(err)
}
for _, k := range keys {
if strings.Contains(k, issued.Token) {
t.Fatal("the raw token must never be stored")
}
}
}
func TestLoginWithBadCredentialsCreatesNoSession(t *testing.T) {
f := newFixture(t, time.Hour)
for name, in := range map[string][2]string{
"wrong password": {"alice", pw + "!"},
"unknown user": {"mallory", pw},
} {
if _, err := f.svc.Login(f.ctx, in[0], in[1]); !errors.Is(err, user.ErrInvalidCredentials) {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
}
if n, err := kv.Client.DBSize(f.ctx).Result(); err != nil || n != 0 {
t.Fatalf("sessions = %d, %v; want none", n, err)
}
}
func TestAuthenticateResolvesTheOwner(t *testing.T) {
f := newFixture(t, time.Hour)
first, _ := f.svc.Login(f.ctx, "alice", pw)
second, _ := f.svc.Login(f.ctx, "alice", pw)
if first.Token == second.Token {
t.Fatal("every login must get its own token")
}
for _, token := range []string{first.Token, second.Token} {
id, err := f.svc.Authenticate(f.ctx, token)
if err != nil || id != f.alice.ID {
t.Fatalf("Authenticate = %v, %v; want alice", id, err)
}
}
_, err := f.svc.Authenticate(f.ctx, "unknown-token")
if !errors.Is(err, auth.ErrUnauthenticated) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Fatalf("unknown token: err = %v, want ErrUnauthenticated", err)
}
}
func TestLogoutRevokesOnlyThatSession(t *testing.T) {
f := newFixture(t, time.Hour)
first, _ := f.svc.Login(f.ctx, "alice", pw)
second, _ := f.svc.Login(f.ctx, "alice", pw)
if err := f.svc.Logout(f.ctx, first.Token); err != nil {
t.Fatalf("Logout: %v", err)
}
if _, err := f.svc.Authenticate(f.ctx, first.Token); !errors.Is(err, auth.ErrUnauthenticated) {
t.Fatalf("revoked token: err = %v, want ErrUnauthenticated", err)
}
if id, err := f.svc.Authenticate(f.ctx, second.Token); err != nil || id != f.alice.ID {
t.Fatalf("other session: %v, %v; want still valid", id, err)
}
}
// Valkey enforces the expiry by the Docker VM clock, which may lag this host
// by a fraction of a second, so the expiry is awaited with a tolerance.
func TestSessionExpiresAfterTTL(t *testing.T) {
const clockTolerance = 3 * time.Second
f := newFixture(t, time.Second)
issued, err := f.svc.Login(f.ctx, "alice", pw)
if err != nil {
t.Fatal(err)
}
if _, err := f.svc.Authenticate(f.ctx, issued.Token); err != nil {
t.Fatalf("fresh session: %v", err)
}
time.Sleep(time.Until(issued.ExpiresAt))
deadline := time.Now().Add(clockTolerance)
for {
_, err := f.svc.Authenticate(f.ctx, issued.Token)
if errors.Is(err, auth.ErrUnauthenticated) {
return
}
if time.Now().After(deadline) {
t.Fatalf("expired session: err = %v %v after ExpiresAt, want ErrUnauthenticated", err, clockTolerance)
}
time.Sleep(100 * time.Millisecond)
}
}