Skip to content

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

fix(role-grant): permission-aware DDL/DML environment warnings (BYT-9390) (#20245)

zchpeter08ed6002a43e
diff --git a/docs/superpowers/plans/2026-05-07-byt-9390-ddl-dml-env-warning.md b/docs/superpowers/plans/2026-05-07-byt-9390-ddl-dml-env-warning.md
new file mode 100644
index 0000000000..e15bfa0f7e
--- /dev/null
+++ b/docs/superpowers/plans/2026-05-07-byt-9390-ddl-dml-env-warning.md
@@ -0,0 +1,1329 @@
+# BYT-9390 DDL/DML Environment-Grant Warnings — Implementation Plan
+
+> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Replace the current muted/blue messaging on four role-grant surfaces with a permission-aware yellow warning that frames the risk as "selecting an environment lets the grantee run DDL/DML directly in SQL Editor without approval."
+
+**Architecture:** A new permission-aware helper (`getRoleEnvironmentLimitationKind`) replaces the boolean `roleHasEnvironmentLimitation`. A new shared component (`DDLWarningCallout`) renders the warning copy in five surface variants (admin grant drawer, developer request drawer, approver issue page, member-list banner with envs, member-list banner without envs). **Five** new i18n keys (4 under `project.members.*`, 1 under `issue.role-grant.*`) replace **three** old keys across 10 locale files (Vue tree + React tree × 5 languages).
+
+**Semantic-equivalence note (anchor):** `getRoleEnvironmentLimitationKind` returns a defined value iff the role has `bb.sql.ddl` and/or `bb.sql.dml`. The boolean it replaces, `roleHasEnvironmentLimitation`, also checks exactly that pair (verified: `checkRoleContainsAnyPermission(role, "bb.sql.ddl", "bb.sql.dml")`). So `getRoleEnvironmentLimitationKind(role) !== undefined` is **bit-identical** to the old gate — no role's banner-visibility changes. Do not confuse with the *sibling* `roleHasDatabaseLimitation`, which checks five permissions including `bb.sql.select`; that helper is unchanged.
+
+**Tech Stack:** React, TypeScript, Tailwind v4 + Base UI, vitest + React Testing Library, vue-i18n locale files (JSON).
+
+**Spec:** `docs/superpowers/specs/2026-05-07-byt-9390-ddl-dml-env-warning-design.md`
+
+---
+
+## File Structure
+
+**Created files:**
+- `frontend/src/react/components/role-grant/DDLWarningCallout.tsx` — shared warning component (discriminated-union props).
+- `frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx` — RTL tests for each variant.
+- `frontend/src/components/ProjectMember/utils.test.ts` — vitest unit test for `getRoleEnvironmentLimitationKind`.
+- `frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx` — new test covering Environments row + warning banner.
+
+**Modified files:**
+- `frontend/src/components/ProjectMember/utils.ts` — replace boolean helper.
+- `frontend/src/react/pages/settings/MembersPage.tsx` — switch helper; replace drawer helper-text + member-list banner.
+- `frontend/src/react/pages/settings/RequestRoleSheet.tsx` — switch helper; add warning under env multiselect.
+- `frontend/src/react/pages/settings/membersPageEnvironment.ts` — switch helper.
+- `frontend/src/react/pages/settings/RequestRoleSheet.test.tsx` — update mock; add assertions.
+- `frontend/src/react/pages/settings/membersPageEnvironment.test.ts` — update mock; add `undefined` case.
+- `frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx` — add Environments row + warning banner.
+- `frontend/src/react/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove 3 old keys, add 5 new keys.
+- `frontend/src/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove 1 old key (`allow-ddl`).
+
+**Why this layout:** The new component lives under `react/components/role-grant/` (a new folder) because the same warning is consumed from three call-site domains (settings page, request drawer, issue-detail page). Putting it in any one of those domain folders would couple it to that domain. The helper change stays in `components/ProjectMember/utils.ts` so it remains discoverable next to its sibling `roleHasDatabaseLimitation`.
+
+---
+
+## Chunk 1: Foundation — helper, new EN copy, shared component
+
+### Task 1: Replace `roleHasEnvironmentLimitation` with `getRoleEnvironmentLimitationKind`
+
+**Files:**
+- Modify: `frontend/src/components/ProjectMember/utils.ts`
+- Create: `frontend/src/components/ProjectMember/utils.test.ts`
+
+- [ ] **Step 1.1: Write the failing unit test.**
+
+```ts
+// frontend/src/components/ProjectMember/utils.test.ts
+import { describe, expect, test, vi } from "vitest";
+import { getRoleEnvironmentLimitationKind } from "./utils";
+
+// Stub the role store — getRoleEnvironmentLimitationKind reads it once
+// per call. Other @/utils + @/store exports are stubbed as no-ops so a
+// sibling export's transitive imports don't crash.
+const fixtures: Record<string, string[]> = {
+ "roles/sqlEditorUser": ["bb.sql.ddl", "bb.sql.dml"],
+ "roles/sqlEditorDDLOnly": ["bb.sql.ddl"],
+ "roles/sqlEditorDMLOnly": ["bb.sql.dml"],
+ "roles/queryOnly": ["bb.sql.select"],
+ "roles/projectViewer": [],
+};
+vi.mock("@/store", () => ({
+ useRoleStore: () => ({
+ getRoleByName: (role: string) =>
+ fixtures[role] === undefined
+ ? undefined
+ : { name: role, permissions: fixtures[role] },
+ }),
+}));
+vi.mock("@/utils", () => ({
+ displayRoleTitle: (r: string) => r,
+ checkRoleContainsAnyPermission: () => false, // unused by the new helper
+}));
+
+describe("getRoleEnvironmentLimitationKind", () => {
+ test("returns 'DDL/DML' when role has both ddl and dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorUser")).toBe(
+ "DDL/DML"
+ );
+ });
+
+ test("returns 'DDL' when role has only ddl", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorDDLOnly")).toBe(
+ "DDL"
+ );
+ });
+
+ test("returns 'DML' when role has only dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorDMLOnly")).toBe(
+ "DML"
+ );
+ });
+
+ test("returns undefined when role has neither ddl nor dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/queryOnly")).toBeUndefined();
+ });
+
+ test("returns undefined for an unknown role", () => {
+ expect(
+ getRoleEnvironmentLimitationKind("roles/doesNotExist")
+ ).toBeUndefined();
+ });
+});
+```
+
+- [ ] **Step 1.2: Run the test and confirm it fails.**
+
+Run: `pnpm --dir frontend test -- src/components/ProjectMember/utils.test.ts`
+Expected: FAIL — `getRoleEnvironmentLimitationKind is not a function` (or "no exported member").
+
+- [ ] **Step 1.3: Implement the helper.**
+
+Replace the body of `frontend/src/components/ProjectMember/utils.ts`:
+
+```ts
+import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
+import { useRoleStore } from "@/store";
+import { checkRoleContainsAnyPermission, displayRoleTitle } from "@/utils";
+
+export const getBindingIdentifier = (binding: Binding): string => {
+ const identifier = [displayRoleTitle(binding.role)];
+ if (binding.condition && binding.condition.expression) {
+ identifier.push(binding.condition.expression);
+ }
+ return identifier.join(".");
+};
+
+export const roleHasDatabaseLimitation = (role: string) => {
+ return checkRoleContainsAnyPermission(
+ role,
+ "bb.sql.select",
+ "bb.sql.ddl",
+ "bb.sql.dml",
+ "bb.sql.explain",
+ "bb.sql.info"
+ );
+};
+
+// {{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.
+export const getRoleEnvironmentLimitationKind = (
+ role: string
+): EnvLimitationKind | undefined => {
+ const r = useRoleStore().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");
+ if (hasDDL && hasDML) return "DDL/DML";
+ if (hasDDL) return "DDL";
+ if (hasDML) return "DML";
+ return undefined;
+};
+
+// Transitional shim — keeps the build green while call sites migrate.
+// Removed in Task 10 once the last caller is gone.
+// @deprecated use getRoleEnvironmentLimitationKind instead.
+export const roleHasEnvironmentLimitation = (role: string): boolean =>
+ getRoleEnvironmentLimitationKind(role) !== undefined;
+```
+
+Note on the `useRoleStore()` call: this is a Pinia store accessor (returns a cached singleton), not a React hook. It's safe to call from a non-component utility — that's the same pattern `IssueDetailRoleGrantDetails.tsx` already uses inline.
+
+The boolean `roleHasEnvironmentLimitation` is kept as a **transitional shim** that delegates to the new helper. Tasks 4–7 migrate each production call site to `getRoleEnvironmentLimitationKind`; Task 10 deletes the shim once the last caller is gone. This keeps `git bisect` and partial-checkout workflows working across the migration.
+
+- [ ] **Step 1.4: Run the test and confirm it passes.**
+
+Run: `pnpm --dir frontend test -- src/components/ProjectMember/utils.test.ts`
+Expected: PASS — 5 cases.
+
+- [ ] **Step 1.5: Run full type-check to confirm tree still builds.**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS. The transitional shim keeps existing call sites compiling. Tasks 4–7 migrate each call site one at a time; the shim is removed in Task 10.
+
+- [ ] **Step 1.6: Commit.**
+
+```bash
+git add frontend/src/components/ProjectMember/utils.ts \
+ frontend/src/components/ProjectMember/utils.test.ts
+git commit -m "feat(role-grant): add getRoleEnvironmentLimitationKind helper
+
+Adds a permission-aware helper (returns 'DDL' / 'DML' / 'DDL/DML' /
+undefined) that will power upcoming DDL/DML warnings. The boolean
+roleHasEnvironmentLimitation stays as a transitional shim until call
+sites migrate; final shim removal in the cleanup commit.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 2: Add new English i18n keys (both Vue + React trees)
+
+**Files:**
+- Modify: `frontend/src/react/locales/en-US.json`
+- Modify: `frontend/src/locales/en-US.json` (no new keys here — Vue tree only loses `allow-ddl` later, no additions needed)
+
+We add only the **React tree** EN keys here. (The Vue tree never sees these surfaces.) Non-EN React locales pick up the new keys in Task 9; old-key removal is Task 10.
+
+- [ ] **Step 2.1: Add the five new keys to `frontend/src/react/locales/en-US.json`.**
+
+Insert under `project.members.*` (alphabetical placement near the existing `allow-ddl*` entries):
+
+```json
+"ddl-current-all": "{{kind}} statements can be directly run in SQL Editor in ALL environments without approval.",
+"ddl-current-none": "{{kind}} statements are not allowed to be run directly in SQL Editor in any environment.",
+"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.",
+```
+
+Insert under `issue.role-grant.*` (next to existing role-grant keys):
+
+```json
+"ddl-warning": "If approved, in {{environments}}, {{kind}} statements can be directly run in SQL Editor without further approval.",
+```
+
+Do **not** remove the old keys yet — they stay live until Task 10's sweep. Existing call sites still reference them.
+
+- [ ] **Step 2.2: Lint the JSON.**
+
+Run: `pnpm --dir frontend fix`
+Expected: no errors. Biome will sort keys alphabetically inside each object — this is the canonical layout.
+
+- [ ] **Step 2.3: Commit.**
+
+```bash
+git add frontend/src/react/locales/en-US.json
+git commit -m "i18n(en): add new ddl-warning + ddl-current-* keys
+
+New copy frames the risk around environment selection and is
+permission-aware ({{kind}} = DDL | DML | DDL/DML). Surfaces consume
+these in subsequent commits; old keys removed in the final sweep.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 3: Create the shared `DDLWarningCallout` component
+
+**Files:**
+- Create: `frontend/src/react/components/role-grant/DDLWarningCallout.tsx`
+- Create: `frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx`
+
+- [ ] **Step 3.1: Write the failing component tests.**
+
+```tsx
+// frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { DDLWarningCallout } from "./DDLWarningCallout";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ // Return the key + a JSON-encoded vars suffix so assertions can match
+ // both the i18n key and the interpolated values. We don't have access
+ // to the locale files in unit tests, so the actual locale value isn't
+ // rendered — just the key + vars, which is sufficient to verify the
+ // component picked the right key and threaded the right interpolation.
+ 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("issue variant renders issue.role-grant.ddl-warning with environments", () => {
+ render(
+ <DDLWarningCallout
+ type="issue"
+ kind="DDL"
+ environments={["Prod", "Test"]}
+ />,
+ );
+ const node = screen.getByText(/issue.role-grant.ddl-warning/);
+ expect(node).toHaveTextContent("DDL");
+ expect(node).toHaveTextContent("Prod, Test");
+ });
+
+ 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");
+ // Pin the contract: the warning copy itself must NOT interpolate
+ // env names. Consumers (e.g. MembersPage) render env badges as a
+ // separate row next to the warning. If a future implementer adds
+ // env interpolation to the i18n string, this assertion catches it.
+ 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();
+ });
+
+});
+
+// Type-level assertions — these functions are NEVER called. They live
+// outside any `it()` block so vitest doesn't execute them. Their sole
+// purpose is to fail `pnpm --dir frontend type-check` if the union
+// shape ever stops rejecting invalid prop combinations. (Spec §6.)
+//
+// `void _typeChecks` keeps eslint from flagging the function as unused.
+const _typeChecks = () => {
+ // @ts-expect-error — `binding-all` does not accept `environments`.
+ const _a = <DDLWarningCallout type="binding-all" kind="DDL" environments={["x"]} />;
+ // @ts-expect-error — `issue` requires `environments`.
+ const _b = <DDLWarningCallout type="issue" kind="DDL" />;
+ // @ts-expect-error — `drawer` does not accept `environments`.
+ const _c = <DDLWarningCallout type="drawer" kind="DDL" environments={["x"]} />;
+ return [_a, _b, _c];
+};
+void _typeChecks;
+```
+
+The thunk is never invoked, so `render(...)` calls never trip on missing `environments` at runtime — but `tsc` still type-checks the JSX inside, which is where the `@ts-expect-error` assertions fire.
+
+- [ ] **Step 3.2: Run the tests and confirm they fail.**
+
+Run: `pnpm --dir frontend test -- src/react/components/role-grant/DDLWarningCallout.test.tsx`
+Expected: FAIL — module not found.
+
+- [ ] **Step 3.3: Implement the component.**
+
+Verified precondition: `frontend/src/react/components/ui/alert.tsx` already exports `Alert` with `variant="warning"` (yellow background, ⚠ icon via `AlertTriangle`). No alert-primitive work needed.
+
+```tsx
+// frontend/src/react/components/role-grant/DDLWarningCallout.tsx
+import { useTranslation } from "react-i18next";
+import type { EnvLimitationKind } from "@/components/ProjectMember/utils";
+import { Alert } from "@/react/components/ui/alert";
+
+// Discriminated union (matches the codebase's `type:` discriminator
+// convention — see usePagedData.tsx, useDropdown.ts).
+// `environments` is required exactly when the variant interpolates
+// them ("issue") and absent everywhere else. Consumers needing to
+// render env badges (e.g. binding-some) carry the env list themselves
+// and render it as a separate row.
+type DDLWarningProps =
+ | { type: "drawer"; kind: EnvLimitationKind }
+ | { type: "issue"; kind: EnvLimitationKind; environments: string[] }
+ | { type: "binding-some"; kind: EnvLimitationKind }
+ | { type: "binding-all"; kind: EnvLimitationKind }
+ | { type: "binding-none"; kind: EnvLimitationKind };
+
+const typeToKey: Record<DDLWarningProps["type"], string> = {
+ drawer: "project.members.ddl-warning",
+ issue: "issue.role-grant.ddl-warning",
+ "binding-some": "project.members.ddl-current-some",
+ "binding-all": "project.members.ddl-current-all",
+ "binding-none": "project.members.ddl-current-none",
+};
+
+export function DDLWarningCallout(props: DDLWarningProps) {
+ const { t } = useTranslation();
+ const key = typeToKey[props.type];
+ const interpolated =
+ props.type === "issue"
+ ? t(key, { kind: props.kind, environments: props.environments.join(", ") })
+ : t(key, { kind: props.kind });
+ return <Alert variant="warning">{interpolated}</Alert>;
+}
+```
+
+Notes:
+- `binding-some` does **not** carry `environments` on its prop. The consumer (`MembersPage.tsx`) already has the env list in scope and renders env badges as a separate row next to the warning — keeping the prop union narrow prevents future implementers from accidentally interpolating env names into the warning string.
+- Discriminator is named `type` (not `variant`) to match the existing pattern in `frontend/src/react/hooks/usePagedData.tsx:36-45` and `frontend/src/react/components/sql-editor/useDropdown.ts`.
+- Bare `Alert` (no title/description) gives a single-line warning, matching the brainstorming mockups.
+
+- [ ] **Step 3.4: Run the tests and confirm they pass.**
+
+Run: `pnpm --dir frontend test -- src/react/components/role-grant/DDLWarningCallout.test.tsx`
+Expected: PASS — 6 cases.
+
+- [ ] **Step 3.5: Type-check.**
+
+Run: `pnpm --dir frontend type-check`
+Expected: type-check still passes (the shim from Task 1 keeps the tree green) — no new errors introduced by this component.
+
+- [ ] **Step 3.6: Commit.**
+
+```bash
+git add frontend/src/react/components/role-grant/
+git commit -m "feat(role-grant): add DDLWarningCallout shared component
+
+Single warning component used by admin grant drawer, developer request
+drawer, role-grant issue page, and member-list current-binding banner.
+Discriminated-union props prevent the env-list footgun.
+
+Refs: BYT-9390"
+```
+
+---
+
+## Chunk 2: Migrate drawer call sites
+
+### Task 4: Switch `RequestRoleSheet` to the new helper + add warning
+
+**Files:**
+- Modify: `frontend/src/react/pages/settings/RequestRoleSheet.tsx`
+- Modify: `frontend/src/react/pages/settings/RequestRoleSheet.test.tsx`
+
+- [ ] **Step 4.1: Update the test mock first (so the failing assertion is meaningful).**
+
+The existing mock at `RequestRoleSheet.test.tsx:157-162` is:
+
+```ts
+vi.mock("@/components/ProjectMember/utils", () => ({
+ // PROJECT_OWNER is not a SQL-permission role — these return false, so the
+ // database/environment scope sections stay hidden in the tests.
+ roleHasDatabaseLimitation: () => false,
+ roleHasEnvironmentLimitation: () => false,
+}));
+```
+
+Replace with:
+
+```ts
+vi.mock("@/components/ProjectMember/utils", () => ({
+ // Wrap in vi.fn() so per-test overrides (vi.mocked(x).mockReturnValue(...))
+ // work — plain arrow functions can't be re-mocked at runtime.
+ // Default behavior matches the existing test assumption: scope sections
+ // stay hidden because PROJECT_OWNER isn't a SQL-permission role.
+ roleHasDatabaseLimitation: vi.fn(() => false),
+ getRoleEnvironmentLimitationKind: vi.fn(() => undefined),
+}));
+```
+
+The new test cases in Step 4.2 override the mock per-test using `vi.mocked(...).mockReturnValue(...)`.
+
+- [ ] **Step 4.2: Add a failing assertion for the new warning.**
+
+The existing tests in this file build the sheet via direct `createRoot` + `act` (no `renderSheet` helper exported). Add the new cases at the end of the existing `describe` block, copying the closest existing test's setup verbatim and only adjusting the role + the assertion. Pattern:
+
+```ts
+it("renders DDL/DML warning under env multiselect for a sql-editor role", async () => {
+ // Override the default helper mock for this case so the env section appears.
+ const utilsMock = await import("@/components/ProjectMember/utils");
+ vi.mocked(utilsMock.getRoleEnvironmentLimitationKind).mockReturnValue(
+ "DDL/DML",
+ );
+
+ // ...same arrange/act as the nearest existing test, with role set to
+ // "roles/sqlEditorUser".
+
+ expect(
+ container.textContent,
+ ).toContain("project.members.ddl-warning");
+});
+
+it("does not render the warning for a non-DDL role", async () => {
+ // Default mock returns undefined for env kind — no override needed.
+ // ...same arrange/act with a SELECT-only role.
+
+ expect(
+ container.textContent,
+ ).not.toContain("project.members.ddl-warning");
+});
+```
+
+Use `container.textContent` rather than `screen.getByText` because the existing tests in this file mount with `createRoot` directly and do not register the RTL `screen` helper; copy the existing tests' pattern verbatim. If the existing tests do use `screen`, switch to `screen.queryByText`.
+
+- [ ] **Step 4.3: Run the test and confirm it fails.**
+
+Run: `pnpm --dir frontend test -- src/react/pages/settings/RequestRoleSheet.test.tsx`
+Expected: FAIL — warning not rendered.
+
+- [ ] **Step 4.4: Update `RequestRoleSheet.tsx`.**
+
+Existing import block at `RequestRoleSheet.tsx:6-9`:
+
+```ts
+import {
+ roleHasDatabaseLimitation,
+ roleHasEnvironmentLimitation,
+} from "@/components/ProjectMember/utils";
+```
+
+Replace with:
+
+```ts
+import {
+ getRoleEnvironmentLimitationKind,
+ roleHasDatabaseLimitation,
+} from "@/components/ProjectMember/utils";
+```
+
+Add a new import block (alphabetical placement among other `@/react/components/...` imports):
+
+```ts
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
+```
+
+Existing derivation at `RequestRoleSheet.tsx:251`:
+
+```ts
+const showEnvironments = !!role && roleHasEnvironmentLimitation(role);
+```
+
+Replace with (`envKind` is its own gate — no separate boolean):
+
+```ts
+const envKind = role ? getRoleEnvironmentLimitationKind(role) : undefined;
+```
+
+Existing JSX block at `RequestRoleSheet.tsx:536-546`:
+
+```tsx
+{showEnvironments && (
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm font-medium">
+ {t("common.environments")}
+ </label>
+ <EnvironmentMultiSelect
+ value={environments}
+ onChange={setEnvironments}
+ />
+ </div>
+)}
+```
+
+Replace with (note `gap-y-2` so the warning sits cleanly under the multiselect, and the new callout):
+
+```tsx
+{envKind && (
+ <div className="flex flex-col gap-y-2">
+ <label className="text-sm font-medium">
+ {t("common.environments")}
+ </label>
+ <EnvironmentMultiSelect
+ value={environments}
+ onChange={setEnvironments}
+ />
+ <DDLWarningCallout type="drawer" kind={envKind} />
+ </div>
+)}
+```
+
+Gating on `envKind` directly narrows it to `EnvLimitationKind` inside the branch — no separate boolean, no non-null assertion.
+
+- [ ] **Step 4.5: Run the test and confirm it passes.**
+
+Run: `pnpm --dir frontend test -- src/react/pages/settings/RequestRoleSheet.test.tsx`
+Expected: PASS — all existing + 2 new cases.
+
+- [ ] **Step 4.6: Commit.**
+
+```bash
+git add frontend/src/react/pages/settings/RequestRoleSheet.tsx \
+ frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
+git commit -m "feat(role-grant): warn on env selection in request drawer
+
+Developers requesting a role with bb.sql.ddl/bb.sql.dml now see a
+permission-aware warning under the environment multiselect explaining
+that selected envs allow direct DDL/DML execution in SQL Editor without
+approval.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 5: Switch `membersPageEnvironment` (and its test) to the new helper
+
+**Files:**
+- Modify: `frontend/src/react/pages/settings/membersPageEnvironment.ts`
+- Modify: `frontend/src/react/pages/settings/membersPageEnvironment.test.ts`
+
+- [ ] **Step 5.1: Update the test mock + add the new case (failing first).**
+
+In `membersPageEnvironment.test.ts`, replace the mock:
+
+```ts
+vi.mock("@/components/ProjectMember/utils", () => ({
+ roleHasEnvironmentLimitation: (role: string) =>
+ role === "roles/sqlEditorUser",
+}));
+```
+
+With:
+
+```ts
+vi.mock("@/components/ProjectMember/utils", () => ({
+ getRoleEnvironmentLimitationKind: (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
+}));
+```
+
+Add a new test case asserting `undefined` propagation:
+
+```ts
+test("returns undefined when getRoleEnvironmentLimitationKind returns undefined", () => {
+ expect(
+ getProjectRoleBindingEnvironmentLimitationState(binding("roles/queryOnly")),
+ ).toBeUndefined();
+});
+```
+
+(Verify whether an equivalent case already exists; if so just adjust the existing assertion's role name.)
+
+- [ ] **Step 5.2: Run the test and confirm it fails.**
+
+Run: `pnpm --dir frontend test -- src/react/pages/settings/membersPageEnvironment.test.ts`
+Expected: FAIL — production file still imports `roleHasEnvironmentLimitation`, mock won't match.
+
+- [ ] **Step 5.3: Update the production module.**
+
+In `membersPageEnvironment.ts`:
+
+```ts
+import { getRoleEnvironmentLimitationKind } from "@/components/ProjectMember/utils";
+// ...
+export const getProjectRoleBindingEnvironmentLimitationState = (
+ binding: Binding
+): ProjectRoleBindingEnvironmentLimitationState | undefined => {
+ if (getRoleEnvironmentLimitationKind(binding.role) === undefined) {
+ return undefined;
+ }
+ // ...rest unchanged
+};
+```
+
+**Semantic equivalence (load-bearing for Task 7).** The new gate `getRoleEnvironmentLimitationKind(role) === undefined` is bit-identical to the old gate `!roleHasEnvironmentLimitation(role)`: both reduce to "role lacks both `bb.sql.ddl` and `bb.sql.dml`." Verify by reading both helpers' definitions in `frontend/src/components/ProjectMember/utils.ts` — they call `checkRoleContainsAnyPermission(role, "bb.sql.ddl", "bb.sql.dml")` against the same permission pair. (Do NOT confuse with the sibling `roleHasDatabaseLimitation`, which checks 5 permissions including `bb.sql.select` — that helper is unchanged.) Therefore the visible-binding set produced by `getProjectRoleBindingEnvironmentLimitationState` does not change for any role. This invariant is what lets Task 7 use `bindingKind` non-null inside the `envLimitation && bindingKind` guard.
+
+The exported `ProjectRoleBindingEnvironmentLimitationState` shape stays the same — `MembersPage.tsx` still consumes it as `unrestricted` / `restricted`. Variant-to-state mapping happens at the rendering layer (Task 7).
+
+- [ ] **Step 5.4: Run the test and confirm it passes.**
+
+Run: `pnpm --dir frontend test -- src/react/pages/settings/membersPageEnvironment.test.ts`
+Expected: PASS.
+
+- [ ] **Step 5.5: Commit.**
+
+```bash
+git add frontend/src/react/pages/settings/membersPageEnvironment.ts \
+ frontend/src/react/pages/settings/membersPageEnvironment.test.ts
+git commit -m "refactor(role-grant): switch membersPageEnvironment to kind helper
+
+No behavior change — the tri-state (unrestricted / restricted with
+envs / undefined) is preserved. Just swaps the gating predicate.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 6: Switch `MembersPage` drawer to the new helper + warning
+
+**Files:**
+- Modify: `frontend/src/react/pages/settings/MembersPage.tsx` — three regions:
+ - **Imports** (top of file): swap the helper import.
+ - **Drawer form component** (~L800-940): swap the env-limitation derivation to `envKind`, replace the helper-text caption with `<DDLWarningCallout>`.
+ - **Drawer submit handler** (~L1162): swap the second helper call to use `envKind` for the env-scope filter.
+
+ All three regions live inside the drawer form's component file. Task 7 (member-list banner) edits a different region (~L1417-1455) of the same file but does not conflict with these regions. Do **not** change anything outside these line spans.
+
+- [ ] **Step 6.1: Update both `roleHasEnvironmentLimitation` call sites.**
+
+Find at ~L804:
+
+```ts
+() => form.role && roleHasEnvironmentLimitation(form.role),
+```
+
+Find at ~L1162:
+
+```ts
+const environments = roleHasEnvironmentLimitation(form.role)
+ ? form.environments
+ : undefined;
+```
+
+Replace both with calls that thread an `envKind` value through the form-section component. Concretely:
+
+In the form component's body, near the existing memos/derived values, derive once:
+
+```ts
+const envKind = form.role
+ ? getRoleEnvironmentLimitationKind(form.role)
+ : undefined;
+```
+
+Then:
+
+```ts
+const environments = envKind !== undefined ? form.environments : undefined;
+```
+
+Update the import line:
+
+```ts
+import {
+ getRoleEnvironmentLimitationKind,
+ roleHasDatabaseLimitation,
+} from "@/components/ProjectMember/utils";
+```
+
+(remove `roleHasEnvironmentLimitation` from the import).
+
+- [ ] **Step 6.2: Replace the helper-text caption with the warning component.**
+
+Verify there is exactly one occurrence of this JSX block in the file before editing (`grep -c "project.members.allow-ddl\"" frontend/src/react/pages/settings/MembersPage.tsx` should report 2 — one for the drawer caption and one for the member-list banner that Task 7 handles separately). If the count is higher, read the file and apply each replacement individually with enough surrounding context to disambiguate.
+
+Find the JSX block at ~L918–934:
+
+```tsx
+{showEnvironments && (
+ <div className="flex flex-col gap-y-2">
+ <div>
+ <label className="block text-sm font-medium text-control">
+ {t("common.environments")}
+ </label>
+ <span className="text-xs text-control-light">
+ {t("project.members.allow-ddl")}
+ </span>
+ </div>
+ <EnvironmentMultiSelect
+ value={form.environments}
+ onChange={(envs) => onChange({ ...form, environments: envs })}
+ />
+ </div>
+)}
+```
+
+Replace with:
+
+```tsx
+{envKind && (
+ <div className="flex flex-col gap-y-2">
+ <label className="block text-sm font-medium text-control">
+ {t("common.environments")}
+ </label>
+ <EnvironmentMultiSelect
+ value={form.environments}
+ onChange={(envs) => onChange({ ...form, environments: envs })}
+ />
+ <DDLWarningCallout type="drawer" kind={envKind} />
+ </div>
+)}
+```
+
+Gating on `envKind` directly narrows it to `EnvLimitationKind` inside the branch — no separate boolean, no non-null assertion.
+
+Add the import:
+
+```ts
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
+```
+
+The faint helper-text `<span>` is **deleted** (its key `project.members.allow-ddl` will be removed in Task 10).
+
+- [ ] **Step 6.3: Type-check the file.**
+
+Run: `pnpm --dir frontend type-check`
+Expected: type-check passes for `MembersPage.tsx` and all files migrated so far. Remaining errors (if any) only in the member-list banner (Task 7) and issue page (Task 8).
+
+- [ ] **Step 6.4: Commit.**
+
+```bash
+git add frontend/src/react/pages/settings/MembersPage.tsx
+git commit -m "feat(role-grant): warn on env selection in admin grant drawer
+
+Replaces the muted helper-text caption with a permission-aware yellow
+warning component under the env multiselect.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 7: Restyle `MembersPage` member-list current-binding banner
+
+**Files:**
+- Modify: `frontend/src/react/pages/settings/MembersPage.tsx` (banner block, ~L1417–1455)
+
+- [ ] **Step 7.1: Replace the inline blue info-banner JSX with the warning component.**
+
+Find the existing block at ~L1417–1455 (rendering `envLimitation` with three branches). The replacement maps the existing tri-state cleanly:
+
+| `envLimitation` | New variant |
+|---|---|
+| `{ type: "unrestricted" }` | `binding-all` |
+| `{ type: "restricted", environments: [...] }` (length > 0) | `binding-some` (env badges rendered separately) |
+| `{ type: "restricted", environments: [] }` | `binding-none` |
+
+Derive the kind once for the row:
+
+```ts
+const bindingKind = getRoleEnvironmentLimitationKind(binding.role);
+```
+
+(`bindingKind` is guaranteed defined here because `envLimitation` is truthy ⇔ kind is defined — the new `membersPageEnvironment` predicate already enforces this. Add a one-line comment if the assertion isn't obvious.)
+
+Replace the banner JSX:
+
+Single render switch — flat tri-state, no compound `&&` chains. Render `EnvironmentLabel` directly (no `Badge` wrapper — `EnvironmentLabel` is already a styled chip; the previous `Badge` wrap was a double-pill carried over from the old blue banner):
+
+```tsx
+{envLimitation && bindingKind && (
+ <div className="mx-4 mt-3">
+ {(() => {
+ 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>
+ );
+ })()}
+ </div>
+)}
+```
+
+Two design choices baked in:
+- The IIFE replaces three sequential compound-`&&` branches with one mutually-exclusive return chain. Reads as a flat tri-state at a glance.
+- `EnvironmentLabel` renders directly without `<Badge variant="secondary">`. The previous wrap was a double-pill (Badge styles + EnvironmentLabel's own colored chip). Task 8 already renders it this way — Task 7 now matches.
+
+Remove now-unused imports (`Info` icon, `Badge` if it's no longer used elsewhere in the file — `pnpm --dir frontend fix` will surface unused imports).
+
+- [ ] **Step 7.2: Add an automated test for the banner tri-state.**
+
+Pick the closest existing `MembersPage` test (or, if none exists, scaffold one in `frontend/src/react/pages/settings/MembersPage.test.tsx` using `IssueDetailRoleGrantDetails.test.tsx` as the harness reference). Add three cases that mount the member-list with one binding each and assert the rendered copy:
+
+```ts
+test("binding-all: renders DDL/DML in ALL environments warning, no env badges", () => {
+ // Mount with envLimitation = { type: "unrestricted" } and role = sql-editor.
+ // Assert: text "project.members.ddl-current-all" is present and the env-badge
+ // container is absent.
+});
+
+test("binding-some: renders 'in the listed environments' warning + EnvironmentLabel chips", () => {
+ // Mount with envLimitation = { type: "restricted", environments: ["environments/prod"] }.
+ // Assert: text "project.members.ddl-current-some" present; EnvironmentLabel
+ // chip for "environments/prod" rendered.
+});
+
+test("binding-none: renders 'not allowed in any environment' warning, no env badges", () => {
+ // Mount with envLimitation = { type: "restricted", environments: [] }.
+ // Assert: text "project.members.ddl-current-none" present.
+});
+```
+
+These lock the IIFE's three return branches against future regression. Match the mocking style established in `RequestRoleSheet.test.tsx`.
+
+- [ ] **Step 7.3: Type-check + lint.**
+
+Run: `pnpm --dir frontend fix && pnpm --dir frontend type-check`
+Expected: passes. The file no longer references `project.members.allow-ddl` / `*-all-environments` / `disallow-*` keys.
+
+- [ ] **Step 7.4: Commit.**
+
+```bash
+git add frontend/src/react/pages/settings/MembersPage.tsx \
+ frontend/src/react/pages/settings/MembersPage.test.tsx
+git commit -m "feat(role-grant): restyle member-list binding banner as warning
+
+Replaces the blue info banner with a permission-aware yellow warning.
+Same tri-state (all envs / specific envs / no envs); copy now centers
+on the risk: DDL/DML statements run directly in SQL Editor without
+approval.
+
+Refs: BYT-9390"
+```
+
+---
+
+## Chunk 3: Issue page + locale sweep + final verification
+
+### Task 8: Add Environments row + warning banner to `IssueDetailRoleGrantDetails`
+
+**Files:**
+- Modify: `frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx`
+- Create: `frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx`
+
+- [ ] **Step 8.1: Write the failing test.**
+
+```tsx
+// IssueDetailRoleGrantDetails.test.tsx
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { IssueDetailRoleGrantDetails } from "./IssueDetailRoleGrantDetails";
+
+vi.mock("react-i18next", () => ({
+ 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));
+ return s;
+ },
+ }),
+}));
+
+vi.mock("@/components/ProjectMember/utils", () => ({
+ getRoleEnvironmentLimitationKind: (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useEnvironmentList: () => [
+ { name: "environments/prod", title: "Prod" },
+ { name: "environments/test", title: "Test" },
+ ],
+}));
+
+// Stub EnvironmentLabel — the real component pulls in useEnvironment +
+// usePlanFeature + theme tokens we don't need to exercise here. Stub
+// with a span that surfaces the env name so the test can assert on it.
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: ({
+ environmentName,
+ className,
+ }: {
+ environmentName: string;
+ className?: string;
+ }) => (
+ <span data-testid="env-label" className={className}>
+ {environmentName}
+ </span>
+ ),
+}));
+
+// vi.mock factories are hoisted above imports — wrap the mutable test
+// context in vi.hoisted() so the closure reads from a binding that's
+// guaranteed initialized at hoist time. Pattern matches other tests in
+// this codebase that share state between vi.mock and per-case setup.
+const { mockContextRef } = vi.hoisted(() => ({
+ mockContextRef: { current: undefined as unknown },
+}));
+
+vi.mock("../context/IssueDetailContext", () => ({
+ useIssueDetailContext: () => mockContextRef.current,
+}));
+
+beforeEach(() => {
+ // Force every test to set its own context — catches cases where a test
+ // relies on a previous case's mock leaking through.
+ mockContextRef.current = undefined;
+});
+
+// stub other stores + utility deps with the minimum shape the component
+// needs (databaseStore.getDatabaseByName, roleStore.getRoleByName,
+// convertFromCELString, etc.) — copy the existing pattern from
+// IssueDetailDatabaseChangeView.test.tsx and trim to what the component uses.
+
+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"]',
+ },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ await screen.findByText(/issue.role-grant.ddl-warning/),
+ ).toBeInTheDocument();
+ // Mock returns translation keys verbatim — assert against the key,
+ // not the English string ("Environments").
+ expect(screen.getByText(/common.environments/)).toBeInTheDocument();
+ // Assert env interpolation flowed into the warning text. The mock t()
+ // appends a JSON-encoded vars suffix, so the warning's text content
+ // contains the env titles.
+ const warning = await screen.findByText(/issue.role-grant.ddl-warning/);
+ expect(warning.textContent).toContain("Prod");
+ expect(warning.textContent).toContain("Test");
+ });
+
+ test("hides warning + env row when role has DDL/DML but condition has no environments", async () => {
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/sqlEditorUser",
+ condition: { expression: "" },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ screen.queryByText(/issue.role-grant.ddl-warning/),
+ ).not.toBeInTheDocument();
+ });
+
+ 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"]',
+ },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ // Helper mock returns undefined for unknown roles — warning hidden,
+ // rest of the details card still renders.
+ expect(
+ screen.queryByText(/issue.role-grant.ddl-warning/),
+ ).not.toBeInTheDocument();
+ });
+
+ test("hides warning when role lacks DDL/DML perms", async () => {
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/queryOnly",
+ condition: {
+ expression: 'resource.environment_id in ["prod"]',
+ },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ screen.queryByText(/issue.role-grant.ddl-warning/),
+ ).not.toBeInTheDocument();
+ });
+});
+```
+
+The test stubs the role-store, env-store, and CEL-parsing helpers. Use the existing `IssueDetailDatabaseChangeView.test.tsx` as the harness reference for the stub shapes — copy the patterns rather than re-deriving them.
+
+- [ ] **Step 8.2: Run the test and confirm it fails.**
+
+Run: `pnpm --dir frontend test -- IssueDetailRoleGrantDetails.test.tsx`
+Expected: FAIL — warning + env row not rendered.
+
+- [ ] **Step 8.3: Update `IssueDetailRoleGrantDetails.tsx`.**
+
+Edits inside the component (between the existing role + permissions block and the existing database + expiration blocks):
+
+1. Add imports (and extend the existing `react` import to include `useMemo`):
+
+```ts
+// Extend the existing import — file currently imports useEffect, useState.
+import { useEffect, useMemo, useState } from "react";
+
+import { getRoleEnvironmentLimitationKind } from "@/components/ProjectMember/utils";
+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
+import { useEnvironmentList } from "@/react/hooks/useAppState";
+```
+
+2. After the existing `condition` `useEffect` block, derive:
+
+```ts
+const envKind = getRoleEnvironmentLimitationKind(requestRoleName);
+const envNames = condition?.environments ?? [];
+const envList = useEnvironmentList();
+const envTitles = useMemo(() => {
+ const names = condition?.environments ?? [];
+ const byName = new Map(envList.map((e) => [e.name, e.title]));
+ return names.map((n) => byName.get(n) ?? n);
+}, [condition?.environments, envList]);
+```
+
+`useEnvironmentList` is the React-native hook for the environment store (already used by `EnvironmentLabel.tsx`). The memo depends on the **stable upstream** `condition?.environments` (set by the async `useEffect` parsing the CEL string), not on the locally-derived `envNames` — `envNames = condition?.environments ?? []` produces a fresh `[]` on every render whenever `condition` is undefined, which would force the memo to re-run unconditionally. Falls back to the raw env resource name (e.g. `environments/prod-old`) if the env isn't in the store, which can happen if the env was renamed or deleted between request submission and approver review — preserves visibility instead of dropping the row silently.
+
+3. As the **first child** of the bordered details `<div>` (before the role row), insert:
+
+```tsx
+{envKind && envNames.length > 0 && (
+ <DDLWarningCallout
+ type="issue"
+ kind={envKind}
+ environments={envTitles}
+ />
+)}
+```
+
+The `envKind && envNames.length > 0` guard narrows `envKind` to `EnvLimitationKind` inside the branch — no non-null assertion needed.
+
+4. Add a new Environments row between Permissions and Database, rendered only when `envNames.length > 0`:
+
+```tsx
+{envNames.length > 0 && (
+ <div className="flex flex-col gap-y-2">
+ <span className="text-sm text-control-light">
+ {t("common.environments")}
+ </span>
+ <div className="flex flex-wrap gap-1">
+ {envNames.map((env) => (
+ <EnvironmentLabel
+ key={env}
+ environmentName={env}
+ className="text-xs"
+ />
+ ))}
+ </div>
+ </div>
+)}
+```
+
+- [ ] **Step 8.4: Run the test and confirm it passes.**
+
+Run: `pnpm --dir frontend test -- IssueDetailRoleGrantDetails.test.tsx`
+Expected: PASS — 3 cases.
+
+- [ ] **Step 8.5: Commit.**
+
+```bash
+git add frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx \
+ frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
+git commit -m "feat(role-grant): show env row + warning on approver issue page
+
+Approvers reviewing a role-grant request now see (a) the list of
+environments the request scopes to and (b) a yellow warning banner at
+the top of the details card naming the env titles and the affected
+statement kinds (DDL / DML / DDL/DML).
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 9: Translate the new keys into non-English React locales
+
+**Files:**
+- Modify: `frontend/src/react/locales/zh-CN.json`
+- Modify: `frontend/src/react/locales/ja-JP.json`
+- Modify: `frontend/src/react/locales/es-ES.json`
+- Modify: `frontend/src/react/locales/vi-VN.json`
+
+For each non-EN React locale, add all five new keys (4 under `project.members.*`, 1 under `issue.role-grant.*`) using the translations below. The `{{kind}}` and `{{environments}}` placeholders are spliced raw — do not localize the kind string (it's a product permission name).
+
+**zh-CN:**
+
+```json
+"project.members.ddl-warning": "在所选环境中,{{kind}} 语句可在 SQL 编辑器中直接执行,无需审批。",
+"project.members.ddl-current-all": "{{kind}} 语句可在 SQL 编辑器中针对所有(ALL)环境直接执行,无需审批。",
+"project.members.ddl-current-some": "{{kind}} 语句可在 SQL 编辑器中针对所列环境直接执行,无需审批。",
+"project.members.ddl-current-none": "{{kind}} 语句不允许在任何环境中通过 SQL 编辑器直接执行。",
+"issue.role-grant.ddl-warning": "若审批通过,在 {{environments}} 中,{{kind}} 语句可在 SQL 编辑器中直接执行,无需进一步审批。"
+```
+
+**ja-JP:**
+
+```json
+"project.members.ddl-warning": "選択した環境では、{{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
+"project.members.ddl-current-all": "すべての(ALL)環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
+"project.members.ddl-current-some": "リストされた環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
+"project.members.ddl-current-none": "{{kind}} ステートメントはどの環境でも SQL エディターで直接実行することは許可されていません。",
+"issue.role-grant.ddl-warning": "承認された場合、{{environments}} で {{kind}} ステートメントを SQL エディターで追加の承認なしに直接実行できます。"
+```
+
+**es-ES:**
+
+```json
+"project.members.ddl-warning": "En los entornos seleccionados, las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL sin aprobación.",
+"project.members.ddl-current-all": "Las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL en TODOS los entornos sin aprobación.",
+"project.members.ddl-current-some": "Las sentencias {{kind}} pueden ejecutarse directamente en el editor SQL en los entornos listados sin aprobación.",
+"project.members.ddl-current-none": "Las sentencias {{kind}} no se pueden ejecutar directamente en el editor SQL en ningún entorno.",
+"issue.role-grant.ddl-warning": "Si se aprueba, en {{environments}}, las sentencias {{kind}} podrán ejecutarse directamente en el editor SQL sin aprobación adicional."
+```
+
+**vi-VN:**
+
+```json
+"project.members.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.",
+"project.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.",
+"project.members.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.",
+"project.members.ddl-current-none": "Câu lệnh {{kind}} không được phép chạy trực tiếp trong SQL Editor ở bất kỳ môi trường nào.",
+"issue.role-grant.ddl-warning": "Nếu được phê duyệt, trong {{environments}}, 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 thêm."
+```
+
+If you are not a native reader of one of these languages, treat the strings above as drafts and flag them in the PR description for native review — do not silently rewrite them.
+
+- [ ] **Step 9.1: Add the five keys to each non-EN locale file.**
+
+Place keys alphabetically under `project.members.*` and `issue.role-grant.*` to match Biome's sort order.
+
+- [ ] **Step 9.2: Lint to confirm sort + JSON validity.**
+
+Run: `pnpm --dir frontend fix && pnpm --dir frontend check`
+Expected: passes; no schema/sort errors.
+
+- [ ] **Step 9.3: Commit.**
+
+```bash
+git add frontend/src/react/locales/{zh-CN,ja-JP,es-ES,vi-VN}.json
+git commit -m "i18n: translate ddl-warning + ddl-current-* into zh/ja/es/vi
+
+Translations for all five new keys across the four non-English React
+locales. Old keys are removed in the final cleanup commit.
+
+Refs: BYT-9390"
+```
+
+---
+
+### Task 10: Remove the old i18n keys + final verification sweep
+
+**Files:**
+- Modify: `frontend/src/react/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove `allow-ddl`, `allow-ddl-all-environments`, `disallow-ddl-all-environments`.
+- Modify: `frontend/src/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove `allow-ddl` only.
+
+- [ ] **Step 10.1: Confirm no source code still references the old keys or the transitional shim.**
+
+Run:
+
+```bash
+grep -rn "allow-ddl\|disallow-ddl-all-environments\|roleHasEnvironmentLimitation" \
+ frontend/src --include="*.ts" --include="*.tsx" --include="*.vue"
+```
+
+Expected: zero results outside locale files. If `roleHasEnvironmentLimitation` still appears, the migration left a caller behind — fix that caller (use `getRoleEnvironmentLimitationKind`) before continuing. If old i18n keys appear in source (not in locale JSON), fix the call site first.
+
+- [ ] **Step 10.2: Delete the keys from all 10 locale files.**
+
+React tree (5 files): remove `project.members.allow-ddl`, `project.members.allow-ddl-all-environments`, `project.members.disallow-ddl-all-environments`.
+
+Vue tree (5 files): remove `project.members.allow-ddl` only.
+
+Also remove the **transitional shim** `roleHasEnvironmentLimitation` from `frontend/src/components/ProjectMember/utils.ts` (added in Task 1 to keep the build green during migration). Step 10.1's grep confirmed no callers remain.
+
+- [ ] **Step 10.3: Lint + type-check + test sweep.**
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend check
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+```
+
+All four must pass cleanly.
+
+- [ ] **Step 10.4: Manually exercise each surface in the dev server.**
+
+Start the backend + dev server per the project's standard instructions (`pnpm --dir frontend dev` against a local Bytebase). Verify:
+
+1. **Admin grant drawer — DDL/DML role.** Project → Members → Grant Role for an `sqlEditorUser`-style role: yellow warning shows below the env multiselect with `DDL/DML statements`.
+2. **Admin grant drawer — DDL-only role.** Use a role that has only `bb.sql.ddl`: warning copy says `DDL statements`. Confirms `variantToKey` + interpolation routing.
+3. **Admin grant drawer — DML-only role.** Same with a `bb.sql.dml`-only role: copy says `DML statements`.
+4. **Admin grant drawer — non-DDL role.** Switch to a query-only role: env field and warning both disappear together (no stale state from prior selection).
+5. **Edit existing binding via the drawer.** Open the drawer in *edit* mode (not create) for an existing sql-editor binding: warning appears immediately on first render, not only after re-selecting the role.
+6. **Developer request drawer.** Run the same DDL/DML / DDL-only / non-DDL checks: warning shows / hides / changes label identically.
+7. **Approver issue page — happy path.** Submit a request-role issue with two envs selected. Open the resulting issue as an approver: yellow banner at the top of the role-grant details card lists both env titles + the correct kind label. Permissions row, new Environments row, Database row, Expired-at row all render correctly.
+8. **Approver issue page — non-DDL role.** Submit a query-only role-grant request: warning + Environments row both hidden; rest of card unchanged.
+9. **Approver issue page — expired binding.** View an expired role-grant issue: existing expiration UI still renders alongside the new warning; no visual collision.
+10. **Member-list banner — `restricted` (envs).** For an existing binding with a sql-editor role + 2 envs, banner is yellow, copy says `… can be directly run in SQL Editor in the listed environments without approval.`, env badges render under the warning.
+11. **Member-list banner — `unrestricted`.** For a binding with no env restriction: banner says `… in ALL environments without approval.` (uppercase ALL preserved), no env badges.
+12. **Member-list banner — `restricted` (no envs).** For a binding restricted to an empty env list: banner says `… are not allowed to be run directly in SQL Editor in any environment.`
+13. **Locale switch.** Switch UI language to each of zh-CN / ja-JP / es-ES / vi-VN: every warning above shows the translated copy with the correct `{{kind}}` and (where present) `{{environments}}` interpolation. Spot-check at least one of `restricted` and `unrestricted` per locale.
+
+- [ ] **Step 10.5: Commit.**
+
+```bash
+git add frontend/src/react/locales/*.json frontend/src/locales/*.json \
+ frontend/src/components/ProjectMember/utils.ts
+git commit -m "chore(role-grant): remove obsolete keys + transitional shim
+
+Removes the old allow-ddl* i18n keys (10 locale files) and deletes the
+roleHasEnvironmentLimitation transitional shim now that all call sites
+use getRoleEnvironmentLimitationKind.
+
+Refs: BYT-9390"
+```
+
+- [ ] **Step 10.6: Push branch and open PR.**
+
+Confirm with the user before pushing or running `gh pr create`. Per repo policy, never push or open a PR without explicit user approval.
+
+---
+
+## Done criteria
+
+- All four UI surfaces show the new permission-aware yellow warning with copy framed around environment selection.
+- Approver issue page shows env titles in both the dedicated row and the warning banner.
+- `roleHasEnvironmentLimitation` is fully removed from the codebase; `getRoleEnvironmentLimitationKind` has unit tests.
+- Old i18n keys (`allow-ddl`, `allow-ddl-all-environments`, `disallow-ddl-all-environments`) are gone from all 10 locale files; new keys are present in all 5 React locales with translations.
+- `pnpm --dir frontend check && pnpm --dir frontend type-check && pnpm --dir frontend test` all pass.
+- Manual smoke test of all five language × role combinations described in Step 10.4 passes.
diff --git a/docs/superpowers/specs/2026-05-07-byt-9390-ddl-dml-env-warning-design.md b/docs/superpowers/specs/2026-05-07-byt-9390-ddl-dml-env-warning-design.md
new file mode 100644
index 0000000000..83fcc2d5a5
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-07-byt-9390-ddl-dml-env-warning-design.md
@@ -0,0 +1,220 @@
+# BYT-9390 — DDL/DML environment-grant warnings
+
+**Status:** Approved (brainstorming)
+**Linear:** [BYT-9390](https://linear.app/bytebase/issue/byt-9390/missing-dmlddl-permission-prompts-in-sql-editor-self-service)
+**Author:** Peter Zhu
+**Date:** 2026-05-07
+
+## Problem
+
+When a Bytebase project role grants `bb.sql.ddl` and/or `bb.sql.dml` and the granter (or requester) selects environments for that role, the resulting binding lets the grantee run DDL/DML **directly in SQL Editor** in those environments **without going through the change-request approval flow**. Today this is severely under-communicated:
+
+1. **Admin grant drawer** (`MembersPage.tsx`) shows muted helper text: *"Allow running DDL/DML statements in the selected environments."* This phrasing is easily misread as "users can submit DDL/DML change requests for these environments" rather than "users bypass change-request approval entirely."
+2. **Developer request drawer** (`RequestRoleSheet.tsx`) shows **no copy at all** under the Environments field — the developer doesn't know they're requesting an approval-bypass scope.
+3. **Role-grant approval issue page** (`IssueDetailRoleGrantDetails.tsx`) does **not display environments at all** and shows no warning, so approvers cannot see (or be warned about) which environments a request will grant direct DDL/DML access in.
+4. **Member-list "current binding" info banner** (`MembersPage.tsx`) styles the same risk as a muted blue *info* banner, which contradicts the warning treatment we are introducing on the other surfaces.
+
+The root cause is that the wording frames the grant around *the role* ("this role allows DDL/DML") when the actual risk is *the environment selection* — selecting environment X turns it into a free-fire zone for that role, bypassing the change-request approval policy. The wording must center on the environment.
+
+## Design
+
+### 1. Risk-model framing
+
+The warning is structured around the same single sentence: in the chosen environment(s), DDL/DML can be run **directly in SQL Editor without approval**. The wording is **permission-aware**: which statement kinds the warning names depends on the perms the role actually has.
+
+| Role grants (env-scoped perms) | Statement-kind label |
+|---|---|
+| `bb.sql.ddl` + `bb.sql.dml` | `DDL/DML` |
+| only `bb.sql.ddl` | `DDL` |
+| only `bb.sql.dml` | `DML` |
+| neither | (no env field, no warning — existing behavior) |
+
+### 2. New helper: `getRoleEnvironmentLimitationKind`
+
+Replace `roleHasEnvironmentLimitation(role): boolean` (in `frontend/src/components/ProjectMember/utils.ts`) with:
+
+```ts
+export type EnvLimitationKind = "DDL" | "DML" | "DDL/DML";
+
+// Returns the human-readable statement-kind label for the role, or undefined
+// if the role has no environment-scoped DDL/DML permissions (i.e. no env
+// field is shown for this role).
+export function getRoleEnvironmentLimitationKind(
+ role: string
+): EnvLimitationKind | undefined;
+```
+
+**Read path.** Implementation is a non-hook utility (call sites include `membersPageEnvironment.ts`, which is not a React component). It reads the role from the Pinia store synchronously via `useRoleStore().getRoleByName(role)` and uses the existing `checkRoleContainsAnyPermission(role, "bb.sql.ddl")` / `("bb.sql.dml")` predicate to test each statement-kind permission separately, then composes the resulting label. This matches how the sibling helper `roleHasDatabaseLimitation` is written today, so the two stay structurally consistent.
+
+**Unknown role.** If the role is not yet loaded into the store (e.g. an issue page that races role-store hydration), `getRoleByName` returns `undefined` (per `frontend/src/store/modules/role.ts:23-25`, which is `roleList.value.find(...)`). The helper short-circuits and returns `undefined` — symmetric with today's `roleHasEnvironmentLimitation` returning `false` for an unknown role. Once the store hydrates, React re-renders and the helper returns the correct label. Document this in a docstring.
+
+**Call-site migration.** All current call sites switch to checking `getRoleEnvironmentLimitationKind(role) !== undefined`. The boolean wrapper is **deleted**. Verified call sites (`grep -rn "roleHasEnvironmentLimitation"` across `frontend/src/`):
+
+| File | Notes |
+|------|-------|
+| `frontend/src/components/ProjectMember/utils.ts` | Definition. Replace. |
+| `frontend/src/react/pages/settings/MembersPage.tsx` | 2 callers (drawer env-field gate, drawer submit-time env scoping). Switch both to the new helper. |
+| `frontend/src/react/pages/settings/RequestRoleSheet.tsx` | 1 caller (drawer env-field gate). Switch. |
+| `frontend/src/react/pages/settings/membersPageEnvironment.ts` | 1 caller in `getProjectRoleBindingEnvironmentLimitationState`. Switch. |
+| `frontend/src/react/pages/settings/RequestRoleSheet.test.tsx` | Mocks the helper. Update to mock `getRoleEnvironmentLimitationKind`. |
+| `frontend/src/react/pages/settings/membersPageEnvironment.test.ts` | Mocks the helper. Update mock. |
+
+(There is no production caller in `RoleGrantPanel.tsx` — earlier draft of this spec was wrong. The Vue tree's `frontend/src/components/RoleGrantPanel/` contains only `DatabaseResourceForm/` and `MaxRowCountSelect.vue`; neither references this helper.)
+
+### 3. i18n keys
+
+#### Drawer copy (admin grant + developer request — shared)
+
+```
+project.members.ddl-warning:
+ "In the selected environments, {{kind}} statements can be directly run in SQL Editor without approval."
+```
+
+`{{kind}}` is interpolated as `"DDL"`, `"DML"`, or `"DDL/DML"`. The literal `kind` strings are not translated — they're product permission names.
+
+#### Issue-page copy (approver — dedicated)
+
+```
+issue.role-grant.ddl-warning:
+ "If approved, in {{environments}}, {{kind}} statements can be directly run in SQL Editor without further approval."
+```
+
+`{{environments}}` is interpolated as a comma-joined list of env display titles (e.g. `Prod, Test`).
+
+#### Member-list current-binding banner (rewrites of three existing keys)
+
+```
+project.members.ddl-current-some:
+ "{{kind}} statements can be directly run in SQL Editor in the listed environments without approval."
+project.members.ddl-current-all:
+ "{{kind}} statements can be directly run in SQL Editor in ALL environments without approval."
+project.members.ddl-current-none:
+ "{{kind}} statements are not allowed to be run directly in SQL Editor in any environment."
+```
+
+`ALL` is intentionally uppercase in `ddl-current-all` to make the unrestricted scope visually obvious to admins scanning a list of bindings.
+
+#### Removed keys
+
+The old keys live in **10 locale files** across both the Vue and React i18n trees. Removal scope:
+
+- `frontend/src/react/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove all three keys: `allow-ddl`, `allow-ddl-all-environments`, `disallow-ddl-all-environments`. (React surfaces are the only runtime callers.)
+- `frontend/src/locales/{en-US,zh-CN,ja-JP,es-ES,vi-VN}.json` — remove the single key `allow-ddl` only. (The Vue locale tree contains only `allow-ddl` for these surfaces; the other two keys never existed there. Confirmed by direct inspection of all five files.)
+
+Verified via grep that no `.vue`/`.ts`/`.tsx` source under `frontend/src/` outside of locale files references any of the three old keys other than `MembersPage.tsx` (the surface we're rewriting).
+
+Non-English React locales (`zh-CN.json`, `ja-JP.json`, `es-ES.json`, `vi-VN.json`) get the **new keys** added with translations produced **during implementation in the same PR**. Translation is part of the implementation plan, not deferred — the existing `allow-ddl` is fully translated in all four non-EN locales today, and we should not regress that. The implementation plan will list each (locale, key) pair as an explicit task so translators / the implementer can sweep them together.
+
+### 4. UI treatment per surface
+
+#### 4.1 Admin grant drawer (`MembersPage.tsx`, env section)
+
+- Remove the muted helper-text caption under the Environments label.
+- Render `<DDLWarningCallout kind={kind} type="drawer" />` **immediately under the env multi-select**, only when `getRoleEnvironmentLimitationKind(role)` returns a kind.
+- Visual: yellow background (`bg-warning-bg`) / yellow border, ⚠ icon, copy from `project.members.ddl-warning`.
+
+#### 4.2 Developer request drawer (`RequestRoleSheet.tsx`, env section)
+
+- Net-add: render the same `<DDLWarningCallout>` under the env multi-select, gated identically.
+
+Both drawers reuse one shared component so styling stays in lockstep.
+
+#### 4.3 Issue page (`IssueDetailRoleGrantDetails.tsx`)
+
+Two changes inside the existing bordered details card:
+
+- **New Environments row**, between Permissions and Database, rendered only when `condition?.environments?.length > 0`. Renders env chips/badges using the same `EnvironmentLabel` component already in use elsewhere.
+- **Top warning Alert** (Option A from brainstorming mockups), the first child inside the bordered card. Yellow Alert with ⚠ icon, copy from `issue.role-grant.ddl-warning`.
+ Renders only when **both**:
+ - `getRoleEnvironmentLimitationKind(issue.roleGrant.role)` returns a kind, **and**
+ - `condition?.environments?.length > 0`
+
+**Edge cases (explicit):**
+
+| Situation | Behavior | Rationale |
+|---|---|---|
+| Role has DDL/DML perms, `condition.environments` is `undefined` | Warning hidden; Environments row hidden. | Today's request flow always emits an `environments` clause when `getRoleEnvironmentLimitationKind(role) !== undefined`, so undefined is only seen for legacy / hand-edited bindings. Approver still sees role title + permissions. |
+| Role has DDL/DML perms, `condition.environments` is `[]` (explicit empty) | Warning hidden; Environments row hidden. | Reachable: the request flow emits `environments: []` when the developer requests a DDL/DML role but selects zero environments. Backend semantics: `resource.environment_id in []` is false everywhere, so the binding grants **no** DDL/DML access — there is no risk to convey, hence no warning. The Environments row is also suppressed because rendering "Environments: (none)" alongside a request that had a DDL/DML-shaped role would invite the misread "this role grants DDL/DML somewhere"; rather than disambiguate via a fourth UI state we let the role's permission list speak for itself. If user research later flags this as confusing, surfacing an explicit "no environments selected" indicator is a follow-up spec. |
+| Role-grant issue references a role that has been **deleted** by the time an approver opens the page | `useRoleStore().getRoleByName` returns `undefined` → helper returns `undefined` → warning hides. | Symmetric with today's silent-hide for unknown roles. Approver still sees the existing role-name and database details; they can revoke/decline as usual. |
+| Role store hasn't hydrated yet | Helper returns `undefined` on first render, warning hidden; React re-renders once the store loads and warning appears. | Matches today's gating behavior; no flash-of-warning on subsequent loads because the store is cached after first hydration. |
+| `kind` would be the empty string | Cannot occur — the warning component is only mounted when `getRoleEnvironmentLimitationKind` returns one of three explicit string literals. **Implementers must NOT add a defensive `kind ?? "DDL/DML"` fallback** — that would mask a logic bug elsewhere. |
+
+Placement is **Option A only** for this plan. Option B (contextual callout under the Environments row) was discussed during brainstorming as a fallback but is intentionally **not** included as a mid-implementation pivot — if review pushes back on Option A, we treat that as a separate spec amendment rather than letting the plan absorb both.
+
+#### 4.4 Member-list current-binding banner (`MembersPage.tsx`)
+
+- Restyle from blue info → yellow warning (`Alert variant="warning"`).
+- Use the same `<DDLWarningCallout>` component with one of three variants so the string switch happens in one place.
+- Gating unchanged: only renders when `getRoleEnvironmentLimitationKind(binding.role) !== undefined` (this is the same set of roles that previously triggered `envLimitation`, so visible bindings don't change).
+
+**Variant ↔ existing limitation-state mapping.** `getProjectRoleBindingEnvironmentLimitationState` (in `membersPageEnvironment.ts`) already returns the three states we need:
+
+| Existing limitation state | New `<DDLWarningCallout>` variant | Visual rendering |
+|---|---|---|
+| `{ type: "unrestricted" }` | `binding-all` | Warning Alert, copy from `ddl-current-all`. **No** env badges. |
+| `{ type: "restricted", environments: [...] }` (length > 0) | `binding-some` | Warning Alert, copy from `ddl-current-some`, **plus** env badges rendered next to or under the copy (mirrors the existing layout). |
+| `{ type: "restricted", environments: [] }` | `binding-none` | Warning Alert, copy from `ddl-current-none`. No env badges. |
+| `undefined` | (don't render) | (banner hidden — no DDL/DML scope on this role.) |
+
+The component receives the limitation state directly (or the variant + optional env list) — implementer's call. The mapping table above is the source of truth.
+
+### 5. New shared component: `DDLWarningCallout`
+
+```tsx
+// frontend/src/react/components/role-grant/DDLWarningCallout.tsx
+
+type DDLWarningProps =
+ | { type: "drawer"; kind: EnvLimitationKind }
+ | { type: "issue"; kind: EnvLimitationKind; environments: string[] }
+ | { type: "binding-some"; kind: EnvLimitationKind }
+ | { type: "binding-all"; kind: EnvLimitationKind }
+ | { type: "binding-none"; kind: EnvLimitationKind };
+```
+
+The discriminated union enforces at compile time that callers provide `environments` exactly when the variant needs them — no `environments?` footgun where a caller forgets to pass them and silently renders an empty list.
+
+Internally:
+- Picks the right i18n key per variant.
+- Interpolates `kind` always; interpolates `environments` (comma-joined display titles) only for `issue`.
+- Renders an `Alert` with `variant="warning"` chrome (yellow background, ⚠ icon).
+
+The component does **not** render env badges itself. Consumers that need badges (issue page's Environments row, member-list `binding-some` banner) render them outside the callout because each surface arranges them differently relative to surrounding rows. Centralizing badge layout in the component would couple it to one surface's layout decisions; the centralized thing here is **copy + i18n key routing**.
+
+### 6. Tests
+
+- **Unit test** for `getRoleEnvironmentLimitationKind`: covers `bb.sql.ddl` only, `bb.sql.dml` only, both, neither, a built-in role that mixes env-scoped with non-env-scoped perms, and the **unknown-role** case (returns `undefined` to lock the symmetry-with-old-`false` behavior).
+- **`MembersPage` test**: switching the selected role updates the kind label in the warning callout (`DDL`, `DML`, `DDL/DML`); for a non-DDL role the env field and warning are both hidden. Member-list banner renders the correct variant for each of `unrestricted` / `restricted` (non-empty) / `restricted` (empty).
+- **`RequestRoleSheet.test.tsx`**: existing mock of `roleHasEnvironmentLimitation` switches to mocking `getRoleEnvironmentLimitationKind`. Add assertions: the warning copy renders for a DDL/DML role and is absent for a SELECT-only role.
+- **`membersPageEnvironment.test.ts`**: existing mock switches to `getRoleEnvironmentLimitationKind`. Existing tri-state assertions stay green; add a case for the new mock returning `undefined` (still produces `undefined` from `getProjectRoleBindingEnvironmentLimitationState`).
+- **`IssueDetailRoleGrantDetails` test (new)**:
+ - Warning + Environments row render for a role-grant issue with `bb.sql.ddl` + `bb.sql.dml` and two envs.
+ - Warning hidden when role lacks DDL/DML perms (e.g. SELECT-only role).
+ - Environments row hidden when `condition.environments` is empty/undefined.
+ - Env-name interpolation: warning text contains the env display titles, not env resource names.
+ - Role-deleted case: helper returns `undefined`, warning is hidden, rest of details still render.
+- **`DDLWarningCallout` snapshot/RTL test**: each variant × representative `kind` renders the expected i18n string. Type-level test (compile-only) confirms the discriminated union rejects passing `environments` to `binding-all` and rejects omitting `environments` from `issue`.
+
+### 7. Out of scope
+
+- No backend changes. CEL expression generation, `RoleGrant` proto, and the approval runner are untouched.
+- The drawer label *Environments* itself is unchanged.
+- No change to which roles support env scoping; we only change how the existing scoping is *communicated*.
+- Surfacing a warning when a role has DDL/DML perms but `condition.environments` is empty/undefined (today this combination is unreachable from the request flow — see §4.3 edge cases).
+
+## Known limitations (accepted)
+
+- **`binding-all` copy ("ALL environments") describes env scope only.** A binding can be `unrestricted` on environments while still being database-scoped (DDL/DML allowed in selected databases × all environments). The warning conveys the env axis only — not the database axis. This is consistent with the warning being attached to environment selection. If user research later flags this as misleading, surfacing the database scope alongside is a follow-up spec; the current scope is intentionally narrow.
+
+- **Async layout shift on the issue page.** `condition.environments` is parsed inside an awaited `convertFromCELString` call in `IssueDetailRoleGrantDetails.tsx`. The Environments row + warning banner therefore appear after first paint, causing a small layout shift at the top of the details card. This already happens today for the database row; the new rows continue the existing pattern. If this becomes noticeable in user research, a skeleton placeholder can land in a follow-up.
+
+- **No equivalent surface in the SQL Editor self-service flow.** Verified via grep: `frontend/src/react/components/sql-editor/RoleGrantPanel.tsx` does not use `EnvironmentMultiSelect` — it grants per-database, not per-environment. The warning is irrelevant there. The Linear ticket title's "SQL Editor self-service" refers to the developer request flow (`RequestRoleSheet`), which is covered.
+
+## Open questions
+
+None. All ambiguity resolved during brainstorming.
+
+## Rollout / risk
+
+- Pure frontend wording + styling change. No data migration, no breaking-change review needed.
+- The shared `DDLWarningCallout` component centralizes copy so future audits or A/B tweaks change one file.
+- A small risk of broken tests in the existing `MembersPage` and `RequestRoleSheet` suites because the rendered copy changes — they will be updated as part of the same PR.
diff --git a/frontend/package.json b/frontend/package.json
index 96f50eb678..7425fda81d 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -112,6 +112,8 @@
"@tailwindcss/forms": "0.5.11",
"@tailwindcss/typography": "0.5.19",
"@tailwindcss/vite": "^4.1.17",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
"@tsconfig/node24": "24.0.4",
"@types/crypto-js": "^4.2.2",
"@types/d3-shape": "^3.1.7",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 1236654800..af7f45d433 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -274,6 +274,12 @@ importers:
'@tailwindcss/vite':
specifier: ^4.1.17
+ '@testing-library/jest-dom':
+ specifier: ^6.9.1
+ version: 6.9.1
+ '@testing-library/react':
+ specifier: ^16.3.2
'@tsconfig/node24':
specifier: 24.0.4
version: 24.0.4
@@ -445,6 +451,9 @@ packages:
'@acemir/[email protected]':
resolution: {integrity: sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==}
+ '@adobe/[email protected]':
+ resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
+
'@asamuzakjp/[email protected]':
resolution: {integrity: sha512-B0Hv6G3gWGMn0xKJ0txEi/jM5iFpT3MfDxmhZFb4W047GvytCf1DHQ1D69W3zHI4yWe2aTZAA0JnbMZ7Xc8DuQ==}
@@ -2158,6 +2167,29 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-JLANqGy/D6k4Ujmh8Tr25lGimuOXNiaVyXaCAZS0W+1390sADdGnyUdSWNIfd49gebtIxGMij4IktRVzrdr12Q==}
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
+ engines: {node: '>=18'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}
+ engines: {node: '>=14', npm: '>=6', yarn: '>=1'}
+
+ '@testing-library/[email protected]':
+ resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@testing-library/dom': ^10.0.0
+ '@types/react': ^18.0.0 || ^19.0.0
+ '@types/react-dom': ^18.0.0 || ^19.0.0
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@tsconfig/[email protected]':
resolution: {integrity: sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==}
@@ -2173,6 +2205,9 @@ packages:
'@tsconfig/[email protected]':
resolution: {integrity: sha512-2A933l5P5oCbv6qSxHs7ckKwobs8BDAe9SJ/Xr2Hy+nDlwmLE1GhFh/g/vXGRZWgxBg9nX/5piDtHR9Dkw/XuA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
+
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -2401,7 +2436,6 @@ packages:
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
- deprecated: Potential CWE-502 - Update to 1.3.1 or higher
'@vitejs/[email protected]':
resolution: {integrity: sha512-CaXb/y0mlfu7jQRELEJJc2/5w2bX2m1JraARgFnvSB2yfvnCNJVWWlqAo6WjnKoepOwKx8gs0ugJThPLKCOXIg==}
@@ -2618,6 +2652,10 @@ packages:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
@@ -2628,6 +2666,13 @@ packages:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
+ resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
+
+ resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
@@ -2866,6 +2911,9 @@ packages:
resolution: {integrity: sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==}
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
+ resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
+
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -3083,6 +3131,12 @@ packages:
resolution: {integrity: sha512-+PVS2VPTgKFPYWo3vAFEA8WPbTf7/xo43TifH9G8S1KqnrQu0o77A3unrF5yOugy4mIz7K5wAVFHUcha7wsz6A==}
+ resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
+
+ resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+
resolution: {integrity: sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==}
@@ -3224,6 +3278,10 @@ packages:
'@typescript-eslint/parser':
optional: true
+ resolution: {integrity: sha512-GaUN0sWim5qc8KVErfPBWmc31LEsOkrUJbvJZV+xuL3u2phMUK4HIvXlWAakfC8W4nzlK+chPEAkYOYb5ZScIw==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}
+
resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
@@ -3254,6 +3312,10 @@ packages:
resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ resolution: {integrity: sha512-AVHPqQoZYc+RUM4/3Ly5udlZY/U4LS8pIG05jEjWM2lQMU/oaZ7qshzAl2YP1tfNmXfftH3ohurfwNAug+MnsQ==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}
+
resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
@@ -3542,6 +3604,10 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
+ resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -3895,6 +3961,10 @@ packages:
peerDependencies:
vue: '>=3.0.1'
+ resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
+ hasBin: true
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -4067,6 +4137,10 @@ packages:
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
engines: {node: '>=8.6'}
+ resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==}
hasBin: true
@@ -4346,6 +4420,10 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
+ engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
+
resolution: {integrity: sha512-/uSMbG4866Bniq893+qMKNArlaq5qWjH74+yRptgTe/F118OXZAgJ6tvSRA0fVn92wWFhRWvYWc75iSGPXLPbQ==}
@@ -4445,6 +4523,9 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
+
resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
peerDependencies:
@@ -4485,6 +4566,10 @@ packages:
resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}
engines: {node: '>= 20.19.0'}
+ resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==}
@@ -4734,6 +4819,10 @@ packages:
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
@@ -4981,7 +5070,6 @@ packages:
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
- deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true
@@ -5313,6 +5401,8 @@ snapshots:
'@acemir/[email protected]': {}
+ '@adobe/[email protected]': {}
+
'@asamuzakjp/[email protected]':
dependencies:
'@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
@@ -7054,6 +7144,36 @@ snapshots:
'@tanstack/[email protected]': {}
+ '@testing-library/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.0
+ '@babel/runtime': 7.29.2
+ '@types/aria-query': 5.0.4
+ aria-query: 5.3.0
+ dom-accessibility-api: 0.5.16
+ lz-string: 1.5.0
+ picocolors: 1.1.1
+ pretty-format: 27.5.1
+
+ '@testing-library/[email protected]':
+ dependencies:
+ '@adobe/css-tools': 4.4.4
+ aria-query: 5.3.2
+ css.escape: 1.5.1
+ dom-accessibility-api: 0.6.3
+ picocolors: 1.1.1
+ redent: 3.0.0
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@testing-library/dom': 10.4.1
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ '@types/react-dom': 19.2.3(@types/[email protected])
+
'@tsconfig/[email protected]': {}
'@tsconfig/[email protected]': {}
@@ -7064,6 +7184,8 @@ snapshots:
'@tsconfig/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/deep-eql': 4.0.2
@@ -7657,12 +7779,20 @@ snapshots:
dependencies:
color-convert: 2.0.1
+
+ dependencies:
+ dequal: 2.0.3
+
+
@@ -7901,6 +8031,8 @@ snapshots:
mdn-data: 2.12.2
source-map-js: 1.2.1
+
@@ -8128,6 +8260,10 @@ snapshots:
'@react-dnd/invariant': 2.0.0
redux: 4.2.1
+
+
optionalDependencies:
'@types/trusted-types': 2.0.7
@@ -8299,6 +8435,13 @@ snapshots:
optionalDependencies:
'@typescript-eslint/parser': 8.57.2([email protected]([email protected]))([email protected])
+ dependencies:
+ '@types/esrecurse': 4.3.1
+ '@types/estree': 1.0.8
+ esrecurse: 4.3.0
+ estraverse: 5.3.0
+
dependencies:
'@types/esrecurse': 4.3.1
@@ -8355,6 +8498,12 @@ snapshots:
acorn-jsx: 5.3.2([email protected])
eslint-visitor-keys: 4.2.1
+ dependencies:
+ acorn: 8.16.0
+ acorn-jsx: 5.3.2([email protected])
+ eslint-visitor-keys: 5.0.1
+
dependencies:
acorn: 8.16.0
@@ -8633,6 +8782,8 @@ snapshots:
+
@@ -8951,6 +9102,8 @@ snapshots:
dependencies:
vue: 3.5.29([email protected])
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -9331,6 +9484,8 @@ snapshots:
braces: 3.0.3
picomatch: 2.3.1
+
@@ -9706,6 +9861,12 @@ snapshots:
+ dependencies:
+ ansi-regex: 5.0.1
+ ansi-styles: 5.2.0
+ react-is: 17.0.2
+
@@ -9793,6 +9954,8 @@ snapshots:
+
dependencies:
'@types/hast': 3.0.4
@@ -9852,6 +10015,11 @@ snapshots:
+ dependencies:
+ indent-string: 4.0.0
+ strip-indent: 3.0.0
+
dependencies:
'@babel/runtime': 7.29.2
@@ -10124,6 +10292,10 @@ snapshots:
dependencies:
ansi-regex: 6.2.2
+ dependencies:
+ min-indent: 1.0.1
+
@@ -10501,9 +10673,9 @@ snapshots:
dependencies:
debug: 4.4.3
eslint: 10.3.0([email protected])
- eslint-scope: 9.1.2
+ eslint-scope: 9.1.1
eslint-visitor-keys: 5.0.1
- espree: 11.2.0
+ espree: 11.1.1
esquery: 1.7.0
semver: 7.7.4
transitivePeerDependencies:
diff --git a/frontend/src/components/ProjectMember/utils.test.ts b/frontend/src/components/ProjectMember/utils.test.ts
new file mode 100644
index 0000000000..9774046a5d
--- /dev/null
+++ b/frontend/src/components/ProjectMember/utils.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test, vi } from "vitest";
+import { getRoleEnvironmentLimitationKind } from "./utils";
+
+const fixtures: Record<string, string[]> = {
+ "roles/sqlEditorUser": ["bb.sql.ddl", "bb.sql.dml"],
+ "roles/sqlEditorDDLOnly": ["bb.sql.ddl"],
+ "roles/sqlEditorDMLOnly": ["bb.sql.dml"],
+ "roles/queryOnly": ["bb.sql.select"],
+ "roles/projectViewer": [],
+};
+vi.mock("@/store", () => ({
+ useRoleStore: () => ({
+ getRoleByName: (role: string) =>
+ fixtures[role] === undefined
+ ? undefined
+ : { name: role, permissions: fixtures[role] },
+ }),
+}));
+vi.mock("@/utils", () => ({
+ displayRoleTitle: (r: string) => r,
+ checkRoleContainsAnyPermission: () => false,
+}));
+
+describe("getRoleEnvironmentLimitationKind", () => {
+ test("returns 'DDL/DML' when role has both ddl and dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorUser")).toBe(
+ "DDL/DML"
+ );
+ });
+
+ test("returns 'DDL' when role has only ddl", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorDDLOnly")).toBe(
+ "DDL"
+ );
+ });
+
+ test("returns 'DML' when role has only dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/sqlEditorDMLOnly")).toBe(
+ "DML"
+ );
+ });
+
+ test("returns undefined when role has neither ddl nor dml", () => {
+ expect(getRoleEnvironmentLimitationKind("roles/queryOnly")).toBeUndefined();
+ });
+
+ test("returns undefined for an unknown role", () => {
+ expect(
+ getRoleEnvironmentLimitationKind("roles/doesNotExist")
+ ).toBeUndefined();
+ });
+});
diff --git a/frontend/src/components/ProjectMember/utils.ts b/frontend/src/components/ProjectMember/utils.ts
index adca087277..c7d4f4c745 100644
--- a/frontend/src/components/ProjectMember/utils.ts
+++ b/frontend/src/components/ProjectMember/utils.ts
@@ -1,3 +1,4 @@
+import { useRoleStore } from "@/store";
import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import { checkRoleContainsAnyPermission, displayRoleTitle } from "@/utils";
@@ -20,6 +21,22 @@ export const roleHasDatabaseLimitation = (role: string) => {
);
};
-export const roleHasEnvironmentLimitation = (role: string) => {
- return checkRoleContainsAnyPermission(role, "bb.sql.ddl", "bb.sql.dml");
+// {{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.
+export const getRoleEnvironmentLimitationKind = (
+ role: string
+): EnvLimitationKind | undefined => {
+ const r = useRoleStore().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");
+ if (hasDDL && hasDML) return "DDL/DML";
+ if (hasDDL) return "DDL";
+ if (hasDML) return "DML";
+ return undefined;
};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 2c692e9063..46a5978c78 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1456,7 +1456,6 @@
"self": "Masking Exemptions"
},
"members": {
- "allow-ddl": "Allow running DDL/DML statements in the selected environments.",
"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.",
"never-expires": "Never",
"workspace-level-roles": "Workspace level roles"
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 910065d37c..56e951c08c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1456,7 +1456,6 @@
"self": "Exenciones de Enmascaramiento"
},
"members": {
- "allow-ddl": "Permitir ejecutar sentencias DDL/DML en los entornos seleccionados.",
"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.",
"never-expires": "Nunca caduca",
"workspace-level-roles": "Roles a nivel de espacio de trabajo"
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 496a76826a..55405bd870 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1456,7 +1456,6 @@
"self": "マスキング免除"
},
"members": {
- "allow-ddl": "選択した環境で DDL/DML ステートメントの実行を許可する。",
"description": "プロジェクトメンバーのロールにより、プロジェクト内のデータベースとイシューを操作するための権限が決まります。プロジェクト所有者、ワークスペース管理者、および DBA はすべて、プロジェクトに対する完全な権限を持っています。",
"never-expires": "有効期限が切れることはありません",
"workspace-level-roles": "ワークスペースレベルのロール"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 5e9a326499..f0c9a3274c 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1456,7 +1456,6 @@
"self": "Miễn trừ Che giấu"
},
"members": {
- "allow-ddl": "Cho phép chạy câu lệnh DDL/DML trong các môi trường đã chọn.",
"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.",
"never-expires": "Không bao giờ",
"workspace-level-roles": "Vai trò cấp độ không gian làm việc"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 3815295ffa..1670a5a517 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1456,7 +1456,6 @@
"self": "脱敏豁免"
},
"members": {
- "allow-ddl": "允许在所选环境中执行 DDL/DML 语句。",
"description": "项目成员角色决定了操作项目中的数据库和工单的权限。项目的所有者,工作空间管理员和 DBA 都具有项目所有的权限。",
"never-expires": "永不过期",
"workspace-level-roles": "工作空间级别角色"
diff --git a/frontend/src/react/components/role-grant/DDLWarningCallout.locale.test.ts b/frontend/src/react/components/role-grant/DDLWarningCallout.locale.test.ts
new file mode 100644
index 0000000000..335aa5f5f0
--- /dev/null
+++ b/frontend/src/react/components/role-grant/DDLWarningCallout.locale.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, test } from "vitest";
+import enReact from "@/react/locales/en-US.json";
+import esReact from "@/react/locales/es-ES.json";
+import jaReact from "@/react/locales/ja-JP.json";
+import viReact from "@/react/locales/vi-VN.json";
+import zhReact from "@/react/locales/zh-CN.json";
+
+// Locale-format guard for the new role-grant warning strings. Component
+// tests use a mock t() that doesn't see the real locale strings, so a typo
+// like "kind" instead of "{{kind}}" — or a translator dropping a placeholder
+// in a non-EN locale — would slip through. This test loads every React
+// locale and asserts placeholder presence directly. Cross-locale key parity
+// is enforced separately by frontend/scripts/check-react-i18n.mjs, but key
+// parity ≠ placeholder parity.
+
+const locales = {
+ "en-US": enReact,
+ "zh-CN": zhReact,
+ "ja-JP": jaReact,
+ "es-ES": esReact,
+ "vi-VN": viReact,
+};
+
+const projectMembersKindKeys = [
+ "ddl-warning",
+ "ddl-current-all",
+ "ddl-current-some",
+ "ddl-current-none",
+] as const;
+
+describe("DDLWarningCallout locale strings", () => {
+ for (const [locale, data] of Object.entries(locales)) {
+ describe(locale, () => {
+ test.each(
+ projectMembersKindKeys
+ )("project.members.%s contains {{kind}} placeholder", (key) => {
+ const value = (
+ data.project.members as unknown as Record<string, string>
+ )[key];
+ expect(value).toBeDefined();
+ expect(value).toContain("{{kind}}");
+ });
+ });
+ }
+});
diff --git a/frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx b/frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx
new file mode 100644
index 0000000000..1202fd4b1b
--- /dev/null
+++ b/frontend/src/react/components/role-grant/DDLWarningCallout.test.tsx
@@ -0,0 +1,60 @@
+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/react/components/role-grant/DDLWarningCallout.tsx b/frontend/src/react/components/role-grant/DDLWarningCallout.tsx
new file mode 100644
index 0000000000..4427edda3a
--- /dev/null
+++ b/frontend/src/react/components/role-grant/DDLWarningCallout.tsx
@@ -0,0 +1,41 @@
+import { useTranslation } from "react-i18next";
+import type { EnvLimitationKind } from "@/components/ProjectMember/utils";
+import { Alert } from "@/react/components/ui/alert";
+
+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/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 1301610cd7..deb8129902 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -1710,10 +1710,11 @@
"self": "Masking Exemptions"
},
"members": {
- "allow-ddl": "Allow running DDL/DML statements in the selected environments.",
- "allow-ddl-all-environments": "No environment restrictions. Allow running DDL/DML statements in all environments.",
+ "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.",
- "disallow-ddl-all-environments": "Disallow running DDL/DML statements for all environments.",
"edit-member": "Edit member - {{member}}",
"never-expires": "Never",
"request-role": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 6ffaad3fa0..ae5865cdf0 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -1702,10 +1702,11 @@
"self": "Exenciones de Enmascaramiento"
},
"members": {
- "allow-ddl": "Permitir ejecutar sentencias DDL/DML en los entornos seleccionados.",
- "allow-ddl-all-environments": "Sin restricciones de entorno. Permitir ejecutar sentencias DDL/DML en todos los entornos.",
+ "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.",
- "disallow-ddl-all-environments": "No permitir ejecutar sentencias DDL/DML en ningún entorno.",
"edit-member": "Editar miembro - {{member}}",
"never-expires": "Never",
"request-role": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index c48df54e30..03f8997233 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -1702,10 +1702,11 @@
"self": "マスキング免除"
},
"members": {
- "allow-ddl": "選択した環境で DDL/DML ステートメントの実行を許可する。",
- "allow-ddl-all-environments": "環境制限はありません。すべての環境で DDL/DML ステートメントの実行を許可する。",
+ "ddl-current-all": "すべての(ALL)環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
+ "ddl-current-none": "{{kind}} ステートメントを SQL エディターで実行するには承認が必要です。",
+ "ddl-current-some": "リストされた環境で {{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
+ "ddl-warning": "選択した環境では、{{kind}} ステートメントを SQL エディターで承認なしに直接実行できます。",
"description": "プロジェクトメンバーのロールにより、プロジェクト内のデータベースとイシューを操作するための権限が決まります。プロジェクト所有者、ワークスペース管理者、および DBA はすべて、プロジェクトに対する完全な権限を持っています。",
- "disallow-ddl-all-environments": "すべての環境で DDL/DML ステートメントの実行を禁止する。",
"edit-member": "メンバー編集 - {{member}}",
"never-expires": "Never",
"request-role": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index abac5978a8..76c087e6f4 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -1702,10 +1702,11 @@
"self": "Miễn trừ Che giấu"
},
"members": {
- "allow-ddl": "Cho phép chạy câu lệnh DDL/DML trong các môi trường đã chọn.",
- "allow-ddl-all-environments": "Không có giới hạn môi trường. Cho phép chạy câu lệnh DDL/DML trong tất cả môi trường.",
+ "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.",
- "disallow-ddl-all-environments": "Không cho phép chạy câu lệnh DDL/DML cho tất cả các môi trường.",
"edit-member": "Chỉnh sửa thành viên - {{member}}",
"never-expires": "Never",
"request-role": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index da67664304..71faf3f21d 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -1702,10 +1702,11 @@
"self": "脱敏豁免"
},
"members": {
- "allow-ddl": "允许在所选环境中执行 DDL/DML 语句。",
- "allow-ddl-all-environments": "无环境限制。允许在所有环境中执行 DDL/DML 语句。",
+ "ddl-current-all": "{{kind}} 语句可在 SQL 编辑器中针对所有(ALL)环境直接执行,无需审批。",
+ "ddl-current-none": "{{kind}} 语句在 SQL 编辑器中运行前需要审批。",
+ "ddl-current-some": "{{kind}} 语句可在 SQL 编辑器中针对所列环境直接执行,无需审批。",
+ "ddl-warning": "在所选环境中,{{kind}} 语句可在 SQL 编辑器中直接执行,无需审批。",
"description": "项目成员角色决定了操作项目中的数据库和工单的权限。项目的所有者,工作空间管理员和 DBA 都具有项目所有的权限。",
- "disallow-ddl-all-environments": "禁止在所有环境中执行 DDL/DML 语句。",
"edit-member": "编辑成员 - {{member}}",
"never-expires": "Never",
"request-role": {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
new file mode 100644
index 0000000000..a1df1246b1
--- /dev/null
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
@@ -0,0 +1,260 @@
+import { render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { IssueDetailRoleGrantDetails } from "./IssueDetailRoleGrantDetails";
+
+// vi.mock factories are hoisted above imports — wrap mutable test state in
+// vi.hoisted so the closure reads from a binding that's initialized at hoist time.
+const { mockContextRef } = vi.hoisted(() => ({
+ mockContextRef: { current: undefined as unknown },
+}));
+
+vi.mock("react-i18next", () => ({
+ 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("@/components/ProjectMember/utils", () => ({
+ getRoleEnvironmentLimitationKind: (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useEnvironmentList: () => [
+ { name: "environments/prod", title: "Prod" },
+ { name: "environments/test", title: "Test" },
+ ],
+}));
+
+// Stub EnvironmentLabel — the real component pulls in Pinia stores + theme tokens.
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: ({
+ environmentName,
+ className,
+ }: {
+ environmentName: string;
+ className?: string;
+ }) => (
+ <span data-testid="env-label" className={className}>
+ {environmentName}
+ </span>
+ ),
+}));
+
+// Stub other modules the component pulls in.
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: <T,>(getter: () => T) => getter(),
+}));
+
+vi.mock("@/store", () => ({
+ useDatabaseV1Store: () => ({
+ batchGetOrFetchDatabases: vi.fn(),
+ getDatabaseByName: () => ({
+ effectiveEnvironment: "",
+ instanceResource: undefined,
+ }),
+ }),
+ useEnvironmentV1Store: () => ({
+ getEnvironmentByName: () => ({ title: "" }),
+ }),
+ useInstanceV1Store: () => ({ getInstanceByName: () => ({ title: "" }) }),
+ useRoleStore: () => ({
+ getRoleByName: (role: string) =>
+ role === "roles/sqlEditorUser"
+ ? { name: role, permissions: ["bb.sql.ddl", "bb.sql.dml"] }
+ : role === "roles/queryOnly"
+ ? { name: role, permissions: ["bb.sql.select"] }
+ : undefined,
+ }),
+}));
+
+vi.mock("@/utils", () => ({
+ displayRoleTitle: (r: string) => r,
+}));
+
+vi.mock("@/utils/issue/cel", () => ({
+ convertFromCELString: async (expr: string) => {
+ // Mini parser just for tests: only recognizes "environment_id in [...]".
+ const m = expr.match(/environment_id in \[([^\]]*)\]/);
+ if (!m) return { environments: undefined };
+ const ids = m[1]
+ .split(",")
+ .map((s) => s.trim().replace(/^"|"$/g, ""))
+ .filter(Boolean);
+ return { environments: ids.map((id) => `environments/${id}`) };
+ },
+}));
+
+vi.mock("@/utils/v1/database", () => ({
+ extractDatabaseResourceName: () => ({ databaseName: "", instanceName: "" }),
+}));
+
+vi.mock("../context/IssueDetailContext", () => ({
+ useIssueDetailContext: () => mockContextRef.current,
+}));
+
+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"]',
+ },
+ },
+ },
+ };
+ 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();
+ });
+
+ 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")',
+ },
+ },
+ },
+ };
+ 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();
+ });
+
+ test("renders binding-all warning when expression is empty entirely", async () => {
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/sqlEditorUser",
+ condition: { expression: "" },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ await screen.findByText(/project.members.ddl-current-all/)
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/common.environments/)).not.toBeInTheDocument();
+ });
+
+ 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 []" },
+ },
+ },
+ };
+ 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();
+ 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();
+ });
+
+ 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"]' },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ screen.queryByText(/project.members.ddl-current-some/)
+ ).not.toBeInTheDocument();
+ });
+
+ test("hides warning when role lacks DDL/DML perms", async () => {
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/queryOnly",
+ condition: { expression: 'resource.environment_id in ["prod"]' },
+ },
+ },
+ };
+ render(<IssueDetailRoleGrantDetails />);
+ expect(
+ screen.queryByText(/project.members.ddl-current-some/)
+ ).not.toBeInTheDocument();
+ });
+
+ test("clears stale environments when the issue prop changes", async () => {
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/sqlEditorUser",
+ condition: { expression: 'resource.environment_id in ["prod"]' },
+ },
+ },
+ };
+ const { rerender } = render(<IssueDetailRoleGrantDetails />);
+ expect(await screen.findByText("Prod")).toBeInTheDocument();
+
+ mockContextRef.current = {
+ issue: {
+ roleGrant: {
+ role: "roles/sqlEditorUser",
+ condition: { 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();
+ });
+});
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
index 5f090b63b3..4c0692a420 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
@@ -1,6 +1,8 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
+import { getRoleEnvironmentLimitationKind } from "@/components/ProjectMember/utils";
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
import {
Table,
TableBody,
@@ -9,6 +11,7 @@ import {
TableHeader,
TableRow,
} from "@/react/components/ui/table";
+import { useEnvironmentList } from "@/react/hooks/useAppState";
import { useVueState } from "@/react/hooks/useVueState";
import {
useDatabaseV1Store,
@@ -38,28 +41,22 @@ export function IssueDetailRoleGrantDetails() {
const [condition, setCondition] = useState<ConditionExpression | undefined>();
useEffect(() => {
- let canceled = false;
+ // Clear synchronously so a prop change doesn't briefly show the
+ // previous issue's environments while the new CEL expression parses.
+ setCondition(undefined);
- const run = async () => {
- const expression = issue?.roleGrant?.condition?.expression ?? "";
- if (!expression) {
- setCondition(undefined);
- return;
- }
+ const expression = issue?.roleGrant?.condition?.expression ?? "";
+ if (!expression) return;
+
+ let canceled = false;
+ void (async () => {
try {
const parsed = await convertFromCELString(expression);
- if (!canceled) {
- setCondition(parsed);
- }
+ if (!canceled) setCondition(parsed);
} catch (error) {
console.error("Failed to parse CEL expression:", error);
- if (!canceled) {
- setCondition(undefined);
- }
}
- };
-
- void run();
+ })();
return () => {
canceled = true;
};
@@ -74,6 +71,26 @@ export function IssueDetailRoleGrantDetails() {
}
}, [condition?.databaseResources, databaseStore]);
+ 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 ?? "";
+ const isParsing = expression !== "" && condition === undefined;
+ const envScope = computeEnvScope(envKind, isParsing, condition?.environments);
+
return (
<div className="flex flex-col gap-y-4">
<h3 className="text-base font-medium">{t("issue.role-grant.details")}</h3>
@@ -101,6 +118,25 @@ export function IssueDetailRoleGrantDetails() {
</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">
+ <span className="text-sm text-control-light">
+ {t("common.environments")}
+ </span>
+ <DDLWarningCallout type="binding-some" kind={envKind} />
+ <div className="text-base">{envTitles.join(", ")}</div>
+ </div>
+ )}
+
{condition?.databaseResources && (
<div className="flex flex-col gap-y-2">
<span className="text-sm text-control-light">
@@ -108,7 +144,9 @@ export function IssueDetailRoleGrantDetails() {
</span>
<div>
{condition.databaseResources.length === 0 ? (
- <span>{t("issue.role-grant.all-databases")}</span>
+ <span className="text-base">
+ {t("issue.role-grant.all-databases")}
+ </span>
) : (
<IssueDetailDatabaseResourceTable
databaseResourceList={condition.databaseResources}
@@ -200,6 +238,17 @@ 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/react/pages/settings/MemberBindingEnvironmentBanner.test.tsx b/frontend/src/react/pages/settings/MemberBindingEnvironmentBanner.test.tsx
new file mode 100644
index 0000000000..3dd8b68f94
--- /dev/null
+++ b/frontend/src/react/pages/settings/MemberBindingEnvironmentBanner.test.tsx
@@ -0,0 +1,74 @@
+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("@/react/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/react/pages/settings/MemberBindingEnvironmentBanner.tsx b/frontend/src/react/pages/settings/MemberBindingEnvironmentBanner.tsx
new file mode 100644
index 0000000000..338dee5e5e
--- /dev/null
+++ b/frontend/src/react/pages/settings/MemberBindingEnvironmentBanner.tsx
@@ -0,0 +1,33 @@
+import type { EnvLimitationKind } from "@/components/ProjectMember/utils";
+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
+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/react/pages/settings/MembersPage.tsx b/frontend/src/react/pages/settings/MembersPage.tsx
index 4d100de2e6..3c030f392d 100644
--- a/frontend/src/react/pages/settings/MembersPage.tsx
+++ b/frontend/src/react/pages/settings/MembersPage.tsx
@@ -3,7 +3,6 @@ import {
Building2,
ChevronDown,
ChevronRight,
- Info,
Pencil,
Plus,
ShieldUser,
@@ -23,17 +22,17 @@ import { groupProjectRoleBindings } from "@/components/Member/projectRoleBinding
import type { MemberBinding } from "@/components/Member/types";
import { getMemberBindings } from "@/components/Member/utils";
import {
+ getRoleEnvironmentLimitationKind,
roleHasDatabaseLimitation,
- roleHasEnvironmentLimitation,
} from "@/components/ProjectMember/utils";
import { AccountMultiSelect } from "@/react/components/AccountMultiSelect";
import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/react/components/DatabaseResourceSelector";
-import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { EnvironmentMultiSelect } from "@/react/components/EnvironmentMultiSelect";
import { FeatureBadge } from "@/react/components/FeatureBadge";
import { LearnMoreLink } from "@/react/components/LearnMoreLink";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { RoleSelect } from "@/react/components/RoleSelect";
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
import { UserAvatar } from "@/react/components/UserAvatar";
import { Alert } from "@/react/components/ui/alert";
import { Badge } from "@/react/components/ui/badge";
@@ -103,6 +102,7 @@ import {
convertFromExpr,
stringifyConditionExpression,
} from "@/utils/issue/cel";
+import { MemberBindingEnvironmentBanner } from "./MemberBindingEnvironmentBanner";
import { getSetIamPolicyPermissionGuardConfig } from "./membersPageActions";
import { getProjectRoleBindingEnvironmentLimitationState } from "./membersPageEnvironment";
import { RequestRoleSheet } from "./RequestRoleSheet";
@@ -796,8 +796,8 @@ function ProjectRoleBindingForm({
() => form.role && roleHasDatabaseLimitation(form.role),
[form.role]
);
- const showEnvironments = useMemo(
- () => form.role && roleHasEnvironmentLimitation(form.role),
+ const envKind = useMemo(
+ () => (form.role ? getRoleEnvironmentLimitationKind(form.role) : undefined),
[form.role]
);
@@ -912,16 +912,12 @@ function ProjectRoleBindingForm({
)}
{/* Environments (conditional on role) */}
- {showEnvironments && (
+ {envKind && (
<div className="flex flex-col gap-y-2">
- <div>
- <label className="block text-sm font-medium text-control">
- {t("common.environments")}
- </label>
- <span className="text-xs text-control-light">
- {t("project.members.allow-ddl")}
- </span>
- </div>
+ <label className="block text-sm font-medium text-control">
+ {t("common.environments")}
+ </label>
+ <DDLWarningCallout type="drawer" kind={envKind} />
<EnvironmentMultiSelect
value={form.environments}
onChange={(envs) => onChange({ ...form, environments: envs })}
@@ -1155,9 +1151,11 @@ function EditMemberRoleDrawer({
form.databaseResources.length > 0
? form.databaseResources
: undefined;
- const environments = roleHasEnvironmentLimitation(form.role)
- ? form.environments
- : undefined;
+ const environments =
+ form.role &&
+ getRoleEnvironmentLimitationKind(form.role) !== undefined
+ ? form.environments
+ : undefined;
const hasCondition =
form.expirationTimestampInMS !== undefined ||
form.reason !== "" ||
@@ -1363,6 +1361,9 @@ function EditMemberRoleDrawer({
const rows = getSingleBindingRows(binding);
const envLimitation =
getProjectRoleBindingEnvironmentLimitationState(binding);
+ const bindingKind = getRoleEnvironmentLimitationKind(
+ binding.role
+ );
const isExpired = isBindingPolicyExpired(binding);
return (
<div
@@ -1411,42 +1412,12 @@ function EditMemberRoleDrawer({
</div>
{/* Environment info banner */}
- {envLimitation && (
- <div className="mx-4 mt-3 flex items-start gap-x-2 rounded-sm bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-700">
- <Info className="h-4 w-4 shrink-0 mt-0.5" />
- <div>
- {envLimitation.type === "unrestricted" ? (
- <span>
- {t(
- "project.members.allow-ddl-all-environments"
- )}
- </span>
- ) : envLimitation.environments.length > 0 ? (
- <>
- <span>{t("project.members.allow-ddl")}</span>
- <div className="flex flex-wrap gap-1 mt-1">
- {envLimitation.environments.map((env) => (
- <Badge
- key={env}
- variant="secondary"
- className="text-xs"
- >
- <EnvironmentLabel
- environmentName={env}
- className="text-xs"
- />
- </Badge>
- ))}
- </div>
- </>
- ) : (
- <span>
- {t(
- "project.members.disallow-ddl-all-environments"
- )}
- </span>
- )}
- </div>
+ {envLimitation && bindingKind && (
+ <div className="mx-4 mt-3">
+ <MemberBindingEnvironmentBanner
+ envLimitation={envLimitation}
+ bindingKind={bindingKind}
+ />
</div>
)}
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
index a2c2f33f6c..ec6b5a684e 100644
--- a/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
@@ -158,10 +158,12 @@ vi.mock("@/router/dashboard/projectV1", () => ({
}));
vi.mock("@/components/ProjectMember/utils", () => ({
- // PROJECT_OWNER is not a SQL-permission role — these return false, so the
- // database/environment scope sections stay hidden in the tests.
- roleHasDatabaseLimitation: () => false,
- roleHasEnvironmentLimitation: () => false,
+ // Wrap in vi.fn() so per-test overrides (vi.mocked(x).mockReturnValue(...))
+ // work — plain arrow functions can't be re-mocked at runtime.
+ // Default: PROJECT_OWNER is not a SQL-permission role — both return
+ // false / undefined, so the scope sections stay hidden by default.
+ roleHasDatabaseLimitation: vi.fn(() => false),
+ getRoleEnvironmentLimitationKind: vi.fn(() => undefined),
}));
vi.mock("@/plugins/cel", () => ({
@@ -324,8 +326,13 @@ async function typeReason(text: string): Promise<void> {
}
// Stub window.open — production handler opens the created issue in a new tab.
-beforeEach(() => {
+beforeEach(async () => {
vi.spyOn(window, "open").mockImplementation(() => null);
+ // Reset env-kind mock between tests so per-test overrides don't leak.
+ const utilsMock = await import("@/components/ProjectMember/utils");
+ vi.mocked(utilsMock.getRoleEnvironmentLimitationKind).mockReturnValue(
+ undefined
+ );
});
describe("RequestRoleSheet — enforceIssueTitle (BYT-9310)", () => {
@@ -401,4 +408,28 @@ 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("@/components/ProjectMember/utils");
+ vi.mocked(utilsMock.getRoleEnvironmentLimitationKind).mockImplementation(
+ () => "DDL/DML"
+ );
+
+ await renderSheet(false);
+ await selectRole("roles/sqlEditorUser");
+ await flush();
+
+ expect(container.textContent).toContain("project.members.ddl-warning");
+ });
+
+ 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();
+
+ expect(container.textContent).not.toContain("project.members.ddl-warning");
+ });
});
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
index c67d0b43af..21406196de 100644
--- a/frontend/src/react/pages/settings/RequestRoleSheet.tsx
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
@@ -4,8 +4,8 @@ import dayjs from "dayjs";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
+ getRoleEnvironmentLimitationKind,
roleHasDatabaseLimitation,
- roleHasEnvironmentLimitation,
} from "@/components/ProjectMember/utils";
import { issueServiceClientConnect } from "@/connect";
import type { ConditionGroupExpr, Factor, Operator } from "@/plugins/cel";
@@ -21,6 +21,7 @@ import type { OptionConfig } from "@/react/components/ExprEditor";
import { ExprEditor } from "@/react/components/ExprEditor";
import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";
import { RoleSelect } from "@/react/components/RoleSelect";
+import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
@@ -244,7 +245,7 @@ function RequestRoleForm({
// scope). Submitting without one produces a project-wide binding which is
// broader than the user typically intends.
const showDatabases = !!role && roleHasDatabaseLimitation(role);
- const showEnvironments = !!role && roleHasEnvironmentLimitation(role);
+ const envKind = role ? getRoleEnvironmentLimitationKind(role) : undefined;
const databaseScopeComplete =
!showDatabases ||
@@ -287,7 +288,9 @@ function RequestRoleForm({
databaseResources.length > 0
? databaseResources
: undefined;
- const scopedEnvironments = showEnvironments ? environments : undefined;
+ // EnvLimitationKind union has no falsy members, so the truthy check
+ // is equivalent to !== undefined.
+ const scopedEnvironments = envKind ? environments : undefined;
// The backend uses two fields on the RoleGrant message:
// 1. `condition.expression` — CEL evaluated by
@@ -528,11 +531,12 @@ function RequestRoleForm({
)}
</div>
)}
- {showEnvironments && (
- <div className="flex flex-col gap-y-1">
+ {envKind && (
+ <div className="flex flex-col gap-y-2">
<label className="text-sm font-medium">
{t("common.environments")}
</label>
+ <DDLWarningCallout type="drawer" kind={envKind} />
<EnvironmentMultiSelect
value={environments}
onChange={setEnvironments}
diff --git a/frontend/src/react/pages/settings/membersPageEnvironment.test.ts b/frontend/src/react/pages/settings/membersPageEnvironment.test.ts
index 6a9effc0a6..d77fc4b766 100644
--- a/frontend/src/react/pages/settings/membersPageEnvironment.test.ts
+++ b/frontend/src/react/pages/settings/membersPageEnvironment.test.ts
@@ -3,8 +3,8 @@ import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import { getProjectRoleBindingEnvironmentLimitationState } from "./membersPageEnvironment";
vi.mock("@/components/ProjectMember/utils", () => ({
- roleHasEnvironmentLimitation: (role: string) =>
- role === "roles/sqlEditorUser",
+ getRoleEnvironmentLimitationKind: (role: string) =>
+ role === "roles/sqlEditorUser" ? "DDL/DML" : undefined,
}));
vi.mock("@/utils/issue/cel", () => ({
diff --git a/frontend/src/react/pages/settings/membersPageEnvironment.ts b/frontend/src/react/pages/settings/membersPageEnvironment.ts
index 7e1e4858d2..42944baa06 100644
--- a/frontend/src/react/pages/settings/membersPageEnvironment.ts
+++ b/frontend/src/react/pages/settings/membersPageEnvironment.ts
@@ -1,4 +1,4 @@
-import { roleHasEnvironmentLimitation } from "@/components/ProjectMember/utils";
+import { getRoleEnvironmentLimitationKind } from "@/components/ProjectMember/utils";
import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import { convertFromExpr } from "@/utils/issue/cel";
@@ -14,7 +14,7 @@ export type ProjectRoleBindingEnvironmentLimitationState =
export const getProjectRoleBindingEnvironmentLimitationState = (
binding: Binding
): ProjectRoleBindingEnvironmentLimitationState | undefined => {
- if (!roleHasEnvironmentLimitation(binding.role)) {
+ if (getRoleEnvironmentLimitationKind(binding.role) === undefined) {
return undefined;
}
diff --git a/frontend/tsconfig.react.json b/frontend/tsconfig.react.json
index 5f20762146..9c32d2851b 100644
--- a/frontend/tsconfig.react.json
+++ b/frontend/tsconfig.react.json
@@ -8,7 +8,7 @@
"lib": ["ES2025", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"jsxImportSource": "react",
- "types": ["react", "react-dom", "vite/client"],
+ "types": ["react", "react-dom", "vite/client", "@testing-library/jest-dom/vitest"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
diff --git a/frontend/vitest.setup.ts b/frontend/vitest.setup.ts
index f4f37f543c..5ab40aa8b6 100644
--- a/frontend/vitest.setup.ts
+++ b/frontend/vitest.setup.ts
@@ -1,3 +1,4 @@
+import "@testing-library/jest-dom/vitest";
import { vi } from "vitest";
vi.mock("pouchdb", () => {