Skip to content

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

feat(frontend): make the role grant's environment field a direct-execution switch

zchpeter16b89d9b4974
diff --git a/frontend/src/components/AccountTypeBadge.tsx b/frontend/src/components/AccountTypeBadge.tsx
new file mode 100644
index 0000000000..f5d420be2d
--- /dev/null
+++ b/frontend/src/components/AccountTypeBadge.tsx
@@ -0,0 +1,20 @@
+import { useTranslation } from "react-i18next";
+import { Badge } from "@/components/ui/badge";
+import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
+
+/** Marks a service account or a workload identity; nothing for a person. */
+export function AccountTypeBadge({ email }: { email: string | undefined }) {
+ const type = email ? getAccountTypeByEmail(email) : AccountType.USER;
+ return type === AccountType.USER ? null : <AccountTypeLabel type={type} />;
+}
+
+function AccountTypeLabel({ type }: { type: AccountType }) {
+ const { t } = useTranslation();
+ return (
+ <Badge variant="secondary" className="text-xs">
+ {type === AccountType.SERVICE_ACCOUNT
+ ? t("settings.members.service-account")
+ : t("settings.members.workload-identity")}
+ </Badge>
+ );
+}
diff --git a/frontend/src/components/EnvironmentLabel.tsx b/frontend/src/components/EnvironmentLabel.tsx
index badf80f4e3..48faa74a29 100644
--- a/frontend/src/components/EnvironmentLabel.tsx
+++ b/frontend/src/components/EnvironmentLabel.tsx
@@ -9,6 +9,7 @@ import type { Environment } from "@/types";
import {
DEFAULT_ENVIRONMENT_COLOR,
formatEnvironmentName,
+ isProtectedEnvironment,
NULL_ENVIRONMENT_NAME,
UNKNOWN_ENVIRONMENT_NAME,
} from "@/types";
@@ -49,8 +50,7 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({
const isUnset =
environment.name === UNKNOWN_ENVIRONMENT_NAME ||
environment.name === NULL_ENVIRONMENT_NAME;
- const isProtected =
- hasEnvTierFeature && environment.tags?.protected === "protected";
+ const isProtected = isProtectedEnvironment(environment, hasEnvTierFeature);
const color = environment.color || DEFAULT_ENVIRONMENT_COLOR;
const baseRgb = !isUnset ? hexToRgb(color) : [];
const displayRgb =
diff --git a/frontend/src/components/EnvironmentSelect.test.tsx b/frontend/src/components/EnvironmentSelect.test.tsx
new file mode 100644
index 0000000000..3048046890
--- /dev/null
+++ b/frontend/src/components/EnvironmentSelect.test.tsx
@@ -0,0 +1,48 @@
+import { act, render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { EnvironmentSelect } from "./EnvironmentSelect";
+
+vi.mock("react-i18next", async () =>
+ (await import("@/test-utils/i18n")).reactI18nextStub()
+);
+
+vi.mock("@/hooks/useAppState", async () => {
+ const { STUB_ENVIRONMENTS } = await import(
+ "@/test-utils/environmentSelectStub"
+ );
+ return { useEnvironmentList: () => STUB_ENVIRONMENTS };
+});
+
+vi.mock("@/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: ({ environment }: { environment: { title: string } }) => (
+ <span>{environment.title}</span>
+ ),
+}));
+
+describe("EnvironmentSelect", () => {
+ test("multiple: each option row is an option in a listbox and carries its suffix", () => {
+ const { container } = render(
+ <EnvironmentSelect
+ multiple
+ className="env-select"
+ value={[]}
+ onChange={() => {}}
+ renderSuffix={(environment) =>
+ environment.tags?.protected === "protected" ? (
+ <span data-testid="suffix">{environment.title}</span>
+ ) : null
+ }
+ />
+ );
+ act(() => {
+ (container.querySelector(".env-select > div") as HTMLElement).dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ expect(screen.getByRole("listbox")).toBeTruthy();
+ expect(screen.getAllByRole("option")).toHaveLength(2);
+ expect(screen.getAllByTestId("suffix").map((n) => n.textContent)).toEqual([
+ "Prod",
+ ]);
+ });
+});
diff --git a/frontend/src/components/EnvironmentSelect.tsx b/frontend/src/components/EnvironmentSelect.tsx
index b5b9b9f99a..c66dc9b65d 100644
--- a/frontend/src/components/EnvironmentSelect.tsx
+++ b/frontend/src/components/EnvironmentSelect.tsx
@@ -11,8 +11,6 @@ interface SingleProps {
multiple?: false;
value: string;
onChange: (value: string) => void;
- /** Extra content rendered next to the selected env in the trigger and rows. */
- renderSuffix?: (environment: Environment) => React.ReactNode;
}
interface MultiProps {
@@ -27,12 +25,17 @@ export type EnvironmentSelectProps = (SingleProps | MultiProps) & {
className?: string;
portal?: boolean;
clearable?: boolean;
+ /**
+ * Extra content rendered next to the environment in every option row, and
+ * in the single-select trigger beside the selected value.
+ */
+ renderSuffix?: (environment: Environment) => React.ReactNode;
};
export function EnvironmentSelect(props: EnvironmentSelectProps) {
const { t } = useTranslation();
const environments = useEnvironmentList();
- const renderSuffix = !props.multiple ? props.renderSuffix : undefined;
+ const renderSuffix = props.renderSuffix;
const options = useMemo(
() =>
diff --git a/frontend/src/components/role-grant/DDLWarningCallout.test.tsx b/frontend/src/components/role-grant/DDLWarningCallout.test.tsx
deleted file mode 100644
index 1202fd4b1b..0000000000
--- a/frontend/src/components/role-grant/DDLWarningCallout.test.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, test, vi } from "vitest";
-import { DDLWarningCallout } from "./DDLWarningCallout";
-
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, vars?: Record<string, unknown>) => {
- const parts = [key];
- if (vars) parts.push(JSON.stringify(vars));
- return parts.join(" ");
- },
- }),
-}));
-
-describe("DDLWarningCallout", () => {
- test("drawer variant renders ddl-warning copy with kind interpolated", () => {
- render(<DDLWarningCallout type="drawer" kind="DDL/DML" />);
- expect(screen.getByText(/project.members.ddl-warning/)).toHaveTextContent(
- "DDL/DML"
- );
- });
-
- test("binding-some renders ddl-current-some copy", () => {
- render(<DDLWarningCallout type="binding-some" kind="DML" />);
- expect(
- screen.getByText(/project.members.ddl-current-some/)
- ).toHaveTextContent("DML");
- expect(screen.queryByText(/Staging/)).not.toBeInTheDocument();
- });
-
- test("binding-all renders ddl-current-all copy", () => {
- render(<DDLWarningCallout type="binding-all" kind="DDL/DML" />);
- expect(
- screen.getByText(/project.members.ddl-current-all/)
- ).toHaveTextContent("DDL/DML");
- });
-
- test("binding-none renders ddl-current-none copy", () => {
- render(<DDLWarningCallout type="binding-none" kind="DML" />);
- expect(
- screen.getByText(/project.members.ddl-current-none/)
- ).toHaveTextContent("DML");
- });
-
- test("renders an alert with role=alert", () => {
- render(<DDLWarningCallout type="drawer" kind="DDL" />);
- expect(screen.getByRole("alert")).toBeInTheDocument();
- });
-});
-
-const _typeChecks = () => {
- // biome-ignore format: keep @ts-expect-error directive aligned with JSX line
- // @ts-expect-error — `binding-all` does not accept extra props.
- const _a = <DDLWarningCallout type="binding-all" kind="DDL" environments={["x"]} />;
- // biome-ignore format: keep @ts-expect-error directive aligned with JSX line
- // @ts-expect-error — `drawer` does not accept extra props.
- const _b = <DDLWarningCallout type="drawer" kind="DDL" environments={["x"]} />;
- return [_a, _b];
-};
-void _typeChecks;
diff --git a/frontend/src/components/role-grant/DDLWarningCallout.tsx b/frontend/src/components/role-grant/DDLWarningCallout.tsx
deleted file mode 100644
index f04b3fad36..0000000000
--- a/frontend/src/components/role-grant/DDLWarningCallout.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { Alert } from "@/components/ui/alert";
-import type { EnvLimitationKind } from "@/lib/project-member/utils";
-
-type DDLWarningProps =
- | { type: "drawer"; kind: EnvLimitationKind }
- | { type: "binding-some"; kind: EnvLimitationKind }
- | { type: "binding-all"; kind: EnvLimitationKind }
- | { type: "binding-none"; kind: EnvLimitationKind };
-
-export function DDLWarningCallout(props: DDLWarningProps) {
- const { t } = useTranslation();
- switch (props.type) {
- case "drawer":
- return (
- <Alert variant="warning">
- {t("project.members.ddl-warning", { kind: props.kind })}
- </Alert>
- );
- case "binding-some":
- return (
- <Alert variant="warning">
- {t("project.members.ddl-current-some", { kind: props.kind })}
- </Alert>
- );
- case "binding-all":
- return (
- <Alert variant="warning">
- {t("project.members.ddl-current-all", { kind: props.kind })}
- </Alert>
- );
- case "binding-none":
- // Info, not warning: this state is benign — DDL/DML is gated, no risk to
- // surface. Yellow on a positive permission state would mislead readers.
- return (
- <Alert variant="info">
- {t("project.members.ddl-current-none", { kind: props.kind })}
- </Alert>
- );
- }
-}
diff --git a/frontend/src/components/role-grant/DirectExecutionCallout.test.tsx b/frontend/src/components/role-grant/DirectExecutionCallout.test.tsx
new file mode 100644
index 0000000000..50e7717640
--- /dev/null
+++ b/frontend/src/components/role-grant/DirectExecutionCallout.test.tsx
@@ -0,0 +1,112 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { STUB_ENVIRONMENTS } from "@/test-utils/environmentSelectStub";
+import {
+ DirectExecutionCallout,
+ type DirectExecutionLead,
+} from "./DirectExecutionCallout";
+import type { DirectExecutionScope } from "@/lib/project-member/directExecution";
+
+vi.mock("react-i18next", async () =>
+ (await import("@/test-utils/i18n")).reactI18nextStub()
+);
+
+vi.mock("@/components/EnvironmentLabel", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentBadgeStub()
+);
+
+const renderCallout = (
+ scope: DirectExecutionScope,
+ extra: Partial<{
+ lead: Exclude<DirectExecutionLead, "approver">;
+ hasEnvTierFeature: boolean;
+ }> = {}
+) =>
+ render(
+ <DirectExecutionCallout
+ kind="DDL/DML"
+ scope={scope}
+ environmentList={STUB_ENVIRONMENTS}
+ hasEnvTierFeature={extra.hasEnvTierFeature ?? true}
+ lead={extra.lead ?? "binding"}
+ />
+ );
+const chips = () => screen.getAllByTestId("env-label").map((el) => el.textContent);
+
+describe("DirectExecutionCallout", () => {
+ test("some: one chip per environment, in the order given, under the surface's lead", () => {
+ renderCallout(
+ { type: "some", environments: ["environments/prod", "environments/staging"] },
+ { lead: "grant" }
+ );
+ expect(chips()).toEqual(["environments/prod", "environments/staging"]);
+ expect(screen.getByText(/direct-execution\.lead-grant/).textContent).toContain(
+ '"kind":"DDL/DML"'
+ );
+ });
+
+ test("the member drawer's lead names no one", () => {
+ renderCallout({ type: "some", environments: ["environments/prod"] });
+ expect(
+ screen.getByText(/direct-execution\.lead-binding/).textContent
+ ).toContain('"kind":"DDL/DML"');
+ });
+
+ test("some: the protected line names only the protected environments", () => {
+ renderCallout({
+ type: "some",
+ environments: ["environments/staging", "environments/prod"],
+ });
+ const line = screen.getByText(/direct-execution\.protected/);
+ expect(line.textContent).toContain('"count":1');
+ expect(line.textContent).toContain('"environments":"Prod"');
+ });
+
+ test("some: without the environment-tier feature there is no protected line", () => {
+ renderCallout(
+ { type: "some", environments: ["environments/prod"] },
+ { hasEnvTierFeature: false }
+ );
+ expect(screen.queryByText(/direct-execution\.protected/)).toBeNull();
+ });
+
+ test("some: a name the list no longer has still gets a chip", () => {
+ renderCallout({ type: "some", environments: ["environments/gone"] });
+ expect(chips()).toEqual(["environments/gone"]);
+ expect(screen.queryByText(/direct-execution\.protected/)).toBeNull();
+ });
+
+ test("some: each lead renders its own sentence; the approver lead names the grantee", () => {
+ const scope: DirectExecutionScope = {
+ type: "some",
+ environments: ["environments/staging"],
+ };
+ const { rerender } = renderCallout(scope, { lead: "request" });
+ expect(screen.getByText(/lead-request/)).toBeTruthy();
+ rerender(
+ <DirectExecutionCallout
+ kind="DML"
+ lead="approver"
+ grantee="Alex Kim"
+ scope={scope}
+ environmentList={STUB_ENVIRONMENTS}
+ hasEnvTierFeature
+ />
+ );
+ expect(screen.getByText(/lead-approver/).textContent).toContain(
+ '"grantee":"Alex Kim"'
+ );
+ });
+
+ test("none: one sentence for every surface, no chips", () => {
+ renderCallout({ type: "none" });
+ expect(screen.getByText(/direct-execution\.none/)).toBeTruthy();
+ expect(screen.queryByTestId("env-label")).toBeNull();
+ });
+
+ test("all: the unscoped sentence, no chips", () => {
+ renderCallout({ type: "all" });
+ expect(screen.getByText(/direct-execution\.all/)).toBeTruthy();
+ expect(screen.queryByTestId("env-label")).toBeNull();
+ });
+});
diff --git a/frontend/src/components/role-grant/DirectExecutionCallout.tsx b/frontend/src/components/role-grant/DirectExecutionCallout.tsx
new file mode 100644
index 0000000000..054f351382
--- /dev/null
+++ b/frontend/src/components/role-grant/DirectExecutionCallout.tsx
@@ -0,0 +1,111 @@
+import { useTranslation } from "react-i18next";
+import { EnvironmentBadge } from "@/components/EnvironmentLabel";
+import { Alert } from "@/components/ui/alert";
+import type { DirectExecutionScope } from "@/lib/project-member/directExecution";
+import type { EnvLimitationKind } from "@/lib/project-member/utils";
+import {
+ type Environment,
+ isProtectedEnvironment,
+ resolveEnvironment,
+} from "@/types/v1/environment";
+import { formatList } from "@/utils/string";
+
+/** Who the sentence is about: the surface picks the lead. */
+export type DirectExecutionLead = "grant" | "request" | "approver" | "binding";
+
+/** The approver lead names the grantee; no other lead takes a name. */
+type DirectExecutionLeadProps =
+ | { lead: "approver"; grantee: string }
+ | { lead: Exclude<DirectExecutionLead, "approver">; grantee?: undefined };
+
+/**
+ * Hook-free, like the badge it renders: a member's drawer shows one callout
+ * per binding, so the environment list and the tier feature are read once by
+ * the surface and handed down.
+ */
+export function DirectExecutionCallout({
+ kind,
+ scope,
+ environmentList,
+ hasEnvTierFeature,
+ ...leadProps
+}: {
+ kind: EnvLimitationKind;
+ scope: DirectExecutionScope;
+ environmentList: Environment[];
+ hasEnvTierFeature: boolean;
+} & DirectExecutionLeadProps) {
+ const { t, i18n } = useTranslation();
+
+ // Literal keys per lead so the i18n check can see every key in use.
+ const leadText = (): string => {
+ switch (leadProps.lead) {
+ case "grant":
+ return t("project.members.direct-execution.lead-grant", { kind });
+ case "request":
+ return t("project.members.direct-execution.lead-request", { kind });
+ case "approver":
+ return t("project.members.direct-execution.lead-approver", {
+ kind,
+ grantee: leadProps.grantee,
+ });
+ case "binding":
+ return t("project.members.direct-execution.lead-binding", { kind });
+ }
+ };
+
+ switch (scope.type) {
+ case "none":
+ // Info, not warning: nothing is allowed, so there is no risk to surface.
+ return (
+ <Alert variant="info">
+ {t("project.members.direct-execution.none", { kind })}
+ </Alert>
+ );
+ case "all":
+ return (
+ <Alert variant="warning">
+ {t("project.members.direct-execution.all", { kind })}
+ </Alert>
+ );
+ case "some": {
+ const environments = scope.environments.map((name) =>
+ resolveEnvironment(name, environmentList)
+ );
+ const protectedTitles = environments.flatMap((env) =>
+ isProtectedEnvironment(env, hasEnvTierFeature) ? [env.title] : []
+ );
+ return (
+ <Alert
+ variant="warning"
+ description={
+ <div className="flex flex-col gap-y-1.5">
+ <div className="flex flex-wrap items-center gap-1">
+ <span>{leadText()}</span>
+ {environments.map((env) => (
+ <EnvironmentBadge
+ key={env.name}
+ environment={env}
+ hasEnvTierFeature={hasEnvTierFeature}
+ className="text-xs"
+ />
+ ))}
+ </div>
+ {protectedTitles.length > 0 && (
+ <div>
+ {t("project.members.direct-execution.protected", {
+ count: protectedTitles.length,
+ environments: formatList(
+ protectedTitles,
+ i18n.resolvedLanguage ?? "en-US"
+ ),
+ })}
+ </div>
+ )}
+ </div>
+ }
+ />
+ );
+ }
+ }
+}
diff --git a/frontend/src/components/role-grant/DirectExecutionField.test.tsx b/frontend/src/components/role-grant/DirectExecutionField.test.tsx
new file mode 100644
index 0000000000..5931950794
--- /dev/null
+++ b/frontend/src/components/role-grant/DirectExecutionField.test.tsx
@@ -0,0 +1,118 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { DirectExecutionField } from "./DirectExecutionField";
+import type { DirectExecutionValue } from "@/lib/project-member/directExecution";
+
+vi.mock("react-i18next", async () =>
+ (await import("@/test-utils/i18n")).reactI18nextStub()
+);
+
+const featureRef = vi.hoisted(() => ({ on: true }));
+vi.mock("@/hooks/useAppState", () => ({
+ useEnvironmentList: () => [],
+ usePlanFeature: () => featureRef.on,
+}));
+
+afterEach(() => {
+ featureRef.on = true;
+});
+
+vi.mock("@/components/EnvironmentSelect", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentSelectStub()
+);
+
+vi.mock("./DirectExecutionCallout", () => ({
+ DirectExecutionCallout: ({
+ scope,
+ }: {
+ scope: { type: string; environments?: string[] };
+ }) => (
+ <div
+ data-testid="callout"
+ data-scope={scope.type}
+ data-envs={scope.environments?.join(",")}
+ />
+ ),
+}));
+
+const renderField = (value: DirectExecutionValue, onChange = vi.fn()) => {
+ render(
+ <DirectExecutionField
+ kind="DDL/DML"
+ lead="grant"
+ value={value}
+ onChange={onChange}
+ />
+ );
+ return onChange;
+};
+const off: DirectExecutionValue = { enabled: false, environments: [] };
+const onEmpty: DirectExecutionValue = { enabled: true, environments: [] };
+const onStaging: DirectExecutionValue = {
+ enabled: true,
+ environments: ["environments/staging"],
+};
+
+describe("DirectExecutionField", () => {
+ test("off: the caption, no picker, no callout", () => {
+ renderField(off);
+ expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe(
+ "false"
+ );
+ expect(screen.getByText(/direct-execution\.none/).textContent).toContain(
+ '"kind":"DDL/DML"'
+ );
+ expect(screen.queryByTestId("env-multi-select")).toBeNull();
+ expect(screen.queryByTestId("callout")).toBeNull();
+ });
+
+ test("turning the switch on reports enabled and keeps the list", () => {
+ const onChange = renderField({
+ enabled: false,
+ environments: ["environments/staging"],
+ });
+ fireEvent.click(screen.getByRole("switch"));
+ expect(onChange).toHaveBeenCalledWith(onStaging);
+ });
+
+ test("on with nothing picked: the picker, the adjacent error, no callout", () => {
+ renderField(onEmpty);
+ expect(screen.getByTestId("env-multi-select")).toBeTruthy();
+ expect(screen.getByText(/select-environments/)).toBeTruthy();
+ expect(screen.getByText(/environment-required/)).toBeTruthy();
+ expect(screen.queryByTestId("callout")).toBeNull();
+ expect(screen.queryByText(/direct-execution\.none/)).toBeNull();
+ });
+
+ test("on with a pick: the callout for the picked list, no error", () => {
+ renderField(onStaging);
+ expect(screen.queryByText(/environment-required/)).toBeNull();
+ const callout = screen.getByTestId("callout");
+ expect(callout.getAttribute("data-scope")).toBe("some");
+ expect(callout.getAttribute("data-envs")).toBe("environments/staging");
+ });
+
+ test("the field is controlled: picks are reported, never applied", () => {
+ const onChange = renderField(onEmpty);
+ fireEvent.click(screen.getByTestId("pick-staging"));
+ expect(onChange).toHaveBeenCalledWith(onStaging);
+ expect(screen.getByTestId("env-multi-select").getAttribute("data-value")).toBe(
+ ""
+ );
+ });
+
+ test("on: the picker flags the protected environment when the plan has tiers", () => {
+ renderField(onStaging);
+ const tags = screen.getAllByText(/direct-execution\.protected-tag/);
+ expect(tags).toHaveLength(1);
+ expect(
+ tags[0].closest("[data-testid='env-option']")?.textContent
+ ).toContain("Prod");
+ });
+
+ test("on: without environment tiers no row is flagged", () => {
+ featureRef.on = false;
+ renderField(onStaging);
+ expect(screen.queryByText(/direct-execution\.protected-tag/)).toBeNull();
+ });
+});
diff --git a/frontend/src/components/role-grant/DirectExecutionField.tsx b/frontend/src/components/role-grant/DirectExecutionField.tsx
new file mode 100644
index 0000000000..fabf508747
--- /dev/null
+++ b/frontend/src/components/role-grant/DirectExecutionField.tsx
@@ -0,0 +1,101 @@
+import { useCallback, useId } from "react";
+import { useTranslation } from "react-i18next";
+import { EnvironmentSelect } from "@/components/EnvironmentSelect";
+import { Badge } from "@/components/ui/badge";
+import { FormError, FormField } from "@/components/ui/form";
+import { Switch } from "@/components/ui/switch";
+import { useEnvironmentList, usePlanFeature } from "@/hooks/useAppState";
+import type { DirectExecutionValue } from "@/lib/project-member/directExecution";
+import type { EnvLimitationKind } from "@/lib/project-member/utils";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import {
+ type Environment,
+ isProtectedEnvironment,
+} from "@/types/v1/environment";
+import {
+ DirectExecutionCallout,
+ type DirectExecutionLead,
+} from "./DirectExecutionCallout";
+
+export function DirectExecutionField({
+ kind,
+ lead,
+ value,
+ onChange,
+}: {
+ kind: EnvLimitationKind;
+ lead: Extract<DirectExecutionLead, "grant" | "request">;
+ value: DirectExecutionValue;
+ onChange: (next: DirectExecutionValue) => void;
+}) {
+ const { t } = useTranslation();
+ const labelId = useId();
+ const hasEnvTierFeature = usePlanFeature(
+ PlanFeature.FEATURE_ENVIRONMENT_TIERS
+ );
+ const environmentList = useEnvironmentList();
+ const { enabled, environments } = value;
+ // Stable so the picker's option memo survives the form's re-renders.
+ const renderProtectedTag = useCallback(
+ (environment: Environment) =>
+ isProtectedEnvironment(environment, hasEnvTierFeature) ? (
+ <Badge variant="warning">
+ {t("project.members.direct-execution.protected-tag")}
+ </Badge>
+ ) : null,
+ [hasEnvTierFeature, t]
+ );
+
+ return (
+ <FormField
+ title={<>{t("project.members.direct-execution.title", { kind })}</>}
+ >
+ <div className="flex items-center gap-x-2">
+ <Switch
+ checked={enabled}
+ onCheckedChange={(checked) =>
+ onChange({ enabled: checked, environments })
+ }
+ aria-labelledby={labelId}
+ />
+ <span id={labelId} className="text-sm leading-5">
+ {t("project.members.direct-execution.switch-label", { kind })}
+ </span>
+ </div>
+ {enabled ? (
+ <div className="flex flex-col gap-y-1.5 pt-2">
+ <span className="text-sm font-medium leading-5">
+ {t("project.members.direct-execution.in-environments")}
+ </span>
+ <EnvironmentSelect
+ multiple
+ portal
+ value={environments}
+ onChange={(next) => onChange({ enabled, environments: next })}
+ placeholder={t(
+ "project.members.direct-execution.select-environments"
+ )}
+ renderSuffix={renderProtectedTag}
+ />
+ {environments.length === 0 ? (
+ <FormError>
+ {t("project.members.direct-execution.environment-required")}
+ </FormError>
+ ) : (
+ <DirectExecutionCallout
+ kind={kind}
+ lead={lead}
+ scope={{ type: "some", environments }}
+ environmentList={environmentList}
+ hasEnvTierFeature={hasEnvTierFeature}
+ />
+ )}
+ </div>
+ ) : (
+ <p className="text-xs leading-4 text-control-light">
+ {t("project.members.direct-execution.none", { kind })}
+ </p>
+ )}
+ </FormField>
+ );
+}
diff --git a/frontend/src/components/role-grant/RoleDescription.tsx b/frontend/src/components/role-grant/RoleDescription.tsx
new file mode 100644
index 0000000000..cd820ffb63
--- /dev/null
+++ b/frontend/src/components/role-grant/RoleDescription.tsx
@@ -0,0 +1,19 @@
+import { displayRoleDescriptionFromList } from "@/lib/role";
+import type { Role } from "@/types/proto-es/v1/role_service_pb";
+
+/** The selected role's description, under a role select or a role title. */
+export function RoleDescription({
+ role,
+ roleList,
+}: {
+ role: string;
+ roleList: Role[];
+}) {
+ const description = role
+ ? displayRoleDescriptionFromList(role, roleList)
+ : undefined;
+ if (!description) {
+ return null;
+ }
+ return <p className="text-xs leading-4 text-control-light">{description}</p>;
+}
diff --git a/frontend/src/components/ui/combobox.test.tsx b/frontend/src/components/ui/combobox.test.tsx
index 8ae73213cf..2905f55412 100644
--- a/frontend/src/components/ui/combobox.test.tsx
+++ b/frontend/src/components/ui/combobox.test.tsx
@@ -80,7 +80,10 @@ describe("Combobox", () => {
const option = Array.from(dropdown?.querySelectorAll("button") ?? []).find(
(button) => button.textContent?.includes("Alpha")
);
- expect(option?.parentElement?.parentElement?.className).toContain("px-2");
+ // The option sits in a group inside the listbox, inside the padded body.
+ expect(option?.closest("[role='listbox']")?.parentElement?.className).toContain(
+ "px-2"
+ );
act(() => {
root.unmount();
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx
index 0e0a404be8..19be1a7284 100644
--- a/frontend/src/components/ui/combobox.tsx
+++ b/frontend/src/components/ui/combobox.tsx
@@ -341,6 +341,8 @@ export function Combobox(props: ComboboxProps) {
<button
key={option.value}
type="button"
+ role="option"
+ aria-selected={isSelected}
disabled={option.disabled}
data-selected={isSelected || undefined}
className={cn(
@@ -414,26 +416,39 @@ export function Combobox(props: ComboboxProps) {
className="h-7"
/>
<div className="px-2 pb-2">
- {filteredGroups.every((g) => g.options.length === 0) ? (
- noResultsContent !== undefined ? (
- <div className="p-3">{noResultsContent}</div>
+ <div
+ role="listbox"
+ aria-label={placeholder || undefined}
+ aria-multiselectable={multiple || undefined}
+ >
+ {filteredGroups.every((g) => g.options.length === 0) ? (
+ noResultsContent !== undefined ? (
+ <div className="p-3">{noResultsContent}</div>
+ ) : (
+ <div className="px-3 py-6 text-sm text-control-placeholder text-center">
+ {noResultsText ?? "—"}
+ </div>
+ )
) : (
- <div className="px-3 py-6 text-sm text-control-placeholder text-center">
- {noResultsText ?? "—"}
- </div>
- )
- ) : (
- filteredGroups.map((group) => (
- <div key={group.label}>
- {group.label && (
- <div className="px-3 py-1.5 text-xs font-medium text-control-light uppercase tracking-wide bg-control-bg">
- {group.label}
- </div>
- )}
- {group.options.map(renderOptionRow)}
- </div>
- ))
- )}
+ filteredGroups.map((group) => (
+ <div
+ key={group.label}
+ role={group.label ? "group" : undefined}
+ aria-label={group.label || undefined}
+ >
+ {group.label && (
+ <div
+ role="presentation"
+ className="px-3 py-1.5 text-xs font-medium text-control-light uppercase tracking-wide bg-control-bg"
+ >
+ {group.label}
+ </div>
+ )}
+ {group.options.map(renderOptionRow)}
+ </div>
+ ))
+ )}
+ </div>
{hasMore && onLoadMore && (
<Button
type="button"
diff --git a/frontend/src/hooks/useAppState.ts b/frontend/src/hooks/useAppState.ts
index e591395eed..b3001bb4d0 100644
--- a/frontend/src/hooks/useAppState.ts
+++ b/frontend/src/hooks/useAppState.ts
@@ -10,12 +10,7 @@ import type { AppFeatures } from "@/types/appProfile";
import type { Permission } from "@/types/iam/permission";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import {
- isValidEnvironmentName,
- NULL_ENVIRONMENT_NAME,
- nullEnvironment,
- unknownEnvironment,
-} from "@/types/v1/environment";
+import { resolveEnvironment } from "@/types/v1/environment";
import { isValidProjectName } from "@/types/v1/project";
import { unknownUser } from "@/types/v1/user";
import {
@@ -207,25 +202,10 @@ export function useEnvironmentList() {
export function useEnvironment(name: string | undefined) {
const environmentList = useEnvironmentList();
- return useMemo(() => {
- if (!name || name === NULL_ENVIRONMENT_NAME) {
- return nullEnvironment();
- }
- const environment = environmentList.find((env) => env.name === name);
- if (environment) {
- return environment;
- }
- if (!isValidEnvironmentName(name)) {
- return unknownEnvironment();
- }
- const id = name.replace(/^environments\//, "");
- return {
- ...unknownEnvironment(),
- id,
- name,
- title: id,
- };
- }, [environmentList, name]);
+ return useMemo(
+ () => resolveEnvironment(name ?? "", environmentList),
+ [environmentList, name]
+ );
}
export function usePlanFeature(feature: PlanFeature) {
diff --git a/frontend/src/lib/project-member/directExecution.test.ts b/frontend/src/lib/project-member/directExecution.test.ts
new file mode 100644
index 0000000000..17f34ca3d6
--- /dev/null
+++ b/frontend/src/lib/project-member/directExecution.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment node
+import { describe, expect, test, vi } from "vitest";
+import {
+ directExecutionEnvironments,
+ directExecutionOf,
+ EMPTY_DIRECT_EXECUTION,
+ isDirectExecutionValid,
+} from "./directExecution";
+
+vi.mock("./utils", () => ({
+ getRoleEnvironmentLimitationKind: (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
+}));
+
+const scopeOf = (condition?: {
+ environments?: string[];
+ expiredTime?: string;
+}) => directExecutionOf("roles/sqlEditorUser", condition)?.scope;
+
+describe("directExecutionOf", () => {
+ test("a role without DDL/DML has nothing to show", () => {
+ expect(
+ directExecutionOf("roles/viewer", { environments: [] })
+ ).toBeUndefined();
+ });
+
+ test("no condition, or one without an environment clause, is unscoped", () => {
+ expect(scopeOf(undefined)).toEqual({ type: "all" });
+ expect(scopeOf({ expiredTime: "2026-10-01" })).toEqual({ type: "all" });
+ });
+
+ test("an empty list is the switch off; a list is the switch on, in order", () => {
+ expect(scopeOf({ environments: [] })).toEqual({ type: "none" });
+ expect(
+ scopeOf({ environments: ["environments/staging", "environments/prod"] })
+ ).toEqual({
+ type: "some",
+ environments: ["environments/staging", "environments/prod"],
+ });
+ expect(directExecutionOf("roles/sqlEditorUser", undefined)?.kind).toBe(
+ "DDL/DML"
+ );
+ });
+});
+
+describe("the form value", () => {
+ test("only on-with-nothing-picked is invalid", () => {
+ expect(isDirectExecutionValid(EMPTY_DIRECT_EXECUTION)).toBe(true);
+ expect(isDirectExecutionValid({ enabled: true, environments: [] })).toBe(
+ false
+ );
+ expect(
+ isDirectExecutionValid({
+ enabled: true,
+ environments: ["environments/prod"],
+ })
+ ).toBe(true);
+ });
+
+ test("off always submits the empty list; on submits the picked list", () => {
+ expect(
+ directExecutionEnvironments({
+ enabled: false,
+ environments: ["environments/prod"],
+ })
+ ).toEqual([]);
+ expect(
+ directExecutionEnvironments({
+ enabled: true,
+ environments: ["environments/prod"],
+ })
+ ).toEqual(["environments/prod"]);
+ });
+});
diff --git a/frontend/src/lib/project-member/directExecution.ts b/frontend/src/lib/project-member/directExecution.ts
new file mode 100644
index 0000000000..288df7214b
--- /dev/null
+++ b/frontend/src/lib/project-member/directExecution.ts
@@ -0,0 +1,62 @@
+import type { ConditionExpression } from "@/utils/issue/cel";
+import {
+ type EnvLimitationKind,
+ getRoleEnvironmentLimitationKind,
+} from "./utils";
+
+/**
+ * Where a role assignment lets its members run DDL/DML in SQL Editor without
+ * approval. `all` is a condition with no environment clause, as the workspace
+ * member sheet writes.
+ */
+export type DirectExecutionScope =
+ | { type: "some"; environments: string[] }
+ | { type: "none" }
+ | { type: "all" };
+
+const directExecutionScopeFromCondition = (
+ condition: ConditionExpression | undefined
+): DirectExecutionScope => {
+ if (condition?.environments === undefined) {
+ return { type: "all" };
+ }
+ if (condition.environments.length === 0) {
+ return { type: "none" };
+ }
+ return { type: "some", environments: condition.environments };
+};
+
+/**
+ * The form's view of the field. `enabled` is kept beside the list rather
+ * than derived from it: off and on-with-nothing-picked serialize to the
+ * same empty clause, and only the form knows which one the reader meant.
+ */
+export interface DirectExecutionValue {
+ enabled: boolean;
+ environments: string[];
+}
+
+export const EMPTY_DIRECT_EXECUTION: DirectExecutionValue = {
+ enabled: false,
+ environments: [],
+};
+
+export const isDirectExecutionValid = (value: DirectExecutionValue): boolean =>
+ !value.enabled || value.environments.length > 0;
+
+/** What the binding's environment clause should carry; off is the empty list. */
+export const directExecutionEnvironments = (
+ value: DirectExecutionValue
+): string[] => (value.enabled ? value.environments : []);
+
+// What a role's binding lets its members run directly, from the environments
+// its condition proves (`readableCondition`).
+export const directExecutionOf = (
+ role: string,
+ condition: ConditionExpression | undefined
+): { kind: EnvLimitationKind; scope: DirectExecutionScope } | undefined => {
+ const kind = getRoleEnvironmentLimitationKind(role);
+ return kind
+ ? { kind, scope: directExecutionScopeFromCondition(condition) }
+ : undefined;
+};
diff --git a/frontend/src/lib/project-member/utils.test.ts b/frontend/src/lib/project-member/utils.test.ts
index fa57344ee5..9c5f143b97 100644
--- a/frontend/src/lib/project-member/utils.test.ts
+++ b/frontend/src/lib/project-member/utils.test.ts
@@ -1,6 +1,9 @@
// @vitest-environment node
import { describe, expect, test, vi } from "vitest";
-import { getRoleEnvironmentLimitationKind } from "./utils";
+import {
+ getRoleEnvironmentLimitationKind,
+ getRolesEnvironmentLimitationKind,
+} from "./utils";
const fixtures: Record<string, string[]> = {
"roles/sqlEditorUser": ["bb.sql.ddl", "bb.sql.dml"],
@@ -10,27 +13,12 @@ const fixtures: Record<string, string[]> = {
"roles/projectViewer": [],
};
vi.mock("@/stores/app", () => ({
- useAppStore: Object.assign(
- (selector: (state: unknown) => unknown) =>
- selector({
- getRoleByName: (role: string) =>
- fixtures[role] === undefined
- ? undefined
- : { name: role, permissions: fixtures[role] },
- }),
- {
- getState: () => ({
- getRoleByName: (role: string) =>
- fixtures[role] === undefined
- ? undefined
- : { name: role, permissions: fixtures[role] },
- }),
- }
- ),
+ useAppStore: { getState: () => ({ roleList: [] }) },
}));
vi.mock("@/utils", () => ({
displayRoleTitle: (r: string) => r,
- checkRoleContainsAnyPermission: () => false,
+ checkRoleContainsAnyPermission: (role: string, ...permissions: string[]) =>
+ permissions.some((permission) => fixtures[role]?.includes(permission)),
}));
describe("getRoleEnvironmentLimitationKind", () => {
@@ -62,3 +50,30 @@ describe("getRoleEnvironmentLimitationKind", () => {
).toBeUndefined();
});
});
+
+describe("getRolesEnvironmentLimitationKind", () => {
+ test("unions the roles' permissions", () => {
+ expect(
+ getRolesEnvironmentLimitationKind([
+ "roles/sqlEditorDDLOnly",
+ "roles/sqlEditorDMLOnly",
+ ])
+ ).toBe("DDL/DML");
+ expect(getRolesEnvironmentLimitationKind(["roles/sqlEditorDDLOnly"])).toBe(
+ "DDL"
+ );
+ });
+
+ test("ignores roles without the permissions and unknown roles", () => {
+ expect(
+ getRolesEnvironmentLimitationKind(["roles/queryOnly", "roles/missing"])
+ ).toBeUndefined();
+ expect(getRolesEnvironmentLimitationKind([])).toBeUndefined();
+ expect(
+ getRolesEnvironmentLimitationKind([
+ "roles/missing",
+ "roles/sqlEditorUser",
+ ])
+ ).toBe("DDL/DML");
+ });
+});
diff --git a/frontend/src/lib/project-member/utils.ts b/frontend/src/lib/project-member/utils.ts
index fdae14162e..28b960bb05 100644
--- a/frontend/src/lib/project-member/utils.ts
+++ b/frontend/src/lib/project-member/utils.ts
@@ -1,5 +1,6 @@
import { displayRoleTitleFromList } from "@/lib/role";
import { useAppStore } from "@/stores/app";
+import type { Permission } from "@/types/iam";
import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import { checkRoleContainsAnyPermission } from "@/utils";
@@ -27,17 +28,21 @@ export const roleHasDatabaseLimitation = (role: string) => {
// {{kind}} is spliced raw into translated strings — do not localize.
export type EnvLimitationKind = "DDL" | "DML" | "DDL/DML";
-// undefined ⇔ role has no env-scoped permissions ⇔ caller hides the env section.
-// Reads the role once (vs. two checkRoleContainsAnyPermission calls) so the
-// hot path on member-list / drawer renders touches the role store once.
+// undefined ⇔ the role carries no DDL/DML permission ⇔ no direct-execution
+// field, callout, or row to show.
export const getRoleEnvironmentLimitationKind = (
role: string
+): EnvLimitationKind | undefined => getRolesEnvironmentLimitationKind([role]);
+
+// Roles granted together carry the union of their permissions; unknown roles
+// contribute nothing.
+export const getRolesEnvironmentLimitationKind = (
+ roles: string[]
): EnvLimitationKind | undefined => {
- const r = useAppStore.getState().getRoleByName(role);
- if (!r) return undefined;
- const perms = new Set(r.permissions);
- const hasDDL = perms.has("bb.sql.ddl");
- const hasDML = perms.has("bb.sql.dml");
+ const has = (permission: Permission) =>
+ roles.some((role) => checkRoleContainsAnyPermission(role, permission));
+ const hasDDL = has("bb.sql.ddl");
+ const hasDML = has("bb.sql.dml");
if (hasDDL && hasDML) return "DDL/DML";
if (hasDDL) return "DDL";
if (hasDML) return "DML";
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index b8d70a1794..8f2e70fdfd 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1533,8 +1533,11 @@
"all-databases": "All databases",
"all-databases-tip": "All current and future databases in this project.",
"details": "Role grant details",
+ "direct-execution-suffix": "{{kind}} without approval in {{environments}}",
"expired-at": "Expired at",
+ "grantee": "Grantee",
"manually-select": "Manually select",
+ "requested-by": "Requested by {{creator}}",
"use-cel": "Use CEL Expression"
},
"sort": {
@@ -2016,11 +2019,23 @@
"self": "Masking Exemptions"
},
"members": {
- "ddl-current-all": "{{kind}} statements can be directly run in SQL Editor in ALL environments without approval.",
- "ddl-current-none": "{{kind}} statements require approval before running in SQL Editor.",
- "ddl-current-some": "{{kind}} statements can be directly run in SQL Editor in the listed environments without approval.",
- "ddl-warning": "In the selected environments, {{kind}} statements can be directly run in SQL Editor without approval.",
"description": "Project members determine the permission to operate database and issues inside the project. Project Owner, Workspace Admin and Workspace DBA all have full project permissions.",
+ "direct-execution": {
+ "all": "Can run {{kind}} in SQL Editor in every environment without approval.",
+ "environment-required": "At least one environment is required.",
+ "in-environments": "In these environments",
+ "lead-approver": "Approving lets {{grantee}} run {{kind}} in SQL Editor without approval in:",
+ "lead-binding": "Can run {{kind}} in SQL Editor without approval in:",
+ "lead-grant": "Members with this role can run {{kind}} in SQL Editor without approval in:",
+ "lead-request": "Once approved, you can run {{kind}} in SQL Editor without approval in:",
+ "none": "{{kind}} cannot run in SQL Editor without approval.",
+ "protected-tag": "Production environment",
+ "protected_one": "{{environments}} is a production environment.",
+ "protected_other": "{{environments}} are production environments.",
+ "select-environments": "Select environments",
+ "switch-label": "Allow running {{kind}} in SQL Editor without approval",
+ "title": "Direct {{kind}} execution"
+ },
"edit-member": "Edit member - {{member}}",
"expiration-presets": {
"one-month": "1 month",
@@ -2278,7 +2293,7 @@
"self": "SQL Editor Read User"
},
"sql-editor-user": {
- "description": "Permissions for querying database data.",
+ "description": "Query data, and run DDL/DML in allowed environments.",
"self": "SQL Editor User"
},
"title": "Title",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 6ca550a655..debbd28c98 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1533,8 +1533,11 @@
"all-databases": "todas las bases de datos",
"all-databases-tip": "Todas las bases de datos actuales y futuras de este proyecto.",
"details": "Detalles de la concesión de rol",
+ "direct-execution-suffix": "{{kind}} sin aprobación en {{environments}}",
"expired-at": "Expiró el",
+ "grantee": "Beneficiario",
"manually-select": "selección manual",
+ "requested-by": "Solicitado por {{creator}}",
"use-cel": "Usar expresión CEL"
},
"sort": {
@@ -2016,11 +2019,23 @@
"self": "Exenciones de Enmascaramiento"
},
"members": {
- "ddl-current-all": "Las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL en TODOS los entornos sin aprobación.",
- "ddl-current-none": "Las sentencias {{kind}} requieren aprobación antes de ejecutarse en el editor SQL.",
- "ddl-current-some": "Las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL en los entornos listados sin aprobación.",
- "ddl-warning": "En los entornos seleccionados, las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL sin aprobación.",
"description": "Los miembros del proyecto determinan el permiso para operar la base de datos y los problemas dentro del proyecto. El propietario del proyecto, el administrador del espacio de trabajo y el DBA del espacio de trabajo tienen permisos completos para el proyecto.",
+ "direct-execution": {
+ "all": "Puede ejecutar {{kind}} en el editor SQL en todos los entornos sin aprobación.",
+ "environment-required": "Se requiere al menos un entorno.",
+ "in-environments": "En estos entornos",
+ "lead-approver": "Al aprobar, {{grantee}} podrá ejecutar {{kind}} en el editor SQL sin aprobación en:",
+ "lead-binding": "Puede ejecutar {{kind}} en el editor SQL sin aprobación en:",
+ "lead-grant": "Los miembros con este rol pueden ejecutar {{kind}} en el editor SQL sin aprobación en:",
+ "lead-request": "Una vez aprobado, podrás ejecutar {{kind}} en el editor SQL sin aprobación en:",
+ "none": "{{kind}} no puede ejecutarse en el editor SQL sin aprobación.",
+ "protected-tag": "Entorno de producción",
+ "protected_one": "{{environments}} es un entorno de producción.",
+ "protected_other": "{{environments}} son entornos de producción.",
+ "select-environments": "Seleccionar entornos",
+ "switch-label": "Permitir ejecutar {{kind}} en el editor SQL sin aprobación",
+ "title": "Ejecución directa de {{kind}}"
+ },
"edit-member": "Editar miembro - {{member}}",
"expiration-presets": {
"one-month": "1 mes",
@@ -2278,7 +2293,7 @@
"self": "Usuario de solo lectura del editor SQL"
},
"sql-editor-user": {
- "description": "El consultor del proyecto tiene todos los permisos dentro del proyecto, excepto la gestión de miembros del proyecto.",
+ "description": "Consulta datos y ejecuta DDL/DML en los entornos permitidos.",
"self": "Usuario del editor SQL"
},
"title": "Título",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index dcab0dfb32..df0ea50f73 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1533,8 +1533,11 @@
"all-databases": "すべてのデータベース",
"all-databases-tip": "このプロジェクトに属する現在および将来のすべてのデータベース。",
"details": "ロール付与の詳細",
+ "direct-execution-suffix": "{{environments}} で承認なしに {{kind}} を実行",
"expired-at": "有効期限",
+ "grantee": "付与先",
"manually-select": "手動選択",
+ "requested-by": "{{creator}} による申請",
"use-cel": "CEL式を使用"
},
"sort": {
@@ -2016,11 +2019,23 @@
"self": "マスキング免除"
},
"members": {
- "ddl-current-all": "すべての(ALL)環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
- "ddl-current-none": "{{kind}} ステートメントを SQL エディターで実行するには承認が必要です。",
- "ddl-current-some": "リストされた環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
- "ddl-warning": "選択した環境では、{{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
"description": "プロジェクトメンバーのロールにより、プロジェクト内のデータベースとイシューを操作するための権限が決まります。プロジェクト所有者、ワークスペース管理者、および DBA はすべて、プロジェクトに対する完全な権限を持っています。",
+ "direct-execution": {
+ "all": "すべての環境で SQL エディターから承認なしに {{kind}} を実行できます。",
+ "environment-required": "環境を 1 つ以上選択してください。",
+ "in-environments": "対象の環境",
+ "lead-approver": "承認すると、{{grantee}} は SQL エディターで承認なしに {{kind}} を実行できます。対象:",
+ "lead-binding": "SQL エディターで承認なしに {{kind}} を実行できます。対象:",
+ "lead-grant": "このロールを持つメンバーは SQL エディターで承認なしに {{kind}} を実行できます。対象:",
+ "lead-request": "承認されると、SQL エディターで承認なしに {{kind}} を実行できます。対象:",
+ "none": "{{kind}} は承認なしには SQL エディターで実行できません。",
+ "protected-tag": "本番環境",
+ "protected_one": "{{environments}} は本番環境です。",
+ "protected_other": "{{environments}} は本番環境です。",
+ "select-environments": "環境を選択",
+ "switch-label": "SQL エディターで承認なしに {{kind}} を実行することを許可する",
+ "title": "{{kind}} の直接実行"
+ },
"edit-member": "メンバー編集 - {{member}}",
"expiration-presets": {
"one-month": "1か月",
@@ -2278,7 +2293,7 @@
"self": "SQLエディタ読み取り専用ユーザー"
},
"sql-editor-user": {
- "description": "指定した範囲内のデータをクエリできます。",
+ "description": "データを照会し、許可された環境で DDL/DML を実行できます。",
"self": "SQLエディタのユーザー"
},
"title": "タイトル",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 82611e7385..0bfc985b07 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1533,8 +1533,11 @@
"all-databases": "Tất cả cơ sở dữ liệu",
"all-databases-tip": "Tất cả cơ sở dữ liệu hiện tại và tương lai trong dự án này.",
"details": "Chi tiết cấp vai trò",
+ "direct-execution-suffix": "{{kind}} không cần phê duyệt tại {{environments}}",
"expired-at": "Hết hạn lúc",
+ "grantee": "Người được cấp",
"manually-select": "Chọn thủ công",
+ "requested-by": "Được yêu cầu bởi {{creator}}",
"use-cel": "Sử dụng biểu thức CEL"
},
"sort": {
@@ -2016,11 +2019,23 @@
"self": "Miễn trừ Che giấu"
},
"members": {
- "ddl-current-all": "Câu lệnh {{kind}} có thể được chạy trực tiếp trong SQL Editor ở TẤT CẢ các môi trường mà không cần phê duyệt.",
- "ddl-current-none": "Câu lệnh {{kind}} cần được phê duyệt trước khi chạy trong SQL Editor.",
- "ddl-current-some": "Câu lệnh {{kind}} có thể được chạy trực tiếp trong SQL Editor ở các môi trường được liệt kê mà không cần phê duyệt.",
- "ddl-warning": "Trong các môi trường đã chọn, câu lệnh {{kind}} có thể được chạy trực tiếp trong SQL Editor mà không cần phê duyệt.",
"description": "Thành viên dự án xác định quyền để vận hành cơ sở dữ liệu và các vấn đề bên trong dự án. Chủ sở hữu dự án, Quản trị viên không gian làm việc và DBA không gian làm việc đều có toàn quyền dự án.",
+ "direct-execution": {
+ "all": "Có thể chạy {{kind}} trong SQL Editor ở mọi môi trường mà không cần phê duyệt.",
+ "environment-required": "Cần chọn ít nhất một môi trường.",
+ "in-environments": "Trong các môi trường sau",
+ "lead-approver": "Khi phê duyệt, {{grantee}} có thể chạy {{kind}} trong SQL Editor mà không cần phê duyệt tại:",
+ "lead-binding": "Có thể chạy {{kind}} trong SQL Editor mà không cần phê duyệt tại:",
+ "lead-grant": "Thành viên có vai trò này có thể chạy {{kind}} trong SQL Editor mà không cần phê duyệt tại:",
+ "lead-request": "Sau khi được phê duyệt, bạn có thể chạy {{kind}} trong SQL Editor mà không cần phê duyệt tại:",
+ "none": "{{kind}} không thể chạy trong SQL Editor nếu không được phê duyệt.",
+ "protected-tag": "Môi trường sản xuất",
+ "protected_one": "{{environments}} là môi trường sản xuất.",
+ "protected_other": "{{environments}} là môi trường sản xuất.",
+ "select-environments": "Chọn môi trường",
+ "switch-label": "Cho phép chạy {{kind}} trong SQL Editor mà không cần phê duyệt",
+ "title": "Chạy trực tiếp {{kind}}"
+ },
"edit-member": "Chỉnh sửa thành viên - {{member}}",
"expiration-presets": {
"one-month": "1 tháng",
@@ -2278,7 +2293,7 @@
"self": "Người dùng Trình soạn thảo SQL chỉ đọc"
},
"sql-editor-user": {
- "description": "Quyền truy vấn dữ liệu cơ sở dữ liệu.",
+ "description": "Truy vấn dữ liệu và chạy DDL/DML trong các môi trường được phép.",
"self": "Người dùng Trình soạn thảo SQL"
},
"title": "Tiêu đề",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index f706aa0307..741e1cbe25 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1533,8 +1533,11 @@
"all-databases": "所有数据库",
"all-databases-tip": "所有当前和未来属于这个项目的数据库。",
"details": "角色授权详情",
+ "direct-execution-suffix": "在 {{environments}} 免审批执行 {{kind}}",
"expired-at": "过期时间",
+ "grantee": "被授权人",
"manually-select": "手动选择",
+ "requested-by": "由 {{creator}} 申请",
"use-cel": "使用 CEL 表达式"
},
"sort": {
@@ -2016,11 +2019,23 @@
"self": "脱敏豁免"
},
"members": {
- "ddl-current-all": "{{kind}} 语句可在 SQL 编辑器中针对所有(ALL)环境直接执行,无需审批。",
- "ddl-current-none": "{{kind}} 语句在 SQL 编辑器中运行前需要审批。",
- "ddl-current-some": "{{kind}} 语句可在 SQL 编辑器中针对所列环境直接执行,无需审批。",
- "ddl-warning": "在所选环境中,{{kind}} 语句可在 SQL 编辑器中直接执行,无需审批。",
"description": "项目成员角色决定了操作项目中的数据库和工单的权限。项目的所有者,工作空间管理员和 DBA 都具有项目所有的权限。",
+ "direct-execution": {
+ "all": "可在所有环境中免审批在 SQL 编辑器执行 {{kind}}。",
+ "environment-required": "至少需要选择一个环境。",
+ "in-environments": "允许的环境",
+ "lead-approver": "批准后,{{grantee}} 可在 SQL 编辑器中免审批执行 {{kind}},适用环境:",
+ "lead-binding": "可在 SQL 编辑器中免审批执行 {{kind}},适用环境:",
+ "lead-grant": "拥有此角色的成员可在 SQL 编辑器中免审批执行 {{kind}},适用环境:",
+ "lead-request": "批准后,你可在 SQL 编辑器中免审批执行 {{kind}},适用环境:",
+ "none": "{{kind}} 在 SQL 编辑器中需审批后才能执行。",
+ "protected-tag": "生产环境",
+ "protected_one": "{{environments}} 是生产环境。",
+ "protected_other": "{{environments}} 是生产环境。",
+ "select-environments": "选择环境",
+ "switch-label": "允许在 SQL 编辑器中免审批执行 {{kind}}",
+ "title": "{{kind}} 直接执行"
+ },
"edit-member": "编辑成员 - {{member}}",
"expiration-presets": {
"one-month": "1 个月",
@@ -2278,7 +2293,7 @@
"self": "SQL 编辑器只读用户"
},
"sql-editor-user": {
- "description": "可查询指定范围的数据。",
+ "description": "可查询数据,并可在允许的环境中执行 DDL/DML。",
"self": "SQL 编辑器用户"
},
"title": "称谓",
diff --git a/frontend/src/modules/access-control/RequestRoleSheet.test.tsx b/frontend/src/modules/access-control/RequestRoleSheet.test.tsx
index c56309bacf..42619f063e 100644
--- a/frontend/src/modules/access-control/RequestRoleSheet.test.tsx
+++ b/frontend/src/modules/access-control/RequestRoleSheet.test.tsx
@@ -17,10 +17,13 @@ import type { Permission } from "@/types";
// from the app store, which is not worth wiring up for these tests.
// ---------------------------------------------------------------------------
-vi.mock("@/components/EnvironmentSelect", () => ({
- EnvironmentSelect: () =>
- createElement("div", { "data-testid": "env-multi-select" }),
-}));
+vi.mock("@/components/EnvironmentSelect", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentSelectStub()
+);
+
+vi.mock("@/components/EnvironmentLabel", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentBadgeStub()
+);
// ---------------------------------------------------------------------------
// UI primitive mocks — mirror the Task 7/8 test harness so the sheet renders
@@ -111,10 +114,9 @@ vi.mock("@/components/RoleSelect", () => ({
}),
}));
-vi.mock("react-i18next", () => ({
- initReactI18next: { type: "3rdParty", init: () => {} },
- useTranslation: () => ({ t: (key: string) => key }),
-}));
+vi.mock("react-i18next", async () =>
+ (await import("@/test-utils/i18n")).reactI18nextStub()
+);
// ---------------------------------------------------------------------------
// Infra / cross-module mocks
@@ -143,6 +145,9 @@ vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
}));
vi.mock("@/types/proto-es/v1/project_service_pb", () => ({}));
+vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
+ PlanFeature: { FEATURE_ENVIRONMENT_TIERS: "FEATURE_ENVIRONMENT_TIERS" },
+}));
vi.mock("@/app/router", async (importOriginal) => ({
...(await importOriginal<typeof import("@/app/router")>()),
@@ -194,6 +199,13 @@ vi.mock("@/types", () => ({
},
}));
+// `@/types/v1/environment` reaches `setting_service_pb`, whose descriptor
+// needs the real `@bufbuild/protobuf/wkt` this file stubs.
+vi.mock("@/types/proto-es/v1/setting_service_pb", () => ({
+ EnvironmentSetting_EnvironmentSchema: {},
+ Setting_SettingName: { EMAIL: 1 },
+}));
+
// ---------------------------------------------------------------------------
// Store / connect mocks — stable singletons.
// ---------------------------------------------------------------------------
@@ -213,16 +225,23 @@ vi.mock("@/api", () => ({
}));
vi.mock("@/stores", () => ({
+ environmentNamePrefix: "environments/",
pushNotification: (...args: unknown[]) => mocks.pushNotification(...args),
}));
-vi.mock("@/hooks/useAppState", () => ({
- useCurrentUser: () => mocks.currentUser,
-}));
+vi.mock("@/hooks/useAppState", async () => {
+ const { STUB_ENVIRONMENTS } = await import(
+ "@/test-utils/environmentSelectStub"
+ );
+ return {
+ useCurrentUser: () => mocks.currentUser,
+ useEnvironmentList: () => STUB_ENVIRONMENTS,
+ usePlanFeature: () => true,
+ };
+});
-vi.mock("@/stores/app", () => ({
- useAppStore: (selector: (state: unknown) => unknown) =>
- selector({
+vi.mock("@/stores/app", () => {
+ const state = {
roleList: [],
getRoleByName: (name: string) => ({
name,
@@ -241,13 +260,20 @@ vi.mock("@/stores/app", () => ({
? undefined
: { seconds: BigInt(mocks.maximumRequestExpirationSeconds) },
}),
- }),
-}));
+ };
+ return {
+ useAppStore: Object.assign(
+ (selector: (state: unknown) => unknown) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
// ---------------------------------------------------------------------------
// Import SUT after mocks are registered.
// ---------------------------------------------------------------------------
+import { directExecutionDriver } from "@/test-utils/directExecutionDriver";
import { nativeChange } from "@/test-utils/nativeChange";
import { RequestRoleSheet } from "./RequestRoleSheet";
@@ -424,7 +450,7 @@ describe("RequestRoleSheet — enforceIssueTitle (BYT-9310)", () => {
};
// formatIssueTitle sentinel: mock wraps in FMT(...) so if the production
// code drops the formatIssueTitle() call, this assertion fails.
- expect(req.issue.title).toBe("FMT(issue.title.request-specific-role)");
+ expect(req.issue.title).toMatch(/^FMT\(issue\.title\.request-specific-role /);
});
it("blocks stale role submissions when the selected role misses required permissions", async () => {
@@ -440,27 +466,142 @@ describe("RequestRoleSheet — enforceIssueTitle (BYT-9310)", () => {
expect(getSubmitButton().disabled).toBe(false);
});
- it("renders DDL/DML warning under env multiselect when role has env limitation", async () => {
- // Override default helper mock for this case so the env section appears.
- const utilsMock = await import("@/lib/project-member/utils");
- vi.mocked(utilsMock.getRoleEnvironmentLimitationKind).mockImplementation(
- () => "DDL/DML"
- );
+ describe("direct DDL/DML execution", () => {
+ async function useDdlRole(): Promise<void> {
+ const utilsMock = await import("@/lib/project-member/utils");
+ vi.mocked(utilsMock.getRoleEnvironmentLimitationKind).mockImplementation(
+ (role: string) => (role === "roles/sqlEditorUser" ? "DDL/DML" : undefined)
+ );
+ }
+ beforeEach(useDdlRole);
+ const field = directExecutionDriver(flush);
+ function submittedRequest(): {
+ issue: {
+ title: string;
+ roleGrant: { condition: { environments?: string[] } };
+ };
+ } {
+ expect(mocks.createIssue).toHaveBeenCalledTimes(1);
+ return mocks.createIssue.mock.calls[0][0] as never;
+ }
+
+ it("is off by default: caption, no picker, and the empty clause on submit", async () => {
+ await renderSheet(false);
+ await selectRole("roles/sqlEditorUser");
+ await flush();
+
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("false");
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.none"
+ );
+ expect(
+ container.querySelector("[data-testid='env-multi-select']")
+ ).toBeNull();
+ expect(getSubmitButton().disabled).toBe(false);
+
+ await act(async () => {
+ getSubmitButton().click();
+ });
+ await flush();
+
+ const req = submittedRequest();
+ expect(req.issue.roleGrant.condition.environments).toEqual([]);
+ expect(req.issue.title).not.toContain("direct-execution-suffix");
+ });
- await renderSheet(false);
- await selectRole("roles/sqlEditorUser");
- await flush();
+ it("blocks submit while on with nothing picked, with the error beside the picker", async () => {
+ await renderSheet(false);
+ await selectRole("roles/sqlEditorUser");
+ await field.toggle();
+
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("true");
+ expect(
+ container.querySelector("[data-testid='env-multi-select']")
+ ).not.toBeNull();
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.environment-required"
+ );
+ expect(container.textContent).not.toContain(
+ "project.members.direct-execution.lead-request"
+ );
+ expect(getSubmitButton().disabled).toBe(true);
+ });
- expect(container.textContent).toContain("project.members.ddl-warning");
- });
+ it("submits the picked list, shows the requester's lead, and suffixes the title", async () => {
+ await renderSheet(false);
+ await selectRole("roles/sqlEditorUser");
+ await field.toggle();
+ await field.pickStaging();
+
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.lead-request"
+ );
+ expect(container.textContent).not.toContain(
+ "project.members.direct-execution.environment-required"
+ );
+ expect(getSubmitButton().disabled).toBe(false);
+
+ await act(async () => {
+ getSubmitButton().click();
+ });
+ await flush();
+
+ const req = submittedRequest();
+ expect(req.issue.roleGrant.condition.environments).toEqual([
+ "environments/staging",
+ ]);
+ // The suffix carries the environment's title, not its name: D9.
+ expect(req.issue.title).toMatch(
+ /^FMT\(issue\.title\.request-specific-role .* · issue\.role-grant\.direct-execution-suffix \{"kind":"DDL\/DML","environments":"Staging"\}\)$/
+ );
+ });
- it("does not render DDL warning when role has no env limitation", async () => {
- // Default mock returns undefined — no override needed. Confirms the
- // warning is gated by envKind, not always-rendered.
- await renderSheet(false);
- await selectRole("roles/projectOwner");
- await flush();
+ it("suffixes an enforced title too", async () => {
+ await renderSheet(true);
+ await selectRole("roles/sqlEditorUser");
+ await typeReason("fix the backfill");
+ await field.toggle();
+ await field.pickStaging();
+
+ await act(async () => {
+ getSubmitButton().click();
+ });
+ await flush();
+
+ expect(submittedRequest().issue.title).toBe(
+ '[issue.title.request-role] fix the backfill · issue.role-grant.direct-execution-suffix {"kind":"DDL/DML","environments":"Staging"}'
+ );
+ });
+
+ it("a role change turns the switch off and clears the error", async () => {
+ await renderSheet(false);
+ await selectRole("roles/sqlEditorUser");
+ await field.toggle();
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.environment-required"
+ );
+
+ await selectRole("roles/projectOwner");
+ await flush();
+ expect(field.getSwitch()).toBeNull();
+
+ await selectRole("roles/sqlEditorUser");
+ await flush();
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("false");
+ expect(container.textContent).not.toContain(
+ "project.members.direct-execution.environment-required"
+ );
+ });
+
+ it("renders no field for a role without DDL/DML", async () => {
+ await renderSheet(false);
+ await selectRole("roles/projectOwner");
+ await flush();
- expect(container.textContent).not.toContain("project.members.ddl-warning");
+ expect(field.getSwitch()).toBeNull();
+ expect(container.textContent).not.toContain(
+ "project.members.direct-execution"
+ );
+ });
});
});
diff --git a/frontend/src/modules/access-control/RequestRoleSheet.tsx b/frontend/src/modules/access-control/RequestRoleSheet.tsx
index c443a2866a..47043cba20 100644
--- a/frontend/src/modules/access-control/RequestRoleSheet.tsx
+++ b/frontend/src/modules/access-control/RequestRoleSheet.tsx
@@ -7,12 +7,12 @@ import { issueServiceClientConnect } from "@/api";
import { router } from "@/app/router";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/app/router/handles";
import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/components/DatabaseResourceSelector";
-import { EnvironmentSelect } from "@/components/EnvironmentSelect";
import type { OptionConfig } from "@/components/ExprEditor";
import { ExprEditor } from "@/components/ExprEditor";
import { IssueLabelSelect } from "@/components/IssueLabelSelect";
import { RoleSelect } from "@/components/RoleSelect";
-import { DDLWarningCallout } from "@/components/role-grant/DDLWarningCallout";
+import { DirectExecutionField } from "@/components/role-grant/DirectExecutionField";
+import { RoleDescription } from "@/components/role-grant/RoleDescription";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { ExpirationPicker } from "@/components/ui/expiration-picker";
@@ -27,7 +27,13 @@ import {
SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
-import { useCurrentUser } from "@/hooks/useAppState";
+import { useCurrentUser, useEnvironmentList } from "@/hooks/useAppState";
+import {
+ type DirectExecutionValue,
+ directExecutionEnvironments,
+ EMPTY_DIRECT_EXECUTION,
+ isDirectExecutionValid,
+} from "@/lib/project-member/directExecution";
import {
getRoleEnvironmentLimitationKind,
roleHasDatabaseLimitation,
@@ -58,6 +64,7 @@ import {
} from "@/types/proto-es/v1/issue_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import type { Role } from "@/types/proto-es/v1/role_service_pb";
+import { resolveEnvironment } from "@/types/v1/environment";
import {
batchConvertParsedExprToCELString,
extractIssueUID,
@@ -75,6 +82,7 @@ import {
buildConditionExpr,
stringifyConditionExpression,
} from "@/utils/issue/cel";
+import { formatList } from "@/utils/string";
import type { DatabaseMode } from "./types";
export interface RequestRoleSheetProps {
@@ -168,7 +176,7 @@ function RequestRoleForm({
initialDatabaseResources = EMPTY_DATABASE_RESOURCES,
onClose,
}: Readonly<Omit<RequestRoleSheetProps, "open">>) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const currentUser = useCurrentUser();
// Theming is handled by the outer RequestRoleSheet (inline vars on
// SheetContent); this form just inherits them.
@@ -194,10 +202,13 @@ function RequestRoleForm({
const [exprGroup, setExprGroup] = useState<ConditionGroupExpr>(() =>
wrapAsGroup(emptySimpleExpr())
);
- const [environments, setEnvironments] = useState<string[]>([]);
+ const [directExecution, setDirectExecution] = useState<DirectExecutionValue>(
+ EMPTY_DIRECT_EXECUTION
+ );
const [submitting, setSubmitting] = useState(false);
const roleList = useAppStore((state) => state.roleList);
+ const environmentList = useEnvironmentList();
const selectedRole = useAppStore((state) =>
role ? state.getRoleByName(role) : undefined
);
@@ -318,6 +329,7 @@ function RequestRoleForm({
!labelsMisconfigured &&
databaseScopeComplete &&
selectedRoleMatchesRequiredPermissions &&
+ isDirectExecutionValid(directExecution) &&
(!project.forceIssueLabels || labels.length > 0);
const handleSubmit = async () => {
@@ -339,7 +351,9 @@ function RequestRoleForm({
: undefined;
// EnvLimitationKind union has no falsy members, so the truthy check
// is equivalent to !== undefined.
- const scopedEnvironments = envKind ? environments : undefined;
+ const scopedEnvironments = envKind
+ ? directExecutionEnvironments(directExecution)
+ : undefined;
// The backend uses two fields on the RoleGrant message:
// 1. `condition.expression` — CEL evaluated by
@@ -421,14 +435,29 @@ function RequestRoleForm({
? [...new Set(scopedDatabaseResources.map((r) => r.databaseFullName))]
: undefined;
+ // Stored text: the details card, not the title, is the authoritative
+ // record of the scope, so a later environment rename leaves it stale.
+ const suffix =
+ envKind && scopedEnvironments?.length
+ ? ` · ${t("issue.role-grant.direct-execution-suffix", {
+ kind: envKind,
+ environments: formatList(
+ scopedEnvironments.map(
+ (name) => resolveEnvironment(name, environmentList).title
+ ),
+ i18n.resolvedLanguage ?? "en-US"
+ ),
+ })}`
+ : "";
// When the project enforces issue titles, the user-provided reason is
- // treated as the title.
+ // treated as the title. A generated title ends with its timestamp, so the
+ // suffix goes before it, where a truncated issue-list row keeps it.
const title = project.enforceIssueTitle
- ? `[${t("issue.title.request-role")}] ${trimmedReason}`
+ ? `[${t("issue.title.request-role")}] ${trimmedReason}${suffix}`
: formatIssueTitle(
- t("issue.title.request-specific-role", {
+ `${t("issue.title.request-specific-role", {
role: displayRoleTitleFromList(role, roleList),
- }),
+ })}${suffix}`,
titleDatabaseNames
);
@@ -513,10 +542,11 @@ function RequestRoleForm({
setDatabaseMode("ALL");
setDatabaseResources([]);
setExprGroup(wrapAsGroup(emptySimpleExpr()));
- setEnvironments([]);
+ setDirectExecution(EMPTY_DIRECT_EXECUTION);
}}
filterRole={roleMatchesRequiredPermissions}
/>
+ <RoleDescription role={role} roleList={roleList} />
{!!role && !selectedRoleMatchesRequiredPermissions && (
<FormError>
{t("common.missing-required-permission", {
@@ -585,15 +615,12 @@ function RequestRoleForm({
</FormField>
)}
{envKind && (
- <FormField title={<>{t("common.environments")}</>}>
- <DDLWarningCallout type="drawer" kind={envKind} />
- <EnvironmentSelect
- multiple
- portal
- value={environments}
- onChange={setEnvironments}
- />
- </FormField>
+ <DirectExecutionField
+ kind={envKind}
+ lead="request"
+ value={directExecution}
+ onChange={setDirectExecution}
+ />
)}
<FormField
title={
diff --git a/frontend/src/modules/cel/logic/resolve.ts b/frontend/src/modules/cel/logic/resolve.ts
index 0a58fd49fe..7025cc8e45 100644
--- a/frontend/src/modules/cel/logic/resolve.ts
+++ b/frontend/src/modules/cel/logic/resolve.ts
@@ -46,15 +46,17 @@ const getConstantInt64Value = (expr: CELExpr): number => {
return 0;
};
-const getConstantStringValue = (expr: CELExpr): string => {
- if (
- expr.exprKind?.case === "constExpr" &&
- expr.exprKind.value.constantKind?.case === "stringValue"
- ) {
- return expr.exprKind.value.constantKind.value;
- }
- return "";
-};
+// The string a constant node carries; undefined for any other node.
+export const constantStringOf = (
+ expr: CELExpr | undefined
+): string | undefined =>
+ expr?.exprKind?.case === "constExpr" &&
+ expr.exprKind.value.constantKind?.case === "stringValue"
+ ? expr.exprKind.value.constantKind.value
+ : undefined;
+
+const getConstantStringValue = (expr: CELExpr): string =>
+ constantStringOf(expr) ?? "";
const getConstantBoolValue = (expr: CELExpr): boolean => {
if (
@@ -332,16 +334,28 @@ export const emptySimpleExpr = (
};
};
-const getFactorName = (expr: CELExpr): string => {
- if (expr.exprKind?.case === "identExpr") {
+// `resource.environment_id` parses as a select on the ident `resource`; the
+// dotted ident is what `buildCELExpr` emits. Only an ident or a select names a
+// factor.
+export const factorNameOf = (expr: CELExpr | undefined): string | undefined => {
+ if (expr?.exprKind?.case === "identExpr") {
return expr.exprKind.value.name;
- } else if (expr.exprKind?.case === "selectExpr") {
- const selectExpr = expr.exprKind.value;
+ }
+ if (expr?.exprKind?.case === "selectExpr") {
+ const { operand, field } = expr.exprKind.value;
const operandName =
- selectExpr.operand?.exprKind?.case === "identExpr"
- ? selectExpr.operand.exprKind.value.name
+ operand?.exprKind?.case === "identExpr"
+ ? operand.exprKind.value.name
: "";
- return `${operandName}.${selectExpr.field}`;
+ return `${operandName}.${field}`;
+ }
+ return undefined;
+};
+
+const getFactorName = (expr: CELExpr): string => {
+ const name = factorNameOf(expr);
+ if (name === undefined) {
+ throw new Error(`cannot resolve factor name ${JSON.stringify(expr)}`);
}
- throw new Error(`cannot resolve factor name ${JSON.stringify(expr)}`);
+ return name;
};
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
index d46316fabb..720c939b14 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
@@ -8,52 +8,59 @@ const { mockContextRef } = vi.hoisted(() => ({
mockContextRef: { current: undefined as unknown },
}));
-vi.mock("react-i18next", () => ({
- initReactI18next: { type: "3rdParty", init: () => {} },
- useTranslation: () => ({
- t: (key: string, vars?: Record<string, unknown>) => {
- let s = key;
- if (vars) {
- for (const [k, v] of Object.entries(vars)) {
- s = s.replace(`{{${k}}}`, String(v));
- }
- // Append a JSON suffix so we can also assert on raw vars in messy cases.
- s += " " + JSON.stringify(vars);
- }
- return s;
- },
- }),
-}));
+vi.mock("react-i18next", async () =>
+ (await import("@/test-utils/i18n")).reactI18nextStub()
+);
vi.mock("@/lib/project-member/utils", () => ({
getRoleEnvironmentLimitationKind: (role: string) =>
role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
}));
+vi.mock("@/lib/role", () => ({
+ displayRoleTitleFromList: (role: string) => `TITLE(${role})`,
+ displayRoleDescriptionFromList: (role: string) => `DESC(${role})`,
+}));
+
+// What usePrincipal resolves: two people, a person whose record never arrived
+// (title still empty), and a service account.
+const PRINCIPALS: Record<string, { title: string; email: string }> = {
+ "users/[email protected]": {
+ title: "Alex Kim",
+ email: "[email protected]",
+ },
+ "users/[email protected]": {
+ title: "CI Bot",
+ email: "[email protected]",
+ },
+ "users/[email protected]": {
+ title: "",
+ email: "[email protected]",
+ },
+ "users/[email protected]": {
+ title: "deploy",
+ email: "[email protected]",
+ },
+};
+
vi.mock("@/hooks/useAppState", () => ({
useEnvironmentList: () => [
- { name: "environments/prod", title: "Prod" },
- { name: "environments/test", title: "Test" },
+ { name: "environments/prod", title: "Prod", tags: {} },
+ { name: "environments/test", title: "Test", tags: {} },
],
+ usePlanFeature: () => true,
}));
-// Stub EnvironmentLabel — the real component pulls in app-store hooks and
-// theme tokens.
-vi.mock("@/components/EnvironmentLabel", () => ({
- EnvironmentLabel: ({
- environmentName,
- className,
- }: {
- environmentName: string;
- className?: string;
- }) => (
- <span data-testid="env-label" className={className}>
- {environmentName}
- </span>
- ),
+vi.mock("./usePrincipal", () => ({
+ usePrincipal: (identifier?: string) =>
+ identifier ? PRINCIPALS[identifier] : undefined,
}));
-// Stub other modules the component pulls in.
+// Stub the badge — the real one pulls in theme tokens and router links.
+vi.mock("@/components/EnvironmentLabel", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentBadgeStub()
+);
+
vi.mock("@/types/v1/database", () => ({
unknownDatabase: () => ({
name: "instances/-/databases/-",
@@ -91,12 +98,9 @@ vi.mock("@/stores/app", () => {
};
});
-vi.mock("@/utils", () => ({
- displayRoleTitle: (r: string) => r,
-}));
-
vi.mock("@/utils/issue/cel", () => ({
- convertFromCELString: async (expr: string) => {
+ readableConditionFromCELString: async (expr: string) => {
+ if (expr === "unreadable") throw new Error("unreadable");
// Mini parser just for tests: only recognizes "environment_id in [...]".
const m = expr.match(/environment_id in \[([^\]]*)\]/);
if (!m) return { environments: undefined };
@@ -116,158 +120,171 @@ vi.mock("../context/IssueDetailContext", () => ({
useIssueDetailContext: () => mockContextRef.current,
}));
+const issueWith = (
+ overrides: Partial<{
+ role: string;
+ expression: string;
+ user: string;
+ creator: string;
+ }>
+) => ({
+ issue: {
+ creator: overrides.creator ?? "users/[email protected]",
+ roleGrant: {
+ role: overrides.role ?? "roles/sqlEditorUser",
+ user: overrides.user ?? "users/[email protected]",
+ condition: { expression: overrides.expression ?? "" },
+ },
+ },
+});
+
beforeEach(() => {
mockContextRef.current = undefined;
});
describe("IssueDetailRoleGrantDetails", () => {
- test("renders Environments row and warning when role has DDL/DML and env list is non-empty", async () => {
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: {
- expression: 'resource.environment_id in ["prod", "test"]',
- },
- },
- },
- };
+ test("the grantee row shows the grant's user, not the creator, and no 'requested by' when they match", () => {
+ mockContextRef.current = issueWith({});
render(<IssueDetailRoleGrantDetails />);
- expect(
- await screen.findByText(/project.members.ddl-current-some/)
- ).toBeInTheDocument();
- expect(screen.getByText(/common.environments/)).toBeInTheDocument();
- // Env titles render as plain text inside the env section.
- expect(screen.getByText("Prod, Test")).toBeInTheDocument();
+ const row = screen.getByTestId("role-grant-grantee");
+ expect(row.textContent).toContain("Alex Kim");
+ expect(row.textContent).toContain("[email protected]");
+ expect(row.textContent).not.toContain("requested-by");
});
- test("renders binding-all warning when condition has no environment clause (unrestricted)", async () => {
- // Expression with expiration but no environment_id clause — the grant
- // would apply to ALL environments. This is the highest-risk scenario;
- // the approver MUST see the warning.
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: {
- expression: 'request.time < timestamp("2026-12-31T00:00:00Z")',
- },
- },
- },
- };
+ test("'requested by' appears only when the creator differs from the grantee", () => {
+ mockContextRef.current = issueWith({ creator: "users/[email protected]" });
render(<IssueDetailRoleGrantDetails />);
expect(
- await screen.findByText(/project.members.ddl-current-all/)
- ).toBeInTheDocument();
- // No env list rendered for binding-all.
- expect(screen.queryByText(/common.environments/)).not.toBeInTheDocument();
+ screen.getByTestId("role-grant-grantee").textContent
+ ).toContain('requested-by {"creator":"CI Bot"}');
});
- test("renders binding-all warning when expression is empty entirely", async () => {
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: { expression: "" },
- },
- },
- };
+ test("the grantee and what approving grants come before the permission list", async () => {
+ mockContextRef.current = issueWith({
+ expression: 'resource.environment_id in ["prod"]',
+ });
render(<IssueDetailRoleGrantDetails />);
- expect(
- await screen.findByText(/project.members.ddl-current-all/)
- ).toBeInTheDocument();
- expect(screen.queryByText(/common.environments/)).not.toBeInTheDocument();
+ const execution = await screen.findByTestId("role-grant-direct-execution");
+ const follows = (a: Element, b: Element) =>
+ Boolean(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(follows(screen.getByTestId("role-grant-grantee"), execution)).toBe(
+ true
+ );
+ expect(follows(execution, screen.getByText(/^common\.permissions/))).toBe(
+ true
+ );
});
- test("hides env section entirely for empty env clause (degenerate binding-none)", async () => {
- // A request submitted with no envs selected serializes to
- // `environment_id in []` — degenerate, grants no env access. We hide
- // the env section to avoid suggesting approval-relevant DDL/DML risk
- // when the binding wouldn't grant DDL/DML anywhere anyway.
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: { expression: "resource.environment_id in []" },
- },
- },
- };
+ test("a list renders the approver lead naming the grantee, with one chip per environment", async () => {
+ mockContextRef.current = issueWith({
+ expression: 'resource.environment_id in ["prod", "test"]',
+ });
render(<IssueDetailRoleGrantDetails />);
- // Wait for the async CEL parse to complete by polling that the loading
- // guard has lifted (envScope === undefined during parse hides everything).
- // After parse, if any warning were going to show it would be present;
- // assert all three are absent.
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(
- screen.queryByText(/project.members.ddl-current-none/)
- ).not.toBeInTheDocument();
+ const lead = await screen.findByText(/lead-approver/);
+ expect(lead.textContent).toContain('"grantee":"Alex Kim"');
expect(
- screen.queryByText(/project.members.ddl-current-all/)
- ).not.toBeInTheDocument();
- expect(
- screen.queryByText(/project.members.ddl-current-some/)
- ).not.toBeInTheDocument();
- expect(screen.queryByText(/common.environments/)).not.toBeInTheDocument();
+ screen.getAllByTestId("env-label").map((el) => el.textContent)
+ ).toEqual(["environments/prod", "environments/test"]);
});
- test("hides warning when role has been deleted (helper returns undefined)", async () => {
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/wasDeleted",
- condition: { expression: 'resource.environment_id in ["prod"]' },
- },
- },
- };
+ test("the empty list renders the 'none' sentence rather than nothing", async () => {
+ mockContextRef.current = issueWith({
+ expression: "resource.environment_id in []",
+ });
render(<IssueDetailRoleGrantDetails />);
- expect(
- screen.queryByText(/project.members.ddl-current-some/)
- ).not.toBeInTheDocument();
+ expect(await screen.findByText(/direct-execution\.none/)).toBeTruthy();
+ expect(screen.queryByTestId("env-label")).toBeNull();
});
- test("hides warning when role lacks DDL/DML perms", async () => {
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/queryOnly",
- condition: { expression: 'resource.environment_id in ["prod"]' },
- },
- },
- };
+ test("no environment clause renders the unscoped warning", async () => {
+ mockContextRef.current = issueWith({
+ expression: 'request.time < timestamp("2026-10-01T00:00:00Z")',
+ });
render(<IssueDetailRoleGrantDetails />);
- expect(
- screen.queryByText(/project.members.ddl-current-some/)
- ).not.toBeInTheDocument();
+ expect(await screen.findByText(/direct-execution\.all/)).toBeTruthy();
+ });
+
+ test("an empty expression is unscoped too", () => {
+ mockContextRef.current = issueWith({ expression: "" });
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.getByText(/direct-execution\.all/)).toBeTruthy();
+ });
+
+ test("a condition the reader rejects renders the unscoped warning, not nothing", async () => {
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ try {
+ mockContextRef.current = issueWith({ expression: "unreadable" });
+ render(<IssueDetailRoleGrantDetails />);
+ expect(await screen.findByText(/direct-execution\.all/)).toBeTruthy();
+ expect(consoleError).toHaveBeenCalledWith(
+ "Failed to parse CEL expression:",
+ expect.any(Error)
+ );
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+
+ test("a role without DDL/DML has no execution row", () => {
+ mockContextRef.current = issueWith({ role: "roles/queryOnly" });
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.queryByTestId("role-grant-direct-execution")).toBeNull();
+ });
+
+ test("a service-account grantee is marked as one and named from its email until its record arrives", async () => {
+ mockContextRef.current = issueWith({
+ user: "users/[email protected]",
+ creator: "users/[email protected]",
+ expression: 'resource.environment_id in ["prod"]',
+ });
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.getByText("settings.members.service-account")).toBeTruthy();
+ expect(screen.getByText("deploy")).toBeTruthy();
+ expect(screen.getByText("[email protected]")).toBeTruthy();
+ expect((await screen.findByText(/lead-approver/)).textContent).toContain(
+ '"grantee":"deploy"'
+ );
+ });
+
+ test("a person as grantee carries no account badge", () => {
+ mockContextRef.current = issueWith({});
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.queryByText("settings.members.service-account")).toBeNull();
+ expect(screen.queryByText("settings.members.workload-identity")).toBeNull();
+ });
+
+ test("a person whose record has not arrived is shown by email, not by resource name", () => {
+ mockContextRef.current = issueWith({
+ user: "users/[email protected]",
+ creator: "users/[email protected]",
+ });
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.getByText("[email protected]")).toBeTruthy();
+ expect(screen.queryByText("users/[email protected]")).toBeNull();
+ });
+
+ test("the role's description renders under its title", () => {
+ mockContextRef.current = issueWith({});
+ render(<IssueDetailRoleGrantDetails />);
+ expect(screen.getByText("DESC(roles/sqlEditorUser)")).toBeTruthy();
});
test("clears stale environments when the issue prop changes", async () => {
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: { expression: 'resource.environment_id in ["prod"]' },
- },
- },
- };
+ mockContextRef.current = issueWith({
+ expression: 'resource.environment_id in ["prod"]',
+ });
const { rerender } = render(<IssueDetailRoleGrantDetails />);
- expect(await screen.findByText("Prod")).toBeInTheDocument();
+ await screen.findByText(/lead-approver/);
- mockContextRef.current = {
- issue: {
- roleGrant: {
- role: "roles/sqlEditorUser",
- condition: { expression: 'resource.environment_id in ["test"]' },
- },
- },
- };
+ mockContextRef.current = issueWith({
+ expression: 'resource.environment_id in ["test"]',
+ });
rerender(<IssueDetailRoleGrantDetails />);
-
- // Without the synchronous setCondition(undefined), stale "Prod" leaks
- // into the env row until the async CEL parse for "test" resolves.
- expect(screen.queryByText("Prod")).not.toBeInTheDocument();
-
- // After the new parse, "Test" shows; "Prod" stays absent.
- expect(await screen.findByText("Test")).toBeInTheDocument();
- expect(screen.queryByText("Prod")).not.toBeInTheDocument();
+ expect(
+ (await screen.findAllByTestId("env-label")).map((el) => el.textContent)
+ ).toEqual(["environments/test"]);
});
});
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
index 4a44df0e5d..42f9143316 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
@@ -1,7 +1,10 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { AccountTypeBadge } from "@/components/AccountTypeBadge";
import { HumanizeTs } from "@/components/HumanizeTs";
-import { DDLWarningCallout } from "@/components/role-grant/DDLWarningCallout";
+import { DirectExecutionCallout } from "@/components/role-grant/DirectExecutionCallout";
+import { RoleDescription } from "@/components/role-grant/RoleDescription";
+import { UserCell } from "@/components/UserCell";
import {
Table,
TableBody,
@@ -10,28 +13,40 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { useEnvironmentList } from "@/hooks/useAppState";
-import { getRoleEnvironmentLimitationKind } from "@/lib/project-member/utils";
+import { useEnvironmentList, usePlanFeature } from "@/hooks/useAppState";
+import { directExecutionOf } from "@/lib/project-member/directExecution";
import { displayRoleTitleFromList } from "@/lib/role";
import { useAppStore } from "@/stores/app";
import type { DatabaseResource } from "@/types";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { unknownDatabase } from "@/types/v1/database";
import {
type ConditionExpression,
- convertFromCELString,
+ readableConditionFromCELString,
} from "@/utils/issue/cel";
import { extractDatabaseResourceName } from "@/utils/v1/database";
import { useIssueDetailContext } from "../context/IssueDetailContext";
+import { usePrincipal } from "./usePrincipal";
export function IssueDetailRoleGrantDetails() {
const { t } = useTranslation();
const page = useIssueDetailContext();
const issue = page.issue;
const requestRoleName = issue?.roleGrant?.role ?? "";
+ const granteeName = issue?.roleGrant?.user;
+ const creatorName = issue?.creator;
const roleList = useAppStore((state) => state.roleList);
const requestRole = useAppStore((state) =>
state.getRoleByName(requestRoleName)
);
+ const grantee = usePrincipal(granteeName);
+ const showRequestedBy =
+ creatorName !== undefined && creatorName !== granteeName;
+ const creator = usePrincipal(showRequestedBy ? creatorName : undefined);
+ const environmentList = useEnvironmentList();
+ const hasEnvTierFeature = usePlanFeature(
+ PlanFeature.FEATURE_ENVIRONMENT_TIERS
+ );
const [condition, setCondition] = useState<ConditionExpression | undefined>();
useEffect(() => {
@@ -45,10 +60,13 @@ export function IssueDetailRoleGrantDetails() {
let canceled = false;
void (async () => {
try {
- const parsed = await convertFromCELString(expression);
+ const parsed = await readableConditionFromCELString(expression);
if (!canceled) setCondition(parsed);
} catch (error) {
+ // Unreadable reads as the widest grant, so the execution row never
+ // disappears.
console.error("Failed to parse CEL expression:", error);
+ if (!canceled) setCondition({ databaseResources: [] });
}
})();
return () => {
@@ -67,25 +85,14 @@ export function IssueDetailRoleGrantDetails() {
}
}, [condition?.databaseResources]);
- const envKind = getRoleEnvironmentLimitationKind(requestRoleName);
- const envNames = condition?.environments ?? [];
- const envList = useEnvironmentList();
- // Falls back to the raw env resource name (e.g. environments/prod-old) when
- // the env isn't in the store — happens when an env is renamed or deleted
- // between request submission and approver review.
- const envTitles = envNames.map(
- (n) => envList.find((e) => e.name === n)?.title ?? n
- );
-
- // Three-way env scope:
- // environments === undefined → no env clause in CEL → unrestricted (binding-all)
- // environments === [] → restricted to empty list (binding-none)
- // environments === [list] → restricted to listed envs (binding-some)
- // Hide during async parse so we don't briefly show binding-all for an
- // expression that's about to resolve to binding-some/binding-none.
const expression = issue?.roleGrant?.condition?.expression ?? "";
+ // Hidden while the expression parses, so a request that resolves to an
+ // explicit list is never shown as unscoped in between.
const isParsing = expression !== "" && condition === undefined;
- const envScope = computeEnvScope(envKind, isParsing, condition?.environments);
+ const directExecution = isParsing
+ ? undefined
+ : directExecutionOf(requestRoleName, condition);
+ const granteeTitle = grantee?.title || grantee?.email || granteeName || "";
return (
<div className="flex flex-col gap-y-4">
@@ -98,40 +105,52 @@ export function IssueDetailRoleGrantDetails() {
<div className="text-base">
{displayRoleTitleFromList(requestRoleName, roleList)}
</div>
+ <RoleDescription role={requestRoleName} roleList={roleList} />
</div>
)}
- {requestRole && (
- <div className="flex flex-col gap-y-2">
+ {granteeName && (
+ <div
+ className="flex flex-col gap-y-2"
+ data-testid="role-grant-grantee"
+ >
<span className="text-sm text-control-light">
- {t("common.permissions")} ({requestRole.permissions.length})
+ {t("issue.role-grant.grantee")}
</span>
- <div className="max-h-[10em] overflow-auto rounded-sm border p-2">
- {requestRole.permissions.map((permission) => (
- <p key={permission} className="text-sm leading-5">
- {permission}
- </p>
- ))}
- </div>
+ <UserCell
+ title={granteeTitle}
+ subtitle={grantee?.title ? grantee.email : undefined}
+ showAvatar={false}
+ badges={<AccountTypeBadge email={grantee?.email} />}
+ />
+ {showRequestedBy && (
+ <p className="text-xs leading-4 text-control-light">
+ {t("issue.role-grant.requested-by", {
+ creator: creator?.title || creator?.email || creatorName,
+ })}
+ </p>
+ )}
</div>
)}
- {envScope === "binding-all" && envKind && (
- <DDLWarningCallout type="binding-all" kind={envKind} />
- )}
- {/*
- * binding-none on the issue page = the request specified an empty
- * env list (degenerate: the binding would grant no env access at
- * all). Showing an info box would suggest there's something to
- * approve here when really the binding grants nothing. Hide.
- */}
- {envScope === "binding-some" && envKind && (
- <div className="flex flex-col gap-y-2">
+ {directExecution && (
+ <div
+ className="flex flex-col gap-y-2"
+ data-testid="role-grant-direct-execution"
+ >
<span className="text-sm text-control-light">
- {t("common.environments")}
+ {t("project.members.direct-execution.title", {
+ kind: directExecution.kind,
+ })}
</span>
- <DDLWarningCallout type="binding-some" kind={envKind} />
- <div className="text-base">{envTitles.join(", ")}</div>
+ <DirectExecutionCallout
+ kind={directExecution.kind}
+ lead="approver"
+ scope={directExecution.scope}
+ grantee={granteeTitle}
+ environmentList={environmentList}
+ hasEnvTierFeature={hasEnvTierFeature}
+ />
</div>
)}
@@ -169,6 +188,21 @@ export function IssueDetailRoleGrantDetails() {
)}
</div>
</div>
+
+ {requestRole && (
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm text-control-light">
+ {t("common.permissions")} ({requestRole.permissions.length})
+ </span>
+ <div className="max-h-[10em] overflow-auto rounded-sm border p-2">
+ {requestRole.permissions.map((permission) => (
+ <p key={permission} className="text-sm leading-5">
+ {permission}
+ </p>
+ ))}
+ </div>
+ </div>
+ )}
</div>
</div>
);
@@ -251,17 +285,6 @@ function IssueDetailDatabaseResourceTable({
);
}
-function computeEnvScope(
- envKind: ReturnType<typeof getRoleEnvironmentLimitationKind>,
- isParsing: boolean,
- environments: string[] | undefined
-): "binding-all" | "binding-some" | "binding-none" | undefined {
- if (!envKind || isParsing) return undefined;
- if (environments === undefined) return "binding-all";
- if (environments.length === 0) return "binding-none";
- return "binding-some";
-}
-
function extractTableName(databaseResource: DatabaseResource) {
if (!databaseResource.schema && !databaseResource.table) {
return "*";
diff --git a/frontend/src/routes/project/issue-detail/components/usePrincipal.test.tsx b/frontend/src/routes/project/issue-detail/components/usePrincipal.test.tsx
new file mode 100644
index 0000000000..3b213a9961
--- /dev/null
+++ b/frontend/src/routes/project/issue-detail/components/usePrincipal.test.tsx
@@ -0,0 +1,103 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { usePrincipal } from "./usePrincipal";
+
+// The store's getters as they behave: a person is undefined until fetched; a
+// service account or workload identity is a placeholder named from its email.
+const store = vi.hoisted(() => {
+ const state = {
+ usersByName: {} as Record<string, { title: string; email: string }>,
+ serviceAccountsByName: {} as Record<string, { title: string }>,
+ workloadIdentitiesByName: {} as Record<string, { title: string }>,
+ getUserByIdentifier: (identifier: string) => state.usersByName[identifier],
+ getServiceAccount: (name: string) =>
+ state.serviceAccountsByName[name] ?? {
+ title: name.slice("serviceAccounts/".length).split("@")[0],
+ },
+ getWorkloadIdentity: (name: string) =>
+ state.workloadIdentitiesByName[name] ?? {
+ title: name.slice("workloadIdentities/".length).split("@")[0],
+ },
+ getOrFetchUserByIdentifier: vi.fn(),
+ fetchServiceAccount: vi.fn(),
+ fetchWorkloadIdentity: vi.fn(),
+ };
+ return state;
+});
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: Object.assign(
+ (selector: (s: unknown) => unknown) => selector(store),
+ { getState: () => store }
+ ),
+}));
+
+beforeEach(() => {
+ store.usersByName = {};
+ store.serviceAccountsByName = {};
+ store.workloadIdentitiesByName = {};
+ store.getOrFetchUserByIdentifier.mockReset();
+ store.fetchServiceAccount.mockReset();
+ store.fetchWorkloadIdentity.mockReset();
+});
+
+describe("usePrincipal", () => {
+ test("a person is read from the user cache and fetched through the user service", () => {
+ store.usersByName["users/[email protected]"] = {
+ title: "Alex Kim",
+ email: "[email protected]",
+ };
+ const { result } = renderHook(() => usePrincipal("users/[email protected]"));
+ expect(result.current).toEqual({ email: "[email protected]", title: "Alex Kim" });
+ expect(store.getOrFetchUserByIdentifier).toHaveBeenCalledWith({
+ identifier: "users/[email protected]",
+ });
+ expect(store.fetchServiceAccount).not.toHaveBeenCalled();
+ });
+
+ test("a person not yet fetched has no title", () => {
+ const { result } = renderHook(() => usePrincipal("users/[email protected]"));
+ expect(result.current).toEqual({ email: "[email protected]", title: "" });
+ });
+
+ test("a service account is fetched from its own service and named from its email until its record arrives", () => {
+ const { result, rerender } = renderHook(() =>
+ usePrincipal("users/[email protected]")
+ );
+ expect(result.current).toEqual({
+ email: "[email protected]",
+ title: "deploy",
+ });
+ expect(store.fetchServiceAccount).toHaveBeenCalledWith(
+ "serviceAccounts/[email protected]",
+ true
+ );
+ expect(store.getOrFetchUserByIdentifier).not.toHaveBeenCalled();
+
+ store.serviceAccountsByName["serviceAccounts/[email protected]"] = {
+ title: "Deploy bot",
+ };
+ rerender();
+ expect(result.current?.title).toBe("Deploy bot");
+ });
+
+ test("a workload identity likewise", () => {
+ const { result } = renderHook(() =>
+ usePrincipal("users/[email protected]")
+ );
+ expect(result.current?.title).toBe("ci");
+ expect(store.fetchWorkloadIdentity).toHaveBeenCalledWith(
+ "workloadIdentities/[email protected]",
+ true
+ );
+ expect(store.getOrFetchUserByIdentifier).not.toHaveBeenCalled();
+ });
+
+ test("no identifier: nothing, and no fetch", () => {
+ const { result } = renderHook(() => usePrincipal(undefined));
+ expect(result.current).toBeUndefined();
+ expect(store.getOrFetchUserByIdentifier).not.toHaveBeenCalled();
+ expect(store.fetchServiceAccount).not.toHaveBeenCalled();
+ expect(store.fetchWorkloadIdentity).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/routes/project/issue-detail/components/usePrincipal.ts b/frontend/src/routes/project/issue-detail/components/usePrincipal.ts
new file mode 100644
index 0000000000..425169b831
--- /dev/null
+++ b/frontend/src/routes/project/issue-detail/components/usePrincipal.ts
@@ -0,0 +1,70 @@
+import { useEffect } from "react";
+import { useAppStore } from "@/stores/app";
+import { ensureServiceAccountFullName } from "@/stores/app/serviceAccount";
+import { ensureWorkloadIdentityFullName } from "@/stores/app/workloadIdentity";
+import { extractUserEmail } from "@/stores/modules/v1/common";
+import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
+import { ensureUserFullName } from "@/utils/v1/user";
+
+interface Principal {
+ email: string;
+ title: string;
+}
+
+type AppState = ReturnType<typeof useAppStore.getState>;
+
+// The user service refuses service accounts and workload identities, which
+// have services of their own; the account type read from the email decides
+// where a principal is read and fetched.
+const PRINCIPAL_SERVICES: Record<
+ AccountType,
+ {
+ name: (email: string) => string;
+ title: (state: AppState, name: string) => string | undefined;
+ fetch: (state: AppState, name: string) => Promise<unknown>;
+ }
+> = {
+ [AccountType.SERVICE_ACCOUNT]: {
+ name: ensureServiceAccountFullName,
+ title: (state, name) => state.getServiceAccount(name).title,
+ fetch: (state, name) => state.fetchServiceAccount(name, true),
+ },
+ [AccountType.WORKLOAD_IDENTITY]: {
+ name: ensureWorkloadIdentityFullName,
+ title: (state, name) => state.getWorkloadIdentity(name).title,
+ fetch: (state, name) => state.fetchWorkloadIdentity(name, true),
+ },
+ [AccountType.USER]: {
+ name: ensureUserFullName,
+ title: (state, name) => state.getUserByIdentifier(name)?.title,
+ fetch: (state, name) =>
+ state.getOrFetchUserByIdentifier({ identifier: name }),
+ },
+};
+
+/**
+ * Whoever a `users/{email}` identifier names: a person, a service account, or
+ * a workload identity. Until a record arrives the store names a service
+ * account or workload identity from its email, as the member list does, and
+ * a person has no title.
+ */
+export function usePrincipal(
+ identifier: string | undefined
+): Principal | undefined {
+ const email = identifier ? extractUserEmail(identifier) : undefined;
+ const service =
+ PRINCIPAL_SERVICES[email ? getAccountTypeByEmail(email) : AccountType.USER];
+ const name = email === undefined ? undefined : service.name(email);
+ const title = useAppStore((state) =>
+ name === undefined ? undefined : service.title(state, name)
+ );
+ useEffect(() => {
+ if (name !== undefined) {
+ void service.fetch(useAppStore.getState(), name);
+ }
+ }, [name, service]);
+ if (email === undefined) {
+ return undefined;
+ }
+ return { email, title: title ?? "" };
+}
diff --git a/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.test.tsx b/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.test.tsx
deleted file mode 100644
index 21b55f86e5..0000000000
--- a/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.test.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, test, vi } from "vitest";
-import { MemberBindingEnvironmentBanner } from "./MemberBindingEnvironmentBanner";
-
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, vars?: Record<string, unknown>) => {
- const parts = [key];
- if (vars) parts.push(JSON.stringify(vars));
- return parts.join(" ");
- },
- }),
-}));
-
-vi.mock("@/components/EnvironmentLabel", () => ({
- EnvironmentLabel: ({
- environmentName,
- className,
- }: {
- environmentName: string;
- className?: string;
- }) => (
- <span data-testid="env-label" className={className}>
- {environmentName}
- </span>
- ),
-}));
-
-describe("MemberBindingEnvironmentBanner", () => {
- test("binding-all: renders ALL environments warning, no env badges", () => {
- render(
- <MemberBindingEnvironmentBanner
- envLimitation={{ type: "unrestricted" }}
- bindingKind="DDL/DML"
- />
- );
- expect(
- screen.getByText(/project.members.ddl-current-all/)
- ).toHaveTextContent("DDL/DML");
- expect(screen.queryAllByTestId("env-label")).toHaveLength(0);
- });
-
- test("binding-some: renders 'in the listed environments' warning + env labels", () => {
- render(
- <MemberBindingEnvironmentBanner
- envLimitation={{
- type: "restricted",
- environments: ["environments/prod", "environments/test"],
- }}
- bindingKind="DDL"
- />
- );
- expect(
- screen.getByText(/project.members.ddl-current-some/)
- ).toHaveTextContent("DDL");
- const labels = screen.getAllByTestId("env-label");
- expect(labels).toHaveLength(2);
- expect(labels[0]).toHaveTextContent("environments/prod");
- expect(labels[1]).toHaveTextContent("environments/test");
- });
-
- test("binding-none: renders 'not allowed' warning, no env badges", () => {
- render(
- <MemberBindingEnvironmentBanner
- envLimitation={{ type: "restricted", environments: [] }}
- bindingKind="DML"
- />
- );
- expect(
- screen.getByText(/project.members.ddl-current-none/)
- ).toHaveTextContent("DML");
- expect(screen.queryAllByTestId("env-label")).toHaveLength(0);
- });
-});
diff --git a/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.tsx b/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.tsx
deleted file mode 100644
index 95843f15e8..0000000000
--- a/frontend/src/routes/workspace/MemberBindingEnvironmentBanner.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { EnvironmentLabel } from "@/components/EnvironmentLabel";
-import { DDLWarningCallout } from "@/components/role-grant/DDLWarningCallout";
-import type { EnvLimitationKind } from "@/lib/project-member/utils";
-import type { ProjectRoleBindingEnvironmentLimitationState } from "./membersPageEnvironment";
-
-export function MemberBindingEnvironmentBanner({
- envLimitation,
- bindingKind,
-}: Readonly<{
- envLimitation: ProjectRoleBindingEnvironmentLimitationState;
- bindingKind: EnvLimitationKind;
-}>) {
- if (envLimitation.type === "unrestricted") {
- return <DDLWarningCallout type="binding-all" kind={bindingKind} />;
- }
- if (envLimitation.environments.length === 0) {
- return <DDLWarningCallout type="binding-none" kind={bindingKind} />;
- }
- return (
- <div className="flex flex-col gap-y-2">
- <DDLWarningCallout type="binding-some" kind={bindingKind} />
- <div className="flex flex-wrap gap-1">
- {envLimitation.environments.map((env) => (
- <EnvironmentLabel
- key={env}
- environmentName={env}
- className="text-xs"
- />
- ))}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/routes/workspace/MembersPage.test.tsx b/frontend/src/routes/workspace/MembersPage.test.tsx
index dfd305a21d..76e9f27198 100644
--- a/frontend/src/routes/workspace/MembersPage.test.tsx
+++ b/frontend/src/routes/workspace/MembersPage.test.tsx
@@ -52,10 +52,9 @@ vi.mock("@/components/DatabaseResourceSelector", () => ({
createElement("div", { "data-testid": "database-resource-selector" }),
}));
-vi.mock("@/components/EnvironmentSelect", () => ({
- EnvironmentSelect: () =>
- createElement("div", { "data-testid": "environment-multi-select" }),
-}));
+vi.mock("@/components/EnvironmentSelect", async () =>
+ (await import("@/test-utils/environmentSelectStub")).environmentSelectStub()
+);
vi.mock("@/components/ExprEditor", () => ({
ExprEditor: () => createElement("div", { "data-testid": "expr-editor" }),
@@ -93,8 +92,25 @@ vi.mock("@/components/RoleSelect", () => ({
}),
}));
-vi.mock("@/components/role-grant/DDLWarningCallout", () => ({
- DDLWarningCallout: () => null,
+vi.mock("@/components/role-grant/DirectExecutionCallout", () => ({
+ DirectExecutionCallout: ({
+ lead,
+ scope,
+ }: {
+ lead: string;
+ scope: { type: string; environments?: string[] };
+ }) =>
+ createElement("div", {
+ "data-testid": "direct-execution-callout",
+ "data-lead": lead,
+ "data-scope": scope.type,
+ "data-envs": scope.environments?.join(",") ?? "",
+ }),
+}));
+
+vi.mock("@/lib/role", () => ({
+ displayRoleTitleFromList: (role: string) => role,
+ displayRoleDescriptionFromList: (role: string) => `DESC(${role})`,
}));
vi.mock("@/components/UserCell", () => ({
@@ -203,6 +219,7 @@ vi.mock("@/hooks/useEscapeKey", () => ({
vi.mock("@/lib/project-member/utils", () => ({
getRoleEnvironmentLimitationKind: vi.fn(() => undefined),
+ getRolesEnvironmentLimitationKind: vi.fn(() => undefined),
roleHasDatabaseLimitation: vi.fn((role: string) =>
role.includes("sqlEditor")
),
@@ -272,6 +289,7 @@ vi.mock("@/utils/cel-attributes", () => ({
vi.mock("@/utils/issue/cel", () => ({
buildConditionExpr: (args: Record<string, unknown>) => ({ ...args }),
convertFromExpr: () => ({}),
+ readableCondition: () => ({}),
stringifyConditionExpression: () => "",
}));
@@ -300,6 +318,8 @@ vi.mock("@/hooks/useAppState", () => ({
name: "users/[email protected]",
}),
+ useEnvironmentList: () => [],
+ usePlanFeature: () => true,
}));
vi.mock("@/stores/app", () => {
@@ -349,10 +369,6 @@ vi.mock("@/stores/app", () => {
return { useAppStore };
});
-vi.mock("./MemberBindingEnvironmentBanner", () => ({
- MemberBindingEnvironmentBanner: () => null,
-}));
-
vi.mock("./MemberDatabaseResourceName", () => ({
MemberDatabaseResourceName: () => null,
}));
@@ -362,6 +378,11 @@ vi.mock("@/modules/access-control/RequestRoleSheet", () => ({
}));
import { buildCELExpr } from "@/modules/cel";
+import {
+ getRoleEnvironmentLimitationKind,
+ getRolesEnvironmentLimitationKind,
+} from "@/lib/project-member/utils";
+import { directExecutionDriver } from "@/test-utils/directExecutionDriver";
import { nativeChange } from "@/test-utils/nativeChange";
import { MembersPage } from "./MembersPage";
@@ -577,6 +598,139 @@ describe("MembersPage project role grant drawer", () => {
});
});
+describe("MembersPage direct DDL/DML execution", () => {
+ const isDdlRole = (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined;
+ beforeEach(() => {
+ vi.mocked(getRoleEnvironmentLimitationKind).mockImplementation(isDdlRole);
+ vi.mocked(getRolesEnvironmentLimitationKind).mockImplementation(
+ (roles: string[]) =>
+ roles.map(isDdlRole).find((kind) => kind !== undefined)
+ );
+ });
+ afterEach(() => {
+ // Back to the module mock's `() => undefined`.
+ vi.mocked(getRoleEnvironmentLimitationKind).mockReset();
+ vi.mocked(getRolesEnvironmentLimitationKind).mockReset();
+ });
+ async function clickGrantAccess(): Promise<void> {
+ const grantButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "settings.members.grant-access"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ grantButton.click();
+ });
+ await flush();
+ }
+ async function openGrantDrawerWithRole(role: string): Promise<void> {
+ await renderPage();
+ await clickGrantAccess();
+ await act(async () => {
+ (
+ container.querySelector(
+ "[data-testid='account-select']"
+ ) as HTMLButtonElement
+ ).click();
+ });
+ await selectRole(role);
+ }
+ const field = directExecutionDriver(flush);
+ async function selectRole(role: string): Promise<void> {
+ await act(async () => {
+ nativeChange(
+ container.querySelector(
+ "[data-testid='role-select']"
+ ) as HTMLInputElement,
+ role
+ );
+ });
+ await flush();
+ }
+ function getCreateButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.create"
+ ) as HTMLButtonElement;
+ }
+ async function clickCreate(): Promise<void> {
+ await act(async () => {
+ getCreateButton().click();
+ });
+ await flush();
+ }
+ function savedEnvironments(): string[] | undefined {
+ expect(mockUpdateProjectIamPolicy).toHaveBeenCalledTimes(1);
+ const policy = mockUpdateProjectIamPolicy.mock.calls[0][1] as {
+ bindings: { condition: { environments?: string[] } }[];
+ };
+ return policy.bindings.at(-1)?.condition.environments;
+ }
+
+ it("shows the role's description under the select", async () => {
+ await openGrantDrawerWithRole("roles/sqlEditorUser");
+ expect(container.textContent).toContain("DESC(roles/sqlEditorUser)");
+ });
+
+ it("off by default hands the condition builder the empty list, as the old empty picker did", async () => {
+ await openGrantDrawerWithRole("roles/sqlEditorUser");
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("false");
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.none"
+ );
+ expect(container.querySelector("[data-testid='env-multi-select']")).toBeNull();
+ await clickCreate();
+ expect(savedEnvironments()).toEqual([]);
+ });
+
+ it("on with nothing picked cannot be created", async () => {
+ await openGrantDrawerWithRole("roles/sqlEditorUser");
+ await field.toggle();
+ expect(container.textContent).toContain(
+ "project.members.direct-execution.environment-required"
+ );
+ expect(getCreateButton().disabled).toBe(true);
+ });
+
+ it("on with a pick writes the picked list and shows the grant lead", async () => {
+ await openGrantDrawerWithRole("roles/sqlEditorUser");
+ await field.toggle();
+ await field.pickStaging();
+ const callout = container.querySelector(
+ "[data-testid='direct-execution-callout']"
+ ) as HTMLElement;
+ expect(callout.getAttribute("data-lead")).toBe("grant");
+ expect(callout.getAttribute("data-envs")).toBe("environments/staging");
+ expect(getCreateButton().disabled).toBe(false);
+ await clickCreate();
+ expect(savedEnvironments()).toEqual(["environments/staging"]);
+ });
+
+ it("a role change turns the switch off", async () => {
+ await openGrantDrawerWithRole("roles/sqlEditorUser");
+ await field.toggle();
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("true");
+ await selectRole("roles/projectOwner");
+ expect(field.getSwitch()).toBeNull();
+ await selectRole("roles/sqlEditorUser");
+ expect(field.getSwitch().getAttribute("aria-checked")).toBe("false");
+ expect(container.textContent).not.toContain(
+ "project.members.direct-execution.environment-required"
+ );
+ });
+
+ it("the workspace sheet says an unscoped grant runs everywhere, for a role that carries the permission", async () => {
+ await renderWorkspacePage();
+ await clickGrantAccess();
+ const callout = () =>
+ container.querySelector("[data-testid='direct-execution-callout']");
+ expect(callout()).toBeNull();
+ await selectRole("roles/projectViewer");
+ expect(callout()).toBeNull();
+ await selectRole("roles/sqlEditorUser");
+ expect(callout()?.getAttribute("data-lead")).toBe("binding");
+ expect(callout()?.getAttribute("data-scope")).toBe("all");
+ });
+});
+
describe("MembersPage onboarding intro", () => {
it("binds Grant Access only on the editable workspace page", async () => {
await renderWorkspacePage();
diff --git a/frontend/src/routes/workspace/MembersPage.tsx b/frontend/src/routes/workspace/MembersPage.tsx
index 42304e9dda..a20a13c5c6 100644
--- a/frontend/src/routes/workspace/MembersPage.tsx
+++ b/frontend/src/routes/workspace/MembersPage.tsx
@@ -22,8 +22,8 @@ import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { WORKSPACE_ROUTE_GROUPS } from "@/app/router";
import { AccountMultiSelect } from "@/components/AccountMultiSelect";
+import { AccountTypeBadge } from "@/components/AccountTypeBadge";
import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/components/DatabaseResourceSelector";
-import { EnvironmentSelect } from "@/components/EnvironmentSelect";
import { ExprEditor, type OptionConfig } from "@/components/ExprEditor";
import { FeatureBadge } from "@/components/FeatureBadge";
import { HumanizeTs } from "@/components/HumanizeTs";
@@ -35,7 +35,9 @@ import {
ProjectPageToolbar,
} from "@/components/ProjectPageLayout";
import { RoleSelect } from "@/components/RoleSelect";
-import { DDLWarningCallout } from "@/components/role-grant/DDLWarningCallout";
+import { DirectExecutionCallout } from "@/components/role-grant/DirectExecutionCallout";
+import { DirectExecutionField } from "@/components/role-grant/DirectExecutionField";
+import { RoleDescription } from "@/components/role-grant/RoleDescription";
import { UserCell } from "@/components/UserCell";
import { Alert } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
@@ -69,7 +71,11 @@ import {
WorkspacePageLayout,
WorkspacePageToolbar,
} from "@/components/WorkspacePageLayout";
-import { useCurrentUser } from "@/hooks/useAppState";
+import {
+ useCurrentUser,
+ useEnvironmentList,
+ usePlanFeature,
+} from "@/hooks/useAppState";
import { useEscapeKey } from "@/hooks/useEscapeKey";
import { useProjectByName } from "@/hooks/useProjectByName";
import {
@@ -80,8 +86,16 @@ import {
GRANT_ACCESS_PRODUCT_INTRO,
useProductIntro,
} from "@/lib/productIntro";
+import {
+ type DirectExecutionValue,
+ directExecutionEnvironments,
+ directExecutionOf,
+ EMPTY_DIRECT_EXECUTION,
+ isDirectExecutionValid,
+} from "@/lib/project-member/directExecution";
import {
getRoleEnvironmentLimitationKind,
+ getRolesEnvironmentLimitationKind,
roleHasDatabaseLimitation,
} from "@/lib/project-member/utils";
import { displayRoleTitleFromList } from "@/lib/role";
@@ -117,7 +131,6 @@ import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import type { User } from "@/types/proto-es/v1/user_service_pb";
import type { GroupBinding, MemberBinding } from "@/types/v1/member";
-import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
import {
batchConvertParsedExprToCELString,
formatAbsoluteDateTime,
@@ -136,12 +149,11 @@ import {
import {
buildConditionExpr,
convertFromExpr,
+ readableCondition,
stringifyConditionExpression,
} from "@/utils/issue/cel";
-import { MemberBindingEnvironmentBanner } from "./MemberBindingEnvironmentBanner";
import { MemberDatabaseResourceName } from "./MemberDatabaseResourceName";
import { getSetIamPolicyPermissionGuardConfig } from "./membersPageActions";
-import { getProjectRoleBindingEnvironmentLimitationState } from "./membersPageEnvironment";
const EMPTY_ROLE_SET = new Set<string>();
@@ -454,22 +466,9 @@ function MemberTable({
{t("settings.members.pending-invite")}
</Badge>
)}
- {mb.type === "users" &&
- mb.user?.email &&
- getAccountTypeByEmail(mb.user.email) ===
- AccountType.SERVICE_ACCOUNT && (
- <Badge variant="secondary" className="text-xs">
- {t("settings.members.service-account")}
- </Badge>
- )}
- {mb.type === "users" &&
- mb.user?.email &&
- getAccountTypeByEmail(mb.user.email) ===
- AccountType.WORKLOAD_IDENTITY && (
- <Badge variant="secondary" className="text-xs">
- {t("settings.members.workload-identity")}
- </Badge>
- )}
+ {mb.type === "users" && (
+ <AccountTypeBadge email={mb.user?.email} />
+ )}
{mb.group && (
<span className="text-control-light text-xs">
({mb.group.members.length}{" "}
@@ -506,6 +505,7 @@ function MemberTable({
<Button
appearance="secondary"
size="sm"
+ aria-label={t("common.edit")}
onClick={() => onUpdateBinding(mb)}
>
<Pencil className="h-4 w-4" />
@@ -756,28 +756,9 @@ function MemberTableByRole({
{t("settings.members.pending-invite")}
</Badge>
)}
- {mb.type === "users" &&
- mb.user?.email &&
- getAccountTypeByEmail(mb.user.email) ===
- AccountType.SERVICE_ACCOUNT && (
- <Badge
- variant="secondary"
- className="text-xs"
- >
- {t("settings.members.service-account")}
- </Badge>
- )}
- {mb.type === "users" &&
- mb.user?.email &&
- getAccountTypeByEmail(mb.user.email) ===
- AccountType.WORKLOAD_IDENTITY && (
- <Badge
- variant="secondary"
- className="text-xs"
- >
- {t("settings.members.workload-identity")}
- </Badge>
- )}
+ {mb.type === "users" && (
+ <AccountTypeBadge email={mb.user?.email} />
+ )}
{mb.group?.deleted && (
<Badge
variant="destructive"
@@ -797,6 +778,7 @@ function MemberTableByRole({
<Button
appearance="secondary"
size="sm"
+ aria-label={t("common.edit")}
onClick={() => onUpdateBinding(mb)}
>
<Pencil className="h-4 w-4" />
@@ -928,7 +910,7 @@ interface RoleBindingFormState {
databaseMode: DatabaseMode;
databaseResources: DatabaseResource[];
exprGroup: ConditionGroupExpr;
- environments: string[];
+ directExecution: DirectExecutionValue;
}
// ============================================================
@@ -1095,10 +1077,10 @@ function ProjectRoleBindingForm({
() => form.role && roleHasDatabaseLimitation(form.role),
[form.role]
);
- const envKind = useMemo(
- () => (form.role ? getRoleEnvironmentLimitationKind(form.role) : undefined),
- [form.role]
- );
+ // Not memoized: the role store may fill in after the form mounts.
+ const envKind = form.role
+ ? getRoleEnvironmentLimitationKind(form.role)
+ : undefined;
const handleRoleChange = (role: string) => {
onChange({
@@ -1107,7 +1089,7 @@ function ProjectRoleBindingForm({
databaseMode: "ALL",
databaseResources: [],
exprGroup: wrapAsGroup(emptySimpleExpr()),
- environments: [],
+ directExecution: EMPTY_DIRECT_EXECUTION,
});
};
@@ -1171,6 +1153,7 @@ function ProjectRoleBindingForm({
multiple={false}
scope="project"
/>
+ <RoleDescription role={form.role} roleList={roleList} />
</FormField>
{/* Permissions display */}
@@ -1238,17 +1221,13 @@ function ProjectRoleBindingForm({
/>
)}
- {/* Environments (conditional on role) */}
{envKind && (
- <FormField title={<>{t("common.environments")}</>}>
- <DDLWarningCallout type="drawer" kind={envKind} />
- <EnvironmentSelect
- multiple
- portal
- value={form.environments}
- onChange={(envs) => onChange({ ...form, environments: envs })}
- />
- </FormField>
+ <DirectExecutionField
+ kind={envKind}
+ lead="grant"
+ value={form.directExecution}
+ onChange={(next) => onChange({ ...form, directExecution: next })}
+ />
)}
{/* Expiration */}
@@ -1346,6 +1325,10 @@ function EditMemberRoleDrawer({
initialBindings?: string[];
}) {
const { t } = useTranslation();
+ const environmentList = useEnvironmentList();
+ const hasEnvTierFeature = usePlanFeature(
+ PlanFeature.FEATURE_ENVIRONMENT_TIERS
+ );
const patchWorkspaceIamPolicy = useAppStore(
(state) => state.patchWorkspaceIamPolicy
);
@@ -1428,7 +1411,7 @@ function EditMemberRoleDrawer({
databaseMode: "ALL",
databaseResources: [],
exprGroup: wrapAsGroup(emptySimpleExpr()),
- environments: [],
+ directExecution: EMPTY_DIRECT_EXECUTION,
}));
useEscapeKey(true, onClose);
@@ -1556,7 +1539,7 @@ function EditMemberRoleDrawer({
const environments =
form.role &&
getRoleEnvironmentLimitationKind(form.role) !== undefined
- ? form.environments
+ ? directExecutionEnvironments(form.directExecution)
: undefined;
const hasCondition =
form.expirationTimestampInMS !== undefined ||
@@ -1744,6 +1727,11 @@ function EditMemberRoleDrawer({
}
};
+ // The simple role picker writes bindings without an environment clause, so a
+ // DDL/DML role granted here runs everywhere; say so before it is saved.
+ const unscopedDirectExecutionKind =
+ getRolesEnvironmentLimitationKind(selectedRoles);
+
const allowConfirm = isProjectCreateMode
? selectedBindings.length > 0 &&
!!form.role &&
@@ -1757,7 +1745,8 @@ function EditMemberRoleDrawer({
roleHasDatabaseLimitation(form.role) &&
form.databaseMode === "EXPRESSION" &&
!validateSimpleExpr(form.exprGroup)
- )
+ ) &&
+ isDirectExecutionValid(form.directExecution)
: isEditMode
? selectedRoles.length > 0
: selectedBindings.length > 0 && selectedRoles.length > 0;
@@ -1796,10 +1785,9 @@ function EditMemberRoleDrawer({
)}
{liveProjectRoleBindings.map((binding, idx) => {
const rows = getSingleBindingRows(binding);
- const envLimitation =
- getProjectRoleBindingEnvironmentLimitationState(binding);
- const bindingKind = getRoleEnvironmentLimitationKind(
- binding.role
+ const directExecution = directExecutionOf(
+ binding.role,
+ readableCondition(binding.parsedExpr)
);
const isExpired = isBindingPolicyExpired(binding);
return (
@@ -1827,33 +1815,27 @@ function EditMemberRoleDrawer({
</Badge>
)}
</div>
- <div className="flex items-center gap-x-1">
- <Button
- appearance="secondary"
- size="sm"
- title={t("common.edit")}
- onClick={() => setShowNestedGrant(true)}
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- appearance="secondary"
- size="sm"
- title={t("common.delete")}
- disabled={isRequesting}
- onClick={() => handleDeleteRole(binding)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
+ {/* Delete only: the grant form adds a role, so a
+ pencil here would read as editing this one. */}
+ <Button
+ appearance="secondary"
+ size="sm"
+ title={t("common.delete")}
+ disabled={isRequesting}
+ onClick={() => handleDeleteRole(binding)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
</div>
- {/* Environment info banner */}
- {envLimitation && bindingKind && (
+ {directExecution && (
<div className="mx-4 mt-3">
- <MemberBindingEnvironmentBanner
- envLimitation={envLimitation}
- bindingKind={bindingKind}
+ <DirectExecutionCallout
+ kind={directExecution.kind}
+ lead="binding"
+ scope={directExecution.scope}
+ environmentList={environmentList}
+ hasEnvTierFeature={hasEnvTierFeature}
/>
</div>
)}
@@ -1990,6 +1972,15 @@ function EditMemberRoleDrawer({
onChange={setSelectedRoles}
scope={projectName ? "project" : undefined}
/>
+ {unscopedDirectExecutionKind && (
+ <DirectExecutionCallout
+ kind={unscopedDirectExecutionKind}
+ lead="binding"
+ scope={{ type: "all" }}
+ environmentList={environmentList}
+ hasEnvTierFeature={hasEnvTierFeature}
+ />
+ )}
</FormField>
)}
</div>
diff --git a/frontend/src/routes/workspace/membersPageEnvironment.test.ts b/frontend/src/routes/workspace/membersPageEnvironment.test.ts
deleted file mode 100644
index 03b78a833e..0000000000
--- a/frontend/src/routes/workspace/membersPageEnvironment.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// @vitest-environment node
-import { describe, expect, test, vi } from "vitest";
-import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
-import { getProjectRoleBindingEnvironmentLimitationState } from "./membersPageEnvironment";
-
-vi.mock("@/lib/project-member/utils", () => ({
- getRoleEnvironmentLimitationKind: (role: string) =>
- role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
-}));
-
-vi.mock("@/utils/issue/cel", () => ({
- convertFromExpr: (expr: { environments?: string[] }) => ({
- environments: expr.environments,
- }),
-}));
-
-const binding = (role: string, environments?: string[]): Binding =>
- ({
- role,
- parsedExpr: environments === undefined ? {} : { environments },
- }) as Binding;
-
-const bindingWithoutParsedExpr = (role: string): Binding =>
- ({
- role,
- }) as Binding;
-
-describe("getProjectRoleBindingEnvironmentLimitation", () => {
- test("returns undefined for roles without DDL or DML environment restrictions", () => {
- expect(
- getProjectRoleBindingEnvironmentLimitationState(
- binding("roles/viewer", [])
- )
- ).toBeUndefined();
- });
-
- test("returns unrestricted when a DDL/DML role has no environment condition", () => {
- expect(
- getProjectRoleBindingEnvironmentLimitationState(
- binding("roles/sqlEditorUser")
- )
- ).toEqual({
- type: "unrestricted",
- });
- });
-
- test("returns unrestricted when a DDL/DML role has no parsed condition", () => {
- expect(
- getProjectRoleBindingEnvironmentLimitationState(
- bindingWithoutParsedExpr("roles/sqlEditorUser")
- )
- ).toEqual({
- type: "unrestricted",
- });
- });
-
- test("preserves explicit empty environment restrictions", () => {
- expect(
- getProjectRoleBindingEnvironmentLimitationState(
- binding("roles/sqlEditorUser", [])
- )
- ).toEqual({
- environments: [],
- type: "restricted",
- });
- });
-});
diff --git a/frontend/src/routes/workspace/membersPageEnvironment.ts b/frontend/src/routes/workspace/membersPageEnvironment.ts
deleted file mode 100644
index 55a92cd7a5..0000000000
--- a/frontend/src/routes/workspace/membersPageEnvironment.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { getRoleEnvironmentLimitationKind } from "@/lib/project-member/utils";
-import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
-import { convertFromExpr } from "@/utils/issue/cel";
-
-export type ProjectRoleBindingEnvironmentLimitationState =
- | {
- type: "unrestricted";
- }
- | {
- environments: string[];
- type: "restricted";
- };
-
-export const getProjectRoleBindingEnvironmentLimitationState = (
- binding: Binding
-): ProjectRoleBindingEnvironmentLimitationState | undefined => {
- if (getRoleEnvironmentLimitationKind(binding.role) === undefined) {
- return undefined;
- }
-
- if (!binding.parsedExpr) {
- return {
- type: "unrestricted",
- };
- }
-
- const environments = convertFromExpr(binding.parsedExpr).environments;
- if (environments === undefined) {
- return {
- type: "unrestricted",
- };
- }
-
- return {
- environments,
- type: "restricted",
- };
-};
diff --git a/frontend/src/test-utils/directExecutionDriver.ts b/frontend/src/test-utils/directExecutionDriver.ts
new file mode 100644
index 0000000000..714db63653
--- /dev/null
+++ b/frontend/src/test-utils/directExecutionDriver.ts
@@ -0,0 +1,28 @@
+import { act } from "@testing-library/react";
+
+/**
+ * Drives the direct-execution field inside a form test that stubs
+ * `EnvironmentSelect` with `environmentSelectStub` and renders into the
+ * document: the switch, and the stub's "pick Staging" target.
+ */
+export const directExecutionDriver = (flush: () => Promise<void>) => {
+ const getSwitch = () =>
+ document.querySelector("[role='switch']") as HTMLElement;
+ return {
+ getSwitch,
+ async toggle(): Promise<void> {
+ await act(async () => {
+ getSwitch().click();
+ });
+ await flush();
+ },
+ async pickStaging(): Promise<void> {
+ await act(async () => {
+ (
+ document.querySelector("[data-testid='pick-staging']") as HTMLElement
+ ).click();
+ });
+ await flush();
+ },
+ };
+};
diff --git a/frontend/src/test-utils/environmentSelectStub.tsx b/frontend/src/test-utils/environmentSelectStub.tsx
new file mode 100644
index 0000000000..07faf3af41
--- /dev/null
+++ b/frontend/src/test-utils/environmentSelectStub.tsx
@@ -0,0 +1,67 @@
+import type { ReactNode } from "react";
+import type { Environment } from "@/types/v1/environment";
+
+/** Two environments, one of them protected, for any test that needs a list. */
+export const STUB_ENVIRONMENTS = [
+ {
+ id: "staging",
+ name: "environments/staging",
+ title: "Staging",
+ tags: {},
+ color: "",
+ },
+ {
+ id: "prod",
+ name: "environments/prod",
+ title: "Prod",
+ tags: { protected: "protected" },
+ color: "",
+ },
+] as unknown as Environment[];
+
+/**
+ * A stand-in for `EnvironmentSelect` that exposes what a form test drives:
+ * the current value, one row per environment with its suffix, and a target
+ * that picks Staging, without the store the real picker reads from.
+ * Use as `vi.mock("@/components/EnvironmentSelect", async () =>
+ * (await import("@/test-utils/environmentSelectStub")).environmentSelectStub())`.
+ */
+export const environmentSelectStub = () => ({
+ EnvironmentSelect: ({
+ value,
+ onChange,
+ placeholder,
+ renderSuffix,
+ }: {
+ value: string[];
+ onChange: (next: string[]) => void;
+ placeholder?: string;
+ renderSuffix?: (environment: Environment) => ReactNode;
+ }) => (
+ <div data-testid="env-multi-select" data-value={value.join(",")}>
+ <span>{placeholder}</span>
+ {STUB_ENVIRONMENTS.map((environment) => (
+ <span key={environment.name} data-testid="env-option">
+ {environment.title}
+ {renderSuffix?.(environment)}
+ </span>
+ ))}
+ <span
+ data-testid="pick-staging"
+ onClick={() => onChange(["environments/staging"])}
+ />
+ </div>
+ ),
+});
+
+/**
+ * A stand-in for `EnvironmentBadge` that shows only the name it was given,
+ * so a chip assertion reads the resolved environment and nothing else.
+ * Use as `vi.mock("@/components/EnvironmentLabel", async () =>
+ * (await import("@/test-utils/environmentSelectStub")).environmentBadgeStub())`.
+ */
+export const environmentBadgeStub = () => ({
+ EnvironmentBadge: ({ environment }: { environment: { name: string } }) => (
+ <span data-testid="env-label">{environment.name}</span>
+ ),
+});
diff --git a/frontend/src/test-utils/i18n.ts b/frontend/src/test-utils/i18n.ts
new file mode 100644
index 0000000000..f082e478b1
--- /dev/null
+++ b/frontend/src/test-utils/i18n.ts
@@ -0,0 +1,15 @@
+/**
+ * A react-i18next stand-in that keeps what a test might be about: the key,
+ * and the variables interpolated into it (appended as JSON so an assertion
+ * can read them back). `vi.mock` is hoisted above imports, so use it as
+ * `vi.mock("react-i18next", async () =>
+ * (await import("@/test-utils/i18n")).reactI18nextStub())`.
+ */
+export const reactI18nextStub = () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, unknown>) =>
+ vars ? `${key} ${JSON.stringify(vars)}` : key,
+ i18n: { language: "en-US" },
+ }),
+});
diff --git a/frontend/src/types/v1/environment.test.ts b/frontend/src/types/v1/environment.test.ts
new file mode 100644
index 0000000000..e3a3a85368
--- /dev/null
+++ b/frontend/src/types/v1/environment.test.ts
@@ -0,0 +1,45 @@
+// @vitest-environment node
+import { describe, expect, test } from "vitest";
+import {
+ type Environment,
+ isProtectedEnvironment,
+ NULL_ENVIRONMENT_NAME,
+ resolveEnvironment,
+ unknownEnvironment,
+} from "./environment";
+
+const env = (name: string, title: string, tags?: Record<string, string>) =>
+ ({ ...unknownEnvironment(), name, title, tags: tags ?? {} }) as Environment;
+
+const list = [env("environments/prod", "Production")];
+
+describe("resolveEnvironment", () => {
+ test("a name in the list resolves to that environment", () => {
+ expect(resolveEnvironment("environments/prod", list).title).toBe(
+ "Production"
+ );
+ });
+
+ test("a name the list no longer has is titled by its id", () => {
+ const gone = resolveEnvironment("environments/gone", list);
+ expect(gone.name).toBe("environments/gone");
+ expect(gone.title).toBe("gone");
+ });
+
+ test("no name is the null environment", () => {
+ expect(resolveEnvironment("", list).name).toBe(NULL_ENVIRONMENT_NAME);
+ });
+});
+
+describe("isProtectedEnvironment", () => {
+ test("needs both the tag and the feature", () => {
+ const prod = env("environments/prod", "Production", {
+ protected: "protected",
+ });
+ expect(isProtectedEnvironment(prod, true)).toBe(true);
+ expect(isProtectedEnvironment(prod, false)).toBe(false);
+ expect(isProtectedEnvironment(env("environments/dev", "Dev"), true)).toBe(
+ false
+ );
+ });
+});
diff --git a/frontend/src/types/v1/environment.ts b/frontend/src/types/v1/environment.ts
index 9803a9c32c..2f0b249afb 100644
--- a/frontend/src/types/v1/environment.ts
+++ b/frontend/src/types/v1/environment.ts
@@ -52,3 +52,31 @@ export const isValidEnvironmentName = (name: unknown): name is string => {
export const formatEnvironmentName = (envId: string): string => {
return `${environmentNamePrefix}${envId}`;
};
+
+// The environment a resource name refers to. A valid name the list no longer
+// has (renamed or deleted since the reference was written) resolves to a
+// placeholder titled by its id, so the reference still reads; the null and
+// malformed names resolve to their sentinels.
+export const resolveEnvironment = (
+ name: string,
+ environmentList: Environment[]
+): Environment => {
+ if (!name || name === NULL_ENVIRONMENT_NAME) {
+ return nullEnvironment();
+ }
+ const environment = environmentList.find((env) => env.name === name);
+ if (environment) {
+ return environment;
+ }
+ if (!isValidEnvironmentName(name)) {
+ return unknownEnvironment();
+ }
+ const id = name.replace(/^environments\//, "");
+ return { ...unknownEnvironment(), id, name, title: id };
+};
+
+// The protected tag only means something on plans with environment tiers.
+export const isProtectedEnvironment = (
+ environment: Environment,
+ hasEnvTierFeature: boolean
+): boolean => hasEnvTierFeature && environment.tags?.protected === "protected";
diff --git a/frontend/src/utils/issue/cel.test.ts b/frontend/src/utils/issue/cel.test.ts
new file mode 100644
index 0000000000..c29c3c6f15
--- /dev/null
+++ b/frontend/src/utils/issue/cel.test.ts
@@ -0,0 +1,125 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import {
+ type Expr,
+ ExprSchema,
+} from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";
+import {
+ convertFromExpr,
+ readableCondition,
+ stringifyConditionExpression,
+} from "./cel";
+
+// Trees shaped as the server's parser returns them.
+const ident = (name: string) =>
+ create(ExprSchema, { exprKind: { case: "identExpr", value: { name } } });
+const select = (operand: Expr, field: string) =>
+ create(ExprSchema, {
+ exprKind: { case: "selectExpr", value: { operand, field } },
+ });
+const call = (fn: string, ...args: Expr[]) =>
+ create(ExprSchema, {
+ exprKind: { case: "callExpr", value: { function: fn, args } },
+ });
+const constant = (
+ constantKind:
+ | { case: "stringValue"; value: string }
+ | { case: "boolValue"; value: boolean }
+ | { case: "int64Value"; value: bigint }
+) =>
+ create(ExprSchema, {
+ exprKind: { case: "constExpr", value: { constantKind } },
+ });
+const str = (value: string) => constant({ case: "stringValue", value });
+const bool = (value: boolean) => constant({ case: "boolValue", value });
+const int = (value: number) =>
+ constant({ case: "int64Value", value: BigInt(value) });
+const list = (...elements: Expr[]) =>
+ create(ExprSchema, { exprKind: { case: "listExpr", value: { elements } } });
+const resource = (field: string) => select(ident("resource"), field);
+const eq = (attribute: string, value: string) =>
+ call("_==_", resource(attribute), str(value));
+const envIn = (...ids: string[]) =>
+ call("@in", resource("environment_id"), list(...ids.map(str)));
+const timeBefore = (iso: string) =>
+ call("_<_", select(ident("request"), "time"), call("timestamp", str(iso)));
+const and = (...exprs: Expr[]) =>
+ exprs.reduce((left, right) => call("_&&_", left, right));
+const or = (...exprs: Expr[]) =>
+ exprs.reduce((left, right) => call("_||_", left, right));
+
+const environments = (expr: Expr) => readableCondition(expr).environments;
+const A = "instances/i/databases/a";
+
+describe("stringifyConditionExpression", () => {
+ test("the switch off is byte-for-byte the empty picker's clause", () => {
+ expect(stringifyConditionExpression({ environments: [] })).toBe(
+ "resource.environment_id in []"
+ );
+ expect(stringifyConditionExpression({ environments: undefined })).toBe("");
+ expect(
+ stringifyConditionExpression({
+ environments: ["environments/staging", "environments/prod"],
+ })
+ ).toBe('resource.environment_id in ["staging", "prod"]');
+ });
+});
+
+describe("readableCondition proves the environments and keeps the rest best-effort", () => {
+ test("the environment clause alone, and beside the other clauses the forms write", () => {
+ expect(environments(envIn())).toEqual([]);
+ expect(environments(envIn("test", "test"))).toEqual(["environments/test"]);
+ expect(
+ readableCondition(
+ and(
+ eq("database", A),
+ timeBefore("2026-10-01T00:00:00Z"),
+ envIn("prod")
+ )
+ )
+ ).toEqual({
+ databaseResources: [{ databaseFullName: A }],
+ expiredTime: "2026-10-01T00:00:00.000Z",
+ environments: ["environments/prod"],
+ });
+ });
+
+ test("the frontend builder's dotted ident is read too", () => {
+ expect(
+ environments(
+ call("@in", ident("resource.environment_id"), list(str("prod")))
+ )
+ ).toEqual(["environments/prod"]);
+ });
+
+ test("a clause under || or ! does not count: `in [] || true` is not the switch off", () => {
+ expect(convertFromExpr(or(envIn(), bool(true))).environments).toEqual([]);
+ expect(environments(or(envIn(), bool(true)))).toBeUndefined();
+ expect(environments(or(envIn("prod"), envIn("dev")))).toBeUndefined();
+ expect(
+ environments(and(bool(true), or(envIn("prod"), bool(true))))
+ ).toBeUndefined();
+ expect(environments(call("!_", envIn()))).toBeUndefined();
+ });
+
+ test("a computed or non-string environment list does not count", () => {
+ expect(
+ environments(
+ call(
+ "@in",
+ resource("environment_id"),
+ call("_+_", list(str("prod")), list(str("dev")))
+ )
+ )
+ ).toBeUndefined();
+ expect(
+ environments(call("@in", resource("environment_id"), list(int(1))))
+ ).toBeUndefined();
+ });
+
+ test("two root environment clauses intersect", () => {
+ expect(environments(and(envIn("prod", "dev"), envIn("dev")))).toEqual([
+ "environments/dev",
+ ]);
+ });
+});
diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.ts
index 45d5574f8e..5f478b9f75 100644
--- a/frontend/src/utils/issue/cel.ts
+++ b/frontend/src/utils/issue/cel.ts
@@ -1,8 +1,13 @@
import { create } from "@bufbuild/protobuf";
import dayjs from "dayjs";
-import { cloneDeep, head } from "lodash-es";
+import { cloneDeep, head, uniq } from "lodash-es";
import type { SimpleExpr } from "@/modules/cel";
-import { isRawStringExpr, resolveCELExpr } from "@/modules/cel";
+import {
+ constantStringOf,
+ factorNameOf,
+ isRawStringExpr,
+ resolveCELExpr,
+} from "@/modules/cel";
import {
databaseNamePrefix,
environmentNamePrefix,
@@ -353,21 +358,6 @@ const convertToCELString = (
return `(${topLevelCondition})`;
};
-export const convertFromCELString = async (
- cel: string
-): Promise<ConditionExpression> => {
- let expr: Expr | undefined;
- if (cel) {
- const celExpr = await batchConvertCELStringToParsedExpr([cel]);
- expr = celExpr[0];
- }
- if (!expr) {
- return {};
- }
-
- return convertFromExpr(expr);
-};
-
export const batchConvertFromCELString = async (
cels: string[]
): Promise<ConditionExpression[]> => {
@@ -383,6 +373,76 @@ export const batchConvertFromCELString = async (
return resp;
};
+/**
+ * A condition as the member drawer and the approver's card show it. The
+ * environments decide the direct-execution row, whose *none* sentence is an
+ * assurance, so they count only as the condition proves them: a literal
+ * `resource.environment_id in […]` at the root of the `&&` chain of the
+ * server's syntax tree, since a conjunct only narrows (two intersect). Any
+ * other clause reads as every environment; `convertFromExpr` also finds one
+ * under `||` or `!` and would read `in [] || true` as the switch off. The
+ * databases and the expiry are `convertFromExpr`'s.
+ */
+export const readableCondition = (
+ expr: Expr | undefined
+): ConditionExpression =>
+ expr
+ ? { ...convertFromExpr(expr), environments: provenEnvironments(expr) }
+ : { databaseResources: [] };
+
+export const readableConditionFromCELString = async (
+ cel: string
+): Promise<ConditionExpression> =>
+ readableCondition(
+ cel ? (await batchConvertCELStringToParsedExpr([cel]))[0] : undefined
+ );
+
+const provenEnvironments = (expr: Expr): string[] | undefined => {
+ let environments: string[] | undefined;
+ for (const member of conjuncts(expr)) {
+ const clause = environmentClauseOf(member);
+ if (clause) {
+ const allowed = new Set(clause);
+ environments =
+ environments === undefined
+ ? clause
+ : environments.filter((name) => allowed.has(name));
+ }
+ }
+ return environments;
+};
+
+const callOf = (expr: Expr | undefined) =>
+ expr?.exprKind?.case === "callExpr" ? expr.exprKind.value : undefined;
+
+const conjuncts = (expr: Expr): Expr[] => {
+ const call = callOf(expr);
+ return call?.function === "_&&_" ? call.args.flatMap(conjuncts) : [expr];
+};
+
+const stringList = (expr: Expr | undefined): string[] | undefined => {
+ if (expr?.exprKind?.case !== "listExpr") {
+ return undefined;
+ }
+ const values = expr.exprKind.value.elements.map(constantStringOf);
+ return values.every((value): value is string => value !== undefined)
+ ? values
+ : undefined;
+};
+
+// `resource.environment_id in [literal strings]`, as environment names.
+const environmentClauseOf = (expr: Expr): string[] | undefined => {
+ const call = callOf(expr);
+ if (
+ call?.function !== "@in" ||
+ factorNameOf(call.args[0]) !== CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID
+ ) {
+ return undefined;
+ }
+ const ids = stringList(call.args[1]);
+ return ids && uniq(ids).map((id) => `${environmentNamePrefix}${id}`);
+};
+
export const convertFromExpr = (expr: Expr): ConditionExpression => {
const simpleExpr = resolveCELExpr(expr);
const conditionExpression: ConditionExpression = {
diff --git a/frontend/src/utils/string.test.ts b/frontend/src/utils/string.test.ts
index 9be2e7bd97..71646ac857 100644
--- a/frontend/src/utils/string.test.ts
+++ b/frontend/src/utils/string.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { normalizeTitle } from "./string";
+import { formatList, normalizeTitle } from "./string";
describe("normalizeTitle", () => {
it("trims plain ASCII whitespace", () => {
@@ -37,3 +37,31 @@ describe("normalizeTitle", () => {
expect(normalizeTitle("\uFEFF")).toBe("\uFEFF");
});
});
+
+describe("formatList", () => {
+ it.each(["en-US", "zh-CN", "ja-JP", "es-ES", "vi-VN"])(
+ "keeps the names apart in %s",
+ (language) => {
+ const joined = formatList(["Staging", "Prod"], language);
+ expect(joined).toContain("Staging");
+ expect(joined).toContain("Prod");
+ expect(joined).not.toBe("StagingProd");
+ }
+ );
+
+ it("returns a single name unchanged", () => {
+ expect(formatList(["Prod"], "en-US")).toBe("Prod");
+ });
+
+ it("falls back to commas where the browser has no Intl.ListFormat", () => {
+ const descriptor = Object.getOwnPropertyDescriptor(Intl, "ListFormat");
+ Reflect.deleteProperty(Intl, "ListFormat");
+ try {
+ expect(formatList(["Staging", "Prod"], "en-US")).toBe("Staging, Prod");
+ } finally {
+ if (descriptor) {
+ Object.defineProperty(Intl, "ListFormat", descriptor);
+ }
+ }
+ });
+});
diff --git a/frontend/src/utils/string.ts b/frontend/src/utils/string.ts
index 66eb4e3914..f8dabe152a 100644
--- a/frontend/src/utils/string.ts
+++ b/frontend/src/utils/string.ts
@@ -40,3 +40,11 @@ export function hashCode(s: string): number {
}
return hash;
}
+
+// Joins display names the way the reader's locale does ("a, b, and c").
+// Always the conjunction style: "unit" renders zh-CN with no separator. The
+// build still targets browsers without Intl.ListFormat, which get commas.
+export const formatList = (items: string[], language: string): string =>
+ typeof Intl.ListFormat === "function"
+ ? new Intl.ListFormat(language, { type: "conjunction" }).format(items)
+ : items.join(", ");
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.ts
index 8eadd8f530..52871e9325 100644
--- a/frontend/tests/e2e/framework/api-client.ts
+++ b/frontend/tests/e2e/framework/api-client.ts
@@ -645,6 +645,26 @@ export class BytebaseApiClient {
});
}
+ // A role-grant request on `user`'s behalf; the caller is its creator.
+ async createRoleGrantIssue(
+ project: string,
+ roleGrant: { role: string; user: string; expression?: string },
+ title: string,
+ ): Promise<{ name: string }> {
+ return this.request("POST", `/v1/${project}/issues`, {
+ title,
+ type: "ROLE_GRANT",
+ roleGrant: {
+ role: roleGrant.role,
+ user: roleGrant.user,
+ condition:
+ roleGrant.expression === undefined
+ ? undefined
+ : { expression: roleGrant.expression },
+ },
+ });
+ }
+
// Draft review Issues are the UI-authored Plan lifecycle boundary. They stay
// hidden from active review until the Plan Detail "Ready for Review" action
// flips only the draft field.
diff --git a/frontend/tests/e2e/project-members/project-members.page.ts b/frontend/tests/e2e/project-members/project-members.page.ts
new file mode 100644
index 0000000000..5979a34219
--- /dev/null
+++ b/frontend/tests/e2e/project-members/project-members.page.ts
@@ -0,0 +1,81 @@
+import type { Locator, Page } from "@playwright/test";
+
+// Project members page, its Grant Access sheet, and a member's edit drawer.
+export class ProjectMembersPage {
+ readonly page: Page;
+ readonly baseURL: string;
+ readonly sheet: Locator;
+ readonly grantAccessButton: Locator;
+ readonly createButton: Locator;
+ readonly directExecutionSwitch: Locator;
+ readonly environmentPicker: Locator;
+
+ constructor(page: Page, baseURL = "") {
+ this.page = page;
+ this.baseURL = baseURL;
+ // Toasts also carry role="dialog" (with a data-type); the sheet does not.
+ this.sheet = page.locator("[role='dialog']:not([data-type])");
+ this.grantAccessButton = page.getByRole("button", { name: "Grant Access" });
+ this.createButton = this.sheet.getByRole("button", { name: "Create", exact: true });
+ this.directExecutionSwitch = this.sheet.getByRole("switch");
+ this.environmentPicker = this.sheet.getByText("Select environments", { exact: true });
+ }
+
+ async goto(projectId: string): Promise<void> {
+ await this.page.goto(`${this.baseURL}/projects/${projectId}/members`);
+ await this.grantAccessButton.waitFor({ timeout: 15_000 });
+ }
+
+ async openGrantAccess(): Promise<void> {
+ await this.grantAccessButton.click();
+ await this.sheet.waitFor();
+ }
+
+ // Escape would close the whole sheet, so a popup is dismissed by clicking
+ // the sheet's own heading.
+ private async dismissPopup(): Promise<void> {
+ await this.sheet.getByRole("heading").first().click({ force: true });
+ }
+
+ // The same email and titles usually also sit in a table behind the sheet,
+ // so every pick stays inside the open listbox.
+ async pickAccount(email: string): Promise<void> {
+ await this.sheet.getByText("Select accounts", { exact: true }).click();
+ await this.page.getByPlaceholder("Search for more").fill(email);
+ await this.page.getByRole("listbox").getByText(email, { exact: true }).first().click();
+ await this.dismissPopup();
+ }
+
+ private async pickOption(trigger: Locator, title: string): Promise<void> {
+ await trigger.click();
+ await this.page
+ .getByRole("listbox")
+ .getByRole("option")
+ .filter({ has: this.page.getByText(title, { exact: true }) })
+ .first()
+ .click();
+ }
+
+ async pickRole(title: string): Promise<void> {
+ // The field title and the trigger placeholder both read "Assign role".
+ await this.pickOption(this.sheet.getByText("Assign role", { exact: true }).last(), title);
+ }
+
+ async pickEnvironment(title: string): Promise<void> {
+ await this.pickOption(this.environmentPicker, title);
+ await this.dismissPopup();
+ }
+
+ // Opens the member's edit drawer, which lists every binding with its
+ // direct-execution callout.
+ async openMember(email: string): Promise<void> {
+ const row = this.page.getByRole("row").filter({ hasText: email });
+ await row.getByRole("button", { name: "Edit" }).first().click();
+ await this.sheet.waitFor();
+ }
+
+ async closeSheet(): Promise<void> {
+ await this.page.keyboard.press("Escape");
+ await this.sheet.waitFor({ state: "hidden" });
+ }
+}
diff --git a/frontend/tests/e2e/project-members/project-members.spec.ts b/frontend/tests/e2e/project-members/project-members.spec.ts
new file mode 100644
index 0000000000..b17837b83d
--- /dev/null
+++ b/frontend/tests/e2e/project-members/project-members.spec.ts
@@ -0,0 +1,268 @@
+// Project members — the direct DDL/DML execution field on the grant form.
+//
+// A role that carries bb.sql.ddl / bb.sql.dml gets a switch instead of a bare
+// environment picker. Off writes `resource.environment_id in []` (the binding
+// adds no direct execution); on names the environments where a member runs
+// DDL/DML straight from SQL Editor. These tests own their user and bindings
+// and verify the form, the stored condition, what SQL Editor then does, what
+// the member list says, and what the approver's card says.
+import {
+ type BrowserContext,
+ expect,
+ type Page,
+ test,
+} from "@playwright/test";
+import type { BytebaseApiClient, IamPolicy } from "../framework/api-client";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { execSql, getInstancePgPort, querySql } from "../framework/psql";
+import { signInBrowserAs } from "../framework/sign-in";
+import { SqlEditorPage } from "../sql-editor/sql-editor.page";
+import { ProjectMembersPage } from "./project-members.page";
+
+test.setTimeout(180_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let pgPort: string;
+
+const TEST_PASSWORD = "e2e-members-pw-1!"; // NOSONAR — e2e fixture only
+const GRANTEE = {
+ email: "[email protected]",
+ title: "E2E Members Grantee",
+ authFile: ".auth/members-grantee.json",
+};
+const GRANTEE_MEMBER = `user:${GRANTEE.email}`;
+const SQL_EDITOR_USER_ROLE = "roles/sqlEditorUser";
+// hr_test lives in the sample "Test" environment.
+const PROBE_TABLE = "e2e_direct_exec_probe";
+
+// One signed-in grantee context for the two SQL Editor tests: the sign-in is
+// the setup bottleneck, and each test sets its own binding and drops the
+// probe table before it runs.
+let grantee: { context: BrowserContext; page: Page; sqlEditor: SqlEditorPage };
+
+// The grantee's stored SQL Editor User condition, "" when there is none.
+async function storedExpression(): Promise<string> {
+ const policy = await env.api.getProjectIamPolicy(env.project);
+ const binding = policy.bindings.find(
+ (b) => b.role === SQL_EDITOR_USER_ROLE && b.members.includes(GRANTEE_MEMBER),
+ );
+ return binding?.condition?.expression ?? "";
+}
+
+// Every policy change is one read and one write; a binding left without
+// members goes with it.
+async function editPolicy(edit: (policy: IamPolicy) => void): Promise<void> {
+ const policy = await env.api.getProjectIamPolicy(env.project);
+ edit(policy);
+ policy.bindings = policy.bindings.filter((b) => b.members.length > 0);
+ await env.api.setProjectIamPolicy(env.project, policy);
+}
+
+function dropGrantee(policy: IamPolicy, role?: string): void {
+ for (const binding of policy.bindings) {
+ if (!role || binding.role === role) {
+ binding.members = binding.members.filter((m) => m !== GRANTEE_MEMBER);
+ }
+ }
+}
+
+// Replaces the grantee's SQL Editor User binding with one carrying the expression.
+function setGranteeSqlEditorUser(expression: string): Promise<void> {
+ return editPolicy((policy) => {
+ dropGrantee(policy, SQL_EDITOR_USER_ROLE);
+ policy.bindings.push({
+ role: SQL_EDITOR_USER_ROLE,
+ members: [GRANTEE_MEMBER],
+ condition: { expression },
+ });
+ });
+}
+
+function dropProbeTable(): void {
+ execSql(env.databaseId, pgPort, `DROP TABLE IF EXISTS ${PROBE_TABLE}`);
+}
+
+// A positive oracle: psql failing for any other reason is an error, not "absent".
+function probeTableExists(): boolean {
+ return (
+ querySql(env.databaseId, pgPort, `SELECT to_regclass('public.${PROBE_TABLE}') IS NOT NULL`) ===
+ "t"
+ );
+}
+
+// Runs the CREATE TABLE and returns; each test waits for the outcome it
+// asserts. (`runPreparedQuery` waits for a row count or an ERROR, and a
+// refused DDL produces neither.)
+async function runProbeCreateAsGrantee(): Promise<void> {
+ await grantee.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await expect(grantee.sqlEditor.codeEditor).toBeVisible({ timeout: 30_000 });
+ await grantee.sqlEditor.setEditorContent(`CREATE TABLE ${PROBE_TABLE} (id INT PRIMARY KEY);`);
+ await grantee.sqlEditor.runButton.click();
+}
+
+test.beforeAll(async ({ browser }) => {
+ // The file-level timeout covers tests only; a hook keeps the 30 s default.
+ test.setTimeout(180_000);
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+ [pgPort] = await Promise.all([
+ getInstancePgPort(env),
+ // Idempotent: a retried run on the same server already has the user.
+ env.api.createUser(GRANTEE.email, TEST_PASSWORD, GRANTEE.title).catch((err: unknown) => {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (!msg.includes("(409)") && !msg.includes("already exists")) throw err;
+ }),
+ ]);
+ // Project Developer carries bb.plans.create, so a refused statement is
+ // answered with the change-plan hint instead of a bare error. Dropping the
+ // grantee first keeps a retried run from stacking bindings.
+ await Promise.all([
+ signInBrowserAs(browser, env.baseURL, GRANTEE.email, TEST_PASSWORD, GRANTEE.authFile),
+ editPolicy((policy) => {
+ dropGrantee(policy);
+ policy.bindings.push({ role: "roles/projectDeveloper", members: [GRANTEE_MEMBER] });
+ }),
+ ]);
+ const context = await browser.newContext({ storageState: GRANTEE.authFile });
+ const page = await context.newPage();
+ grantee = { context, page, sqlEditor: new SqlEditorPage(page, env.baseURL) };
+});
+
+// Guarded: a beforeAll that failed before these were assigned must not have
+// its error buried under a teardown error. Every binding the spec made goes.
+test.afterAll(async () => {
+ await grantee?.context.close();
+ if (pgPort) dropProbeTable();
+ if (env) await editPolicy((policy) => dropGrantee(policy));
+ // The user stays: DELETE deactivates rather than purges, and a retried
+ // run would then fail to sign in. The disposable server is torn down anyway.
+});
+
+test.describe("grant form", () => {
+ test("the switch is off by default, refuses a bare on, and writes the picked environment", async ({ page }) => {
+ const members = new ProjectMembersPage(page, env.baseURL);
+ await members.goto(projectId);
+ await members.openGrantAccess();
+ await members.pickAccount(GRANTEE.email);
+ await members.pickRole("SQL Editor User");
+
+ await expect(members.directExecutionSwitch).toHaveAttribute("aria-checked", "false");
+ await expect(members.sheet).toContainText("DDL/DML cannot run in SQL Editor without approval.");
+ await expect(members.environmentPicker).toHaveCount(0);
+
+ await members.directExecutionSwitch.click();
+ await expect(members.sheet).toContainText("At least one environment is required.");
+ await expect(members.createButton).toBeDisabled();
+
+ await members.pickEnvironment("Test");
+ await expect(members.sheet).toContainText(
+ "Members with this role can run DDL/DML in SQL Editor without approval in:",
+ );
+ await expect(members.createButton).toBeEnabled();
+ await members.createButton.click();
+ await expect(members.sheet).toBeHidden({ timeout: 10_000 });
+
+ await expect
+ .poll(storedExpression, { timeout: 10_000 })
+ .toContain('resource.environment_id in ["test"]');
+ });
+});
+
+test.describe("what the grant does in SQL Editor", () => {
+ test("on for Test: a CREATE TABLE runs immediately, with no plan offered", async () => {
+ await setGranteeSqlEditorUser('resource.environment_id in ["test"]');
+ dropProbeTable();
+
+ await runProbeCreateAsGrantee();
+
+ await expect(grantee.page.getByText(/rows affected/i).first()).toBeVisible({
+ timeout: 15_000,
+ });
+ expect(probeTableExists()).toBe(true);
+ await expect(grantee.page.getByText(/Data Change Plan/i)).toHaveCount(0);
+ });
+
+ test("off: the same statement is refused and answered with the change-plan hint", async () => {
+ await setGranteeSqlEditorUser("resource.environment_id in []");
+ dropProbeTable();
+
+ await runProbeCreateAsGrantee();
+
+ await expect(grantee.page.getByText(/Data Change Plan/i).first()).toBeVisible({
+ timeout: 15_000,
+ });
+ expect(probeTableExists()).toBe(false);
+ });
+});
+
+test.describe("member list", () => {
+ test("an off binding says it adds nothing; an on binding lists its environment; a clause under || reads as every environment", async ({ page }) => {
+ await setGranteeSqlEditorUser("resource.environment_id in []");
+ const members = new ProjectMembersPage(page, env.baseURL);
+ await members.goto(projectId);
+ await members.openMember(GRANTEE.email);
+ await expect(members.sheet).toContainText("DDL/DML cannot run in SQL Editor without approval.");
+ await members.closeSheet();
+
+ await setGranteeSqlEditorUser('resource.environment_id in ["test"]');
+ await members.goto(projectId);
+ await members.openMember(GRANTEE.email);
+ await expect(members.sheet).toContainText("Can run DDL/DML in SQL Editor without approval in:");
+ await expect(members.sheet.getByText("Test", { exact: true }).first()).toBeVisible();
+ // A binding is removed, never edited: the grant form only adds.
+ await expect(members.sheet.getByRole("button", { name: "Delete", exact: true }).first()).toBeVisible();
+ await expect(members.sheet.getByRole("button", { name: "Edit", exact: true })).toHaveCount(0);
+ await members.closeSheet();
+
+ // `|| true` makes the clause inert: only a clause at the root narrows.
+ await setGranteeSqlEditorUser("resource.environment_id in [] || true");
+ await members.goto(projectId);
+ await members.openMember(GRANTEE.email);
+ await expect(members.sheet).toContainText(
+ "Can run DDL/DML in SQL Editor in every environment without approval.",
+ );
+ });
+});
+
+// The approver's card reads the request's condition through the same parser
+// and reader. The API creates the requests on the grantee's behalf, so the
+// card also names the requester. Role requests need the approval-workflow
+// feature the suite's license provides. Last, because an approved request
+// grants the role, and afterAll drops every binding.
+test.describe("approver's card", () => {
+ const states: [string, string | undefined, string, string?][] = [
+ [
+ "on for Test",
+ 'resource.environment_id in ["test"]',
+ `Approving lets ${GRANTEE.title} run DDL/DML in SQL Editor without approval in:`,
+ "Test",
+ ],
+ ["off", "resource.environment_id in []", "DDL/DML cannot run in SQL Editor without approval."],
+ [
+ "no clause",
+ undefined,
+ "Can run DDL/DML in SQL Editor in every environment without approval.",
+ ],
+ [
+ "a clause under ||",
+ "resource.environment_id in [] || true",
+ "Can run DDL/DML in SQL Editor in every environment without approval.",
+ ],
+ ];
+ for (const [state, expression, text, chip] of states) {
+ test(`${state}: the execution row says what approving grants`, async ({ page }) => {
+ const issue = await env.api.createRoleGrantIssue(
+ env.project,
+ { role: SQL_EDITOR_USER_ROLE, user: `users/${GRANTEE.email}`, expression },
+ `e2e role grant, ${state}`,
+ );
+ await page.goto(`${env.baseURL}/projects/${projectId}/issues/${issue.name.split("/").pop()}`);
+ const card = page.getByTestId("role-grant-direct-execution");
+ await expect(card).toContainText(text, { timeout: 15_000 });
+ if (chip) await expect(card.getByText(chip, { exact: true })).toBeVisible();
+ await expect(page.getByText(/^Requested by /)).toBeVisible();
+ });
+ }
+});