Skip to content

Commit 6d90212

Browse files
committed
fix(backup): reject unrestorable symlinks during create
1 parent 5523f8a commit 6d90212

5 files changed

Lines changed: 140 additions & 85 deletions

File tree

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,6 @@ src/commands/agent-via-gateway.ts
523523
src/commands/agent.test.ts
524524
src/commands/auth-choice.test.ts
525525
src/commands/backup-verify.test.ts
526-
src/commands/backup-verify.ts
527526
src/commands/channels.add.test.ts
528527
src/commands/configure.wizard.ts
529528
src/commands/daemon-install-helpers.test.ts

‎src/commands/backup-verify.ts‎

Lines changed: 11 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Verifies backup archives by validating their manifest, payload entries, and hardlink targets.
1+
// Verifies backup archives, including payload paths and hardlink/symbolic-link targets.
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
@@ -7,6 +7,12 @@ import { toStringifiedError } from "@openclaw/normalization-core/error-coercion"
77
import { readStringValue } from "@openclaw/normalization-core/string-coerce";
88
import * as tar from "tar";
99
import { loadSqliteVecExtension } from "../../packages/memory-host-sdk/src/engine-storage.js";
10+
import {
11+
assertArchiveSymbolicLinkTarget,
12+
isArchivePathWithin,
13+
normalizeArchivePath,
14+
normalizeArchiveRoot,
15+
} from "../infra/backup-archive-path-policy.js";
1016
import { isTransientSqliteBackupPath } from "../infra/backup-volatile-filter.js";
1117
import { formatDiskSpaceBytes, tryReadDiskSpace } from "../infra/disk-space.js";
1218
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
@@ -15,7 +21,6 @@ import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
1521
import { isRecord, resolveUserPath } from "../utils.js";
1622
import { BACKUP_MAX_DECOMPRESSION_RATIO, buildBackupArchivePath } from "./backup-shared.js";
1723

