UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

434 lines (433 loc) • 15.2 kB
import { L as resolvePositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { i as truncateWithMarker } from "./utf16-slice-CuDyEXgS.mjs"; import { p as isPathInside } from "./includes-wjVi5Ymt.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { l as resolveRuntimeServiceVersion } from "./version-GlxUMdxI.mjs"; import { Et as _enum, Fn as object, Jn as string, Nt as array, Pn as number, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { t as normalizePositiveInt } from "./shared-DyBTHA2R.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { n as inspectPathPermissions, r as safeStat } from "./audit-fs-DX0NF-Sb.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; //#region src/security/install-policy-response.ts const MAX_REASON_CHARS = 1e3; const MAX_FINDINGS = 100; const MAX_FINDING_TEXT_CHARS = 1e3; const TRUNCATION_MARKER = "..."; const installPolicyResponseEnvelopeSchema = object({ protocolVersion: literal(1), decision: _enum([ "allow", "warn", "block" ]), reason: unknown().optional(), findings: array(unknown()).optional().catch(void 0) }); const installPolicyReasonSchema = string().trim().min(1); const findingTextSchema = string().trim().min(1); const optionalFindingTextSchema = findingTextSchema.optional().catch(void 0); const installPolicyFindingSchema = object({ ruleId: findingTextSchema, severity: _enum([ "info", "warn", "critical" ]), message: findingTextSchema, file: optionalFindingTextSchema, line: number().finite().transform((e) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(1, Math.floor(e)))).optional().catch(void 0), evidence: optionalFindingTextSchema }).transform(({ evidence: e, file: t, line: n, ...r }) => ({ ...r, ...t ? { file: t } : {}, ...n !== void 0 ? { line: n } : {}, ...e ? { evidence: e } : {} })); function truncateText(e, t) { return truncateWithMarker(e, t, { marker: TRUNCATION_MARKER, reserve: 3, trimEnd: false }); } function createInstallPolicyFailure(e) { return { blocked: { code: "security_scan_failed", reason: `install policy failed closed: ${truncateText(e, MAX_REASON_CHARS)}` } }; } function blockedByPolicy(e, t) { return { blocked: { code: "security_scan_blocked", reason: `blocked by install policy: ${truncateText(e, MAX_REASON_CHARS)}` }, ...t && t.length > 0 ? { findings: t } : {} }; } function normalizeFinding(e) { const t = installPolicyFindingSchema.safeParse(e); return t.success ? t.data : null; } function truncateFinding(e) { return { ruleId: truncateText(e.ruleId, MAX_FINDING_TEXT_CHARS), severity: e.severity, message: truncateText(e.message, MAX_FINDING_TEXT_CHARS), ...e.file ? { file: truncateText(e.file, MAX_FINDING_TEXT_CHARS) } : {}, ...e.line !== void 0 ? { line: e.line } : {}, ...e.evidence ? { evidence: truncateText(e.evidence, MAX_FINDING_TEXT_CHARS) } : {} }; } function fingerprintWarning(e, t) { return createHash("sha256").update(JSON.stringify({ reason: e, findings: t })).digest("hex"); } function formatPolicyResponseEnvelopeError(e) { const t = e.issues[0]?.path[0]; return t === void 0 ? "policy response must be a JSON object" : t === "protocolVersion" ? "policy response protocolVersion must be 1" : "policy response decision must be \"allow\", \"warn\", or \"block\""; } function parseInstallPolicyResponse(e) { const t = e.trim(); if (!t) return createInstallPolicyFailure("policy command returned empty stdout"); let n; try { n = JSON.parse(t); } catch (e) { return createInstallPolicyFailure(`policy command returned invalid JSON (${formatErrorMessage(e)})`); } const r = installPolicyResponseEnvelopeSchema.safeParse(n); if (!r.success) return createInstallPolicyFailure(formatPolicyResponseEnvelopeError(r.error)); const i = (r.data.findings ?? []).map(normalizeFinding).filter((e) => e !== null); const a = i.slice(0, MAX_FINDINGS).map(truncateFinding); if (r.data.decision === "allow") return a.length > 0 ? { findings: a } : {}; const o = installPolicyReasonSchema.safeParse(r.data.reason); if (!o.success) return createInstallPolicyFailure(`policy response decision "${r.data.decision}" requires a non-empty reason`); if (r.data.decision === "warn") { if (i.length > MAX_FINDINGS) return createInstallPolicyFailure(`policy warning returned more than ${String(MAX_FINDINGS)} valid findings; reduce the findings before retrying`); return { warning: { reason: truncateText(o.data, MAX_REASON_CHARS), fingerprint: fingerprintWarning(o.data, i) }, ...a.length > 0 ? { findings: a } : {} }; } return blockedByPolicy(o.data, a); } //#endregion //#region src/security/install-policy.ts const DEFAULT_TIMEOUT_MS = 1e4; const DEFAULT_MAX_OUTPUT_BYTES = 1048576; const DEFAULT_MAX_REQUEST_BYTES = 262144; const WINDOWS_ABS_PATH_PATTERN = /^[A-Za-z]:[\\/]/; const WINDOWS_UNC_PATH_PATTERN = /^\\\\[^\\]+\\[^\\]+/; const POLICY_INTERPRETER_NAMES = /* @__PURE__ */ new Set([ "bash", "bun", "deno", "env", "fish", "node", "perl", "powershell", "pwsh", "python", "python3", "ruby", "sh", "zsh" ]); const POLICY_SCRIPT_ARG_PATTERN = /\.(?:bash|cjs|cts|js|mjs|mts|pl|ps1|py|rb|sh|ts|zsh)$/i; function isAbsolutePathname(e) { if (path.isAbsolute(e)) return true; return process.platform === "win32" && (WINDOWS_ABS_PATH_PATTERN.test(e) || WINDOWS_UNC_PATH_PATTERN.test(e)); } function executableName(e) { return path.basename(e).replace(/\.exe$/i, "").toLowerCase(); } function isPolicyScriptArg(e) { return isAbsolutePathname(e) || e.startsWith(".") || e.includes("/") || e.includes("\\") || POLICY_SCRIPT_ARG_PATTERN.test(e); } async function readFileStatOrThrow(e, t) { const n = await safeStat(e); if (!n.ok) throw new Error(`${t} is not readable: ${e}`); if (n.isDir) throw new Error(`${t} must be a file: ${e}`); return n; } function collectPathAncestorDirs(e) { const t = []; let n = path.resolve(path.dirname(e)); while (true) { t.push(n); const e = path.dirname(n); if (e === n) return t; n = e; } } async function assertSecureCommandAncestorDirs(e) { const t = typeof process.getuid === "function" ? process.getuid() : void 0; for (const n of collectPathAncestorDirs(e.targetPath)) { const r = await inspectPathPermissions(n); if (!r.ok) throw new Error(`${e.label} parent directory permissions could not be verified: ${n}`); let i = false; if (process.platform !== "win32" && (r.worldWritable || r.groupWritable)) try { i = ((await fs.stat(n)).mode & 512) !== 0; } catch { i = false; } if ((r.worldWritable || r.groupWritable) && !i) throw new Error(`${e.label} parent directory permissions are too open: ${n}`); if (process.platform !== "win32" && t !== void 0) { let r; try { r = await fs.stat(n); } catch { throw new Error(`${e.label} parent directory ownership could not be verified: ${n}`); } if (r.uid !== 0 && r.uid !== t) throw new Error(`${e.label} parent directory owner is not trusted: ${n}`); } if (process.platform === "win32" && r.source === "unknown") throw new Error(`${e.label} parent directory ACL verification unavailable on Windows for ${n}. Move ${e.label} to a direct path whose ACLs can be verified.`); } } async function assertSecureCommandPath(e) { if (!isAbsolutePathname(e.targetPath)) throw new Error(`${e.label} must be an absolute path.`); const t = e.targetPath; const n = await readFileStatOrThrow(t, e.label); if (n.isSymlink) throw new Error(`${e.label} must not be a symlink: ${t}`); if (e.trustedDirs && e.trustedDirs.length > 0) { if (!e.trustedDirs.map((e) => resolveUserPath(e)).some((e) => isPathInside(e, t))) throw new Error(`${e.label} is outside trustedDirs: ${t}`); } const r = await inspectPathPermissions(t); if (!r.ok) throw new Error(`${e.label} permissions could not be verified: ${t}`); if (r.worldWritable || r.groupWritable) throw new Error(`${e.label} permissions are too open: ${t}`); await assertSecureCommandAncestorDirs({ targetPath: t, label: e.label }); if (process.platform === "win32" && r.source === "unknown") throw new Error(`${e.label} ACL verification unavailable on Windows for ${t}. Move ${e.label} to a direct path whose ACLs can be verified.`); if (process.platform !== "win32" && typeof process.getuid === "function" && n.uid != null) { const r = process.getuid(); if (n.uid !== r && n.uid !== 0) throw new Error(`${e.label} must be owned by the current user (uid=${r}) or root: ${t}`); } return t; } async function assertSecurePolicyScriptArg(e) { const t = executableName(e.command); if (t === "env") throw new Error("security.installPolicy.exec.command must not use env; configure the policy executable directly."); if (!POLICY_INTERPRETER_NAMES.has(t)) return; const n = e.args.flatMap((e, t) => { if (!e) return []; const n = e.startsWith("-") ? e.indexOf("=") : -1; if (e.startsWith("-") && n <= 0) return []; const r = n > 0 ? e.slice(n + 1) : e; return isPolicyScriptArg(r) ? [{ index: t, path: r }] : []; }); for (const t of n) await assertSecureCommandPath({ targetPath: t.path, label: `security.installPolicy.exec.args[${t.index}]`, trustedDirs: e.trustedDirs }); } function readPassEnvValue(e, t) { const n = e[t]; if (n !== void 0 || process.platform !== "win32") return n; const r = t.toLowerCase(); const i = Object.keys(e).find((e) => e.toLowerCase() === r); return i ? e[i] : void 0; } function resolveConfiguredTargets(e) { const t = e.targets; return t && t.length > 0 ? [...new Set(t)] : ["skill", "plugin"]; } async function validateInstallPolicyStatic(e) { const t = e?.security?.installPolicy; if (!t || t.enabled !== true) return { enabled: false, targets: [], issues: [] }; const n = resolveConfiguredTargets(t); const r = []; if (!t.exec) { r.push({ severity: "error", message: "security.installPolicy is enabled but security.installPolicy.exec is not configured." }); return { enabled: true, targets: n, issues: r }; } if (!isAbsolutePathname(t.exec.command)) { r.push({ severity: "error", message: "security.installPolicy.exec.command must be an absolute path." }); return { enabled: true, targets: n, issues: r }; } try { await assertSecureCommandPath({ targetPath: t.exec.command, label: "security.installPolicy.exec.command", trustedDirs: t.exec.trustedDirs }); } catch (e) { r.push({ severity: "error", message: formatErrorMessage(e) }); } try { await assertSecurePolicyScriptArg({ command: t.exec.command, args: t.exec.args ?? [], trustedDirs: t.exec.trustedDirs }); } catch (e) { r.push({ severity: "error", message: formatErrorMessage(e) }); } return { enabled: true, targets: n, issues: r }; } async function runInstallPolicy(e) { const t = formatDecisionContext(e.request); const logBlocked = (n) => { if (n.blocked) e.logger?.debug?.(`Install policy ${t}: ${n.blocked.reason}`); return n; }; const failClosed = (e) => logBlocked(createInstallPolicyFailure(e)); let n = e.config; if (!n) try { const { captureRuntimeConfigAsyncReader: e } = await import("./io-DeTUDO0h.mjs"); n = await e({ skipPluginValidation: true })(); } catch (e) { return failClosed(`could not load OpenClaw config (${formatErrorMessage(e)})`); } const r = n?.security?.installPolicy; if (!r || r.enabled !== true) return; const i = r.targets; if (i && i.length !== 0 && !i.includes(e.request.targetType)) return; if (!r.exec) return failClosed("security.installPolicy is enabled but security.installPolicy.exec is not configured"); const a = r.exec; const o = JSON.stringify({ protocolVersion: 1, openclawVersion: resolveRuntimeServiceVersion(e.env ?? process.env), ...e.request }); if (Buffer.byteLength(o, "utf8") > DEFAULT_MAX_REQUEST_BYTES) return failClosed(`policy request exceeded maxInputBytes (${DEFAULT_MAX_REQUEST_BYTES})`); const s = a.command; if (!isAbsolutePathname(s)) return failClosed("security.installPolicy.exec.command must be an absolute path."); let c; try { c = await assertSecureCommandPath({ targetPath: s, label: "security.installPolicy.exec.command", trustedDirs: a.trustedDirs }); await assertSecurePolicyScriptArg({ command: c, args: a.args ?? [], trustedDirs: a.trustedDirs }); } catch (e) { return failClosed(formatErrorMessage(e)); } const l = e.env ?? process.env; const u = {}; for (const e of a.passEnv ?? []) { const t = readPassEnvValue(l, e); if (t !== void 0) u[e] = t; } for (const [e, t] of Object.entries(a.env ?? {})) u[e] = t; const d = resolvePositiveTimerTimeoutMs(a.timeoutMs, DEFAULT_TIMEOUT_MS); const f = resolvePositiveTimerTimeoutMs(a.noOutputTimeoutMs, d); const p = normalizePositiveInt(a.maxOutputBytes, DEFAULT_MAX_OUTPUT_BYTES); const m = path.dirname(c); let h; try { h = await runCommandWithTimeout([c, ...a.args ?? []], { baseEnv: {}, cwd: m, env: u, input: o, killProcessTree: true, maxCombinedOutputBytes: p, maxOutputBytes: p, noOutputTimeoutMs: f, outputCapture: "head", terminateOnOutputLimit: true, timeoutMs: d }); } catch (e) { return failClosed(formatErrorMessage(e)); } if (h.termination === "timeout") return failClosed(`policy command timed out after ${d}ms`); if (h.termination === "no-output-timeout") return failClosed(`policy command produced no output for ${f}ms`); if (h.outputLimitExceeded) return failClosed(`output exceeded maxOutputBytes (${p})`); if (h.code !== 0) return failClosed(`policy command exited with code ${String(h.code)}`); const g = parseInstallPolicyResponse(h.stdout); if (g.blocked) return logBlocked(g); if (g.warning) { e.logger?.debug?.(`Install policy ${t}: warned`); return g; } e.logger?.debug?.(`Install policy ${t}: allowed`); return g; } function formatDecisionContext(e) { const t = e.source ? ` source=${e.source.kind}/${e.source.authority}` : ""; const n = typeof e.origin.type === "string" ? e.origin.type : "unknown"; return [ `target=${e.targetType}:${e.targetName}`, `request=${e.request.kind}/${e.request.mode}`, `origin=${n}`, `pathKind=${e.sourcePathKind}`, t.trim() ].filter(Boolean).join(" "); } async function probeInstallPolicy(e) { const t = await validateInstallPolicyStatic(e.config); if (!t.enabled || t.issues.some((e) => e.severity === "error")) return; const n = t.targets.includes("skill") ? "skill" : t.targets[0]; if (!n) return; return await runInstallPolicy({ config: e.config, env: e.env, logger: e.logger, request: { targetType: n, targetName: "doctor-install-policy-probe", sourcePath: e.sourcePath, sourcePathKind: "directory", origin: { type: "doctor" }, request: { kind: n === "skill" ? "skill-install" : "plugin-dir", mode: "install", requestedSpecifier: "doctor:install-policy-probe" } } }); } //#endregion export { runInstallPolicy as n, validateInstallPolicyStatic as r, probeInstallPolicy as t };