fix(vastbase): support old passwords and retire stale connections
Closes #8481
This commit is contained in:
1 parent
f75f5eb159
commit
92da1bcbee
19 files changed
+730
-32
No files matched your search
+212
-3
@@ -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<void> | 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<unknown> }) => {
|
||||
executeWithProductionSqlGuard: async (options: { execute: () => Promise<unknown> }) => {
|
||||
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<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", () => {
|
||||
it("syncs the grant option from loaded SHOW GRANTS rows and renders the database scope editor", async () => {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
|
||||
+24
@@ -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", () => {
|
||||
const availablePrivileges = ["SELECT", "INSERT", "UPDATE", "EXECUTE"];
|
||||
|
||||
|
||||
@@ -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<DatabaseType, DatabaseUserA
|
||||
["kwdb", postgresCompatibleUserAdminProvider],
|
||||
["opengauss", postgresCompatibleUserAdminProvider],
|
||||
["questdb", postgresCompatibleUserAdminProvider],
|
||||
["vastbase", postgresCompatibleUserAdminProvider],
|
||||
["vastbase", { ...postgresCompatibleUserAdminProvider, supportsOldPassword: true, alterPasswordSql: vastbaseAlterRolePasswordSql }],
|
||||
["starrocks", starrocksUserAdminProvider],
|
||||
]);
|
||||
|
||||
|
||||
Reference in new issue
Block a user