From 1931bf322ab3a30a632455dfeaa283f551346026 Mon Sep 17 00:00:00 2001
From: Sycun <165354365+Sycun@users.noreply.github.com>
Date: Tue, 3 Nov 2026 00:08:19 +0800
Subject: [PATCH] fix(assessment): use authenticated transport for workbench
requests
---
scripts/assessment-browser-smoke.mjs | 26 +++++++++++++++++++++++---
web/static/js/assessments.js | 5 +++--
2 files changed, 26 insertions(+), 5 deletions(-)
diff --git a/scripts/assessment-browser-smoke.mjs b/scripts/assessment-browser-smoke.mjs
index 73725f89..7c0d5d24 100644
--- a/scripts/assessment-browser-smoke.mjs
+++ b/scripts/assessment-browser-smoke.mjs
@@ -12,6 +12,9 @@ const out = await fs.mkdtemp(path.join(os.tmpdir(), 'csai-assessment-browser-'))
const labels = JSON.parse(await fs.readFile('web/static/i18n/zh-CN.json', 'utf8')).assessments;
const now = () => new Date().toISOString();
let sequence = 0;
+const authenticatedPaths = new Set();
+let unauthorizedRequests = 0;
+const fixtureSession = { token: 'assessment-fixture-session', expires_at: new Date(Date.now()+3600000).toISOString(), user: {id:'fixture-user',username:'fixture'}, roles:['admin'], scope:'all', permissions:['assessment:read','assessment:write','assessment:delete','agent:execute','hitl:write','project:read','project:write','asset:write','vulnerability:write','skills:read'] };
const task = { id: 'fixture-assessment', name: '本地测评 · 浏览器验证', goal: '核验本地隔离测试数据', scope: '仅使用浏览器测试夹具,无外部目标', material: '已提供两个测试端点', strategy: '先核验响应,再检查访问控制边界', model: 'fixture', tools: ['inspect'], approval_mode: 'manual', concurrency: 2, token_budget: 200000, tokens: 1250, reserved_tokens: 0, remaining_seconds: 7200, deadline: 0, rounds: 2, max_rounds: 12, status: 'paused', reason: 'user_paused', summary: '已记录响应证据,下一步检查访问控制。', project_id: 'fixture-project', created_at: now(), updated_at: now(), steps: [
{ id: 's1', key: 'inspect', title: '检查响应和服务信息', instruction: '读取测试夹具并记录响应。', depends_on: [], status: 'completed', result: '响应证据已记录。', checkpoint: '服务响应已保存,后续可复用。', evidence: [{ kind: 'fact', title: '已记录测试响应', detail: '本地测试数据返回固定响应。', execution_ids: ['fixture-execution-1'] }] },
{ id: 's2', key: 'access', title: '核验访问控制边界', instruction: '对照测试夹具中的两个角色。', depends_on: ['inspect'], status: 'blocked', result: '等待补充测试角色。', evidence: [{ kind: 'finding', title: '待复核访问控制线索', detail: '仅为合成数据,需在授权环境中复核。', execution_ids: ['fixture-execution-2'] }] }
@@ -25,7 +28,7 @@ const server = http.createServer(async (req, res) => {
try {
if (url.pathname === '/') {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
- res.end(``); return;
+ res.end(`
`); return;
}
if (url.pathname.startsWith('/static/')) {
const p = path.resolve(repo, 'web', '.' + url.pathname); if (!p.startsWith(path.join(repo, 'web', 'static') + path.sep)) throw Error('invalid path');
@@ -33,6 +36,13 @@ const server = http.createServer(async (req, res) => {
}
let body = ''; for await (const chunk of req) body += chunk;
const input = body ? JSON.parse(body) : {};
+ if (url.pathname === '/api/auth/login') { send(fixtureSession); return; }
+ if (url.pathname.startsWith('/api/')) {
+ if (req.headers.authorization !== 'Bearer ' + fixtureSession.token) { unauthorizedRequests++; res.statusCode=401; send({error:'未授权访问,请先登录'}); return; }
+ authenticatedPaths.add(url.pathname);
+ }
+ if (url.pathname === '/api/auth/validate') {send(fixtureSession);return;}
+ if (url.pathname.endsWith('/report')) {res.setHeader('Content-Type','text/markdown');res.end('# Fixture assessment report');return;}
if (url.pathname === '/api/assessments/options') { send({ models: [{ id: 'fixture', name: 'Fixture', model: 'local-test' }], tools: [{ name: 'inspect', description: 'Inspect local fixture' }], projects: [{id:'fixture-project',name:'本地测试项目'}] }); return; }
if (url.pathname === '/api/assessments' && req.method === 'POST') {
const created = { ...task, ...input, id: 'created-' + (++sequence), status: 'draft', steps: [], tokens: 0, rounds: 0, created_at: now(), updated_at: now() }; tasks.unshift(created); send({ assessment: created }); return;
@@ -74,7 +84,11 @@ try {
const screenshot = async name => { const shot = await cdp('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); await fs.writeFile(path.join(out, name + '.png'), Buffer.from(shot.data, 'base64')); };
await cdp('Runtime.enable');
await cdp('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false });
- await cdp('Page.navigate', { url: 'http://127.0.0.1:' + port }); await waitFor("!!document.querySelector('[data-id=fixture-assessment]')");
+ await cdp('Page.setDownloadBehavior', {behavior:'allow',downloadPath:out});
+ await cdp('Page.navigate', { url: 'http://127.0.0.1:' + port });
+ await waitFor("!!document.getElementById('login-form') && typeof submitLogin === 'function'");
+ await evaluate("document.getElementById('login-password').value='fixture-password';document.getElementById('login-form').requestSubmit()");
+ await waitFor("!!document.querySelector('[data-id=fixture-assessment]')");
await click('[data-id=fixture-assessment]'); await waitFor("!!document.getElementById('assessment-guidance')");
await evaluate("document.getElementById('assessment-guidance').value='preserve unsaved guidance'"); await delay(3000);
assert.equal(await evaluate("document.getElementById('assessment-guidance').value"), 'preserve unsaved guidance', 'poll erased typed guidance');
@@ -98,8 +112,14 @@ try {
await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await click('[data-tab=plan]'); await evaluate("document.getElementById('assessment-tab').scrollIntoView()"); await screenshot('mobile-plan');
assert.ok(await evaluate('document.documentElement.scrollWidth <= window.innerWidth + 1'), 'mobile horizontal overflow');
+ await click('[data-assessment-action=report]');
+ for(let i=0;i<100&&!authenticatedPaths.has('/api/assessments/fixture-assessment/report');i++) await delay(50);
+ await click('[data-assessment-action=metrics]');
+ for(let i=0;i<100&&!authenticatedPaths.has('/api/assessments/fixture-assessment/metrics');i++) await delay(50);
+ assert.equal(unauthorizedRequests,0,'a logged-in workbench request omitted its Bearer token');
+ for(const route of ['/api/assessments','/api/assessments/options','/api/assessments/fixture-assessment/report','/api/assessments/fixture-assessment/metrics']) assert.ok(authenticatedPaths.has(route),'missing authenticated request: '+route);
await evaluate('cleanupAssessmentsPage()');
- console.log(JSON.stringify({ ok: true, screenshots: out, checks: ['task selection', 'poll preserves draft', 'graph', 'candidate publishing controls', 'XSS escaping', 'create', 'start', 'approval', 'completion', 'mobile overflow'] }, null, 2));
+ console.log(JSON.stringify({ ok: true, screenshots: out, checks: ['real auth.js login and Bearer propagation', 'authenticated create/options/control/downloads', 'task selection', 'poll preserves draft', 'graph', 'candidate publishing controls', 'XSS escaping', 'create', 'start', 'approval', 'completion', 'mobile overflow'] }, null, 2));
} finally {
if (socket) socket.close(); chrome.kill(); server.close();
}
diff --git a/web/static/js/assessments.js b/web/static/js/assessments.js
index f8c1cd67..92c4ddce 100644
--- a/web/static/js/assessments.js
+++ b/web/static/js/assessments.js
@@ -10,7 +10,7 @@
const badge = (s) => '' + esc(tr('status.' + s)) + '';
const button = (action, text, permission, attrs) => '';
async function api(path, method, body) {
- const response = await fetch('/api/assessments' + path, { method: method || 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const response = await apiFetch('/api/assessments' + path, { method: method || 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || response.statusText);
return data;
@@ -109,6 +109,7 @@
const field = document.getElementById('assessment-guidance'); if (field && value) field.value = value;
}
} else detail();
+ if (document.getElementById('assessment-message')?.classList.contains('is-error')) message('', false);
} catch (err) { if (version === epoch) message(err.message, true); }
finally { loading = false; }
}
@@ -160,7 +161,7 @@
else if (action === 'delete') { if (!window.confirm(tr('deleteConfirm'))) return; await api('/' + id, 'DELETE'); selected = ''; history.replaceState(null, '', '#assessments'); task = null; events = []; after = 0; }
else if (action === 'fact' || action === 'vulnerability' || action === 'asset') { await api('/' + id + '/publish', 'POST', { step_id: target.dataset.step, index: Number(target.dataset.index), kind: action, revision: target.dataset.revision }); message(tr('published')); }
else if (action === 'report' || action === 'metrics') {
- const response = await fetch('/api/assessments/' + id + '/' + action, { credentials: 'same-origin' }); if (!response.ok) throw new Error(response.statusText);
+ const response = await apiFetch('/api/assessments/' + id + '/' + action, { credentials: 'same-origin' }); if (!response.ok) throw new Error(response.statusText);
const url = URL.createObjectURL(await response.blob()); const link = document.createElement('a'); link.href = url; link.download = 'assessment-' + id + (action === 'metrics' ? '-metrics.json' : '.md'); link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
await refresh(true);