Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(mcp): operator-visible MCP provenance badge on the audit log page (#21132)

Vincent Huanga6400f2d022e
diff --git a/frontend/src/components/AuditLogTable.test.tsx b/frontend/src/components/AuditLogTable.test.tsx
index 6767c0e4fc..661d643811 100644
--- a/frontend/src/components/AuditLogTable.test.tsx
+++ b/frontend/src/components/AuditLogTable.test.tsx
@@ -131,6 +131,9 @@ beforeEach(async () => {
});
afterEach(() => {
+ // Restore here, not in the test body: an assertion that throws before the
+ // restore would leak fake timers into every later test in the file.
+ vi.useRealTimers();
document.body.innerHTML = "";
});
@@ -172,4 +175,177 @@ describe("AuditLogTable", () => {
unmount();
});
+
+ test("badges only the rows carrying MCP delegation provenance", async () => {
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ user: "users/[email protected]",
+ mcpDelegation: { correlationId: "corr-1" },
+ }),
+ create(AuditLogSchema, {
+ name: "auditLogs/2",
+ method: "/bytebase.v1.SQLService/Query",
+ user: "users/[email protected]",
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const rows = [...container.querySelectorAll("tbody tr")];
+ expect(rows).toHaveLength(2);
+ expect(rows[0].textContent).toContain("[email protected]");
+ expect(rows[0].textContent).toContain("audit-log.mcp.badge");
+ expect(rows[1].textContent).toContain("[email protected]");
+ expect(rows[1].textContent).not.toContain("audit-log.mcp.badge");
+
+ unmount();
+ });
+
+ test("a delegation whose every field is empty still badges the row", async () => {
+ // Presence of the message is the marker: a pre-grant legacy session — a
+ // plain web-session token at /mcp — stores no scope, resource, or client
+ // ID, and must still be badged.
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ user: "users/[email protected]",
+ mcpDelegation: {},
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain("audit-log.mcp.badge");
+
+ unmount();
+ });
+
+ // Reads the tooltip as label -> value pairs rather than flat text, so a
+ // field rendered under the wrong label fails instead of passing on
+ // substring presence.
+ const openTooltipFields = async (container: HTMLElement) => {
+ // The Tooltip trigger wraps the Badge, so both spans carry the same
+ // textContent; the first in document order is the trigger. focusin
+ // bubbles, so either would open the tooltip.
+ const trigger = [...container.querySelectorAll("span")].find(
+ (el) => el.textContent === "audit-log.mcp.badge"
+ );
+ expect(trigger).toBeInstanceOf(HTMLSpanElement);
+ await act(async () => {
+ trigger?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
+ vi.advanceTimersByTime(100);
+ });
+ const overlay = document.getElementById("bb-react-layer-overlay");
+ expect(overlay).toBeInstanceOf(HTMLDivElement);
+ const pairs: Record<string, string> = {};
+ for (const row of overlay?.querySelectorAll("div") ?? []) {
+ const spans = row.querySelectorAll(":scope > span");
+ if (spans.length === 2) {
+ pairs[spans[0].textContent ?? ""] = spans[1].textContent ?? "";
+ }
+ }
+ return { overlayText: overlay?.textContent ?? "", pairs };
+ };
+
+ test("the badge tooltip pairs each grant field with its own label", async () => {
+ vi.useFakeTimers();
+ // The ordinary grant-backed session: every field populated, including the
+ // consented scope that decides read-only vs read-write.
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ user: "users/[email protected]",
+ mcpDelegation: {
+ clientId: "bb_oauth_client",
+ correlationId: "8b1f0a1e-corr",
+ resource: "https://example.com/mcp",
+ scope: "mcp:read-write",
+ },
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const { overlayText, pairs } = await openTooltipFields(container);
+ expect(overlayText).toContain("audit-log.mcp.origin");
+ expect(pairs).toEqual({
+ "audit-log.mcp.correlation-id": "8b1f0a1e-corr",
+ "common.scope": "mcp:read-write",
+ "common.resource": "https://example.com/mcp",
+ "audit-log.mcp.client-id": "bb_oauth_client",
+ });
+
+ unmount();
+ });
+
+ test("the tooltip omits the fields a scope-omitting grant left empty", async () => {
+ vi.useFakeTimers();
+ // A client that omitted `scope` at consent — a steady-state population,
+ // since discovery deliberately does not advertise the vocabulary until
+ // P1b enforces it. See DelegatedGrant in backend/common/context.go.
+ mocks.searchAuditLogs.mockResolvedValue({
+ auditLogs: [
+ create(AuditLogSchema, {
+ name: "auditLogs/1",
+ method: "/bytebase.v1.SQLService/Query",
+ user: "users/[email protected]",
+ mcpDelegation: {
+ correlationId: "8b1f0a1e-corr",
+ resource: "https://example.com/mcp",
+ },
+ }),
+ ],
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <AuditLogTable parent="projects/-" canExport={false} />
+ );
+ await render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const { overlayText, pairs } = await openTooltipFields(container);
+ expect(overlayText).toContain("audit-log.mcp.origin");
+ expect(pairs).toEqual({
+ "audit-log.mcp.correlation-id": "8b1f0a1e-corr",
+ "common.resource": "https://example.com/mcp",
+ });
+ expect(overlayText).not.toContain("common.scope");
+ expect(overlayText).not.toContain("audit-log.mcp.client-id");
+
+ unmount();
+ });
});
diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsx
index 8d99b8433e..617ca1d99f 100644
--- a/frontend/src/components/AuditLogTable.tsx
+++ b/frontend/src/components/AuditLogTable.tsx
@@ -15,6 +15,7 @@ import {
} from "@/components/AdvancedSearch";
import { RouterLink } from "@/components/RouterLink";
import { TimeRangePicker } from "@/components/TimeRangePicker";
+import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
@@ -31,6 +32,7 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
+import { Tooltip } from "@/components/ui/tooltip";
import { usePlanFeature } from "@/hooks/useAppState";
import { useColumnWidths } from "@/hooks/useColumnWidths";
import { PagedTableFooter } from "@/hooks/usePagedData";
@@ -49,7 +51,10 @@ import {
} from "@/stores/modules/v1/common";
import { getDateForPbTimestampProtoEs } from "@/types";
import { StatusSchema } from "@/types/proto-es/google/rpc/status_pb";
-import type { AuditLog } from "@/types/proto-es/v1/audit_log_service_pb";
+import type {
+ AuditLog,
+ MCPDelegation,
+} from "@/types/proto-es/v1/audit_log_service_pb";
import {
AuditLog_Severity,
ExportAuditLogsRequestSchema,
@@ -203,6 +208,92 @@ function getViewLink(auditLog: AuditLog): string | null {
return null;
}
+// ============================================================
+// MCP provenance
+// ============================================================
+
+// McpProvenanceField renders one label/value pair of the delegation grant.
+// Empty values are omitted rather than shown as a placeholder: these are the
+// grant's stored values copied verbatim, so empty means the grant recorded
+// nothing — a pre-grant legacy session, or a client that omitted `scope` at
+// consent. Inventing a stand-in would misreport stored state as unknown state.
+// See DelegatedGrant in backend/common/context.go for the empty-state map.
+function McpProvenanceField({
+ label,
+ value,
+}: Readonly<{ label: string; value: string }>) {
+ if (!value) return null;
+ return (
+ <div className="flex flex-col">
+ <span className="opacity-70">{label}</span>
+ <span className="font-mono break-all">{value}</span>
+ </div>
+ );
+}
+
+function McpProvenanceDetail({
+ delegation,
+}: Readonly<{ delegation: MCPDelegation }>) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex flex-col gap-y-1.5 text-xs">
+ <span className="font-medium">{t("audit-log.mcp.origin")}</span>
+ <McpProvenanceField
+ label={t("audit-log.mcp.correlation-id")}
+ value={delegation.correlationId}
+ />
+ <McpProvenanceField label={t("common.scope")} value={delegation.scope} />
+ <McpProvenanceField
+ label={t("common.resource")}
+ value={delegation.resource}
+ />
+ <McpProvenanceField
+ label={t("audit-log.mcp.client-id")}
+ value={delegation.clientId}
+ />
+ </div>
+ );
+}
+
+// AuditLogActorCell renders the acting user, badged when the call reached the
+// API through the MCP server's delegated credential. Presence of
+// `mcpDelegation` is the marker — never read its values to decide MCP-ness.
+// Only `correlationId` is minted for every session; `scope`, `resource`, and
+// `clientId` are grant state that a legacy or scope-omitting session leaves
+// empty, so no field value is a sound proxy for MCP origin.
+function AuditLogActorCell({ log }: Readonly<{ log: AuditLog }>) {
+ const { t } = useTranslation();
+ const email = extractUserEmail(log.user);
+ return (
+ <div className="flex items-center gap-x-1.5">
+ {email ? (
+ // As a flex item the anchor is blockified, so `truncate` now ellipses
+ // where the bare inline anchor used to hard-clip; `title` keeps the
+ // full address reachable.
+ <a
+ href={`mailto:${email}`}
+ title={email}
+ className="text-accent hover:underline truncate min-w-0"
+ >
+ {email}
+ </a>
+ ) : (
+ <span>-</span>
+ )}
+ {log.mcpDelegation && (
+ <Tooltip
+ content={<McpProvenanceDetail delegation={log.mcpDelegation} />}
+ popupClassName="max-w-96"
+ >
+ <Badge variant="secondary" className="text-xs px-1.5 py-0 shrink-0">
+ {t("audit-log.mcp.badge")}
+ </Badge>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
// ============================================================
// JSONStringView
// ============================================================
@@ -358,15 +449,7 @@ function useColumnDefs(): ColumnDef[] {
defaultWidth: 200,
minWidth: 120,
resizable: true,
- render: (log: AuditLog) => {
- if (!log.user) return <span>-</span>;
- const email = extractUserEmail(log.user);
- return (
- <a href={`mailto:${email}`} className="text-accent hover:underline">
- {email}
- </a>
- );
- },
+ render: (log: AuditLog) => <AuditLogActorCell log={log} />,
},
{
key: "request",
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 8bb9b7ffad..577b2f2257 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -94,6 +94,12 @@
},
"export-finished": "Export finished",
"export-tooltip": "Must select start time and end time within 30 days",
+ "mcp": {
+ "badge": "MCP",
+ "client-id": "Client ID",
+ "correlation-id": "Correlation ID",
+ "origin": "Originated from an MCP (Model Context Protocol) client"
+ },
"table": {
"actor": "Actor",
"created-ts": "Time",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 2dbb71f1e5..09f12aeeb1 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -94,6 +94,12 @@
},
"export-finished": "Exportación finalizada",
"export-tooltip": "Debe seleccionar hora de inicio y fin dentro de 30 días",
+ "mcp": {
+ "badge": "MCP",
+ "client-id": "ID de cliente",
+ "correlation-id": "ID de correlación",
+ "origin": "Originado en un cliente MCP (Model Context Protocol)"
+ },
"table": {
"actor": "Actor",
"created-ts": "Hora",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 3914df9224..53f40e8960 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -94,6 +94,12 @@
},
"export-finished": "エクスポートが完了しました",
"export-tooltip": "30日以内の開始時間と終了時間を選択する必要があります",
+ "mcp": {
+ "badge": "MCP",
+ "client-id": "クライアント ID",
+ "correlation-id": "相関 ID",
+ "origin": "MCP (Model Context Protocol) クライアントからのリクエスト"
+ },
"table": {
"actor": "操作者",
"created-ts": "時間",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index bb7ee07b59..f190a4c2b3 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -94,6 +94,12 @@
},
"export-finished": "Xuất hoàn tất",
"export-tooltip": "Phải chọn thời gian bắt đầu và kết thúc trong vòng 30 ngày",
+ "mcp": {
+ "badge": "MCP",
+ "client-id": "ID máy khách",
+ "correlation-id": "ID tương quan",
+ "origin": "Bắt nguồn từ một máy khách MCP (Model Context Protocol)"
+ },
"table": {
"actor": "Người thực hiện",
"created-ts": "Thời gian",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index d230227a09..47b101ca28 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -94,6 +94,12 @@
},
"export-finished": "导出完成",
"export-tooltip": "必须选择 30 天范围内的开始和结束日期",
+ "mcp": {
+ "badge": "MCP",
+ "client-id": "客户端 ID",
+ "correlation-id": "关联 ID",
+ "origin": "来自 MCP (Model Context Protocol) 客户端"
+ },
"table": {
"actor": "操作者",
"created-ts": "时间",