feat(mysql): support table-scoped grants for new users

This commit is contained in:
zipg authored and GitHub committed 2026-08-18 14:50:48 +08:00
1 parent 2eee29c0bf
commit 61103523de
13 files changed
+407 -24

No files matched your search

@@ -10,6 +10,9 @@ const mocks = vi.hoisted(() => ({
executeMulti: vi.fn(),
productionGuard: vi.fn(),
toast: vi.fn(),
listDatabases: vi.fn(),
listTables: vi.fn(),
listSchemas: vi.fn(),
}));
function passthrough(tag: string): Component {
@@ -44,6 +47,21 @@ function modelDialog(): Component {
});
}
function passwordInput(): Component {
return defineComponent({
inheritAttrs: false,
setup(_, { attrs }) {
return () =>
h("input", {
...attrs,
"data-password-input": "true",
value: attrs.modelValue as string,
onInput: (event: Event) => (attrs["onUpdate:modelValue"] as ((value: string) => void) | undefined)?.((event.target as HTMLInputElement).value),
});
},
});
}
vi.mock("vue-i18n", () => ({
useI18n: () => ({
t: (key: string, values?: Record<string, unknown>) => (values?.message ? `${key}: ${values.message}` : key),
@@ -54,6 +72,7 @@ vi.mock("@lucide/vue", () => {
return {
AlertTriangle: Icon,
Check: Icon,
ChevronDown: Icon,
Globe2: Icon,
KeyRound: Icon,
Lock: Icon,
@@ -62,6 +81,7 @@ vi.mock("@lucide/vue", () => {
RefreshCcw: Icon,
Search: Icon,
ShieldCheck: Icon,
Table2: Icon,
Trash2: Icon,
Unlock: Icon,
UserRound: Icon,
@@ -77,7 +97,12 @@ vi.mock("@/components/ui/dialog", () => ({
DialogTitle: passthrough("div"),
}));
vi.mock("@/components/ui/input", () => ({ Input: modelInput() }));
vi.mock("@/components/ui/PasswordInput.vue", () => ({ default: passthrough("input") }));
vi.mock("@/components/ui/PasswordInput.vue", () => ({ default: passwordInput() }));
vi.mock("@/components/ui/popover", () => ({
Popover: passthrough("div"),
PopoverContent: passthrough("div"),
PopoverTrigger: passthrough("div"),
}));
vi.mock("@/components/ui/select", () => ({
Select: passthrough("div"),
SelectContent: passthrough("div"),
@@ -93,8 +118,9 @@ vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({
vi.mock("@/lib/backend/api", () => ({
executeQuery: mocks.executeQuery,
executeMulti: mocks.executeMulti,
listDatabases: vi.fn(),
listSchemas: vi.fn(),
listDatabases: mocks.listDatabases,
listTables: mocks.listTables,
listSchemas: mocks.listSchemas,
}));
vi.mock("@/lib/database/productionExecutionGuard", () => ({
executeWithProductionSqlGuard: (options: { execute: () => Promise<unknown> }) => {
@@ -193,6 +219,47 @@ function findButton(text: string): HTMLButtonElement | undefined {
return Array.from(root?.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);
mocks.executeQuery.mockResolvedValueOnce({ columns: ["user", "host", "plugin"], rows: [["root", "%", "caching_sha2_password"]] }).mockResolvedValueOnce({ columns: ["Grants"], rows: [["GRANT ALL PRIVILEGES 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));
findButton("userAdmin.newUser")?.click();
await vi.waitFor(() => expect(mocks.listDatabases).toHaveBeenCalledWith("native-mysql"));
await nextTick();
findButton("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();
await vi.waitFor(() => expect(mocks.listTables).toHaveBeenCalledWith("native-mysql", "scope_test", ""));
await nextTick();
expect(findButton("userAdmin.previewSql")?.disabled).toBe(true);
findButton("allowed_table")?.click();
await nextTick();
expect(findButton("userAdmin.previewSql")?.disabled).toBe(false);
findButton("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`.*");
expect(root.textContent).not.toContain("`blocked_table`");
});
});
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'"]] });
@@ -121,6 +121,37 @@ describe("database authorization plans", () => {
expect(grant).toMatchObject({ subject: "app@2001:db8::1", targetDatabase: "db:prod" });
});
it("grants only selected MySQL tables and filters database-only privileges", () => {
const plan = buildCreateUserAuthorizationPlan({
provider: mysqlUserAdminProvider,
principal: { user: "table_reader", host: "%", password: "secret" },
accountType: "standard",
databases: [{ database: "app_db", preset: "readWrite", tables: ["orders", "audit`log", "orders"] }],
});
const sql = authorizationPlanSql(plan);
const grants = plan.steps.filter((step) => step.operation === "grantDatabase");
expect(grants).toHaveLength(2);
expect(grants.map((step) => step.targetTable)).toEqual(["orders", "audit`log"]);
expect(sql).toContain("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, REFERENCES, SHOW VIEW, CREATE VIEW, TRIGGER ON `app_db`.`orders` TO 'table_reader'@'%';");
expect(sql).toContain("ON `app_db`.`audit``log`");
expect(sql).not.toContain("ON `app_db`.*");
expect(sql).not.toContain("EVENT");
expect(sql).not.toContain("CREATE ROUTINE");
expect(sql).not.toContain("LOCK TABLES");
});
it("keeps database-wide MySQL grants as the default", () => {
const plan = buildCreateUserAuthorizationPlan({
provider: mysqlUserAdminProvider,
principal: { user: "db_reader", host: "%", password: "secret" },
accountType: "standard",
databases: [{ database: "app_db", preset: "readOnly" }],
});
expect(authorizationPlanSql(plan)).toContain("GRANT SELECT, SHOW VIEW ON `app_db`.* TO 'db_reader'@'%';");
});
it("reports PostgreSQL object grants independently", async () => {
const plan = buildCreateDatabaseAuthorizationPlan({
provider: postgresUserAdminProvider,
@@ -3,6 +3,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 AuthorizationObjectScope = "schemas" | "tables" | "sequences" | "functions";
@@ -11,6 +12,7 @@ export interface DatabaseAuthorizationSelection {
preset: AuthorizationPreset;
privileges?: string[];
schemas?: string[];
tables?: string[];
}
export interface AuthorizationPlanStep {
@@ -22,6 +24,7 @@ export interface AuthorizationPlanStep {
operation: AuthorizationStepOperation;
subject?: string;
targetDatabase?: string;
targetTable?: string;
objectScope?: AuthorizationObjectScope;
schema?: string;
owner?: string;
@@ -60,6 +63,8 @@ const MYSQL_PRESETS: Record<Exclude<AuthorizationPreset, "custom">, string[]> =
readWrite: ["SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER", "INDEX", "REFERENCES", "EXECUTE", "SHOW VIEW", "CREATE VIEW", "CREATE ROUTINE", "ALTER ROUTINE", "TRIGGER", "EVENT", "CREATE TEMPORARY TABLES", "LOCK TABLES"],
};
const MYSQL_TABLE_PRIVILEGES = new Set(["SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER", "INDEX", "REFERENCES", "SHOW VIEW", "CREATE VIEW", "TRIGGER"]);
const POSTGRES_PRESETS: Record<Exclude<AuthorizationPreset, "custom">, string[]> = {
readOnly: ["SELECT"],
dml: ["SELECT", "INSERT", "UPDATE", "DELETE"],
@@ -67,15 +72,18 @@ const POSTGRES_PRESETS: Record<Exclude<AuthorizationPreset, "custom">, string[]>
readWrite: ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", "EXECUTE", "CREATE", "TEMPORARY"],
};
export function authorizationPresetPrivileges(provider: DatabaseUserAdminProvider, preset: AuthorizationPreset, custom: string[] = []): string[] {
if (preset === "custom") return uniquePrivileges(custom);
return [...(provider.dialect === "mysql" ? MYSQL_PRESETS[preset] : POSTGRES_PRESETS[preset])];
export function authorizationPresetPrivileges(provider: DatabaseUserAdminProvider, preset: AuthorizationPreset, custom: string[] = [], targetScope: AuthorizationTargetScope = "database"): string[] {
const privileges = preset === "custom" ? uniquePrivileges(custom) : [...(provider.dialect === "mysql" ? MYSQL_PRESETS[preset] : POSTGRES_PRESETS[preset])];
return provider.dialect === "mysql" && targetScope === "table" ? privileges.filter((privilege) => MYSQL_TABLE_PRIVILEGES.has(privilege)) : privileges;
}
export function authorizationPrivileges(provider: DatabaseUserAdminProvider): string[] {
export function authorizationPrivileges(provider: DatabaseUserAdminProvider, targetScope: AuthorizationTargetScope = "database"): string[] {
const privilegesForScope = provider.privilegesForScope;
if (!privilegesForScope) return [];
if (provider.dialect === "mysql") return Array.from(privilegesForScope("mysql"));
if (provider.dialect === "mysql") {
const privileges = Array.from(privilegesForScope("mysql"));
return targetScope === "table" ? privileges.filter((privilege) => MYSQL_TABLE_PRIVILEGES.has(privilege)) : privileges;
}
return uniquePrivileges([...privilegesForScope("database"), ...privilegesForScope("schema"), ...privilegesForScope("table"), "EXECUTE", "USAGE", "UPDATE"]);
}
@@ -116,20 +124,26 @@ export function buildCreateUserAuthorizationPlan(input: CreateUserAuthorizationP
for (const selection of input.databases) {
const database = selection.database.trim();
if (!database) continue;
const privileges = authorizationPresetPrivileges(input.provider, selection.preset, selection.privileges);
if (input.provider.dialect === "mysql") {
steps.push({
id: `grant-${steps.length}`,
label: `grant ${input.provider.label(identity)} access to ${database}`,
database: "",
sql: input.provider.grantPrivilegesSql({ user: identity, privileges, database, table: "*", scope: "mysql" }),
dependsOn: [createStepId],
operation: "grantDatabase",
subject: input.provider.label(identity),
targetDatabase: database,
});
const targetScope = input.provider.supportsTableGrantsOnCreate && selection.tables !== undefined ? "table" : "database";
const privileges = authorizationPresetPrivileges(input.provider, selection.preset, selection.privileges, targetScope);
const tables = targetScope === "database" ? ["*"] : uniqueNames(selection.tables ?? []);
for (const table of tables) {
steps.push({
id: `grant-${steps.length}`,
label: `grant ${input.provider.label(identity)} access to ${table === "*" ? database : `${database}.${table}`}`,
database: "",
sql: input.provider.grantPrivilegesSql({ user: identity, privileges, database, table, scope: "mysql" }),
dependsOn: [createStepId],
operation: "grantDatabase",
subject: input.provider.label(identity),
targetDatabase: database,
targetTable: table === "*" ? undefined : table,
});
}
continue;
}
const privileges = authorizationPresetPrivileges(input.provider, selection.preset, selection.privileges);
steps.push(...postgresDatabaseAuthorizationSteps(identity, database, privileges, selection.schemas ?? ["public"], createStepId, steps.length));
}
return { steps };
@@ -418,6 +432,10 @@ function uniquePrivileges(privileges: string[]): string[] {
return Array.from(new Set(privileges.map((privilege) => privilege.trim().toUpperCase()).filter(Boolean)));
}
function uniqueNames(names: string[]): string[] {
return Array.from(new Set(names.map((name) => name.trim()).filter(Boolean)));
}
function queryResultMessage(result: QueryResult): string {
return String(result.rows[0]?.[0] ?? "Execution failed");
}
@@ -41,6 +41,7 @@ export interface PrivilegeSelection {
export interface DatabaseUserAdminProvider {
dialect: UserAdminDialect;
defaultScope: PrivilegeScope;
supportsTableGrantsOnCreate?: boolean;
listUsersSql(): string;
fallbackListUsersSql?: () => string;
parseUsers(result: QueryResult): DatabaseUserIdentity[];
@@ -689,6 +690,7 @@ function postgresRoleBypassRlsSql(alias: string): string {
export const mysqlUserAdminProvider: DatabaseUserAdminProvider = {
dialect: "mysql",
defaultScope: "mysql",
supportsTableGrantsOnCreate: true,
listUsersSql: mysqlListUsersSql,
fallbackListUsersSql: mysqlListUsersFallbackSql,
parseUsers: usersFromMySqlUserResult,