Skip to content

Commit d9fa6aa

Browse files
committed
fix(server): harden service backup preservation, UNC paths, and lock edges
1 parent 05c9ee0 commit d9fa6aa

6 files changed

Lines changed: 139 additions & 22 deletions

File tree

‎apps/server/src/cli/uninstall.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,22 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => {
7474
assert.isFalse(
7575
yield* fs.exists(path.join(root, "userdata", "db-backup", "partial.staging")),
7676
);
77+
78+
// If `runtime/db-backup` cannot be enumerated for a non-NotFound reason (e.g. ENOTDIR),
79+
// uninstall aborts before deleting `runtimeDir`.
80+
yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true });
81+
yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3"), "");
82+
yield* fs.writeFileString(path.join(runtimeDir, "db-backup"), "not-a-directory");
83+
const failedError = yield* runUninstall({ baseDir: root, assumeYes: true }).pipe(
84+
Effect.provideService(BootService.BootService, bootService),
85+
Effect.provideService(HostProcess.Platform, "linux"),
86+
Effect.provideService(HostProcess.Environment, {}),
87+
Effect.provideService(HostProcess.IsExecutable, false),
88+
Effect.flip,
89+
);
90+
assert.equal(failedError._tag, "CliUninstallError");
91+
assert.include(failedError.message, "Could not inspect pending update database backups");
92+
assert.isTrue(yield* fs.exists(path.join(runtimeDir, "versions", "1.0.0", "t3")));
7793
}).pipe(Effect.scoped),
7894
);
7995

