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(frontend): let the server gate actor lists and offer typed accounts
Vincent Huangf6325d17acbd
diff --git a/frontend/src/components/AuditLogTable.test.tsx b/frontend/src/components/AuditLogTable.test.tsxindex 52284b8c46..5f4e97d1d8 100644--- a/frontend/src/components/AuditLogTable.test.tsx+++ b/frontend/src/components/AuditLogTable.test.tsx@@ -22,6 +22,7 @@ import { PermissionDeniedDetailSchema } from "@/types/proto-es/v1/common_pb";interface ListActorParams {parent?: string;filter?: { query?: string };+ silent?: boolean;}const mocks = vi.hoisted(() => ({@@ -77,9 +78,6 @@ vi.mock("@/stores/app", () => ({listUsers: mocks.listUsers,listServiceAccounts: mocks.listServiceAccounts,listWorkloadIdentities: mocks.listWorkloadIdentities,- projectsByName: { "projects/project-a": {} },- hasWorkspacePermission: () => true,- hasProjectPermission: () => true,}),}));@@ -190,6 +188,11 @@ const ACTORS = {email: "[email protected]",title: "CI",},+ projectServiceAccount: {+ name: "serviceAccounts/[email protected]",+ email: "[email protected]",+ title: "Deployer",+ },};// Mirrors the server's filter: a case-insensitive contains match on the@@ -203,15 +206,23 @@ const matchesQuery =);};+// Like the server, a project parent lists only that project's accounts and a+// workspace parent only workspace-level ones.const seedActors = () => {mocks.listUsers.mockImplementation(async (params) => ({users: [ACTORS.user].filter(matchesQuery(params)),}));mocks.listServiceAccounts.mockImplementation(async (params) => ({- serviceAccounts: [ACTORS.serviceAccount].filter(matchesQuery(params)),+ serviceAccounts: (params?.parent === "projects/project-a"+ ? [ACTORS.projectServiceAccount]+ : [ACTORS.serviceAccount]+ ).filter(matchesQuery(params)),}));mocks.listWorkloadIdentities.mockImplementation(async (params) => ({- workloadIdentities: [ACTORS.workloadIdentity].filter(matchesQuery(params)),+ workloadIdentities: (params?.parent === "projects/project-a"+ ? []+ : [ACTORS.workloadIdentity]+ ).filter(matchesQuery(params)),}));};@@ -274,6 +285,7 @@ describe("AuditLogTable", () => {ACTORS.user,ACTORS.serviceAccount,ACTORS.workloadIdentity,+ ACTORS.projectServiceAccount,])("finds $name typed into the actor search box", async (actor) => {vi.useFakeTimers();seedActors();@@ -314,7 +326,7 @@ describe("AuditLogTable", () => {table.unmount();});- test("lists every actor kind for an empty keyword", async () => {+ test("lists every actor kind from the workspace and the project", async () => {seedActors();mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });@@ -324,14 +336,37 @@ describe("AuditLogTable", () => {await render();const options = await getActorScope()?.onSearch?.("");- // The fake lists the same accounts under the workspace and the project.expect(options?.map((option) => option.value)).toEqual([ACTORS.user.name,ACTORS.serviceAccount.name,+ ACTORS.projectServiceAccount.name,ACTORS.workloadIdentity.name,]);- expect(mocks.listServiceAccounts).toHaveBeenCalledTimes(2);- expect(mocks.listWorkloadIdentities).toHaveBeenCalledTimes(2);++ unmount();+ });++ test("leaves the account list permissions to the server", async () => {+ seedActors();+ mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });++ const { render, unmount } = renderIntoContainer(+ <AuditLogTable parent="projects/project-a" canExport={false} />+ );+ await render();+ await getActorScope()?.onSearch?.("");++ for (const list of [+ mocks.listServiceAccounts,+ mocks.listWorkloadIdentities,+ ]) {+ expect(+ list.mock.calls.map(([params]) => [params?.parent, params?.silent])+ ).toEqual([+ ["workspaces/default", true],+ ["projects/project-a", true],+ ]);+ }unmount();});@@ -357,7 +392,7 @@ describe("AuditLogTable", () => {test("keeps the other actor kinds when one list fails", async () => {seedActors();- mocks.listWorkloadIdentities.mockRejectedValueOnce(new Error("denied"));+ mocks.listWorkloadIdentities.mockRejectedValueOnce(new Error("unavailable"));mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });const { render, unmount } = renderIntoContainer(@@ -374,7 +409,14 @@ describe("AuditLogTable", () => {unmount();});- test("filters a service account actor by its name and its legacy user name", async () => {+ const serviceAccountFilter =+ '(actor == "serviceAccounts/[email protected]" || actor == "users/[email protected]")';+ test.each([+ [ACTORS.serviceAccount.name, serviceAccountFilter],+ ["serviceaccounts/[email protected]", serviceAccountFilter],+ [ACTORS.serviceAccount.email, serviceAccountFilter],+ [ACTORS.user.email, 'actor == "users/[email protected]"'],+ ])("filters the actor value %s", async (value, filter) => {mocks.searchAuditLogs.mockResolvedValue({ auditLogs: [], nextPageToken: "" });const { render, unmount } = renderIntoContainer(@@ -389,18 +431,12 @@ describe("AuditLogTable", () => {scopes: Array<{ id: string; value: string }>;}) => void)| undefined- )?.({- query: "",- scopes: [{ id: "actor", value: ACTORS.serviceAccount.name }],- });+ )?.({ query: "", scopes: [{ id: "actor", value }] });await Promise.resolve();});expect(mocks.searchAuditLogs).toHaveBeenLastCalledWith(- expect.objectContaining({- filter:- '(actor == "serviceAccounts/[email protected]" || actor == "users/[email protected]")',- })+ expect.objectContaining({ filter }));unmount();diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsxindex 5ad7fa08cc..73d5bd67c2 100644--- a/frontend/src/components/AuditLogTable.tsx+++ b/frontend/src/components/AuditLogTable.tsx@@ -73,7 +73,9 @@ import { RolloutService } from "@/types/proto-es/v1/rollout_service_pb";import { SQLService } from "@/types/proto-es/v1/sql_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { protobufJsonRegistry } from "@/types/protobufJsonRegistry";+import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";import { getDefaultPagination, humanizeDurationV1 } from "@/utils";+import { isValidEmail } from "@/utils/util";import { celString } from "@/utils/v1/celLiteral";dayjs.extend(utc);@@ -94,12 +96,32 @@ function uniqueValueOptions(options: ValueOption[]): ValueOption[] {return [...new Map(options.map((option) => [option.value, option])).values()];}-// Strips an actor name's resource prefix, since the account lists match on-// email. Ignores case because AdvancedSearch lowercases the keyword.-const ACTOR_NAME_PREFIX = new RegExp(- `^(?:${userNamePrefix}|${serviceAccountNamePrefix}|${workloadIdentityNamePrefix})`,- "i"-);+const ACTOR_NAME_PREFIXES = [+ userNamePrefix,+ serviceAccountNamePrefix,+ workloadIdentityNamePrefix,+];++// Returns the resource name an actor value stands for, lowercased with the+// canonical prefix: account emails are stored lowercase, and AdvancedSearch+// lowercases the keyword. A bare email takes the account kind its domain names.+function toActorName(value: string): string {+ const lowered = value.toLowerCase();+ const prefix = ACTOR_NAME_PREFIXES.find((candidate) =>+ lowered.startsWith(candidate.toLowerCase())+ );+ if (prefix) {+ return `${prefix}${lowered.slice(prefix.length)}`;+ }+ switch (getAccountTypeByEmail(lowered)) {+ case AccountType.SERVICE_ACCOUNT:+ return `${serviceAccountNamePrefix}${lowered}`;+ case AccountType.WORKLOAD_IDENTITY:+ return `${workloadIdentityNamePrefix}${lowered}`;+ default:+ return `${userNamePrefix}${lowered}`;+ }+}function toActorOptions(accounts: Array<{ name: string; email: string; title: string }>@@ -116,20 +138,12 @@ function buildFilterString(filter: AuditLogFilter): string {if (filter.level !== undefined)parts.push(`severity == ${celString(AuditLog_Severity[filter.level])}`);if (filter.actor) {- const legacyUser = `${userNamePrefix}${filter.actor.slice(- filter.actor.indexOf("/") + 1- )}`;- const matchesLegacyUser =- filter.actor.startsWith(serviceAccountNamePrefix) ||- filter.actor.startsWith(workloadIdentityNamePrefix);+ const actor = toActorName(filter.actor);+ const legacyUser = `${userNamePrefix}${actor.slice(actor.indexOf("/") + 1)}`;parts.push(- matchesLegacyUser- ? `(actor == ${celString(filter.actor)} || actor == ${celString(legacyUser)})`- : `actor == ${celString(- filter.actor.startsWith(userNamePrefix)- ? filter.actor- : `${userNamePrefix}${filter.actor}`- )}`+ actor === legacyUser+ ? `actor == ${celString(actor)}`+ : `(actor == ${celString(actor)} || actor == ${celString(legacyUser)})`);}if (filter.createdTsAfter)@@ -624,31 +638,6 @@ export function AuditLogTable({parent !== `${projectNamePrefix}-` && parent.startsWith(projectNamePrefix)? parent: "";- const project = useAppStore((state) =>- projectAccountParent- ? state.projectsByName[projectAccountParent]- : undefined- );- const canListWorkspaceServiceAccounts = useAppStore((state) =>- workspaceResourceName- ? state.hasWorkspacePermission("bb.serviceAccounts.list")- : false- );- const canListWorkspaceWorkloadIdentities = useAppStore((state) =>- workspaceResourceName- ? state.hasWorkspacePermission("bb.workloadIdentities.list")- : false- );- const canListProjectServiceAccounts = useAppStore((state) =>- project- ? state.hasProjectPermission(project, "bb.serviceAccounts.list")- : false- );- const canListProjectWorkloadIdentities = useAppStore((state) =>- project- ? state.hasProjectPermission(project, "bb.workloadIdentities.list")- : false- );const columns = useColumnDefs();const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);@@ -827,54 +816,52 @@ export function AuditLogTable({);const searchActors = useCallback(async (keyword: string): Promise<ValueOption[]> => {- const query = keyword.trim().replace(ACTOR_NAME_PREFIX, "");+ const actor = toActorName(keyword.trim());+ // The account lists match display names and emails, not resource names.+ const query = actor.slice(actor.indexOf("/") + 1);const pageSize = getDefaultPagination();+ // The server checks the list permissions; silent keeps a denied list+ // from redirecting to /403, and allSettled then drops it.const accountParams = (parent: string) => ({parent,pageSize,showDeleted: false,filter: { query },skipCache: true,+ silent: true,});- const accountParents = (- canListInWorkspace: boolean,- canListInProject: boolean- ) => [- ...(workspaceResourceName && canListInWorkspace- ? [workspaceResourceName]- : []),- ...(projectAccountParent && canListInProject- ? [projectAccountParent]- : []),- ];+ const accountParents = [+ workspaceResourceName,+ projectAccountParent,+ ].filter(Boolean);const results = await Promise.allSettled([- listUsers({- pageSize,- filter: query ? { query } : undefined,- }).then(({ users }) => toActorOptions(users)),- ...accountParents(- canListWorkspaceServiceAccounts,- canListProjectServiceAccounts- ).map((parent) =>+ listUsers({ pageSize, filter: { query } }).then(({ users }) =>+ toActorOptions(users)+ ),+ ...accountParents.map((parent) =>listServiceAccounts(accountParams(parent)).then(({ serviceAccounts }) => toActorOptions(serviceAccounts))),- ...accountParents(- canListWorkspaceWorkloadIdentities,- canListProjectWorkloadIdentities- ).map((parent) =>+ ...accountParents.map((parent) =>listWorkloadIdentities(accountParams(parent)).then(({ workloadIdentities }) => toActorOptions(workloadIdentities))),]);- return uniqueValueOptions(- results.flatMap((result) =>+ // The lists reach only this page's parents and skip deleted accounts, so+ // a full service account or workload identity email is offered as typed.+ const typedAccount =+ isValidEmail(query) && !actor.startsWith(userNamePrefix)+ ? [{ value: actor, keywords: [query] }]+ : [];+ return uniqueValueOptions([+ ...typedAccount,+ ...results.flatMap((result) =>result.status === "fulfilled" ? result.value : []- )- );+ ),+ ]);},[listUsers,@@ -882,10 +869,6 @@ export function AuditLogTable({listWorkloadIdentities,workspaceResourceName,projectAccountParent,- canListWorkspaceServiceAccounts,- canListWorkspaceWorkloadIdentities,- canListProjectServiceAccounts,- canListProjectWorkloadIdentities,]);diff --git a/frontend/src/components/ui/column-resize-handle.test.tsx b/frontend/src/components/ui/column-resize-handle.test.tsxnew file mode 100644index 0000000000..51fd210766--- /dev/null+++ b/frontend/src/components/ui/column-resize-handle.test.tsx@@ -0,0 +1,20 @@+import { describe, expect, test } from "vitest";+import { ColumnResizeHandle } from "./column-resize-handle";++describe("ColumnResizeHandle", () => {+ test("keeps its hitbox inside the header edge", () => {+ const element = ColumnResizeHandle({ onMouseDown: () => {} });++ expect(element.props.className).toContain("right-0");+ expect(element.props.className).not.toContain("right-[-6px]");+ expect(element.props.className).toContain("w-3");+ expect(element.props.children.props.className).toContain("right-0");+ expect(element.props.children.props.className).toContain("w-0.5");+ });++ test("sets no z-index, so inline popups paint over it", () => {+ const element = ColumnResizeHandle({ onMouseDown: () => {} });++ expect(element.props.className).not.toMatch(/(?:^|[\s:])!?-?z-/);+ });+});diff --git a/frontend/src/components/ui/column-resize-handle.tsx b/frontend/src/components/ui/column-resize-handle.tsxindex 4711620165..1852f67ce2 100644--- a/frontend/src/components/ui/column-resize-handle.tsx+++ b/frontend/src/components/ui/column-resize-handle.tsx@@ -7,9 +7,8 @@ interface ColumnResizeHandleProps {/*** Drag affordance for resizing a table column. Designed to be absolutely- * positioned inside a `relative` `<th>`. Its z-index only lifts it above the- * cell's own content: inline popups such as the AdvancedSearch menu share the- * page's stacking context at `LAYER_SURFACE_CLASS` and must cover it.+ * positioned inside a `relative` `<th>`. It has no z-index: inline popups such+ * as the AdvancedSearch menu share the page's stacking context and must cover it.*/export function ColumnResizeHandle({onMouseDown,@@ -18,7 +17,7 @@ export function ColumnResizeHandle({return (<divclassName={cn(- "group absolute right-0 top-0 z-1 h-full w-3 cursor-col-resize",+ "group absolute right-0 top-0 h-full w-3 cursor-col-resize",className)}onMouseDown={onMouseDown}diff --git a/frontend/src/components/ui/table.test.tsx b/frontend/src/components/ui/table.test.tsxindex ba66a238c7..e2d1a8203a 100644--- a/frontend/src/components/ui/table.test.tsx+++ b/frontend/src/components/ui/table.test.tsx@@ -1,6 +1,4 @@import { describe, expect, test } from "vitest";-import { ColumnResizeHandle } from "./column-resize-handle";-import { LAYER_SURFACE_CLASS } from "./layer";import { TableBody, TableEmptyView, TableRow } from "./table";describe("table primitives", () => {@@ -51,24 +49,4 @@ describe("table primitives", () => {expect(content.props.style).toEqual({ width: 640 });expect(content.props.children).toBe("No data");});-- test("ColumnResizeHandle keeps its hitbox inside the header edge", () => {- const element = ColumnResizeHandle({ onMouseDown: () => {} });-- expect(element.props.className).toContain("right-0");- expect(element.props.className).not.toContain("right-[-6px]");- expect(element.props.className).toContain("w-3");- expect(element.props.children.props.className).toContain("right-0");- expect(element.props.children.props.className).toContain("w-0.5");- });-- test("ColumnResizeHandle stacks below popup surfaces", () => {- const zIndexOf = (className: string) =>- Number(/\bz-(\d+)\b/.exec(className)?.[1]);- const element = ColumnResizeHandle({ onMouseDown: () => {} });-- expect(zIndexOf(element.props.className)).toBeLessThan(- zIndexOf(LAYER_SURFACE_CLASS)- );- });});diff --git a/frontend/src/stores/app/serviceAccount.ts b/frontend/src/stores/app/serviceAccount.tsindex 815cdf12d5..46dd4fb3e9 100644--- a/frontend/src/stores/app/serviceAccount.ts+++ b/frontend/src/stores/app/serviceAccount.ts@@ -63,7 +63,13 @@ export const createServiceAccountSlice: AppSliceCreator<ServiceAccountSlice> = (pageToken: params.pageToken,showDeleted: params.showDeleted,filter: buildAccountListFilter(params.filter ?? {}),- })+ }),+ {+ contextValues: createContextValues().set(+ silentContextKey,+ params.silent ?? false+ ),+ });if (!params.skipCache) {set((state) => ({diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex 46a8e499d9..37536b86e9 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -142,6 +142,7 @@ export type ListServiceAccountsParams = {showDeleted: boolean;filter?: AccountFilter;skipCache?: boolean;+ silent?: boolean;};export type ListWorkloadIdentitiesParams = {@@ -151,6 +152,7 @@ export type ListWorkloadIdentitiesParams = {showDeleted: boolean;filter?: AccountFilter;skipCache?: boolean;+ silent?: boolean;};export type AccessGrantFilter = {diff --git a/frontend/src/stores/app/workloadIdentity.ts b/frontend/src/stores/app/workloadIdentity.tsindex 627848c61e..156d2fa9ae 100644--- a/frontend/src/stores/app/workloadIdentity.ts+++ b/frontend/src/stores/app/workloadIdentity.ts@@ -55,7 +55,13 @@ export const createWorkloadIdentitySlice: AppSliceCreator<pageToken: params.pageToken,showDeleted: params.showDeleted,filter: buildAccountListFilter(params.filter ?? {}),- })+ }),+ {+ contextValues: createContextValues().set(+ silentContextKey,+ params.silent ?? false+ ),+ });if (!params.skipCache) {set((state) => ({