18-
const WINDOWS_ABSOLUTE_ARCHIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
1924
const MAX_MANIFEST_BYTES = 1024 * 1024;
2025
const MAX_SQLITE_SNAPSHOT_EXTRACT_BYTES = 64 * 1024 * 1024 * 1024;
2126
const SQLITE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES = 256 * 1024 * 1024;
@@ -88,45 +93,6 @@ type SqliteSnapshotEntry = NormalizedArchiveEntry & {
8893

8994
type ExpectedSqliteRole = "agent" | "global";
9095

91-
function stripTrailingSlashes(value: string): string {
92-
return value.replace(/\/+$/u, "");
93-
}
94-
95-
function normalizeArchivePath(entryPath: string, label: string): string {
96-
const trimmed = stripTrailingSlashes(entryPath.trim());
97-
if (!trimmed) {
98-
throw new Error(`${label} is empty.`);
99-
}
100-
if (trimmed.startsWith("/") || WINDOWS_ABSOLUTE_ARCHIVE_PATH_RE.test(trimmed)) {
101-
throw new Error(`${label} must be relative: ${entryPath}`);
102-
}
103-
if (trimmed.includes("\\")) {
104-
throw new Error(`${label} must use forward slashes: ${entryPath}`);
105-
}
106-
if (trimmed.split("/").some((segment) => segment === "." || segment === "..")) {
107-
throw new Error(`${label} contains path traversal segments: ${entryPath}`);
108-
}
109-
110-
const normalized = stripTrailingSlashes(path.posix.normalize(trimmed));
111-
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../")) {
112-
throw new Error(`${label} resolves outside the archive root: ${entryPath}`);
113-
}
114-
return normalized;
115-
}
116-
117-
function normalizeArchiveRoot(rootName: string): string {
118-
const normalized = normalizeArchivePath(rootName, "Backup manifest archiveRoot");
119-
if (normalized.includes("/")) {
120-
throw new Error(`Backup manifest archiveRoot must be a single path segment: ${rootName}`);
121-
}
122-
return normalized;
123-
}
124-
125-
function isArchivePathWithin(child: string, parent: string): boolean {
126-
const relative = path.posix.relative(parent, child);
127-
return relative === "" || (!relative.startsWith("../") && relative !== "..");
128-
}
129-
13096
function parseManifest(raw: string): BackupManifest {
13197
let parsed: unknown;
13298
try {
@@ -312,34 +278,6 @@ function verifyHardlinkTargetsAgainstArchiveRoot(
312278
}
313279
}
314280

315-
function verifySymbolicLinkTargetsAgainstArchiveRoot(
316-
symbolicLinks: Array<{ entryPath: string; linkpath: string }>,
317-
archiveRoot: string,
318-
): void {
319-
const normalizedRoot = normalizeArchiveRoot(archiveRoot);
320-
for (const link of symbolicLinks) {
321-
if (link.linkpath.startsWith("/") || WINDOWS_ABSOLUTE_ARCHIVE_PATH_RE.test(link.linkpath)) {
322-
throw new Error(
323-
`Archive symbolic link target must be relative: ${link.entryPath} -> ${link.linkpath}`,
324-
);
325-
}
326-
if (link.linkpath.includes("\\")) {
327-
throw new Error(
328-
`Archive symbolic link target must use forward slashes: ${link.entryPath} -> ${link.linkpath}`,
329-
);
330-
}
331-
const entryPath = normalizeArchivePath(link.entryPath, "Archive symbolic link path");
332-
const targetPath = path.posix.normalize(
333-
path.posix.join(path.posix.dirname(entryPath), link.linkpath),
334-
);
335-
if (!isArchivePathWithin(targetPath, normalizedRoot)) {
336-
throw new Error(
337-
`Archive symbolic link target is outside the declared archive root: ${link.entryPath} -> ${link.linkpath}`,
338-
);
339-
}
340-
}
341-
}
342-
343281
function formatResult(result: BackupVerifyResult): string {
344282
return [
345283
`Backup archive OK: ${result.archivePath}`,
@@ -764,12 +702,7 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
764702
}));
765703
const symbolicLinks = rawEntries
766704
.filter((entry) => entry.type === "SymbolicLink")
767-
.map((entry) => {
768-
if (!entry.linkpath) {
769-
throw new Error(`Archive symbolic link is missing its target: ${entry.path}`);
770-
}
771-
return { entryPath: entry.path, linkpath: entry.linkpath };
772-
});
705+
.map((entry) => ({ entryPath: entry.path, linkpath: entry.linkpath }));
773706
const normalizedEntrySet = new Set(entries.map((entry) => entry.normalized));
774707

775708
const manifestMatches = entries.filter((entry) => isRootManifestEntry(entry.normalized));
@@ -799,7 +732,9 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
799732
manifest.archiveRoot,
800733
normalizedEntrySet,
801734
);
802-
verifySymbolicLinkTargetsAgainstArchiveRoot(symbolicLinks, manifest.archiveRoot);
735+
for (const link of symbolicLinks) {
736+
assertArchiveSymbolicLinkTarget({ ...link, archiveRoot: manifest.archiveRoot });
737+
}
803738
await verifySqliteSnapshots({ archivePath, entries, manifest });
804739

