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
This commit is contained in:
parent
423df2488a
commit
52d1828b46
5 changed files with 140 additions and 6 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -78,12 +78,18 @@ func requireAdmin(users userLookup) gin.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
// requireAuth checks the access token. It reads "Authorization: Bearer <jwt>";
|
||||
// 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.
|
||||
//
|
||||
// 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,6 +113,19 @@ 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.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(ctxUsername, claims.Username)
|
||||
c.Next()
|
||||
|
|
|
|||
108
internal/api/http/middleware_test.go
Normal file
108
internal/api/http/middleware_test.go
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue