diff --git a/internal/api/http/middleware.go b/internal/api/http/middleware.go index 0f27cc5..0e41a92 100644 --- a/internal/api/http/middleware.go +++ b/internal/api/http/middleware.go @@ -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,11 +85,20 @@ func requireAdmin(users userLookup) gin.HandlerFunc { } } +// 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. +// 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 "; // when allowQuery is true and the header is absent it also accepts the @@ -118,6 +134,11 @@ func requireAuth(tokens tokenParser, users userLookup, allowQuery bool) gin.Hand 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") @@ -127,6 +148,7 @@ func requireAuth(tokens tokenParser, users userLookup, allowQuery bool) gin.Hand return } c.Set(ctxUserID, claims.UserID) + c.Set(ctxAccount, user) c.Set(ctxUsername, claims.Username) c.Next() } diff --git a/internal/api/http/middleware_test.go b/internal/api/http/middleware_test.go index 16ff7c4..f98a1eb 100644 --- a/internal/api/http/middleware_test.go +++ b/internal/api/http/middleware_test.go @@ -60,6 +60,49 @@ func TestRequireAuthChecksWhoTheTokenWasIssuedFor(t *testing.T) { } } +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) { @@ -97,6 +140,14 @@ func TestATokenOfADeletedUserDoesNotWorkAsWhoeverGetsTheSameId(t *testing.T) { 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) diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index f3d6011..15d8bee 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -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) }