- feat(config): TOML config with env overrides, strict parsing and validation - feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun, embedded per-driver SQL migrations with a transactional runner - feat(schema): catalog tables (artists, albums, tracks, audio_files with per-root paths), users and listening events with idempotency keys - feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only registration and login - feat(api): gin REST API under /api/v1 (health, register, login, listens) with a consistent error envelope, body limit and request logging - feat(sondad): zap logger, graceful shutdown, composition root in main - chore: example config, .gitignore for secrets, DB files, IDE and agent files
202 lines
5.1 KiB
Go
202 lines
5.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// ---- password hashing ----
|
|
|
|
func TestHashAndVerify(t *testing.T) {
|
|
h, err := HashPassword("correct horse")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.HasPrefix(h, "$argon2id$") {
|
|
t.Fatalf("hash = %q, want argon2id PHC string", h)
|
|
}
|
|
if !VerifyPassword(h, "correct horse") {
|
|
t.Error("correct password rejected")
|
|
}
|
|
if VerifyPassword(h, "wrong") {
|
|
t.Error("wrong password accepted")
|
|
}
|
|
}
|
|
|
|
func TestHashIsSalted(t *testing.T) {
|
|
a, _ := HashPassword("same")
|
|
b, _ := HashPassword("same")
|
|
if a == b {
|
|
t.Error("two hashes of the same password are identical")
|
|
}
|
|
}
|
|
|
|
func TestVerifyRejectsGarbage(t *testing.T) {
|
|
for _, h := range []string{"", "plaintext", "$argon2id$v=19$m=1,t=1,p=1$bad", "$bcrypt$x$y"} {
|
|
if VerifyPassword(h, "x") {
|
|
t.Errorf("garbage hash %q accepted", h)
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- tokens ----
|
|
|
|
const testSecret = "0123456789abcdef0123456789abcdef"
|
|
|
|
func TestTokenRoundTrip(t *testing.T) {
|
|
iss := NewTokenIssuer(testSecret, time.Hour)
|
|
tok, exp, err := iss.Issue(User{ID: 7, Username: "bob"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if time.Until(exp) <= 0 {
|
|
t.Error("expiry is not in the future")
|
|
}
|
|
claims, err := iss.Parse(tok)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if claims.UserID != 7 || claims.Username != "bob" {
|
|
t.Errorf("claims = %+v", claims)
|
|
}
|
|
}
|
|
|
|
func TestTokenExpired(t *testing.T) {
|
|
iss := NewTokenIssuer(testSecret, time.Hour)
|
|
iss.now = func() time.Time { return time.Now().Add(-2 * time.Hour) }
|
|
tok, _, err := iss.Issue(User{ID: 1, Username: "a"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
iss.now = time.Now
|
|
if _, err := iss.Parse(tok); err == nil {
|
|
t.Fatal("expired token accepted")
|
|
}
|
|
}
|
|
|
|
func TestTokenWrongSecret(t *testing.T) {
|
|
tok, _, _ := NewTokenIssuer(testSecret, time.Hour).Issue(User{ID: 1, Username: "a"})
|
|
other := NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour)
|
|
if _, err := other.Parse(tok); err == nil {
|
|
t.Fatal("token signed with another secret accepted")
|
|
}
|
|
}
|
|
|
|
func TestTokenRejectsAlgNone(t *testing.T) {
|
|
claims := jwt.RegisteredClaims{
|
|
Subject: "1",
|
|
Issuer: tokenIssuerName,
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
|
}
|
|
tok, err := jwt.NewWithClaims(jwt.SigningMethodNone, claims).SignedString(jwt.UnsafeAllowNoneSignatureType)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := NewTokenIssuer(testSecret, time.Hour).Parse(tok); err == nil {
|
|
t.Fatal("alg=none token accepted")
|
|
}
|
|
}
|
|
|
|
func TestTokenGarbage(t *testing.T) {
|
|
if _, err := NewTokenIssuer(testSecret, time.Hour).Parse("not.a.jwt"); err == nil {
|
|
t.Fatal("garbage token accepted")
|
|
}
|
|
}
|
|
|
|
// ---- service ----
|
|
|
|
type fakeStore struct {
|
|
users map[string]fakeUser
|
|
next int64
|
|
}
|
|
|
|
type fakeUser struct {
|
|
u User
|
|
hash string
|
|
}
|
|
|
|
func newFakeStore() *fakeStore { return &fakeStore{users: map[string]fakeUser{}} }
|
|
|
|
func (f *fakeStore) CountUsers(context.Context) (int, error) { return len(f.users), nil }
|
|
|
|
func (f *fakeStore) CreateUser(_ context.Context, username, hash string) (User, error) {
|
|
key := strings.ToLower(username)
|
|
if _, ok := f.users[key]; ok {
|
|
return User{}, ErrUsernameTaken
|
|
}
|
|
f.next++
|
|
u := User{ID: f.next, Username: username, CreatedAt: time.Now()}
|
|
f.users[key] = fakeUser{u: u, hash: hash}
|
|
return u, nil
|
|
}
|
|
|
|
func (f *fakeStore) UserByUsername(_ context.Context, username string) (User, string, error) {
|
|
fu, ok := f.users[strings.ToLower(username)]
|
|
if !ok {
|
|
return User{}, "", ErrUserNotFound
|
|
}
|
|
return fu.u, fu.hash, nil
|
|
}
|
|
|
|
func newTestService() *Service {
|
|
return NewService(newFakeStore(), NewTokenIssuer(testSecret, time.Hour))
|
|
}
|
|
|
|
func TestRegisterFirstUserThenClosed(t *testing.T) {
|
|
s := newTestService()
|
|
ctx := context.Background()
|
|
if _, err := s.Register(ctx, "alice", "longenough"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := s.Register(ctx, "bob", "longenough"); !errors.Is(err, ErrRegistrationClosed) {
|
|
t.Fatalf("err = %v, want ErrRegistrationClosed", err)
|
|
}
|
|
}
|
|
|
|
func TestRegisterValidation(t *testing.T) {
|
|
tests := []struct {
|
|
name, user, pass string
|
|
}{
|
|
{"short username", "ab", "longenough"},
|
|
{"long username", strings.Repeat("a", 65), "longenough"},
|
|
{"bad chars", "bad name!", "longenough"},
|
|
{"short password", "alice", "short"},
|
|
{"huge password", "alice", strings.Repeat("x", 300)},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
_, err := newTestService().Register(context.Background(), tt.user, tt.pass)
|
|
if !errors.Is(err, ErrInvalidInput) {
|
|
t.Fatalf("err = %v, want ErrInvalidInput", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestLogin(t *testing.T) {
|
|
s := newTestService()
|
|
ctx := context.Background()
|
|
if _, err := s.Register(ctx, "alice", "longenough"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
res, err := s.Login(ctx, "ALICE", "longenough") // usernames are case-insensitive
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Token == "" || res.User.Username != "alice" {
|
|
t.Errorf("result = %+v", res)
|
|
}
|
|
|
|
if _, err := s.Login(ctx, "alice", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) {
|
|
t.Errorf("wrong password: err = %v", err)
|
|
}
|
|
if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
|
|
t.Errorf("unknown user: err = %v", err)
|
|
}
|
|
}
|