805740
const result: BackupVerifyResult = {
@@ -834,4 +769,3 @@ export async function backupVerifyCommand(
834769
export const testApi = {
835770
assertSqliteExtractionBudget,
836771
};
837-
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import path from "node:path";
2+
import { isWindowsDrivePath } from "./archive-path.js";
3+
4+
// Creation and verification must agree on which archive paths can be restored.
5+
function assertPortableRelativePathSyntax(
6+
value: string,
7+
label: string,
8+
reportedValue = value,
9+
): void {
10+
if (value.startsWith("/") || isWindowsDrivePath(value)) {
11+
throw new Error(`${label} must be relative: ${reportedValue}`);
12+
}
13+
if (value.includes("\\")) {
14+
throw new Error(`${label} must use forward slashes: ${reportedValue}`);
15+
}
16+
}
17+
18+
function stripTrailingSlashes(value: string): string {
19+
return value.replace(/\/+$/u, "");
20+
}
21+
22+
export function normalizeArchivePath(entryPath: string, label: string): string {
23+
const trimmed = stripTrailingSlashes(entryPath.trim());
24+
if (!trimmed) {
25+
throw new Error(`${label} is empty.`);
26+
}
27+
assertPortableRelativePathSyntax(trimmed, label, entryPath);
28+
if (trimmed.split("/").some((segment) => segment === "." || segment === "..")) {
29+
throw new Error(`${label} contains path traversal segments: ${entryPath}`);
30+
}
31+
32+
const normalized = stripTrailingSlashes(path.posix.normalize(trimmed));
33+
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../")) {
34+
throw new Error(`${label} resolves outside the archive root: ${entryPath}`);
35+
}
36+
return normalized;
37+
}
38+
39+
export function normalizeArchiveRoot(rootName: string): string {
40+
const normalized = normalizeArchivePath(rootName, "Backup manifest archiveRoot");
41+
if (normalized.includes("/")) {
42+
throw new Error(`Backup manifest archiveRoot must be a single path segment: ${rootName}`);
43+
}
44+
return normalized;
45+
}
46+
47+
export function isArchivePathWithin(child: string, parent: string): boolean {
48+
const relative = path.posix.relative(parent, child);
49+
return relative === "" || (!relative.startsWith("../") && relative !== "..");
50+
}
51+
52+
export function assertArchiveSymbolicLinkTarget(params: {
53+
archiveRoot: string;
54+
entryPath: string;
55+
linkpath?: string;
56+
}): void {
57+
if (!params.linkpath) {
58+
throw new Error(`Archive symbolic link is missing its target: ${params.entryPath}`);
59+
}
60+
assertPortableRelativePathSyntax(
61+
params.linkpath,
62+
"Archive symbolic link target",
63+
`${params.entryPath} -> ${params.linkpath}`,
64+
);
65+
const entryPath = normalizeArchivePath(params.entryPath, "Archive symbolic link path");
66+
const targetPath = path.posix.normalize(
67+
path.posix.join(path.posix.dirname(entryPath), params.linkpath),
68+
);
69+
if (!isArchivePathWithin(targetPath, normalizeArchiveRoot(params.archiveRoot))) {
70+
throw new Error(
71+
`Archive symbolic link target is outside the declared archive root: ${params.entryPath} -> ${params.linkpath}`,
72+
);
73+
}
74+
}

‎src/infra/backup-create.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2199,6 +2199,35 @@ describe("createBackupArchive", () => {
21992199
);
22002200
});
22012201

