openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
177 lines (176 loc) • 7.16 kB
JavaScript
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { n as applyPrivateModeToFdSync, t as applyPrivateModeSync } from "./private-mode-D8ql0tOD.mjs";
import { a as resolveSqliteDatabaseFilePaths } from "./sqlite-files-rWisKj_V.mjs";
import { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs";
import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, statSync } from "node:fs";
import path from "node:path";
//#region src/state/openclaw-state-db-permissions.ts
const OPENCLAW_STATE_DIR_MODE = 448;
const OPENCLAW_STATE_FILE_MODE = 384;
const stateDbLog = createSubsystemLogger("state/db");
/** Targets already warned about, so chmod-less filesystems warn once per path. */
const chmodWarnedTargets = createDedupeCache({
ttlMs: 0,
maxSize: 4096
});
function bestEffortChmodSync(e, t) {
let n;
try {
n = applyPrivateModeSync(e, t);
} catch (t) {
if (!hasErrnoCode(t, "EPERM") || !process.getuid || statSync(e).uid === process.getuid()) throw t;
n = {
applied: false,
error: t
};
}
if (n.applied || chmodWarnedTargets.check(e)) return;
stateDbLog.warn(`skipped permission hardening for ${e}: ${String(n.error)}`);
}
/** Private stores this installation owns beside its shared state database. */
const PRIVATE_STATE_STORES = Object.freeze([["client", "credentials.sqlite"], ["control", "services.sqlite"]]);
/** Mirrors resolveUpdateCaptureRoot, which is a hard sibling of the state directory. */
const UPDATE_CAPTURE_ROOT_SUFFIX = ".update-captures";
function bestEffortFchmodSync(e, t, n) {
let r;
try {
r = applyPrivateModeToFdSync(e, t, n);
} catch (t) {
if (!hasErrnoCode(t, "EPERM") || !process.getuid || fstatSync(e).uid === process.getuid()) throw t;
r = {
applied: false,
error: t
};
}
if (r.applied || chmodWarnedTargets.check(t)) return;
stateDbLog.warn(`skipped permission hardening for ${t}: ${String(r.error)}`);
}
/** Opens an enumerated store path, refusing a symlink standing in for it. */
function openStorePathSync(e, t) {
const n = constants.O_RDONLY | constants.O_NOFOLLOW | (t ? constants.O_DIRECTORY : constants.O_NONBLOCK);
try {
return openSync(e, n);
} catch (t) {
if (hasErrnoCode(t, "ENOENT") || hasErrnoCode(t, "ENOTDIR")) return;
if (hasErrnoCode(t, "ELOOP") || hasErrnoCode(t, "EMLINK")) {
stateDbLog.warn(`skipped permission restore for ${e}: symbolic link`);
return;
}
if (hasErrnoCode(t, "EACCES") || hasErrnoCode(t, "EPERM")) {
if (!chmodWarnedTargets.check(e)) stateDbLog.warn(`skipped permission restore for ${e}: ${String(t)}`);
return;
}
throw t;
}
}
/** True while the descriptor and the pathname still name one filesystem object. */
function describesSamePathSync(e, t) {
try {
const n = fstatSync(e, { bigint: true });
const r = lstatSync(t, { bigint: true });
return n.dev === r.dev && n.ino === r.ino;
} catch (e) {
if (hasErrnoCode(e, "ENOENT") || hasErrnoCode(e, "ENOTDIR")) return false;
throw e;
}
}
/**
* Restores one admitted, installation-owned object through its descriptor.
*
* Deliberately narrow, so this stays a repair rather than a policy change:
* foreign-owned objects are left alone, an already-private object is untouched
* so its ctime stays stable, an object carrying world permission bits is left
* for its owner to refuse because fsGroup never sets those, and a file with
* more than one link is refused because its other name may sit outside this
* installation, where this repair has no authority.
*
* Returns true when the object is admitted as this installation's own, so the
* caller may go on to inspect what it contains.
*/
function restoreAdmittedModeSync(e, t, n, r) {
const i = fstatSync(e, { bigint: true });
if (r === "directory" ? !i.isDirectory() : !i.isFile()) {
stateDbLog.warn(`skipped permission restore for ${t}: not a regular ${r}`);
return false;
}
if (!describesSamePathSync(e, t)) return false;
if (r === "file" && i.nlink !== 1n) {
stateDbLog.warn(`skipped permission restore for ${t}: more than one link`);
return false;
}
const a = process.getuid?.();
if (a !== void 0 && i.uid !== BigInt(a)) return false;
const o = i.mode & 4095n;
if ((o & 7n) !== 0n) return false;
if ((o & 3640n) === 0n) return true;
bestEffortFchmodSync(e, t, n);
return true;
}
/**
* Restores a store directory, then the database files it is admitted to hold.
*
* Admitting the directory decides whether its children may be touched at all:
* a refused directory may be an alias, and a pathname below it would resolve
* through that alias to an object this installation does not own.
*/
function restoreStoreDirectorySync(e, t) {
const n = openStorePathSync(e, true);
if (n === void 0) return;
try {
if (!restoreAdmittedModeSync(n, e, OPENCLAW_STATE_DIR_MODE, "directory")) return;
for (const r of t) for (const t of resolveSqliteDatabaseFilePaths(path.join(e, r))) {
if (!describesSamePathSync(n, e)) return;
const r = openStorePathSync(t, false);
if (r === void 0) continue;
try {
restoreAdmittedModeSync(r, t, OPENCLAW_STATE_FILE_MODE, "file");
} finally {
closeSync(r);
}
}
} finally {
closeSync(n);
}
}
/**
* Restores private modes that an fsGroup volume remount broadens.
*
* Kubernetes re-applies `fsGroup` group permissions to every directory and file
* of a volume on each mount, and Linux propagates the volume's setgid bit into
* directories the gateway creates under it. The private-storage owners then
* refuse to open state this installation already owns, and the Gateway cannot
* start (#192959). `fsGroupChangePolicy: OnRootMismatch` only narrows when this
* will happen; it does not restore permissions already broadened.
*
* This repairs an enumerated set of owned paths before those owners run, so
* every downstream admission check stays exactly as strict as before.
*/
function restorePrivateStateStoreModes(e) {
if (process.platform === "win32") return;
const t = path.resolve(resolveStateDir(e));
restoreStoreDirectorySync(`${t}${UPDATE_CAPTURE_ROOT_SUFFIX}`, []);
for (const [e, n] of PRIVATE_STATE_STORES) restoreStoreDirectorySync(path.join(t, e), [n]);
}
function ensureOpenClawStatePermissions(e, t, n = {}) {
const r = path.dirname(e);
const i = resolveOpenClawStateSqlitePath(t);
const a = path.dirname(i);
const o = path.resolve(e) === path.resolve(i);
if (o && r !== a) throw new Error(`OpenClaw state database path resolved outside its state dir: ${e}`);
const s = existsSync(r);
if (n.createDirectory) mkdirSync(r, {
recursive: true,
mode: OPENCLAW_STATE_DIR_MODE
});
if (o || !s) bestEffortChmodSync(r, OPENCLAW_STATE_DIR_MODE);
for (const t of resolveSqliteDatabaseFilePaths(e)) if (existsSync(t)) try {
bestEffortChmodSync(t, OPENCLAW_STATE_FILE_MODE);
} catch (n) {
if (t === e || !hasErrnoCode(n, "ENOENT")) throw n;
}
}
//#endregion
export { restorePrivateStateStoreModes as n, ensureOpenClawStatePermissions as t };