fix(security,config): enforce 0600 file permissions, dynamic account store path, and HTTP origin protection
This commit is contained in:
1 parent
bd585db889
commit
d0af46b445
5 files changed
+143
-19
No files matched your search
@@ -10,6 +10,14 @@ export const ACCOUNT_CACHE_PATH = join(
|
||||
"accounts.json"
|
||||
);
|
||||
|
||||
export function resolveAccountCachePath(): string {
|
||||
const envFile = process.env.HOSE_ACCOUNTS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "accounts.json");
|
||||
return ACCOUNT_CACHE_PATH;
|
||||
}
|
||||
|
||||
export const AccountCorporationMetaSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
@@ -48,8 +56,9 @@ function ensureDir(path: string): void {
|
||||
}
|
||||
|
||||
export function loadAccountStore(): AccountStore {
|
||||
const filePath = resolveAccountCachePath();
|
||||
try {
|
||||
const content = readFileSync(ACCOUNT_CACHE_PATH, "utf-8");
|
||||
const content = readFileSync(filePath, "utf-8");
|
||||
return AccountStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return { accounts: {} };
|
||||
@@ -57,8 +66,15 @@ export function loadAccountStore(): AccountStore {
|
||||
}
|
||||
|
||||
export function saveAccountStore(store: AccountStore): void {
|
||||
ensureDir(ACCOUNT_CACHE_PATH);
|
||||
writeFileSync(ACCOUNT_CACHE_PATH, JSON.stringify(store, null, 2), "utf-8");
|
||||
const filePath = resolveAccountCachePath();
|
||||
ensureDir(filePath);
|
||||
writeFileSync(filePath, JSON.stringify(store, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function saveAccount(entry: AccountEntry): void {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
syncLegacyEnterprisesDir,
|
||||
syncLegacyGlobalConfig,
|
||||
} from "./loader.js";
|
||||
import { saveAccount, loadAccountStore, resolveAccountCachePath } from "../auth/account-store.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
|
||||
describe("core/config/loader", () => {
|
||||
@@ -213,4 +214,30 @@ describe("core/config/loader", () => {
|
||||
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("saveCorpConfig and saveAccount enforce 0o600 file permissions and respect HOSE_ACCOUNTS_FILE", () => {
|
||||
const targetDir = join(tempDir, "secure-corps");
|
||||
const corpFile = saveCorpConfig(createMockCorp("sec-1", "安全测试企业"), targetDir);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(corpFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
|
||||
const customAccountsFile = join(tempDir, "secure-accounts", "accounts.json");
|
||||
process.env.HOSE_ACCOUNTS_FILE = customAccountsFile;
|
||||
expect(resolveAccountCachePath()).toBe(customAccountsFile);
|
||||
|
||||
saveAccount({
|
||||
accountId: "86-13800138000",
|
||||
cloudAuthToken: "secret-cloud-token",
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
corporations: [],
|
||||
});
|
||||
|
||||
expect(existsSync(customAccountsFile)).toBe(true);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(customAccountsFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
expect(loadAccountStore().accounts["86-13800138000"]?.cloudAuthToken).toBe("secret-cloud-token");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
@@ -17,7 +17,18 @@ export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "c
|
||||
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function writeSecureFile(filePath: string, content: string): void {
|
||||
ensureDir(dirname(filePath));
|
||||
writeFileSync(filePath, content, { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function resolveEnterprisesDirs(): string[] {
|
||||
@@ -165,8 +176,7 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
ensureDir(dirname(targetFile));
|
||||
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
||||
writeSecureFile(targetFile, JSON.stringify(updated, null, 2));
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -230,7 +240,7 @@ export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
writeSecureFile(filePath, JSON.stringify(validated, null, 2));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
|
||||
+51
-4
@@ -7,13 +7,44 @@ import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
|
||||
export function isTrustedOrigin(originHeader: string | undefined): boolean {
|
||||
if (!originHeader) return true; // non-browser / same-origin requests without Origin header
|
||||
const allowedOriginEnv = process.env.HOSE_HTTP_CORS_ORIGIN?.trim();
|
||||
if (allowedOriginEnv === "*") return true;
|
||||
if (allowedOriginEnv && originHeader === allowedOriginEnv) return true;
|
||||
try {
|
||||
const parsed = new URL(originHeader);
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function checkHttpAuth(req: IncomingMessage): boolean {
|
||||
const requiredToken = process.env.HOSE_HTTP_TOKEN?.trim();
|
||||
if (!requiredToken) return true;
|
||||
const authHeader = req.headers.authorization || "";
|
||||
return authHeader === `Bearer ${requiredToken}`;
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
// 1. CORS headers
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
|
||||
const trustedOrigin = isTrustedOrigin(origin);
|
||||
|
||||
// 1. CORS headers: only grant CORS to local/trusted origins instead of blind wildcard RCE
|
||||
if (trustedOrigin) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin || "http://127.0.0.1");
|
||||
res.setHeader("Vary", "Origin");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||
}
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden cross-origin preflight request");
|
||||
return;
|
||||
}
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
@@ -71,6 +102,14 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
// 3. Command Execution Endpoint: POST /api/cli
|
||||
if (method === "POST" && pathname === "/api/cli") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden: untrusted cross-origin request to /api/cli");
|
||||
return;
|
||||
}
|
||||
if (!checkHttpAuth(req)) {
|
||||
sendError(res, 401, "Unauthorized: valid Bearer token required");
|
||||
return;
|
||||
}
|
||||
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
|
||||
const command = (typeof body?.command === "string" ? body.command : "").trim();
|
||||
if (!command) {
|
||||
@@ -104,6 +143,14 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
// 4. RESTful: GET /v1/corps
|
||||
if (method === "GET" && pathname === "/v1/corps") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden: untrusted cross-origin request to /v1/corps");
|
||||
return;
|
||||
}
|
||||
if (!checkHttpAuth(req)) {
|
||||
sendError(res, 401, "Unauthorized: valid Bearer token required");
|
||||
return;
|
||||
}
|
||||
const configs = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
sendJson(res, 200, {
|
||||
|
||||
+30
-6
@@ -16,10 +16,12 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
test("GET / 返回服务概览与 CORS 标头", async () => {
|
||||
const res = await fetch(`${baseUrl}/`);
|
||||
test("GET / 返回服务概览与本地 CORS 标头", async () => {
|
||||
const res = await fetch(`${baseUrl}/`, {
|
||||
headers: { Origin: "http://localhost:3000" },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("http://localhost:3000");
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.name).toBe("hose-use");
|
||||
expect(json.version).toBe(VERSION);
|
||||
@@ -78,6 +80,19 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
expect(json.stdout).toContain(`hose-use v${VERSION}`);
|
||||
});
|
||||
|
||||
test("POST /api/cli 拒绝来自非授信外部 Origin 的跨站命令执行请求 (防 CSRF RCE)", async () => {
|
||||
const res = await fetch(`${baseUrl}/api/cli`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: "https://evil.example.com",
|
||||
},
|
||||
body: JSON.stringify({ command: "version" }),
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBeNull();
|
||||
});
|
||||
|
||||
test("GET /v1/corps 返回企业列表与运行模式", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -87,10 +102,19 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
expect(Array.isArray(json.corps)).toBe(true);
|
||||
});
|
||||
|
||||
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
|
||||
test("OPTIONS /v1/corps 允许本地 Origin 预检并拦截未知外部 Origin", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: "http://127.0.0.1:8888" },
|
||||
});
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:8888");
|
||||
|
||||
const blocked = await fetch(`${baseUrl}/v1/corps`, {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: "https://attacker.example.com" },
|
||||
});
|
||||
expect(blocked.status).toBe(403);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user