Files
story/test/e2e/visual-family-recording-privacy-controls.mjs
T

146 lines
11 KiB
JavaScript

import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const require = createRequire(process.env.PLAYWRIGHT_REQUIRE_FROM ?? import.meta.url);
const { chromium } = require("playwright");
const outputDirectory = new URL("./screenshots/", import.meta.url);
const webURL = process.env.VISUAL_WEB_URL ?? "http://localhost:3100";
const webHostPattern = new RegExp(new URL(webURL).host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const oidcURLPattern = new RegExp(process.env.VISUAL_OIDC_URL_PATTERN ?? "localhost:58180");
const username = process.env.VISUAL_USERNAME ?? "owner";
const password = process.env.VISUAL_PASSWORD ?? "LocalOnly123!";
const contextID = randomUUID();
const contextPublicID = randomUUID();
const conversationID = randomUUID();
const conversationPublicID = randomUUID();
const grantID = randomUUID();
const grantPublicID = randomUUID();
const grantPurpose = `页面录音撤销夹具-${grantPublicID.slice(0, 8)}`;
const subjectID = "10000000-0000-0000-0000-000000000411";
await mkdir(outputDirectory, { recursive: true });
function psql(statement) {
return execFileSync("docker", ["compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "voice", "-d", "voice_platform", "-Atc", statement], {
cwd: process.cwd(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"]
}).trim();
}
function cleanup() {
psql(`BEGIN;
DELETE FROM recording_access_grant WHERE id='${grantID}'::uuid;
DELETE FROM conversation_state_history WHERE conversation_id='${conversationID}'::uuid;
DELETE FROM conversation WHERE id='${conversationID}'::uuid;
DELETE FROM context_snapshot WHERE id='${contextID}'::uuid;
COMMIT;`);
}
psql(`BEGIN;
INSERT INTO context_snapshot(id,public_id,tenant_id,subject_id,profile_version,consent_snapshot_id,memory_versions,prompt_bundle_version,engine_mode,content_digest,sanitized_summary,preparation_status)
VALUES('${contextID}'::uuid,'${contextPublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'10000000-0000-0000-0000-000000000401'::uuid,1,'10000000-0000-0000-0000-000000000701'::uuid,'[]'::jsonb,'visual-recording-control-v1','s2s_hybrid',repeat('0',64),'浏览器录音授权撤销夹具','READY');
INSERT INTO conversation(id,public_id,tenant_id,household_id,subject_id,device_id,consent_snapshot_id,context_snapshot_id,provider_task_ref,engine_mode,retention_mode,status,allocation_expires_at,started_at,ended_at,stop_reason)
VALUES('${conversationID}'::uuid,'${conversationPublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'10000000-0000-0000-0000-000000000201'::uuid,'10000000-0000-0000-0000-000000000401'::uuid,'10000000-0000-0000-0000-000000000501'::uuid,'10000000-0000-0000-0000-000000000701'::uuid,'${contextID}'::uuid,'visual-recording-control-${conversationPublicID}','s2s_hybrid','transcript_and_audio','COMPLETED',now()+interval '5 minutes',now()-interval '3 minutes',now()-interval '2 minutes','user_hangup');
INSERT INTO conversation_state_history(conversation_id,from_status,to_status,reason,source,occurred_at)
VALUES('${conversationID}'::uuid,NULL,'ROOM_ISSUED','visual fixture','platform',now()-interval '3 minutes'),('${conversationID}'::uuid,'ROOM_ISSUED','ACTIVE','visual fixture','provider',now()-interval '170 seconds'),('${conversationID}'::uuid,'ACTIVE','COMPLETED','visual fixture','device',now()-interval '2 minutes');
INSERT INTO recording_access_grant(id,public_id,tenant_id,subject_id,grantee_user_id,permission,purpose,granted_by,granted_at,expires_at)
VALUES('${grantID}'::uuid,'${grantPublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,'10000000-0000-0000-0000-000000000401'::uuid,'10000000-0000-0000-0000-000000000102'::uuid,'DOWNLOAD','${grantPurpose}','10000000-0000-0000-0000-000000000101'::uuid,now()-interval '10 minutes',now()+interval '2 hours');
COMMIT;`);
const privacyCountBefore = Number(psql(`SELECT count(*) FROM privacy_request WHERE subject_id='10000000-0000-0000-0000-000000000401'::uuid;`));
const exportCountBefore = Number(psql(`SELECT count(*) FROM export_task WHERE subject_id='10000000-0000-0000-0000-000000000401'::uuid;`));
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH ?? "C:/Program Files/Google/Chrome/Application/chrome.exe" });
const page = await browser.newPage({ viewport: { width: 1440, height: 1050 }, deviceScaleFactor: 1 });
const consoleErrors = [];
const failedRequests = [];
const mutations = [];
let expectedMediaRestriction = false;
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
page.on("response", (response) => {
const responseURL = new URL(response.url());
if (response.status() === 403 && /^\/api\/v1\/conversations\/[^/]+\/media$/.test(responseURL.pathname)) expectedMediaRestriction = true;
});
page.on("request", (request) => {
if (request.method() === "POST" && (/\/api\/v1\/recording-access-grants\/[^/]+\/revoke$/.test(request.url()) || /\/api\/v1\/subjects\/[^/]+\/(privacy-requests|exports)$/.test(request.url()))) mutations.push(`${request.method()} ${request.url()}`);
});
page.on("requestfailed", (request) => {
const failure = request.failure()?.errorText ?? "failed";
const requestURL = new URL(request.url());
if (request.method() === "GET" && requestURL.pathname === "/api/v1/events" && failure.includes("ERR_ABORTED")) return;
failedRequests.push(`${request.method()} ${request.url()} ${failure}`);
});
try {
await page.goto(webURL, { waitUntil: "networkidle" });
await page.getByRole("button", { name: "登录研发环境" }).click();
await page.waitForURL(oidcURLPattern);
await page.locator("#username").fill(username);
await page.locator("#password").fill(password);
await page.locator("#kc-login").click();
await page.waitForURL(webHostPattern, { timeout: 15000 });
await page.getByRole("heading", { name: "家庭业务工作台" }).waitFor();
await page.getByRole("button", { name: "通话记录", exact: true }).click();
const conversationRow = page.locator(".conversation-row").filter({ hasText: "端到端混合" }).first();
await conversationRow.waitFor();
await conversationRow.click();
const recordingBlock = page.locator(".recording-block");
await recordingBlock.waitFor();
const grantRow = page.locator(".recording-grants article").filter({ hasText: grantPurpose });
try { await grantRow.waitFor({ timeout: 10000 }); }
catch { throw new Error(`Recording grant fixture not visible. Recording block: ${await recordingBlock.innerText()}`); }
await grantRow.getByRole("button", { name: "立即撤销" }).click();
let form = page.getByRole("form", { name: "家庭业务受控操作" });
await form.waitFor();
let text = await form.textContent();
const recordingTargetBound = text?.includes(grantPublicID) === true && text?.includes("本地编辑者") === true && text?.includes("下载权限") === true && text?.includes(grantPurpose) === true && text?.includes(subjectID) === true;
let action = form.getByRole("button", { name: "确认撤销录音授权" });
const recordingNeedsAcknowledgement = await action.isDisabled();
await form.getByLabel(/我确认后续不会再为该成员签发新的录音播放或下载地址/).check();
const recordingEnabled = await action.isEnabled();
await form.getByRole("button", { name: "取消" }).click();
const recordingCancelClosed = await form.count() === 0;
await page.getByRole("button", { name: "隐私请求" }).click();
await page.getByRole("button", { name: "提交全量盘点" }).click();
form = page.getByRole("form", { name: "家庭业务受控操作" });
await form.waitFor();
text = await form.textContent();
const accessTargetBound = text?.includes(subjectID) === true && text?.includes("共8类") === true && text?.includes("长者档案、授权记录、设备绑定、通话、话轮、摘要、故事、记忆") === true && text?.includes("不包含个人正文") === true;
action = form.getByRole("button", { name: "确认提交盘点" });
const accessNeedsAcknowledgement = await action.isDisabled();
await form.getByLabel(/我确认盘点范围包含当前长者的八类数据/).check();
const accessEnabled = await action.isEnabled();
await form.getByRole("button", { name: "取消" }).click();
const accessCancelClosed = await form.count() === 0;
await page.getByRole("button", { name: "生成私有导出" }).click();
form = page.getByRole("form", { name: "家庭业务受控操作" });
await form.waitFor();
text = await form.textContent();
const exportTargetBound = text?.includes(subjectID) === true && text?.includes("共8类") === true && text?.includes("包含个人正文的私有JSON文件") === true && text?.includes("短期下载地址") === true;
action = form.getByRole("button", { name: "确认生成私有导出" });
const exportNeedsAcknowledgement = await action.isDisabled();
await form.getByLabel(/我确认导出文件将包含当前长者八类数据中的私密正文/).check();
const exportEnabled = await action.isEnabled();
await form.screenshot({ path: fileURLToPath(new URL("family-privacy-export-control.png", outputDirectory)) });
await form.getByRole("button", { name: "取消" }).click();
const exportCancelClosed = await form.count() === 0;
const grantUnchanged = psql(`SELECT (revoked_at IS NULL)::text FROM recording_access_grant WHERE id='${grantID}'::uuid;`) === "true";
const privacyRequestsUnchanged = Number(psql(`SELECT count(*) FROM privacy_request WHERE subject_id='10000000-0000-0000-0000-000000000401'::uuid;`)) === privacyCountBefore;
const exportsUnchanged = Number(psql(`SELECT count(*) FROM export_task WHERE subject_id='10000000-0000-0000-0000-000000000401'::uuid;`)) === exportCountBefore;
const unexpectedConsoleErrors = consoleErrors.filter((message) => !(expectedMediaRestriction && message.includes("Failed to load resource") && message.includes("403")));
const overflow = await page.evaluate(() => [...document.querySelectorAll("body *")]
.filter((element) => element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 2 && getComputedStyle(element).overflowX === "visible")
.slice(0, 20)
.map((element) => `${element.tagName}.${element.className}: ${element.clientWidth}/${element.scrollWidth}`));
const result = { recordingTargetBound, recordingNeedsAcknowledgement, recordingEnabled, recordingCancelClosed, accessTargetBound, accessNeedsAcknowledgement, accessEnabled, accessCancelClosed, exportTargetBound, exportNeedsAcknowledgement, exportEnabled, exportCancelClosed, grantUnchanged, privacyRequestsUnchanged, exportsUnchanged, expectedMediaRestriction, mutations, overflow, unexpectedConsoleErrors, failedRequests };
console.log(JSON.stringify(result, null, 2));
if (Object.entries(result).some(([key, value]) => !["mutations", "overflow", "unexpectedConsoleErrors", "failedRequests"].includes(key) && value !== true) || mutations.length || overflow.length || unexpectedConsoleErrors.length || failedRequests.length) throw new Error("Family recording and privacy controls visual smoke failed");
} finally {
await browser.close();
cleanup();
}