Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 9 additions & 17 deletions .github/scripts/ensure-cloudflare-resources.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const API_BASE_URL = "https://api.cloudflare.com/client/v4";

const LEGACY_D1_DATABASE_NAME = "cfchat-db";
const LEGACY_KV_NAMESPACE_TITLE = "cfchat-sessions";
const PRODUCTION_KV_NAMESPACE_TITLE = "SESSIONS";
const LEGACY_R2_BUCKET_NAME = "cfchat-files";
const R2_NOT_ENABLED_ERROR_CODE = 10042;

Expand All @@ -32,17 +31,13 @@ function readEnv(env, ...names) {
}

function resourceNames(env) {
const explicitKvNamespaceTitle = readEnv(
env,
"EDGECHAT_KV_NAMESPACE_TITLE",
"CFCHAT_KV_NAMESPACE_TITLE",
);
return {
d1DatabaseName:
readEnv(env, "EDGECHAT_D1_DATABASE_NAME", "CFCHAT_D1_DATABASE_NAME") ??
LEGACY_D1_DATABASE_NAME,
kvNamespaceTitle: explicitKvNamespaceTitle ?? LEGACY_KV_NAMESPACE_TITLE,
kvNamespaceTitleExplicit: Boolean(explicitKvNamespaceTitle),
kvNamespaceTitle:
readEnv(env, "EDGECHAT_KV_NAMESPACE_TITLE", "CFCHAT_KV_NAMESPACE_TITLE") ??
LEGACY_KV_NAMESPACE_TITLE,
r2BucketName:
readEnv(env, "EDGECHAT_R2_BUCKET_NAME", "CFCHAT_R2_BUCKET_NAME") ??
LEGACY_R2_BUCKET_NAME,
Expand Down Expand Up @@ -264,17 +259,14 @@ async function ensureD1Database(context, d1DatabaseName) {
return { id, created: true };
}

async function ensureKvNamespace(
export async function ensureKvNamespace(
context,
{ kvNamespaceTitle, kvNamespaceTitleExplicit },
kvNamespaceTitle = LEGACY_KV_NAMESPACE_TITLE,
) {
const namespaces = await listKvNamespaces(context);
const candidateTitles = kvNamespaceTitleExplicit
? [kvNamespaceTitle]
: [PRODUCTION_KV_NAMESPACE_TITLE, LEGACY_KV_NAMESPACE_TITLE];
const existing = candidateTitles
.map((title) => namespaces.find((namespace) => namespace.title === title && namespace.id))
.find(Boolean);
const existing = namespaces.find(
(namespace) => namespace.title === kvNamespaceTitle && namespace.id,
);
if (existing) {
console.log(`KV namespace already exists: ${existing.title} (${existing.id})`);
return { id: existing.id, title: existing.title, created: false };
Expand Down Expand Up @@ -330,7 +322,7 @@ export async function ensureCloudflareResources({
);

const d1 = await ensureD1Database(context, names.d1DatabaseName);
const kv = await ensureKvNamespace(context, names);
const kv = await ensureKvNamespace(context, names.kvNamespaceTitle);
const r2 = await ensureR2Bucket(context, names.r2BucketName);

setOutput("d1_database_name", names.d1DatabaseName);
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/deploy-worker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ jobs:
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
EDGECHAT_KV_NAMESPACE_TITLE: ${{ vars.EDGECHAT_KV_NAMESPACE_TITLE || 'cfchat-sessions' }}
run: node .github/scripts/ensure-cloudflare-resources.mjs
- name: Generate wrangler config for CI
shell: bash
Expand Down
12 changes: 9 additions & 3 deletions test/deploy-workflow-security.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,24 @@ test("首次部署自动创建密钥,普通部署保留密钥,手动轮换
assert.match(deployStep, /wrangler deploy --config wrangler\.ci\.toml/);
});

test("资源确认脚本优先复用生产 SESSIONS KV 且保留显式标题覆盖", () => {
test("资源确认脚本仅复用配置的 KV 标题,避免隐式共享会话存储", () => {
const script = readFileSync(
new URL("../.github/scripts/ensure-cloudflare-resources.mjs", import.meta.url),
"utf8",
).replaceAll("\r\n", "\n");

assert.match(script, /const PRODUCTION_KV_NAMESPACE_TITLE = "SESSIONS";/);
assert.doesNotMatch(script, /PRODUCTION_KV_NAMESPACE_TITLE/);
assert.match(
script,
/kvNamespaceTitleExplicit\s*\? \[kvNamespaceTitle\]\s*:\s*\[PRODUCTION_KV_NAMESPACE_TITLE, LEGACY_KV_NAMESPACE_TITLE\]/s,
/namespace\.title === kvNamespaceTitle && namespace\.id/,
);
assert.match(script, /setOutput\("kv_namespace_title", kv\.title\);/);

const resourceStep = getStep("Ensure Cloudflare resources");
assert.match(
resourceStep,
/EDGECHAT_KV_NAMESPACE_TITLE: \$\{\{ vars\.EDGECHAT_KV_NAMESPACE_TITLE \|\| 'cfchat-sessions' \}\}/,
);
});

test("R2 未开通时工作流移除 FILES binding,已开通时保留目标 bucket", () => {
Expand Down
66 changes: 65 additions & 1 deletion test/ensure-cloudflare-resources.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ensureR2Bucket } from "../.github/scripts/ensure-cloudflare-resources.mjs";
import {
ensureKvNamespace,
ensureR2Bucket,
} from "../.github/scripts/ensure-cloudflare-resources.mjs";

function jsonResponse(payload, status = 200) {
return new Response(JSON.stringify(payload), {
Expand All @@ -9,6 +12,67 @@ function jsonResponse(payload, status = 200) {
});
}

test("KV only reuses the explicitly selected namespace title", async () => {
const requests = [];
const result = await ensureKvNamespace(
{
accountId: "account",
apiToken: "token",
async fetchImpl(url, init) {
requests.push({ url: String(url), method: init.method });
return jsonResponse({
success: true,
result: [
{ id: "generic-id", title: "SESSIONS" },
{ id: "target-id", title: "edgechat-production-sessions" },
],
});
},
},
"edgechat-production-sessions",
);

assert.deepEqual(result, {
id: "target-id",
title: "edgechat-production-sessions",
created: false,
});
assert.deepEqual(requests.map((request) => request.method), ["GET"]);
});

test("KV defaults to the isolated legacy title instead of generic SESSIONS", async () => {
const requests = [];
const responses = [
jsonResponse({
success: true,
result: [{ id: "generic-id", title: "SESSIONS" }],
}),
jsonResponse({ success: true, result: { id: "created-id" } }),
];
const result = await ensureKvNamespace({
accountId: "account",
apiToken: "token",
async fetchImpl(url, init) {
requests.push({
url: String(url),
method: init.method,
body: init.body,
});
return responses.shift();
},
});

assert.deepEqual(result, {
id: "created-id",
title: "cfchat-sessions",
created: true,
});
assert.deepEqual(requests.map((request) => request.method), ["GET", "POST"]);
assert.deepEqual(JSON.parse(requests[1].body), {
title: "cfchat-sessions",
});
});

test("R2 error 10042 disables attachment storage without failing deployment", async () => {
const requests = [];
const result = await ensureR2Bucket({
Expand Down
Loading