fix(auth): a password reset signs out Subsonic apps too, and a change can (#8107)

A reset ended every session but left the API key and Subsonic password
working, and anyone signed in to the account can make either. So whoever had
the account kept it through a Subsonic app after the owner reset the
password. The forgotten-password reset and an admin's reset now replace the
API key with one nobody holds and clear the Subsonic password.

A self-service change keeps Subsonic apps signed in by default, since it
would sign out the owner's own apps too. The web and Android password forms
gain "Sign out Subsonic apps too", sent as sign_out_subsonic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 23:48:21 -05:00
co-authored by Claude Opus 5.5
parent 1c28e17dfc
commit c6a9535cf7
16 changed files with 246 additions and 18 deletions
+7 -3
View File
@@ -276,9 +276,10 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
return
}
// The target's existing sessions end with the old password. An admin
// resetting their own password keeps the session they're using, the
// same as a self-service change.
// The target's existing sessions end with the old password, and so does
// their Subsonic apps' access (signOutSubsonicApps). An admin resetting
// their own password keeps the session they're using, the same as a
// self-service change.
sessID, ownSession := auth.SessionIDFromContext(r.Context())
if targetID == caller.ID && ownSession {
_, err = q.DeleteOtherSessionsForUser(r.Context(), dbq.DeleteOtherSessionsForUserParams{UserID: targetID, ID: sessID})
@@ -288,6 +289,9 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
if err != nil {
h.logger.Error("admin reset password: revoke sessions failed", "err", err)
}
if err := h.signOutSubsonicApps(r.Context(), targetID); err != nil {
h.logger.Error("admin reset password: sign out subsonic apps failed", "err", err)
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, caller.ID, targetID, audit.ActionPasswordResetAdmin, nil)
+20
View File
@@ -270,3 +270,23 @@ func TestAdminResetPassword_TooShort_400(t *testing.T) {
t.Errorf("status = %d, want 400", rec.Code)
}
}
func TestAdminResetPassword_SignsOutSubsonicApps(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
admin := seedUser(t, pool, "rsubadm", "pw", true)
target := seedUser(t, pool, "rsubtgt", "oldpw1234", false)
giveSubsonicPassword(t, h, target)
before, _ := subsonicCredentials(t, h, target)
req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
bytes.NewReader([]byte(`{"password":"newpassword1"}`)))
rec := httptest.NewRecorder()
newAdminUsersRouter(h).ServeHTTP(rec, withUser(req, admin))
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
assertSubsonicSignedOut(t, h, target, before)
}
+6 -3
View File
@@ -102,12 +102,15 @@ func (h *handlers) handleResetPassword(w http.ResponseWriter, r *http.Request) {
return
}
// End every session the account has. Whoever needed a reset isn't signed
// in anywhere they rely on, and whoever may have learned the old password
// must not stay signed in on it.
// End every session the account has, and its Subsonic apps' access.
// Whoever needed a reset isn't signed in anywhere they rely on, and
// whoever may have learned the old password must not stay signed in on it.
if _, err := q.DeleteSessionsForUser(r.Context(), reset.UserID); err != nil {
h.logger.Error("reset password: revoke sessions failed", "err", err)
}
if err := h.signOutSubsonicApps(r.Context(), reset.UserID); err != nil {
h.logger.Error("reset password: sign out subsonic apps failed", "err", err)
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, reset.UserID, reset.UserID, audit.ActionPasswordResetByEmail, nil)
+27
View File
@@ -143,3 +143,30 @@ func TestResetPassword_BogusToken_400(t *testing.T) {
t.Errorf("status = %d, want 400 (invalid_token for bogus)", rec.Code)
}
}
// A reset ends Subsonic apps' access too: they sign in with the API key or
// the Subsonic password, which whoever had the account could have made.
func TestResetPassword_SignsOutSubsonicApps(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "resetsubsonic", "oldpw1234", false)
giveSubsonicPassword(t, h, user)
before, _ := subsonicCredentials(t, h, user)
token := "test-reset-token-subsonic"
if _, err := pool.Exec(context.Background(),
`INSERT INTO password_resets (token, user_id, expires_at)
VALUES ($1, $2, $3)`, token, user.ID, time.Now().Add(time.Hour),
); err != nil {
t.Fatalf("seed: %v", err)
}
body := `{"token":"` + token + `","new_password":"newpassword1"}`
rec := httptest.NewRecorder()
h.handleResetPassword(rec, httptest.NewRequest(http.MethodPost, "/api/auth/reset-password", bytes.NewReader([]byte(body))))
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
assertSubsonicSignedOut(t, h, user, before)
}
+16 -1
View File
@@ -15,6 +15,11 @@ import (
type changePasswordReq struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
// SignOutSubsonic also ends the account's Subsonic apps' access, for
// someone changing a password they think another person knows. It is a
// choice here, unlike on a reset, because it signs out the owner's own
// apps too: they make a new key or Subsonic password in Settings.
SignOutSubsonic bool `json:"sign_out_subsonic"`
}
// handleChangePassword implements PUT /api/me/password. Self-service:
@@ -74,7 +79,17 @@ func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request)
}
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, nil)
var auditMeta map[string]any
if req.SignOutSubsonic {
if err := h.signOutSubsonicApps(r.Context(), user.ID); err != nil {
h.logger.Error("change password: sign out subsonic apps failed", "err", err)
writeErr(w, apierror.Internal(err))
return
}
auditMeta = map[string]any{"signed_out_subsonic": true}
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, auditMeta)
w.WriteHeader(http.StatusNoContent)
}
+30
View File
@@ -81,3 +81,33 @@ func TestChangePassword_TooShort_400(t *testing.T) {
t.Errorf("status = %d, want 400 (password_too_short)", rec.Code)
}
}
// A change keeps Subsonic apps signed in unless the person asks for them to
// be signed out as well.
func TestChangePassword_SignsOutSubsonicAppsOnlyWhenAsked(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "chpwsub", "oldpassword1", false)
giveSubsonicPassword(t, h, user)
before, _ := subsonicCredentials(t, h, user)
change := func(body string) {
t.Helper()
req := httptest.NewRequest(http.MethodPut, "/api/me/password", bytes.NewReader([]byte(body)))
rec := httptest.NewRecorder()
newMePasswordRouter(h).ServeHTTP(rec, withUser(req, user))
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
}
}
change(`{"current_password":"oldpassword1","new_password":"newpassword1"}`)
if after, hasPassword := subsonicCredentials(t, h, user); after != before || !hasPassword {
t.Fatal("a plain password change signed out Subsonic apps")
}
change(`{"current_password":"newpassword1","new_password":"newpassword2","sign_out_subsonic":true}`)
assertSubsonicSignedOut(t, h, user, before)
}
+29
View File
@@ -1,12 +1,17 @@
package api
import (
"context"
"crypto/rand"
"encoding/base64"
"net/http"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
)
@@ -88,3 +93,27 @@ func (h *handlers) handleClearMySubsonicPassword(w http.ResponseWriter, r *http.
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionSubsonicPasswordClear, nil)
w.WriteHeader(http.StatusNoContent)
}
// signOutSubsonicApps ends every Subsonic app's access to the account: the
// API key is replaced with one nobody holds and the Subsonic password is
// cleared. The owner makes new ones in Settings to sign their apps back in.
//
// A Subsonic app signs in with one of these, never with the login password,
// and anyone signed in to the account can make either. So ending sessions
// on a password reset doesn't shut out whoever had the account; this does.
func (h *handlers) signOutSubsonicApps(ctx context.Context, userID pgtype.UUID) error {
unheld, err := auth.MintSessionToken()
if err != nil {
return err
}
return pgx.BeginFunc(ctx, h.pool, func(tx pgx.Tx) error {
q := dbq.New(tx)
if err := q.RegenerateApiToken(ctx, dbq.RegenerateApiTokenParams{
ID: userID,
ApiTokenHash: auth.HashAPIToken(unheld),
}); err != nil {
return err
}
return q.SetSubsonicPassword(ctx, dbq.SetSubsonicPasswordParams{ID: userID, SubsonicPassword: nil})
})
}
+36
View File
@@ -143,3 +143,39 @@ func TestSubsonicPassword_StatusAndClear(t *testing.T) {
t.Errorf("stored after clear = %q, want NULL", *got)
}
}
// subsonicCredentials reads what a Subsonic app signs in with: the API key's
// hash and whether a Subsonic password is set.
func subsonicCredentials(t *testing.T, h *handlers, user dbq.User) (apiKeyHash string, hasPassword bool) {
t.Helper()
var pw *string
if err := h.pool.QueryRow(context.Background(),
"SELECT api_token_hash, subsonic_password FROM users WHERE id = $1", user.ID).Scan(&apiKeyHash, &pw); err != nil {
t.Fatalf("read subsonic credentials: %v", err)
}
return apiKeyHash, pw != nil
}
// giveSubsonicPassword stores a Subsonic password for user, as Settings does.
func giveSubsonicPassword(t *testing.T, h *handlers, user dbq.User) {
t.Helper()
req := withUser(httptest.NewRequest(http.MethodPost, "/api/me/subsonic-password", nil), user)
rec := httptest.NewRecorder()
newMeSubsonicPasswordRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("generate subsonic password: %d %s", rec.Code, rec.Body.String())
}
}
// assertSubsonicSignedOut fails unless the API key has changed from before and
// no Subsonic password is left.
func assertSubsonicSignedOut(t *testing.T, h *handlers, user dbq.User, before string) {
t.Helper()
after, hasPassword := subsonicCredentials(t, h, user)
if after == before {
t.Error("the API key still works after the reset")
}
if hasPassword {
t.Error("the Subsonic password still works after the reset")
}
}