From 92da1bcbee3ad44096c13eee3f875083bd870d0c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 2 Oct 2026 11:32:50 +0000 Subject: [PATCH] fix(vastbase): support old passwords and retire stale connections Closes #8481 --- .../components/admin/DatabaseUserAdmin.vue | 117 +++++++- apps/desktop/src/i18n/locales/az.ts | 4 + apps/desktop/src/i18n/locales/en.ts | 4 + apps/desktop/src/i18n/locales/es.ts | 4 + apps/desktop/src/i18n/locales/id.ts | 4 + apps/desktop/src/i18n/locales/it.ts | 4 + apps/desktop/src/i18n/locales/ja.ts | 4 + apps/desktop/src/i18n/locales/ko.ts | 4 + apps/desktop/src/i18n/locales/pt-BR.ts | 4 + apps/desktop/src/i18n/locales/ru.ts | 4 + apps/desktop/src/i18n/locales/tr.ts | 4 + apps/desktop/src/i18n/locales/zh-CN.ts | 4 + apps/desktop/src/i18n/locales/zh-TW.ts | 4 + .../DatabaseUserAdmin.component.spec.ts | 215 +++++++++++++- .../databaseUserAdmin.passwordGuard.spec.ts | 24 ++ .../database/databaseUserAdmin.spec.ts | 21 ++ .../src/lib/database/databaseUserAdmin.ts | 9 +- .../connectionStore.passwordChange.spec.ts | 272 ++++++++++++++++++ apps/desktop/src/stores/connectionStore.ts | 56 +++- 19 files changed, 730 insertions(+), 32 deletions(-) create mode 100644 apps/desktop/src/lib/__tests__/database/databaseUserAdmin.passwordGuard.spec.ts create mode 100644 apps/desktop/src/stores/__tests__/connectionStore.passwordChange.spec.ts diff --git a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue index 7c436f11fa..2eba522aed 100644 --- a/apps/desktop/src/components/admin/DatabaseUserAdmin.vue +++ b/apps/desktop/src/components/admin/DatabaseUserAdmin.vue @@ -77,12 +77,16 @@ const pendingPlan = ref(); const pendingResults = ref([]); const pendingDanger = ref(false); const pendingAfterApply = ref<(() => Promise) | undefined>(); +const pendingPasswordChange = ref<{ connectionId: string; selfChange: boolean }>(); +const passwordReconnectRequired = ref(false); +const passwordCleanupFailed = ref(false); const createUser = ref("app_user"); const createHost = ref("%"); const createPassword = ref(""); const newHost = ref(""); const newPassword = ref(""); +const oldPassword = ref(""); const privilegeDatabase = ref(restoredUiState.privilegeDatabase ?? (props.connection.database || "*")); const privilegeTable = ref(restoredUiState.privilegeTable ?? "*"); const privilegeScope = ref(privilegeScopes.includes(restoredUiState.privilegeScope as PrivilegeScope) ? restoredUiState.privilegeScope! : "mysql"); @@ -192,12 +196,14 @@ async function ensureConnection() { } async function loadUsers() { + if (passwordReconnectRequired.value) return; const userProvider = provider.value; if (!userProvider) return; loadingUsers.value = true; loadError.value = ""; try { await ensureConnection(); + if (passwordReconnectRequired.value) return; let nextUsers: DatabaseUserIdentity[] = []; try { const result = await api.executeQuery(props.connection.id, "", userProvider.listUsersSql(), undefined, undefined, { @@ -221,6 +227,7 @@ async function loadUsers() { } async function loadGrants() { + if (passwordReconnectRequired.value) return; const user = selectedUser.value; const userProvider = provider.value; if (!user || !userProvider) { @@ -264,6 +271,7 @@ async function loadGrants() { } async function loadCurrentTableGrants() { + if (passwordReconnectRequired.value) return; const user = selectedUser.value; const userProvider = provider.value; if (!user || !userProvider?.tableGrantsSql || !userProvider.parseTableGrants || currentTableGrantsLoading.value) return; @@ -339,6 +347,7 @@ function togglePrivilege(privilege: string) { // 加载当前连接下的数据库列表:新增用户弹窗与权限编辑面板的授权范围编辑器共用 function loadDatabases(): Promise { + if (passwordReconnectRequired.value) return Promise.resolve(); if (databaseLoadPromise) return databaseLoadPromise; let request!: Promise; request = (async () => { @@ -347,6 +356,7 @@ function loadDatabases(): Promise { createDatabasesLoadError.value = ""; try { await ensureConnection(); + if (passwordReconnectRequired.value) return; const config = props.connection; if (provider.value?.authorizationModel === "starrocks") { const catalogs = await api.listDorisCatalogs(config.id); @@ -409,6 +419,7 @@ async function prepareAuthorizationSelections(selections: DatabaseAuthorizationS } function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => Promise } = {}) { + pendingPasswordChange.value = undefined; pendingSql.value = sql; pendingPlan.value = undefined; pendingResults.value = []; @@ -418,35 +429,88 @@ function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => } async function applyPendingSql() { - if (!pendingSql.value.trim()) return; + if (!pendingSql.value.trim() || applying.value || passwordReconnectRequired.value) return; + const sql = pendingSql.value; + const plan = pendingPlan.value; + const afterApply = pendingAfterApply.value; + const passwordChange = pendingPasswordChange.value; + const connection = props.connection; + const passwordSecrets = passwordChange ? [newPassword.value, oldPassword.value].filter(Boolean) : []; applying.value = true; try { const result = await executeWithProductionSqlGuard({ - connection: props.connection, + connection, database: "", - sql: pendingSql.value, + sql, source: t("production.sourceAdmin"), execute: async () => { - if (pendingPlan.value) { - return executeAuthorizationPlan(pendingPlan.value, (step) => api.executeMulti(props.connection.id, step.database, step.sql, undefined, undefined, { maxRows: 1000, catalog: step.targetCatalog, continueOnError: step.targetCatalog ? false : true })); + if (!sqlDialogOpen.value || pendingSql.value !== sql || props.connection.id !== connection.id) return undefined; + if (plan) { + return executeAuthorizationPlan(plan, (step) => api.executeMulti(connection.id, step.database, step.sql, undefined, undefined, { maxRows: 1000, catalog: step.targetCatalog, continueOnError: step.targetCatalog ? false : true })); } - const queryResults = await api.executeMulti(props.connection.id, "", pendingSql.value, undefined, undefined, { maxRows: 1000, continueOnError: true }); + const queryResults = await api.executeMulti(connection.id, "", sql, undefined, undefined, { maxRows: 1000, continueOnError: true }); const failed = queryResults.find((item) => item.execution_error === true); if (failed) throw new Error(String(failed.rows[0]?.[0] ?? t("userAdmin.applyFailedUnknown"))); + if (passwordChange?.selfChange) { + if (props.connection.id === connection.id) { + passwordReconnectRequired.value = true; + clearPendingSql(); + passwordDialogOpen.value = false; + } + try { + await connectionStore.retirePasswordAfterChange(passwordChange.connectionId); + toast(t("userAdmin.passwordChangedReconnect"), 8000); + } catch { + if (props.connection.id === connection.id) passwordCleanupFailed.value = true; + toast(t("userAdmin.passwordChangedCleanupFailed"), 10000); + } + } return [] as AuthorizationStepResult[]; }, }); if (!result) return; + if (passwordChange?.selfChange) return; + if (props.connection.id !== connection.id) return; pendingResults.value = result; const status = result.length > 0 ? authorizationPlanStatus(result) : "success"; toast(t(status === "success" ? "userAdmin.applySuccess" : status === "partial" ? "userAdmin.applyPartial" : "userAdmin.applyFailedSummary"), status === "success" ? 2500 : 5000); - const createSucceeded = !pendingPlan.value || result.some((item) => item.step.id === "create-user" && item.status === "success"); - if (createSucceeded) await (pendingAfterApply.value?.() ?? Promise.resolve()); - if (!pendingPlan.value) sqlDialogOpen.value = false; + const createSucceeded = !plan || result.some((item) => item.step.id === "create-user" && item.status === "success"); + if (createSucceeded) await (afterApply?.() ?? Promise.resolve()); + if (!plan) sqlDialogOpen.value = false; await loadUsers(); await loadGrants(); } catch (error: any) { - toast(t("userAdmin.applyFailed", { message: error?.message || String(error) }), 5000); + let message = error?.message || String(error); + for (const secret of passwordSecrets) { + message = message.replaceAll(secret.replaceAll("'", "''"), "***").replaceAll(secret, "***"); + } + toast(t("userAdmin.applyFailed", { message }), 5000); + } finally { + applying.value = false; + } +} + +function clearPendingSql() { + pendingSql.value = ""; + pendingPlan.value = undefined; + pendingResults.value = []; + pendingAfterApply.value = undefined; + pendingPasswordChange.value = undefined; + sqlDialogOpen.value = false; + newPassword.value = ""; + oldPassword.value = ""; +} + +async function reconnectAfterPasswordChange() { + if (applying.value || passwordCleanupFailed.value) return; + applying.value = true; + try { + await connectionStore.connect(connectionStore.getConfig(props.connection.id) ?? props.connection); + passwordReconnectRequired.value = false; + await loadUsers(); + await loadGrants(); + } catch { + toast(t("userAdmin.passwordChangedReconnect"), 8000); } finally { applying.value = false; } @@ -546,13 +610,15 @@ function previewPasswordChange() { const userProvider = provider.value; const alterPasswordSql = userProvider?.alterPasswordSql; if (!user || !alterPasswordSql || !newPassword.value) return; - previewSql(alterPasswordSql(user, newPassword.value), { + previewSql(alterPasswordSql(user, newPassword.value, oldPassword.value), { danger: true, afterApply: async () => { passwordDialogOpen.value = false; newPassword.value = ""; + oldPassword.value = ""; }, }); + pendingPasswordChange.value = { connectionId: props.connection.id, selfChange: !!userProvider?.supportsOldPassword && user.user === props.connection.username }; } function previewHostChange() { @@ -667,6 +733,17 @@ function resetPrivilegeDefaults(scope: PrivilegeScope) { } } +watch(passwordDialogOpen, (open) => { + if (open) return; + newPassword.value = ""; + oldPassword.value = ""; + if (pendingPasswordChange.value) clearPendingSql(); +}); + +watch(sqlDialogOpen, (open) => { + if (!open) clearPendingSql(); +}); + watch( () => createDialogOpen.value, (open) => { @@ -694,6 +771,10 @@ watch( watch( () => props.connection.id, () => { + clearPendingSql(); + passwordDialogOpen.value = false; + passwordReconnectRequired.value = false; + passwordCleanupFailed.value = false; tableGrantRequestId += 1; users.value = []; createDatabases.value = []; @@ -761,19 +842,23 @@ onMounted(() => { {{ connection.name }}
- -
-
+
+