‎apps/server/src/cli/uninstall.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,18 @@ const preserveUnrecoveredDatabaseBackups = Effect.fn("cli.uninstall.preserve_db_
201201
const fs = yield* FileSystem.FileSystem;
202202
const path = yield* Path.Path;
203203
const backupRoot = path.join(input.runtimeDir, "db-backup");
204-
const entries = yield* fs.readDirectory(backupRoot).pipe(Effect.orElseSucceed(() => []));
204+
const entries = yield* fs.readDirectory(backupRoot).pipe(
205+
Effect.catchIf(
206+
(error) => error.reason._tag === "NotFound",
207+
() => Effect.succeed([] as Array<string>),
208+
),
209+
Effect.mapError(
210+
() =>
211+
new CliUninstallError({
212+
reason: `Could not inspect pending update database backups under ${backupRoot}.`,
213+
}),
214+
),
215+
);
205216
const preserved = entries.filter((entry) => !entry.endsWith(".staging"));
206217
if (preserved.length === 0) return;
207218
const destinationRoot = path.join(input.userdataDir, "db-backup");

‎apps/server/src/cloud/serviceProtocol.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,8 @@ export const isValidServiceUpdateId = (id: string): boolean =>
208208
/^[A-Za-z0-9._-]{1,128}$/.test(id) && id !== "." && id !== "..";
209209

210210
const isAbsoluteServiceDatabasePath = (dbPath: string): boolean =>
211-
!dbPath.includes("\0") && (dbPath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(dbPath));
211+
!dbPath.includes("\0") &&
212+
(dbPath.startsWith("/") || dbPath.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(dbPath));
212213

213214
const isRecord = (value: unknown): value is Record<string, unknown> =>
214215
typeof value === "object" && value !== null && !Array.isArray(value);

‎apps/server/src/cloud/serviceSelectionLock.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,22 @@ export async function acquireServiceSelectionLock(selectionPath: string): Promis
4343
} catch (error) {
4444
const code = (error as NodeJS.ErrnoException).code ?? "";
4545
const windowsContention =
46-
(code === "EPERM" || code === "EACCES") &&
47-
(NodePath.sep === "\\" || NodeFS.existsSync(lock));
46+
(code === "EPERM" || code === "EACCES") && NodeFS.existsSync(lock);
4847
if (!["EEXIST", "ENOTEMPTY"].includes(code) && !windowsContention) throw error;
4948
}
5049
let owners: string[];
5150
try {
5251
owners = NodeFS.readdirSync(lock);
5352
} catch (error) {
54-
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
53+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
54+
if (Date.now() >= deadline)
55+
throw new Error(
56+
`Service selection is locked at ${lock}. Retry when the other operation finishes.`,
57+
{ cause: error },
58+
);
59+
await new Promise<void>((resolve) => setTimeout(resolve, 10));
60+
continue;
61+
}
5562
throw error;
5663
}
5764
if (owners.length === 1) {

‎apps/server/src/serviceLauncher.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2401,4 +2401,74 @@ setInterval(() => {}, 1_000);
24012401
}),
24022402
),
24032403
);
2404+
2405+
it.effect(
2406+
"accepts Windows UNC database paths and recovers missing databases through a symlinked home",
2407+
() =>
2408+
runNode(
2409+
Effect.gen(function* () {
2410+
const fs = yield* FileSystem.FileSystem;
2411+
const path = yield* Path.Path;
2412+
2413+
const uncDecoded = decodeServiceState({
2414+
protocol: SERVICE_LAUNCHER_PROTOCOL,
2415+
activeVersion: "1.0.0",
2416+
update: {
2417+
id: "unc-update",
2418+
fromVersion: "1.0.0",
2419+
targetVersion: "1.1.0",
2420+
dbPath: "\\\\server\\share\\t3\\userdata\\statev2.sqlite",
2421+
status: "pending",
2422+
},
2423+
});
2424+
assert.equal(uncDecoded?.update?.status, "pending");
2425+
2426+
const outer = yield* fs.makeTempDirectoryScoped({
2427+
prefix: "t3-service-launcher-symlink-home-",
2428+
});
2429+
const realHome = path.join(outer, "real-home");
2430+
const symlinkHome = path.join(outer, "symlink-home");
2431+
yield* fs.makeDirectory(path.join(realHome, "userdata"), { recursive: true });
2432+
yield* fs.symlink(realHome, symlinkHome);
2433+
2434+
const symlinkDbPath = path.join(symlinkHome, "userdata", "statev2.sqlite");
2435+
const backupDir = path.join(symlinkHome, "runtime", "db-backup", "interrupted-restore");
2436+
yield* fs.makeDirectory(backupDir, { recursive: true });
2437+
yield* fs.writeFileString(path.join(backupDir, "database"), "restored-through-symlink");
2438+
yield* fs.writeFileString(path.join(backupDir, ".restore-pending"), "");
2439+
2440+
const statePath = path.join(symlinkHome, "runtime", "service-state.json");
2441+
yield* Effect.promise(() =>
2442+
writeServiceState(statePath, {
2443+
protocol: SERVICE_LAUNCHER_PROTOCOL,
2444+
activeVersion: "1.0.0",
2445+
update: {
2446+
id: "interrupted-restore",
2447+
fromVersion: "1.0.0",
2448+
targetVersion: "1.1.0",
2449+
dbPath: symlinkDbPath,
2450+
status: "pending",
2451+
},
2452+
}),
2453+
);
2454+
2455+
const controlDir = path.join(outer, "control");
2456+
yield* fs.makeDirectory(controlDir, { recursive: true });
2457+
yield* Effect.promise(() =>
2458+
recoverServiceLauncherUninstall({
2459+
baseDir: symlinkHome,
2460+
controlDir,
2461+
acl: trustedTestAcl,
2462+
}),
2463+
);
2464+
2465+
assert.equal(
2466+
yield* fs.readFileString(path.join(realHome, "userdata", "statev2.sqlite")),
2467+
"restored-through-symlink",
2468+
);
2469+
const recoveredState = yield* Effect.promise(() => readServiceState(statePath));
2470+
assert.equal(recoveredState.update?.status, "failed");
2471+
}),
2472+
),
2473+
);
24042474
});

