Files
mtusi2026lab5/internal/app/auth_test.go
T

177 lines
6.7 KiB
Go

package app_test
import (
"encoding/base64"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"messenger/internal/user"
)
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
func TestLoginReturnsBearerSession(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
before := time.Now()
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword))
ts.expect(res, http.StatusCreated, "")
s := decode[sessionBody](t, res)
if s.TokenType != "Bearer" || len(s.Token) != 43 || s.Token == alice.token {
t.Fatalf("session = %+v; want a fresh 43-character Bearer token", s)
}
if s.User != alice.Response {
t.Fatalf("user = %+v, want %+v", s.User, alice.Response)
}
expires, err := time.Parse(time.RFC3339, s.ExpiresAt)
if err != nil || !strings.HasSuffix(s.ExpiresAt, "Z") {
t.Fatalf("expires_at = %q: %v", s.ExpiresAt, err)
}
if ttl := expires.Sub(before); ttl < 59*time.Minute || ttl > 61*time.Minute {
t.Fatalf("expires_at is %v after login, want the 1h TTL", ttl)
}
if strings.Contains(string(res.raw), "password") || strings.Contains(string(res.raw), "argon2") {
t.Fatalf("session response leaks password data: %s", res.raw)
}
}
func TestLoginFailuresAreUniformBasicChallenges(t *testing.T) {
ts := newTester(t)
ts.user("alice", "Алиса")
encoded := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
cases := map[string]map[string]string{
"wrong password": basic("alice", testPassword+"!"),
"unknown user": basic("mallory", testPassword),
"no header": nil,
"bearer scheme": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"not base64": {"Authorization": "Basic !!!"},
"no colon": {"Authorization": "Basic " + encoded("alice")},
"nul username": basic("a\x00b", testPassword),
"non-utf-8 name": basic("\xff\xfe", testPassword),
}
messages := map[string]string{}
for name, headers := range cases {
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != basicChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, basicChallenge)
}
var eb errorBody
_ = json.Unmarshal(res.raw, &eb)
messages[name] = eb.Error.Message
}
if messages["wrong password"] != messages["unknown user"] {
t.Fatalf("wrong password and unknown user must look the same: %q vs %q", messages["wrong password"], messages["unknown user"])
}
}
// The password is UTF-8 and may contain colons; only the first colon of the
// Basic credentials separates the username (contracts/README.md).
func TestLoginAcceptsColonAndUnicodePasswords(t *testing.T) {
ts := newTester(t)
const password = "пароль:с:двоеточием 👋"
body := map[string]string{"username": "alice", "display_name": "Алиса", "password": password}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusCreated, "")
s := ts.login("alice", password)
if s.User.Username != "alice" {
t.Fatalf("logged in as %+v", s.User)
}
}
func TestProtectedRoutesAcceptOnlyBearer(t *testing.T) {
ts := newTester(t)
alice, eve := ts.user("alice", "A"), ts.user("eve", "E")
me := func(headers map[string]string) response {
return ts.do(http.MethodGet, "/api/v1/users/me", "", nil, headers)
}
rejected := map[string]map[string]string{
"no header": nil,
"basic with valid credentials": basic("alice", testPassword),
"x-user-id alone": {"X-User-Id": alice.ID},
"unknown token": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"empty token": {"Authorization": "Bearer "},
"scheme only": {"Authorization": "Bearer"},
"other scheme": {"Authorization": "Token " + alice.token},
"two tokens": {"Authorization": "Bearer " + alice.token + " " + eve.token},
}
for name, headers := range rejected {
res := me(headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != bearerChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, bearerChallenge)
}
}
accepted := map[string]map[string]string{
"lowercase scheme": {"Authorization": "bearer " + alice.token},
"several spaces": {"Authorization": "Bearer " + alice.token},
"x-user-id is ignored": {"Authorization": "Bearer " + alice.token, "X-User-Id": eve.ID},
}
for name, headers := range accepted {
res := me(headers)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got.ID != alice.ID {
t.Errorf("%s: caller = %s, want alice", name, got.ID)
}
}
}
func TestLogoutRevokesOnlyTheCurrentToken(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
other := ts.login("alice", testPassword)
res := ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil)
ts.expect(res, http.StatusNoContent, "")
if len(res.raw) != 0 {
t.Fatalf("204 must have no body, got %q", res.raw)
}
for _, again := range []response{
ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil),
ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil),
} {
ts.expect(again, http.StatusUnauthorized, "unauthorized")
if again.challenge != bearerChallenge {
t.Fatalf("revoked token: WWW-Authenticate = %q, want %q", again.challenge, bearerChallenge)
}
}
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", other.Token, nil, nil), http.StatusOK, "")
}
// Valkey enforces the expiry by the Docker VM clock, which may lag this host
// by a fraction of a second, so the 401 is awaited with a tolerance.
func TestSessionExpiresAfterTTL(t *testing.T) {
const ttl, clockTolerance = 2 * time.Second, 3 * time.Second
ts := newTesterWithTTL(t, ttl)
alice := ts.user("alice", "A")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusOK, "")
time.Sleep(ttl)
deadline := time.Now().Add(clockTolerance)
for {
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
if res.status == http.StatusUnauthorized {
ts.expect(res, http.StatusUnauthorized, "unauthorized")
return
}
if time.Now().After(deadline) {
t.Fatalf("session still valid %v after its TTL of %v", clockTolerance, ttl)
}
time.Sleep(100 * time.Millisecond)
}
}
func TestRegistrationIsPublicAndIgnoresAuthorization(t *testing.T) {
ts := newTester(t)
body := map[string]string{"username": "alice", "display_name": "A", "password": testPassword}
headers := map[string]string{"Authorization": "Bearer garbage"}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, headers), http.StatusCreated, "")
}