fix(vastbase): support old passwords and retire stale connections

Closes #8481
This commit is contained in:
t8y2 committed 2026-10-02 12:05:05 +00:00
1 parent f75f5eb159
commit 92da1bcbee
19 files changed
+730 -32

No files matched your search

@@ -77,12 +77,16 @@ const pendingPlan = ref<AuthorizationPlan>();
const pendingResults = ref<AuthorizationStepResult[]>([]); const pendingResults = ref<AuthorizationStepResult[]>([]);
const pendingDanger = ref(false); const pendingDanger = ref(false);
const pendingAfterApply = ref<(() => Promise<void>) | undefined>(); const pendingAfterApply = ref<(() => Promise<void>) | undefined>();
const pendingPasswordChange = ref<{ connectionId: string; selfChange: boolean }>();
const passwordReconnectRequired = ref(false);
const passwordCleanupFailed = ref(false);
const createUser = ref("app_user"); const createUser = ref("app_user");
const createHost = ref("%"); const createHost = ref("%");
const createPassword = ref(""); const createPassword = ref("");
const newHost = ref(""); const newHost = ref("");
const newPassword = ref(""); const newPassword = ref("");
const oldPassword = ref("");
const privilegeDatabase = ref(restoredUiState.privilegeDatabase ?? (props.connection.database || "*")); const privilegeDatabase = ref(restoredUiState.privilegeDatabase ?? (props.connection.database || "*"));
const privilegeTable = ref(restoredUiState.privilegeTable ?? "*"); const privilegeTable = ref(restoredUiState.privilegeTable ?? "*");
const privilegeScope = ref<PrivilegeScope>(privilegeScopes.includes(restoredUiState.privilegeScope as PrivilegeScope) ? restoredUiState.privilegeScope! : "mysql"); const privilegeScope = ref<PrivilegeScope>(privilegeScopes.includes(restoredUiState.privilegeScope as PrivilegeScope) ? restoredUiState.privilegeScope! : "mysql");
@@ -192,12 +196,14 @@ async function ensureConnection() {
} }
async function loadUsers() { async function loadUsers() {
if (passwordReconnectRequired.value) return;
const userProvider = provider.value; const userProvider = provider.value;
if (!userProvider) return; if (!userProvider) return;
loadingUsers.value = true; loadingUsers.value = true;
loadError.value = ""; loadError.value = "";
try { try {
await ensureConnection(); await ensureConnection();
if (passwordReconnectRequired.value) return;
let nextUsers: DatabaseUserIdentity[] = []; let nextUsers: DatabaseUserIdentity[] = [];
try { try {
const result = await api.executeQuery(props.connection.id, "", userProvider.listUsersSql(), undefined, undefined, { const result = await api.executeQuery(props.connection.id, "", userProvider.listUsersSql(), undefined, undefined, {
@@ -221,6 +227,7 @@ async function loadUsers() {
} }
async function loadGrants() { async function loadGrants() {
if (passwordReconnectRequired.value) return;
const user = selectedUser.value; const user = selectedUser.value;
const userProvider = provider.value; const userProvider = provider.value;
if (!user || !userProvider) { if (!user || !userProvider) {
@@ -264,6 +271,7 @@ async function loadGrants() {
} }
async function loadCurrentTableGrants() { async function loadCurrentTableGrants() {
if (passwordReconnectRequired.value) return;
const user = selectedUser.value; const user = selectedUser.value;
const userProvider = provider.value; const userProvider = provider.value;
if (!user || !userProvider?.tableGrantsSql || !userProvider.parseTableGrants || currentTableGrantsLoading.value) return; if (!user || !userProvider?.tableGrantsSql || !userProvider.parseTableGrants || currentTableGrantsLoading.value) return;
@@ -339,6 +347,7 @@ function togglePrivilege(privilege: string) {
// 加载当前连接下的数据库列表:新增用户弹窗与权限编辑面板的授权范围编辑器共用 // 加载当前连接下的数据库列表:新增用户弹窗与权限编辑面板的授权范围编辑器共用
function loadDatabases(): Promise<void> { function loadDatabases(): Promise<void> {
if (passwordReconnectRequired.value) return Promise.resolve();
if (databaseLoadPromise) return databaseLoadPromise; if (databaseLoadPromise) return databaseLoadPromise;
let request!: Promise<void>; let request!: Promise<void>;
request = (async () => { request = (async () => {
@@ -347,6 +356,7 @@ function loadDatabases(): Promise<void> {
createDatabasesLoadError.value = ""; createDatabasesLoadError.value = "";
try { try {
await ensureConnection(); await ensureConnection();
if (passwordReconnectRequired.value) return;
const config = props.connection; const config = props.connection;
if (provider.value?.authorizationModel === "starrocks") { if (provider.value?.authorizationModel === "starrocks") {
const catalogs = await api.listDorisCatalogs(config.id); 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<void> } = {}) { function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => Promise<void> } = {}) {
pendingPasswordChange.value = undefined;
pendingSql.value = sql; pendingSql.value = sql;
pendingPlan.value = undefined; pendingPlan.value = undefined;
pendingResults.value = []; pendingResults.value = [];
@@ -418,35 +429,88 @@ function previewSql(sql: string, options: { danger?: boolean; afterApply?: () =>
} }
async function applyPendingSql() { 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; applying.value = true;
try { try {
const result = await executeWithProductionSqlGuard({ const result = await executeWithProductionSqlGuard({
connection: props.connection, connection,
database: "", database: "",
sql: pendingSql.value, sql,
source: t("production.sourceAdmin"), source: t("production.sourceAdmin"),
execute: async () => { execute: async () => {
if (pendingPlan.value) { if (!sqlDialogOpen.value || pendingSql.value !== sql || props.connection.id !== connection.id) return undefined;
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 (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); const failed = queryResults.find((item) => item.execution_error === true);
if (failed) throw new Error(String(failed.rows[0]?.[0] ?? t("userAdmin.applyFailedUnknown"))); 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[]; return [] as AuthorizationStepResult[];
}, },
}); });
if (!result) return; if (!result) return;
if (passwordChange?.selfChange) return;
if (props.connection.id !== connection.id) return;
pendingResults.value = result; pendingResults.value = result;
const status = result.length > 0 ? authorizationPlanStatus(result) : "success"; const status = result.length > 0 ? authorizationPlanStatus(result) : "success";
toast(t(status === "success" ? "userAdmin.applySuccess" : status === "partial" ? "userAdmin.applyPartial" : "userAdmin.applyFailedSummary"), status === "success" ? 2500 : 5000); 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"); const createSucceeded = !plan || result.some((item) => item.step.id === "create-user" && item.status === "success");
if (createSucceeded) await (pendingAfterApply.value?.() ?? Promise.resolve()); if (createSucceeded) await (afterApply?.() ?? Promise.resolve());
if (!pendingPlan.value) sqlDialogOpen.value = false; if (!plan) sqlDialogOpen.value = false;
await loadUsers(); await loadUsers();
await loadGrants(); await loadGrants();
} catch (error: any) { } 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 { } finally {
applying.value = false; applying.value = false;
} }
@@ -546,13 +610,15 @@ function previewPasswordChange() {
const userProvider = provider.value; const userProvider = provider.value;
const alterPasswordSql = userProvider?.alterPasswordSql; const alterPasswordSql = userProvider?.alterPasswordSql;
if (!user || !alterPasswordSql || !newPassword.value) return; if (!user || !alterPasswordSql || !newPassword.value) return;
previewSql(alterPasswordSql(user, newPassword.value), { previewSql(alterPasswordSql(user, newPassword.value, oldPassword.value), {
danger: true, danger: true,
afterApply: async () => { afterApply: async () => {
passwordDialogOpen.value = false; passwordDialogOpen.value = false;
newPassword.value = ""; newPassword.value = "";
oldPassword.value = "";
}, },
}); });
pendingPasswordChange.value = { connectionId: props.connection.id, selfChange: !!userProvider?.supportsOldPassword && user.user === props.connection.username };
} }
function previewHostChange() { 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( watch(
() => createDialogOpen.value, () => createDialogOpen.value,
(open) => { (open) => {
@@ -694,6 +771,10 @@ watch(
watch( watch(
() => props.connection.id, () => props.connection.id,
() => { () => {
clearPendingSql();
passwordDialogOpen.value = false;
passwordReconnectRequired.value = false;
passwordCleanupFailed.value = false;
tableGrantRequestId += 1; tableGrantRequestId += 1;
users.value = []; users.value = [];
createDatabases.value = []; createDatabases.value = [];
@@ -761,19 +842,23 @@ onMounted(() => {
<Badge variant="outline" class="h-5 rounded-md px-1.5 text-[11px]">{{ connection.name }}</Badge> <Badge variant="outline" class="h-5 rounded-md px-1.5 text-[11px]">{{ connection.name }}</Badge>
</div> </div>
<div class="ml-auto flex items-center gap-1.5"> <div class="ml-auto flex items-center gap-1.5">
<Button variant="outline" size="sm" class="h-7 gap-1.5 px-2 text-xs" @click="loadUsers"> <Button variant="outline" size="sm" class="h-7 gap-1.5 px-2 text-xs" :disabled="passwordReconnectRequired" @click="loadUsers">
<Loader2 v-if="loadingUsers" class="h-3.5 w-3.5 animate-spin" /> <Loader2 v-if="loadingUsers" class="h-3.5 w-3.5 animate-spin" />
<RefreshCcw v-else class="h-3.5 w-3.5" /> <RefreshCcw v-else class="h-3.5 w-3.5" />
{{ t("grid.refresh") }} {{ t("grid.refresh") }}
</Button> </Button>
<Button v-if="canCreateUser" size="sm" class="h-7 gap-1.5 px-2 text-xs" @click="openCreateUserDialog"> <Button v-if="canCreateUser" size="sm" class="h-7 gap-1.5 px-2 text-xs" :disabled="passwordReconnectRequired" @click="openCreateUserDialog">
<Plus class="h-3.5 w-3.5" /> <Plus class="h-3.5 w-3.5" />
{{ t("userAdmin.newUser") }} {{ t("userAdmin.newUser") }}
</Button> </Button>
</div> </div>
</div> </div>
<div v-if="!supported" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground"> <div v-if="passwordReconnectRequired" class="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground">
<p>{{ t(passwordCleanupFailed ? "userAdmin.passwordChangedCleanupFailed" : "userAdmin.passwordChangedReconnect") }}</p>
<Button v-if="!passwordCleanupFailed" :disabled="applying" @click="reconnectAfterPasswordChange">{{ t("contextMenu.openConnection") }}</Button>
</div>
<div v-else-if="!supported" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
{{ t("userAdmin.unsupported") }} {{ t("userAdmin.unsupported") }}
</div> </div>
@@ -1000,6 +1085,10 @@ onMounted(() => {
<DialogHeader> <DialogHeader>
<DialogTitle>{{ t("userAdmin.changePassword") }}</DialogTitle> <DialogTitle>{{ t("userAdmin.changePassword") }}</DialogTitle>
</DialogHeader> </DialogHeader>
<template v-if="provider?.supportsOldPassword">
<PasswordInput v-model="oldPassword" :placeholder="t('userAdmin.oldPassword')" autocomplete="current-password" />
<p class="text-xs text-muted-foreground">{{ t("userAdmin.oldPasswordHint") }}</p>
</template>
<PasswordInput v-model="newPassword" :placeholder="t('userAdmin.newPassword')" /> <PasswordInput v-model="newPassword" :placeholder="t('userAdmin.newPassword')" />
<DialogFooter> <DialogFooter>
<Button variant="outline" @click="passwordDialogOpen = false">{{ t("dangerDialog.cancel") }}</Button> <Button variant="outline" @click="passwordDialogOpen = false">{{ t("dangerDialog.cancel") }}</Button>
+4
View File
@@ -4212,6 +4212,10 @@ export default withEnglishFallback({
}, },
}, },
userAdmin: { 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", 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.", 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", newUser: "Yeni istifadəçi",
+4
View File
@@ -4791,6 +4791,10 @@ export default {
}, },
}, },
userAdmin: { 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", title: "Users & Privileges",
unsupported: "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.", unsupported: "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.",
newUser: "New User", newUser: "New User",
+4
View File
@@ -4395,6 +4395,10 @@ export default withEnglishFallback({
doltSystemTables: "Tablas del sistema de Dolt", doltSystemTables: "Tablas del sistema de Dolt",
}, },
userAdmin: { 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", 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.", 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", newUser: "Nuevo usuario",
+4
View File
@@ -4695,6 +4695,10 @@ export default withEnglishFallback({
}, },
}, },
userAdmin: { 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", title: "Pengguna & Hak Akses",
unsupported: "Koneksi yang kompatibel dengan MySQL dan PostgreSQL didukung. SQL Server, Oracle, dan model izin lainnya dapat ditambahkan berikutnya.", unsupported: "Koneksi yang kompatibel dengan MySQL dan PostgreSQL didukung. SQL Server, Oracle, dan model izin lainnya dapat ditambahkan berikutnya.",
newUser: "Pengguna Baru", newUser: "Pengguna Baru",
+4
View File
@@ -4217,6 +4217,10 @@ export default withEnglishFallback({
doltSystemTables: "Tabelle di sistema di Dolt", doltSystemTables: "Tabelle di sistema di Dolt",
}, },
userAdmin: { 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", 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.", 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", newUser: "Nuovo Utente",
+4
View File
@@ -4283,6 +4283,10 @@ export default withEnglishFallback({
summarySize: "サイズ", summarySize: "サイズ",
}, },
userAdmin: { userAdmin: {
oldPassword: "現在のパスワード(任意)",
oldPasswordHint: "Vastbase では初期ユーザー以外が自分のパスワードを変更するには現在のパスワードが必要です。権限のある他ユーザーのリセットでは省略できます。",
passwordChangedReconnect: "パスワードを変更しました。接続を切断し、古いパスワードを消去しました。接続設定で「保存して接続」を選び、新しいパスワードを入力してください。",
passwordChangedCleanupFailed: "パスワードは変更されましたが、接続のクリーンアップに失敗しました。自動再接続を停止しました。DBX を再起動する前に接続を編集し、古いパスワードを消去してください。",
title: "ユーザーと権限", title: "ユーザーと権限",
unsupported: "MySQL互換およびPostgreSQL互換の接続がサポートされています。SQL Server、Oracle、その他の権限モデルは今後追加予定です。", unsupported: "MySQL互換およびPostgreSQL互換の接続がサポートされています。SQL Server、Oracle、その他の権限モデルは今後追加予定です。",
newUser: "新しいユーザー", newUser: "新しいユーザー",
+4
View File
@@ -4229,6 +4229,10 @@ export default withEnglishFallback({
blockIoChart: "블록 I/O", blockIoChart: "블록 I/O",
}, },
userAdmin: { userAdmin: {
oldPassword: "현재 비밀번호(선택 사항)",
oldPasswordHint: "Vastbase에서 초기 사용자를 제외한 사용자가 자신의 비밀번호를 변경하려면 현재 비밀번호가 필요합니다. 권한이 있는 다른 사용자 재설정에서는 생략할 수 있습니다.",
passwordChangedReconnect: "비밀번호가 변경되었습니다. 연결을 끊고 이전 비밀번호를 지웠습니다. 연결 설정에서 저장 및 연결을 선택하고 새 비밀번호를 입력하세요.",
passwordChangedCleanupFailed: "비밀번호가 변경되었지만 연결 정리에 실패했습니다. 자동 재연결이 차단되었습니다. DBX를 다시 시작하기 전에 연결을 편집하여 이전 비밀번호를 지우세요.",
title: "사용자 및 권한", title: "사용자 및 권한",
unsupported: "MySQL 호환 및 PostgreSQL 호환 연결을 지원합니다. SQL Server, Oracle 및 기타 권한 모델은 추후 추가될 수 있습니다.", unsupported: "MySQL 호환 및 PostgreSQL 호환 연결을 지원합니다. SQL Server, Oracle 및 기타 권한 모델은 추후 추가될 수 있습니다.",
newUser: "새 사용자", newUser: "새 사용자",
+4
View File
@@ -4219,6 +4219,10 @@ export default withEnglishFallback({
doltSystemTables: "Tabelas de sistema do Dolt", doltSystemTables: "Tabelas de sistema do Dolt",
}, },
userAdmin: { 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", 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.", 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", newUser: "Novo Usuário",
+4
View File
@@ -4682,6 +4682,10 @@ export default withEnglishFallback({
}, },
}, },
userAdmin: { userAdmin: {
oldPassword: "Текущий пароль (необязательно)",
oldPasswordHint: "В Vastbase для смены собственного пароля требуется текущий пароль, кроме начального пользователя. При разрешённом сбросе пароля другого пользователя его можно не указывать.",
passwordChangedReconnect: "Пароль изменён. Соединение закрыто, старый пароль удалён. В настройках соединения выберите «Сохранить и подключиться» и введите новый пароль.",
passwordChangedCleanupFailed: "Пароль изменён, но очистка соединения не удалась. Автоматическое подключение заблокировано. Удалите старый пароль в настройках соединения перед перезапуском DBX.",
title: "Пользователи и привилегии", title: "Пользователи и привилегии",
unsupported: "Поддерживаются подключения, совместимые с MySQL и PostgreSQL. SQL Server, Oracle и другие модели разрешений могут быть добавлены позже.", unsupported: "Поддерживаются подключения, совместимые с MySQL и PostgreSQL. SQL Server, Oracle и другие модели разрешений могут быть добавлены позже.",
newUser: "Новый пользователь", newUser: "Новый пользователь",
+4
View File
@@ -4116,6 +4116,10 @@ export default withEnglishFallback({
blockIoChart: "Blok G/Ç", blockIoChart: "Blok G/Ç",
}, },
userAdmin: { 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", 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.", 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ı", newUser: "Yeni Kullanıcı",
+4
View File
@@ -4767,6 +4767,10 @@ export default withEnglishFallback({
}, },
}, },
userAdmin: { userAdmin: {
oldPassword: "旧密码(可选)",
oldPasswordHint: "Vastbase 除初始用户外,修改自己的密码需提供旧密码;有权限重置其他用户密码时可留空。",
passwordChangedReconnect: "密码已修改。此连接已断开并清除旧密码。请在连接设置中选择“保存并连接”,并输入新密码。",
passwordChangedCleanupFailed: "密码已修改,但连接清理失败,已阻止自动重连。重启 DBX 前,请编辑此连接并清除旧密码。",
title: "用户与权限", title: "用户与权限",
unsupported: "当前支持 MySQL 兼容与 PostgreSQL 兼容连接。SQL Server、Oracle 等会按各自权限模型继续扩展。", unsupported: "当前支持 MySQL 兼容与 PostgreSQL 兼容连接。SQL Server、Oracle 等会按各自权限模型继续扩展。",
newUser: "新建用户", newUser: "新建用户",
+4
View File
@@ -8562,6 +8562,10 @@ export default withEnglishFallback({
nacosContextPathHint: "留空時使用目前連線模式的預設值;明確使用服務根路徑請填寫 /,反向代理情境可填寫 /nacos 等前綴。", nacosContextPathHint: "留空時使用目前連線模式的預設值;明確使用服務根路徑請填寫 /,反向代理情境可填寫 /nacos 等前綴。",
}, },
userAdmin: { userAdmin: {
oldPassword: "舊密碼(選填)",
oldPasswordHint: "Vastbase 除初始使用者外,修改自己的密碼需提供舊密碼;有權限重設其他使用者密碼時可留空。",
passwordChangedReconnect: "密碼已修改。此連線已中斷並清除舊密碼。請在連線設定中選擇「儲存並連線」,並輸入新密碼。",
passwordChangedCleanupFailed: "密碼已修改,但連線清理失敗,已阻止自動重連。重新啟動 DBX 前,請編輯此連線並清除舊密碼。",
title: "使用者與權限", title: "使用者與權限",
unsupported: "支援 MySQL 相容和 PostgreSQL 相容連線。SQL Server、Oracle 等其他權限模型將在後續版本中新增。", unsupported: "支援 MySQL 相容和 PostgreSQL 相容連線。SQL Server、Oracle 等其他權限模型將在後續版本中新增。",
newUser: "新增使用者", newUser: "新增使用者",
@@ -6,6 +6,12 @@ import type { ConnectionConfig } from "@/types/database";
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
ensureConnected: vi.fn(), ensureConnected: vi.fn(),
retirePasswordAfterChange: vi.fn(),
connect: vi.fn(),
getConfig: vi.fn(),
guardCancelled: false,
guardWait: undefined as Promise<void> | undefined,
trackUiState: vi.fn(),
executeQuery: vi.fn(), executeQuery: vi.fn(),
executeMulti: vi.fn(), executeMulti: vi.fn(),
productionGuard: vi.fn(), productionGuard: vi.fn(),
@@ -114,7 +120,7 @@ vi.mock("@/components/ui/select", () => ({
SelectValue: passthrough("span"), SelectValue: passthrough("span"),
})); }));
vi.mock("@/stores/connectionStore", () => ({ 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/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (sql: string) => sql }) })); vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (sql: string) => sql }) }));
@@ -128,13 +134,15 @@ vi.mock("@/lib/backend/api", () => ({
listSchemas: mocks.listSchemas, listSchemas: mocks.listSchemas,
})); }));
vi.mock("@/lib/database/productionExecutionGuard", () => ({ vi.mock("@/lib/database/productionExecutionGuard", () => ({
executeWithProductionSqlGuard: (options: { execute: () => Promise<unknown> }) => { executeWithProductionSqlGuard: async (options: { execute: () => Promise<unknown> }) => {
mocks.productionGuard(options); mocks.productionGuard(options);
await mocks.guardWait;
if (mocks.guardCancelled) return Promise.resolve(undefined);
return options.execute(); return options.execute();
}, },
})); }));
vi.mock("@/lib/tabs/tabUiState", () => ({ 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"; import DatabaseUserAdmin from "@/components/admin/DatabaseUserAdmin.vue";
@@ -188,9 +196,210 @@ afterEach(() => {
app = undefined; app = undefined;
root = undefined; root = undefined;
mocks.tabUiState = {}; mocks.tabUiState = {};
mocks.guardCancelled = false;
mocks.guardWait = undefined;
vi.clearAllMocks(); 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<HTMLInputElement>(`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<HTMLButtonElement>("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<HTMLInputElement>('input[placeholder="userAdmin.newPassword"]')!.value).toBe("");
expect(root!.querySelector<HTMLInputElement>('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<void>((resolve) => {
confirm = resolve;
});
findButton("userAdmin.applySql")!.click();
await nextTick();
const cancels = Array.from(root!.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLInputElement>('input[placeholder="userAdmin.newPassword"]')!.value).toBe("");
expect(root!.querySelector<HTMLInputElement>('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<HTMLInputElement>('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", () => { describe("DatabaseUserAdmin MySQL grant loading", () => {
it("syncs the grant option from loaded SHOW GRANTS rows and renders the database scope editor", async () => { it("syncs the grant option from loaded SHOW GRANTS rows and renders the database scope editor", async () => {
mocks.ensureConnected.mockResolvedValue(undefined); mocks.ensureConnected.mockResolvedValue(undefined);
@@ -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();
});
});
@@ -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", () => { describe("MySQL grant privilege selection", () => {
const availablePrivileges = ["SELECT", "INSERT", "UPDATE", "EXECUTE"]; const availablePrivileges = ["SELECT", "INSERT", "UPDATE", "EXECUTE"];
@@ -66,7 +66,8 @@ export interface DatabaseUserAdminProvider {
parseGrants?(result: QueryResult): string[]; parseGrants?(result: QueryResult): string[];
createUserSql?(input: CreatePrincipalInput): string; createUserSql?(input: CreatePrincipalInput): string;
renameUserSql?(user: DatabaseUserIdentity, newHost: string): 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; alterLoginSql?(user: DatabaseUserIdentity, enabled: boolean): string;
dropUserSql?(user: DatabaseUserIdentity): string; dropUserSql?(user: DatabaseUserIdentity): string;
grantPrivilegesSql?(input: PrivilegeChangeInput): string; grantPrivilegesSql?(input: PrivilegeChangeInput): string;
@@ -657,6 +658,10 @@ export function postgresAlterRolePasswordSql(user: DatabaseUserIdentity, passwor
return `ALTER ROLE ${quotePostgresIdentifier(user.user)} PASSWORD ${quoteSqlString(password)};`; 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 { export function postgresAlterRoleLoginSql(user: DatabaseUserIdentity, enabled: boolean): string {
return `ALTER ROLE ${quotePostgresIdentifier(user.user)} ${enabled ? "LOGIN" : "NOLOGIN"};`; return `ALTER ROLE ${quotePostgresIdentifier(user.user)} ${enabled ? "LOGIN" : "NOLOGIN"};`;
} }
@@ -967,7 +972,7 @@ const DATABASE_USER_ADMIN_PROVIDER_BY_TYPE = new Map<DatabaseType, DatabaseUserA
["kwdb", postgresCompatibleUserAdminProvider], ["kwdb", postgresCompatibleUserAdminProvider],
["opengauss", postgresCompatibleUserAdminProvider], ["opengauss", postgresCompatibleUserAdminProvider],
["questdb", postgresCompatibleUserAdminProvider], ["questdb", postgresCompatibleUserAdminProvider],
["vastbase", postgresCompatibleUserAdminProvider], ["vastbase", { ...postgresCompatibleUserAdminProvider, supportsOldPassword: true, alterPasswordSql: vastbaseAlterRolePasswordSql }],
["starrocks", starrocksUserAdminProvider], ["starrocks", starrocksUserAdminProvider],
]); ]);
@@ -0,0 +1,272 @@
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ConnectionConfig } from "@/types/database";
const api = vi.hoisted(() => ({
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<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
describe("connectionStore password retirement", () => {
beforeEach(() => {
const data = new Map<string, string>();
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<void>((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<void>();
const oldSaveEntered = deferred<void>();
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<string>();
const metadataEntered = deferred<void>();
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<void>((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);
});
});
+43 -13
View File
@@ -683,6 +683,7 @@ export const useConnectionStore = defineStore("connection", () => {
const connectInFlight = new Map<string, Promise<void>>(); const connectInFlight = new Map<string, Promise<void>>();
const disconnectInFlight = new Map<string, Promise<void>>(); const disconnectInFlight = new Map<string, Promise<void>>();
const disconnectInFlightScoped = new Map<string, boolean>(); const disconnectInFlightScoped = new Map<string, boolean>();
const passwordChangeReconnectRequired = new Map<string, "retiring" | "ready">();
const cancelDisconnectInFlight = new Map<string, Promise<void>>(); const cancelDisconnectInFlight = new Map<string, Promise<void>>();
const activeLocalConnectionAttempts = new Map<string, number>(); const activeLocalConnectionAttempts = new Map<string, number>();
const cancelledLocalConnectionAttempts = new Map<string, Set<number>>(); const cancelledLocalConnectionAttempts = new Map<string, Set<number>>();
@@ -4536,15 +4537,16 @@ export const useConnectionStore = defineStore("connection", () => {
} }
} }
async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise<void> { async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string, localAttempt: number): Promise<void> {
if (!rememberPassword) return; if (!rememberPassword || !isCurrentLocalConnectionAttempt(config.id, localAttempt)) return;
const index = connections.value.findIndex((connection) => connection.id === config.id); const index = connections.value.findIndex((connection) => connection.id === config.id);
if (index < 0) return; if (index < 0) return;
if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) return; if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) return;
const nextConnections = [...connections.value]; const nextConnections = [...connections.value];
nextConnections[index] = { ...nextConnections[index], password: config.password, save_password: true }; nextConnections[index] = { ...nextConnections[index], password: config.password, save_password: true };
await persistConnections(nextConnections); 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(); await persistConnections();
return; return;
} }
@@ -4569,12 +4571,19 @@ export const useConnectionStore = defineStore("connection", () => {
async function connect(config: ConnectionConfig) { async function connect(config: ConnectionConfig) {
config = normalizeConnection(config); 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); const expectedConfigFingerprint = connectionConfigFingerprint(getConfig(config.id) ?? config);
if (getBlockingDisconnectInFlight(config.id)) await waitForBlockingDisconnectInFlight(config.id); 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); const localAttempt = beginLocalConnectionAttempt(config.id);
try { try {
let rememberPassword = false; 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); const prompted = await ensureConnectionPassword(config);
config = prompted.config; config = prompted.config;
rememberPassword = prompted.rememberPassword; rememberPassword = prompted.rememberPassword;
@@ -4591,11 +4600,13 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id); await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
await syncMongoLegacyDriverFallback(id, config); await syncMongoLegacyDriverFallback(id, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id); await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
passwordChangeReconnectRequired.delete(config.id);
activeConnectionId.value = id; activeConnectionId.value = id;
connectedIds.value.add(id); connectedIds.value.add(id);
if (config.db_type !== "plugin") { if (config.db_type !== "plugin") {
void refreshConnectedDatabaseInfo(id, { ...config, id }); void refreshConnectedDatabaseInfo(id, { ...config, id });
await refreshConnectionIdentifierQuote(id, { ...config, id }); await refreshConnectionIdentifierQuote(id, { ...config, id });
ensureLocalConnectionAttemptActive(config.id, localAttempt);
// Compatibility modes warm asynchronously; the QueryEditor watcher and the // Compatibility modes warm asynchronously; the QueryEditor watcher and the
// backend's own A-mode/EXISTS validation make a cold map safe. // backend's own A-mode/EXISTS validation make a cold map safe.
void refreshConnectionDatabaseModes(id, { ...config, id }); void refreshConnectionDatabaseModes(id, { ...config, id });
@@ -4627,18 +4638,18 @@ export const useConnectionStore = defineStore("connection", () => {
}); });
} }
try { try {
await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint); await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt);
} catch (error) { } 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; return id;
} catch (e) { } catch (e) {
if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) { if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) {
clearConnectionError(config.id);
throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE); throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
} }
if (isCancelledConnectionAttempt(e) || isSupersededConnectionAttempt(e)) { if (isCancelledConnectionAttempt(e) || isSupersededConnectionAttempt(e)) {
clearConnectionError(config.id); if (isCurrentLocalConnectionAttempt(config.id, localAttempt)) clearConnectionError(config.id);
} else { } else {
recordConnectionError(config.id, e); recordConnectionError(config.id, e);
} }
@@ -4824,6 +4835,21 @@ export const useConnectionStore = defineStore("connection", () => {
await api.forgetSessionCredential(connectionId); 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) { async function closeDatabaseConnection(connectionId: string, database: string) {
if (hasSqlServerActivityTraceForConnection(connectionId, database)) await disposeSqlServerActivityTracesForConnection(connectionId, database); if (hasSqlServerActivityTraceForConnection(connectionId, database)) await disposeSqlServerActivityTracesForConnection(connectionId, database);
cancelObjectDdlLoadsForDatabase(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 } = {}) { 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)) { if (!options.forceReconnect && connectedIds.value.has(connectionId)) {
// Pure navigation can safely trust the existing connected state. Its // Pure navigation can safely trust the existing connected state. Its
// destination will perform the real API request, while blocking here on // destination will perform the real API request, while blocking here on
@@ -4906,6 +4933,7 @@ export const useConnectionStore = defineStore("connection", () => {
} }
const expectedConfigFingerprint = connectionConfigFingerprint(config); const expectedConfigFingerprint = connectionConfigFingerprint(config);
if (getBlockingDisconnectInFlight(connectionId)) await waitForBlockingDisconnectInFlight(connectionId); if (getBlockingDisconnectInFlight(connectionId)) await waitForBlockingDisconnectInFlight(connectionId);
if (passwordChangeReconnectRequired.has(connectionId)) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect"));
const existingConnect = connectInFlight.get(connectionId); const existingConnect = connectInFlight.get(connectionId);
if (existingConnect) { if (existingConnect) {
await existingConnect; await existingConnect;
@@ -4940,32 +4968,33 @@ export const useConnectionStore = defineStore("connection", () => {
if (config.db_type !== "plugin") { if (config.db_type !== "plugin") {
void refreshConnectedDatabaseInfo(connectionId, config); void refreshConnectedDatabaseInfo(connectionId, config);
await refreshConnectionIdentifierQuote(connectionId, config); await refreshConnectionIdentifierQuote(connectionId, config);
ensureLocalConnectionAttemptActive(connectionId, localAttempt);
void refreshConnectionDatabaseModes(connectionId, config); void refreshConnectionDatabaseModes(connectionId, config);
} }
markSuccessfulLocalConnectionAttempt(connectionId, localAttempt); markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);
markConnectionHealthChecked(connectionId); markConnectionHealthChecked(connectionId);
clearConnectionError(connectionId); clearConnectionError(connectionId);
try { try {
await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint); await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt);
} catch (error) { } 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); connectInFlight.set(connectionId, connectPromise);
try { try {
await connectPromise; await connectPromise;
ensureLocalConnectionAttemptActive(connectionId, localAttempt);
if (options.activate !== false) activeConnectionId.value = connectionId; if (options.activate !== false) activeConnectionId.value = connectionId;
} catch (e) { } catch (e) {
if (isCancelledLocalConnectionAttempt(connectionId, localAttempt)) { if (isCancelledLocalConnectionAttempt(connectionId, localAttempt)) {
clearConnectionError(connectionId);
throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE); throw new Error(CONNECTION_ATTEMPT_CANCELLED_MESSAGE);
} }
if (isCancelledConnectionAttempt(e)) { if (isCancelledConnectionAttempt(e)) {
clearConnectionError(connectionId); if (isCurrentLocalConnectionAttempt(connectionId, localAttempt)) clearConnectionError(connectionId);
throw e; throw e;
} }
if (isSupersededConnectionAttempt(e) && connectedIds.value.has(connectionId)) { if (isSupersededConnectionAttempt(e) && connectedIds.value.has(connectionId)) {
clearConnectionError(connectionId);
return; return;
} }
// 后台搜索触发的重连失败只留一行提示,避免把完整驱动错误(如旧版 SQL Server 的 TLS 提示) // 后台搜索触发的重连失败只留一行提示,避免把完整驱动错误(如旧版 SQL Server 的 TLS 提示)
@@ -10271,6 +10300,7 @@ export const useConnectionStore = defineStore("connection", () => {
handleConnectionLivenessMessage, handleConnectionLivenessMessage,
metadataGenerationFor, metadataGenerationFor,
disconnectAndForgetConnectionPassword, disconnectAndForgetConnectionPassword,
retirePasswordAfterChange,
hasSessionCredential, hasSessionCredential,
closeDatabaseConnection, closeDatabaseConnection,
ensureConnected, ensureConnected,