‎apps/server/src/serviceLauncher.ts‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,11 @@ const databaseBackupDir = (baseDir: string, updateId: string) => {
310310

311311
function resolvePathForContainment(baseDir: string, candidate: string) {
312312
const useWin32 =
313-
IS_WINDOWS || /^[A-Za-z]:[\\/]/.test(baseDir) || /^[A-Za-z]:[\\/]/.test(candidate);
313+
IS_WINDOWS ||
314+
baseDir.startsWith("\\\\") ||
315+
candidate.startsWith("\\\\") ||
316+
/^[A-Za-z]:[\\/]/.test(baseDir) ||
317+
/^[A-Za-z]:[\\/]/.test(candidate);
314318
const pathMod = useWin32 ? NodePath.win32 : NodePath.posix;
315319
const normalizeCase = (value: string) => (useWin32 ? value.toLowerCase() : value);
316320
if (!pathMod.isAbsolute(baseDir) || !pathMod.isAbsolute(candidate)) return undefined;
@@ -668,9 +672,9 @@ async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate
668672
throw createStateDirOwnedDuringBackupError();
669673
}
670674
const stagingDir = `${backupDir}.staging`;
671-
await NodeFSP.rm(stagingDir, { recursive: true, force: true });
672-
await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
673675
try {
676+
await NodeFSP.rm(stagingDir, { recursive: true, force: true });
677+
await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
674678
for (const suffix of DB_FILE_SUFFIXES) {
675679
const source = `${pending.dbPath}${suffix}`;
676680
if (suffix !== "" && !(await pathExists(source))) continue;
@@ -709,25 +713,31 @@ async function markDatabaseRestorePending(backupDir: string): Promise<void> {
709713
}
710714
}
711715

712-
// Resolve symlink targets even if a crashed cp -c left the final target missing.
713-
async function restoreTarget(path: string): Promise<string> {
716+
// Resolve symlink targets and missing leaves under symlinked ancestors.
717+
async function restoreTarget(path: string, depth = 0): Promise<string> {
714718
let current = path;
715-
for (let hops = 0; hops < 40; hops++) {
719+
for (let hops = depth; hops < 40; hops++) {
716720
try {
717721
return await NodeFSP.realpath(current);
718722
} catch (cause) {
719-
if ((cause as NodeJS.ErrnoException).code !== "ENOENT") throw cause;
723+
const code = (cause as NodeJS.ErrnoException).code;
724+
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
720725
}
721726
const link = await NodeFSP.readlink(current).catch((cause: unknown) => {
722727
const code = (cause as NodeJS.ErrnoException).code;
723-
if (code === "ENOENT" || code === "EINVAL") return undefined;
728+
if (code === "ENOENT" || code === "EINVAL" || code === "ENOTDIR") return undefined;
724729
throw cause;
725730
});
726-
if (link === undefined) return current;
727-
// Do not normalize .. before following directory symlinks; match filesystem resolution.
728-
current = NodePath.isAbsolute(link)
729-
? link
730-
: `${await NodeFSP.realpath(NodePath.dirname(current))}${NodePath.sep}${link}`;
731+
if (link !== undefined) {
732+
// Do not normalize .. before following directory symlinks; match filesystem resolution.
733+
const resolvedParent = await restoreTarget(NodePath.dirname(current), hops + 1);
734+
current = NodePath.isAbsolute(link) ? link : `${resolvedParent}${NodePath.sep}${link}`;
735+
continue;
736+
}
737+
const parent = NodePath.dirname(current);
738+
if (parent === current) return current;
739+
const resolvedParent = await restoreTarget(parent, hops + 1);
740+
return NodePath.join(resolvedParent, NodePath.basename(current));
731741
}
732742
throw new Error(`Too many symbolic links resolving ${path}.`);
733743
}
@@ -738,13 +748,15 @@ async function isDatabaseRestoreTargetInsideBaseDir(
738748
): Promise<boolean> {
739749
if (!isDatabasePathInsideBaseDir(baseDir, dbPath)) return false;
740750
try {
741-
const realBaseDir = await NodeFSP.realpath(baseDir).catch(() => baseDir);
751+
const realBaseDir = await restoreTarget(baseDir);
742752
const mainTarget = await restoreTarget(dbPath);
743753
if (resolvePathForContainment(realBaseDir, mainTarget) === undefined) return false;
744754
for (const suffix of DB_FILE_SUFFIXES) {
745-
const livePath = suffix === "" ? dbPath : `${mainTarget}${suffix}`;
746-
const target = await restoreTarget(livePath);
747-
if (resolvePathForContainment(realBaseDir, target) === undefined) return false;
755+
if (suffix === "") continue;
756+
for (const candidate of [`${dbPath}${suffix}`, `${mainTarget}${suffix}`]) {
757+
const target = await restoreTarget(candidate);
758+
if (resolvePathForContainment(realBaseDir, target) === undefined) return false;
759+
}
748760
}
749761
return true;
750762
} catch {

0 commit comments

Comments
 (0)