package http import ( "context" "encoding/base64" "io" "net/http" "strings" "testing" "time" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" ) const ( basicChallenge = `Basic realm="messenger", charset="UTF-8"` bearerChallenge = `Bearer realm="messenger"` ) func expectUnauthorized(t *testing.T, resp *http.Response, challenge string) { t.Helper() defer resp.Body.Close() if resp.StatusCode != http.StatusUnauthorized { data, _ := io.ReadAll(resp.Body) t.Fatalf("expected 401, got %d; body=%s", resp.StatusCode, string(data)) } if got := resp.Header.Get("WWW-Authenticate"); got != challenge { t.Fatalf("WWW-Authenticate = %q, want %q", got, challenge) } e := readError(t, resp) if e.Error.Code != CodeUnauthorized || e.Error.RequestID == "" { t.Fatalf("unexpected error body: %+v", e) } } func (r *testRig) withHeaders(method, path string, headers map[string]string) *http.Response { r.t.Helper() return r.do(method, path, "", headers, nil) } func TestAuth_LoginReturnsSession(t *testing.T) { r := newTestRig(t) alice := r.createUser("login_"+randomSuffix(), "Алиса") before := time.Now() s := r.login(alice.Username, testPassword) if s.TokenType != "Bearer" || len(s.Token) < 32 { t.Fatalf("bad session: type=%q len(token)=%d", s.TokenType, len(s.Token)) } if s.User.ID != alice.ID || s.User.Username != alice.Username { t.Fatalf("session user = %+v, want %s", s.User, alice.ID) } if strings.Contains(s.Token, alice.ID) || strings.Contains(s.Token, alice.Username) { t.Fatal("token is derived from user identity") } if !s.ExpiresAt.After(before.Add(59*time.Minute)) || s.ExpiresAt.After(before.Add(61*time.Minute)) { t.Fatalf("expires_at = %s, want ~now+1h", s.ExpiresAt) } if again := r.login(alice.Username, testPassword); again.Token == s.Token { t.Fatal("second login returned the same token") } } func TestAuth_LoginRejectsBadCredentialsUniformly(t *testing.T) { r := newTestRig(t) alice := r.createUser("bad_"+randomSuffix(), "Алиса") expectUnauthorized(t, r.basicLogin(alice.Username, "wrong-password-123"), basicChallenge) expectUnauthorized(t, r.basicLogin("nobody_"+randomSuffix(), testPassword), basicChallenge) b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } for _, h := range []string{ "", "Bearer " + b64(alice.Username+":"+testPassword), "Basic not-base64!!!", "Basic " + b64(alice.Username), "Basic " + b64(alice.Username+":"), "Basic " + b64(":"+testPassword), "Basic " + b64(alice.Username+":\xff\xfe"), } { headers := map[string]string{} if h != "" { headers["Authorization"] = h } expectUnauthorized(t, r.withHeaders(http.MethodPost, "/api/v1/auth/sessions", headers), basicChallenge) } } func TestAuth_PasswordWithColonAndUnicode(t *testing.T) { r := newTestRig(t) username := "colon_" + randomSuffix() pw := "пароль:с:двоеточиями🙂" resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ Username: username, DisplayName: "Двоеточие", Password: pw, }) expectStatus(t, resp, http.StatusCreated) resp.Body.Close() r.login(username, pw) expectUnauthorized(t, r.basicLogin(username, "пароль"), basicChallenge) } func TestAuth_LoginRejectsBody(t *testing.T) { r := newTestRig(t) alice := r.createUser("body_"+randomSuffix(), "Алиса") req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", strings.NewReader(`{"username":"`+alice.Username+`"}`)) req.Header.Set("Content-Type", "application/json") req.SetBasicAuth(alice.Username, testPassword) resp, err := r.client.Do(req) if err != nil { t.Fatal(err) } expectStatus(t, resp, http.StatusBadRequest) resp.Body.Close() } func TestAuth_BearerRequired(t *testing.T) { r := newTestRig(t) alice, _, eve, _ := bootstrap(r) expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", nil), bearerChallenge) expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": alice.ID}), bearerChallenge) basic := base64.StdEncoding.EncodeToString([]byte(alice.Username + ":" + testPassword)) expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Basic " + basic}), bearerChallenge) expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + strings.Repeat("A", 43)}), bearerChallenge) expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + alice.ID}), bearerChallenge) resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, map[string]string{"X-User-Id": eve.ID}, nil) expectStatus(t, resp, http.StatusOK) var me dto.UserResponse readJSON(t, resp, &me) if me.ID != alice.ID { t.Fatalf("X-User-Id overrode bearer identity: got %s", me.ID) } tok := r.tokens[alice.ID] resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "bearer " + tok}) expectStatus(t, resp, http.StatusOK) resp.Body.Close() } func TestAuth_Logout(t *testing.T) { r := newTestRig(t) alice := r.createUser("logout_"+randomSuffix(), "Алиса") other := r.login(alice.Username, testPassword) resp := r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil) expectStatus(t, resp, http.StatusNoContent) body, _ := io.ReadAll(resp.Body) resp.Body.Close() if len(body) != 0 { t.Fatalf("204 with body %q", body) } expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) expectUnauthorized(t, r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil), bearerChallenge) resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + other.Token}) expectStatus(t, resp, http.StatusOK) resp.Body.Close() } func TestAuth_SessionExpires(t *testing.T) { r := newRig(t, defaultTestLimits, session.NewMemory(), 2*time.Second) alice := r.createUser("ttl_"+randomSuffix(), "Алиса") resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) expectStatus(t, resp, http.StatusOK) resp.Body.Close() time.Sleep(2100 * time.Millisecond) expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) } type brokenSessions struct { *session.Memory down bool } func (b *brokenSessions) Get(ctx context.Context, h []byte) (session.Session, error) { if b.down { return session.Session{}, domain.ErrUnavailable } return b.Memory.Get(ctx, h) } func (b *brokenSessions) Save(ctx context.Context, h []byte, s session.Session) error { if b.down { return domain.ErrUnavailable } return b.Memory.Save(ctx, h, s) } func TestAuth_SessionStoreDownIs503NotAnonymous(t *testing.T) { store := &brokenSessions{Memory: session.NewMemory()} r := newRig(t, defaultTestLimits, store, time.Hour) alice := r.createUser("down_"+randomSuffix(), "Алиса") store.down = true resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) expectStatus(t, resp, http.StatusServiceUnavailable) if e := readError(t, resp); e.Error.Code != CodeUnavailable { t.Fatalf("code = %q, want %q", e.Error.Code, CodeUnavailable) } resp = r.basicLogin(alice.Username, testPassword) expectStatus(t, resp, http.StatusServiceUnavailable) resp.Body.Close() }