Skip to content

Commit 21a9428

Browse files
authored
fix(identity): prevent cross-runtime device identity races (#120643)
* fix(identity): coordinate SQLite ownership across runtimes * fix(ci): route changed-scope fixture tests
1 parent 99afb31 commit 21a9428

15 files changed

Lines changed: 495 additions & 108 deletions

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

Lines changed: 92 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -34,24 +34,29 @@ enum DeviceIdentitySQLiteStore {
3434
}
3535

3636
private final class IdentityCoordinator {
37-
private var database: OpaquePointer?
37+
private var databases: [OpaquePointer]
3838

39-
init(database: OpaquePointer) {
40-
self.database = database
39+
init(databases: [OpaquePointer]) {
40+
self.databases = databases
4141
}
4242

4343
func release() throws {
44-
guard let database else { return }
45-
self.database = nil
46-
var releaseError: NSError?
47-
if sqlite3_exec(database, "ROLLBACK", nil, nil, nil) != SQLITE_OK {
48-
releaseError = DeviceIdentityStore.storageError(
49-
"Could not release device identity coordinator: \(String(cString: sqlite3_errmsg(database)))")
44+
let databases = self.databases
45+
self.databases = []
46+
var releaseErrors: [String] = []
47+
for database in databases.reversed() {
48+
if sqlite3_exec(database, "ROLLBACK", nil, nil, nil) != SQLITE_OK {
49+
releaseErrors.append(String(cString: sqlite3_errmsg(database)))
50+
}
51+
if sqlite3_close(database) != SQLITE_OK {
52+
releaseErrors.append("could not close coordinator database")
53+
}
5054
}
51-
if sqlite3_close(database) != SQLITE_OK, releaseError == nil {
52-
releaseError = DeviceIdentityStore.storageError("Could not close device identity coordinator")
55+
if !releaseErrors.isEmpty {
56+
throw DeviceIdentityStore.storageError(
57+
"Could not release device identity coordinator: " +
58+
releaseErrors.joined(separator: "; "))
5359
}
54-
if let releaseError { throw releaseError }
5560
}
5661
}
5762

@@ -64,7 +69,11 @@ enum DeviceIdentitySQLiteStore {
6469
afterLegacyCommit: (() throws -> Void)? = nil) throws
6570
-> DeviceIdentity
6671
{
67-
let coordinator = try self.acquireIdentityCoordinator(databaseURL: databaseURL)
72+
try self.secureDirectory(destinationStateDirURL)
73+
try self.secureDirectory(databaseURL.deletingLastPathComponent())
74+
let coordinator = try self.acquireIdentityCoordinator(
75+
databaseURL: databaseURL,
76+
destinationStateDirURL: destinationStateDirURL)
6877
do {
6978
let identity = try self.loadOrCreateOwned(
7079
databaseURL: databaseURL,
@@ -128,8 +137,6 @@ enum DeviceIdentitySQLiteStore {
128137
beforeLegacyClaim: ((DeviceIdentityPaths.LegacyIdentitySource) throws -> Void)?,
129138
afterLegacyCommit: (() throws -> Void)?) throws -> DeviceIdentity
130139
{
131-
try self.secureDirectory(destinationStateDirURL)
132-
try self.secureDirectory(databaseURL.deletingLastPathComponent())
133140
// SQLite owns an existing profile; leave any downgrade-recreated legacy source for Doctor.
134141
if self.pathMayExist(databaseURL),
135142
let existing = try self.loadExisting(databaseURL: databaseURL, profile: profile)
@@ -229,17 +236,67 @@ enum DeviceIdentitySQLiteStore {
229236
return authoritative.identity
230237
}
231238

232-
private static func acquireIdentityCoordinator(databaseURL: URL) throws -> IdentityCoordinator {
233-
let canonicalPath = self.canonicalDatabasePath(databaseURL)
234-
let digest = SHA256.hash(data: Data(canonicalPath.utf8))
239+
static func resolveDeviceIdentityCoordinatorURLs(
240+
databaseURL: URL,
241+
destinationStateDirURL: URL,
242+
temporaryDirectory: URL,
243+
uid: uid_t) -> [URL]
244+
{
245+
let canonicalDatabasePath = self.canonicalExistingAncestorPath(databaseURL)
246+
let digest = SHA256.hash(data: Data(canonicalDatabasePath.utf8))
235247
let pathHash = digest.prefix(4).map { String(format: "%02x", $0) }.joined()
236-
let lockDirectoryURL = FileManager.default.temporaryDirectory
237-
.appendingPathComponent("openclaw-\(getuid())", isDirectory: true)
238-
try self.secureCoordinatorDirectory(lockDirectoryURL)
239-
let coordinatorURL = lockDirectoryURL.appendingPathComponent(
240-
"device-identity.\(pathHash).lock.sqlite",
241-
isDirectory: false)
248+
let filename = "device-identity.\(pathHash).lock.sqlite"
249+
let suffix = "openclaw-\(uid)"
250+
let canonicalStateDirURL = URL(
251+
fileURLWithPath: self.canonicalExistingAncestorPath(destinationStateDirURL),
252+
isDirectory: true)
253+
let orderedURLs = [
254+
temporaryDirectory.standardizedFileURL
255+
.appendingPathComponent(suffix, isDirectory: true)
256+
.appendingPathComponent(filename, isDirectory: false),
257+
canonicalStateDirURL
258+
.appendingPathComponent("tmp", isDirectory: true)
259+
.appendingPathComponent(suffix, isDirectory: true)
260+
.appendingPathComponent(filename, isDirectory: false),
261+
]
262+
var seen: Set<String> = []
263+
return orderedURLs.filter { seen.insert(self.canonicalExistingAncestorPath($0)).inserted }
264+
}
242265

266+
private static func acquireIdentityCoordinator(
267+
databaseURL: URL,
268+
destinationStateDirURL: URL) throws -> IdentityCoordinator
269+
{
270+
let coordinatorURLs = self.resolveDeviceIdentityCoordinatorURLs(
271+
databaseURL: databaseURL,
272+
destinationStateDirURL: destinationStateDirURL,
273+
temporaryDirectory: FileManager.default.temporaryDirectory,
274+
uid: getuid())
275+
for coordinatorURL in coordinatorURLs {
276+
try self.secureCoordinatorDirectory(coordinatorURL.deletingLastPathComponent())
277+
}
278+
var databases: [OpaquePointer] = []
279+
do {
280+
// v2026.7.2-beta.4 through beta.7 use process temp. Keep it first until
281+
// those builds are no longer rolling-upgrade peers.
282+
for coordinatorURL in coordinatorURLs {
283+
try databases.append(self.acquireIdentityCoordinator(at: coordinatorURL))
284+
}
285+
return IdentityCoordinator(databases: databases)
286+
} catch let acquisitionError {
287+
do {
288+
try IdentityCoordinator(databases: databases).release()
289+
} catch let cleanupError {
290+
throw DeviceIdentityStore.storageError(
291+
"Could not acquire every device identity coordinator: " +
292+
"\(acquisitionError.localizedDescription); cleanup failed: " +
293+
cleanupError.localizedDescription)
294+
}
295+
throw acquisitionError
296+
}
297+
}
298+
299+
private static func acquireIdentityCoordinator(at coordinatorURL: URL) throws -> OpaquePointer {
243300
var database: OpaquePointer?
244301
let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX
245302
let openResult = sqlite3_open_v2(coordinatorURL.path, &database, flags, nil)
@@ -254,16 +311,17 @@ enum DeviceIdentitySQLiteStore {
254311
"Could not configure device identity coordinator timeout: " +
255312
String(cString: sqlite3_errmsg(database)))
256313
}
314+
try self.secureFile(coordinatorURL)
257315
var errorMessage: UnsafeMutablePointer<CChar>?
258316
guard sqlite3_exec(database, "BEGIN EXCLUSIVE", nil, nil, &errorMessage) == SQLITE_OK else {
259317
let detail = errorMessage.map { String(cString: $0) }
260318
?? String(cString: sqlite3_errmsg(database))
261319
sqlite3_free(errorMessage)
262320
throw DeviceIdentityStore.storageError("Could not acquire device identity coordinator: \(detail)")
263321
}
264-
try self.secureFile(coordinatorURL)
265-
return IdentityCoordinator(database: database)
322+
return database
266323
} catch {
324+
sqlite3_exec(database, "ROLLBACK", nil, nil, nil)
267325
sqlite3_close(database)
268326
throw error
269327
}
@@ -276,9 +334,10 @@ enum DeviceIdentitySQLiteStore {
276334
guard inspectError == ENOENT else {
277335
throw POSIXError(POSIXErrorCode(rawValue: inspectError) ?? .EIO)
278336
}
279-
if mkdir(url.path, mode_t(0o700)) != 0, errno != EEXIST {
280-
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
281-
}
337+
try FileManager.default.createDirectory(
338+
at: url,
339+
withIntermediateDirectories: true,
340+
attributes: [.posixPermissions: 0o700])
282341
guard lstat(url.path, &info) == 0 else {
283342
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
284343
}
@@ -302,19 +361,19 @@ enum DeviceIdentitySQLiteStore {
302361
}
303362
}
304363

305-
private static func canonicalDatabasePath(_ databaseURL: URL) -> String {
364+
private static func canonicalExistingAncestorPath(_ url: URL) -> String {
306365
let fileManager = FileManager.default
307-
let resolved = databaseURL.standardizedFileURL
366+
let resolved = url.standardizedFileURL
308367
var current = resolved
309368
var missingSegments: [String] = []
310369
while !fileManager.fileExists(atPath: current.path) {
311370
let parent = current.deletingLastPathComponent()
312371
guard parent.path != current.path else { return resolved.path }
313-
missingSegments.insert(current.lastPathComponent, at: 0)
372+
missingSegments.append(current.lastPathComponent)
314373
current = parent
315374
}
316375
var canonical = current.resolvingSymlinksInPath().standardizedFileURL
317-
for segment in missingSegments {
376+
for segment in missingSegments.reversed() {
318377
canonical.appendPathComponent(segment)
319378
}
320379
return canonical.standardizedFileURL.path
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import Darwin
2+
import Foundation
3+
import Testing
4+
@testable import OpenClawKit
5+
6+
private struct DeviceIdentityCoordinatorContractFixture: Decodable {
7+
let databasePath: String
8+
let stateDirectory: String
9+
let temporaryDirectory: String
10+
let uid: UInt32
11+
let orderedExpectedPaths: [String]
12+
}
13+
14+
private enum DeviceIdentityCoordinatorContractFixtureLoader {
15+
static func load() throws -> DeviceIdentityCoordinatorContractFixture {
16+
let fixtureURL = try self.findFixtureURL(startingAt: URL(fileURLWithPath: #filePath))
17+
return try JSONDecoder().decode(
18+
DeviceIdentityCoordinatorContractFixture.self,
19+
from: Data(contentsOf: fixtureURL))
20+
}
21+
22+
private static func findFixtureURL(startingAt fileURL: URL) throws -> URL {
23+
var directory = fileURL.deletingLastPathComponent()
24+
while directory.path != "/" {
25+
let candidate = directory.appendingPathComponent(
26+
"test/fixtures/device-identity-coordinator-contract.json")
27+
if FileManager.default.fileExists(atPath: candidate.path) {
28+
return candidate
29+
}
30+
directory.deleteLastPathComponent()
31+
}
32+
throw NSError(domain: "DeviceIdentityCoordinatorContractFixtureLoader", code: 1)
33+
}
34+
}
35+
36+
struct DeviceIdentityCoordinatorContractTests {
37+
@Test func `matches shared ordered path vector`() throws {
38+
let fixture = try DeviceIdentityCoordinatorContractFixtureLoader.load()
39+
let resolved = DeviceIdentitySQLiteStore.resolveDeviceIdentityCoordinatorURLs(
40+
databaseURL: URL(fileURLWithPath: fixture.databasePath),
41+
destinationStateDirURL: URL(fileURLWithPath: fixture.stateDirectory, isDirectory: true),
42+
temporaryDirectory: URL(fileURLWithPath: fixture.temporaryDirectory, isDirectory: true),
43+
uid: uid_t(fixture.uid))
44+
45+
#expect(resolved.map(\.path) == fixture.orderedExpectedPaths)
46+
}
47+
}

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import CryptoKit
2+
import Darwin
23
import Foundation
34
import SQLite3
45
import Testing
@@ -442,6 +443,22 @@ struct DeviceIdentityStoreTests {
442443
FileManager.default.attributesOfItem(atPath: fixture.databaseURL.path)[.posixPermissions] as? NSNumber)
443444
#expect(directoryMode.intValue & 0o777 == 0o700)
444445
#expect(databaseMode.intValue & 0o777 == 0o600)
446+
447+
let coordinatorURLs = DeviceIdentitySQLiteStore.resolveDeviceIdentityCoordinatorURLs(
448+
databaseURL: fixture.databaseURL,
449+
destinationStateDirURL: fixture.destination,
450+
temporaryDirectory: FileManager.default.temporaryDirectory,
451+
uid: getuid())
452+
#expect(coordinatorURLs.count == 2)
453+
for coordinatorURL in coordinatorURLs {
454+
let coordinatorDirectoryMode = try #require(
455+
FileManager.default.attributesOfItem(
456+
atPath: coordinatorURL.deletingLastPathComponent().path)[.posixPermissions] as? NSNumber)
457+
let coordinatorFileMode = try #require(
458+
FileManager.default.attributesOfItem(atPath: coordinatorURL.path)[.posixPermissions] as? NSNumber)
459+
#expect(coordinatorDirectoryMode.intValue & 0o777 == 0o700)
460+
#expect(coordinatorFileMode.intValue & 0o777 == 0o600)
461+
}
445462
}
446463

447464
@Test

‎scripts/ci-changed-scope.mjs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ const SKILLS_PYTHON_SCOPE_RE = /^(skills\/|skills\/pyproject\.toml$)/;
3939
const INSTALL_SMOKE_WORKFLOW_SCOPE_RE = /^\.github\/workflows\/install-smoke\.yml$/;
4040
const NATIVE_PROTOCOL_GEN_RE = /^apps\/shared\/OpenClawKit\/Sources\/OpenClawProtocol\//;
4141
const APPLE_SWIFT_CONFIG_RE = /^config\/(?:swiftformat|swiftlint\.yml)$/;
42+
const APPLE_SHARED_CONTRACT_FIXTURE_RE =
43+
/^test\/fixtures\/(?:device-identity-coordinator|talk-config)-contract\.json$/;
4244
const MACOS_NATIVE_RE =
4345
/^(apps\/macos\/|apps\/macos-mlx-tts\/|apps\/ios\/|apps\/shared\/|apps\/swabble\/|Swabble\/)/;
4446
const MACOS_SCRIPT_SCOPE_RE =
@@ -142,7 +144,10 @@ export function detectChangedScope(changedPaths) {
142144

143145
if (
144146
!NATIVE_PROTOCOL_GEN_RE.test(path) &&
145-
(MACOS_NATIVE_RE.test(path) || MACOS_SCRIPT_SCOPE_RE.test(path) || isAppleSwiftConfig)
147+
(MACOS_NATIVE_RE.test(path) ||
148+
MACOS_SCRIPT_SCOPE_RE.test(path) ||
149+
APPLE_SHARED_CONTRACT_FIXTURE_RE.test(path) ||
150+
isAppleSwiftConfig)
146151
) {
147152
runMacos = true;
148153
}

‎scripts/test-projects.test-support.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1830,6 +1830,7 @@ const releaseCheck = "test/release-check.test.ts";
18301830
const installDocker = "test-install-sh-docker";
18311831
const changedScope = "src/scripts/ci-changed-scope.test.ts";
18321832
const changedScopeTests = [
1833+
"src/scripts/ci-changed-scope.contract-fixtures.test.ts",
18331834
"src/scripts/ci-changed-scope.control-ui.test.ts",
18341835
"src/scripts/ci-changed-scope.native-i18n.test.ts",
18351836
changedScope,

‎src/config/paths.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -405,8 +405,10 @@ export const DEFAULT_GATEWAY_PORT = 18789;
405405
* Gateway lock directory inside the selected state tree.
406406
* Default: $OPENCLAW_STATE_DIR/tmp/openclaw-<uid> (uid suffix when available).
407407
*/
408-
export function resolveGatewayLockDir(stateDir: string = resolveStateDir()): string {
409-
const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
408+
export function resolveGatewayLockDir(
409+
stateDir: string = resolveStateDir(),
410+
uid: number | undefined = typeof process.getuid === "function" ? process.getuid() : undefined,
411+
): string {
410412
const suffix = uid != null ? `openclaw-${uid}` : "openclaw";
411413
// Clean break: older binaries still use process temp and do not exclude a
412414
// state-local binary during a mixed-version upgrade.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import path from "node:path";
2+
import { resolveGatewayLockDir } from "../config/paths.js";
3+
import { resolvePathViaExistingAncestorSync } from "./boundary-path.js";
4+
import { sha256HexPrefix } from "./crypto-digest.js";
5+
6+
function resolveDeviceIdentityCoordinatorFilename(databasePath: string): string {
7+
const canonicalPath = resolvePathViaExistingAncestorSync(databasePath);
8+
const databaseHash = sha256HexPrefix(canonicalPath, 8);
9+
return `device-identity.${databaseHash}.lock.sqlite`;
10+
}
11+
12+
export function resolveDeviceIdentityCoordinatorPath(
13+
databasePath: string,
14+
lockDir: string,
15+
): string {
16+
return path.join(lockDir, resolveDeviceIdentityCoordinatorFilename(databasePath));
17+
}
18+
19+
export function resolveDeviceIdentityCoordinatorPaths(params: {
20+
databasePath: string;
21+
stateDir: string;
22+
temporaryDirectory: string;
23+
uid: number | undefined;
24+
}): string[] {
25+
const suffix = params.uid === undefined ? "openclaw" : `openclaw-${params.uid}`;
26+
const filename = resolveDeviceIdentityCoordinatorFilename(params.databasePath);
27+
const canonicalStateDir = resolvePathViaExistingAncestorSync(params.stateDir);
28+
const orderedPaths = [
29+
path.join(path.resolve(params.temporaryDirectory), suffix, filename),
30+
path.join(resolveGatewayLockDir(canonicalStateDir, params.uid), filename),
31+
];
32+
const seen = new Set<string>();
33+
return orderedPaths.filter((coordinatorPath) => {
34+
const canonicalPath = resolvePathViaExistingAncestorSync(coordinatorPath);
35+
if (seen.has(canonicalPath)) {
36+
return false;
37+
}
38+
seen.add(canonicalPath);
39+
return true;
40+
});
41+
}

0 commit comments

Comments
 (0)