fix: windows path style in snapshot (#742)

This commit is contained in:
Nico 2026-04-04 17:21:13 +02:00 committed by GitHub
parent 43d9cb837f
commit 9e7f1bf138
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 216 additions and 25 deletions

View file

@ -102,6 +102,12 @@ describe("RestoreForm", () => {
filesSkipped: 0, filesSkipped: 0,
}); });
}), }),
http.get("/api/v1/volumes/filesystem/browse", () => {
return HttpResponse.json({
path: "/",
directories: [{ name: "restore-target", path: "/restore-target", type: "dir" }],
});
}),
); );
render( render(
@ -114,8 +120,26 @@ describe("RestoreForm", () => {
/>, />,
); );
expect(
screen.getByText(
"This snapshot was created from source paths that do not match this Zerobyte server or the current linked volume. Restoring to the original location is unavailable. Restore it to a custom location, or download it instead.",
),
).toBeTruthy();
expect(screen.getByRole("button", { name: "Original location" }).hasAttribute("disabled")).toBe(true);
expect(screen.getByRole("button", { name: "Restore All" }).hasAttribute("disabled")).toBe(true);
await userEvent.click(screen.getByRole("button", { name: "Change" }));
await userEvent.click(await screen.findByRole("button", { name: "restore-target" }));
await waitFor(() => {
expect(screen.getByRole("button", { name: "Restore All" }).hasAttribute("disabled")).toBe(false);
});
const row = await screen.findByRole("button", { name: "mnt" }); const row = await screen.findByRole("button", { name: "mnt" });
await userEvent.click(within(row).getByRole("checkbox")); await userEvent.click(within(row).getByRole("checkbox"));
await waitFor(() => {
expect(screen.getByRole("button", { name: "Restore 1 item" }).hasAttribute("disabled")).toBe(false);
});
await userEvent.click(screen.getByRole("button", { name: "Restore 1 item" })); await userEvent.click(screen.getByRole("button", { name: "Restore 1 item" }));
await waitFor(() => { await waitFor(() => {
@ -123,6 +147,7 @@ describe("RestoreForm", () => {
snapshotId: "snap-1", snapshotId: "snap-1",
include: ["/mnt"], include: ["/mnt"],
selectedItemKind: "dir", selectedItemKind: "dir",
targetPath: "/restore-target",
overwrite: "always", overwrite: "always",
}); });
}); });

View file

