mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-04 08:47:45 +08:00
fix(api): require access codes and limit sizes on helper routes
- Shared checkAccessCode for validate-diagram, validate-model, parse-url, verify-access-code - parse-url: 5 MB streamed body limit; validate-diagram: 5 MB image limit - validate-model refuses redirects when private URLs are blocked - Admin settings state shared across module instances via globalThis - Server model ids: unique slugs (non-ASCII names encoded), duplicates rejected - Panel Bedrock credentials stored as ADMIN_AWS_* so the DynamoDB client keeps its own - Locale redirect keeps basePath and query; EdgeOne function drops open CORS and checks the access code - Providers payload reports whether .env sets a default model
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
// @vitest-environment node
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest"
|
||||
import { GET, PUT } from "@/app/api/admin/providers/route"
|
||||
import { _resetForTests } from "@/lib/admin/settings"
|
||||
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "admin-providers-route-"))
|
||||
process.env.SETTINGS_FILE = path.join(tmpDir, "settings.json")
|
||||
process.env.ADMIN_PASSWORD = "pw"
|
||||
process.env.AI_MODELS_CONFIG_PATH = path.join(tmpDir, "none.json")
|
||||
_resetForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
_resetForTests()
|
||||
delete process.env.SETTINGS_FILE
|
||||
delete process.env.ADMIN_PASSWORD
|
||||
delete process.env.AI_MODELS_CONFIG_PATH
|
||||
delete process.env.AI_MODEL
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const headers = { "x-admin-password": "pw" }
|
||||
|
||||
async function saveDefaultPanelProvider() {
|
||||
const res = await PUT(
|
||||
new Request("http://localhost/api/admin/providers", {
|
||||
method: "PUT",
|
||||
headers: { ...headers, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
providers: [
|
||||
{
|
||||
id: "p1",
|
||||
provider: "openai",
|
||||
apiKey: "sk-test",
|
||||
models: ["gpt-panel"],
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
}
|
||||
|
||||
async function envHasDefaultModel(): Promise<boolean> {
|
||||
const res = await GET(
|
||||
new Request("http://localhost/api/admin/providers", { headers }),
|
||||
)
|
||||
return (await res.json()).envHasDefaultModel
|
||||
}
|
||||
|
||||
describe("envHasDefaultModel", () => {
|
||||
it("is true when .env sets AI_MODEL, even after a panel default", async () => {
|
||||
process.env.AI_MODEL = "gpt-env"
|
||||
expect(await envHasDefaultModel()).toBe(true)
|
||||
await saveDefaultPanelProvider()
|
||||
expect(await envHasDefaultModel()).toBe(true)
|
||||
})
|
||||
|
||||
it("ignores the AI_MODEL the panel default writes", async () => {
|
||||
await saveDefaultPanelProvider()
|
||||
expect(process.env.AI_MODEL).toBe("gpt-panel")
|
||||
expect(await envHasDefaultModel()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -69,7 +69,7 @@ describe("deriveEnvUpdates", () => {
|
||||
expect(updates.ADMIN_OPENAI_API_KEY_2).toBe("sk-second")
|
||||
})
|
||||
|
||||
it("maps bedrock credentials to AWS env vars", () => {
|
||||
it("maps bedrock credentials to ADMIN_AWS_* env vars", () => {
|
||||
const updates = deriveEnvUpdates(
|
||||
[
|
||||
provider({
|
||||
@@ -83,9 +83,26 @@ describe("deriveEnvUpdates", () => {
|
||||
],
|
||||
[],
|
||||
)
|
||||
expect(updates.AWS_ACCESS_KEY_ID).toBe("AKIA123")
|
||||
expect(updates.AWS_SECRET_ACCESS_KEY).toBe("secret")
|
||||
expect(updates.AWS_REGION).toBe("us-west-2")
|
||||
expect(updates.ADMIN_AWS_ACCESS_KEY_ID).toBe("AKIA123")
|
||||
expect(updates.ADMIN_AWS_SECRET_ACCESS_KEY).toBe("secret")
|
||||
expect(updates.ADMIN_AWS_REGION).toBe("us-west-2")
|
||||
// Standard AWS vars are left to the environment
|
||||
expect(updates.AWS_ACCESS_KEY_ID).toBeUndefined()
|
||||
})
|
||||
|
||||
it("clears AWS_* bedrock keys written by older versions", () => {
|
||||
const bedrock = provider({
|
||||
provider: "bedrock",
|
||||
apiKey: undefined,
|
||||
awsAccessKeyId: "AKIA123",
|
||||
awsSecretAccessKey: "secret",
|
||||
models: ["claude-x"],
|
||||
})
|
||||
const updates = deriveEnvUpdates([bedrock], [bedrock])
|
||||
expect(updates.AWS_ACCESS_KEY_ID).toBeNull()
|
||||
expect(updates.AWS_SECRET_ACCESS_KEY).toBeNull()
|
||||
expect(updates.AWS_REGION).toBeNull()
|
||||
expect(updates.ADMIN_AWS_ACCESS_KEY_ID).toBe("AKIA123")
|
||||
})
|
||||
|
||||
it("clears keys owned by the previous list when providers are removed", () => {
|
||||
@@ -315,6 +332,32 @@ describe("validateAdminProviders", () => {
|
||||
expect(validateAdminProviders(list)).toMatch(/unique/)
|
||||
})
|
||||
|
||||
it("rejects names that differ only in case or punctuation", () => {
|
||||
const list = [
|
||||
provider({ id: "p1", name: "Open AI" }),
|
||||
provider({ id: "p2", name: "open-ai" }),
|
||||
]
|
||||
expect(validateAdminProviders(list)).toMatch(/unique/)
|
||||
})
|
||||
|
||||
it("rejects a case-only clash with an env-configured name", () => {
|
||||
expect(
|
||||
validateAdminProviders([provider({ name: "openai" })], {
|
||||
providers: [
|
||||
{ name: "OpenAI", provider: "openai", models: ["gpt-x"] },
|
||||
],
|
||||
}),
|
||||
).toMatch(/already defined/)
|
||||
})
|
||||
|
||||
it("accepts distinct CJK names", () => {
|
||||
const list = [
|
||||
provider({ id: "p1", provider: "deepseek", name: "主力" }),
|
||||
provider({ id: "p2", provider: "deepseek", name: "备用" }),
|
||||
]
|
||||
expect(validateAdminProviders(list)).toBeNull()
|
||||
})
|
||||
|
||||
it("rejects multiple defaults", () => {
|
||||
const list = [
|
||||
provider({ id: "p1", isDefault: true }),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest"
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
||||
import {
|
||||
_resetForTests,
|
||||
applyToEnv,
|
||||
@@ -100,6 +100,24 @@ describe("applyToEnv / saveSettings", () => {
|
||||
expect(process.env.TEST_ADMIN_VAR).toBeUndefined()
|
||||
})
|
||||
|
||||
it("a second module instance can remove a key the first one overlaid", async () => {
|
||||
// instrumentation.ts and API routes load separate copies in a build
|
||||
process.env.TEST_ADMIN_VAR = "from-env"
|
||||
fs.writeFileSync(
|
||||
process.env.SETTINGS_FILE!,
|
||||
JSON.stringify({ version: 1, values: { TEST_ADMIN_VAR: "abc" } }),
|
||||
)
|
||||
applyToEnv()
|
||||
expect(process.env.TEST_ADMIN_VAR).toBe("abc")
|
||||
|
||||
vi.resetModules()
|
||||
const second = await import("@/lib/admin/settings")
|
||||
expect(second.getValueSource("TEST_ADMIN_VAR")).toBe("file")
|
||||
second.saveSettings({ TEST_ADMIN_VAR: null })
|
||||
expect(process.env.TEST_ADMIN_VAR).toBe("from-env")
|
||||
expect(second.getEnvFallback("TEST_ADMIN_VAR")).toBe("from-env")
|
||||
})
|
||||
|
||||
it("persists across cache reset (file round-trip)", () => {
|
||||
saveSettings({ TEST_ADMIN_VAR: "persisted" })
|
||||
_resetForTests()
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// @vitest-environment node
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
||||
import { POST as parseUrl } from "@/app/api/parse-url/route"
|
||||
import { POST as validateDiagram } from "@/app/api/validate-diagram/route"
|
||||
import { POST as validateModel } from "@/app/api/validate-model/route"
|
||||
import { POST as verifyAccessCode } from "@/app/api/verify-access-code/route"
|
||||
import { checkAccessCode } from "@/lib/access-code"
|
||||
|
||||
// Treat every URL as public so no test hits DNS
|
||||
vi.mock("@/lib/ssrf-protection", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/ssrf-protection")>()),
|
||||
isPrivateUrl: async () => false,
|
||||
}))
|
||||
|
||||
function post(path: string, body: unknown, accessCode?: string): Request {
|
||||
return new Request(`http://localhost${path}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(accessCode ? { "x-access-code": accessCode } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.ACCESS_CODE_LIST = "secret, other"
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.ACCESS_CODE_LIST
|
||||
delete process.env.ALLOW_PRIVATE_URLS
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe("checkAccessCode", () => {
|
||||
it("passes when no access codes are configured", () => {
|
||||
delete process.env.ACCESS_CODE_LIST
|
||||
expect(checkAccessCode(post("/x", {}))).toBeNull()
|
||||
})
|
||||
|
||||
it("rejects a missing or wrong code and accepts a listed one", () => {
|
||||
expect(checkAccessCode(post("/x", {}))?.status).toBe(401)
|
||||
expect(checkAccessCode(post("/x", {}, "nope"))?.status).toBe(401)
|
||||
expect(checkAccessCode(post("/x", {}, "other"))).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe("routes that spend server resources require the access code", () => {
|
||||
it("parse-url", async () => {
|
||||
const res = await parseUrl(
|
||||
post("/api/parse-url", { url: "https://example.com" }),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it("validate-diagram", async () => {
|
||||
const res = await validateDiagram(
|
||||
post("/api/validate-diagram", {
|
||||
imageData: "data:image/png;base64,AAAA",
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it("validate-model", async () => {
|
||||
const res = await validateModel(
|
||||
post("/api/validate-model", {
|
||||
provider: "openai",
|
||||
apiKey: "sk",
|
||||
modelId: "m",
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it("verify-access-code", async () => {
|
||||
const bad = await verifyAccessCode(post("/api/verify-access-code", {}))
|
||||
expect(bad.status).toBe(401)
|
||||
expect((await bad.json()).valid).toBe(false)
|
||||
|
||||
const good = await verifyAccessCode(
|
||||
post("/api/verify-access-code", {}, "secret"),
|
||||
)
|
||||
expect((await good.json()).valid).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("size limits", () => {
|
||||
it("parse-url stops reading a body over the download limit", async () => {
|
||||
const chunk = new Uint8Array(1024 * 1024)
|
||||
let sent = 0
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
sent++
|
||||
controller.enqueue(chunk)
|
||||
},
|
||||
})
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(body, {
|
||||
headers: { "content-type": "text/html" },
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const res = await parseUrl(
|
||||
post("/api/parse-url", { url: "https://example.com" }, "secret"),
|
||||
)
|
||||
expect(res.status).toBe(413)
|
||||
expect(sent).toBeLessThan(10)
|
||||
})
|
||||
|
||||
it("validate-diagram rejects oversized image data", async () => {
|
||||
const imageData = `data:image/png;base64,${"A".repeat(6 * 1024 * 1024)}`
|
||||
const res = await validateDiagram(
|
||||
post("/api/validate-diagram", { imageData }, "secret"),
|
||||
)
|
||||
expect(res.status).toBe(413)
|
||||
})
|
||||
})
|
||||
|
||||
describe("validate-model redirects", () => {
|
||||
it("refuses redirects when private URLs are blocked", async () => {
|
||||
process.env.ALLOW_PRIVATE_URLS = "false"
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "http://169.254.169.254/" },
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const res = await validateModel(
|
||||
post(
|
||||
"/api/validate-model",
|
||||
{
|
||||
provider: "openai",
|
||||
apiKey: "sk",
|
||||
modelId: "m",
|
||||
baseUrl: "https://attacker.example/v1",
|
||||
},
|
||||
"secret",
|
||||
),
|
||||
)
|
||||
const data = await res.json()
|
||||
expect(data.valid).toBe(false)
|
||||
expect(data.error).toMatch(/Redirects are not allowed/)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest"
|
||||
import { onRequest } from "@/edge-functions/api/edgeai/chat/completions"
|
||||
|
||||
function request(headers: Record<string, string>): Request {
|
||||
return new Request("http://localhost/api/edgeai/chat/completions", {
|
||||
method: "POST",
|
||||
headers,
|
||||
// Non-streaming requests return a mock reply without calling AI
|
||||
body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }),
|
||||
})
|
||||
}
|
||||
|
||||
const json = { "Content-Type": "application/json" }
|
||||
|
||||
describe("EdgeOne chat completions function", () => {
|
||||
it("sends no CORS headers", async () => {
|
||||
const res = await onRequest({ request: request(json), env: {} })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get("access-control-allow-origin")).toBeNull()
|
||||
})
|
||||
|
||||
it("rejects non-JSON requests", async () => {
|
||||
const res = await onRequest({
|
||||
request: request({ "Content-Type": "text/plain" }),
|
||||
env: {},
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it("checks the access code when ACCESS_CODE_LIST is set", async () => {
|
||||
const env = { ACCESS_CODE_LIST: "secret" }
|
||||
const missing = await onRequest({ request: request(json), env })
|
||||
expect(missing.status).toBe(401)
|
||||
|
||||
const ok = await onRequest({
|
||||
request: request({ ...json, "x-access-code": "secret" }),
|
||||
env,
|
||||
})
|
||||
expect(ok.status).toBe(200)
|
||||
})
|
||||
|
||||
it("lets requests through when env is unavailable", async () => {
|
||||
const res = await onRequest({ request: request(json) })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
loadFlattenedServerModels,
|
||||
type ServerModelsConfig,
|
||||
ServerModelsConfigSchema,
|
||||
slugify,
|
||||
} from "@/lib/server-model-config"
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env }
|
||||
@@ -233,3 +234,50 @@ describe("loadFlattenedServerModels", () => {
|
||||
expect(models[0].apiKeyEnv).toEqual(["OPENAI_KEY_1", "OPENAI_KEY_2"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("slugify", () => {
|
||||
it("keeps ASCII names readable", () => {
|
||||
expect(slugify("OpenAI Production")).toBe("openai-production")
|
||||
})
|
||||
|
||||
it("gives distinct ASCII slugs to distinct CJK names", () => {
|
||||
const slugs = ["主力", "备用", "DeepSeek 官方", "DeepSeek 备用"].map(
|
||||
slugify,
|
||||
)
|
||||
expect(new Set(slugs).size).toBe(4)
|
||||
for (const slug of slugs) expect(slug).toMatch(/^[a-z0-9-]+$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("loadFlattenedServerModels id collisions", () => {
|
||||
it("drops a model whose id repeats an earlier provider's", async () => {
|
||||
const config: ServerModelsConfig = {
|
||||
providers: [
|
||||
{ name: "OpenAI", provider: "openai", models: ["gpt-4o"] },
|
||||
{
|
||||
name: "openai",
|
||||
provider: "openai",
|
||||
models: ["gpt-4o"],
|
||||
apiKeyEnv: "OTHER_KEY",
|
||||
},
|
||||
{
|
||||
name: "主力",
|
||||
provider: "deepseek",
|
||||
models: ["deepseek-chat"],
|
||||
},
|
||||
{
|
||||
name: "备用",
|
||||
provider: "deepseek",
|
||||
models: ["deepseek-chat"],
|
||||
},
|
||||
],
|
||||
}
|
||||
process.env.AI_MODELS_CONFIG = JSON.stringify(config)
|
||||
|
||||
const models = await loadFlattenedServerModels()
|
||||
const ids = models.map((m) => m.id)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(ids).toHaveLength(3)
|
||||
expect(models[0].apiKeyEnv).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user