Merge pull request 'fix(auth): a token stops working when its account is deleted' (#32) from fix/token-user-identity into main

This commit is contained in:
squidd 2026-11-11 19:30:18 +01:00
commit c7a2813b5d
6 changed files with 232 additions and 8 deletions

View file

@ -242,7 +242,7 @@ A library path must be an absolute, existing folder, never the filesystem root,
## Security notes
- Sonda listens on localhost only, unless you change `server.listen`. To use it from other machines, put it behind a reverse proxy that terminates HTTPS.
- Passwords are hashed with Argon2id. Refresh tokens are stored only as hashes.
- Passwords are hashed with Argon2id. Refresh tokens are stored only as hashes. An access token is checked against the database on every request, so it stops working as soon as its account is deleted, even if the same user id is given to a new account.
- Music folders are read-only to Sonda. Streaming opens files through `os.Root`, so a path can never leave its library, even if a symlink is swapped in later.
- File paths are never returned by the catalog, and audio file paths are not logged.
- Provider API keys are write-only through the API and never logged. They sit in the database, so protect your backups.

View file

@ -16,6 +16,7 @@ import (
const (
ctxUserID = "user_id"
ctxUsername = "username"
ctxAccount = "account" // the auth.User that requireAuth already looked up
)
// limitBody caps the request body size.
@ -63,14 +64,20 @@ type userLookup interface {
// of when the access token expires.
func requireAdmin(users userLookup) gin.HandlerFunc {
return func(c *gin.Context) {
user, err := users.User(c.Request.Context(), currentUserID(c))
// requireAuth just read the account in this same request: use it, do not
// read it twice.
account, known := accountOf(c)
var err error
if !known {
account, err = users.User(c.Request.Context(), currentUserID(c))
}
switch {
case errors.Is(err, auth.ErrUserNotFound):
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
case !user.IsAdmin:
case !account.IsAdmin:
writeError(c, http.StatusForbidden, "admin_required", "this action needs an admin account")
default:
c.Next()
@ -78,12 +85,27 @@ func requireAdmin(users userLookup) gin.HandlerFunc {
}
}
// requireAuth checks the access token. It reads "Authorization: Bearer <jwt>";
// accountOf returns the account that requireAuth looked up for this request.
func accountOf(c *gin.Context) (auth.User, bool) {
v, ok := c.Get(ctxAccount)
u, isUser := v.(auth.User)
return u, ok && isUser
}
// requireAuth checks the access token, then that it was issued for the account
// that has this id now. User ids can be given again after an account is deleted
// (SQLite reuses the highest one), and a token lives for minutes: without this check
// the token of a deleted user would work as whoever gets the id next. The account
// must exist, have the same name, and not have been created after the token was signed
// (both times are whole seconds from the server's clock; a clock stepped back can make
// a new account look newer than its token for the length of the step).
//
// It reads "Authorization: Bearer <jwt>";
// when allowQuery is true and the header is absent it also accepts the
// access_token query parameter. That is for routes loaded by an <audio> element,
// which cannot send headers. A header that is present always wins, so a bad
// header is never rescued by a query token.
func requireAuth(tokens tokenParser, allowQuery bool) gin.HandlerFunc {
func requireAuth(tokens tokenParser, users userLookup, allowQuery bool) gin.HandlerFunc {
return func(c *gin.Context) {
token := ""
if header := c.GetHeader("Authorization"); header != "" {
@ -107,7 +129,26 @@ func requireAuth(tokens tokenParser, allowQuery bool) gin.HandlerFunc {
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
return
}
user, err := users.User(c.Request.Context(), claims.UserID)
switch {
case errors.Is(err, auth.ErrUserNotFound):
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
return
case err != nil && c.Request.Context().Err() != nil:
// The client left (a player seeking aborts its Range request): nobody
// is waiting and nothing went wrong here.
c.AbortWithStatus(statusClientClosed)
return
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
case user.Username != claims.Username || user.CreatedAt.Unix() > claims.IssuedAt.Unix():
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
return
}
c.Set(ctxUserID, claims.UserID)
c.Set(ctxAccount, user)
c.Set(ctxUsername, claims.Username)
c.Next()
}

View file

@ -0,0 +1,159 @@
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)
}
}
}

View file

@ -132,7 +132,7 @@ func NewRouter(d Deps) *gin.Engine {
v1.POST("/auth/logout", a.logout)
// Any signed-in user.
protected := v1.Group("", requireAuth(d.Tokens, false))
protected := v1.Group("", requireAuth(d.Tokens, d.Auth, false))
protected.GET("/auth/me", a.me)
protected.POST("/auth/password", a.changePassword)
l := &listenHandlers{svc: d.Listening}
@ -163,7 +163,7 @@ func NewRouter(d Deps) *gin.Engine {
// Audio loaded by an <audio> element cannot send headers, so this route also
// takes the access token as a query parameter. It never records a listen.
st := &streamHandlers{svc: d.Streams}
audio := v1.Group("", requireAuth(d.Tokens, true))
audio := v1.Group("", requireAuth(d.Tokens, d.Auth, true))
audio.GET("/tracks/:id/stream", st.stream)
audio.HEAD("/tracks/:id/stream", st.stream)

View file

@ -64,6 +64,23 @@ func TestTokenRoundTrip(t *testing.T) {
}
}
func TestTokenCarriesTheMomentItWasIssued(t *testing.T) {
iss := NewTokenIssuer(testSecret, time.Hour)
at := time.Date(2026, 5, 6, 7, 8, 9, 500_000_000, time.UTC)
iss.now = func() time.Time { return at }
tok, _, err := iss.Issue(User{ID: 7, Username: "bob"})
if err != nil {
t.Fatal(err)
}
claims, err := iss.Parse(tok)
if err != nil {
t.Fatal(err)
}
if want := at.Truncate(time.Second); !claims.IssuedAt.Equal(want) {
t.Errorf("issued at = %v, want %v (whole seconds)", claims.IssuedAt, want)
}
}
func TestTokenExpired(t *testing.T) {
iss := NewTokenIssuer(testSecret, time.Hour)
iss.now = func() time.Time { return time.Now().Add(-2 * time.Hour) }

View file

@ -14,6 +14,9 @@ const tokenIssuerName = "sonda"
type Claims struct {
UserID int64
Username string
// IssuedAt is when the token was signed. An account created after that moment
// cannot be the one the token was issued for.
IssuedAt time.Time
}
type tokenClaims struct {
@ -67,5 +70,9 @@ func (i *TokenIssuer) Parse(token string) (Claims, error) {
if err != nil || id <= 0 {
return Claims{}, fmt.Errorf("invalid token: bad subject")
}
return Claims{UserID: id, Username: tc.Username}, nil
var issued time.Time
if tc.IssuedAt != nil {
issued = tc.IssuedAt.Time
}
return Claims{UserID: id, Username: tc.Username, IssuedAt: issued}, nil
}