@ -1,8 +1,9 @@
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import { ChevronDown, Download, FolderOpen, RotateCcw } from "lucide-react"; import { AlertTriangle, ChevronDown, Download, FolderOpen, RotateCcw } from "lucide-react";
import { Button } from "~/client/components/ui/button"; import { Button } from "~/client/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "~/client/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipTrigger } from "~/client/components/ui/tooltip";
import { Alert, AlertDescription, AlertTitle } from "~/client/components/ui/alert";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/client/components/ui/card";
import { Input } from "~/client/components/ui/input"; import { Input } from "~/client/components/ui/input";
import { Label } from "~/client/components/ui/label"; import { Label } from "~/client/components/ui/label";
@ -22,6 +23,7 @@ import { RestoreProgress } from "~/client/components/restore-progress";
import { restoreSnapshotMutation } from "~/client/api-client/@tanstack/react-query.gen"; import { restoreSnapshotMutation } from "~/client/api-client/@tanstack/react-query.gen";
import { type RestoreCompletedEvent, useServerEvents } from "~/client/hooks/use-server-events"; import { type RestoreCompletedEvent, useServerEvents } from "~/client/hooks/use-server-events";
import { OVERWRITE_MODES, type OverwriteMode } from "@zerobyte/core/restic"; import { OVERWRITE_MODES, type OverwriteMode } from "@zerobyte/core/restic";
import { isPathWithin } from "@zerobyte/core/utils";
import type { Repository } from "~/client/lib/types"; import type { Repository } from "~/client/lib/types";
import { handleRepositoryError } from "~/client/lib/errors"; import { handleRepositoryError } from "~/client/lib/errors";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
@ -35,15 +37,27 @@ interface RestoreFormProps {
returnPath: string; returnPath: string;
queryBasePath?: string; queryBasePath?: string;
displayBasePath?: string; displayBasePath?: string;
hasNonPosixSnapshotPaths?: boolean;
} }
export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath, displayBasePath }: RestoreFormProps) { export function RestoreForm({
repository,
snapshotId,
returnPath,
queryBasePath,
displayBasePath,
hasNonPosixSnapshotPaths = false,
}: RestoreFormProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { addEventListener } = useServerEvents(); const { addEventListener } = useServerEvents();
const snapshotBasePath = queryBasePath ?? "/"; const snapshotBasePath = queryBasePath ?? "/";
const hasMismatchedDisplayBasePath = displayBasePath && !isPathWithin(displayBasePath, snapshotBasePath);
const restoreRequiresCustomTarget = hasNonPosixSnapshotPaths || hasMismatchedDisplayBasePath;
const [restoreLocation, setRestoreLocation] = useState<RestoreLocation>("original"); const [restoreLocation, setRestoreLocation] = useState<RestoreLocation>(
restoreRequiresCustomTarget ? "custom" : "original",
);
const [customTargetPath, setCustomTargetPath] = useState(""); const [customTargetPath, setCustomTargetPath] = useState("");
const [overwriteMode, setOverwriteMode] = useState<OverwriteMode>("always"); const [overwriteMode, setOverwriteMode] = useState<OverwriteMode>("always");
const [showAdvanced, setShowAdvanced] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false);
@ -55,6 +69,15 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
const [selectedPaths, setSelectedPaths] = useState<Set<string>>(new Set()); const [selectedPaths, setSelectedPaths] = useState<Set<string>>(new Set());
const [selectedPathKind, setSelectedPathKind] = useState<"file" | "dir" | null>(null); const [selectedPathKind, setSelectedPathKind] = useState<"file" | "dir" | null>(null);
const trimmedCustomTargetPath = customTargetPath.trim();
const hasCustomTargetPath = trimmedCustomTargetPath !== "";
const selectedPathCount = selectedPaths.size;
useEffect(() => {
if (restoreRequiresCustomTarget) {
setRestoreLocation("custom");
}
}, [restoreRequiresCustomTarget]);
useEffect(() => { useEffect(() => {
const abortController = new AbortController(); const abortController = new AbortController();
@ -114,13 +137,13 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
}); });
const handleRestore = useCallback(() => { const handleRestore = useCallback(() => {
const excludeXattrArray = excludeXattr const excludeXattrValues = excludeXattr
?.split(",") .split(",")
.map((s) => s.trim()) .map((value) => value.trim())
.filter(Boolean); .filter(Boolean);
const isCustomLocation = restoreLocation === "custom"; const isCustomLocation = restoreLocation === "custom";
const targetPath = isCustomLocation && customTargetPath.trim() ? customTargetPath.trim() : undefined; const targetPath = isCustomLocation && hasCustomTargetPath ? trimmedCustomTargetPath : undefined;
const includePaths = Array.from(selectedPaths); const includePaths = Array.from(selectedPaths);
@ -135,7 +158,7 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
snapshotId, snapshotId,
include: includePaths.length > 0 ? includePaths : undefined, include: includePaths.length > 0 ? includePaths : undefined,
selectedItemKind: includePaths.length === 1 ? (selectedPathKind ?? undefined) : undefined, selectedItemKind: includePaths.length === 1 ? (selectedPathKind ?? undefined) : undefined,
excludeXattr: excludeXattrArray && excludeXattrArray.length > 0 ? excludeXattrArray : undefined, excludeXattr: excludeXattrValues.length > 0 ? excludeXattrValues : undefined,
targetPath, targetPath,
overwrite: overwriteMode, overwrite: overwriteMode,
}, },
@ -144,8 +167,9 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
repository.shortId, repository.shortId,
snapshotId, snapshotId,
excludeXattr, excludeXattr,
hasCustomTargetPath,
restoreLocation, restoreLocation,
customTargetPath, trimmedCustomTargetPath,
selectedPaths, selectedPaths,
selectedPathKind, selectedPathKind,
overwriteMode, overwriteMode,
@ -182,13 +206,15 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
} }
}, []); }, []);
const canRestore = restoreLocation === "original" || customTargetPath.trim(); const canRestore = restoreRequiresCustomTarget
const canDownload = selectedPaths.size <= 1; ? hasCustomTargetPath
: restoreLocation === "original" || hasCustomTargetPath;
const canDownload = selectedPathCount <= 1;
const isRestoreRunning = isRestoring || isRestoreActive; const isRestoreRunning = isRestoring || isRestoreActive;
function getDownloadButtonText(): string { function getDownloadButtonText(): string {
if (selectedPaths.size > 0) { if (selectedPathCount > 0) {
return `Download ${selectedPaths.size} ${selectedPaths.size === 1 ? "item" : "items"}`; return `Download ${selectedPathCount} ${selectedPathCount === 1 ? "item" : "items"}`;
} }
return "Download All"; return "Download All";
} }
@ -197,8 +223,8 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
if (isRestoreRunning) { if (isRestoreRunning) {
return "Restoring..."; return "Restoring...";
} }
if (selectedPaths.size > 0) { if (selectedPathCount > 0) {
return `Restore ${selectedPaths.size} ${selectedPaths.size === 1 ? "item" : "items"}`; return `Restore ${selectedPathCount} ${selectedPathCount === 1 ? "item" : "items"}`;
} }
return "Restore All"; return "Restore All";
} }
@ -240,6 +266,18 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
<div className="space-y-6"> <div className="space-y-6">
{isRestoreRunning && <RestoreProgress repositoryId={repository.shortId} snapshotId={snapshotId} />} {isRestoreRunning && <RestoreProgress repositoryId={repository.shortId} snapshotId={snapshotId} />}
{restoreRequiresCustomTarget && (
<Alert variant="warning">
<AlertTriangle className="size-4" />
<AlertTitle>Source paths do not match</AlertTitle>
<AlertDescription>
This snapshot was created from source paths that do not match this Zerobyte server or the current linked
volume. Restoring to the original location is unavailable. Restore it to a custom location, or download
it instead.
</AlertDescription>
</Alert>
)}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Restore Location</CardTitle> <CardTitle>Restore Location</CardTitle>
@ -253,6 +291,7 @@ export function RestoreForm({ repository, snapshotId, returnPath, queryBasePath,
size="sm" size="sm"
className="flex justify-start gap-2" className="flex justify-start gap-2"
onClick={() => setRestoreLocation("original")} onClick={() => setRestoreLocation("original")}
disabled={!!restoreRequiresCustomTarget}
> >
<RotateCcw size={16} className="mr-1" /> <RotateCcw size={16} className="mr-1" />
Original location Original location

View file

@ -68,4 +68,39 @@ describe("SnapshotFileBrowser", () => {
expect(await screen.findByRole("button", { name: "project" })).toBeTruthy(); expect(await screen.findByRole("button", { name: "project" })).toBeTruthy();
}); });
test("renders snapshots backed up from Windows absolute paths", async () => {
const requests: string[] = [];
server.use(
http.get("/api/v1/repositories/:shortId/snapshots/:snapshotId/files", ({ request }) => {
const url = new URL(request.url);
requests.push(url.searchParams.get("path") ?? "");
return HttpResponse.json({
files: [
{ name: "tmp", path: "/tmp", type: "dir" },
{ name: "source", path: "/tmp/source", type: "dir" },
],
});
}),
);
render(
<SnapshotFileBrowser
snapshot={fromAny({
short_id: "snap-1",
time: "2026-04-02T00:00:00.000Z",
paths: ["d:\\some\\path"],
})}
repositoryId="repo-1"
/>,
);
await waitFor(() => {
expect(requests[0]).toBe("/");
});
expect(await screen.findByRole("button", { name: "tmp" })).toBeTruthy();
});
}); });

