Skip to content

Commit 1c37c8c

Browse files
authored
fix(exec): scope reusable approvals to their working directory (#129636)
* fix(exec): bind durable approvals to working directory * chore(apps): refresh native string inventory * test(node-host): preserve prepared working directory * fix(exec): use shared path safety facade * fix(exec): revalidate approved directory identity
1 parent 4c4152e commit 1c37c8c

44 files changed

Lines changed: 1258 additions & 313 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/.i18n/native-source.json‎

Lines changed: 44 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/macos/Sources/OpenClaw/ExecAllowlistMatcher.swift‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import Foundation
33
import JavaScriptCore
44

55
enum ExecAllowlistMatcher {
6-
private static let hashedArgPatternPrefix = "sha256:argv:"
6+
private static let cwdBoundArgPatternPrefix = "sha256:cwd-argv:v1:"
7+
private static let legacyArgPatternPrefix = "sha256:argv:"
78

89
static func match(entries: [ExecAllowlistEntry], resolution: ExecCommandResolution?) -> ExecAllowlistEntry? {
910
guard let resolution, !entries.isEmpty else { return nil }
@@ -40,7 +41,12 @@ enum ExecAllowlistMatcher {
4041
}
4142
continue
4243
}
43-
if let argv = resolution.argv, matchesArgPattern(argPattern, argv: argv) {
44+
if entry.source == "allow-always", !argPattern.hasPrefix(self.cwdBoundArgPatternPrefix) {
45+
continue
46+
}
47+
if let argv = resolution.argv,
48+
self.matchesArgPattern(argPattern, argv: argv, cwd: resolution.cwd)
49+
{
4450
return entry
4551
}
4652
case .invalid:
@@ -97,9 +103,13 @@ enum ExecAllowlistMatcher {
97103
/// use NUL separators plus a trailing sentinel; hand-authored patterns use
98104
/// one space between parsed arguments. Redirect-shaped tokens stay literal
99105
/// because resolution does not retain enough shell syntax provenance.
100-
private static func matchesArgPattern(_ argPattern: String, argv: [String]) -> Bool {
101-
if argPattern.hasPrefix(self.hashedArgPatternPrefix) {
102-
return argPattern == self.hashedArgPattern(argv: argv)
106+
private static func matchesArgPattern(_ argPattern: String, argv: [String], cwd: String?) -> Bool {
107+
if argPattern.hasPrefix(self.cwdBoundArgPatternPrefix) {
108+
guard let cwd else { return false }
109+
return argPattern == self.cwdBoundArgPattern(argv: argv, cwd: cwd)
110+
}
111+
if argPattern.hasPrefix(self.legacyArgPatternPrefix) {
112+
return false
103113
}
104114
let nul = "\0"
105115
let arguments = Array(argv.dropFirst())
@@ -123,13 +133,15 @@ enum ExecAllowlistMatcher {
123133
return result.toBool()
124134
}
125135

126-
private static func hashedArgPattern(argv: [String]) -> String {
136+
private static func cwdBoundArgPattern(argv: [String], cwd: String) -> String {
137+
let normalizedCwd = ExecCommandResolution.canonicalApprovalCwd(cwd)
127138
let arguments = Array(argv.dropFirst())
128-
let subject = "\(arguments.count)\0" + arguments
139+
let argvSubject = "\(arguments.count)\0" + arguments
129140
.map { "\($0.data(using: .utf8)?.count ?? 0)\0\($0)\0" }
130141
.joined()
142+
let subject = "\(normalizedCwd.data(using: .utf8)?.count ?? 0)\0\(normalizedCwd)\0\(argvSubject)"
131143
let digest = SHA256.hash(data: Data(subject.utf8))
132-
return self.hashedArgPatternPrefix + digest.map { String(format: "%02x", $0) }.joined()
144+
return self.cwdBoundArgPatternPrefix + digest.map { String(format: "%02x", $0) }.joined()
133145
}
134146

135147
private static func matches(pattern: String, target: String) -> Bool {

‎apps/macos/Sources/OpenClaw/ExecApprovalEvaluation.swift‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ enum ExecApprovalEvaluator {
248248
envOverrides: [String: String]?,
249249
agentId: String?) async -> ExecApprovalEvaluation
250250
{
251+
let effectiveCwd = ExecCommandResolution.canonicalApprovalCwd(cwd)
251252
let trimmedAgent = agentId?.trimmingCharacters(in: .whitespacesAndNewlines)
252253
let normalizedAgentId = (trimmedAgent?.isEmpty == false) ? trimmedAgent : nil
253254
let approvals = ExecApprovalsStore.resolve(agentId: normalizedAgentId)
@@ -263,11 +264,11 @@ enum ExecApprovalEvaluator {
263264
let allowlistResolutions = ExecCommandResolution.resolveForAllowlist(
264265
command: command,
265266
rawCommand: allowlistRawCommand,
266-
cwd: cwd,
267+
cwd: effectiveCwd,
267268
env: env)
268269
let allowAlwaysPatterns = ExecCommandResolution.resolveAllowAlwaysPatterns(
269270
command: command,
270-
cwd: cwd,
271+
cwd: effectiveCwd,
271272
env: env,
272273
rawCommand: allowlistRawCommand)
273274
let boundCommand = ExecCommandResolution.bindForAllowlistExecution(

‎apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift‎

Lines changed: 25 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ struct ExecHostRequest: Codable {
131131
var policySnapshot: OpenClawSystemRunApprovalPolicySnapshot?
132132
}
133133

134-
private struct ExecHostRunResult: Codable {
134+
struct ExecHostRunResult: Codable {
135135
var exitCode: Int?
136136
var timedOut: Bool
137137
var success: Bool
@@ -165,7 +165,7 @@ struct ExecHostError: Codable, Error {
165165
var reason: String?
166166
}
167167

168-
private struct ExecHostResponse: Codable {
168+
struct ExecHostResponse: Codable {
169169
var type: String
170170
var id: String
171171
var ok: Bool
@@ -737,7 +737,7 @@ enum ExecApprovalsPromptPresenter {
737737
case .allowOnce:
738738
"Allow Once"
739739
case .allowAlways:
740-
"Always Allow"
740+
"Always Allow Here"
741741
case .deny:
742742
"Don't Allow"
743743
}
@@ -881,7 +881,7 @@ extension ExecApprovalsPromptPresenter {
881881
#endif
882882

883883
@MainActor
884-
private enum ExecHostExecutor {
884+
enum ExecHostExecutor {
885885
static func handle(_ request: ExecHostRequest) async -> ExecHostResponse {
886886
let validatedRequest: ExecHostValidatedRequest
887887
switch ExecHostRequestEvaluator.validateRequest(request) {
@@ -890,12 +890,21 @@ private enum ExecHostExecutor {
890890
case let .failure(error):
891891
return self.errorResponse(error)
892892
}
893+
let effectiveCwd = ExecCommandResolution.canonicalApprovalCwd(request.cwd)
894+
guard let approvedCwdSnapshot = ExecCommandResolution.captureApprovalCwdSnapshot(effectiveCwd)
895+
else {
896+
return self.errorResponse(
897+
code: "UNAVAILABLE",
898+
message: "SYSTEM_RUN_DENIED: approval requires an existing canonical cwd",
899+
reason: "approval-required")
900+
}
893901

894902
let context = await self.buildContext(
895903
request: request,
896904
command: validatedRequest.command,
897905
rawCommand: validatedRequest.evaluationRawCommand,
898-
displayCommand: validatedRequest.displayCommand)
906+
displayCommand: validatedRequest.displayCommand,
907+
cwd: effectiveCwd)
899908
let approvalSource = validatedRequest.approvalSource
900909
let security = ExecHostRequestEvaluator.effectiveSecurity(
901910
context: context,
@@ -918,7 +927,7 @@ private enum ExecHostExecutor {
918927
guard let decision = await ExecApprovalsPromptPresenter.prompt(
919928
ExecApprovalPromptRequest(
920929
command: context.displayCommand,
921-
cwd: request.cwd,
930+
cwd: effectiveCwd,
922931
host: "node",
923932
security: context.security.rawValue,
924933
ask: context.ask.rawValue,
@@ -996,7 +1005,7 @@ private enum ExecHostExecutor {
9961005
persistAllowlist: persistAllowlist,
9971006
delayedPolicySnapshot: validatedRequest.delayedPolicySnapshot)
9981007
let timeoutSec = request.timeoutMs.flatMap { Double($0) / 1000.0 }
999-
let cwd = request.cwd
1008+
let cwd = effectiveCwd
10001009
let env = context.env
10011010
if case .failure = ExecApprovalsStore.commitExecution(executionCommit) {
10021011
return self.approvalStoreErrorResponse()
@@ -1009,7 +1018,12 @@ private enum ExecHostExecutor {
10091018
command: executionCommand,
10101019
cwd: cwd,
10111020
env: env,
1012-
timeout: timeoutSec)
1021+
timeout: timeoutSec,
1022+
beforeSpawn: {
1023+
ExecCommandResolution.revalidateApprovalCwdSnapshot(approvedCwdSnapshot)
1024+
? nil
1025+
: ExecCommandResolution.approvalCwdDriftDeniedMessage
1026+
})
10131027
}
10141028
return await self.commandResponse(execution: execution)
10151029
}
@@ -1018,13 +1032,14 @@ private enum ExecHostExecutor {
10181032
request: ExecHostRequest,
10191033
command: [String],
10201034
rawCommand: String?,
1021-
displayCommand: String) async -> ExecApprovalEvaluation
1035+
displayCommand: String,
1036+
cwd: String) async -> ExecApprovalEvaluation
10221037
{
10231038
await ExecApprovalEvaluator.evaluate(
10241039
command: command,
10251040
rawCommand: rawCommand,
10261041
displayCommand: displayCommand,
1027-
cwd: request.cwd,
1042+
cwd: cwd,
10281043
envOverrides: request.env,
10291044
agentId: request.agentId)
10301045
}
@@ -1048,53 +1063,6 @@ private enum ExecHostExecutor {
10481063
message: "PERMISSION_MISSING: screenRecording",
10491064
reason: "permission:screenRecording")
10501065
}
1051-
1052-
private static func commandResponse(
1053-
execution: Task<ShellExecutor.ShellResult, Never>) async -> ExecHostResponse
1054-
{
1055-
let result = await execution.value
1056-
let payload = ExecHostRunResult(
1057-
exitCode: result.exitCode,
1058-
timedOut: result.timedOut,
1059-
success: result.success,
1060-
stdout: ExecHostOutputLimiter.truncate(result.stdout),
1061-
stderr: ExecHostOutputLimiter.truncate(result.stderr),
1062-
error: result.errorMessage)
1063-
return self.successResponse(payload)
1064-
}
1065-
1066-
private static func errorResponse(
1067-
_ error: ExecHostError) -> ExecHostResponse
1068-
{
1069-
ExecHostResponse(
1070-
type: "response",
1071-
id: UUID().uuidString,
1072-
ok: false,
1073-
payload: nil,
1074-
error: error)
1075-
}
1076-
1077-
private static func errorResponse(
1078-
code: String,
1079-
message: String,
1080-
reason: String?) -> ExecHostResponse
1081-
{
1082-
ExecHostResponse(
1083-
type: "exec-res",
1084-
id: UUID().uuidString,
1085-
ok: false,
1086-
payload: nil,
1087-
error: ExecHostError(code: code, message: message, reason: reason))
1088-
}
1089-
1090-
private static func successResponse(_ payload: ExecHostRunResult) -> ExecHostResponse {
1091-
ExecHostResponse(
1092-
type: "exec-res",
1093-
id: UUID().uuidString,
1094-
ok: true,
1095-
payload: payload,
1096-
error: nil)
1097-
}
10981066
}
10991067

11001068
private final class ExecApprovalsSocketLifecycleLease: @unchecked Sendable {

‎apps/macos/Sources/OpenClaw/ExecApprovalsStore.swift‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ enum ExecApprovalsStore {
118118
private static let defaultAsk: ExecAsk = .off
119119
private static let defaultAskFallback: ExecSecurity = .deny
120120
private static let defaultAutoAllowSkills = false
121+
private static let cwdBoundArgPatternPrefix = "sha256:cwd-argv:v1:"
121122

122123
#if compiler(>=6.4)
123124
nonisolated(nonsending) static func withStateDirectory<T>(
@@ -787,6 +788,15 @@ extension ExecApprovalsStore {
787788
let now = Date().timeIntervalSince1970 * 1000
788789
for grant in grants {
789790
let incoming = grant.match
791+
if incoming.argPattern?.hasPrefix(self.cwdBoundArgPatternPrefix) == true {
792+
// Renewing trust for one executable also clears its inactive
793+
// pre-cwd grants, which can never authorize after this upgrade.
794+
allowlist.removeAll { item in
795+
item.pattern == incoming.pattern &&
796+
item.source == "allow-always" &&
797+
item.argPattern?.hasPrefix(self.cwdBoundArgPatternPrefix) != true
798+
}
799+
}
790800
if let index = allowlist.firstIndex(where: {
791801
self.allowlistEntryMatchKey($0) == self.allowlistEntryMatchKey(incoming)
792802
}) {
@@ -846,7 +856,35 @@ extension ExecApprovalsStore {
846856
}
847857

848858
private static func shouldRecordLastUsedCommand(for entry: ExecAllowlistEntry) -> Bool {
849-
!(entry.argPattern?.hasPrefix("sha256:argv:") ?? false)
859+
!(entry.argPattern?.hasPrefix("sha256:") ?? false)
860+
}
861+
862+
@discardableResult
863+
static func removeObsoleteGeneratedAllowAlwaysEntries() -> Result<Int, ExecApprovalsMutationError> {
864+
var removed = 0
865+
let result = self.updateFile { file in
866+
var agents = file.agents ?? [:]
867+
for (key, var agent) in agents {
868+
let current = agent.allowlist ?? []
869+
let retained = current.filter { item in
870+
let pattern = item.pattern.trimmingCharacters(in: .whitespacesAndNewlines)
871+
let keep = item.source != "allow-always" ||
872+
pattern.hasPrefix("=command:") ||
873+
pattern.hasPrefix("=node-command:") ||
874+
item.argPattern?.hasPrefix(self.cwdBoundArgPatternPrefix) == true
875+
if !keep { removed += 1 }
876+
return keep
877+
}
878+
if retained.count != current.count {
879+
agent.allowlist = retained
880+
agents[key] = agent
881+
}
882+
}
883+
if removed > 0 {
884+
file.agents = agents
885+
}
886+
}
887+
return result.map { removed }
850888
}
851889

852890
@discardableResult

0 commit comments

Comments
 (0)