Skip to content

Commit 65597f9

Browse files
authored
fix: restore default-profile backup archives (#123504)
* fix(backup): make default-profile backups restorable * fix(backup): preserve restore cleanup context * refactor(backup): drop preserve-caught-error suppression via hoisted cleanup error * refactor(backup): hoist restore failure handling out of catch scopes
1 parent 749340f commit 65597f9

7 files changed

Lines changed: 247 additions & 25 deletions

File tree

‎docs/cli/backup.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ Archive `create`, `verify`, and `restore`, plus SQLite `create`, `list`, `verify
4545
- The archive embeds a `manifest.json` with the resolved source paths and archive layout.
4646
- Default output is a timestamped `.tar.gz` archive in the current working directory. Timestamped filenames use your machine's local timezone and include the UTC offset. If the current working directory is inside a backed-up source tree, OpenClaw falls back to your home directory for the default archive location.
4747
- Existing archive files are never overwritten. Output paths inside the source state/workspace trees are rejected to avoid self-inclusion.
48-
- `openclaw backup verify <archive>` checks that the archive contains exactly one root manifest, rejects traversal-style archive paths and SQLite sidecars, confirms every manifest-declared payload exists, validates every SQLite snapshot's file shape, and runs full integrity and role checks on canonical OpenClaw databases. Dedicated plugin schemas remain opaque because they may require owner-defined SQLite capabilities. `openclaw backup create --verify` runs that validation immediately after writing the archive.
48+
- `openclaw backup verify <archive>` checks that the archive contains exactly one root manifest, rejects traversal-style archive paths, absolute or archive-escaping symbolic links, and SQLite sidecars, confirms every manifest-declared payload exists, validates every SQLite snapshot's file shape, and runs full integrity and role checks on canonical OpenClaw databases. Dedicated plugin schemas remain opaque because they may require owner-defined SQLite capabilities. `openclaw backup create --verify` runs that validation immediately after writing the archive.
4949
- `openclaw backup create --only-config` backs up just the active JSON config file.
5050

5151
## Restore a full archive
@@ -70,7 +70,9 @@ archive.
7070
relinking. Approvals and delivery/dedupe state also roll back, so review
7171
pending approvals before resuming the Gateway. Plugin `node_modules` trees
7272
are not archived; after activation, run `openclaw plugins update <id>` or
73-
reinstall with `openclaw plugins install <spec> --force`.
73+
reinstall with `openclaw plugins install <spec> --force`. The generated
74+
`plugin-skills/` symlink index is also omitted; run `openclaw skills list` or
75+
start an agent session after activation to rebuild it from plugin metadata.
7476
</Warning>
7577

7678
Activation is a separate offline operator step. Stop the Gateway, move the
@@ -261,6 +263,8 @@ SQLite databases under the state directory are captured with SQLite's online bac
261263

262264
Installed plugin source and manifest files under the state directory's `extensions/` tree are included, but their nested `node_modules/` dependency trees are skipped as rebuildable install artifacts. After restoring an archive, use `openclaw plugins update <id>` or reinstall with `openclaw plugins install <spec> --force` if a restored plugin reports missing dependencies.
263265

266+
The state directory's `plugin-skills/` root is a generated, OpenClaw-owned symlink index, not authoritative state. Backup creation reports and omits that root because its absolute targets are specific to the source installation. After activating restored state, run `openclaw skills list` or start an agent session to rebuild the links from current plugin metadata. Other relative symbolic links are retained when their targets stay inside the archive root; verification rejects absolute or archive-escaping targets.
267+
264268
Installer-managed and rebuildable runtime roots under the state directory are also skipped: `dev/`, `git/`, `npm/`, legacy `npm-runtime/`, `tmp/`, and `tools/`. These contain managed checkouts, package trees, compiler caches, temporary files, and downloaded runtimes rather than authoritative user state; reinstall or update the corresponding runtime or plugin after restore. An explicitly configured config file, credentials directory, or workspace inside one of these roots remains included.
265269

266270
Local edits inside a managed `dev/` checkout are developer source, not OpenClaw product state, and are not included. Commit and push those edits or copy the checkout separately before relying on a state backup.

‎docs/install/backups.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ openclaw backup restore "$ARCHIVE" --target ./restored-openclaw
247247
```
248248

249249
The target must not exist or must be empty. OpenClaw verifies archive structure,
250-
the manifest, hardlinks, and SQLite databases before it writes the target. A
250+
the manifest, hardlinks, symbolic-link containment, and SQLite databases before it writes the target. A
251251
non-empty target is refused, and a failed extraction cleans its incomplete
252252
output. The command never touches the live state directory and has no force or
253253
in-place mode. Treat the restored directory as sensitive: it can contain
@@ -259,7 +259,9 @@ credentials, auth profiles, sessions, and workspace data.
259259
relinking. Approvals and delivery/dedupe state also roll back, so review
260260
pending approvals before resuming the Gateway. Plugin `node_modules` trees
261261
are not archived; after activation, run `openclaw plugins update <id>` or
262-
reinstall with `openclaw plugins install <spec> --force`.
262+
reinstall with `openclaw plugins install <spec> --force`. Run `openclaw
263+
skills list` or start an agent session to regenerate the omitted
264+
`plugin-skills/` symlink index from current plugin metadata.
263265
</Warning>
264266

265267
The manifest records `archiveRoot`, the original paths under `paths`, and an

‎src/commands/backup-restore.test.ts‎

Lines changed: 126 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ async function listFilesystemLeafEntries(root: string, relative = ""): Promise<s
5353
function encodeTarEntry(params: {
5454
path: string;
5555
contents?: string;
56-
type?: "File" | "Directory" | "Link";
56+
type?: "File" | "Directory" | "Link" | "SymbolicLink";
5757
linkpath?: string;
5858
}): Buffer {
5959
const body = Buffer.from(params.contents ?? "", "utf8");
@@ -126,6 +126,18 @@ describe("backupRestoreCommand", () => {
126126
const targetPath = state.path("restored");
127127
await fs.mkdir(outputDir, { recursive: true });
128128
await state.writeText("operator-note.txt", "restore me\n");
129+
const pluginSkillTarget = state.statePath("plugin-source", "canvas");
130+
if (process.platform !== "win32") {
131+
await fs.mkdir(pluginSkillTarget, { recursive: true });
132+
await fs.writeFile(path.join(pluginSkillTarget, "SKILL.md"), "# Canvas\n", "utf8");
133+
const pluginSkillsDir = state.statePath("plugin-skills");
134+
await fs.mkdir(pluginSkillsDir, { recursive: true });
135+
await fs.symlink(
136+
await fs.realpath(pluginSkillTarget),
137+
path.join(pluginSkillsDir, "canvas"),
138+
"dir",
139+
);
140+
}
129141
openOpenClawStateDatabase({ env: state.env });
130142

131143
try {
@@ -152,8 +164,20 @@ describe("backupRestoreCommand", () => {
152164
expect(restored.warnings.join("\n")).toMatch(/WhatsApp/iu);
153165
expect(restored.warnings.join("\n")).toMatch(/pending approvals/iu);
154166
expect(restored.warnings.join("\n")).toMatch(/plugins install <spec> --force/iu);
167+
expect(restored.warnings.join("\n")).toMatch(/openclaw skills list/iu);
155168
expect(runtime.log).toHaveBeenCalledOnce();
156169
expect(JSON.parse(String(vi.mocked(runtime.log).mock.calls[0]?.[0]))).toEqual(restored);
170+
if (process.platform !== "win32") {
171+
expect(backup.skipped).toContainEqual(
172+
expect.objectContaining({
173+
sourcePath: state.statePath("plugin-skills"),
174+
reason: "regenerable",
175+
}),
176+
);
177+
expect(await listArchiveLeafEntries(backup.archivePath)).not.toContainEqual(
178+
expect.stringContaining("/plugin-skills/"),
179+
);
180+
}
157181

158182
expect(await listFilesystemLeafEntries(targetPath)).toEqual(
159183
await listArchiveLeafEntries(backup.archivePath),
@@ -239,6 +263,57 @@ describe("backupRestoreCommand", () => {
239263
);
240264
});
241265

266+
it.each([
267+
{
268+
label: "absolute",
269+
linkpath: "/private/tmp/outside-restore",
270+
error: /symbolic link target must be relative/iu,
271+
},
272+
{
273+
label: "archive-escaping",
274+
linkpath: "../../outside-restore",
275+
error: /symbolic link target is outside the declared archive root/iu,
276+
},
277+
])(
278+
"rejects $label symlink targets before touching the restore target",
279+
async ({ linkpath, error }) => {
280+
await withOpenClawTestState(
281+
{
282+
layout: "state-only",
283+
prefix: "openclaw-backup-restore-absolute-symlink-",
284+
scenario: "minimal",
285+
},
286+
async (state) => {
287+
const archivePath = state.path("absolute-symlink.tar.gz");
288+
const targetPath = state.path("restore-target");
289+
const archiveRoot = "2026-08-12T00-00-00.000Z-openclaw-backup";
290+
const payloadPath = buildBackupArchivePath(archiveRoot, "/tmp/openclaw.json");
291+
await writeArchive({
292+
archivePath,
293+
archiveRoot,
294+
payloadPath,
295+
extraEntries: [
296+
encodeTarEntry({
297+
path: `${archiveRoot}/payload/absolute-link`,
298+
type: "SymbolicLink",
299+
linkpath,
300+
}),
301+
],
302+
});
303+
304+
await expect(
305+
backupRestoreCommand(createRuntime(), { archive: archivePath, target: targetPath }),
306+
).rejects.toThrow(error);
307+
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
308+
await new Promise<void>((resolve) => {
309+
setImmediate(resolve);
310+
});
311+
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
312+
},
313+
);
314+
},
315+
);
316+
242317
it("cleans an incomplete fresh target when extraction fails", async () => {
243318
await withOpenClawTestState(
244319
{
@@ -270,6 +345,56 @@ describe("backupRestoreCommand", () => {
270345
backupRestoreCommand(createRuntime(), { archive: archivePath, target: targetPath }),
271346
).rejects.toThrow(/incomplete target was cleaned/iu);
272347
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
348+
await new Promise<void>((resolve) => {
349+
setImmediate(resolve);
350+
});
351+
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
352+
},
353+
);
354+
});
355+
356+
it("preserves the extraction error when cleanup also fails", async () => {
357+
await withOpenClawTestState(
358+
{
359+
layout: "state-only",
360+
prefix: "openclaw-backup-restore-double-failure-",
361+
scenario: "minimal",
362+
},
363+
async (state) => {
364+
const archivePath = state.path("unextractable.tar.gz");
365+
const targetPath = state.path("restore-target");
366+
const archiveRoot = "2026-08-12T00-00-00.000Z-openclaw-backup";
367+
const assetPath = buildBackupArchivePath(archiveRoot, "/tmp/openclaw.json");
368+
const directoryPath = `${archiveRoot}/payload/invalid-hardlink-target`;
369+
await writeArchive({
370+
archivePath,
371+
archiveRoot,
372+
payloadPath: assetPath,
373+
extraEntries: [
374+
encodeTarEntry({ path: directoryPath, type: "Directory" }),
375+
encodeTarEntry({
376+
path: `${archiveRoot}/payload/directory-hardlink`,
377+
type: "Link",
378+
linkpath: directoryPath,
379+
}),
380+
],
381+
});
382+
const cleanupError = new Error("cleanup denied");
383+
vi.spyOn(fs, "rm").mockRejectedValueOnce(cleanupError);
384+
385+
const restoreError = await backupRestoreCommand(createRuntime(), {
386+
archive: archivePath,
387+
target: targetPath,
388+
}).catch((error: unknown) => error);
389+
390+
expect(restoreError).toBeInstanceOf(Error);
391+
expect((restoreError as Error).message).toMatch(/cleanup denied/iu);
392+
expect((restoreError as Error).cause).toBeInstanceOf(Error);
393+
expect((restoreError as Error).cause).not.toBe(cleanupError);
394+
expect((restoreError as AggregateError).errors).toEqual([
395+
(restoreError as Error).cause,
396+
cleanupError,
397+
]);
273398
},
274399
);
275400
});

‎src/commands/backup-restore.ts‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
33
import path from "node:path";
44
import * as tar from "tar";
55
import { resolveStateDir } from "../config/config.js";
6+
import { formatErrorMessage } from "../infra/errors.js";
67
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
78
import { resolveUserPath, shortenHomePath } from "../utils.js";
89
import { BACKUP_MAX_DECOMPRESSION_RATIO, canonicalizePathForContainment } from "./backup-shared.js";
@@ -14,6 +15,7 @@ const BACKUP_RESTORE_WARNINGS = [
1415
"Messaging-channel credentials with ratchet state, especially WhatsApp, may desynchronize after rollback and require relinking.",
1516
"Approvals and delivery/dedupe state also roll back; review pending approvals before resuming the Gateway.",
1617
"Plugin node_modules are not archived; after activation, run `openclaw plugins update <id>` or reinstall with `openclaw plugins install <spec> --force`.",
18+
"Generated plugin-skills links are not archived; after activation, run `openclaw skills list` or start an agent session to rebuild them.",
1719
] as const;
1820

1921
type BackupRestoreOptions = {
@@ -31,6 +33,7 @@ type BackupRestoreResult = {
3133
runtimeVersion: string;
3234
assetCount: number;
3335
entryCount: number;
36+
symlinkCount: number;
3437
warnings: string[];
3538
};
3639

@@ -84,6 +87,27 @@ async function cleanupFailedRestore(targetPath: string, created: boolean): Promi
8487
}
8588
}
8689

90+
async function extractBackupArchive(archivePath: string, targetPath: string): Promise<void> {
91+
let extractionError: Error | undefined;
92+
await tar.x({
93+
file: archivePath,
94+
gzip: true,
95+
maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO,
96+
cwd: targetPath,
97+
// node-tar strict mode rejects on the first warning before queued writes drain.
98+
// Verification catches fatal archive errors; rethrow recoverable warnings after close.
99+
strict: false,
100+
preserveOwner: false,
101+
onwarn: (code, message, data) => {
102+
extractionError ??=
103+
data instanceof Error ? data : Object.assign(new Error(`${code}: ${message}`), data);
104+
},
105+
});
106+
if (extractionError) {
107+
throw extractionError;
108+
}
109+
}
110+
87111
function formatRestoreResult(result: BackupRestoreResult): string {
88112
return [
89113
`Backup archive restored to staging: ${shortenHomePath(result.targetPath)}`,
@@ -108,26 +132,33 @@ export async function backupRestoreCommand(
108132
const verified = await verifyBackupArchive(options.archive);
109133
const target = await prepareRestoreTarget(targetPath);
110134

135+
let extractionError: unknown;
136+
let extractionFailed = false;
111137
try {
112-
await tar.x({
113-
file: verified.archivePath,
114-
gzip: true,
115-
maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO,
116-
cwd: targetPath,
117-
strict: true,
118-
preserveOwner: false,
119-
});
120-
} catch (error) {
138+
await extractBackupArchive(verified.archivePath, targetPath);
139+
} catch (caughtExtractionError) {
140+
extractionError = caughtExtractionError;
141+
extractionFailed = true;
142+
}
143+
if (extractionFailed) {
144+
let cleanupError: unknown;
145+
let cleanupFailed = false;
121146
try {
122147
await cleanupFailedRestore(targetPath, target.created);
123-
} catch (cleanupError) {
124-
throw new Error(
125-
`Backup restore failed and the incomplete target could not be cleaned: ${targetPath}`,
126-
{ cause: cleanupError },
148+
} catch (caughtCleanupError) {
149+
cleanupError = caughtCleanupError;
150+
cleanupFailed = true;
151+
}
152+
if (cleanupFailed) {
153+
// Extraction stays the primary cause; cleanup rides along as the second AggregateError entry.
154+
throw new AggregateError(
155+
[extractionError, cleanupError],
156+
`Backup restore failed and the incomplete target could not be cleaned: ${targetPath}. Cleanup error: ${formatErrorMessage(cleanupError)}`,
157+
{ cause: extractionError },
127158
);
128159
}
129160
throw new Error(`Backup restore failed; the incomplete target was cleaned: ${targetPath}`, {
130-
cause: error,
161+
cause: extractionError,
131162
});
132163
}
133164

‎src/commands/backup-verify.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ type BackupVerifyResult = {
6565
runtimeVersion: string;
6666
assetCount: number;
6767
entryCount: number;
68+
symlinkCount: number;
6869
};
6970

7071
type ArchiveEntry = {
@@ -311,6 +312,34 @@ function verifyHardlinkTargetsAgainstArchiveRoot(
311312
}
312313
}
313314

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+
314343
function formatResult(result: BackupVerifyResult): string {
315344
return [
316345
`Backup archive OK: ${result.archivePath}`,
@@ -319,6 +348,7 @@ function formatResult(result: BackupVerifyResult): string {
319348
`Runtime version: ${result.runtimeVersion}`,
320349
`Assets verified: ${result.assetCount}`,
321350
`Archive entries scanned: ${result.entryCount}`,
351+
`Symbolic links checked: ${result.symlinkCount}`,
322352
].join("\n");
323353
}
324354

@@ -732,6 +762,14 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
732762
`Archive hardlink target for ${entry.path}`,
733763
),
734764
}));
765+
const symbolicLinks = rawEntries
766+
.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+
});
735773
const normalizedEntrySet = new Set(entries.map((entry) => entry.normalized));
736774

737775
const manifestMatches = entries.filter((entry) => isRootManifestEntry(entry.normalized));
@@ -761,6 +799,7 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
761799
manifest.archiveRoot,
762800
normalizedEntrySet,
763801
);
802+
verifySymbolicLinkTargetsAgainstArchiveRoot(symbolicLinks, manifest.archiveRoot);
764803
await verifySqliteSnapshots({ archivePath, entries, manifest });
765804

766805
const result: BackupVerifyResult = {
@@ -771,6 +810,7 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
771810
runtimeVersion: manifest.runtimeVersion,
772811
assetCount: manifest.assets.length,
773812
entryCount: rawEntries.length,
813+
symlinkCount: symbolicLinks.length,
774814
};
775815

776816
return result;

0 commit comments

Comments
 (0)