feat(users): visual database and table level grants for MySQL
This commit is contained in:
15 files changed
+643
-271
No files matched your search
+76
-11
@@ -42,7 +42,7 @@ function modelDialog(): Component {
|
||||
return defineComponent({
|
||||
inheritAttrs: false,
|
||||
setup(_, { attrs, slots }) {
|
||||
return () => (attrs.open ? h("div", attrs, slots.default?.()) : null);
|
||||
return () => (attrs.open ? h("div", { ...attrs, "data-test-dialog": "true" }, slots.default?.()) : null);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -163,7 +163,7 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("DatabaseUserAdmin MySQL grant loading", () => {
|
||||
it("syncs privilege buttons and grant option from loaded SHOW GRANTS rows", async () => {
|
||||
it("syncs the grant option from loaded SHOW GRANTS rows and renders the database scope editor", async () => {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
mocks.executeQuery.mockResolvedValueOnce({ columns: ["user", "host", "plugin"], rows: [["root", "%", "mysql_native_password"]] }).mockResolvedValueOnce({ columns: ["Grants for root@%"], rows: [["GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION"]] });
|
||||
|
||||
@@ -175,12 +175,12 @@ describe("DatabaseUserAdmin MySQL grant loading", () => {
|
||||
await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(2));
|
||||
await nextTick();
|
||||
|
||||
const privilegeButton = Array.from(root.querySelectorAll("button")).find((button) => button.textContent?.trim() === "INSERT");
|
||||
const grantOptionLabel = Array.from(root.querySelectorAll("label")).find((label) => label.textContent?.includes("userAdmin.grantOption"));
|
||||
const grantOptionInput = grantOptionLabel?.querySelector<HTMLInputElement>('input[type="checkbox"]');
|
||||
|
||||
expect(privilegeButton?.className).toContain("border-primary");
|
||||
expect(grantOptionInput?.checked).toBe(true);
|
||||
// MySQL 的权限编辑改为按数据库/表配置授权范围(与新增用户一致),固定的权限按钮由范围编辑器取代
|
||||
expect(root.querySelector('input[placeholder="userAdmin.searchDatabase"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the current Doris user when SHOW ALL GRANTS requires GRANT_PRIV", async () => {
|
||||
@@ -219,6 +219,12 @@ function findButton(text: string): HTMLButtonElement | undefined {
|
||||
return Array.from(root?.querySelectorAll("button") ?? []).find((button) => button.textContent?.trim() === text);
|
||||
}
|
||||
|
||||
// 权限编辑面板与新增用户弹窗复用同一个授权范围编辑器,断言弹窗内的控件时需要限定在弹窗范围内
|
||||
function findDialogButton(text: string): HTMLButtonElement | undefined {
|
||||
const dialog = root?.querySelector('[data-test-dialog="true"]');
|
||||
return Array.from(dialog?.querySelectorAll("button") ?? []).find((button) => button.textContent?.trim() === text);
|
||||
}
|
||||
|
||||
describe("DatabaseUserAdmin MySQL create-user table grants", () => {
|
||||
it("loads tables, requires a selection, and previews only the selected table grant", async () => {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
@@ -237,22 +243,22 @@ describe("DatabaseUserAdmin MySQL create-user table grants", () => {
|
||||
|
||||
findButton("userAdmin.newUser")?.click();
|
||||
await vi.waitFor(() => expect(mocks.listDatabases).toHaveBeenCalledWith("native-mysql"));
|
||||
await nextTick();
|
||||
findButton("scope_test")?.click();
|
||||
await vi.waitFor(() => expect(findDialogButton("scope_test")).toBeDefined());
|
||||
findDialogButton("scope_test")?.click();
|
||||
const password = root.querySelector<HTMLInputElement>('[data-password-input="true"]');
|
||||
password!.value = "test-password";
|
||||
password!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await nextTick();
|
||||
|
||||
findButton("userAdmin.specificTables")?.click();
|
||||
findDialogButton("userAdmin.specificTables")?.click();
|
||||
await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledWith("native-mysql", "scope_test", ""));
|
||||
await nextTick();
|
||||
expect(findButton("userAdmin.previewSql")?.disabled).toBe(true);
|
||||
expect(findDialogButton("userAdmin.previewSql")?.disabled).toBe(true);
|
||||
|
||||
findButton("allowed_table")?.click();
|
||||
findDialogButton("allowed_table")?.click();
|
||||
await nextTick();
|
||||
expect(findButton("userAdmin.previewSql")?.disabled).toBe(false);
|
||||
findButton("userAdmin.previewSql")?.click();
|
||||
expect(findDialogButton("userAdmin.previewSql")?.disabled).toBe(false);
|
||||
findDialogButton("userAdmin.previewSql")?.click();
|
||||
|
||||
await vi.waitFor(() => expect(root?.textContent).toContain("GRANT SELECT, SHOW VIEW ON `scope_test`.`allowed_table` TO 'app_user'@'%';"));
|
||||
expect(root.textContent).not.toContain("ON `scope_test`.*");
|
||||
@@ -260,6 +266,65 @@ describe("DatabaseUserAdmin MySQL create-user table grants", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("DatabaseUserAdmin MySQL privilege editing", () => {
|
||||
it("previews one grant per selected table for the selected user", async () => {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
mocks.executeQuery.mockResolvedValueOnce({ columns: ["user", "host", "plugin"], rows: [["root", "%", "caching_sha2_password"]] }).mockResolvedValueOnce({ columns: ["Grants"], rows: [["GRANT SELECT ON *.* TO 'root'@'%'"]] });
|
||||
mocks.listDatabases.mockResolvedValue([{ name: "scope_test" }]);
|
||||
mocks.listTables.mockResolvedValue([
|
||||
{ name: "allowed_table", table_type: "BASE TABLE" },
|
||||
{ name: "blocked_table", table_type: "BASE TABLE" },
|
||||
]);
|
||||
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
app = createApp(DatabaseUserAdmin, { connection: nativeMysqlConnection });
|
||||
app.mount(root);
|
||||
await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(2));
|
||||
await vi.waitFor(() => expect(findButton("scope_test")).toBeDefined());
|
||||
|
||||
findButton("scope_test")?.click();
|
||||
await nextTick();
|
||||
findButton("userAdmin.specificTables")?.click();
|
||||
await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledWith("native-mysql", "scope_test", ""));
|
||||
await nextTick();
|
||||
|
||||
findButton("allowed_table")?.click();
|
||||
findButton("blocked_table")?.click();
|
||||
await nextTick();
|
||||
findButton("userAdmin.grant")?.click();
|
||||
|
||||
await vi.waitFor(() => expect(root?.textContent).toContain("GRANT SELECT, SHOW VIEW ON `scope_test`.`allowed_table` TO 'root'@'%';"));
|
||||
expect(root?.textContent).toContain("GRANT SELECT, SHOW VIEW ON `scope_test`.`blocked_table` TO 'root'@'%';");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DatabaseUserAdmin MySQL global scope", () => {
|
||||
it("grants the global scope through the fixed entry and hides table scope", async () => {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
mocks.executeQuery.mockResolvedValueOnce({ columns: ["user", "host", "plugin"], rows: [["root", "%", "caching_sha2_password"]] }).mockResolvedValueOnce({ columns: ["Grants"], rows: [["GRANT SELECT ON *.* TO 'root'@'%'"]] });
|
||||
mocks.listDatabases.mockResolvedValue([{ name: "scope_test" }]);
|
||||
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
app = createApp(DatabaseUserAdmin, { connection: nativeMysqlConnection });
|
||||
app.mount(root);
|
||||
await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalledTimes(2));
|
||||
await vi.waitFor(() => expect(findButton("userAdmin.globalScope")).toBeDefined());
|
||||
|
||||
findButton("userAdmin.globalScope")?.click();
|
||||
await nextTick();
|
||||
|
||||
// 全局作用域没有表级粒度,不应出现表范围控件
|
||||
expect(findButton("userAdmin.specificTables")).toBeUndefined();
|
||||
|
||||
findButton("userAdmin.grant")?.click();
|
||||
|
||||
await vi.waitFor(() => expect(root?.textContent).toContain("GRANT SELECT, SHOW VIEW ON *.* TO 'root'@'%';"));
|
||||
expect(root?.textContent).not.toContain("ON `scope_test`.*");
|
||||
});
|
||||
});
|
||||
|
||||
async function mountNativeMysqlUserAdmin() {
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
mocks.executeQuery.mockResolvedValueOnce({ columns: ["user", "host", "plugin"], rows: [["same-user", "old-host", "caching_sha2_password"]] }).mockResolvedValueOnce({ columns: ["Grants"], rows: [["GRANT SELECT ON *.* TO 'same-user'@'old-host'"]] });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mysqlUserAdminProvider, postgresUserAdminProvider } from "@/lib/database/databaseUserAdmin";
|
||||
import { authorizationPlanSql, buildCreateDatabaseAuthorizationPlan, buildCreateUserAuthorizationPlan, executeAuthorizationPlan } from "@/lib/database/databaseAuthorizationPlan";
|
||||
import { dorisUserAdminProvider, mysqlUserAdminProvider, postgresUserAdminProvider, starrocksUserAdminProvider } from "@/lib/database/databaseUserAdmin";
|
||||
import { authorizationPlanSql, buildCreateDatabaseAuthorizationPlan, buildCreateUserAuthorizationPlan, buildGrantAuthorizationPlan, executeAuthorizationPlan } from "@/lib/database/databaseAuthorizationPlan";
|
||||
|
||||
describe("database authorization plans", () => {
|
||||
it("grants PostgreSQL presets across user schemas and future objects", () => {
|
||||
@@ -184,4 +184,55 @@ describe("database authorization plans", () => {
|
||||
|
||||
expect(results.map((result) => result.status)).toEqual(["failed", "skipped"]);
|
||||
});
|
||||
|
||||
it("expands an existing user's privilege change into one statement per selected table", () => {
|
||||
const plan = buildGrantAuthorizationPlan({
|
||||
provider: mysqlUserAdminProvider,
|
||||
user: { user: "app_user", host: "%" },
|
||||
databases: [{ database: "app_db", preset: "readOnly", tables: ["orders", "audit_log"] }],
|
||||
grantOption: true,
|
||||
});
|
||||
const sql = authorizationPlanSql(plan);
|
||||
|
||||
expect(plan.steps).toHaveLength(2);
|
||||
expect(plan.steps.map((step) => step.operation)).toEqual(["grantDatabase", "grantDatabase"]);
|
||||
expect(plan.steps.map((step) => step.targetTable)).toEqual(["orders", "audit_log"]);
|
||||
expect(sql).toContain("GRANT SELECT, SHOW VIEW ON `app_db`.`orders` TO 'app_user'@'%' WITH GRANT OPTION;");
|
||||
expect(sql).toContain("GRANT SELECT, SHOW VIEW ON `app_db`.`audit_log` TO 'app_user'@'%' WITH GRANT OPTION;");
|
||||
expect(sql).not.toContain("CREATE ROUTINE");
|
||||
});
|
||||
|
||||
it("keeps the global scope as *.* for grant and revoke", () => {
|
||||
const selected = [{ database: "*", preset: "readOnly" as const }];
|
||||
const grant = buildGrantAuthorizationPlan({ provider: mysqlUserAdminProvider, user: { user: "local_admin", host: "%" }, databases: selected });
|
||||
const revoke = buildGrantAuthorizationPlan({ provider: mysqlUserAdminProvider, user: { user: "local_admin", host: "%" }, databases: selected, revoke: true });
|
||||
|
||||
expect(authorizationPlanSql(grant)).toContain("GRANT SELECT, SHOW VIEW ON *.* TO 'local_admin'@'%';");
|
||||
expect(authorizationPlanSql(revoke)).toContain("REVOKE SELECT, SHOW VIEW ON *.* FROM 'local_admin'@'%';");
|
||||
});
|
||||
|
||||
it("builds REVOKE steps without grant options", () => {
|
||||
const plan = buildGrantAuthorizationPlan({
|
||||
provider: mysqlUserAdminProvider,
|
||||
user: { user: "app_user", host: "%" },
|
||||
databases: [{ database: "app_db", preset: "readWrite", tables: ["orders"] }],
|
||||
grantOption: true,
|
||||
revoke: true,
|
||||
});
|
||||
|
||||
expect(plan.steps.map((step) => step.operation)).toEqual(["revokePrivileges"]);
|
||||
expect(plan.steps[0].targetTable).toBe("orders");
|
||||
expect(authorizationPlanSql(plan)).toBe("-- revoke app_user@% app_db.orders (connection scope)\nREVOKE SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, REFERENCES, SHOW VIEW, CREATE VIEW, TRIGGER ON `app_db`.`orders` FROM 'app_user'@'%';");
|
||||
expect(authorizationPlanSql(plan)).not.toContain("GRANT OPTION");
|
||||
});
|
||||
|
||||
it("leaves Doris and StarRocks to their own privilege names", () => {
|
||||
for (const provider of [dorisUserAdminProvider, starrocksUserAdminProvider]) {
|
||||
// 两者都能生成 GRANT SQL,但权限名与 MySQL 预设不同,因此不应由本计划构造语句
|
||||
expect(provider.grantPrivilegesSql).toBeTypeOf("function");
|
||||
const plan = buildGrantAuthorizationPlan({ provider, user: { user: "app_user", host: "%" }, databases: [{ database: "app_db", preset: "readOnly" }] });
|
||||
|
||||
expect(plan.steps).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { mysqlUserAccount, quoteMySqlIdentifier, quotePostgresIdentifier, type C
|
||||
export type AuthorizationAccountType = "standard" | "admin";
|
||||
export type AuthorizationPreset = "readWrite" | "readOnly" | "ddl" | "dml" | "custom";
|
||||
export type AuthorizationTargetScope = "database" | "table";
|
||||
export type AuthorizationStepOperation = "createUser" | "grantAdmin" | "createDatabase" | "grantDatabase" | "grantCurrentObjects" | "grantFutureObjects";
|
||||
export type AuthorizationStepOperation = "createUser" | "grantAdmin" | "createDatabase" | "grantDatabase" | "revokePrivileges" | "grantCurrentObjects" | "grantFutureObjects";
|
||||
export type AuthorizationObjectScope = "schemas" | "tables" | "sequences" | "functions";
|
||||
|
||||
export interface DatabaseAuthorizationSelection {
|
||||
@@ -149,6 +149,57 @@ export function buildCreateUserAuthorizationPlan(input: CreateUserAuthorizationP
|
||||
return { steps };
|
||||
}
|
||||
|
||||
export interface GrantAuthorizationPlanInput {
|
||||
provider: DatabaseUserAdminProvider;
|
||||
/** 目标用户身份 */
|
||||
user: DatabaseUserIdentity;
|
||||
/** 需要授权(或撤权)的库/表选择 */
|
||||
databases: DatabaseAuthorizationSelection[];
|
||||
/** 是否携带 WITH GRANT OPTION,仅对授权语句生效 */
|
||||
grantOption?: boolean;
|
||||
/** 为 true 时生成 REVOKE,默认生成 GRANT */
|
||||
revoke?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为“已存在的用户”构造授权计划:把多库/多表选择展开为多条独立的 GRANT / REVOKE。
|
||||
* 与 buildCreateUserAuthorizationPlan 的差异:
|
||||
* 1. 不包含创建用户步骤,因此各步骤之间没有依赖关系;
|
||||
* 2. 采用追加式语义,只对勾选的库/表生成语句,不做差异比对,也不会回收用户已有的多余权限;
|
||||
* 3. 目前仅用于 MySQL 表级/库级授权,其它方言返回空计划,由调用方沿用原有的单条 SQL 逻辑。
|
||||
*/
|
||||
export function buildGrantAuthorizationPlan(input: GrantAuthorizationPlanInput): AuthorizationPlan {
|
||||
const changePrivilegesSql = input.revoke ? input.provider.revokePrivilegesSql : input.provider.grantPrivilegesSql;
|
||||
if (!changePrivilegesSql) return { steps: [] };
|
||||
// 以 provider 的库/表级授权能力作为判据:Doris / StarRocks 的 dialect 同为 "mysql",
|
||||
// 但它们的权限名与 MySQL 预设不同(SELECT_PRIV 等),仅比较 dialect 会生成无效语句。
|
||||
if (!input.provider.supportsTableGrantsOnCreate) return { steps: [] };
|
||||
const steps: AuthorizationPlanStep[] = [];
|
||||
for (const selection of input.databases) {
|
||||
const database = selection.database.trim();
|
||||
if (!database) continue;
|
||||
// 指定了表则按表级生效,否则作用于该库下的全部表
|
||||
const targetScope = input.provider.supportsTableGrantsOnCreate && selection.tables !== undefined ? "table" : "database";
|
||||
const privileges = authorizationPresetPrivileges(input.provider, selection.preset, selection.privileges, targetScope);
|
||||
if (privileges.length === 0) continue;
|
||||
const tables = targetScope === "database" ? ["*"] : uniqueNames(selection.tables ?? []);
|
||||
for (const table of tables) {
|
||||
const targetTable = table === "*" ? undefined : table;
|
||||
steps.push({
|
||||
id: `change-${steps.length}`,
|
||||
label: `${input.revoke ? "revoke" : "grant"} ${input.provider.label(input.user)} ${targetTable ? `${database}.${targetTable}` : database}`,
|
||||
database: "",
|
||||
sql: changePrivilegesSql({ user: input.user, privileges, database, table, grantOption: input.grantOption, scope: "mysql" }),
|
||||
operation: input.revoke ? "revokePrivileges" : "grantDatabase",
|
||||
subject: input.provider.label(input.user),
|
||||
targetDatabase: database,
|
||||
targetTable,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { steps };
|
||||
}
|
||||
|
||||
export function buildCreateDatabaseAuthorizationPlan(input: CreateDatabaseAuthorizationPlanInput): AuthorizationPlan {
|
||||
const createStepId = "create-database";
|
||||
const steps: AuthorizationPlanStep[] = [
|
||||
|
||||
Reference in new issue
Block a user