Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(masking-exemption): UI bug fixes + e2e test framework (#19945)
zchpeter76cd7cf153b0
diff --git a/.sonarcloud.properties b/.sonarcloud.propertiesindex c2c81c8834..f6357d3152 100644--- a/.sonarcloud.properties+++ b/.sonarcloud.properties@@ -8,7 +8,8 @@ sonar.exclusions=\backend/api/mcp/gen/**,\proto/gen/**,\bytebase-build/**,\- frontend/node_modules/**+ frontend/node_modules/**,\+ frontend/playwright.config.ts# Path to tests — identify test files so they are analyzed as tests, not sourcesonar.test.inclusions=\@@ -21,7 +22,8 @@ sonar.test.inclusions=\frontend/src/**/*.test.ts,\frontend/src/**/*.test.tsx,\frontend/src/**/*.spec.ts,\- frontend/src/**/*.spec.tsx+ frontend/src/**/*.spec.tsx,\+ frontend/tests/**# Source encodingsonar.sourceEncoding=UTF-8@@ -29,7 +31,7 @@ sonar.sourceEncoding=UTF-8# Suppress false-positive security hotspots that travel with the codebase.# These have been triaged and confirmed safe. Using sonar.issue.ignore so# any fork or downstream SonarCloud scan also benefits.-sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql,fp_cognitive_ts,fp_cognitive_go+sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql,fp_cognitive_ts,fp_cognitive_tsx,fp_cognitive_vue,fp_cognitive_go# go:S2077 (SQL Injection) in db plugin sync.go files.# These files query system catalogs (information_schema, pg_catalog, sys.*) using@@ -65,10 +67,16 @@ sonar.issue.ignore.multicriteria.fp_role_sql.resourceKey=backend/plugin/db/*/rol# Cognitive Complexity (S3776) — disabled for this repository.# Bytebase has complex domain logic (CEL parsing, policy evaluation, SQL generation)# where high cognitive complexity is inherent and not a code quality issue.+# NOTE: SonarCloud multicriteria resourceKey does NOT support `**/*` as a+# catch-all — it must match actual file path patterns. Use per-extension globs.sonar.issue.ignore.multicriteria.fp_cognitive_ts.ruleKey=typescript:S3776-sonar.issue.ignore.multicriteria.fp_cognitive_ts.resourceKey=**/*+sonar.issue.ignore.multicriteria.fp_cognitive_ts.resourceKey=**/*.ts+sonar.issue.ignore.multicriteria.fp_cognitive_tsx.ruleKey=typescript:S3776+sonar.issue.ignore.multicriteria.fp_cognitive_tsx.resourceKey=**/*.tsx+sonar.issue.ignore.multicriteria.fp_cognitive_vue.ruleKey=typescript:S3776+sonar.issue.ignore.multicriteria.fp_cognitive_vue.resourceKey=**/*.vuesonar.issue.ignore.multicriteria.fp_cognitive_go.ruleKey=go:S3776-sonar.issue.ignore.multicriteria.fp_cognitive_go.resourceKey=**/*+sonar.issue.ignore.multicriteria.fp_cognitive_go.resourceKey=**/*.go# Exclusions for copy-paste detectionsonar.cpd.exclusions=\@@ -82,4 +90,5 @@ sonar.cpd.exclusions=\frontend/src/**/*.test.ts,\frontend/src/**/*.test.tsx,\frontend/src/react/mount*.ts,\+ frontend/tests/**,\proto/gen/**diff --git a/frontend/.gitignore b/frontend/.gitignoreindex 9f58ea1be1..1d776b7544 100644--- a/frontend/.gitignore+++ b/frontend/.gitignore@@ -30,3 +30,12 @@ type-check.log**.njsproj*.sln*.sw?++# E2E test artifacts+.e2e-env.json+.e2e-snapshot.json+.auth/+test-results/+playwright-report/+.playwright-cli/+.playwright-mcp/diff --git a/frontend/package.json b/frontend/package.jsonindex 913b1acc43..580bff465b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -104,6 +104,7 @@"@iconify/json": "2.2.446","@intlify/eslint-plugin-vue-i18n": "^4.0.0","@intlify/unplugin-vue-i18n": "11.0.7",+ "@playwright/test": "^1.59.1","@rollup/plugin-yaml": "4.1.2","@tailwindcss/forms": "0.5.11","@tailwindcss/typography": "0.5.19",diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.tsnew file mode 100644index 0000000000..4fcf9cdf94--- /dev/null+++ b/frontend/playwright.config.ts@@ -0,0 +1,32 @@+import { defineConfig, devices } from "@playwright/test";+import * as path from "path";++const headed = !!process.env.BYTEBASE_HEADED;++export default defineConfig({+ testDir: "./tests/e2e",+ fullyParallel: false,+ forbidOnly: !!process.env.CI,+ retries: process.env.CI ? 2 : 0,+ workers: 1,+ reporter: process.env.CI ? "github" : "html",+ globalSetup: path.resolve(__dirname, "tests/e2e/framework/global-setup.ts"),+ globalTeardown: path.resolve(__dirname, "tests/e2e/framework/global-teardown.ts"),+ use: {+ headless: !headed,+ trace: "on-first-retry",+ screenshot: "only-on-failure",+ },+ projects: [+ {+ name: "setup",+ testMatch: /framework\/setup-project\.ts/,+ },+ {+ name: "chromium",+ testIgnore: ["**/framework/**"],+ use: { ...devices["Desktop Chrome"], storageState: ".auth/state.json" },+ dependencies: ["setup"],+ },+ ],+});diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 37f7d211fb..db93f24b29 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -253,6 +253,9 @@ importers:'@intlify/unplugin-vue-i18n':specifier: 11.0.7version: 11.0.7(@vue/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]))+ '@playwright/test':+ specifier: ^1.59.1+ version: 1.59.1'@rollup/plugin-yaml':specifier: 4.1.2version: 4.1.2([email protected])@@ -1007,28 +1010,24 @@ packages:engines: {node: '>=14.21.3'}cpu: [arm64]os: [linux]- libc: [musl]'@biomejs/[email protected]':resolution: {integrity: sha512-kMLaI7OF5GN1Q8Doymjro1P8rVEoy7BKQALNz6fiR8IC1WKduoNyteBtJlHT7ASIL0Cx2jR6VUOBIbcB1B8pew==}engines: {node: '>=14.21.3'}cpu: [arm64]os: [linux]- libc: [glibc]'@biomejs/[email protected]':resolution: {integrity: sha512-C9s98IPDu7DYarjlZNuzJKTjVHN03RUnmHV5htvqsx6vEUXCDSJ59DNwjKVD5XYoSS4N+BYhq3RTBAL8X6svEg==}engines: {node: '>=14.21.3'}cpu: [x64]os: [linux]- libc: [musl]'@biomejs/[email protected]':resolution: {integrity: sha512-oHXmUFEoH8Lql1xfc3QkFLiC1hGR7qedv5eKNlC185or+o4/4HiaU7vYODAH3peRCfsuLr1g6v2fK9dFFOYdyw==}engines: {node: '>=14.21.3'}cpu: [x64]os: [linux]- libc: [glibc]'@biomejs/[email protected]':resolution: {integrity: sha512-xzThn87Pf3YrOGTEODFGONmqXpTwUNxovQb72iaUOdcw8sBSY3+3WD8Hm9IhMYLnPi0n32s3L3NWU6+eSjfqFg==}@@ -1872,6 +1871,11 @@ packages:resolution: {integrity: sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==}engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}+ '@playwright/[email protected]':+ resolution: {integrity: sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==}+ engines: {node: '>=18'}+ hasBin: true+'@popperjs/[email protected]':resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==}@@ -1930,79 +1934,66 @@ packages:resolution: {integrity: sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==}cpu: [arm]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==}cpu: [arm]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==}cpu: [arm64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==}cpu: [arm64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==}cpu: [loong64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==}cpu: [loong64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==}cpu: [ppc64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==}cpu: [ppc64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==}cpu: [riscv64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==}cpu: [riscv64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==}cpu: [s390x]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==}cpu: [x64]os: [linux]- libc: [glibc]'@rollup/[email protected]':resolution: {integrity: sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==}cpu: [x64]os: [linux]- libc: [musl]'@rollup/[email protected]':resolution: {integrity: sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==}@@ -2080,28 +2071,24 @@ packages:engines: {node: '>= 20'}cpu: [arm64]os: [linux]- libc: [glibc]'@tailwindcss/[email protected]':resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}engines: {node: '>= 20'}cpu: [arm64]os: [linux]- libc: [musl]'@tailwindcss/[email protected]':resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}engines: {node: '>= 20'}cpu: [x64]os: [linux]- libc: [glibc]'@tailwindcss/[email protected]':resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}engines: {node: '>= 20'}cpu: [x64]os: [linux]- libc: [musl]'@tailwindcss/[email protected]':resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}@@ -3360,6 +3347,11 @@ packages:react-dom:optional: true+ resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]+resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}@@ -3776,28 +3768,24 @@ packages:engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [musl]resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [musl]resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==}@@ -4252,6 +4240,16 @@ packages:resolution: {integrity: sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==}+ resolution: {integrity: sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==}+ engines: {node: '>=18'}+ hasBin: true+resolution: {integrity: sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==}engines: {node: '>= 10.12'}@@ -6811,6 +6809,10 @@ snapshots:'@pkgr/[email protected]': {}+ '@playwright/[email protected]':+ dependencies:+ playwright: 1.59.1+'@popperjs/[email protected]': {}'@rolldown/[email protected]': {}@@ -8390,6 +8392,9 @@ snapshots:react: 19.2.4react-dom: 19.2.4([email protected])+ optional: true+optional: true@@ -9514,6 +9519,14 @@ snapshots:exsolve: 1.0.7pathe: 2.0.3+ [email protected]: {}++ dependencies:+ playwright-core: 1.59.1+ optionalDependencies:+ fsevents: 2.3.2+dependencies:async: 3.2.6diff --git a/frontend/src/components/SensitiveData/exemptionDataUtils.ts b/frontend/src/components/SensitiveData/exemptionDataUtils.tsindex 41151f2e3d..0bc6890248 100644--- a/frontend/src/components/SensitiveData/exemptionDataUtils.ts+++ b/frontend/src/components/SensitiveData/exemptionDataUtils.ts@@ -46,7 +46,9 @@ const databaseResourcePattern =export function extractDatabaseName(resource: string): string {const matches = resource.match(databaseResourcePattern);- return matches?.groups?.databaseName ?? "";+ const name = matches?.groups?.databaseName ?? "";+ // Treat "-1" (legacy UNKNOWN_ID sentinel) as empty — means "all databases"+ return name === "-1" ? "" : name;}export const operatorDisplayMap: Record<string, string> = {diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsxindex e568fe185b..207ec6982f 100644--- a/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx@@ -368,7 +368,7 @@ export function ProjectMaskingExemptionPage({const activePreset = useMemo(() => {const status = getValueFromScopes(searchParams, "status");- return status || "active";+ return status || "all";}, [searchParams]);const selectPreset = useCallback(@@ -955,12 +955,12 @@ function ExemptionMemberItem({</span>)}{isServiceAccount && (- <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-accent/30 bg-accent/5 text-accent">+ <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-accent/30 bg-accent/5 text-accent whitespace-nowrap shrink-0">{t("settings.members.service-account")}</span>)}{isWorkloadIdentity && (- <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-accent/30 bg-accent/5 text-accent">+ <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-accent/30 bg-accent/5 text-accent whitespace-nowrap shrink-0">{t("settings.members.workload-identity")}</span>)}@@ -1057,7 +1057,7 @@ function ExemptionDetailPanel({{member.grants.map((grant, idx) => (<divkey={grant.id}- className="border border-block-border rounded-sm overflow-hidden pt-4"+ className="border border-block-border rounded-sm overflow-hidden"><ExemptionGrantSectiongrant={grant}@@ -1095,13 +1095,10 @@ function ExemptionGrantSection({const title = useMemo(() => generateGrantTitle(grant), [grant]);- const isExpired = useMemo(- () =>- !!grant.expirationTimestamp && grant.expirationTimestamp <= Date.now(),- [grant.expirationTimestamp]- );+ const isExpired =+ !!grant.expirationTimestamp && grant.expirationTimestamp <= Date.now();- const expiryLabel = useMemo(() => {+ const expiryLabel = (() => {if (!grant.expirationTimestamp) return "";const msRemaining = grant.expirationTimestamp - Date.now();const hoursRemaining = msRemaining / (1000 * 60 * 60);@@ -1112,7 +1109,7 @@ function ExemptionGrantSection({days,count: days,});- }, [grant.expirationTimestamp, t]);+ })();return (<div>@@ -1210,7 +1207,7 @@ function ExemptionResourceTable({}) {const { t } = useTranslation();- const isSentinel = (value: string): boolean => value === "";+ const isSentinel = (value: string): boolean => value === "" || value === "-1";const handleDatabaseClick = (resource: DatabaseResource) => {const path = resource.databaseFullName.startsWith("/")diff --git a/frontend/tests/e2e/AGENTS.md b/frontend/tests/e2e/AGENTS.mdnew file mode 100644index 0000000000..d6c452aca8--- /dev/null+++ b/frontend/tests/e2e/AGENTS.md@@ -0,0 +1,151 @@+# E2E Tests — Contributor & AI Agent Guide++Conventions for writing and maintaining Bytebase e2e tests. Follow these rules unless you have a strong, documented reason not to.++## Core Principles++### 1. Create your own test data, don't discover it++**Do:** Create a dedicated schema/table/rows for your test and drop them in `afterAll`.++```typescript+// In beforeAll — create what you need+execSql(env, dbName, `CREATE SCHEMA my_feature_test`);+execSql(env, dbName, `CREATE TABLE my_feature_test.t (id INT PRIMARY KEY, col TEXT)`);+execSql(env, dbName, `INSERT INTO my_feature_test.t VALUES (1, 'KnownValue')`);++// In afterAll — clean up+execSql(env, dbName, `DROP SCHEMA IF EXISTS my_feature_test CASCADE`);+```++**Don't:** Query `information_schema` or scan the demo data to find something usable. Discovery-based tests are fragile — they fail when demo data changes, when tables are empty, or when pre-existing masking hides the values you need.++**Why:** A test that owns its fixtures is deterministic. You know exactly what values exist, what's masked, what's not, and what state is left when the test completes. `masking-exemption.spec.ts:createMaskingTestData` is the canonical example.++### 2. Share a single browser across all tests in a file++**Do:** Create one `BrowserContext` and `Page` in the file-level `test.beforeAll`, and reuse them across every test in the file.++```typescript+let sharedContext: BrowserContext;+let page: Page;++test.beforeAll(async ({ browser }) => {+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ await sharedContext?.close();+});++test("my test", async () => {+ // use the shared `page` — no { page } destructuring+ await page.goto(...);+});+```++**Don't:** Use Playwright's default per-test `{ page }` fixture. It opens and closes a browser context for every test, which:+- Costs real time (especially on CI)+- Triggers NVirtualList first-render timing bugs+- Makes tests slower for no isolation benefit (we run `workers: 1` anyway)++**Side effects to clean up manually** (since we lose per-test isolation):+- Reset viewport in `afterAll` if you changed it mid-suite+- Clear URL/tab state explicitly if it matters (usually via `gotoWithDb` etc.)+- Reset policy state via API (`revokeAllExemptions`) in `beforeEach` when tests depend on clean state++### 3. API for setup, browser for verification++Bytebase's v1 REST API is your tool for fast, deterministic state setup. Use the browser only to verify what a user would see.++**Do:**+- Grant/revoke policies via API, then render them in the browser to assert the UI reflects the state.+- Create test data via `psql` (Unix socket), configure catalog via API, run the test UI flow in the browser.++**Don't:**+- Click through the UI to set up preconditions when an API call would do it.+- Screenshot-compare for logic assertions.++### 4. Use primary keys for masking verification queries++When verifying masked/unmasked data in the SQL editor, query by the row's primary key, not by `LIMIT n`. Ordering is not deterministic without `ORDER BY`, and `LIMIT` may not include your known value.++```typescript+const sql = `SELECT "${col}" FROM "${schema}"."${table}" WHERE "${pkColumn}" = '${pkValue}'`;+```++### 5. Avoid `waitForTimeout` for arbitrary delays++**Do:** Wait for specific conditions via locator auto-wait, `waitForResponse`, `waitForURL`, or `expect(...).toBeVisible()`.++**Don't:** Sprinkle `await page.waitForTimeout(500)` everywhere. Every arbitrary sleep is a flakiness source on slow CI.++*(Existing tests have technical debt here — new tests should not add to it.)*++### 6. Cross-platform keyboard shortcuts++Use `ControlOrMeta+a` (portable), not `Meta+a` (Mac-only) or `Control+a` (Linux/Windows-only).++### 7. Prefer `data-testid` over class-based selectors++Tailwind class substrings like `[class*='border border-gray']` break on any CSS refactor. If you need a new locator, add a `data-testid` attribute to the component. Existing class-based selectors are technical debt.++## Directory Layout++```+frontend/tests/e2e/+├── README.md — human-facing docs (how to run tests)+├── AGENTS.md — this file (conventions)+├── framework/ — shared infrastructure (don't add feature code here)+└── <feature-name>/ — one directory per feature test suite+ ├── *.spec.ts — test files+ └── *.page.ts — page object models (feature-specific)+```++## File Responsibilities++| File | Responsibility |+|------|----------------|+| `framework/api-client.ts` | Bytebase v1 REST API wrapper, token refresh on 401 |+| `framework/env.ts` | `TestEnv` interface, load/save via `.e2e-env.json` |+| `framework/mode-start-new-bytebase.ts` | Disposable server lifecycle + port reconciliation |+| `framework/global-setup.ts` | Starts server before any test runs |+| `framework/global-teardown.ts` | Stops server after all tests finish |+| `framework/setup-project.ts` | Auth + instance/database discovery, writes env + auth state |++## Adding a New Feature Test Suite++1. **Create directory**: `tests/e2e/<feature-name>/`+2. **Write page objects** in `<feature>.page.ts` (one class per UI surface). Accept `baseURL` in the constructor so pages can navigate via absolute URLs.+3. **Write spec file** `<feature>.spec.ts`:+ - Import `loadTestEnv` from `../framework/env`+ - Declare the shared `page` / `sharedContext` at module level+ - In file-level `test.beforeAll`: `loadTestEnv()`, login, create test data, open the shared browser+ - In `test.afterAll`: close browser, clean up test data via the same code path that created it+4. **Use the canonical example** — read `frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts` as a reference.++## Extending the API Client++- Add methods to `BytebaseApiClient` in `framework/api-client.ts`+- Use `this.request<T>()` with typed responses+- Include `pageSize=100` on list endpoints+- Only add methods actually used by a test — no speculative API coverage++## Running DDL / DML (for test data setup)++The Bytebase query API is **read-only**. For DDL/DML, use the `execSql` helper (see `masking-exemption.spec.ts`) which shells out to `psql` via Unix socket to the sample Postgres instance.++**Port layout**: the disposable Bytebase server on `PORT` starts sample Postgres at:+- `PORT + 3` → `test-sample-instance` (hr_test)+- `PORT + 4` → `prod-sample-instance` (hr_prod)++Get the correct port from `getInstance(env.instance)` rather than hardcoding the offset.++## Known Constraints++- **Demo mode only**: tests run against `--demo` data. Demo data is pre-seeded with sample instances and has a built-in enterprise license.+- **Serial execution**: `fullyParallel: false` + `workers: 1`. Tests within and across files are sequential.+- **`psql` dependency**: must be on PATH for DDL/DML setup.+- **Unix-like OS only**: the sample Postgres uses Unix sockets in `/tmp`.+- **Demo admin credentials**: hardcoded `[email protected]` / `12345678` (the well-known demo defaults, not a secret).diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdnew file mode 100644index 0000000000..cfab4e2cad--- /dev/null+++ b/frontend/tests/e2e/README.md@@ -0,0 +1,73 @@+# E2E Tests++Playwright-based end-to-end tests for Bytebase. Starts a disposable Bytebase server with `--demo` data, runs tests, tears down.++## Prerequisites++1. **Bytebase binary with embedded frontend:**+ ```bash+ pnpm --dir frontend release+ go build -tags embed_frontend -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go+ ```++2. **`psql` client** on PATH — required for DDL setup (the Bytebase query API is read-only; tests connect directly to the sample Postgres via Unix socket).++## Running Tests++```bash+cd frontend++# Headless (default)+pnpm exec playwright test++# Headed — watch tests run in a visible browser+BYTEBASE_HEADED=1 pnpm exec playwright test++# Single test file+pnpm exec playwright test masking-exemption+```++## Environment Variables++| Variable | Required | Default | Description |+|----------|----------|---------|-------------|+| `BYTEBASE_BIN` | No | `./bytebase-build/bytebase` | Path to pre-built binary |+| `BYTEBASE_STARTUP_TIMEOUT` | No | `300000` (5 min) | Server startup timeout in ms |+| `BYTEBASE_HEADED` | No | — | Set to `1` for headed browser |+| `CI` | No | — | Enables CI-specific reporter |++## Directory Layout++```+frontend/tests/e2e/+├── README.md — this file (human docs)+├── AGENTS.md — conventions for AI agents / contributors+├── framework/ — shared test infrastructure+│ ├── api-client.ts — Bytebase v1 REST API wrapper+│ ├── env.ts — TestEnv interface, serialization+│ ├── mode-start-new-bytebase.ts — server lifecycle (start/stop/cleanup)+│ ├── global-setup.ts — starts the server before any tests+│ ├── global-teardown.ts — stops the server after all tests+│ └── setup-project.ts — auth + discovery (runs as a Playwright setup project)+└── masking-exemption/ — feature test suite+ ├── masking-exemption.spec.ts+ └── masking-exemption.page.ts+```++## How It Works++1. **`globalSetup`**: Cleans orphaned processes, starts Bytebase with `--demo` + embedded Postgres on a random high port, reconciles sample instance data source ports.+2. **Setup project** (runs as a Playwright test before all others): Logs in as the demo admin (`[email protected]` / `12345678`), discovers instances/databases/projects, saves auth state to `.auth/state.json`.+3. **Tests run**: Each spec file shares one browser context/page (see [AGENTS.md](./AGENTS.md)). Tests call `loadTestEnv()` to get the API client and env data, create their own test data, and run UI-driven verification.+4. **`globalTeardown`**: Kills the server process group, removes temp data dir and PID file.++## Troubleshooting++| Symptom | Fix |+|---|---|+| `Bytebase binary not found` | Run the build commands above or set `BYTEBASE_BIN` |+| `spawn psql ENOENT` | Install Postgres client: `brew install postgresql` or `apt install postgresql-client` |+| Server won't start / port in use | `lsof -ti:18234 \| xargs kill` and check for orphan processes matching `bytebase-e2e` |+| Stale PID file | `rm /tmp/bytebase-e2e-pid` |+| Stale auth state | `rm -rf frontend/.auth/ frontend/tests/.auth/` |+| "This Bytebase build does not bundle frontend" error | Binary was built without `embed_frontend` tag — rebuild with the prerequisite commands above |diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsnew file mode 100644index 0000000000..c92302bdee--- /dev/null+++ b/frontend/tests/e2e/framework/api-client.ts@@ -0,0 +1,138 @@+export interface ApiClientOptions {+ baseURL: string;+ credentials?: { email: string; password: string }; // Optional only during server startup before credentials are known+}++export class BytebaseApiClient {+ private baseURL: string;+ private token = "";+ private credentials?: { email: string; password: string };++ constructor(options: ApiClientOptions) {+ this.baseURL = options.baseURL.replace(/\/$/, "");+ this.credentials = options.credentials;+ }++ private async request<T>(method: string, path: string, body?: unknown): Promise<T> {+ const headers: Record<string, string> = { "Content-Type": "application/json" };+ if (this.token) headers["Authorization"] = `Bearer ${this.token}`;++ const resp = await fetch(`${this.baseURL}${path}`, {+ method,+ headers,+ body: body ? JSON.stringify(body) : undefined,+ });++ // Token refresh on 401+ if (resp.status === 401 && this.credentials) {+ await this.login(this.credentials.email, this.credentials.password);+ headers["Authorization"] = `Bearer ${this.token}`;+ const retry = await fetch(`${this.baseURL}${path}`, {+ method,+ headers,+ body: body ? JSON.stringify(body) : undefined,+ });+ if (!retry.ok) throw new Error(`API ${method} ${path} failed (${retry.status}): ${await retry.text()}`);+ return retry.json() as Promise<T>;+ }++ if (!resp.ok) throw new Error(`API ${method} ${path} failed (${resp.status}): ${await resp.text()}`);+ return resp.json() as Promise<T>;+ }++ // Auth+ async login(email: string, password: string): Promise<string> {+ const { token } = await this.request<{ token: string }>("POST", "/v1/auth/login", { email, password });+ this.token = token;+ this.credentials = { email, password };+ return token;+ }++ // Discovery+ async listInstances() {+ return this.request<{ instances: { name: string; engine: string; title: string }[] }>("GET", "/v1/instances?pageSize=100&showDeleted=false");+ }++ async listDatabases(parent: string) {+ return this.request<{ databases: { name: string; project: string }[] }>("GET", `/v1/${parent}/databases?pageSize=100`);+ }++ async syncDatabase(databaseFullName: string) {+ return this.request<unknown>("POST", `/v1/${databaseFullName}:sync`, {});+ }++ // Policies+ async getPolicy(policyName: string) {+ try {+ return await this.request<Record<string, unknown>>("GET", `/v1/${policyName}`);+ } catch {+ return null;+ }+ }++ async upsertPolicy(parent: string, policyType: string, policy: unknown) {+ // Derive the oneof field name from policyType: "masking_exemption" → "masking_exemption_policy"+ // The backend expects the updateMask to target the specific policy oneof field.+ const updateMask = `${policyType}_policy`;+ return this.request<unknown>(+ "PATCH",+ `/v1/${parent}/policies/${policyType}?allowMissing=true&updateMask=${updateMask}`,+ policy,+ );+ }++ async deletePolicy(parent: string, policyType: string) {+ try { await this.request<unknown>("DELETE", `/v1/${parent}/policies/${policyType}`); } catch { /* ignore */ }+ }++ // Catalog+ async getCatalog(dbName: string) {+ return this.request<Record<string, unknown>>("GET", `/v1/${dbName}/catalog`);+ }++ async updateCatalog(dbName: string, catalog: unknown) {+ return this.request<unknown>("PATCH", `/v1/${dbName}/catalog`, catalog);+ }++ // Instances+ async getInstance(instanceName: string) {+ return this.request<{ name: string; dataSources: { id: string; port: string; host: string }[] }>("GET", `/v1/${instanceName}`);+ }++ async updateInstanceDataSource(instanceName: string, dataSourceId: string, port: string) {+ return this.request<unknown>("PATCH",+ `/v1/${instanceName}:updateDataSource?updateMask=port`,+ { id: dataSourceId, port });+ }++ // Query — endpoint is /v1/instances/{instance}/databases/{database}:query+ async query(databaseFullName: string, statement: string) {+ return this.request<{ results: unknown[] }>("POST", `/v1/${databaseFullName}:query`, {+ name: databaseFullName,+ statement,+ limit: 100,+ });+ }++ // Service Accounts+ async createServiceAccount(parent: string, serviceAccountId: string, title: string) {+ return this.request<{ name: string; email: string }>("POST",+ `/v1/${parent}/serviceAccounts?serviceAccountId=${serviceAccountId}`,+ { title });+ }++ async deleteServiceAccount(email: string) {+ try { await this.request<unknown>("DELETE", `/v1/serviceAccounts/${email}`); } catch { /* ignore */ }+ }++ // Workload Identities+ async createWorkloadIdentity(parent: string, workloadIdentityId: string, title: string, provider: string, issuer: string, subject: string) {+ return this.request<{ name: string; email: string }>("POST",+ `/v1/${parent}/workloadIdentities?workloadIdentityId=${workloadIdentityId}`,+ { title, provider, attestationAuthority: { oidcAuthority: { issuer } }, subjectAttributes: { subject } });+ }++ async deleteWorkloadIdentity(email: string) {+ try { await this.request<unknown>("DELETE", `/v1/workloadIdentities/${email}`); } catch { /* ignore */ }+ }+}diff --git a/frontend/tests/e2e/framework/env.ts b/frontend/tests/e2e/framework/env.tsnew file mode 100644index 0000000000..2e004b9f33--- /dev/null+++ b/frontend/tests/e2e/framework/env.ts@@ -0,0 +1,40 @@+import * as fs from "fs";+import * as path from "path";+import { BytebaseApiClient } from "./api-client";++const ENV_FILE = path.join(__dirname, "../../.e2e-env.json");++export interface TestEnv {+ baseURL: string;+ adminEmail: string;+ adminPassword: string;+ project: string;+ instance: string;+ instanceId: string;+ database: string;+ databaseId: string;+}++export function saveTestEnv(env: TestEnv): void {+ const serialized = { ...env } as Record<string, unknown>;+ delete serialized["api"];+ fs.writeFileSync(ENV_FILE, JSON.stringify(serialized, null, 2));+}++export function loadTestEnv(): TestEnv & { api: BytebaseApiClient } {+ if (!fs.existsSync(ENV_FILE)) {+ throw new Error(+ ".e2e-env.json not found. Run the setup project first (npx playwright test)."+ );+ }+ const raw = JSON.parse(fs.readFileSync(ENV_FILE, "utf-8")) as TestEnv;+ const api = new BytebaseApiClient({+ baseURL: raw.baseURL,+ credentials: { email: raw.adminEmail, password: raw.adminPassword },+ });+ return { ...raw, api };+}++export function cleanupEnvFile(): void {+ if (fs.existsSync(ENV_FILE)) fs.unlinkSync(ENV_FILE);+}diff --git a/frontend/tests/e2e/framework/global-setup.ts b/frontend/tests/e2e/framework/global-setup.tsnew file mode 100644index 0000000000..ae3c138556--- /dev/null+++ b/frontend/tests/e2e/framework/global-setup.ts@@ -0,0 +1,13 @@+import { saveTestEnv } from "./env";+import { cleanupOrphans, startServer } from "./mode-start-new-bytebase";++async function globalSetup() {+ cleanupOrphans();+ const { baseURL, adminEmail, adminPassword } = await startServer();+ saveTestEnv({+ baseURL, adminEmail, adminPassword,+ project: "", instance: "", instanceId: "", database: "", databaseId: "",+ });+}++export default globalSetup;diff --git a/frontend/tests/e2e/framework/global-teardown.ts b/frontend/tests/e2e/framework/global-teardown.tsnew file mode 100644index 0000000000..d49f431728--- /dev/null+++ b/frontend/tests/e2e/framework/global-teardown.ts@@ -0,0 +1,9 @@+import { cleanupEnvFile } from "./env";+import { stopServer } from "./mode-start-new-bytebase";++async function globalTeardown() {+ stopServer();+ cleanupEnvFile();+}++export default globalTeardown;diff --git a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts b/frontend/tests/e2e/framework/mode-start-new-bytebase.tsnew file mode 100644index 0000000000..0fa1e26988--- /dev/null+++ b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts@@ -0,0 +1,183 @@+import * as child_process from "child_process";+import * as fs from "fs";+import * as net from "net";+import * as os from "os";+import * as path from "path";++import { BytebaseApiClient } from "./api-client";++const PID_FILE = "/tmp/bytebase-e2e-pid";+const DEFAULT_PORT = 18234;+const DEFAULT_TIMEOUT = 300000; // 5 minutes — server startup includes embedded Postgres + migrations + demo data+// Demo mode pre-populates this admin user with workspace admin role+const ADMIN_EMAIL = "[email protected]";+const ADMIN_PASSWORD = "12345678"; // NOSONAR: fixed demo account password++let serverProcess: child_process.ChildProcess | undefined;+let tempDir: string | undefined;++export function cleanupOrphans(): void {+ if (!fs.existsSync(PID_FILE)) return;+ const content = fs.readFileSync(PID_FILE, "utf-8").trim().split("\n");+ const pid = parseInt(content[0], 10);+ const dir = content[1];+ try {+ process.kill(-pid, "SIGTERM"); // Kill process group+ } catch {+ /* already dead */+ }+ if (dir && fs.existsSync(dir)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ fs.unlinkSync(PID_FILE);+}++function checkPort(port: number): Promise<boolean> {+ return new Promise((resolve) => {+ const server = net.createServer();+ server.once("error", () => resolve(false));+ server.once("listening", () => {+ server.close();+ resolve(true);+ });+ server.listen(port, "127.0.0.1");+ });+}++// Bytebase --demo allocates 4 ports based on the main --port value:+// PORT — main HTTP server+// PORT + 2 — embedded metadata Postgres+// PORT + 3 — test-sample-instance Postgres+// PORT + 4 — prod-sample-instance Postgres+// All four must be free before we commit to a base port.+export async function findAvailablePort(): Promise<number> {+ let port = DEFAULT_PORT;+ const offsets = [0, 2, 3, 4];+ for (let i = 0; i < 100; i++) {+ const checks = await Promise.all(offsets.map((o) => checkPort(port + o)));+ if (checks.every((free) => free)) return port;+ port += 5; // skip past all 4 offsets to avoid re-checking conflicting slots+ }+ throw new Error("Could not find available port range for Bytebase");+}++export async function startServer(): Promise<{+ baseURL: string;+ adminEmail: string;+ adminPassword: string;+}> {+ // Check both CWD-relative and repo-root-relative paths+ const candidates = [+ process.env.BYTEBASE_BIN,+ "./bytebase-build/bytebase",+ "../bytebase-build/bytebase",+ ].filter(Boolean) as string[];+ const binPath = candidates.find((p) => fs.existsSync(p));+ if (!binPath) {+ throw new Error(+ `Bytebase binary not found. Build it with:\n` ++ ` pnpm --dir frontend build\n` ++ ` go build -tags embed_frontend -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go\n` ++ `Or set BYTEBASE_BIN to the binary path.`+ );+ }++ const port = await findAvailablePort();+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "bytebase-e2e-"));++ const child = child_process.spawn(+ binPath,+ ["--port", String(port), "--data", tempDir, "--demo"],+ {+ detached: true,+ stdio: "ignore",+ env: { ...process.env, PG_URL: "" },+ }+ );++ serverProcess = child;+ child.unref();++ // Write PID file for orphan cleanup+ fs.writeFileSync(PID_FILE, `${child.pid}\n${tempDir}`);++ const baseURL = `http://localhost:${port}`;+ const timeout = parseInt(+ process.env.BYTEBASE_STARTUP_TIMEOUT ?? String(DEFAULT_TIMEOUT),+ 10+ );+ const deadline = Date.now() + timeout;++ // Phase 1: Poll /healthz+ while (Date.now() < deadline) {+ try {+ const resp = await fetch(`${baseURL}/healthz`);+ if (resp.ok) break;+ } catch {+ /* not ready */+ }+ await new Promise((r) => setTimeout(r, 500));+ }+ if (Date.now() >= deadline) {+ throw new Error(+ `Bytebase server did not become healthy within ${timeout}ms`+ );+ }++ // Phase 2: Retry login until success (demo admin is pre-populated)+ const api = new BytebaseApiClient({ baseURL });+ while (Date.now() < deadline) {+ try {+ await api.login(ADMIN_EMAIL, ADMIN_PASSWORD);+ break;+ } catch {+ /* not ready — demo data still loading */+ }+ await new Promise((r) => setTimeout(r, 500));+ }+ if (Date.now() >= deadline) {+ throw new Error(+ "Failed to login as demo admin. Server may not be fully initialized."+ );+ }++ // Reconcile sample instance data source ports.+ // The demo dump has ports from when it was captured (e.g. 8083/8084).+ // The actual sample Postgres runs on PORT+3/PORT+4.+ const sampleInstances = [+ { id: "test-sample-instance", port: String(port + 3) },+ { id: "prod-sample-instance", port: String(port + 4) },+ ];+ for (const si of sampleInstances) {+ try {+ const instance = await api.getInstance(`instances/${si.id}`);+ for (const ds of instance.dataSources ?? []) {+ if (ds.port !== si.port) {+ console.log(`Reconciling ${si.id} data source port: ${ds.port} → ${si.port}`);+ await api.updateInstanceDataSource(`instances/${si.id}`, ds.id, si.port);+ }+ }+ } catch (err) {+ console.warn(`Failed to reconcile instance ${si.id}:`, err);+ }+ }++ return { baseURL, adminEmail: ADMIN_EMAIL, adminPassword: ADMIN_PASSWORD };+}++export function stopServer(): void {+ if (serverProcess?.pid) {+ try {+ process.kill(-serverProcess.pid, "SIGTERM");+ } catch {+ /* already dead */+ }+ serverProcess = undefined;+ }+ if (tempDir && fs.existsSync(tempDir)) {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+ if (fs.existsSync(PID_FILE)) {+ fs.unlinkSync(PID_FILE);+ }+}diff --git a/frontend/tests/e2e/framework/setup-project.ts b/frontend/tests/e2e/framework/setup-project.tsnew file mode 100644index 0000000000..fcbb5f5e67--- /dev/null+++ b/frontend/tests/e2e/framework/setup-project.ts@@ -0,0 +1,77 @@+import { test as setup, expect } from "@playwright/test";+import * as fs from "fs";+import * as path from "path";+import { loadTestEnv, saveTestEnv } from "./env";++const AUTH_FILE = path.join(__dirname, "../../../.auth/state.json");++setup("authenticate and discover", async ({ page }) => {+ const env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);++ // Browser login for auth cookies+ await page.goto(`${env.baseURL}/auth/signin`);+ if (page.url().includes("/auth")) {+ const emailField = page.getByRole("textbox", { name: /email/i });+ const hasDemoLogin = await emailField.count() === 0;++ if (hasDemoLogin) {+ await page.getByRole("button", { name: "Sign in", exact: true }).click();+ } else {+ await emailField.fill(env.adminEmail);+ await page.getByRole("textbox", { name: /password/i }).fill(env.adminPassword);+ await page.getByRole("button", { name: "Sign in", exact: true }).click();+ }+ await expect(page).not.toHaveURL(/\/auth/, { timeout: 60000 });+ }++ // Dismiss modals + suppress "New version" modal+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForTimeout(500);+ await page.evaluate(() => {+ localStorage.setItem(+ "bb.release",+ JSON.stringify({+ ignoreRemindModalTillNextRelease: true,+ nextCheckTs: Date.now() + 86400000,+ })+ );+ });++ // Discovery: find first Postgres instance, database, and project+ const { instances } = await env.api.listInstances();+ const pgInstance = instances?.find(+ (i: { engine: string; name: string }) =>+ i.engine === "POSTGRES" &&+ !i.name.includes("deleted") &&+ !i.name.includes("bytebase-meta")+ );+ if (!pgInstance) {+ throw new Error("Discovery failed: no Postgres instance found");+ }++ const instance = pgInstance.name;+ const instanceId = instance.split("/").pop()!;++ const { databases } = await env.api.listDatabases(instance);+ const db = databases?.find(+ (d: { name: string }) =>+ !d.name.includes("/postgres") &&+ !d.name.includes("/template") &&+ !d.name.includes("/bbdev")+ ) ?? databases?.[0];+ if (!db) {+ throw new Error(`Discovery failed: no suitable database in ${instance}`);+ }++ const database = db.name;+ const databaseId = database.split("/").pop()!;+ const project = (db as { project?: string }).project ?? "";++ saveTestEnv({ ...env, project, instance, instanceId, database, databaseId });++ // Save browser auth state+ const authDir = path.dirname(AUTH_FILE);+ if (!fs.existsSync(authDir)) fs.mkdirSync(authDir, { recursive: true });+ await page.context().storageState({ path: AUTH_FILE });+});diff --git a/frontend/tests/e2e/masking-exemption/masking-exemption.page.ts b/frontend/tests/e2e/masking-exemption/masking-exemption.page.tsnew file mode 100644index 0000000000..a70e78d206--- /dev/null+++ b/frontend/tests/e2e/masking-exemption/masking-exemption.page.ts@@ -0,0 +1,220 @@+import { type Page, type Locator, expect } from "@playwright/test";++export class MaskingExemptionPage {+ readonly page: Page;+ private baseURL: string;++ // Navigation+ readonly grantExemptionButton: Locator;++ // Tabs+ readonly activeTab: Locator;+ readonly expiredTab: Locator;+ readonly allTab: Locator;++ // Search+ readonly searchBar: Locator;++ // Member list+ readonly memberList: Locator;++ // Detail panel+ readonly detailPanel: Locator;++ // Revoke dialog+ readonly revokeConfirmButton: Locator;+ readonly revokeCancelButton: Locator;++ constructor(page: Page, baseURL = "") {+ this.page = page;+ this.baseURL = baseURL;+ this.grantExemptionButton = page.getByRole("button", {+ name: /grant exemption/i,+ });+ this.activeTab = page.getByRole("button", { name: "Active" });+ this.expiredTab = page.getByRole("button", { name: "Expired" });+ this.allTab = page.getByRole("button", { name: "All" });+ this.searchBar = page.getByPlaceholder(/filter/i);+ this.memberList = page.locator("[class*='divide-y']").first();+ this.detailPanel = page.locator("[class*='flex-1 min-w-0']").first();+ this.revokeConfirmButton = page+ .getByRole("dialog")+ .getByRole("button", { name: "Confirm" });+ this.revokeCancelButton = page+ .getByRole("dialog")+ .getByRole("button", { name: "Cancel" });+ }++ async goto(projectId: string) {+ await this.page.goto(+ `${this.baseURL}/projects/${projectId}/masking-exemption`+ );+ // Dismiss any modal overlays (e.g., "New version available")+ await this.page.keyboard.press("Escape").catch(() => {});+ await this.page.waitForTimeout(300);+ // Wait for the page to finish loading+ await this.page+ .getByText(/exemptions|no exemptions/i)+ .first()+ .waitFor({ timeout: 10000 });+ }++ getMemberItem(email: string): Locator {+ return this.page.locator(`[class*="cursor-pointer"]`).filter({+ hasText: email,+ });+ }++ async selectMember(email: string) {+ await this.getMemberItem(email).click();+ }++ getGrantCard(title: string): Locator {+ return this.page.locator("[class*='border border-gray']").filter({+ hasText: title,+ });+ }++ getRevokeButton(grantTitle: string): Locator {+ return this.getGrantCard(grantTitle).getByRole("button", {+ name: "Revoke",+ });+ }++ async revokeGrant(grantTitle: string) {+ await this.getRevokeButton(grantTitle).click();+ await this.revokeConfirmButton.click();+ // Wait for optimistic update+ await this.page.waitForTimeout(500);+ }++ async getMemberCount(): Promise<number> {+ return this.page.locator("[class*='cursor-pointer']").filter({+ has: this.page.locator("[class*='rounded-full']"),+ }).count();+ }++ getExpiryLabel(grantTitle: string): Locator {+ return this.getGrantCard(grantTitle).locator("[class*='text-xs']").first();+ }+}++export class GrantExemptionPage {+ readonly page: Page;+ private baseURL: string;++ readonly allRadio: Locator;+ readonly expressionRadio: Locator;+ readonly selectRadio: Locator;+ readonly reasonInput: Locator;+ readonly expirationInput: Locator;+ readonly accountSelect: Locator;+ readonly confirmButton: Locator;+ readonly cancelButton: Locator;++ constructor(page: Page, baseURL = "") {+ this.page = page;+ this.baseURL = baseURL;+ this.allRadio = page.getByRole("radio", { name: "All", exact: true });+ this.expressionRadio = page.getByRole("radio", {+ name: /use cel/i,+ });+ this.selectRadio = page.getByRole("radio", {+ name: /manually select/i,+ });+ this.reasonInput = page.getByPlaceholder(/description/i);+ this.expirationInput = page.getByRole("textbox").nth(1);+ this.accountSelect = page.getByText("Select accounts", { exact: true });+ this.confirmButton = page.getByRole("button", { name: "Confirm" });+ this.cancelButton = page.getByRole("button", { name: "Cancel" });+ }++ async goto(projectId: string) {+ await this.page.goto(+ `${this.baseURL}/projects/${projectId}/masking-exemption/create`+ );+ await this.page.keyboard.press("Escape").catch(() => {});+ await this.page.waitForTimeout(300);+ await this.page+ .getByText(/grant exemption/i)+ .first()+ .waitFor({ timeout: 10000 });+ }++ async selectAccount(name: string) {+ await this.accountSelect.click();+ await this.page.getByText(name, { exact: true }).click();+ // Close dropdown+ await this.page.keyboard.press("Escape");+ }++ async submit() {+ await expect(this.confirmButton).toBeEnabled();+ await this.confirmButton.click();+ }+}++export class SqlEditorPage {+ readonly page: Page;+ private baseURL: string;+ readonly codeEditor: Locator;+ readonly runButton: Locator;++ constructor(page: Page, baseURL = "") {+ this.page = page;+ this.baseURL = baseURL;+ this.codeEditor = page.getByRole("code");+ this.runButton = page.getByRole("button", { name: /limit \d+/i });+ }++ async gotoWithDb(projectId: string, instanceId: string, dbName: string) {+ // Navigate directly to a SQL editor sheet URL with the database pre-selected.+ // This avoids stale editor state from previous navigations.+ await this.page.goto(+ `${this.baseURL}/sql-editor/projects/${projectId}/instances/${instanceId}/databases/${dbName}`+ );+ await this.page.keyboard.press("Escape").catch(() => {});+ await this.page.waitForTimeout(2000);+ }++ async runQuery(sql: string) {+ await this.page.keyboard.press("Escape").catch(() => {});+ await this.page.waitForTimeout(300);+ // Focus the editor+ await this.codeEditor.click();+ await this.page.waitForTimeout(200);+ // Select all and delete to clear editor (ControlOrMeta for cross-platform)+ await this.page.keyboard.press("ControlOrMeta+a");+ await this.page.waitForTimeout(100);+ await this.page.keyboard.press("Delete");+ await this.page.waitForTimeout(200);+ // Verify editor is empty, then type the query+ await this.page.keyboard.type(sql, { delay: 10 });+ await this.page.waitForTimeout(300);+ await this.runButton.click();+ // Wait for results to load (look for "N rows" or "N row" indicator)+ await this.page.getByText(/\d+ rows?/).first().waitFor({ timeout: 15000 }).catch(() => {});+ await this.page.waitForTimeout(500);+ }++ async hasResultsTable(): Promise<boolean> {+ // Check for the "rows" indicator that appears after query execution+ return (await this.page.getByText(/\d+ rows?/).count()) > 0;+ }++ async resultContainsText(text: string, timeout = 15000): Promise<boolean> {+ // Scope to result grid rows via [data-row-index] attribute set by+ // VirtualDataTable. This avoids matching text in the SQL editor,+ // query history, or overflow-hidden ancestor containers.+ try {+ await this.page+ .locator("[data-row-index]")+ .filter({ hasText: text })+ .first()+ .waitFor({ state: "visible", timeout });+ return true;+ } catch {+ return false;+ }+ }+}diff --git a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.tsnew file mode 100644index 0000000000..4fc7461792--- /dev/null+++ b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts@@ -0,0 +1,462 @@+import { execFileSync } from "child_process";+import { test, expect, type Page, type BrowserContext } from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import { BytebaseApiClient } from "../framework/api-client";+import { MaskingExemptionPage, GrantExemptionPage, SqlEditorPage } from "./masking-exemption.page";++// Give all tests generous timeouts (Mode B's disposable server can be slow)+test.setTimeout(120_000);++interface MaskingTestColumn {+ sampleTable: string;+ sampleSchema: string;+ sampleColumn: string;+ primaryKeyColumn: string;+ primaryKeyValue: string;+ knownUnmaskedValue: string;+}++interface MaskingTestData {+ // Column that is masked via classification level (set in demo data)+ classificationColumn: MaskingTestColumn;+ // Column that we explicitly mask via semanticType (we apply it in beforeAll)+ semanticTypeColumn: MaskingTestColumn;+}++let env: TestEnv & { api: BytebaseApiClient };+let maskingData: MaskingTestData;+// Extracted IDs for convenience — assigned once in file-level beforeAll+let projectId: string;++// Shared browser context and page — reused across ALL tests.+// Avoids browser open/close overhead and NVirtualList first-render issues.+let sharedContext: BrowserContext;+let page: Page;++// ── Feature-specific test data setup ──++// Fixed values we control: the test creates its own schema/table/rows,+// applies masking, and drops everything in teardown.+// All identifiers below must be validated by isSafeIdentifier before being+// interpolated into SQL strings passed to psql. The constants are static+// literals verified at load time; any dynamic values MUST go through the+// validator.+const TEST_SCHEMA = "e2e_masking";+const TEST_TABLE = "t";+const CLASSIFICATION_COLUMN = "col_classification";+const SEMANTIC_TYPE_COLUMN = "col_semantic";+const ROW_PK = 1;+const CLASSIFICATION_VALUE = "ClassValueABCDE";+const SEMANTIC_TYPE_VALUE = "SemValueABCDE";+const CLASSIFICATION_LEVEL = "1-2"; // matches demo classification rules++// Validate SQL identifiers/literal values. Only permits characters safe to+// inline into a SQL string without escaping: letters, digits, underscores.+// Any caller that interpolates into SQL MUST call this first.+function assertSafeSqlIdentifier(value: string, kind: string): void {+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value)) {+ throw new Error(`Unsafe SQL ${kind}: ${JSON.stringify(value)}`);+ }+}+// Validate-on-load so a typo in a constant fails fast, not at test runtime+for (const [name, value] of Object.entries({+ TEST_SCHEMA, TEST_TABLE, CLASSIFICATION_COLUMN, SEMANTIC_TYPE_COLUMN,+ CLASSIFICATION_VALUE, SEMANTIC_TYPE_VALUE,+})) {+ assertSafeSqlIdentifier(value, name);+}++// Get the Postgres port for the database's instance by reading the data source+// from the API. Avoids hardcoding offsets (PORT+3 vs PORT+4) which would break+// if discovery picks the "test" sample instance instead of "prod".+async function getInstancePgPort(env: TestEnv & { api: BytebaseApiClient }): Promise<string> {+ const instance = await env.api.getInstance(env.instance);+ const port = instance.dataSources?.[0]?.port;+ if (!port) {+ throw new Error(`Instance ${env.instance} has no data source port`);+ }+ return port;+}++// Execute SQL via psql over Unix socket on the sample Postgres instance.+// Used for DDL/DML setup and teardown — Bytebase's query API is read-only.+function execSql(dbName: string, port: string, sql: string): void {+ execFileSync("psql", [+ "-h", "/tmp",+ "-p", port,+ "-U", "bbsample",+ "-d", dbName,+ "-v", "ON_ERROR_STOP=1",+ "-c", sql,+ ], { stdio: "pipe" });+}++async function createMaskingTestData(env: TestEnv & { api: BytebaseApiClient }): Promise<MaskingTestData> {+ const dbName = env.databaseId;+ const port = await getInstancePgPort(env);++ // Drop anything leftover from a previous run, then create fresh schema/table/row.+ // All interpolated identifiers are validated constants (see assertSafeSqlIdentifier above).+ execSql(dbName, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);+ execSql(dbName, port, `CREATE SCHEMA ${TEST_SCHEMA}`);+ execSql(dbName, port, `CREATE TABLE ${TEST_SCHEMA}.${TEST_TABLE} (+ id INTEGER PRIMARY KEY,+ ${CLASSIFICATION_COLUMN} TEXT NOT NULL,+ ${SEMANTIC_TYPE_COLUMN} TEXT NOT NULL+ )`);+ execSql(dbName, port, `INSERT INTO ${TEST_SCHEMA}.${TEST_TABLE} (id, ${CLASSIFICATION_COLUMN}, ${SEMANTIC_TYPE_COLUMN})+ VALUES (${ROW_PK}, '${CLASSIFICATION_VALUE}', '${SEMANTIC_TYPE_VALUE}')`);++ // Sync the database schema so Bytebase picks up the new table.+ // Errors here are real — without sync, the catalog update will target a+ // table Bytebase doesn't know about and silently drop the configuration.+ await env.api.syncDatabase(env.database);++ // Configure catalog: classification on one column, semanticType on the other+ await env.api.updateCatalog(env.database, {+ name: `${env.database}/catalog`,+ schemas: [{+ name: TEST_SCHEMA,+ tables: [{+ name: TEST_TABLE,+ columns: {+ columns: [+ { name: CLASSIFICATION_COLUMN, classification: CLASSIFICATION_LEVEL },+ { name: SEMANTIC_TYPE_COLUMN, semanticType: "bb.default-partial" },+ ],+ },+ }],+ }],+ });++ const common = {+ sampleTable: TEST_TABLE,+ sampleSchema: TEST_SCHEMA,+ primaryKeyColumn: "id",+ primaryKeyValue: String(ROW_PK),+ };+ return {+ classificationColumn: {+ ...common,+ sampleColumn: CLASSIFICATION_COLUMN,+ knownUnmaskedValue: CLASSIFICATION_VALUE,+ },+ semanticTypeColumn: {+ ...common,+ sampleColumn: SEMANTIC_TYPE_COLUMN,+ knownUnmaskedValue: SEMANTIC_TYPE_VALUE,+ },+ };+}++async function dropMaskingTestData(env: TestEnv & { api: BytebaseApiClient }): Promise<void> {+ try {+ const port = await getInstancePgPort(env);+ execSql(env.databaseId, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);+ } catch (err) {+ // Server may have been torn down by globalTeardown before afterAll ran.+ // Surface the error so genuine cleanup failures are visible.+ console.warn(`dropMaskingTestData: ${err instanceof Error ? err.message : err}`);+ }+}++async function grantExemption(description: string, member = `user:${env.adminEmail}`): Promise<void> {+ const existing = await env.api.getPolicy(`${env.project}/policies/masking_exemption`) as {+ maskingExemptionPolicy?: { exemptions: { members: string[]; condition?: { expression: string; description: string } }[] };+ } | null;+ const exemptions = existing?.maskingExemptionPolicy?.exemptions ?? [];+ exemptions.push({+ members: [member],+ condition: { expression: "", description },+ });+ await env.api.upsertPolicy(env.project, "masking_exemption", {+ type: "MASKING_EXEMPTION",+ maskingExemptionPolicy: { exemptions },+ });+}++async function revokeAllExemptions(): Promise<void> {+ await env.api.upsertPolicy(env.project, "masking_exemption", {+ type: "MASKING_EXEMPTION",+ maskingExemptionPolicy: { exemptions: [] },+ });+}++// ── Setup/Teardown ──++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ projectId = env.project.split("/").pop()!;+ await env.api.login(env.adminEmail, env.adminPassword);++ // Create our own test schema/table/data — no dependency on demo content.+ // Applies classification to one column and semanticType to another.+ maskingData = await createMaskingTestData(env);++ // Create a shared browser context/page for all tests+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ await sharedContext?.close();+ await revokeAllExemptions().catch((err) => {+ console.warn(`afterAll revokeAllExemptions: ${err instanceof Error ? err.message : err}`);+ });+ await dropMaskingTestData(env);+});++// ── Exemption List Page ──++test.describe("Exemption List Page", () => {+ test.beforeAll(async () => {+ await grantExemption("Test grant A");+ await grantExemption("Test grant B");+ });++ test("loads and displays member list with grant details", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);++ await expect(exemptionPage.grantExemptionButton).toBeVisible();+ await expect(exemptionPage.activeTab).toBeVisible();+ await expect(exemptionPage.expiredTab).toBeVisible();+ await expect(exemptionPage.allTab).toBeVisible();+ await expect(page.getByText(env.adminEmail).first()).toBeVisible();+ });++ test("Active tab shows only active grants", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);+ await exemptionPage.activeTab.click();+ await page.waitForTimeout(500);++ await expect(page.getByText("Never expires").first()).toBeVisible();+ await expect(page.getByText("(Expired)")).toHaveCount(0);+ });++ test("selecting a member shows their grants in detail panel", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);+ await exemptionPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);++ await expect(page.getByText(/\d+ masking exemption/)).toBeVisible();+ await expect(page.getByText("Reason:").first()).toBeVisible();+ });++ test("grant card shows reason", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);+ await exemptionPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);++ await expect(page.getByText("Reason:").first()).toBeVisible();+ });++ test("clicking All tab removes Active filter and shows all data", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);++ await exemptionPage.allTab.click();+ await page.waitForTimeout(500);++ await expect(page.getByText("status: Active")).not.toBeVisible();+ await expect(page.getByText("status: Expired")).not.toBeVisible();+ });++ test("grant card has no excessive top padding", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);+ await exemptionPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);++ const grantCard = page.locator("[class*='border border-gray']").first();+ const cardBox = await grantCard.boundingBox();+ const header = grantCard.locator("> div").first();+ const headerBox = await header.boundingBox();+ if (cardBox && headerBox) {+ const topGap = headerBox.y - cardBox.y;+ expect(topGap).toBeLessThanOrEqual(12);+ }+ });+});++// ── Service Account badge ──++test.describe("Member Type Badges", () => {+ const saId = "e2e-test-sa";+ let saEmail = "";++ test.beforeAll(async () => {+ const sa = await env.api.createServiceAccount(env.project, saId, "E2E Test SA");+ saEmail = sa.email;+ await grantExemption("SA test", `serviceAccount:${saEmail}`);+ });++ test.afterAll(async () => {+ await revokeAllExemptions();+ await env.api.deleteServiceAccount(saEmail);+ });++ test("service account badge renders on single line", async () => {+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);+ await exemptionPage.allTab.click();+ await page.waitForTimeout(500);++ const badge = page.getByText("Service Account", { exact: true }).first();+ await expect(badge).toBeVisible();+ const box = await badge.boundingBox();+ expect(box).toBeTruthy();+ expect(box!.height).toBeLessThan(45);+ });+});++// ── Grant and Revoke ──++test.describe("Grant and Revoke", () => {+ test.beforeEach(async () => {+ await revokeAllExemptions();+ });++ test("grant exemption via UI and verify it appears in list", async () => {+ const grantPage = new GrantExemptionPage(page, env.baseURL);+ const listPage = new MaskingExemptionPage(page, env.baseURL);++ await grantPage.goto(projectId);+ await expect(grantPage.allRadio).toBeChecked();+ await expect(grantPage.confirmButton).toBeDisabled();++ await grantPage.reasonInput.fill("E2E test grant");+ const adminName = env.adminEmail === "[email protected]" ? "Demo" : "Admin";+ await grantPage.selectAccount(adminName);+ await expect(grantPage.confirmButton).toBeEnabled();+ await grantPage.submit();+ await page.waitForTimeout(1000);++ await listPage.goto(projectId);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);+ await expect(page.getByText("E2E test grant")).toBeVisible();+ });++ test("revoke exemption via UI and verify it disappears", async () => {+ const listPage = new MaskingExemptionPage(page, env.baseURL);++ await grantExemption("To be revoked");++ await listPage.goto(projectId);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);+ await expect(page.getByText("To be revoked")).toBeVisible();++ const revokeBtn = page.getByRole("button", { name: "Revoke" }).first();+ await revokeBtn.click();+ await expect(page.getByRole("dialog")).toBeVisible();+ await page.getByRole("dialog").getByRole("button", { name: "Confirm" }).click();+ await page.waitForTimeout(500);++ await expect(page.getByText("To be revoked")).not.toBeVisible();+ });++ test("revoke confirmation can be cancelled", async () => {+ const listPage = new MaskingExemptionPage(page, env.baseURL);++ await grantExemption("Should survive cancel");++ await listPage.goto(projectId);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);++ await page.getByRole("button", { name: "Revoke" }).first().click();+ await expect(page.getByRole("dialog")).toBeVisible();+ await page.getByRole("dialog").getByRole("button", { name: "Cancel" }).click();+ await expect(page.getByRole("dialog")).not.toBeVisible();+ await expect(page.getByText("Should survive cancel")).toBeVisible();+ });+});++// ── E2E Masking Verification ──++test.describe("E2E Masking Verification", () => {+ // Shared cycle test: masked → grant via UI → unmasked → revoke via UI → masked.+ // Parameterized by which column (classification-masked vs semantic-type-masked).+ const runMaskingCycle = async (target: MaskingTestColumn, reason: string) => {+ const sqlEditor = new SqlEditorPage(page, env.baseURL);+ const grantPage = new GrantExemptionPage(page, env.baseURL);+ const listPage = new MaskingExemptionPage(page, env.baseURL);+ const sql = `SELECT "${target.sampleColumn}" FROM "${target.sampleSchema}"."${target.sampleTable}" WHERE "${target.primaryKeyColumn}" = '${target.primaryKeyValue}';`;+ const adminName = env.adminEmail === "[email protected]" ? "Demo" : "Admin";++ // Step 1: No exemption → data is masked+ await revokeAllExemptions();+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await sqlEditor.runQuery(sql);+ expect(await sqlEditor.resultContainsText(target.knownUnmaskedValue)).toBe(false);++ // Step 2: Grant exemption via UI → data becomes unmasked+ await grantPage.goto(projectId);+ await grantPage.reasonInput.fill(reason);+ await grantPage.selectAccount(adminName);+ await grantPage.submit();+ await page.waitForTimeout(1000);++ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await sqlEditor.runQuery(sql);+ expect(await sqlEditor.resultContainsText(target.knownUnmaskedValue)).toBe(true);++ // Step 3: Revoke exemption via UI → data becomes masked again+ await listPage.goto(projectId);+ await listPage.selectMember(env.adminEmail);+ await page.waitForTimeout(500);+ await page.getByRole("button", { name: "Revoke" }).first().click();+ await page.getByRole("dialog").getByRole("button", { name: "Confirm" }).click();+ await page.waitForTimeout(500);++ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await sqlEditor.runQuery(sql);+ expect(await sqlEditor.resultContainsText(target.knownUnmaskedValue)).toBe(false);+ };++ test("classification-based masking: cycle via UI", async () => {+ await runMaskingCycle(maskingData.classificationColumn, "e2e classification masking test");+ });++ test("semantic-type-based masking: cycle via UI", async () => {+ await runMaskingCycle(maskingData.semanticTypeColumn, "e2e semantic type masking test");+ });+});++// ── Responsive Layout ──++test.describe("Responsive Layout", () => {+ test.beforeAll(async () => {+ await grantExemption("Layout test grant");+ });++ test.afterAll(async () => {+ // Reset viewport so subsequent tests (if any) aren't stuck at mobile size+ await page.setViewportSize({ width: 1280, height: 720 });+ });++ test("wide screen shows split-panel layout", async () => {+ await page.setViewportSize({ width: 1440, height: 900 });+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);++ await expect(page.getByText(/\d+ masking exemption/).first()).toBeVisible();+ await expect(page.getByText("Reason:").first()).toBeVisible();+ });++ test("narrow screen shows expandable list", async () => {+ await page.setViewportSize({ width: 768, height: 1024 });+ const exemptionPage = new MaskingExemptionPage(page, env.baseURL);+ await exemptionPage.goto(projectId);++ await expect(page.getByText(env.adminEmail).first()).toBeVisible();+ await page.getByText(env.adminEmail).first().click();+ await page.waitForTimeout(300);+ await expect(page.getByText("Reason:").first()).toBeVisible();+ });+});diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex a1151d72ef..41614068ba 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -8,7 +8,7 @@ export default mergeConfig(test: {globals: true,environment: "jsdom",- exclude: [...configDefaults.exclude, "e2e/*"],+ exclude: [...configDefaults.exclude, "e2e/*", "tests/e2e/**"],root: fileURLToPath(new URL("./", import.meta.url)),},})