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
@@ -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,
)
/**
@@ -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,
),
)
}
@@ -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,
@@ -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,
+4 -2
View File
@@ -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.
+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")
}
}
+8 -1
View File
@@ -35,10 +35,17 @@ export type MyProfile = {
export type APITokenResponse = { api_token: string };
export async function changePassword(currentPassword: string, newPassword: string): Promise<void> {
// 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<void> {
await api.put('/api/me/password', {
current_password: currentPassword,
new_password: newPassword,
sign_out_subsonic: signOutSubsonic,
});
}
+20 -2
View File
@@ -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}
/>
</SettingRow>
<SettingRow
label="Sign out Subsonic apps too"
hint="Your API token and Subsonic password stop working."
for="password-signout-subsonic"
>
<input
id="password-signout-subsonic"
type="checkbox"
bind:checked={signOutSubsonic}
class="h-4 w-4 cursor-pointer accent-accent"
/>
</SettingRow>
<div class="flex justify-end px-4 py-3">
<button type="submit" disabled={passwordSaving || !current || !next || !confirm} class={primary}>
{passwordSaving ? 'Saving…' : 'Change password'}
@@ -78,7 +78,21 @@ describe('Settings › Account', () => {
await fireEvent.input(screen.getByLabelText(/^new password/i), { target: { value: 'newpw1234' } });
await fireEvent.input(screen.getByLabelText(/confirm new password/i), { target: { value: 'newpw1234' } });
await fireEvent.click(screen.getByRole('button', { name: /change password/i }));
await waitFor(() => expect(changePassword).toHaveBeenCalledWith('oldpw1234', 'newpw1234'));
await waitFor(() => expect(changePassword).toHaveBeenCalledWith('oldpw1234', 'newpw1234', false));
});
test('ticking "Sign out Subsonic apps too" asks the server to sign them out', async () => {
setup();
vi.mocked(changePassword).mockResolvedValue(undefined);
await fireEvent.input(screen.getByLabelText(/current password/i), { target: { value: 'oldpw1234' } });
await fireEvent.input(screen.getByLabelText(/^new password/i), { target: { value: 'newpw1234' } });
await fireEvent.input(screen.getByLabelText(/confirm new password/i), { target: { value: 'newpw1234' } });
await fireEvent.click(screen.getByLabelText(/sign out subsonic apps too/i));
await fireEvent.click(screen.getByRole('button', { name: /change password/i }));
await waitFor(() => expect(changePassword).toHaveBeenCalledWith('oldpw1234', 'newpw1234', true));
expect(pushToast).toHaveBeenCalledWith(
'Password changed. Your other devices and Subsonic apps have been signed out.',
);
});
test('the Android app leads the page when the server bundles it', async () => {