sonda/internal/api/http/auth_test.go
tgiachi 32068f7cf6 fix(listening): report a deleted account first and document one event per play
- fix: a listen from a deleted account is answered 401 before the track or the
  duration is looked at, so a client that signs out on 401 does it whatever
  else is wrong with the request (UserExists on the store)
- docs: one event per play, sent when the play ends or is abandoned, with one
  idempotency key per play. An event cannot be upgraded afterwards: a key that
  was already used is ignored even if the type or duration differ, and a new
  key would count the same play twice. The README no longer says to report at
  20 seconds, which led straight into that trap, and no longer hard-codes the
  minimum
- test: the SQL filter at exactly the threshold and just under it, the order of
  events within the same second, the order of checks for a deleted account
2026-11-11 15:02:28 +01:00

391 lines
14 KiB
Go

package httpapi
import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
)
func str(m map[string]any, key string) string {
v, _ := m[key].(string)
return v
}
func sub(m map[string]any, key string) map[string]any {
v, _ := m[key].(map[string]any)
return v
}
// loginSession logs in and returns the whole session body.
func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]any {
t.Helper()
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": user, "password": pass})
if r.Code != http.StatusOK {
t.Fatalf("login %s: %d %v", user, r.Code, r.Body)
}
return r.Body
}
// addUser has the admin create an account and returns that account's access token.
func addUser(t *testing.T, h http.Handler, adminTok, name string, admin bool) (id float64, token string) {
t.Helper()
r := do(t, h, "POST", "/api/v1/users", adminTok,
map[string]any{"username": name, "password": "longenough", "is_admin": admin})
if r.Code != http.StatusCreated {
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
}
id, _ = r.Body["id"].(float64)
return id, str(loginSession(t, h, name, "longenough"), "access_token")
}
func userPath(id float64) string {
return "/api/v1/users/" + strconv.FormatInt(int64(id), 10)
}
// ---- login, me ----
func TestLoginReturnsSessionWithRoles(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
for _, k := range []string{"access_token", "refresh_token", "access_expires_at", "refresh_expires_at"} {
if str(s, k) == "" {
t.Errorf("%s missing from %v", k, s)
}
}
u := sub(s, "user")
if u["username"] != "alice" || u["is_admin"] != true {
t.Errorf("user = %v, want alice as admin", u)
}
}
func TestMe(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
if r := do(t, h, "GET", "/api/v1/auth/me", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", r.Code)
}
r := do(t, h, "GET", "/api/v1/auth/me", tok, nil)
if r.Code != http.StatusOK || r.Body["username"] != "alice" || r.Body["is_admin"] != true {
t.Fatalf("me: %d %v", r.Code, r.Body)
}
if _, leaked := r.Body["password_hash"]; leaked {
t.Error("password hash leaked")
}
}
// ---- refresh, logout ----
func TestRefreshRotatesAndOldTokenCannotBeReplayed(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
first := loginSession(t, h, "alice", "longenough")
r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(first, "refresh_token")})
if r.Code != http.StatusOK || str(r.Body, "access_token") == "" {
t.Fatalf("refresh: %d %v", r.Code, r.Body)
}
second := str(r.Body, "refresh_token")
if second == "" || second == str(first, "refresh_token") {
t.Fatal("refresh token was not rotated")
}
// The new access token works.
if r := do(t, h, "GET", "/api/v1/auth/me", str(r.Body, "access_token"), nil); r.Code != http.StatusOK {
t.Errorf("new access token: %d", r.Code)
}
// Replaying the spent token fails. Right after a rotation that is treated as
// a race (two tabs), so the newer token keeps working; reuse long after the
// rotation revoking every session is covered in the auth and storage tests.
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(first, "refresh_token")})
if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_refresh_token" {
t.Fatalf("replay: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": second})
if r.Code != http.StatusOK {
t.Fatalf("the newer token must survive a replay inside the grace window: %d", r.Code)
}
}
func TestRefreshRejectsBadRequests(t *testing.T) {
h := newTestAPI(t)
for name, body := range map[string]any{
"empty": map[string]string{},
"unknown": map[string]string{"refresh_token": "nope"},
"malformed": "{oops",
} {
r := do(t, h, "POST", "/api/v1/auth/refresh", "", body)
want := http.StatusUnauthorized
if name == "malformed" {
want = http.StatusBadRequest
}
if r.Code != want {
t.Errorf("%s: %d %v, want %d", name, r.Code, r.Body, want)
}
}
}
func TestAccessTokenCannotBeUsedAsRefreshToken(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(s, "access_token")})
if r.Code != http.StatusUnauthorized {
t.Fatalf("access token accepted as refresh token: %d", r.Code)
}
}
func TestLogout(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
body := map[string]string{"refresh_token": str(s, "refresh_token")}
if r := do(t, h, "POST", "/api/v1/auth/logout", "", body); r.Code != http.StatusNoContent {
t.Fatalf("logout: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", body); r.Code != http.StatusUnauthorized {
t.Errorf("refresh after logout: %d", r.Code)
}
// Idempotent, and it never reveals whether the token existed.
if r := do(t, h, "POST", "/api/v1/auth/logout", "", body); r.Code != http.StatusNoContent {
t.Errorf("second logout: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/auth/logout", "", map[string]string{"refresh_token": "junk"}); r.Code != http.StatusNoContent {
t.Errorf("junk logout: %d", r.Code)
}
}
// ---- password ----
func TestChangePassword(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
if r := do(t, h, "POST", "/api/v1/auth/password", "", map[string]string{"current_password": "x", "new_password": "y"}); r.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", r.Code)
}
r := do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "wrongwrong", "new_password": "brandnewpass"})
if r.Code != http.StatusForbidden || errCode(r) != "invalid_credentials" {
t.Fatalf("wrong current: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "longenough", "new_password": "short"})
if r.Code != http.StatusBadRequest {
t.Fatalf("weak new password: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "longenough", "new_password": "brandnewpass"})
if r.Code != http.StatusNoContent {
t.Fatalf("change: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": "alice", "password": "longenough"}); r.Code != http.StatusUnauthorized {
t.Errorf("old password still works: %d", r.Code)
}
loginSession(t, h, "alice", "brandnewpass")
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(s, "refresh_token")}); r.Code != http.StatusUnauthorized {
t.Errorf("old session survived a password change: %d", r.Code)
}
}
// ---- admin ----
func TestAdminEndpointsRejectNonAdmins(t *testing.T) {
h := newTestAPIWithScan(t, &fakeScan{})
admin := registerAndLogin(t, h)
bobID, bob := addUser(t, h, admin, "bob", false)
calls := []struct{ method, path string }{
{"GET", "/api/v1/users"},
{"POST", "/api/v1/users"},
{"PATCH", userPath(bobID)},
{"PUT", userPath(bobID) + "/password"},
{"DELETE", userPath(bobID)},
{"POST", "/api/v1/library/scan"},
}
for _, c := range calls {
if r := do(t, h, c.method, c.path, "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("%s %s without token: %d", c.method, c.path, r.Code)
}
r := do(t, h, c.method, c.path, bob, map[string]any{"username": "x", "password": "longenough", "is_admin": true})
if r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("%s %s as non-admin: %d %v", c.method, c.path, r.Code, r.Body)
}
}
// Reading the scan status stays open to every signed-in user.
if r := do(t, h, "GET", "/api/v1/library/scan", bob, nil); r.Code != http.StatusOK {
t.Errorf("scan status as user: %d", r.Code)
}
}
func TestAdminUserLifecycle(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
bobID, bob := addUser(t, h, admin, "bob", false)
r := do(t, h, "GET", "/api/v1/users", admin, nil)
users, _ := r.Body["users"].([]any)
if r.Code != http.StatusOK || len(users) != 2 {
t.Fatalf("list: %d %v", r.Code, r.Body)
}
for _, u := range users {
if _, leaked := u.(map[string]any)["password_hash"]; leaked {
t.Error("password hash leaked in the user list")
}
}
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "BOB", "password": "longenough"}); r.Code != http.StatusConflict || errCode(r) != "username_taken" {
t.Errorf("duplicate: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "x", "password": "longenough"}); r.Code != http.StatusBadRequest {
t.Errorf("invalid: %d", r.Code)
}
// Promote bob: his existing token now passes the admin check.
r = do(t, h, "PATCH", userPath(bobID), admin, map[string]any{"is_admin": true})
if r.Code != http.StatusOK || r.Body["is_admin"] != true {
t.Fatalf("promote: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/users", bob, nil); r.Code != http.StatusOK {
t.Errorf("promoted user cannot list users: %d", r.Code)
}
// Reset bob's password: the new one works, his sessions are gone.
bobSession := loginSession(t, h, "bob", "longenough")
if r := do(t, h, "PUT", userPath(bobID)+"/password", admin, map[string]string{"password": "resetpassword"}); r.Code != http.StatusNoContent {
t.Fatalf("reset: %d %v", r.Code, r.Body)
}
loginSession(t, h, "bob", "resetpassword")
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(bobSession, "refresh_token")}); r.Code != http.StatusUnauthorized {
t.Errorf("session survived a password reset: %d", r.Code)
}
// Delete bob: his still-valid access token stops working on admin routes.
if r := do(t, h, "DELETE", userPath(bobID), admin, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/users", bob, nil); r.Code != http.StatusUnauthorized {
t.Errorf("deleted admin's token: %d, want 401", r.Code)
}
if r := do(t, h, "DELETE", userPath(bobID), admin, nil); r.Code != http.StatusNotFound || errCode(r) != "user_not_found" {
t.Errorf("delete twice: %d %v", r.Code, r.Body)
}
}
func TestLastAdminCannotBeRemoved(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
me := do(t, h, "GET", "/api/v1/auth/me", admin, nil)
id, _ := me.Body["id"].(float64)
r := do(t, h, "PATCH", userPath(id), admin, map[string]any{"is_admin": false})
if r.Code != http.StatusConflict || errCode(r) != "last_admin" {
t.Errorf("demote last admin: %d %v", r.Code, r.Body)
}
r = do(t, h, "DELETE", userPath(id), admin, nil)
if r.Code != http.StatusConflict || errCode(r) != "last_admin" {
t.Errorf("delete last admin: %d %v", r.Code, r.Body)
}
}
func TestAdminRoutesValidateInput(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
if r := do(t, h, "PATCH", "/api/v1/users/abc", admin, map[string]any{"is_admin": true}); r.Code != http.StatusBadRequest {
t.Errorf("non-numeric id: %d", r.Code)
}
if r := do(t, h, "PATCH", "/api/v1/users/1", admin, map[string]any{}); r.Code != http.StatusBadRequest {
t.Errorf("missing is_admin: %d", r.Code)
}
if r := do(t, h, "PATCH", "/api/v1/users/999", admin, map[string]any{"is_admin": true}); r.Code != http.StatusNotFound {
t.Errorf("unknown user: %d", r.Code)
}
if r := do(t, h, "PUT", "/api/v1/users/999/password", admin, map[string]string{"password": "longenough"}); r.Code != http.StatusNotFound {
t.Errorf("reset unknown: %d", r.Code)
}
}
func TestAdminCanStartScan(t *testing.T) {
scan := &fakeScan{}
h := newTestAPIWithScan(t, scan)
admin := registerAndLogin(t, h)
if r := do(t, h, "POST", "/api/v1/library/scan", admin, nil); r.Code != http.StatusAccepted {
t.Fatalf("admin scan: %d %v", r.Code, r.Body)
}
if scan.starts != 1 {
t.Errorf("starts = %d", scan.starts)
}
}
// Only "Authorization: Bearer <token>" is accepted. A bare token must not pass.
func TestAuthorizationHeaderMustUseTheBearerScheme(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
for name, header := range map[string]string{
"bare token": tok,
"basic scheme": "Basic " + tok,
"token scheme": "Token " + tok,
"empty bearer": "Bearer ",
"bearer no gap": "Bearer" + tok,
} {
req := httptest.NewRequest("GET", "/api/v1/auth/me", nil)
req.Header.Set("Authorization", header)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s: status %d, want 401", name, rec.Code)
}
}
req := httptest.NewRequest("GET", "/api/v1/auth/me", nil)
req.Header.Set("Authorization", "Bearer "+tok)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("proper Bearer header: %d", rec.Code)
}
}
// RFC 7235: the name of the authentication scheme is case-insensitive.
func TestBearerSchemeIsCaseInsensitive(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
for _, scheme := range []string{"Bearer", "bearer", "BEARER", "bEaReR"} {
req := httptest.NewRequest("GET", "/api/v1/auth/me", nil)
req.Header.Set("Authorization", scheme+" "+tok)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("scheme %q: status %d, want 200", scheme, rec.Code)
}
}
}
// An access token outlives a deleted account for a few minutes. Reporting a
// listen with it must be a 401, not a database error.
func TestListenWithADeletedAccountsTokenIsUnauthorized(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
bobID, bob := addUser(t, h, admin, "bob", false)
if r := do(t, h, "DELETE", userPath(bobID), admin, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete: %d", r.Code)
}
// Whatever else is wrong with the request, the deleted account is told
// "unauthorized" first.
for name, body := range map[string]map[string]any{
"a valid event": {"track_id": 1, "event_type": "play", "idempotency_key": "k"},
"an unknown track": {"track_id": 999, "event_type": "play", "idempotency_key": "k"},
"an absurd length": {"track_id": 1, "event_type": "play", "duration_played_ms": 1, "idempotency_key": "k2"},
} {
r := do(t, h, "POST", "/api/v1/listens", bob, body)
if r.Code != http.StatusUnauthorized || errCode(r) != "unauthorized" {
t.Errorf("%s after the account was deleted: %d %v", name, r.Code, r.Body)
}
}
}