From c6a9535cf7adb73e7b0a6decaedead84d1840d91 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 23:48:21 -0500 Subject: [PATCH] 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 --- .../minstrel/api/endpoints/MeApi.kt | 5 ++- .../minstrel/settings/data/MeRepository.kt | 8 +++-- .../minstrel/settings/ui/PasswordCard.kt | 7 ++++ .../minstrel/settings/ui/PasswordViewModel.kt | 13 +++++-- docs/security.md | 6 ++-- internal/api/admin_users.go | 10 ++++-- internal/api/admin_users_test.go | 20 +++++++++++ internal/api/auth_reset.go | 9 +++-- internal/api/auth_reset_test.go | 27 ++++++++++++++ internal/api/me_password.go | 17 ++++++++- internal/api/me_password_test.go | 30 ++++++++++++++++ internal/api/me_subsonic_password.go | 29 +++++++++++++++ internal/api/me_subsonic_password_test.go | 36 +++++++++++++++++++ web/src/lib/api/me.ts | 9 ++++- web/src/routes/settings/account/+page.svelte | 22 ++++++++++-- .../routes/settings/account/account.test.ts | 16 ++++++++- 16 files changed, 246 insertions(+), 18 deletions(-) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt index ce6d6589..bf089a4a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt @@ -82,12 +82,15 @@ data class UpdateProfileRequest( ) /** - * Body for `PUT /api/me/password`. Both fields required. + * Body for `PUT /api/me/password`. Both passwords required. + * [signOutSubsonic] also ends every Subsonic app's access: the API token and + * Subsonic password stop working. */ @Serializable data class ChangePasswordRequest( @SerialName("current_password") val currentPassword: String, @SerialName("new_password") val newPassword: String, + @SerialName("sign_out_subsonic") val signOutSubsonic: Boolean = false, ) /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt index 634f8483..77b70534 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt @@ -30,9 +30,13 @@ class MeRepository @Inject constructor(retrofit: Retrofit) { UpdateProfileRequest(displayName = displayName, email = email), ).toDomain() - suspend fun changePassword(current: String, next: String) { + suspend fun changePassword(current: String, next: String, signOutSubsonic: Boolean = false) { api.changePassword( - ChangePasswordRequest(currentPassword = current, newPassword = next), + ChangePasswordRequest( + currentPassword = current, + newPassword = next, + signOutSubsonic = signOutSubsonic, + ), ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt index 749ebf60..7f1234a5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt @@ -21,6 +21,7 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.fabledsword.minstrel.theme.Muted import com.fabledsword.minstrel.theme.Section +import com.fabledsword.minstrel.theme.SwitchRow @Composable fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) { @@ -41,6 +42,12 @@ fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) { label = "Confirm new password", onChange = viewModel::setConfirm, ) + SwitchRow( + title = "Sign out Subsonic apps too", + summary = "Your API token and Subsonic password stop working.", + checked = state.signOutSubsonic, + onCheckedChange = viewModel::setSignOutSubsonic, + ) Spacer(Modifier.height(4.dp)) Button( onClick = viewModel::change, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt index ea50c42d..6b76a435 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt @@ -16,6 +16,7 @@ data class PasswordUiState( val current: String = "", val next: String = "", val confirm: String = "", + val signOutSubsonic: Boolean = false, val isChanging: Boolean = false, val message: String? = null, ) @@ -37,6 +38,8 @@ class PasswordViewModel @Inject constructor( fun setCurrent(value: String) = internal.update { it.copy(current = value, message = null) } fun setNext(value: String) = internal.update { it.copy(next = value, message = null) } fun setConfirm(value: String) = internal.update { it.copy(confirm = value, message = null) } + fun setSignOutSubsonic(value: Boolean) = + internal.update { it.copy(signOutSubsonic = value, message = null) } fun change() { val s = internal.value @@ -55,9 +58,15 @@ class PasswordViewModel @Inject constructor( viewModelScope.launch { internal.update { it.copy(isChanging = true, message = null) } try { - repository.changePassword(current = s.current, next = s.next) + repository.changePassword( + current = s.current, + next = s.next, + signOutSubsonic = s.signOutSubsonic, + ) + val signedOut = + if (s.signOutSubsonic) "Your other devices and Subsonic apps" else "Your other devices" internal.update { - PasswordUiState(message = "Password changed. Your other devices have been signed out.") + PasswordUiState(message = "Password changed. $signedOut have been signed out.") } } catch ( @Suppress("TooGenericExceptionCaught") e: Throwable, diff --git a/docs/security.md b/docs/security.md index b7fe2b66..91e844fb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -14,8 +14,10 @@ decisions that look odd at first. For deployment steps, see password, so timing doesn't reveal which accounts exist. - **Sessions** are random 256-bit tokens; the server stores only their SHA-256. A session ends after 30 days unused or 365 days in total. Changing - your password signs out your other devices; a password reset, or an admin - resetting it, signs out all of them. + your password signs out your other devices, and your Subsonic apps too if + you tick "Sign out Subsonic apps too". A password reset, or an admin + resetting it, signs out all of them and every Subsonic app: the API key and + Subsonic password stop working, and you make new ones in Settings. - **API keys** (the OpenSubsonic `apiKey`) are stored as SHA-256 too, so a key is shown once, when you generate it in Settings, and can only be replaced after that. diff --git a/internal/api/admin_users.go b/internal/api/admin_users.go index 26b7ee1f..c6c33a23 100644 --- a/internal/api/admin_users.go +++ b/internal/api/admin_users.go @@ -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) diff --git a/internal/api/admin_users_test.go b/internal/api/admin_users_test.go index 5536ce47..774ff5df 100644 --- a/internal/api/admin_users_test.go +++ b/internal/api/admin_users_test.go @@ -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) +} diff --git a/internal/api/auth_reset.go b/internal/api/auth_reset.go index df94cf43..af592da5 100644 --- a/internal/api/auth_reset.go +++ b/internal/api/auth_reset.go @@ -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) diff --git a/internal/api/auth_reset_test.go b/internal/api/auth_reset_test.go index 7b0bf31c..bc0cd151 100644 --- a/internal/api/auth_reset_test.go +++ b/internal/api/auth_reset_test.go @@ -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) +} diff --git a/internal/api/me_password.go b/internal/api/me_password.go index 9ec27a87..eb370e2d 100644 --- a/internal/api/me_password.go +++ b/internal/api/me_password.go @@ -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) } diff --git a/internal/api/me_password_test.go b/internal/api/me_password_test.go index 2723b030..e88f528d 100644 --- a/internal/api/me_password_test.go +++ b/internal/api/me_password_test.go @@ -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) +} diff --git a/internal/api/me_subsonic_password.go b/internal/api/me_subsonic_password.go index bb60b804..9063675e 100644 --- a/internal/api/me_subsonic_password.go +++ b/internal/api/me_subsonic_password.go @@ -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}) + }) +} diff --git a/internal/api/me_subsonic_password_test.go b/internal/api/me_subsonic_password_test.go index 46a842c3..7ece3ce3 100644 --- a/internal/api/me_subsonic_password_test.go +++ b/internal/api/me_subsonic_password_test.go @@ -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") + } +} diff --git a/web/src/lib/api/me.ts b/web/src/lib/api/me.ts index 2a9fdb96..5046107d 100644 --- a/web/src/lib/api/me.ts +++ b/web/src/lib/api/me.ts @@ -35,10 +35,17 @@ export type MyProfile = { export type APITokenResponse = { api_token: string }; -export async function changePassword(currentPassword: string, newPassword: string): Promise { +// signOutSubsonic also ends every Subsonic app's access (the API token and +// the Subsonic password stop working), for a password someone else may know. +export async function changePassword( + currentPassword: string, + newPassword: string, + signOutSubsonic = false, +): Promise { await api.put('/api/me/password', { current_password: currentPassword, new_password: newPassword, + sign_out_subsonic: signOutSubsonic, }); } diff --git a/web/src/routes/settings/account/+page.svelte b/web/src/routes/settings/account/+page.svelte index faba9ce1..41652e7a 100644 --- a/web/src/routes/settings/account/+page.svelte +++ b/web/src/routes/settings/account/+page.svelte @@ -78,6 +78,7 @@ let current = $state(''); let next = $state(''); let confirm = $state(''); + let signOutSubsonic = $state(false); let passwordSaving = $state(false); async function onSavePassword(e: SubmitEvent) { @@ -88,9 +89,14 @@ } passwordSaving = true; try { - await changePassword(current, next); - pushToast('Password changed. Your other devices have been signed out.'); + await changePassword(current, next, signOutSubsonic); + pushToast( + signOutSubsonic + ? 'Password changed. Your other devices and Subsonic apps have been signed out.' + : 'Password changed. Your other devices have been signed out.', + ); current = next = confirm = ''; + signOutSubsonic = false; } catch (err: unknown) { const code = errCode(err); if (code === 'wrong_password') pushToast('Current password is incorrect.', 'error'); @@ -183,6 +189,18 @@ class={input} /> + + +