2202+
it("rejects absolute symlink targets before publishing the archive", async () => {
2203+
if (process.platform === "win32") {
2204+
return;
2205+
}
2206+
2207+
await withOpenClawTestState(
2208+
{
2209+
layout: "state-only",
2210+
prefix: "openclaw-backup-absolute-symlink-",
2211+
scenario: "minimal",
2212+
},
2213+
async (state) => {
2214+
const outputPath = state.path("absolute-symlink.tar.gz");
2215+
const outsideTarget = state.path("outside-target.txt");
2216+
await fs.writeFile(outsideTarget, "outside\n", "utf8");
2217+
await fs.symlink(outsideTarget, state.statePath("ordinary-link"));
2218+
2219+
await expect(
2220+
createBackupArchive({
2221+
output: outputPath,
2222+
includeWorkspace: false,
2223+
nowMs: Date.UTC(2026, 4, 9, 8, 33, 0),
2224+
}),
2225+
).rejects.toThrow(/Archive symbolic link target must be relative/iu);
2226+
await expect(fs.access(outputPath)).rejects.toMatchObject({ code: "ENOENT" });
2227+
},
2228+
);
2229+
});
2230+
22022231
it("preserves noncanonical symlinked SQLite paths without dereferencing them", async () => {
22032232
if (process.platform === "win32") {
22042233
return;

‎src/infra/backup-create.ts‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
} from "../state/openclaw-state-snapshot-sanitizer.js";
2626
import { resolveHomeDir, resolveUserPath, shortenHomePath } from "../utils.js";
2727
import { resolveRuntimeServiceVersion } from "../version.js";
28+
import { assertArchiveSymbolicLinkTarget } from "./backup-archive-path-policy.js";
2829
import {
2930
cleanupBackupArchivePublication,
3031
createBackupArchivePublication,
@@ -855,9 +856,10 @@ export async function createBackupArchive(
855856
const volatilePlan = { stateDirs: [stateAsset?.sourcePath ?? plan.stateDir] };
856857
let skippedVolatileCount = 0;
857858
let skippedPluginSkills = false;
858-
// node-tar invokes filters from async stat callbacks, so throwing inside
859-
// the filter is uncaught. Omit unexpected SQLite and reject after tar settles.
859+
// node-tar invokes filter/onWriteEntry from async filesystem callbacks, so
860+
// collect violations there and reject only after tar settles.
860861
const unexpectedSqliteSourcePaths: string[] = [];
862+
let archiveSymlinkViolation: Error | undefined;
861863
const tarFilter = (
862864
entryPath: string,
863865
entryStat: import("node:fs").Stats | import("tar").ReadEntry,
@@ -921,6 +923,7 @@ export async function createBackupArchive(
921923
skippedVolatileCount = 0;
922924
skippedPluginSkills = false;
923925
unexpectedSqliteSourcePaths.length = 0;
926+
archiveSymlinkViolation = undefined;
924927
const prepared = await writeArchiveStreamToFile({
925928
archivePath: attemptTempArchivePath,
926929
createArchiveStream: (reportProgress) =>
@@ -943,12 +946,25 @@ export async function createBackupArchive(
943946
reportProgress({ phase: "raw", entryPath: sourceEntryPath, bytes });
944947
});
945948
}
946-
entry.path = remapArchiveEntryPath({
949+
const archiveEntryPath = remapArchiveEntryPath({
947950
entryPath: entry.path,
948951
manifestPath,
949952
archiveRoot,
950953
sourcePathRemaps,
951954
});
955+
if (entry.type === "SymbolicLink" && !archiveSymlinkViolation) {
956+
try {
957+
assertArchiveSymbolicLinkTarget({
958+
archiveRoot,
959+
entryPath: archiveEntryPath,
960+
linkpath: entry.linkpath,
961+
});
962+
} catch (error) {
963+
archiveSymlinkViolation =
964+
error instanceof Error ? error : new Error(String(error));
965+
}
966+
}
967+
entry.path = archiveEntryPath;
952968
},
953969
},
954970
[
@@ -963,13 +979,16 @@ export async function createBackupArchive(
963979
},
964980
});
965981
const unexpectedSqliteSourcePath = unexpectedSqliteSourcePaths[0];
966-
if (unexpectedSqliteSourcePath) {
982+
const archiveValidationError = unexpectedSqliteSourcePath
983+
? new Error(
984+
`SQLite state appeared after snapshot discovery: ${unexpectedSqliteSourcePath}. Retry backup so it can be snapshotted.`,
985+
)
986+
: archiveSymlinkViolation;
987+
if (archiveValidationError) {
967988
if (!removePreparedBackupArchive(prepared)) {
968989
publication.pendingCleanupArchives.push(prepared);
969990
}
970-
throw new Error(
971-
`SQLite state appeared after snapshot discovery: ${unexpectedSqliteSourcePath}. Retry backup so it can be snapshotted.`,
972-
);
991+
throw archiveValidationError;
973992
}
974993
return prepared;
975994
},

0 commit comments

Comments
 (0)