Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: admin mode aduit (#20915)
ecmadao875e2e8fd2ba
diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.goindex 469cf72e11..827759d14c 100644--- a/backend/api/v1/acl.go+++ b/backend/api/v1/acl.go@@ -78,11 +78,10 @@ type aclStreamingConn struct {}func (c *aclStreamingConn) Receive(msg any) error {- err := c.interceptor.doACLCheck(c.ctx, msg, c.fullMethod)- if err != nil {+ if err := c.StreamingHandlerConn.Receive(msg); err != nil {return err}- return c.StreamingHandlerConn.Receive(msg)+ return c.interceptor.doACLCheck(c.ctx, msg, c.fullMethod)}// hasAllowMissingEnabled checks if the request has allow_missing field set to true.diff --git a/backend/tests/sql_service_audit_test.go b/backend/tests/sql_service_audit_test.gonew file mode 100644index 0000000000..86c26577f2--- /dev/null+++ b/backend/tests/sql_service_audit_test.go@@ -0,0 +1,56 @@+package tests++import (+ "context"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++func TestAdminExecuteAuditLog(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), "admin-execute-audit")+ a.NoError(err)+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("instance"),+ Instance: &v1pb.Instance{+ Title: "admin execute audit",+ Engine: v1pb.Engine_SQLITE,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: instanceDir, Id: "admin"}},+ },+ }))+ a.NoError(err)++ databaseName := "admin_execute_audit"+ a.NoError(ctl.createDatabase(ctx, ctl.project, instanceResp.Msg, nil, databaseName, ""))+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: instanceResp.Msg.Name + "/databases/" + databaseName,+ }))+ a.NoError(err)++ results, err := ctl.adminQuery(ctx, databaseResp.Msg, "SELECT 1")+ a.NoError(err)+ a.NotEmpty(results)++ logs, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{+ Parent: ctl.project.Name,+ Filter: `method == "/bytebase.v1.SQLService/AdminExecute"`,+ OrderBy: "create_time desc",+ }))+ a.NoError(err)+ a.NotEmpty(logs.Msg.AuditLogs, "AdminExecute must produce an audit entry")+ entry := logs.Msg.AuditLogs[0]+ a.Equal("/bytebase.v1.SQLService/AdminExecute", entry.Method)+ a.Equal(databaseResp.Msg.Name, entry.Resource)+}diff --git a/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.test.tsx b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.test.tsxnew file mode 100644index 0000000000..43e6029fc9--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.test.tsx@@ -0,0 +1,76 @@+import { act, render } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { SQLEditorTabMode } from "@/types/sqlEditor/tab";+import { PRESET_BY_ID } from "./presets";+import type { SQLEditorTheme } from "./types";+import { useMonacoThemeController } from "./useMonacoThemeController";++const mocks = vi.hoisted(() => ({+ mode: "WORKSHEET" as SQLEditorTabMode,+ setTheme: vi.fn(),+ workspaceTheme: undefined as SQLEditorTheme | undefined,+}));++vi.mock("@/react/components/monaco/core", () => ({+ getResolvedTheme: (theme: string) => `resolved:${theme}`,+ loadMonacoEditor: vi.fn(async () => ({+ editor: {+ setTheme: mocks.setTheme,+ },+ })),+}));++vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: <T,>(selector: (state: unknown) => T) =>+ selector({+ currentTabId: "tab",+ tabsById: new Map([["tab", { mode: mocks.mode }]]),+ }),+}));++vi.mock("./useWorkspaceSQLEditorTheme", () => ({+ useWorkspaceSQLEditorTheme: () => mocks.workspaceTheme,+}));++function Probe() {+ useMonacoThemeController();+ return null;+}++const flushEffects = async () => {+ await act(async () => {+ await Promise.resolve();+ });+};++describe("useMonacoThemeController", () => {+ beforeEach(() => {+ mocks.mode = "WORKSHEET";+ mocks.workspaceTheme = PRESET_BY_ID.light;+ mocks.setTheme.mockClear();+ });++ test("does not call global setTheme for admin-mode-only transitions", async () => {+ const { rerender } = render(<Probe />);+ await flushEffects();++ mocks.mode = "ADMIN";+ rerender(<Probe />);+ await flushEffects();++ expect(mocks.setTheme).not.toHaveBeenCalled();+ });++ test("applies global setTheme when the workspace theme changes", async () => {+ const { rerender } = render(<Probe />);+ await flushEffects();++ mocks.workspaceTheme = PRESET_BY_ID.dark;+ rerender(<Probe />);+ await flushEffects();++ expect(mocks.setTheme).toHaveBeenCalledWith(+ `resolved:${PRESET_BY_ID.dark.monacoBase}`+ );+ });+});diff --git a/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.ts b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.tsindex 9b173904d8..414a2fb574 100644--- a/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.ts+++ b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.ts@@ -3,33 +3,42 @@ import {getResolvedTheme,loadMonacoEditor,} from "@/react/components/monaco/core";-import { monacoThemeName } from "./derive";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";+import { monacoThemeName, resolveAdminTheme } from "./derive";import type { SQLEditorTheme } from "./types";-import { useActiveSQLEditorTheme } from "./useActiveSQLEditorTheme";+import { useWorkspaceSQLEditorTheme } from "./useWorkspaceSQLEditorTheme";/**- * Live-applies the active SQL Editor theme to Monaco's (global) theme when the- * user switches themes while editors are already mounted.+ * Live-applies the workspace SQL Editor theme to Monaco's (global) theme when+ * the user switches themes while editors are already mounted.** IMPORTANT: it must NOT call `monaco.editor.setTheme` on the initial mount.* Each SQL Editor Monaco instance already sets its own theme at construction via* its `options.theme`; calling the global `setTheme` *while an editor is still* constructing* races the codingame VSCode theme service and throws, which makes* the editor fall back to its read-only `<pre>`. So we only re-apply on a GENUINE- * theme change (prev exists and differs). This also makes the effect safe under- * React StrictMode's double-invoke — the replay runs with `prev === theme` and is- * skipped.+ * workspace-theme change (prev exists and differs). Mode-only flips (worksheet+ * ⇄ admin) remount their editor surface with the right construction theme, and+ * calling global `setTheme` during that swap would race the new editor.+ * This also makes the effect safe under React StrictMode's double-invoke — the+ * replay runs with `prev === theme` and is skipped.*/export function useMonacoThemeController() {- const theme = useActiveSQLEditorTheme();- const prevThemeRef = useRef<SQLEditorTheme | null>(null);+ const workspaceTheme = useWorkspaceSQLEditorTheme();+ const mode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const prevWorkspaceThemeRef = useRef<SQLEditorTheme | null>(null);useEffect(() => {- const prev = prevThemeRef.current;- prevThemeRef.current = theme;- // Initial mount (prev === null) or StrictMode replay / no real change- // (prev === theme): editors apply the theme themselves at construction.- if (prev === null || prev === theme) return;+ const prev = prevWorkspaceThemeRef.current;+ prevWorkspaceThemeRef.current = workspaceTheme;+ // Initial mount (prev === null), StrictMode replay, or a mode-only change:+ // editors apply the theme themselves at construction.+ if (prev === null || prev === workspaceTheme) return;++ const theme =+ mode === "ADMIN" ? resolveAdminTheme(workspaceTheme) : workspaceTheme;let cancelled = false;void loadMonacoEditor().then((monaco) => {@@ -39,5 +48,5 @@ export function useMonacoThemeController() {return () => {cancelled = true;};- }, [theme]);+ }, [mode, workspaceTheme]);}