You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/AdminTemplateStartupScriptB...

170 lines
7.9 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const source = (await readFile(new URL('../public/cloud/admin.js', import.meta.url), 'utf8'))
.replace('void initialize();', '')
+ '\n;globalThis.__scripts = { startupScriptState, openStartupScript, closeStartupScript, saveStartupScript, loadCatalog };\n';
class Element {
constructor() {
this.value = ''; this.textContent = ''; this.children = []; this.dataset = {};
this.disabled = false; this.readOnly = false; this.open = false; this.isConnected = true;
this.listeners = new Map(); this.attributes = new Map();
}
append(...items) { this.children.push(...items); }
replaceChildren(...items) { this.children = items; }
addEventListener(name, listener) { this.listeners.set(name, listener); }
setAttribute(name, value) { this.attributes.set(name, value); }
showModal() { this.open = true; }
close() { this.open = false; }
focus() { this.focused = true; }
}
const flush = async () => { for (let n = 0; n < 20; n += 1) await Promise.resolve(); };
const entry = { id: '1234567890abcdef', name: '<img src=x onerror=alert(1)>', created_at: 1234 };
const payload = { startup_script: '#!/bin/bash\necho ready\n', created_at: 1234, revision: 2 };
const submit = { preventDefault() {} };
function fixture(canManage = true, rescue = false) {
const elements = new Map();
const get = id => { if (!elements.has(id)) elements.set(id, new Element()); return elements.get(id); };
const root = new Element();
root.dataset = { canManage: canManage ? '1' : '0', cloudAdmin: rescue ? 'rescue' : 'templates' };
const requests = [];
const context = {
document: { getElementById: get, querySelector: () => root, createElement: () => new Element() },
window: { ADMIN_CSRF_TOKEN: 'test-token' }, location: { protocol: 'https:', hostname: 'panel.test' },
Headers, TextEncoder,
fetch(path, options) {
return new Promise((resolve, reject) => requests.push({ path, ...options, resolve, reject }));
},
};
vm.runInNewContext(source, context, { filename: 'admin.js' });
return {
...context.__scripts, get, requests,
async respond(request, data, status = 200) {
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => data });
await flush();
},
};
}
// The catalog has a dedicated settings button, and opening it renders a
// literal image label while reads are pending; no script goes into HTML.
{
const h = fixture();
const loading = h.loadCatalog();
await h.respond(h.requests[0], { templates: [entry] });
await loading;
const button = h.get('catalog-list').children[0].children.find(item => item.textContent === '设置启动脚本');
assert.ok(button);
const opening = button.listeners.get('click')();
assert.equal(h.get('template-startup-dialog').open, true);
assert.equal(h.get('template-startup-title').textContent, `启动脚本 · ${entry.name}`);
assert.equal(h.get('template-startup-save').disabled, true);
await h.saveStartupScript(submit);
assert.equal(h.requests.length, 2, 'A loading dialog cannot submit a blank overwrite');
await h.respond(h.requests[1], payload);
await opening;
assert.equal(h.get('template-startup-script').value, payload.startup_script);
assert.equal(h.get('template-startup-save').disabled, false);
h.get('template-startup-script').value = '#!/bin/bash\r\necho "中文"\r\n';
const saving = h.saveStartupScript(submit);
const request = h.requests[2];
assert.equal(request.method, 'PATCH');
assert.equal(request.headers.get('X-CSRF-Token'), 'test-token');
assert.deepEqual(JSON.parse(request.body), {
script: '#!/bin/bash\necho "中文"\n', expected_revision: 2, created_at: 1234,
});
assert.equal(h.get('template-startup-script').readOnly, true);
h.closeStartupScript();
await h.openStartupScript({ ...entry, id: 'fedcba0987654321' }, new Element());
await h.saveStartupScript(submit);
assert.equal(h.get('template-startup-dialog').open, true);
assert.equal(h.requests.length, 3, 'Saving cannot switch images or duplicate a request');
await h.respond(request, { ...payload, startup_script: '#!/bin/bash\necho "中文"\n', revision: 3 });
await saving;
assert.equal(h.startupScriptState.revision, 3);
assert.equal(h.get('template-startup-close').disabled, false);
h.closeStartupScript();
assert.equal(h.get('template-startup-script').value, '', 'Closing must clear script contents');
assert.equal(button.focused, true);
}
// Closed dialogs and older image responses cannot overwrite the active image.
for (const error of [false, true]) {
const h = fixture();
const first = h.openStartupScript(entry, new Element());
h.closeStartupScript();
const second = h.openStartupScript({ ...entry, id: 'fedcba0987654321', created_at: 1235 }, new Element());
await h.respond(h.requests[0], error ? { detail: 'old read failed' } : payload, error ? 502 : 200);
await first;
assert.equal(h.get('template-startup-script').value, '');
assert.equal(h.get('template-startup-save').disabled, true);
assert.notEqual(h.get('template-startup-status').textContent, 'old read failed');
await h.respond(h.requests[1], { ...payload, created_at: 1235, startup_script: 'echo second' });
await second;
assert.equal(h.get('template-startup-script').value, 'echo second');
}
// A deleted/reimported image with the same ID cannot silently receive settings
// from a stale catalog, and an unsuccessful read cannot enable a save.
for (const result of [{ ...payload, created_at: 1235 }, { detail: 'read failed' }]) {
const h = fixture();
const opening = h.openStartupScript(entry, new Element());
await h.respond(h.requests[0], result, result.detail ? 502 : 200);
await opening;
await h.saveStartupScript(submit);
assert.equal(h.requests.length, 1);
assert.equal(h.get('template-startup-save').disabled, true);
}
// A read-only administrator can view the script but never issue a PATCH.
{
const h = fixture(false);
const opening = h.openStartupScript(entry, new Element());
await h.respond(h.requests[0], payload);
await opening;
assert.equal(h.get('template-startup-script').readOnly, true);
assert.equal(h.get('template-startup-save').disabled, true);
await h.saveStartupScript(submit);
assert.equal(h.requests.length, 1);
}
// Validate UTF-8 byte length, preserve a conflict draft, and accept clearing.
{
const h = fixture();
const opening = h.openStartupScript(entry, new Element());
await h.respond(h.requests[0], payload);
await opening;
for (const invalid of ['中'.repeat(10923), 'echo\0bad']) {
h.get('template-startup-script').value = invalid;
await h.saveStartupScript(submit);
assert.equal(h.requests.length, 1);
}
h.get('template-startup-script').value = 'echo my draft';
const conflict = h.saveStartupScript(submit);
await h.respond(h.requests[1], { detail: '初始化脚本已被修改,请重新打开对话框' }, 409);
await conflict;
assert.equal(h.get('template-startup-script').value, 'echo my draft');
assert.equal(h.startupScriptState.revision, 2, 'A conflict cannot invent a new revision');
assert.match(h.get('template-startup-status').textContent, /已被修改/);
assert.equal(h.get('template-startup-close').disabled, false);
h.get('template-startup-script').value = ' \n';
const whitespace = h.saveStartupScript(submit);
await h.respond(h.requests[2], { ...payload, startup_script: ' \n', revision: 3 });
await whitespace;
assert.match(h.get('template-startup-status').textContent, /已保存/, 'Only an empty script disables startup execution');
h.get('template-startup-script').value = '';
const clearing = h.saveStartupScript(submit);
assert.equal(JSON.parse(h.requests[3].body).script, '');
await h.respond(h.requests[3], { ...payload, startup_script: '', revision: 4 });
await clearing;
assert.match(h.get('template-startup-status').textContent, /停用/);
}
console.log('Admin startup-script dialog permissions, CAS, stale reads and validation passed.');