继续复审前保存初始化安全校验与链路测试检查点

This commit is contained in:
xuans committed 2026-09-16 20:06:36 +08:00
1 parent 199d727ecc
commit c6bfcfd9ae
15 files changed
+676 -23

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@
"version": "0.1.0",
"type": "module",
"scripts": {
"test": "node --test src/views/SetupWizard/SetupWizard.test.js src/views/Dashboard/Dashboard.test.js",
"test": "node --test src/App.test.js src/views/SetupWizard/SetupWizard.test.js src/views/SetupWizard/DatabaseSetup.test.js src/views/SetupWizard/BootstrapPayload.test.js src/views/Dashboard/Dashboard.test.js",
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
+7 -1
View File
@@ -71,7 +71,13 @@ export function useAppShell() {
function handleInitialized(result) {
if (result?.completed && result?.management_url) {
const destination = new URL(result.management_url);
let destination;
try {
destination = new URL(result.management_url);
} catch {
error.value = "正式管理地址无效,请检查服务器配置。";
return;
}
if (destination.protocol !== "https:" || destination.username || destination.password) {
error.value = "正式管理地址无效,请检查服务器配置。";
return;
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { useAppShell } from "./App.js";
import { mountComposable } from "./test-support/mount.js";
test("初始化令牌兑换前清除地址片段,后续请求只用同源会话", async (t) => {
const calls = [];
const { state } = await mountComposable(t, () => {
window.location.hash = "#token=test-bootstrap-token";
window.history.replaceState = (_, __, url) => calls.push({ replace: url });
return useAppShell();
}, async (path, options) => {
calls.push({ path, options });
if (path.endsWith("/status")) return Response.json({ mode: "bootstrap" });
if (path.endsWith("/session")) return Response.json({ authenticated: true });
return Response.json({ mode: "bootstrap", initialized: false });
});
assert.equal(state.error.value, "");
assert.equal(state.setupState.value.mode, "bootstrap");
assert.equal(calls[1].replace, "/");
assert.equal(calls[2].path, "/api/v1/bootstrap/session");
assert.equal(calls[2].options.credentials, "same-origin");
assert.deepEqual(JSON.parse(calls[2].options.body), { token: "test-bootstrap-token" });
assert.equal(calls[3].path, "/api/v1/bootstrap/settings");
});
test("没有令牌和有效会话时不暴露初始化表单", async (t) => {
const { state } = await mountComposable(t, useAppShell, async (path) => path.endsWith("/status")
? Response.json({ mode: "bootstrap" }) : new Response(null, { status: 401 }));
assert.equal(state.setupState.value, null);
assert.match(state.error.value, /完整一次性地址/);
});
test("正式服务回退状态接口并检查登录态", async (t) => {
const calls = [];
const { state } = await mountComposable(t, useAppShell, async (path) => {
calls.push(path);
if (path.includes("bootstrap")) return new Response(null, { status: 404 });
if (path.includes("setup")) return Response.json({ initialized: true });
return new Response(null, { status: 401 });
});
assert.deepEqual(calls, ["/api/v1/bootstrap/status", "/api/v1/setup/status", "/api/v1/auth/session"]);
assert.equal(state.authenticated.value, false);
});
test("完成跳转拒绝畸形地址、非 HTTPS 和带密码地址", async (t) => {
const { state } = await mountComposable(t, () => {
window.location.pathname = "/login";
return useAppShell();
}, () => { throw new Error("不应发送请求"); });
for (const address of ["invalid", "http://example.test", "https://owner:password@example.test"]) {
assert.doesNotThrow(() => state.handleInitialized({ completed: true, management_url: address }));
assert.match(state.error.value, /正式管理地址无效/);
}
let destination;
window.setTimeout = (callback) => callback();
window.location.assign = (url) => { destination = url; };
state.handleInitialized({ completed: true, management_url: "https://127.0.0.1:8443/" });
assert.equal(destination, "https://127.0.0.1:8443/");
});
+4 -1
View File
@@ -43,7 +43,10 @@ export async function mountComposable(t, factory, fetcher) {
clearInterval(intervalID) {
intervals.delete(intervalID);
},
location: { assign() {} },
location: { pathname: "/", search: "", hash: "", assign() {} },
history: { replaceState() {} },
setTimeout,
clearTimeout,
},
document: { body: { style: { overflow: "" } } },
})) {
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import test from "node:test";
import { bootstrapPayload } from "./BootstrapPayload.js";
test("初始化只提交服务端验证令牌,通知字段保持兼容且不带凭据引用", () => {
const payload = bootstrapPayload({
admin_username: "owner", dns_verification_token: "test-dns-token",
dns_credential_ref: "secret://untrusted/dns", certificate_root: "/untrusted",
email_http_enabled: true, email_http_credential_ref: "secret://untrusted/mail",
email_http_credentials: { token: "test-notification-token" },
email_smtp_password: "test-notification-password", email_retry_count: 0,
recipients: ["owner@example.test"],
}, "test-database-token", "staging");
assert.equal(payload.database_verification_token, "test-database-token");
assert.equal(payload.dns_verification_token, "test-dns-token");
assert.equal(payload.acme_environment, "staging");
assert.equal("certificate_root" in payload, false);
assert.equal("dns_credential_ref" in payload, false);
assert.equal("http_credential_ref" in payload.notification, false);
assert.deepEqual(payload.notification.http_credentials, { token: "test-notification-token" });
assert.equal(payload.notification.smtp_password, "test-notification-password");
assert.equal(payload.notification.retry_count, 0);
assert.deepEqual(payload.notification.recipients, ["owner@example.test"]);
});
@@ -0,0 +1,88 @@
.database-setup {
display: grid;
gap: 12px;
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #e4ebf5;
color: #32405a;
font-size: 12px;
}
.setup-section-heading {
display: grid;
gap: 5px;
}
.setup-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
label {
display: grid;
gap: 6px;
min-width: 0;
}
input,
select {
box-sizing: border-box;
width: 100%;
min-width: 0;
min-height: 38px;
padding: 8px 10px;
border: 1px solid #d5deeb;
border-radius: 8px;
background: #fff;
color: #172033;
font: inherit;
}
.dns-test-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
button {
padding: 9px 14px;
border: 1px solid #315faa;
border-radius: 8px;
background: #315faa;
color: #fff;
font: inherit;
cursor: pointer;
}
button:disabled {
opacity: 0.65;
cursor: wait;
}
input:focus-visible,
select:focus-visible,
button:focus-visible {
outline: 2px solid #315faa;
outline-offset: 2px;
}
p {
margin: 0;
line-height: 1.6;
}
.inline-error {
color: #b42318;
}
[role="status"] {
color: #26754f;
}
@media (max-width: 760px) {
.setup-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@@ -1,7 +1,15 @@
import { computed, onUnmounted, ref, watch } from "vue";
export function useDatabaseSetup(clock) {
const databaseForm = ref({ driver: "sqlite", host: "", port: 3306, database: "scert", username: "", password: "", root_certificate: "" });
const databaseForm = ref({
driver: "sqlite",
host: "",
port: 3306,
database: "scert",
username: "",
password: "",
root_certificate: "",
});
const databaseTesting = ref(false);
const databaseError = ref("");
const databaseVerification = ref(null);
@@ -38,7 +46,8 @@ export function useDatabaseSetup(clock) {
});
const result = await response.json().catch(() => ({}));
if (current !== version) return;
if (!response.ok || !result.verified || !result.verification_token) {
if (!response.ok || result.verified !== true || !result.verification_token ||
result.driver !== payload.driver || !(new Date(result.expires_at).getTime() > Date.now())) {
throw new Error(result.error || "数据库连接和写权限验证失败。");
}
databaseVerification.value = result;
@@ -0,0 +1,96 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ref } from "vue";
import { useDatabaseSetup } from "./DatabaseSetup.js";
import { deferred, mountComposable } from "../../test-support/mount.js";
function verified(driver = "sqlite", token = "test-database-token") {
return Response.json({
driver,
verified: true,
verification_token: token,
expires_at: new Date(Date.now() + 60000).toISOString(),
});
}
for (const driver of ["sqlite", "mysql", "postgres"]) {
test(`数据库 ${driver} 使用结构化参数与严格 TLS`, async (t) => {
const requests = [];
const { state } = await mountComposable(t, () => useDatabaseSetup(ref(Date.now())), async (path, options) => {
requests.push({ path, payload: JSON.parse(options.body), credentials: options.credentials });
return verified(driver);
});
state.databaseForm.value.driver = driver;
Object.assign(state.databaseForm.value, {
host: "db.example.test", username: "test-user", password: "test-password",
});
await state.testDatabase();
assert.equal(state.databaseVerified.value, true);
assert.equal(requests[0].path, "/api/v1/bootstrap/database/test");
assert.equal(requests[0].credentials, "same-origin");
if (driver === "sqlite") {
assert.deepEqual(requests[0].payload, { driver: "sqlite" });
} else {
assert.equal(requests[0].payload.port, driver === "mysql" ? 3306 : 5432);
assert.equal(requests[0].payload.tls_mode, driver === "mysql" ? "true" : "verify-full");
}
});
}
test("数据库输入变化立即作废令牌并忽略旧响应", async (t) => {
const pending = deferred();
const { state } = await mountComposable(t, () => useDatabaseSetup(ref(Date.now())), () => pending.promise);
const task = state.testDatabase();
state.databaseForm.value.password = "changed-test-password";
pending.resolve(verified());
await task;
assert.equal(state.databaseVerified.value, false);
assert.equal(state.databaseVerification.value, null);
assert.equal(state.databaseTesting.value, false);
});
test("数据库旧失败不覆盖新成功,卸载后不接受在途结果", async (t) => {
const first = deferred();
const second = deferred();
const third = deferred();
const pending = [first, second, third];
const { state, unmount } = await mountComposable(t, () => useDatabaseSetup(ref(Date.now())), () => pending.shift().promise);
const oldTask = state.testDatabase();
const newTask = state.testDatabase();
second.resolve(verified());
await newTask;
first.reject(new Error("旧请求失败"));
await oldTask;
assert.equal(state.databaseVerified.value, true);
assert.equal(state.databaseError.value, "");
const closingTask = state.testDatabase();
unmount();
third.resolve(verified());
await closingTask;
assert.equal(state.databaseVerification.value, null);
});
test("数据库令牌到期后不可继续提交", async (t) => {
const clock = ref(Date.now());
const { state, advanceTime } = await mountComposable(t, () => useDatabaseSetup(clock), () => verified());
await state.testDatabase();
assert.equal(state.databaseVerified.value, true);
advanceTime(60001);
clock.value = Date.now();
assert.equal(state.databaseVerified.value, false);
});
test("拒绝数据库类型不匹配、非法有效期与畸形响应", async (t) => {
const responses = [
() => verified("mysql"),
() => Response.json({ verified: true, driver: "sqlite", verification_token: "test", expires_at: "invalid" }),
() => Response.json({ verified: "true", driver: "sqlite", verification_token: "test" }),
() => new Response("not-json", { status: 502 }),
];
const { state } = await mountComposable(t, () => useDatabaseSetup(ref(Date.now())), () => responses.shift()());
for (let index = 0; index < 4; index += 1) {
await state.testDatabase();
assert.equal(state.databaseVerified.value, false);
assert.notEqual(state.databaseError.value, "");
}
});
@@ -24,11 +24,26 @@ const emit = defineEmits(["test"]);
</select>
</label>
<template v-if="form.driver !== 'sqlite'">
<label><span>数据库主机</span><input v-model.trim="form.host" autocomplete="off" placeholder="db.example.com" /></label>
<label><span>数据库端口</span><input v-model.number="form.port" type="number" min="1" max="65535" /></label>
<label><span>数据库名称</span><input v-model.trim="form.database" autocomplete="off" /></label>
<label><span>数据库用户名</span><input v-model.trim="form.username" autocomplete="off" /></label>
<label><span>数据库密码</span><input v-model="form.password" type="password" autocomplete="new-password" /></label>
<label>
<span>数据库主机</span>
<input v-model.trim="form.host" autocomplete="off" placeholder="db.example.com" />
</label>
<label>
<span>数据库端口</span>
<input v-model.number="form.port" type="number" min="1" max="65535" />
</label>
<label>
<span>数据库名称</span>
<input v-model.trim="form.database" autocomplete="off" />
</label>
<label>
<span>数据库用户名</span>
<input v-model.trim="form.username" autocomplete="off" />
</label>
<label>
<span>数据库密码</span>
<input v-model="form.password" type="password" autocomplete="new-password" />
</label>
<label v-if="form.driver === 'postgres'">
<span>根证书路径(服务器绝对路径,可选)</span>
<input v-model.trim="form.root_certificate" placeholder="使用系统信任库时留空" />
@@ -45,3 +60,5 @@ const emit = defineEmits(["test"]);
<p v-if="error" class="inline-error" role="alert">{{ error }}</p>
</section>
</template>
<style scoped src="./DatabaseSetup.css"></style>