sonda/internal/api/http/middleware_test.go
tgiachi cce689b77d fix(auth): reuse the account, quiet aborted requests, more tests
- requireAdmin reuses the account requireAuth already read in the same request
  instead of reading it again.
- A request the client aborted while the account was being read (a player
  seeking) ends with 499 and no error in the log instead of a 500.
- A comment on what a clock stepped back does to the created-after check.
- Tests: the streaming route with the token of a deleted user, the token's
  issue time round trip, the aborted request, the single lookup for admins.
2026-11-11 19:29:39 +01:00

159 lines
6 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 TestRequireAuthDoesNotCallAClientThatLeftAnInternalError(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := gin.New()
var logged int
r.Use(func(c *gin.Context) { c.Next(); logged = len(c.Errors) })
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "bob"}}, fakeUsers{err: context.Canceled}, false), func(c *gin.Context) {
t.Error("the handler ran for a client that left")
})
req := httptest.NewRequest("GET", "/x", nil).WithContext(ctx)
req.Header.Set("Authorization", "Bearer anything")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code == http.StatusInternalServerError || logged != 0 {
t.Errorf("status %d and %d logged errors: a client leaving is not an internal error", rec.Code, logged)
}
}
func TestAdminCheckReusesTheAccountAlreadyLookedUp(t *testing.T) {
calls := 0
users := countingUsers{user: auth.User{ID: 5, Username: "root", IsAdmin: true}, calls: &calls}
r := gin.New()
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "root", IssuedAt: time.Now()}}, users, false),
requireAdmin(users), 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.StatusOK || calls != 1 {
t.Errorf("status %d after %d lookups, want 200 after 1", rec.Code, calls)
}
}
type countingUsers struct {
user auth.User
calls *int
}
func (f countingUsers) User(context.Context, int64) (auth.User, error) {
*f.calls++
return f.user, nil
}
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)
}
// The streaming route also takes the token in the query. Track 999 does not
// exist: the right token gets "not found", the wrong one must not get that far.
if r := do(t, h, "GET", "/api/v1/tracks/999/stream?access_token="+bob, "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("stream with bob's token: %d, want 401", r.Code)
}
if r := do(t, h, "GET", "/api/v1/tracks/999/stream?access_token="+carol, "", nil); r.Code != http.StatusNotFound {
t.Errorf("stream with carol's token: %d, want 404", r.Code)
}
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)
}
}
}