Skip to content

Commit b834477

Browse files
authored
fix(cli): refuse live state reset and uninstall (#125253)
* fix(cli): guard live state cleanup * fix(cli): preserve linked paths on cleanup failure * fix(cli): retain gateway ownership through cleanup * fix(cli): keep cleanup planning read-only * fix(cli): skip mutating bootstrap for cleanup * fix(apple): keep identity locks sandbox-writable * docs(apple): clarify identity lock domains
1 parent 7170a62 commit b834477

28 files changed

Lines changed: 1339 additions & 288 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawKit/DeviceIdentitySQLiteStore.swift‎

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ import CryptoKit
22
import Darwin
33
import Foundation
44
import OpenClawNativeState
5+
#if canImport(Security)
6+
import Security
7+
#endif
58
import SQLite3
69

710
enum DeviceIdentitySQLiteStore {
@@ -13,6 +16,20 @@ enum DeviceIdentitySQLiteStore {
1316
private static let maximumLegacyIdentityBytes = 64 * 1024
1417
private static let doctorClaimSuffix = ".doctor-importing"
1518
private static let nativeClaimSuffix = ".native-importing"
19+
private static let appSandboxed: Bool = {
20+
#if os(macOS) && canImport(Security)
21+
guard let task = SecTaskCreateFromSelf(nil) else {
22+
return ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] != nil
23+
}
24+
let value = SecTaskCopyValueForEntitlement(
25+
task,
26+
"com.apple.security.app-sandbox" as CFString,
27+
nil)
28+
return (value as? Bool) == true
29+
#else
30+
return true
31+
#endif
32+
}()
1633

1734
private struct LegacyClaim {
1835
let source: DeviceIdentityPaths.LegacyIdentitySource
@@ -252,10 +269,35 @@ enum DeviceIdentitySQLiteStore {
252269
return authoritative.identity
253270
}
254271

272+
static func resolveStateLifecycleRuntimeDirectory(
273+
destinationStateDirURL: URL,
274+
appSandboxed: Bool) -> URL
275+
{
276+
if !appSandboxed {
277+
return URL(fileURLWithPath: "/tmp", isDirectory: true)
278+
}
279+
// Sandboxed app and extension processes share container-owned state that Node cannot
280+
// traverse. CLI-shared macOS state is unentitled and uses the common /tmp namespace.
281+
return destinationStateDirURL.standardizedFileURL
282+
.appendingPathComponent("tmp", isDirectory: true)
283+
}
284+
285+
static func resolveStateDatabaseCoordinatorURL(
286+
databaseURL: URL,
287+
runtimeDirectory: URL,
288+
uid: uid_t) -> URL
289+
{
290+
let canonicalDatabasePath = self.canonicalExistingAncestorPath(databaseURL)
291+
let digest = SHA256.hash(data: Data(canonicalDatabasePath.utf8))
292+
let pathHash = digest.prefix(4).map { String(format: "%02x", $0) }.joined()
293+
return runtimeDirectory.standardizedFileURL
294+
.appendingPathComponent("openclaw-state-locks-\(uid)", isDirectory: true)
295+
.appendingPathComponent("state-lifecycle.\(pathHash).lock.sqlite", isDirectory: false)
296+
}
297+
255298
static func resolveDeviceIdentityCoordinatorURLs(
256299
databaseURL: URL,
257300
destinationStateDirURL: URL,
258-
temporaryDirectory: URL,
259301
uid: uid_t) -> [URL]
260302
{
261303
let canonicalDatabasePath = self.canonicalExistingAncestorPath(databaseURL)
@@ -266,35 +308,34 @@ enum DeviceIdentitySQLiteStore {
266308
let canonicalStateDirURL = URL(
267309
fileURLWithPath: self.canonicalExistingAncestorPath(destinationStateDirURL),
268310
isDirectory: true)
269-
let orderedURLs = [
270-
temporaryDirectory.standardizedFileURL
271-
.appendingPathComponent(suffix, isDirectory: true)
272-
.appendingPathComponent(filename, isDirectory: false),
311+
return [
273312
canonicalStateDirURL
274313
.appendingPathComponent("tmp", isDirectory: true)
275314
.appendingPathComponent(suffix, isDirectory: true)
276315
.appendingPathComponent(filename, isDirectory: false),
277316
]
278-
var seen: Set<String> = []
279-
return orderedURLs.filter { seen.insert(self.canonicalExistingAncestorPath($0)).inserted }
280317
}
281318

282319
private static func acquireIdentityCoordinator(
283320
databaseURL: URL,
284321
destinationStateDirURL: URL) throws -> IdentityCoordinator
285322
{
286-
let coordinatorURLs = self.resolveDeviceIdentityCoordinatorURLs(
323+
let coordinatorURLs = [
324+
self.resolveStateDatabaseCoordinatorURL(
325+
databaseURL: databaseURL,
326+
runtimeDirectory: self.resolveStateLifecycleRuntimeDirectory(
327+
destinationStateDirURL: destinationStateDirURL,
328+
appSandboxed: self.appSandboxed),
329+
uid: getuid()),
330+
] + self.resolveDeviceIdentityCoordinatorURLs(
287331
databaseURL: databaseURL,
288332
destinationStateDirURL: destinationStateDirURL,
289-
temporaryDirectory: FileManager.default.temporaryDirectory,
290333
uid: getuid())
291334
for coordinatorURL in coordinatorURLs {
292335
try self.secureCoordinatorDirectory(coordinatorURL.deletingLastPathComponent())
293336
}
294337
var databases: [OpaquePointer] = []
295338
do {
296-
// v2026.7.2-beta.4 through beta.7 use process temp. Keep it first until
297-
// those builds are no longer rolling-upgrade peers.
298339
for coordinatorURL in coordinatorURLs {
299340
try databases.append(self.acquireIdentityCoordinator(at: coordinatorURL))
300341
}

‎apps/shared/OpenClawKit/Tests/OpenClawKitTests/DeviceIdentityCoordinatorContractTests.swift‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import Testing
66
private struct DeviceIdentityCoordinatorContractFixture: Decodable {
77
let databasePath: String
88
let stateDirectory: String
9-
let temporaryDirectory: String
9+
let runtimeDirectory: String
1010
let uid: UInt32
11+
let stateCoordinatorPath: String
1112
let orderedExpectedPaths: [String]
1213
}
1314

@@ -34,14 +35,32 @@ private enum DeviceIdentityCoordinatorContractFixtureLoader {
3435
}
3536

3637
struct DeviceIdentityCoordinatorContractTests {
38+
@Test func `uses a sandbox writable lifecycle runtime`() {
39+
let stateDirectory = URL(fileURLWithPath: "/sandbox/group/OpenClaw", isDirectory: true)
40+
41+
#expect(
42+
DeviceIdentitySQLiteStore.resolveStateLifecycleRuntimeDirectory(
43+
destinationStateDirURL: stateDirectory,
44+
appSandboxed: true).path == "/sandbox/group/OpenClaw/tmp")
45+
#expect(
46+
DeviceIdentitySQLiteStore.resolveStateLifecycleRuntimeDirectory(
47+
destinationStateDirURL: stateDirectory,
48+
appSandboxed: false).path == "/tmp")
49+
}
50+
3751
@Test func `matches shared ordered path vector`() throws {
3852
let fixture = try DeviceIdentityCoordinatorContractFixtureLoader.load()
53+
let databaseURL = URL(fileURLWithPath: fixture.databasePath)
3954
let resolved = DeviceIdentitySQLiteStore.resolveDeviceIdentityCoordinatorURLs(
40-
databaseURL: URL(fileURLWithPath: fixture.databasePath),
55+
databaseURL: databaseURL,
4156
destinationStateDirURL: URL(fileURLWithPath: fixture.stateDirectory, isDirectory: true),
42-
temporaryDirectory: URL(fileURLWithPath: fixture.temporaryDirectory, isDirectory: true),
57+
uid: uid_t(fixture.uid))
58+
let stateCoordinator = DeviceIdentitySQLiteStore.resolveStateDatabaseCoordinatorURL(
59+
databaseURL: databaseURL,
60+
runtimeDirectory: URL(fileURLWithPath: fixture.runtimeDirectory, isDirectory: true),
4361
uid: uid_t(fixture.uid))
4462

63+
#expect(stateCoordinator.path == fixture.stateCoordinatorPath)
4564
#expect(resolved.map(\.path) == fixture.orderedExpectedPaths)
4665
}
4766
}

‎apps/shared/OpenClawKit/Tests/OpenClawKitTests/DeviceIdentityStoreTests.swift‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,9 +471,8 @@ struct DeviceIdentityStoreTests {
471471
let coordinatorURLs = DeviceIdentitySQLiteStore.resolveDeviceIdentityCoordinatorURLs(
472472
databaseURL: fixture.databaseURL,
473473
destinationStateDirURL: fixture.destination,
474-
temporaryDirectory: FileManager.default.temporaryDirectory,
475474
uid: getuid())
476-
#expect(coordinatorURLs.count == 2)
475+
#expect(coordinatorURLs.count == 1)
477476
for coordinatorURL in coordinatorURLs {
478477
let coordinatorDirectoryMode = try #require(
479478
FileManager.default.attributesOfItem(

‎docs/cli/reset.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ openclaw reset --scope full --yes --non-interactive
3838
## Notes
3939

4040
- Run `openclaw backup create` first for a restorable snapshot before removing local state.
41+
- Before removing the state directory, `full` requires exclusive state ownership. If an unmanaged or externally supervised Gateway is still running, reset refuses and asks you to stop it first.
4142
- Workspace setup state and attestations are rows in the shared SQLite database, so `full` removes them with the state directory; there are no current attestation sidecar files to remove separately.
4243
- Without `--scope`, `openclaw reset` prompts interactively for the scope to remove.
4344
- `--non-interactive` is only valid when both `--scope` and `--yes` are set.

‎docs/cli/uninstall.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ openclaw uninstall --dry-run
4242

4343
- Run `openclaw backup create` first for a restorable snapshot before removing
4444
state or workspaces.
45+
- Before removing state, `--state` requires exclusive state ownership. If an
46+
unmanaged or externally supervised Gateway is still running, uninstall
47+
refuses and asks you to stop it first.
4548
- `--state` preserves configured workspace directories unless `--workspace` is
4649
also selected.
4750

‎src/cli/command-catalog.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
115115
},
116116
{ commandPath: ["message"], policy: { loadPlugins: "never" } },
117117
{ commandPath: ["docs"], policy: { configGuard: "skip" } },
118+
// Destructive maintenance owns a validity-aware, non-observing config read.
119+
// Startup migrations would mutate the SQLite state these commands may refuse to remove.
120+
{ commandPath: ["reset"], policy: { configGuard: "skip" } },
121+
{ commandPath: ["uninstall"], policy: { configGuard: "skip" } },
118122
{
119123
commandPath: ["channels"],
120124
policy: {

‎src/cli/command-startup-policy.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ describe("command-startup-policy", () => {
3232
["config", "validate"],
3333
["config", "schema"],
3434
["docs"],
35+
["reset"],
36+
["uninstall"],
3537
["agent", "exec"],
3638
["status"],
3739
["agents", "bindings"],

‎src/commands/cleanup-command.test-support.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { vi } from "vitest";
33
import { createNonExitingRuntime, type RuntimeEnv } from "../runtime.js";
44
import type { MockFn } from "../test-utils/vitest-mock-fn.js";
55

6-
const resolveCleanupPlanFromDisk = vi.fn();
6+
const resolveCleanupPlanForDryRun = vi.fn();
7+
export const resolveCleanupPlanForRemoval = vi.fn();
78
const removePath = vi.fn();
89
export const listAgentSessionDirs = vi.fn();
910
export const prepareLegacyWorkspaceStateReset = vi.fn();
@@ -28,14 +29,16 @@ vi.mock("../config/config.js", () => ({
2829
get isNixMode() {
2930
return cleanupConfigState.isNixMode;
3031
},
32+
resolveConfigPath: () => "/tmp/.openclaw/openclaw.json",
3133
}));
3234

3335
vi.mock("../daemon/service.js", () => ({
3436
resolveGatewayService: () => gatewayService,
3537
}));
3638

3739
vi.mock("./cleanup-plan.js", () => ({
38-
resolveCleanupPlanFromDisk,
40+
resolveCleanupPlanForDryRun,
41+
resolveCleanupPlanForRemoval,
3942
}));
4043

4144
vi.mock("./cleanup-utils.js", () => ({
@@ -51,14 +54,16 @@ export function createCleanupCommandRuntime() {
5154

5255
export function resetCleanupCommandMocks() {
5356
vi.clearAllMocks();
54-
resolveCleanupPlanFromDisk.mockReturnValue({
57+
const cleanupPlan = {
5558
stateDir: "/tmp/.openclaw",
5659
configPath: "/tmp/.openclaw/openclaw.json",
5760
oauthDir: "/tmp/.openclaw/credentials",
5861
configInsideState: true,
5962
oauthInsideState: true,
6063
workspaceDirs: ["/tmp/.openclaw/workspace"],
61-
});
64+
};
65+
resolveCleanupPlanForDryRun.mockResolvedValue(cleanupPlan);
66+
resolveCleanupPlanForRemoval.mockResolvedValue(cleanupPlan);
6267
removePath.mockResolvedValue({ ok: true });
6368
listAgentSessionDirs.mockResolvedValue(["/tmp/.openclaw/agents/main/sessions"]);
6469
prepareLegacyWorkspaceStateReset.mockImplementation((workspaceDir: string) => ({ workspaceDir }));

0 commit comments

Comments
 (0)