View file

@ -30,7 +30,8 @@ export const SnapshotFileBrowser = (props: Props) => {
const { snapshot, repositoryId, backupId, displayBasePath, onDeleteSnapshot, isDeletingSnapshot } = props; const { snapshot, repositoryId, backupId, displayBasePath, onDeleteSnapshot, isDeletingSnapshot } = props;
const { formatDateTime } = useTimeFormat(); const { formatDateTime } = useTimeFormat();
const queryBasePath = findCommonAncestor(snapshot.paths); const hasNonPosixSnapshotPaths = snapshot.paths.some((path) => !path.startsWith("/"));
const queryBasePath = hasNonPosixSnapshotPaths ? "/" : findCommonAncestor(snapshot.paths);
return ( return (
<div className="space-y-4"> <div className="space-y-4">

View file

@ -7,10 +7,11 @@ type Props = {
returnPath: string; returnPath: string;
queryBasePath?: string; queryBasePath?: string;
displayBasePath?: string; displayBasePath?: string;
hasNonPosixSnapshotPaths?: boolean;
}; };
export function RestoreSnapshotPage(props: Props) { export function RestoreSnapshotPage(props: Props) {
const { returnPath, snapshotId, repository, queryBasePath, displayBasePath } = props; const { returnPath, snapshotId, repository, queryBasePath, displayBasePath, hasNonPosixSnapshotPaths } = props;
return ( return (
<RestoreForm <RestoreForm
@ -19,6 +20,7 @@ export function RestoreSnapshotPage(props: Props) {
returnPath={returnPath} returnPath={returnPath}
queryBasePath={queryBasePath} queryBasePath={queryBasePath}
displayBasePath={displayBasePath} displayBasePath={displayBasePath}
hasNonPosixSnapshotPaths={hasNonPosixSnapshotPaths}
/> />
); );
} }

View file

@ -26,12 +26,15 @@ export const Route = createFileRoute("/(dashboard)/backups/$backupId/$snapshotId
}), }),
]); ]);
const hasNonPosixSnapshotPaths = snapshot.paths.some((path) => !path.startsWith("/"));
return { return {
snapshot, snapshot,
repository, repository,
schedule: schedule.data, schedule: schedule.data,
queryBasePath: findCommonAncestor(snapshot.paths), queryBasePath: hasNonPosixSnapshotPaths ? "/" : findCommonAncestor(snapshot.paths),
displayBasePath: getVolumeMountPath(schedule.data.volume), displayBasePath: getVolumeMountPath(schedule.data.volume),
hasNonPosixSnapshotPaths,
}; };
}, },
head: ({ params }) => ({ head: ({ params }) => ({
@ -55,7 +58,7 @@ export const Route = createFileRoute("/(dashboard)/backups/$backupId/$snapshotId
function RouteComponent() { function RouteComponent() {
const { backupId, snapshotId } = Route.useParams(); const { backupId, snapshotId } = Route.useParams();
const { repository, queryBasePath, displayBasePath } = Route.useLoaderData(); const { repository, queryBasePath, displayBasePath, hasNonPosixSnapshotPaths } = Route.useLoaderData();
return ( return (
<RestoreSnapshotPage <RestoreSnapshotPage
@ -64,6 +67,7 @@ function RouteComponent() {
repository={repository} repository={repository}
queryBasePath={queryBasePath} queryBasePath={queryBasePath}
displayBasePath={displayBasePath} displayBasePath={displayBasePath}
hasNonPosixSnapshotPaths={hasNonPosixSnapshotPaths}
/> />
); );
} }

View file

@ -25,7 +25,15 @@ export const Route = createFileRoute("/(dashboard)/repositories/$repositoryId/$s
} }
} }
return { snapshot, repository, queryBasePath: findCommonAncestor(snapshot.paths), displayBasePath }; const hasNonPosixSnapshotPaths = snapshot.paths.some((path) => !path.startsWith("/"));
return {
snapshot,
repository,
queryBasePath: hasNonPosixSnapshotPaths ? "/" : findCommonAncestor(snapshot.paths),
displayBasePath,
hasNonPosixSnapshotPaths,
};
}, },
staticData: { staticData: {
breadcrumb: (match) => [ breadcrumb: (match) => [
@ -48,7 +56,7 @@ export const Route = createFileRoute("/(dashboard)/repositories/$repositoryId/$s
function RouteComponent() { function RouteComponent() {
const { repositoryId, snapshotId } = Route.useParams(); const { repositoryId, snapshotId } = Route.useParams();
const { repository, queryBasePath, displayBasePath } = Route.useLoaderData(); const { repository, queryBasePath, displayBasePath, hasNonPosixSnapshotPaths } = Route.useLoaderData();
return ( return (
<RestoreSnapshotPage <RestoreSnapshotPage
@ -57,6 +65,7 @@ function RouteComponent() {
snapshotId={snapshotId} snapshotId={snapshotId}
queryBasePath={queryBasePath} queryBasePath={queryBasePath}
displayBasePath={displayBasePath} displayBasePath={displayBasePath}
hasNonPosixSnapshotPaths={hasNonPosixSnapshotPaths}
/> />
); );
} }

View file

@ -376,6 +376,28 @@ describe("repositoriesService.dumpSnapshot", () => {
}), }),
); );
}); });
test("downloads the full snapshot from root when source paths are non-posix", async () => {
const { organizationId, userId, shortId } = await setupDumpSnapshotScenario({
snapshotId: "snapshot-windows",
basePath: "/tmp/repro/source",
snapshotPaths: ["d:\\some\\path"],
});
const result = await withContext({ organizationId, userId }, () =>
repositoriesService.dumpSnapshot(shortId, "snapshot-windows"),
);
expect(result.filename).toBe("snapshot-snapshot-windows.tar");
expect(result.contentType).toBe("application/x-tar");
expect(await readStreamText(result.stream)).toBe(
JSON.stringify({
snapshotRef: "snapshot-windows",
path: "/",
archive: true,
}),
);
});
}); });
describe("repositoriesService.restoreSnapshot", () => { describe("repositoriesService.restoreSnapshot", () => {
@ -383,7 +405,7 @@ describe("repositoriesService.restoreSnapshot", () => {
vi.restoreAllMocks(); vi.restoreAllMocks();
}); });
const setupRestoreSnapshotScenario = async () => { const setupRestoreSnapshotScenario = async (paths = ["/var/lib/zerobyte/volumes/vol123/_data"]) => {
const organizationId = session.organizationId; const organizationId = session.organizationId;
const repository = await createTestRepository(organizationId); const repository = await createTestRepository(organizationId);
@ -392,7 +414,7 @@ describe("repositoriesService.restoreSnapshot", () => {
id: "snapshot-restore", id: "snapshot-restore",
short_id: "snapshot-restore", short_id: "snapshot-restore",
time: new Date().toISOString(), time: new Date().toISOString(),
paths: ["/var/lib/zerobyte/volumes/vol123/_data"], paths,
hostname: "host", hostname: "host",
}, },
]); ]);
@ -456,6 +478,50 @@ describe("repositoriesService.restoreSnapshot", () => {
}), }),
); );
}); });
test("rejects original-location restore for snapshots with non-posix source paths", async () => {
const { organizationId, userId, repositoryShortId, restoreMock } = await setupRestoreSnapshotScenario([
"d:\\some\\path",
]);
await expect(
withContext({ organizationId, userId }, () =>
repositoriesService.restoreSnapshot(repositoryShortId, "snapshot-restore", {
include: ["/tmp/source"],
selectedItemKind: "dir",
}),
),
).rejects.toThrow("Original location restore is unavailable for this snapshot");
expect(restoreMock).not.toHaveBeenCalled();
});
test("allows restore-all to a custom target for snapshots with non-posix source paths", async () => {
const { organizationId, userId, repositoryShortId, restoreMock } = await setupRestoreSnapshotScenario([
"d:\\some\\path",
]);
const targetPath = await fs.mkdtemp(nodePath.join(process.cwd(), "restore-target-"));
try {
await withContext({ organizationId, userId }, () =>
repositoriesService.restoreSnapshot(repositoryShortId, "snapshot-restore", { targetPath }),
);
} finally {
await fs.rm(targetPath, { recursive: true, force: true });
}
expect(restoreMock).toHaveBeenCalledWith(
expect.objectContaining({
backend: "local",
}),
"snapshot-restore",
targetPath,
expect.objectContaining({
organizationId,
basePath: "/",
}),
);
});
}); });
describe("repositoriesService.getRetentionCategories", () => { describe("repositoriesService.getRetentionCategories", () => {

View file

@ -16,7 +16,8 @@ export const prepareSnapshotDump = (params: {
const archiveFilename = `snapshot-${sanitizeFilenamePart(snapshotId)}.tar`; const archiveFilename = `snapshot-${sanitizeFilenamePart(snapshotId)}.tar`;
const normalizedRequestedPath = normalizeAbsolutePath(requestedPath); const normalizedRequestedPath = normalizeAbsolutePath(requestedPath);
const basePath = normalizeAbsolutePath(findCommonAncestor(snapshotPaths)); const hasNonPosixSnapshotPaths = snapshotPaths.some((snapshotPath) => !snapshotPath.startsWith("/"));
const basePath = hasNonPosixSnapshotPaths ? "/" : findCommonAncestor(snapshotPaths);
if (basePath === "/") { if (basePath === "/") {
return { return {

View file

@ -307,6 +307,7 @@ const restoreSnapshot = async (
snapshotId: string, snapshotId: string,
options?: { options?: {
include?: string[]; include?: string[];
selectedItemKind?: "file" | "dir";
exclude?: string[]; exclude?: string[];
excludeXattr?: string[]; excludeXattr?: string[];
delete?: boolean; delete?: boolean;
@ -334,7 +335,15 @@ const restoreSnapshot = async (
} }
const { paths } = await getSnapshotDetails(repository.shortId, snapshotId); const { paths } = await getSnapshotDetails(repository.shortId, snapshotId);
const basePath = findCommonAncestor(paths); const hasNonPosixSnapshotPaths = paths.some((path) => !path.startsWith("/"));
if (hasNonPosixSnapshotPaths && !options?.targetPath) {
throw new BadRequestError(
"Original location restore is unavailable for this snapshot. Restore it to a custom location instead.",
);
}
const basePath = hasNonPosixSnapshotPaths ? "/" : findCommonAncestor(paths);
const releaseLock = await repoMutex.acquireShared(repository.id, `restore:${snapshotId}`); const releaseLock = await repoMutex.acquireShared(repository.id, `restore:${snapshotId}`);
try { try {