sonda/internal/api/http/middleware_test.go
tgiachi 52d1828b46 fix(auth): a token stops working when its account is deleted
SQLite gives the highest user id again after that user is deleted, and an access
token lives for minutes, so the token of a deleted user worked as whoever got the
id next (settings, taste, listens, account).

requireAuth now looks the account up after checking the token and refuses it when
the account is gone, has another name, or was created after the token was signed.
The token carries its issue time for this.

Tests: a unit test of every case, and the real scenario on SQLite (delete the
highest id, create another user, the old token gets 401, the new one works).

Closes #30
2026-11-11 19:25:09 +01:00

108 lines
3.9 KiB
Go

package httpapi
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/auth"
)
type fakeParser struct {
claims auth.Claims
err error
}
func (f fakeParser) Parse(string) (auth.Claims, error) { return f.claims, f.err }
type fakeUsers struct {
user auth.User
err error
}
func (f fakeUsers) User(context.Context, int64) (auth.User, error) { return f.user, f.err }
func TestRequireAuthChecksWhoTheTokenWasIssuedFor(t *testing.T) {
issued := time.Unix(1_700_000_000, 0)
token := auth.Claims{UserID: 5, Username: "bob", IssuedAt: issued}
for _, tt := range []struct {
name string
users fakeUsers
want int
}{
{"the same account", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(-time.Hour)}}, http.StatusOK},
{"created in the same second as the token", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued}}, http.StatusOK},
{"the account is gone", fakeUsers{err: auth.ErrUserNotFound}, http.StatusUnauthorized},
{"the id now belongs to somebody else", fakeUsers{user: auth.User{ID: 5, Username: "carol", CreatedAt: issued.Add(-time.Hour)}}, http.StatusUnauthorized},
{"the id was reused for the same name, later", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(time.Minute)}}, http.StatusUnauthorized},
{"the database fails", fakeUsers{err: errors.New("boom")}, http.StatusInternalServerError},
} {
r := gin.New()
r.GET("/x", requireAuth(fakeParser{claims: token}, tt.users, false), func(c *gin.Context) {
if currentUserID(c) != 5 {
t.Errorf("%s: user id = %d", tt.name, currentUserID(c))
}
c.Status(http.StatusOK)
})
req := httptest.NewRequest("GET", "/x", nil)
req.Header.Set("Authorization", "Bearer anything")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Errorf("%s: status %d, want %d", tt.name, rec.Code, tt.want)
}
}
}
func TestRequireAuthDoesNotLookUpWhenTheTokenIsBad(t *testing.T) {
r := gin.New()
r.GET("/x", requireAuth(fakeParser{err: errors.New("bad")}, fakeUsers{err: errors.New("must not be called")}, false), func(c *gin.Context) {
c.Status(http.StatusOK)
})
req := httptest.NewRequest("GET", "/x", nil)
req.Header.Set("Authorization", "Bearer anything")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status %d, want 401", rec.Code)
}
}
// On SQLite the highest id is given again once its user is deleted. A token of the
// deleted user must not work as the new one.
func TestATokenOfADeletedUserDoesNotWorkAsWhoeverGetsTheSameId(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
create := func(name string) (id int64, token string) {
cred := map[string]any{"username": name, "password": "longenough"}
r := do(t, h, "POST", "/api/v1/users", admin, cred)
if r.Code != http.StatusCreated {
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
}
token, _ = do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string)
return int64(r.Body["id"].(float64)), token
}
bobID, bob := create("bob")
if r := do(t, h, "DELETE", "/api/v1/users/"+strconv.FormatInt(bobID, 10), admin, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete bob: %d %v", r.Code, r.Body)
}
carolID, carol := create("carol")
if carolID != bobID {
t.Skipf("the id was not reused (%d then %d): nothing to prove here", bobID, carolID)
}
for _, path := range []string{"/api/v1/me/settings", "/api/v1/me/taste", "/api/v1/listens", "/api/v1/auth/me"} {
if r := do(t, h, "GET", path, bob, nil); r.Code != http.StatusUnauthorized {
t.Errorf("GET %s with bob's token: %d %v, want 401", path, r.Code, r.Body)
}
if r := do(t, h, "GET", path, carol, nil); r.Code != http.StatusOK {
t.Errorf("GET %s with carol's own token: %d %v, want 200", path, r.Code, r.Body)
}
}
}