{{ t(passwordCleanupFailed ? "userAdmin.passwordChangedCleanupFailed" : "userAdmin.passwordChangedReconnect") }}

+ +
+
{{ t("userAdmin.unsupported") }}
@@ -1000,6 +1085,10 @@ onMounted(() => { {{ t("userAdmin.changePassword") }} + diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts index aea8163530..cdd566b69d 100644 --- a/apps/desktop/src/i18n/locales/az.ts +++ b/apps/desktop/src/i18n/locales/az.ts @@ -4212,6 +4212,10 @@ export default withEnglishFallback({ }, }, userAdmin: { + oldPassword: "Cari parol (istəyə bağlı)", + oldPasswordHint: "Vastbase-də ilkin istifadəçidən başqa öz parolunuzu dəyişmək üçün cari parol tələb olunur. Başqa istifadəçinin parolunu səlahiyyətlə sıfırlayarkən boş buraxıla bilər.", + passwordChangedReconnect: "Parol dəyişdirildi. Bu bağlantı kəsildi və köhnə parol silindi. Bağlantı parametrlərində Saxla və qoşul seçimini istifadə edib yeni parolu daxil edin.", + passwordChangedCleanupFailed: "Parol dəyişdirildi, lakin bağlantının təmizlənməsi uğursuz oldu. Avtomatik yenidən qoşulma bloklanıb. DBX-i yenidən başlatmazdan əvvəl bu bağlantını redaktə edib köhnə parolu silin.", title: "İstifadəçilər və səlahiyyətlər", unsupported: "MySQL və PostgreSQL ilə uyğun əlaqələr dəstəklənir. SQL Server, Oracle və digər icazə modelləri sonradan əlavə edilə bilər.", newUser: "Yeni istifadəçi", diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index c3cf9c1af2..d478d42843 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -4791,6 +4791,10 @@ export default { }, }, userAdmin: { + oldPassword: "Current password (optional)", + oldPasswordHint: "For Vastbase, changing your own password requires the current password, except for the initial user. Authorized resets of another user may leave it empty.", + passwordChangedReconnect: "Password changed. This connection is disconnected and its old password has been cleared. To reconnect, use Save & Connect in connection settings and enter the new password.", + passwordChangedCleanupFailed: "Password changed, but connection cleanup failed. Automatic reconnection is blocked. Edit this connection to clear the old password before restarting DBX.", title: "Users & Privileges", unsupported: "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.", newUser: "New User", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 9fedc59015..633b81b777 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -4395,6 +4395,10 @@ export default withEnglishFallback({ doltSystemTables: "Tablas del sistema de Dolt", }, userAdmin: { + oldPassword: "Contraseña actual (opcional)", + oldPasswordHint: "En Vastbase, salvo el usuario inicial, cambiar la propia contraseña requiere la actual. Puede omitirse al restablecer la de otro usuario con autorización.", + passwordChangedReconnect: "Contraseña cambiada. Se desconectó esta conexión y se borró la contraseña anterior. Use Guardar y conectar en la configuración de conexión e introduzca la nueva contraseña.", + passwordChangedCleanupFailed: "Contraseña cambiada, pero falló la limpieza de la conexión. La reconexión automática está bloqueada. Edite esta conexión para borrar la contraseña anterior antes de reiniciar DBX.", title: "Usuarios y Privilegios", unsupported: "Se admiten conexiones compatibles con MySQL y PostgreSQL. Los modelos de permisos de SQL Server, Oracle y otros se pueden agregar próximamente.", newUser: "Nuevo usuario", diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts index 8b0adf8452..ca2ea04237 100644 --- a/apps/desktop/src/i18n/locales/id.ts +++ b/apps/desktop/src/i18n/locales/id.ts @@ -4695,6 +4695,10 @@ export default withEnglishFallback({ }, }, userAdmin: { + oldPassword: "Kata sandi saat ini (opsional)", + oldPasswordHint: "Di Vastbase, selain pengguna awal, perubahan kata sandi sendiri memerlukan kata sandi saat ini. Pengaturan ulang pengguna lain yang diizinkan dapat mengosongkannya.", + passwordChangedReconnect: "Kata sandi diubah. Koneksi diputus dan kata sandi lama dihapus. Gunakan Simpan dan hubungkan di pengaturan koneksi, lalu masukkan kata sandi baru.", + passwordChangedCleanupFailed: "Kata sandi diubah, tetapi pembersihan koneksi gagal. Koneksi ulang otomatis diblokir. Edit koneksi ini untuk menghapus kata sandi lama sebelum memulai ulang DBX.", title: "Pengguna & Hak Akses", unsupported: "Koneksi yang kompatibel dengan MySQL dan PostgreSQL didukung. SQL Server, Oracle, dan model izin lainnya dapat ditambahkan berikutnya.", newUser: "Pengguna Baru", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 871f332afc..7e1cb8c564 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -4217,6 +4217,10 @@ export default withEnglishFallback({ doltSystemTables: "Tabelle di sistema di Dolt", }, userAdmin: { + oldPassword: "Password attuale (facoltativa)", + oldPasswordHint: "In Vastbase, tranne per l'utente iniziale, per cambiare la propria password serve quella attuale. È possibile ometterla per reimpostazioni autorizzate di altri utenti.", + passwordChangedReconnect: "Password cambiata. La connessione è stata chiusa e la vecchia password cancellata. Usa Salva e connetti nelle impostazioni della connessione e inserisci la nuova password.", + passwordChangedCleanupFailed: "Password cambiata, ma la pulizia della connessione non è riuscita. La riconnessione automatica è bloccata. Modifica questa connessione per cancellare la vecchia password prima di riavviare DBX.", title: "Utenti e Privilegi", unsupported: "Connessioni compatibili con MySQL e PostgreSQL sono supportate. SQL Server, Oracle e altri modelli di autorizzazione possono essere aggiunti in seguito.", newUser: "Nuovo Utente", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 6b7a965b4d..d15f5a0425 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -4283,6 +4283,10 @@ export default withEnglishFallback({ summarySize: "サイズ", }, userAdmin: { + oldPassword: "現在のパスワード(任意)", + oldPasswordHint: "Vastbase では初期ユーザー以外が自分のパスワードを変更するには現在のパスワードが必要です。権限のある他ユーザーのリセットでは省略できます。", + passwordChangedReconnect: "パスワードを変更しました。接続を切断し、古いパスワードを消去しました。接続設定で「保存して接続」を選び、新しいパスワードを入力してください。", + passwordChangedCleanupFailed: "パスワードは変更されましたが、接続のクリーンアップに失敗しました。自動再接続を停止しました。DBX を再起動する前に接続を編集し、古いパスワードを消去してください。", title: "ユーザーと権限", unsupported: "MySQL互換およびPostgreSQL互換の接続がサポートされています。SQL Server、Oracle、その他の権限モデルは今後追加予定です。", newUser: "新しいユーザー", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 685f355209..46f81cfa80 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -4229,6 +4229,10 @@ export default withEnglishFallback({ blockIoChart: "블록 I/O", }, userAdmin: { + oldPassword: "현재 비밀번호(선택 사항)", + oldPasswordHint: "Vastbase에서 초기 사용자를 제외한 사용자가 자신의 비밀번호를 변경하려면 현재 비밀번호가 필요합니다. 권한이 있는 다른 사용자 재설정에서는 생략할 수 있습니다.", + passwordChangedReconnect: "비밀번호가 변경되었습니다. 연결을 끊고 이전 비밀번호를 지웠습니다. 연결 설정에서 저장 및 연결을 선택하고 새 비밀번호를 입력하세요.", + passwordChangedCleanupFailed: "비밀번호가 변경되었지만 연결 정리에 실패했습니다. 자동 재연결이 차단되었습니다. DBX를 다시 시작하기 전에 연결을 편집하여 이전 비밀번호를 지우세요.", title: "사용자 및 권한", unsupported: "MySQL 호환 및 PostgreSQL 호환 연결을 지원합니다. SQL Server, Oracle 및 기타 권한 모델은 추후 추가될 수 있습니다.", newUser: "새 사용자", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 077b6a00a1..57b858fbb6 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -4219,6 +4219,10 @@ export default withEnglishFallback({ doltSystemTables: "Tabelas de sistema do Dolt", }, userAdmin: { + oldPassword: "Senha atual (opcional)", + oldPasswordHint: "No Vastbase, exceto para o usuário inicial, alterar a própria senha exige a senha atual. Redefinições autorizadas de outro usuário podem omiti-la.", + passwordChangedReconnect: "Senha alterada. Esta conexão foi desconectada e a senha antiga foi apagada. Use Salvar e conectar nas configurações da conexão e digite a nova senha.", + passwordChangedCleanupFailed: "Senha alterada, mas a limpeza da conexão falhou. A reconexão automática está bloqueada. Edite esta conexão para apagar a senha antiga antes de reiniciar o DBX.", title: "Usuários e Privilégios", unsupported: "Conexões compatíveis com MySQL e PostgreSQL são suportadas. SQL Server, Oracle e outros modelos de permissão podem ser adicionados em seguida.", newUser: "Novo Usuário", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index 7015c3b92f..e24b687a91 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -4682,6 +4682,10 @@ export default withEnglishFallback({ }, }, userAdmin: { + oldPassword: "Текущий пароль (необязательно)", + oldPasswordHint: "В Vastbase для смены собственного пароля требуется текущий пароль, кроме начального пользователя. При разрешённом сбросе пароля другого пользователя его можно не указывать.", + passwordChangedReconnect: "Пароль изменён. Соединение закрыто, старый пароль удалён. В настройках соединения выберите «Сохранить и подключиться» и введите новый пароль.", + passwordChangedCleanupFailed: "Пароль изменён, но очистка соединения не удалась. Автоматическое подключение заблокировано. Удалите старый пароль в настройках соединения перед перезапуском DBX.", title: "Пользователи и привилегии", unsupported: "Поддерживаются подключения, совместимые с MySQL и PostgreSQL. SQL Server, Oracle и другие модели разрешений могут быть добавлены позже.", newUser: "Новый пользователь", diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts index 3a05d98ef0..292bddc67d 100644 --- a/apps/desktop/src/i18n/locales/tr.ts +++ b/apps/desktop/src/i18n/locales/tr.ts @@ -4116,6 +4116,10 @@ export default withEnglishFallback({ blockIoChart: "Blok G/Ç", }, userAdmin: { + oldPassword: "Geçerli parola (isteğe bağlı)", + oldPasswordHint: "Vastbase'de ilk kullanıcı dışında kendi parolanızı değiştirmek için geçerli parola gerekir. Başka bir kullanıcının parolasını yetkili olarak sıfırlarken boş bırakılabilir.", + passwordChangedReconnect: "Parola değiştirildi. Bu bağlantı kesildi ve eski parola temizlendi. Bağlantı ayarlarında Kaydet ve Bağlan seçeneğini kullanıp yeni parolayı girin.", + passwordChangedCleanupFailed: "Parola değiştirildi ancak bağlantı temizlenemedi. Otomatik yeniden bağlantı engellendi. DBX'i yeniden başlatmadan önce bu bağlantıyı düzenleyip eski parolayı temizleyin.", title: "Kullanıcılar ve Yetkiler", unsupported: "MySQL uyumlu ve PostgreSQL uyumlu bağlantılar desteklenir. SQL Server, Oracle ve diğer yetki modelleri daha sonra eklenebilir.", newUser: "Yeni Kullanıcı", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 9a9dfdfe01..241e7377ed 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -4767,6 +4767,10 @@ export default withEnglishFallback({ }, }, userAdmin: { + oldPassword: "旧密码(可选)", + oldPasswordHint: "Vastbase 除初始用户外,修改自己的密码需提供旧密码;有权限重置其他用户密码时可留空。", + passwordChangedReconnect: "密码已修改。此连接已断开并清除旧密码。请在连接设置中选择“保存并连接”,并输入新密码。", + passwordChangedCleanupFailed: "密码已修改,但连接清理失败,已阻止自动重连。重启 DBX 前,请编辑此连接并清除旧密码。", title: "用户与权限", unsupported: "当前支持 MySQL 兼容与 PostgreSQL 兼容连接。SQL Server、Oracle 等会按各自权限模型继续扩展。", newUser: "新建用户", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index c90559a342..1f45494210 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -8562,6 +8562,10 @@ export default withEnglishFallback({ nacosContextPathHint: "留空時使用目前連線模式的預設值;明確使用服務根路徑請填寫 /,反向代理情境可填寫 /nacos 等前綴。", }, userAdmin: { + oldPassword: "舊密碼(選填)", + oldPasswordHint: "Vastbase 除初始使用者外,修改自己的密碼需提供舊密碼;有權限重設其他使用者密碼時可留空。", + passwordChangedReconnect: "密碼已修改。此連線已中斷並清除舊密碼。請在連線設定中選擇「儲存並連線」,並輸入新密碼。", + passwordChangedCleanupFailed: "密碼已修改,但連線清理失敗,已阻止自動重連。重新啟動 DBX 前,請編輯此連線並清除舊密碼。", title: "使用者與權限", unsupported: "支援 MySQL 相容和 PostgreSQL 相容連線。SQL Server、Oracle 等其他權限模型將在後續版本中新增。", newUser: "新增使用者", diff --git a/apps/desktop/src/lib/__tests__/database/DatabaseUserAdmin.component.spec.ts b/apps/desktop/src/lib/__tests__/database/DatabaseUserAdmin.component.spec.ts index 3399b6c6b1..417f41d341 100644 --- a/apps/desktop/src/lib/__tests__/database/DatabaseUserAdmin.component.spec.ts +++ b/apps/desktop/src/lib/__tests__/database/DatabaseUserAdmin.component.spec.ts @@ -6,6 +6,12 @@ import type { ConnectionConfig } from "@/types/database"; const mocks = vi.hoisted(() => ({ ensureConnected: vi.fn(), + retirePasswordAfterChange: vi.fn(), + connect: vi.fn(), + getConfig: vi.fn(), + guardCancelled: false, + guardWait: undefined as Promise | undefined, + trackUiState: vi.fn(), executeQuery: vi.fn(), executeMulti: vi.fn(), productionGuard: vi.fn(), @@ -114,7 +120,7 @@ vi.mock("@/components/ui/select", () => ({ SelectValue: passthrough("span"), })); vi.mock("@/stores/connectionStore", () => ({ - useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected }), + useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected, retirePasswordAfterChange: mocks.retirePasswordAfterChange, connect: mocks.connect, getConfig: mocks.getConfig }), })); vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) })); vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (sql: string) => sql }) })); @@ -128,13 +134,15 @@ vi.mock("@/lib/backend/api", () => ({ listSchemas: mocks.listSchemas, })); vi.mock("@/lib/database/productionExecutionGuard", () => ({ - executeWithProductionSqlGuard: (options: { execute: () => Promise }) => { + executeWithProductionSqlGuard: async (options: { execute: () => Promise }) => { mocks.productionGuard(options); + await mocks.guardWait; + if (mocks.guardCancelled) return Promise.resolve(undefined); return options.execute(); }, })); vi.mock("@/lib/tabs/tabUiState", () => ({ - useTabUiState: () => ({ initialState: mocks.tabUiState, track: vi.fn(), update: vi.fn() }), + useTabUiState: () => ({ initialState: mocks.tabUiState, track: mocks.trackUiState, update: vi.fn() }), })); import DatabaseUserAdmin from "@/components/admin/DatabaseUserAdmin.vue"; @@ -188,9 +196,210 @@ afterEach(() => { app = undefined; root = undefined; mocks.tabUiState = {}; + mocks.guardCancelled = false; + mocks.guardWait = undefined; vi.clearAllMocks(); }); +describe("DatabaseUserAdmin Vastbase passwords", () => { + const config = { ...postgresConnection, id: "vastbase", db_type: "vastbase", username: "fixture_self", password: "saved-old" } as ConnectionConfig; + + async function mountPassword(user = "fixture_self", dbConfig = config) { + mocks.ensureConnected.mockResolvedValue(undefined); + mocks.retirePasswordAfterChange.mockResolvedValue(undefined); + mocks.connect.mockResolvedValue(undefined); + mocks.getConfig.mockReturnValue({ ...dbConfig, password: "", save_password: false }); + mocks.executeQuery.mockImplementation(async (_id, _db, sql: string) => (!sql.startsWith("WITH target") ? { columns: ["user", "host", "plugin"], rows: [[user, "LOGIN", ""]] } : { columns: ["grant"], rows: [] })); + root = document.createElement("div"); + document.body.append(root); + app = createApp(DatabaseUserAdmin, { connection: dbConfig }); + app.mount(root); + await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(2)); + findButton("userAdmin.changePassword")!.click(); + await nextTick(); + } + + async function preview(old = "fixture-old") { + for (const [key, value] of [ + ["newPassword", "fixture-new"], + ["oldPassword", old], + ]) { + const input = root!.querySelector(`input[placeholder="userAdmin.${key}"]`); + expect(input).not.toBeNull(); + input!.value = value; + input!.dispatchEvent(new Event("input", { bubbles: true })); + } + await nextTick(); + findButton("userAdmin.previewSql")!.click(); + await nextTick(); + } + + it("retires self credentials immediately after mutation without refreshing", async () => { + await mountPassword(); + await preview(); + expect(root!.textContent).toContain(`ALTER ROLE "fixture_self" IDENTIFIED BY 'fixture-new' REPLACE 'fixture-old';`); + mocks.executeMulti.mockResolvedValueOnce([]); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.retirePasswordAfterChange).toHaveBeenCalledWith("vastbase")); + await nextTick(); + expect(mocks.executeMulti.mock.invocationCallOrder[0]).toBeLessThan(mocks.retirePasswordAfterChange.mock.invocationCallOrder[0]); + expect(mocks.executeQuery).toHaveBeenCalledTimes(2); + expect(mocks.ensureConnected).toHaveBeenCalledTimes(1); + expect(root!.textContent).not.toContain("fixture-new"); + expect(root!.textContent).not.toContain("fixture-old"); + expect(mocks.toast).toHaveBeenCalledWith("userAdmin.passwordChangedReconnect", 8000); + expect(mocks.connect).not.toHaveBeenCalled(); + const trackedState = mocks.trackUiState.mock.calls[0][0](); + expect(JSON.stringify(trackedState)).not.toContain("fixture-new"); + expect(JSON.stringify(trackedState)).not.toContain("fixture-old"); + }); + + it("refreshes after an authorized other-user reset without retiring current credentials", async () => { + await mountPassword("fixture_other"); + await preview(""); + expect(root!.textContent).toContain(`ALTER ROLE "fixture_other" IDENTIFIED BY 'fixture-new';`); + mocks.executeMulti.mockResolvedValueOnce([]); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(4)); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + expect(config.password).toBe("saved-old"); + }); + + it.each(["missing old password", "wrong old password", "cross-admin denied"])("preserves credentials when the server reports %s", async (message) => { + await mountPassword(message === "cross-admin denied" ? "fixture_admin" : "fixture_self"); + await preview(message === "missing old password" ? "" : "fixture-incorrect"); + mocks.executeMulti.mockResolvedValueOnce([{ execution_error: true, rows: [[message]] }]); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(`userAdmin.applyFailed: ${message}`, 5000)); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + expect(mocks.executeQuery).toHaveBeenCalledTimes(2); + expect(config.password).toBe("saved-old"); + }); + + it("does not execute or retire passwords when the production guard is cancelled", async () => { + await mountPassword(); + await preview(); + mocks.guardCancelled = true; + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.productionGuard).toHaveBeenCalled()); + expect(mocks.executeMulti).not.toHaveBeenCalled(); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + }); + + it("clears password fields and SQL when a preview is closed and reopened", async () => { + await mountPassword(); + await preview(); + const cancels = Array.from(root!.querySelectorAll("button")).filter((button) => button.textContent === "dangerDialog.cancel"); + cancels.at(-1)!.click(); + await nextTick(); + expect(root!.textContent).not.toContain("fixture-new"); + expect(root!.textContent).not.toContain("fixture-old"); + findButton("userAdmin.changePassword")!.click(); + await nextTick(); + expect(root!.querySelector('input[placeholder="userAdmin.newPassword"]')!.value).toBe(""); + expect(root!.querySelector('input[placeholder="userAdmin.oldPassword"]')!.value).toBe(""); + expect(findButton("userAdmin.previewSql")!.disabled).toBe(true); + }); + + it("does not dispatch a preview closed while confirmation is pending", async () => { + await mountPassword(); + await preview(); + let confirm!: () => void; + mocks.guardWait = new Promise((resolve) => { + confirm = resolve; + }); + findButton("userAdmin.applySql")!.click(); + await nextTick(); + const cancels = Array.from(root!.querySelectorAll("button")).filter((button) => button.textContent === "dangerDialog.cancel"); + cancels.at(-1)!.click(); + await nextTick(); + confirm(); + await nextTick(); + await nextTick(); + expect(mocks.executeMulti).not.toHaveBeenCalled(); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + }); + + it("retains the mutation identity when its dialog closes during execution", async () => { + await mountPassword(); + await preview(); + let finish!: (result: unknown[]) => void; + mocks.executeMulti.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalled()); + const cancels = Array.from(root!.querySelectorAll("button")).filter((button) => button.textContent === "dangerDialog.cancel"); + cancels.at(-1)!.click(); + await nextTick(); + finish([]); + await vi.waitFor(() => expect(mocks.retirePasswordAfterChange).toHaveBeenCalledWith(config.id)); + expect(mocks.executeQuery).toHaveBeenCalledTimes(2); + }); + + it("reports cleanup failure as an already changed password without retrying or refreshing", async () => { + await mountPassword(); + await preview(); + mocks.executeMulti.mockResolvedValueOnce([]); + mocks.retirePasswordAfterChange.mockRejectedValueOnce(new Error("cleanup failed")); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("userAdmin.passwordChangedCleanupFailed", 10000)); + expect(mocks.executeQuery).toHaveBeenCalledTimes(2); + expect(root!.textContent).not.toContain("fixture-new"); + expect(findButton("userAdmin.applySql")).toBeUndefined(); + expect(findButton("contextMenu.openConnection")).toBeUndefined(); + }); + + it("loads users only after an explicit reconnect and starts the next operation with empty secrets", async () => { + await mountPassword(); + await preview(); + mocks.executeMulti.mockResolvedValueOnce([]); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.retirePasswordAfterChange).toHaveBeenCalled()); + await nextTick(); + mocks.connect.mockRejectedValueOnce(new Error("prompt cancelled")); + findButton("contextMenu.openConnection")!.click(); + await nextTick(); + await nextTick(); + expect(mocks.executeQuery).toHaveBeenCalledTimes(2); + findButton("contextMenu.openConnection")!.click(); + await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(4)); + expect(mocks.connect).toHaveBeenCalledWith(expect.objectContaining({ password: "", save_password: false })); + findButton("userAdmin.changePassword")!.click(); + await nextTick(); + expect(root!.querySelector('input[placeholder="userAdmin.newPassword"]')!.value).toBe(""); + expect(root!.querySelector('input[placeholder="userAdmin.oldPassword"]')!.value).toBe(""); + }); + + it("redacts passwords echoed by a rejected backend request", async () => { + await mountPassword(); + await preview(); + mocks.executeMulti.mockRejectedValueOnce(new Error("rejected fixture-new with fixture-old")); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("userAdmin.applyFailed: rejected *** with ***", 5000)); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + }); + + it("keeps the PostgreSQL password dialog and SQL unchanged", async () => { + await mountPassword("fixture_self", { ...config, db_type: "postgres" }); + expect(root!.querySelector('input[placeholder="userAdmin.oldPassword"]')).toBeNull(); + const input = root!.querySelector('input[placeholder="userAdmin.newPassword"]')!; + input.value = "fixture-new"; + input.dispatchEvent(new Event("input", { bubbles: true })); + await nextTick(); + findButton("userAdmin.previewSql")!.click(); + await nextTick(); + expect(root!.textContent).toContain(`ALTER ROLE "fixture_self" PASSWORD 'fixture-new';`); + mocks.executeMulti.mockResolvedValueOnce([]); + findButton("userAdmin.applySql")!.click(); + await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(4)); + expect(mocks.retirePasswordAfterChange).not.toHaveBeenCalled(); + }); +}); + describe("DatabaseUserAdmin MySQL grant loading", () => { it("syncs the grant option from loaded SHOW GRANTS rows and renders the database scope editor", async () => { mocks.ensureConnected.mockResolvedValue(undefined); diff --git a/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.passwordGuard.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.passwordGuard.spec.ts new file mode 100644 index 0000000000..c683e88a6f --- /dev/null +++ b/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.passwordGuard.spec.ts @@ -0,0 +1,24 @@ +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getDatabaseUserAdminProvider } from "@/lib/database/databaseUserAdmin"; +import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard"; +import { useProductionSafetyStore } from "@/stores/productionSafetyStore"; +import type { ConnectionConfig } from "@/types/database"; + +describe("Vastbase password production guard", () => { + beforeEach(() => setActivePinia(createPinia())); + + it.each([true, false])("executes password SQL only when confirmation is %s", async (confirmed) => { + const connection: ConnectionConfig = { id: "vastbase-guard", name: "Fixture", db_type: "vastbase", host: "localhost", port: 5432, username: "fixture_self", password: "", is_production: true }; + const sql = getDatabaseUserAdminProvider("vastbase")!.alterPasswordSql!({ user: "fixture_self", host: "LOGIN" }, "fixture-new", "fixture-old"); + const execute = vi.fn().mockResolvedValue([]); + const pending = executeWithProductionSqlGuard({ connection, database: "", sql, execute }); + await vi.waitFor(() => expect(useProductionSafetyStore().pending?.sql).toBe(sql)); + expect(execute).not.toHaveBeenCalled(); + if (confirmed) useProductionSafetyStore().confirm(); + else useProductionSafetyStore().cancel(); + await pending; + expect(execute).toHaveBeenCalledTimes(confirmed ? 1 : 0); + expect(useProductionSafetyStore().pending).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.spec.ts index f6aacfe0ad..844d6c9f94 100644 --- a/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.spec.ts +++ b/apps/desktop/src/lib/__tests__/database/databaseUserAdmin.spec.ts @@ -37,6 +37,27 @@ function connection(dbType: ConnectionConfig["db_type"], driverProfile?: string) }; } +describe("Vastbase password changes", () => { + const user = { user: 'fixture"role', host: "LOGIN" }; + + it("quotes both passwords and the role in the exact self-change grammar", () => { + const provider = getDatabaseUserAdminProvider("vastbase")!; + expect(provider.alterPasswordSql!(user, "new'password", "old'password")).toBe(`ALTER ROLE "fixture""role" IDENTIFIED BY 'new''password' REPLACE 'old''password';`); + }); + + it("allows the server to authorize a reset without the old password", () => { + const provider = getDatabaseUserAdminProvider("vastbase")!; + expect(provider.alterPasswordSql!(user, "new", "")).toBe('ALTER ROLE "fixture""role" IDENTIFIED BY \'new\';'); + expect(provider.alterPasswordSql!(user, "new")).toBe('ALTER ROLE "fixture""role" IDENTIFIED BY \'new\';'); + }); + + it("keeps whitespace in old passwords and preserves PostgreSQL and MySQL defaults", () => { + expect(getDatabaseUserAdminProvider("vastbase")!.alterPasswordSql!(user, "new", " ")).toContain(" REPLACE ' ';"); + expect(getDatabaseUserAdminProvider("postgres")!.alterPasswordSql!(user, "new", "old")).toBe('ALTER ROLE "fixture""role" PASSWORD \'new\';'); + expect(getDatabaseUserAdminProvider("mysql")!.alterPasswordSql!({ user: "fixture", host: "%" }, "new", "old")).toBe("ALTER USER 'fixture'@'%' IDENTIFIED BY 'new';"); + }); +}); + describe("MySQL grant privilege selection", () => { const availablePrivileges = ["SELECT", "INSERT", "UPDATE", "EXECUTE"]; diff --git a/apps/desktop/src/lib/database/databaseUserAdmin.ts b/apps/desktop/src/lib/database/databaseUserAdmin.ts index 16930cf7e7..4c867f8a50 100644 --- a/apps/desktop/src/lib/database/databaseUserAdmin.ts +++ b/apps/desktop/src/lib/database/databaseUserAdmin.ts @@ -66,7 +66,8 @@ export interface DatabaseUserAdminProvider { parseGrants?(result: QueryResult): string[]; createUserSql?(input: CreatePrincipalInput): string; renameUserSql?(user: DatabaseUserIdentity, newHost: string): string; - alterPasswordSql?(user: DatabaseUserIdentity, password: string): string; + supportsOldPassword?: boolean; + alterPasswordSql?(user: DatabaseUserIdentity, password: string, oldPassword?: string): string; alterLoginSql?(user: DatabaseUserIdentity, enabled: boolean): string; dropUserSql?(user: DatabaseUserIdentity): string; grantPrivilegesSql?(input: PrivilegeChangeInput): string; @@ -657,6 +658,10 @@ export function postgresAlterRolePasswordSql(user: DatabaseUserIdentity, passwor return `ALTER ROLE ${quotePostgresIdentifier(user.user)} PASSWORD ${quoteSqlString(password)};`; } +export function vastbaseAlterRolePasswordSql(user: DatabaseUserIdentity, password: string, oldPassword?: string): string { + return `ALTER ROLE ${quotePostgresIdentifier(user.user)} IDENTIFIED BY ${quoteSqlString(password)}${oldPassword ? ` REPLACE ${quoteSqlString(oldPassword)}` : ""};`; +} + export function postgresAlterRoleLoginSql(user: DatabaseUserIdentity, enabled: boolean): string { return `ALTER ROLE ${quotePostgresIdentifier(user.user)} ${enabled ? "LOGIN" : "NOLOGIN"};`; } @@ -967,7 +972,7 @@ const DATABASE_USER_ADMIN_PROVIDER_BY_TYPE = new Map ({ + connectDb: vi.fn(), + disconnectDb: vi.fn(), + saveConnections: vi.fn(), + sessionCredentialStatus: vi.fn(), + forgetSessionCredential: vi.fn(), + checkConnectionHealth: vi.fn(), + connectionIdentifierQuote: vi.fn(), +})); +const requestPassword = vi.hoisted(() => vi.fn()); +const retainedTabRefresh = vi.hoisted(() => vi.fn()); + +vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false })); +vi.mock("@/lib/backend/api", () => ({ + ...api, + deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined), + loadSchemaCache: vi.fn().mockResolvedValue(null), + saveSidebarLayout: vi.fn().mockResolvedValue(undefined), + connectionDatabaseInfo: vi.fn().mockResolvedValue(undefined), + listInstalledAgents: vi.fn().mockResolvedValue([]), +})); +vi.mock("@/stores/connectionPasswordPromptStore", () => ({ + useConnectionPasswordPromptStore: () => ({ pending: null, requestPassword }), +})); +vi.mock("@/stores/queryStore", () => ({ + useQueryStore: () => ({ + rollbackConnectionTransactions: retainedTabRefresh, + closeConnectionTabs: retainedTabRefresh, + releaseConnectionTabs: retainedTabRefresh, + invalidateConnectionMetadata: vi.fn(), + tabs: [], + flushPendingPersist: vi.fn().mockResolvedValue(undefined), + }), +})); + +const config: ConnectionConfig = { + id: "vastbase-password-fixture", + name: "Vastbase fixture", + db_type: "vastbase", + host: "localhost", + port: 5432, + username: "fixture_self", + password: "fixture-old", + save_password: true, +}; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((complete) => { + resolve = complete; + }); + return { promise, resolve }; +} + +describe("connectionStore password retirement", () => { + beforeEach(() => { + const data = new Map(); + vi.stubGlobal("localStorage", { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => data.set(key, value), + removeItem: (key: string) => data.delete(key), + }); + setActivePinia(createPinia()); + for (const mock of Object.values(api)) mock.mockReset().mockResolvedValue(undefined); + api.connectDb.mockResolvedValue(config.id); + api.sessionCredentialStatus.mockResolvedValue(true); + retainedTabRefresh.mockReset(); + requestPassword.mockReset().mockResolvedValue({ password: "fixture-new", rememberPassword: false }); + }); + + afterEach(() => vi.unstubAllGlobals()); + + async function storeWithConnection() { + const { useConnectionStore } = await import("@/stores/connectionStore"); + const { useSettingsStore } = await import("@/stores/settingsStore"); + useSettingsStore().editorSettings.disconnectTabHandlingMode = "keep-tabs-keep-results"; + const store = useConnectionStore(); + store.connections = [{ ...config }, { ...config, id: "other-connection", password: "other-secret" }]; + store.connectedIds.add(config.id); + return store; + } + + it("blocks retained-tab reconnects before disconnect and clears only the changed connection", async () => { + const store = await storeWithConnection(); + let finishDisconnect!: () => void; + api.disconnectDb.mockImplementation( + () => + new Promise((resolve) => { + finishDisconnect = resolve; + }), + ); + const retirement = store.retirePasswordAfterChange(config.id); + await expect(store.ensureConnected(config.id)).rejects.toThrow(); + await expect(store.connect(config)).rejects.toThrow(); + let retainedTabError: unknown; + retainedTabRefresh.mockImplementation(() => { + void store.ensureConnected(config.id).catch((error) => { + retainedTabError = error; + }); + }); + await vi.waitFor(() => expect(retainedTabRefresh).toHaveBeenCalled()); + finishDisconnect(); + await retirement; + expect(retainedTabError).toBeInstanceOf(Error); + expect(api.connectDb).not.toHaveBeenCalled(); + expect(api.checkConnectionHealth).not.toHaveBeenCalled(); + expect(api.forgetSessionCredential).toHaveBeenCalledWith(config.id); + expect(api.disconnectDb.mock.invocationCallOrder[0]).toBeLessThan(api.forgetSessionCredential.mock.invocationCallOrder[0]); + expect(store.getConfig(config.id)).toMatchObject({ password: "", save_password: false }); + expect(store.getConfig("other-connection")?.password).toBe("other-secret"); + expect(api.saveConnections).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ id: config.id, password: "", save_password: false })])); + await expect(store.ensureConnected(config.id, { forceReconnect: true })).rejects.toThrow(); + }); + + it("requires fresh input for explicit reconnect even if a caller retains the old config", async () => { + const store = await storeWithConnection(); + await store.retirePasswordAfterChange(config.id); + await store.connect(config); + expect(requestPassword).toHaveBeenCalledTimes(1); + expect(api.connectDb).toHaveBeenCalledWith(expect.objectContaining({ password: "fixture-new", save_password: false }), expect.any(Number)); + expect(store.getConfig(config.id)?.password).toBe(""); + await expect(store.ensureConnected(config.id, { verifyHealth: false })).resolves.toBeUndefined(); + }); + + describe.each(["connect", "ensureConnected"] as const)("%s credential persistence", (method) => { + it.each(["none", "transient", "remembered"] as const)("does not restore a retired password after a delayed save with %s fresh reconnect", async (reconnect) => { + const store = await storeWithConnection(); + const unsaved = { ...config, password: "", save_password: false }; + store.connections[0] = unsaved; + store.connectedIds.delete(config.id); + store.connectedIds.add("other-connection"); + const other = { ...store.getConfig("other-connection")! }; + const oldSave = deferred(); + const oldSaveEntered = deferred(); + let persisted = store.connections.map((connection) => ({ ...connection })); + api.saveConnections.mockImplementation(async (snapshot: ConnectionConfig[]) => { + const saved = snapshot.map((connection) => ({ ...connection })); + if (saved.find((connection) => connection.id === config.id)?.password === config.password) { + oldSaveEntered.resolve(); + await oldSave.promise; + } + persisted = saved; + }); + api.sessionCredentialStatus.mockResolvedValue(false); + requestPassword.mockResolvedValueOnce({ password: config.password, rememberPassword: true }); + + const connecting = (method === "connect" ? store.connect(unsaved) : store.ensureConnected(config.id)).catch((error: unknown) => error); + await oldSaveEntered.promise; + const waiting = method === "ensureConnected" ? store.ensureConnected(config.id, { forceReconnect: true }).catch((error: unknown) => error) : undefined; + expect(store.connectedIds.has(config.id)).toBe(true); + await store.retirePasswordAfterChange(config.id); + expect(store.getConfig(config.id)).toMatchObject({ password: "", save_password: false }); + expect(persisted.find((connection) => connection.id === config.id)).toMatchObject({ password: "", save_password: false }); + + if (reconnect !== "none") { + requestPassword.mockResolvedValueOnce({ password: "fixture-new", rememberPassword: reconnect === "remembered" }); + await store.connect(unsaved); + expect(api.connectDb).toHaveBeenLastCalledWith(expect.objectContaining({ password: "fixture-new" }), expect.any(Number)); + } + const current = store.connections.map((connection) => ({ ...connection })); + const active = store.activeConnectionId; + const currentError = store.connectionErrors[config.id]; + const disconnectCount = api.disconnectDb.mock.calls.length; + oldSave.resolve(); + const result = await connecting; + const waitingResult = await waiting; + + expect.soft(store.connections).toEqual(current); + expect.soft(persisted).toEqual(current); + expect(api.saveConnections).toHaveBeenCalledTimes(reconnect === "remembered" ? 4 : 3); + expect(store.connectedIds.has(config.id)).toBe(reconnect !== "none"); + expect(store.activeConnectionId).toBe(active); + expect(store.connectionErrors[config.id]).toBe(currentError); + expect(api.disconnectDb).toHaveBeenCalledTimes(disconnectCount); + expect(store.getConfig("other-connection")).toEqual(other); + expect(store.connectedIds.has("other-connection")).toBe(true); + expect(persisted.find((connection) => connection.id === "other-connection")).toEqual(other); + expect(result).toBeInstanceOf(Error); + if (waiting) expect(waitingResult).toBeInstanceOf(Error); + if (reconnect === "none") await expect(store.ensureConnected(config.id)).rejects.toThrow(); + else await expect(store.ensureConnected(config.id, { verifyHealth: false })).resolves.toBeUndefined(); + }); + + it.each([false, true])("does not save a retired password after metadata resumes (fresh reconnect: %s)", async (reconnect) => { + const store = await storeWithConnection(); + const unsaved = { ...config, db_type: "gaussdb" as const, password: "", save_password: false }; + store.connections[0] = unsaved; + store.connectedIds.delete(config.id); + const metadata = deferred(); + const metadataEntered = deferred(); + api.connectionIdentifierQuote.mockImplementationOnce(() => { + metadataEntered.resolve(); + return metadata.promise; + }); + api.sessionCredentialStatus.mockResolvedValue(false); + requestPassword.mockResolvedValueOnce({ password: config.password, rememberPassword: true }); + + const connecting = (method === "connect" ? store.connect(unsaved) : store.ensureConnected(config.id)).catch((error: unknown) => error); + await metadataEntered.promise; + expect(store.connectedIds.has(config.id)).toBe(true); + expect(api.saveConnections).not.toHaveBeenCalled(); + await store.retirePasswordAfterChange(config.id); + if (reconnect) await store.connect(unsaved); + const current = store.connections.map((connection) => ({ ...connection })); + const active = store.activeConnectionId; + const currentError = store.connectionErrors[config.id]; + metadata.resolve('"'); + const result = await connecting; + + expect(store.connections).toEqual(current); + expect(api.saveConnections).toHaveBeenCalledTimes(1); + expect(api.saveConnections).toHaveBeenLastCalledWith(current); + expect(store.connectedIds.has(config.id)).toBe(reconnect); + expect(store.activeConnectionId).toBe(active); + expect(store.connectionErrors[config.id]).toBe(currentError); + expect(api.disconnectDb).toHaveBeenCalledTimes(1); + expect(result).toBeInstanceOf(Error); + }); + }); + + it.each(["connect", "ensureConnected"] as const)("cancels %s already waiting on a previous disconnect", async (method) => { + const store = await storeWithConnection(); + let finishDisconnect!: () => void; + api.disconnectDb.mockImplementationOnce( + () => + new Promise((resolve) => { + finishDisconnect = resolve; + }), + ); + const disconnect = store.disconnect(config.id); + const pendingConnect = (method === "connect" ? store.connect(config) : store.ensureConnected(config.id)).catch((error: unknown) => error); + const retirement = store.retirePasswordAfterChange(config.id); + finishDisconnect(); + await Promise.all([disconnect, retirement]); + expect(await pendingConnect).toBeInstanceOf(Error); + expect(api.connectDb).not.toHaveBeenCalled(); + }); + + it("keeps automatic reconnect blocked when fresh input is cancelled or rejected", async () => { + const store = await storeWithConnection(); + await store.retirePasswordAfterChange(config.id); + requestPassword.mockResolvedValueOnce(null); + await expect(store.connect(config)).rejects.toThrow(); + expect(api.connectDb).not.toHaveBeenCalled(); + api.connectDb.mockRejectedValueOnce(new Error("server rejected new password")); + await expect(store.connect(config)).rejects.toThrow("server rejected new password"); + await expect(store.ensureConnected(config.id)).rejects.toThrow(); + expect(store.getConfig(config.id)?.password).toBe(""); + }); + + it.each(["saveConnections", "disconnectDb", "sessionCredentialStatus", "forgetSessionCredential"] as const)("stays blocked if %s fails after the server changed the password", async (method) => { + const store = await storeWithConnection(); + api[method].mockRejectedValueOnce(new Error("fixture cleanup failure")); + await expect(store.retirePasswordAfterChange(config.id)).rejects.toThrow(); + await expect(store.ensureConnected(config.id)).rejects.toThrow(); + await expect(store.connect(config)).rejects.toThrow(); + expect(api.connectDb).not.toHaveBeenCalled(); + expect(store.getConfig(config.id)?.password).toBe(""); + }); + + it("does not forget a nonexistent transient password for a saved-password connection", async () => { + const store = await storeWithConnection(); + api.sessionCredentialStatus.mockResolvedValue(false); + await store.retirePasswordAfterChange(config.id); + expect(api.forgetSessionCredential).not.toHaveBeenCalled(); + expect(store.connectedIds.has(config.id)).toBe(false); + }); +}); diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts index f14d1c01f4..f443cea15a 100644 --- a/apps/desktop/src/stores/connectionStore.ts +++ b/apps/desktop/src/stores/connectionStore.ts @@ -683,6 +683,7 @@ export const useConnectionStore = defineStore("connection", () => { const connectInFlight = new Map>(); const disconnectInFlight = new Map>(); const disconnectInFlightScoped = new Map(); + const passwordChangeReconnectRequired = new Map(); const cancelDisconnectInFlight = new Map>(); const activeLocalConnectionAttempts = new Map(); const cancelledLocalConnectionAttempts = new Map>(); @@ -4536,15 +4537,16 @@ export const useConnectionStore = defineStore("connection", () => { } } - async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise { - if (!rememberPassword) return; + async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string, localAttempt: number): Promise { + if (!rememberPassword || !isCurrentLocalConnectionAttempt(config.id, localAttempt)) return; const index = connections.value.findIndex((connection) => connection.id === config.id); if (index < 0) return; if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) return; const nextConnections = [...connections.value]; nextConnections[index] = { ...nextConnections[index], password: config.password, save_password: true }; await persistConnections(nextConnections); - if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) { + const current = getConfig(config.id); + if (!isCurrentLocalConnectionAttempt(config.id, localAttempt) || !current || connectionConfigFingerprint(current) !== expectedConfigFingerprint) { await persistConnections(); return; } @@ -4569,12 +4571,19 @@ export const useConnectionStore = defineStore("connection", () => { async function connect(config: ConnectionConfig) { config = normalizeConnection(config); + const passwordChangeState = passwordChangeReconnectRequired.get(config.id); + if (passwordChangeState === "retiring") throw new Error(i18n.global.t("userAdmin.passwordChangedCleanupFailed")); const expectedConfigFingerprint = connectionConfigFingerprint(getConfig(config.id) ?? config); if (getBlockingDisconnectInFlight(config.id)) await waitForBlockingDisconnectInFlight(config.id); + if (passwordChangeReconnectRequired.get(config.id) !== passwordChangeState) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect")); const localAttempt = beginLocalConnectionAttempt(config.id); try { let rememberPassword = false; - if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(config.id))) { + if (passwordChangeState === "ready") { + const prompted = await ensureConnectionPassword({ ...config, password: "", save_password: false }, true); + config = prompted.config; + rememberPassword = prompted.rememberPassword; + } else if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(config.id))) { const prompted = await ensureConnectionPassword(config); config = prompted.config; rememberPassword = prompted.rememberPassword; @@ -4591,11 +4600,13 @@ export const useConnectionStore = defineStore("connection", () => { await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id); await syncMongoLegacyDriverFallback(id, config); await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id); + passwordChangeReconnectRequired.delete(config.id); activeConnectionId.value = id; connectedIds.value.add(id); if (config.db_type !== "plugin") { void refreshConnectedDatabaseInfo(id, { ...config, id }); await refreshConnectionIdentifierQuote(id, { ...config, id }); + ensureLocalConnectionAttemptActive(config.id, localAttempt); // Compatibility modes warm asynchronously; the QueryEditor watcher and the // backend's own A-mode/EXISTS validation make a cold map safe. void refreshConnectionDatabaseModes(id, { ...config, id }); @@ -4627,18 +4638,18 @@ export const useConnectionStore = defineStore("connection", () => { }); } try { - await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint); + await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt); } catch (error) { - setConnectionError(id, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) })); + if (isCurrentLocalConnectionAttempt(config.id, localAttempt)) setConnectionError(id, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) })); } + ensureLocalConnectionAttemptActive(config.id, localAttempt); return id; } catch (e) { if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) { - clearConnectionError(config.id); throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE); } if (isCancelledConnectionAttempt(e) || isSupersededConnectionAttempt(e)) { - clearConnectionError(config.id); + if (isCurrentLocalConnectionAttempt(config.id, localAttempt)) clearConnectionError(config.id); } else { recordConnectionError(config.id, e); } @@ -4824,6 +4835,21 @@ export const useConnectionStore = defineStore("connection", () => { await api.forgetSessionCredential(connectionId); } + async function retirePasswordAfterChange(connectionId: string) { + passwordChangeReconnectRequired.set(connectionId, "retiring"); + connections.value = connections.value.map((config) => (config.id === connectionId ? { ...config, password: "", save_password: false } : config)); + const results = await Promise.allSettled([disconnect(connectionId), persistConnections()]); + try { + if (await api.sessionCredentialStatus(connectionId)) await api.forgetSessionCredential(connectionId); + if (results.some((result) => result.status === "rejected")) throw new Error(); + passwordChangeReconnectRequired.set(connectionId, "ready"); + setConnectionError(connectionId, i18n.global.t("userAdmin.passwordChangedReconnect")); + } catch { + setConnectionError(connectionId, i18n.global.t("userAdmin.passwordChangedCleanupFailed")); + throw new Error(i18n.global.t("userAdmin.passwordChangedCleanupFailed")); + } + } + async function closeDatabaseConnection(connectionId: string, database: string) { if (hasSqlServerActivityTraceForConnection(connectionId, database)) await disposeSqlServerActivityTracesForConnection(connectionId, database); cancelObjectDdlLoadsForDatabase(connectionId, database); @@ -4863,6 +4889,7 @@ export const useConnectionStore = defineStore("connection", () => { } async function ensureConnected(connectionId: string, options: { activate?: boolean; verifyHealth?: boolean; forceReconnect?: boolean; allowPasswordPrompt?: boolean } = {}) { + if (passwordChangeReconnectRequired.has(connectionId)) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect")); if (!options.forceReconnect && connectedIds.value.has(connectionId)) { // Pure navigation can safely trust the existing connected state. Its // destination will perform the real API request, while blocking here on @@ -4906,6 +4933,7 @@ export const useConnectionStore = defineStore("connection", () => { } const expectedConfigFingerprint = connectionConfigFingerprint(config); if (getBlockingDisconnectInFlight(connectionId)) await waitForBlockingDisconnectInFlight(connectionId); + if (passwordChangeReconnectRequired.has(connectionId)) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect")); const existingConnect = connectInFlight.get(connectionId); if (existingConnect) { await existingConnect; @@ -4940,32 +4968,33 @@ export const useConnectionStore = defineStore("connection", () => { if (config.db_type !== "plugin") { void refreshConnectedDatabaseInfo(connectionId, config); await refreshConnectionIdentifierQuote(connectionId, config); + ensureLocalConnectionAttemptActive(connectionId, localAttempt); void refreshConnectionDatabaseModes(connectionId, config); } markSuccessfulLocalConnectionAttempt(connectionId, localAttempt); markConnectionHealthChecked(connectionId); clearConnectionError(connectionId); try { - await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint); + await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt); } catch (error) { - setConnectionError(connectionId, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) })); + if (isCurrentLocalConnectionAttempt(connectionId, localAttempt)) setConnectionError(connectionId, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) })); } + ensureLocalConnectionAttemptActive(connectionId, localAttempt); })(); connectInFlight.set(connectionId, connectPromise); try { await connectPromise; + ensureLocalConnectionAttemptActive(connectionId, localAttempt); if (options.activate !== false) activeConnectionId.value = connectionId; } catch (e) { if (isCancelledLocalConnectionAttempt(connectionId, localAttempt)) { - clearConnectionError(connectionId); throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE); } if (isCancelledConnectionAttempt(e)) { - clearConnectionError(connectionId); + if (isCurrentLocalConnectionAttempt(connectionId, localAttempt)) clearConnectionError(connectionId); throw e; } if (isSupersededConnectionAttempt(e) && connectedIds.value.has(connectionId)) { - clearConnectionError(connectionId); return; } // 后台搜索触发的重连失败只留一行提示,避免把完整驱动错误(如旧版 SQL Server 的 TLS 提示) @@ -10271,6 +10300,7 @@ export const useConnectionStore = defineStore("connection", () => { handleConnectionLivenessMessage, metadataGenerationFor, disconnectAndForgetConnectionPassword, + retirePasswordAfterChange, hasSessionCredential, closeDatabaseConnection, ensureConnected,