Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test: lock masking exemption CEL precedence (BYT-9788) + e2e composite coverage (#20711)
zchpeterb5ce78702ac8
diff --git a/frontend/src/react/lib/sensitive-data/exemptionDataUtils.test.ts b/frontend/src/react/lib/sensitive-data/exemptionDataUtils.test.tsindex 2b37d9fa00..219bec746f 100644--- a/frontend/src/react/lib/sensitive-data/exemptionDataUtils.test.ts+++ b/frontend/src/react/lib/sensitive-data/exemptionDataUtils.test.ts@@ -1017,3 +1017,84 @@ describe("rewriteResourceDatabase", () => {expect(rewriteResourceDatabase("")).toBe("");});});++// ============================================================+// BYT-9788 — composite (OR) exemption precedence & read-path round-trip+//+// `&&` binds tighter than `||` in CEL, and the backend evaluates with stock+// cel-go (backend/api/v1/masking_evaluator.go), so a masking exemption that ORs+// several resources and ANDs a request.time bound must wrap the OR-group —+// request.time < T && ((c1) || (c2))+// otherwise the expiry binds only to the last branch. PR #20683 (create page)+// and #20687 (GrantAccessDialog) make the builders satisfy that invariant.+//+// The read-path helpers below (parseExpirationTimestamp / getConditionExpression)+// assume the expiration is a top-level `&&` term; these round-trip the wrapped+// output to prove the writer and reader agree.+// ============================================================++describe("composite exemption precedence (BYT-9788)", () => {+ // One resource's clause = instance && database (&& table), the exact shape+ // getExpressionsForDatabaseResource produces, AND-joined.+ const clause = (instance: string, database: string, table?: string): string =>+ [+ `resource.instance_id == "${instance}"`,+ `resource.database_name == "${database}"`,+ table ? `resource.table_name == "${table}"` : "",+ ]+ .filter((e) => e)+ .join(" && ");++ const TIME = "2026-06-02T10:00:00.000Z";+ const timeClause = `request.time < timestamp("${TIME}")`;+ const timeMs = new Date(TIME).getTime();++ const c1 = clause("inst", "db", "SPCP_CP_ENTITY_AUTHORISATION");+ const c2 = clause("inst", "db", "SPCP_CP_AUTH_ACCESS");++ describe("fixed format (what PR #20683 now writes)", () => {+ // request.time < T && ((c1) || (c2))+ const fixedMulti = `${timeClause} && ((${c1}) || (${c2}))`;++ test("expiration applies to the whole OR-group (timestamp extracted)", () => {+ expect(parseExpirationTimestamp(fixedMulti)).toBe(timeMs);+ });++ test("getConditionExpression strips time and keeps the OR-group intact", () => {+ // Both resources survive, OR operator preserved, internal && preserved.+ expect(getConditionExpression(fixedMulti)).toBe(`((${c1}) || (${c2}))`);+ });++ test("round-trip: time + condition reconstruct the original expression", () => {+ const condition = getConditionExpression(fixedMulti);+ const ts = parseExpirationTimestamp(fixedMulti);+ const rebuilt = [+ `request.time < timestamp("${new Date(ts!).toISOString()}")`,+ condition,+ ].join(" && ");+ expect(rebuilt).toBe(fixedMulti);+ });++ test("single resource is wrapped but parses identically", () => {+ const fixedSingle = `${timeClause} && (${c1})`;+ expect(parseExpirationTimestamp(fixedSingle)).toBe(timeMs);+ expect(getConditionExpression(fixedSingle)).toBe(`(${c1})`);+ });++ test("classification level inside an OR branch is still parsed", () => {+ const withLevel = `${timeClause} && ((${c1} && resource.classification_level <= 3) || (${c2} && resource.classification_level <= 3))`;+ expect(+ parseClassificationLevel(getConditionExpression(withLevel))+ ).toEqual({ operator: "<=", value: 3 });+ });++ test("EXPRESSION mode: a top-level || in custom CEL is wrapped and bounded", () => {+ // The create page wraps the user's celString: request.time < T && (a || b)+ const expr = `${timeClause} && (resource.database_name == "a" || resource.database_name == "b")`;+ expect(parseExpirationTimestamp(expr)).toBe(timeMs);+ expect(getConditionExpression(expr)).toBe(+ '(resource.database_name == "a" || resource.database_name == "b")'+ );+ });+ });+});diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.test.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.test.tsxnew file mode 100644index 0000000000..7d434c31d1--- /dev/null+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.test.tsx@@ -0,0 +1,393 @@+import type {+ ButtonHTMLAttributes,+ InputHTMLAttributes,+ ReactNode,+} from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++// ============================================================+// BYT-9788 — REGRESSION test for PR #20683.+//+// Drives the REAL create-page builder (onSubmit) and asserts that the generated+// masking-exemption CEL wraps the whole resource OR-group BEFORE the expiration+// is AND-joined, so `request.time` binds to every resource:+// request.time < timestamp("…") && ((c1) || (c2))+//+// The pre-fix builder produced `(c1) || (c2) && request.time < …`, which cel-go+// reads as `(c1) || ((c2) && time)` — the first resource never expired.+// (#20687 later shared this builder with GrantAccessDialog, fixing BYT-9791.)+// ============================================================++const mocks = vi.hoisted(() => ({+ upsertPolicy: vi.fn(),+ getOrFetchPolicyByParentAndType: vi.fn(),+ getOrFetchSettingByName: vi.fn(),+ classification: vi.fn(() => []),+ buildCELExpr: vi.fn(),+ batchConvertParsedExprToCELString: vi.fn(),+ getExpressionsForDatabaseResource: vi.fn(+ (_resource: { table?: string }): string[] => []+ ),+ routerBack: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/plugins/cel", () => ({+ buildCELExpr: mocks.buildCELExpr,+ emptySimpleExpr: vi.fn(() => ({ type: "ConditionGroup", args: [] })),+ validateSimpleExpr: vi.fn(() => true),+ wrapAsGroup: vi.fn((expr) => expr),+}));++vi.mock("@/react/components/AccountMultiSelect", () => ({+ AccountMultiSelect: ({+ value,+ onChange,+ }: {+ value: string[];+ onChange: (value: string[]) => void;+ }) => (+ <button+ data-testid="account-multi-select"+ onClick={() => onChange([...value, "users/alice"])}+ type="button"+ />+ ),+}));++vi.mock("@/react/components/DatabaseResourceSelector", () => ({+ DatabaseResourceSelector: ({+ onChange,+ }: {+ onChange?: (resources: unknown[]) => void;+ }) => (+ <button+ data-testid="set-two-resources"+ type="button"+ onClick={() =>+ onChange?.([+ {+ databaseFullName: "instances/inst1/databases/db1",+ schema: "public",+ table: "t1",+ },+ {+ databaseFullName: "instances/inst1/databases/db1",+ schema: "public",+ table: "t2",+ },+ ])+ }+ />+ ),+}));++vi.mock("@/react/components/ExprEditor", () => ({+ ExprEditor: ({ onUpdate }: { onUpdate: (expr: unknown) => void }) => (+ <button+ data-testid="set-expr"+ type="button"+ onClick={() => onUpdate({ type: "ConditionGroup", args: ["set"] })}+ />+ ),+}));++vi.mock("@/react/components/FeatureAttention", () => ({+ FeatureAttention: () => <div data-testid="feature-attention" />,+}));++vi.mock("@/react/components/FeatureBadge", () => ({+ FeatureBadge: () => <div data-testid="feature-badge" />,+}));++vi.mock("@/react/components/ui/feature-modal", () => ({+ FeatureModal: ({ open }: { open: boolean }) =>+ open ? <div data-testid="feature-modal" /> : null,+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: (props: ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+}));++vi.mock("@/react/components/ui/expiration-picker", () => ({+ ExpirationPicker: ({ onChange }: { onChange?: (value: string) => void }) => (+ <button+ data-testid="set-expiration"+ type="button"+ onClick={() => onChange?.("2026-06-02T10:00:00.000Z")}+ />+ ),+}));++vi.mock("@/react/components/ui/input", () => ({+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++vi.mock("@/react/hooks/useProjectByName", () => ({+ useProjectByName: () => ({ name: "projects/proj1" }),+}));++vi.mock("@/react/lib/sensitive-data/components-utils", () => ({+ getClassificationLevelOptions: () => [],+}));++vi.mock("@/react/lib/sensitive-data/exemptionDataUtils", () => ({+ rewriteResourceDatabase: vi.fn((expression: string) => expression),+}));++vi.mock("@/react/lib/sensitive-data/utils", () => ({+ getExpressionsForDatabaseResource: mocks.getExpressionsForDatabaseResource,+}));++vi.mock("@/react/router", () => ({+ router: { back: mocks.routerBack },+}));++vi.mock("@/store", () => ({+ pushNotification: vi.fn(),+}));++vi.mock("@/store/modules/v1/common", () => ({+ projectNamePrefix: "projects/",+}));++vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (+ selector: (state: {+ projectsByName: Record<string, unknown>;+ settingsByName: Record<string, unknown>;+ hasFeature: () => boolean;+ }) => unknown+ ) =>+ selector({+ projectsByName: {},+ settingsByName: {},+ hasFeature: () => true,+ }),+ {+ getState: () => ({+ getOrFetchSettingByName: mocks.getOrFetchSettingByName,+ getOrFetchPolicyByParentAndType: mocks.getOrFetchPolicyByParentAndType,+ upsertPolicy: mocks.upsertPolicy,+ classification: mocks.classification,+ }),+ }+ ),+}));++vi.mock("@/utils", () => ({+ batchConvertParsedExprToCELString: mocks.batchConvertParsedExprToCELString,+ getDatabaseNameOptionConfig: vi.fn(() => ({ options: [] })),+}));++vi.mock("@/utils/cel-attributes", () => ({+ CEL_ATTRIBUTE_RESOURCE_DATABASE: "resource.database",+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME: "resource.table_name",+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME: "resource.schema_name",+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME: "resource.column_name",+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL: "resource.classification_level",+}));++import { ProjectMaskingExemptionCreatePage } from "./ProjectMaskingExemptionCreatePage";++const TIME = 'request.time < timestamp("2026-06-02T10:00:00.000Z")';+const c1 =+ 'resource.instance_id == "inst1" && resource.database_name == "db1" && resource.table_name == "t1"';+const c2 =+ 'resource.instance_id == "inst1" && resource.database_name == "db1" && resource.table_name == "t2"';++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++const click = async (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });+ await flush();+};++const render = () => {+ const container = document.createElement("div");+ const root = createRoot(container);+ act(() => {+ root.render(<ProjectMaskingExemptionCreatePage projectId="proj1" />);+ });+ return {+ container,+ unmount: () => act(() => root.unmount()),+ };+};++const submittedExpression = (): string | undefined => {+ const arg = mocks.upsertPolicy.mock.calls[0]?.[0] as+ | {+ policy: {+ policy: {+ value: { exemptions: { condition?: { expression: string } }[] };+ };+ };+ }+ | undefined;+ return arg?.policy.policy.value.exemptions[0]?.condition?.expression;+};++const clickRadio = async (container: HTMLElement, index: number) => {+ const radios = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')+ );+ await click(radios[index]!);+};++const clickConfirm = async (container: HTMLElement) => {+ const confirm = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "common.confirm");+ expect(confirm).toBeTruthy();+ expect(confirm?.disabled).toBe(false);+ await click(confirm!);+};++describe("ProjectMaskingExemptionCreatePage builder (BYT-9788)", () => {+ beforeEach(() => {+ mocks.upsertPolicy.mockClear();+ mocks.getOrFetchPolicyByParentAndType.mockReset();+ mocks.buildCELExpr.mockReset();+ mocks.batchConvertParsedExprToCELString.mockReset();+ mocks.getExpressionsForDatabaseResource.mockImplementation(+ (resource: { table?: string }) => [+ 'resource.instance_id == "inst1"',+ 'resource.database_name == "db1"',+ `resource.table_name == "${resource.table}"`,+ ]+ );+ });++ afterEach(() => {+ mocks.getExpressionsForDatabaseResource.mockReset();+ });++ test("SELECT mode: wraps the OR-group so the expiration binds to every resource", async () => {+ const { container, unmount } = render();+ await flush();++ await clickRadio(container, 2); // SELECT+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-two-resources"]')!+ );+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-expiration"]')!+ );+ await click(+ container.querySelector<HTMLElement>(+ '[data-testid="account-multi-select"]'+ )!+ );++ await clickConfirm(container);+ await flush();++ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);+ // FIXED form: the OR-group is parenthesized and the time constraint leads.+ expect(submittedExpression()).toBe(`${TIME} && ((${c1}) || (${c2}))`);++ unmount();+ });++ test("SELECT mode without expiration: OR-group only, still parenthesized", async () => {+ const { container, unmount } = render();+ await flush();++ await clickRadio(container, 2); // SELECT+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-two-resources"]')!+ );+ await click(+ container.querySelector<HTMLElement>(+ '[data-testid="account-multi-select"]'+ )!+ );++ await clickConfirm(container);+ await flush();++ expect(submittedExpression()).toBe(`((${c1}) || (${c2}))`);++ unmount();+ });++ test("EXPRESSION mode: a top-level || in custom CEL is wrapped and bound by the expiration", async () => {+ mocks.buildCELExpr.mockResolvedValue({ parsed: true });+ mocks.batchConvertParsedExprToCELString.mockResolvedValue([+ 'resource.database_name == "a" || resource.database_name == "b"',+ ]);++ const { container, unmount } = render();+ await flush();++ await clickRadio(container, 1); // EXPRESSION+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-expr"]')!+ );+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-expiration"]')!+ );+ await click(+ container.querySelector<HTMLElement>(+ '[data-testid="account-multi-select"]'+ )!+ );++ await clickConfirm(container);+ await flush();++ expect(submittedExpression()).toBe(+ `${TIME} && (resource.database_name == "a" || resource.database_name == "b")`+ );++ unmount();+ });++ test("ALL mode with expiration: time-only expression, no resource group", async () => {+ const { container, unmount } = render();+ await flush();++ // Default mode is ALL.+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-expiration"]')!+ );+ await click(+ container.querySelector<HTMLElement>(+ '[data-testid="account-multi-select"]'+ )!+ );++ await clickConfirm(container);+ await flush();++ expect(submittedExpression()).toBe(TIME);++ unmount();+ });+});diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsxindex c33cf99baa..caf591d1bf 100644--- a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx@@ -5,7 +5,7 @@ import type {} from "react";import { act } from "react";import { createRoot } from "react-dom/client";-import { beforeEach, describe, expect, test, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import type { SensitiveColumn } from "@/react/lib/sensitive-data/types";(@@ -100,15 +100,35 @@ vi.mock("@/react/components/DatabaseResourceSelector", () => ({DatabaseResourceSelector: ({value,includeColumns,+ onChange,}: {value: unknown;includeColumns?: boolean;+ onChange?: (resources: unknown[]) => void;}) => (<divdata-include-columns={String(includeColumns)}data-testid="database-resource-selector">{JSON.stringify(value)}+ <button+ data-testid="set-two-resources"+ type="button"+ onClick={() =>+ onChange?.([+ {+ databaseFullName: "instances/inst1/databases/db1",+ schema: "public",+ table: "t1",+ },+ {+ databaseFullName: "instances/inst1/databases/db1",+ schema: "public",+ table: "t2",+ },+ ])+ }+ /></div>),}));@@ -173,8 +193,20 @@ vi.mock("@/react/components/ui/dialog", () => ({}));vi.mock("@/react/components/ui/expiration-picker", () => ({- ExpirationPicker: ({ minDate }: { minDate: string }) => (- <div data-min-date={minDate} data-testid="expiration-picker" />+ ExpirationPicker: ({+ minDate,+ onChange,+ }: {+ minDate: string;+ onChange?: (value: string) => void;+ }) => (+ <div data-min-date={minDate} data-testid="expiration-picker">+ <button+ data-testid="set-expiration"+ type="button"+ onClick={() => onChange?.("2026-06-02T10:00:00.000Z")}+ />+ </div>),}));@@ -230,6 +262,7 @@ vi.mock("@/utils/v1/cel", () => ({batchConvertCELStringToParsedExpr: mocks.batchConvertCELStringToParsedExpr,}));+import { getExpressionsForDatabaseResource } from "@/react/lib/sensitive-data/utils";import { GrantAccessDialog } from "./GrantAccessDialog";const flush = async () => {@@ -538,3 +571,91 @@ describe("GrantAccessDialog", () => {unmount();});});++// ============================================================+// BYT-9791 — REGRESSION GUARD (bug fixed by #20687).+//+// This was filed as a sibling of BYT-9788: GrantAccessDialog used to emit the+// unwrapped `(c1) || (c2) && request.time < …`, which cel-go reads as+// `(c1) || ((c2) && time)`, leaking the first resource past expiry. #20687+// extracted the shared buildMaskingExemption helper and routed both this dialog+// and the create page through it, so the OR-group is now wrapped and the time+// constraint binds to every resource. This test drives the real dialog and pins+// the corrected output so GrantAccessDialog can't regress to the buggy shape.+// ============================================================++describe("GrantAccessDialog — composite exemption precedence (BYT-9791)", () => {+ const c1 =+ 'resource.instance_id == "inst1" && resource.database_name == "db1" && resource.table_name == "t1"';+ const c2 =+ 'resource.instance_id == "inst1" && resource.database_name == "db1" && resource.table_name == "t2"';+ const timeClause = 'request.time < timestamp("2026-06-02T10:00:00.000Z")';++ beforeEach(() => {+ mocks.upsertPolicy.mockClear();+ mocks.getOrFetchPolicyByParentAndType.mockReset();+ // Return real per-resource clauses so onSubmit assembles a real expression.+ vi.mocked(getExpressionsForDatabaseResource).mockImplementation(+ (resource: { table?: string }) => [+ 'resource.instance_id == "inst1"',+ 'resource.database_name == "db1"',+ `resource.table_name == "${resource.table}"`,+ ]+ );+ });++ afterEach(() => {+ // Restore the inert default the other tests rely on.+ vi.mocked(getExpressionsForDatabaseResource).mockReturnValue([]);+ });++ test("wraps the OR-group so the expiration binds to every resource", async () => {+ const { container, unmount } = renderGrantAccessDialog();+ await flush();++ // Default mode for a non-column-scoped selection is SELECT (radio index 2).+ const radios = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')+ );+ expect(radios[2]?.checked).toBe(true);++ await click(+ container.querySelector<HTMLElement>('[data-testid="set-two-resources"]')!+ );+ await click(+ container.querySelector<HTMLElement>('[data-testid="set-expiration"]')!+ );+ await click(+ container.querySelector<HTMLElement>(+ '[data-testid="account-multi-select"]'+ )!+ );++ const confirm = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "common.confirm");+ expect(confirm).toBeTruthy();+ expect(confirm?.disabled).toBe(false);++ await click(confirm!);+ await flush();++ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);+ const arg = mocks.upsertPolicy.mock.calls[0][0] as {+ policy: {+ policy: {+ value: { exemptions: { condition?: { expression: string } }[] };+ };+ };+ };+ const expression =+ arg.policy.policy.value.exemptions[0]?.condition?.expression;++ // FIXED (#20687): the OR-group is wrapped and the time constraint leads, so+ // the expiry binds to every resource — not just the last branch.+ expect(expression).toBe(`${timeClause} && ((${c1}) || (${c2}))`);+ expect(expression).not.toBe(`(${c1}) || (${c2}) && ${timeClause}`);++ unmount();+ });+});diff --git a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.tsindex 630cdb3ddb..c575990e2a 100644--- a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts+++ b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts@@ -276,6 +276,37 @@ async function revokeAllExemptions(): Promise<void> {});}+// ── Composite (multi-resource) exemption helpers (BYT-9788) ──++// One column-scoped resource clause, AND-joined exactly like the create-page+// builder's getExpressionsForDatabaseResource output. instance_id/database_name+// are the instance resource id and the database name — the same attributes the+// backend masking evaluator populates (masking_evaluator.go:199-203).+function columnResourceClause(column: string): string {+ return [+ `resource.instance_id == "${env.instanceId}"`,+ `resource.database_name == "${env.databaseId}"`,+ `resource.schema_name == "${TEST_SCHEMA}"`,+ `resource.table_name == "${TEST_TABLE}"`,+ `resource.column_name == "${column}"`,+ ].join(" && ");+}++// Replace the project's exemption policy with exactly one exemption carrying a+// raw CEL expression, so the test controls the precise OR/AND/precedence shape.+async function setSingleExemption(+ expression: string,+ description: string,+ member = `user:${env.adminEmail}`,+): Promise<void> {+ await env.api.upsertPolicy(env.project, "masking_exemption", {+ type: "MASKING_EXEMPTION",+ maskingExemptionPolicy: {+ exemptions: [{ members: [member], condition: { expression, description } }],+ },+ });+}+// ── Setup/Teardown ──test.beforeAll(async ({ browser }) => {@@ -543,6 +574,110 @@ test.describe("E2E Masking Verification", () => {});});+// ── Composite Exemption Expiration (BYT-9788) ──+//+// A composite exemption ORs several resource clauses and ANDs a request.time+// bound. Because `&&` binds tighter than `||` in CEL — and the backend evaluates+// with stock cel-go (masking_evaluator.go:237) — the OR-group MUST be wrapped:+// request.time < T && ((res1) || (res2))+// If it isn't, the time bound attaches only to the LAST branch and every earlier+// resource is served unmasked forever (the GovTech incident). #20683 fixed the+// create-page builder and #20687 shared it with GrantAccessDialog (BYT-9791).+//+// These verify the contract end-to-end through the real masking evaluator and SQL+// editor — the on-screen masked/unmasked result is the oracle, not a CEL string.+test.describe("Composite Exemption Expiration (BYT-9788)", () => {+ const PAST = "2020-01-01T00:00:00.000Z";+ const FUTURE = "2099-01-01T00:00:00.000Z";+ let res1: string; // col_classification clause+ let res2: string; // col_semantic clause++ test.beforeAll(() => {+ res1 = columnResourceClause(CLASSIFICATION_COLUMN);+ res2 = columnResourceClause(SEMANTIC_TYPE_COLUMN);+ });++ test.beforeEach(async () => {+ await revokeAllExemptions();+ });++ test.afterAll(async () => {+ await revokeAllExemptions();+ });++ // Query one column in the SQL editor; true = its known unmasked value is+ // visible (unmasked), false = masked.+ const columnUnmasked = async (col: MaskingTestColumn): Promise<boolean> => {+ const sqlEditor = new SqlEditorPage(page, env.baseURL);+ const sql = `SELECT "${col.sampleColumn}" FROM "${col.sampleSchema}"."${col.sampleTable}" WHERE "${col.primaryKeyColumn}" = '${col.primaryKeyValue}';`;+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await sqlEditor.runQuery(sql);+ return sqlEditor.resultContainsText(col.knownUnmaskedValue);+ };++ test("future expiry unmasks ALL columns in the composite", async () => {+ await setSingleExemption(+ `request.time < timestamp("${FUTURE}") && ((${res1}) || (${res2}))`,+ "composite future expiry",+ );+ expect(+ await columnUnmasked(maskingData.classificationColumn),+ "first column should be unmasked under a valid future expiry",+ ).toBe(true);+ expect(+ await columnUnmasked(maskingData.semanticTypeColumn),+ "second column should be unmasked under a valid future expiry",+ ).toBe(true);+ });++ test("past expiry re-masks ALL columns in the composite (the BYT-9788 contract)", async () => {+ await setSingleExemption(+ `request.time < timestamp("${PAST}") && ((${res1}) || (${res2}))`,+ "composite past expiry",+ );+ expect(+ await columnUnmasked(maskingData.classificationColumn),+ "first column must be masked once the wrapped expiry passes",+ ).toBe(false);+ expect(+ await columnUnmasked(maskingData.semanticTypeColumn),+ "second column must be masked once the wrapped expiry passes",+ ).toBe(false);+ });++ test("list page shows a composite grant's Active/Expired status consistently", async () => {+ const listPage = new MaskingExemptionPage(page, env.baseURL);++ // Future expiry → appears under Active, both columns listed, not expired.+ await setSingleExemption(+ `request.time < timestamp("${FUTURE}") && ((${res1}) || (${res2}))`,+ "composite display future",+ );+ await listPage.goto(projectId);+ await listPage.activeTab.click();+ await page.waitForTimeout(500);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);+ await expect(page.getByText("composite display future")).toBeVisible();+ await expect(page.getByText("(Expired)")).toHaveCount(0);+ await expect(page.getByText(CLASSIFICATION_COLUMN).first()).toBeVisible();+ await expect(page.getByText(SEMANTIC_TYPE_COLUMN).first()).toBeVisible();++ // Past expiry → appears under Expired, marked expired.+ await setSingleExemption(+ `request.time < timestamp("${PAST}") && ((${res1}) || (${res2}))`,+ "composite display past",+ );+ await listPage.goto(projectId);+ await listPage.expiredTab.click();+ await page.waitForTimeout(500);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);+ await expect(page.getByText("composite display past")).toBeVisible();+ await expect(page.getByText("(Expired)").first()).toBeVisible();+ });+});+// ── Responsive Layout ──test.describe("Responsive Layout", () => {