Skip to content

Commit 67433ff

Browse files
authored
fix: apply workspace permission changes to active runs (#132407)
* fix: apply workspace permission changes to active runs * fix: preserve permission lifecycle invariants and hermetic tests * test: remove obsolete updater fixture argument * fix: repair permission-change CI and scanner reporting * refactor: trim run-loop aliases and validate scanner fixture paths * fix: prepare permission-bound prompt sections before model continuation * fix: fence permission prompt preparation across startup and replacement * fix: align permission fixtures and deduplicate run authority checks * test: keep permission checks aligned with shared labels and revocation cases
1 parent 5de1376 commit 67433ff

133 files changed

Lines changed: 5061 additions & 1459 deletions

File tree

Some content is hidden

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

‎.github/workflows/opengrep-precise-full.yml‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,19 @@ jobs:
6060
mkdir -p .opengrep-out
6161
scripts/run-opengrep.sh --sarif --error
6262
63+
- name: Prepare SARIF for GitHub Code Scanning
64+
id: github-sarif
65+
if: always() && hashFiles('.opengrep-out/precise.sarif') != ''
66+
run: >-
67+
node scripts/opengrep-github-sarif.mjs .opengrep-out/precise.sarif
68+
> .opengrep-out/precise.github.sarif
69+
6370
- name: Upload SARIF to GitHub Code Scanning
6471
uses: github/codeql-action/upload-sarif@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
65-
# Only upload if the scan actually produced a SARIF file.
66-
if: always() && hashFiles('.opengrep-out/precise.sarif') != ''
72+
# Never publish a partial conversion; the raw audit artifact stays intact.
73+
if: always() && steps.github-sarif.outcome == 'success'
6774
with:
68-
sarif_file: .opengrep-out/precise.sarif
75+
sarif_file: .opengrep-out/precise.github.sarif
6976
category: opengrep-full
7077

7178
- name: Upload SARIF as workflow artifact

‎.github/workflows/opengrep-precise.yml‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,19 @@ jobs:
9191
mkdir -p .opengrep-out
9292
scripts/run-opengrep.sh --changed --sarif --error
9393
94+
- name: Prepare SARIF for GitHub Code Scanning
95+
id: github-sarif
96+
if: always() && hashFiles('.opengrep-out/precise.sarif') != ''
97+
run: >-
98+
node scripts/opengrep-github-sarif.mjs .opengrep-out/precise.sarif
99+
> .opengrep-out/precise.github.sarif
100+
94101
- name: Upload SARIF to GitHub Code Scanning
95102
uses: github/codeql-action/upload-sarif@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
96-
# Only upload if the scan actually produced a SARIF file.
97-
if: always() && hashFiles('.opengrep-out/precise.sarif') != ''
103+
# Never publish a partial conversion; the raw audit artifact stays intact.
104+
if: always() && steps.github-sarif.outcome == 'success'
98105
with:
99-
sarif_file: .opengrep-out/precise.sarif
106+
sarif_file: .opengrep-out/precise.github.sarif
100107
category: opengrep-pr-diff
101108

102109
- name: Upload SARIF as workflow artifact

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6394,6 +6394,7 @@ public struct SessionRow: Codable, Sendable {
63946394
public let spawnedworkspacedir: String?
63956395
public let spawnedcwd: String?
63966396
public let permissionmode: SessionPermissionMode?
6397+
public let permissionmodepending: Bool?
63976398
public let sessionroot: String?
63986399
public let createdvia: AnyCodable?
63996400
public let createdactor: SessionCreatedActor?
@@ -6468,6 +6469,7 @@ public struct SessionRow: Codable, Sendable {
64686469
spawnedworkspacedir: String? = nil,
64696470
spawnedcwd: String? = nil,
64706471
permissionmode: SessionPermissionMode? = nil,
6472+
permissionmodepending: Bool? = nil,
64716473
sessionroot: String? = nil,
64726474
createdvia: AnyCodable? = nil,
64736475
createdactor: SessionCreatedActor? = nil,
@@ -6541,6 +6543,7 @@ public struct SessionRow: Codable, Sendable {
65416543
self.spawnedworkspacedir = spawnedworkspacedir
65426544
self.spawnedcwd = spawnedcwd
65436545
self.permissionmode = permissionmode
6546+
self.permissionmodepending = permissionmodepending
65446547
self.sessionroot = sessionroot
65456548
self.createdvia = createdvia
65466549
self.createdactor = createdactor
@@ -6616,6 +6619,7 @@ public struct SessionRow: Codable, Sendable {
66166619
case spawnedworkspacedir = "spawnedWorkspaceDir"
66176620
case spawnedcwd = "spawnedCwd"
66186621
case permissionmode = "permissionMode"
6622+
case permissionmodepending = "permissionModePending"
66196623
case sessionroot = "sessionRoot"
66206624
case createdvia = "createdVia"
66216625
case createdactor = "createdActor"

‎docs/gateway/permission-modes.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ New sessions, including managed worktree sessions, inherit the configured global
3232

3333
The Control UI permission picker labels Default with the agent's resolved exec posture when it matches a session mode, for example **Default (Guarded)** for `tools.exec.mode: "ask"` without a stricter host approval policy. Resolution includes global settings, agent overrides, and host approval floors. Without those settings or sandboxing, the default is full access. Allowlist-only policy and non-equivalent `security`/`ask` pairs, including `ask: "always"`, keep the plain **Default** label. Agents whose sandbox configuration could apply to their sessions also keep plain **Default**, because effective policy cannot be stated at agent scope. This is display metadata, not an authorization decision or a filesystem-access guarantee; tool policy still applies. Selecting Default clears the session override; it does not save the displayed mode into the session.
3434

35+
## Change permissions during a task
36+
37+
Choose a mode from the chat composer's **Permissions** menu. The picker shows **Applying permissions…** until the running task acknowledges the change. Other clients viewing the same session also see this pending state.
38+
39+
- **Codex:** OpenClaw interrupts the active native turn and stops its background terminals, then continues in the same conversation with the new permissions and an internal **Permission change** notice. It does not reset the conversation or replay the original request.
40+
- **OpenClaw native runtime:** OpenClaw refreshes the active tool policy without restarting the conversation. Subsequent tool calls use the updated permissions.
41+
42+
Pending approvals from the old permissions are canceled, not granted. Changing permissions does not undo completed writes or other side effects. Commands and background processes that have already started are not rolled back.
43+
44+
Active CLI-backed runs and runs whose entire agent executes on a worker (`worker-turn`) do not support live permission changes. OpenClaw rejects the change before saving it. Stop the task, change permissions, then continue in the same session. Worker placements that run only remote commands (`remote-exec`) follow the behavior of their locally running agent runtime.
45+
3546
## Policy precedence and clamping
3647

3748
Session-wide exec policy belongs to the permission mode. When the mode is unset, normal global or per-agent configuration applies. `/exec security=... ask=...` applies only to its message and can only tighten an explicit session mode; `host` and `node` remain session placement defaults. See [Exec session overrides](/tools/exec#session-overrides-exec).

‎extensions/codex/src/app-server/approval-bridge.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,41 @@ describe("Codex app-server approval bridge", () => {
433433
});
434434
});
435435

436+
it("cancels native approval when permissions change during final file revalidation", async () => {
437+
const params = createParams();
438+
const controller = new AbortController();
439+
params.hostCapabilities = {
440+
...params.hostCapabilities,
441+
prepareMutableFileApproval: async () => ({
442+
ok: true,
443+
requiresOneShot: false,
444+
revalidate: async () => {
445+
controller.abort("permission-change");
446+
return { ok: true };
447+
},
448+
}),
449+
};
450+
451+
const result = await handleCodexAppServerApprovalRequest({
452+
method: "item/commandExecution/requestApproval",
453+
requestParams: {
454+
...codexTestTurnIds(),
455+
itemId: "cmd-permission-change",
456+
command: "node script.js",
457+
},
458+
paramsForRun: params,
459+
...codexTestTurnIds(),
460+
autoApprove: true,
461+
signal: controller.signal,
462+
});
463+
464+
expect(result).toEqual({ decision: "cancel" });
465+
expect(params.onAgentEvent).not.toHaveBeenCalledWith(
466+
expect.objectContaining({ data: expect.objectContaining({ status: "approved" }) }),
467+
);
468+
expect(mockCallGatewayTool).not.toHaveBeenCalled();
469+
});
470+
436471
it("keeps permission grants on the human path under full-auto runtime policy", async () => {
437472
const params = createParams();
438473
mockCallGatewayTool

‎extensions/codex/src/app-server/approval-bridge.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,12 @@ export async function handleCodexAppServerApprovalRequest(params: {
118118
resolvedOutcome = "approved-once";
119119
resolvedMessage = "Codex app-server approval granted for this byte-bound command only.";
120120
}
121+
// Permission changes close this native turn while its outer run stays live.
122+
// Recheck after byte revalidation before releasing a grant to Codex.
123+
params.signal?.throwIfAborted();
124+
if (resolvedOutcome !== "denied") {
125+
params.paramsForRun.hostCapabilities.assertActive();
126+
}
121127
emitApprovalEvent(params.paramsForRun, {
122128
phase: "resolved",
123129
kind: context.kind,
@@ -166,6 +172,7 @@ export async function handleCodexAppServerApprovalRequest(params: {
166172
autoApprove: params.autoApprove,
167173
signal: params.signal,
168174
});
175+
params.signal?.throwIfAborted();
169176
if (policyOutcome?.outcome === "denied") {
170177
recordNativeToolFailureDisposition(params, context, policyOutcome.failureDisposition);
171178
return await resolvePolicyApproval("denied", policyOutcome.reason);
@@ -189,6 +196,7 @@ export async function handleCodexAppServerApprovalRequest(params: {
189196
// executable, so unresolved requests must stay on the human approval route.
190197
const requestResult = await requestPluginApproval({
191198
hostCapabilities: params.paramsForRun.hostCapabilities,
199+
signal: params.signal,
192200
title: context.title,
193201
description: context.description,
194202
severity: context.severity,

‎extensions/codex/src/app-server/elicitation-bridge.test.ts‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -907,21 +907,29 @@ describe("Codex app-server elicitation bridge", () => {
907907
expect(mockCallGatewayTool).not.toHaveBeenCalled();
908908
});
909909

910-
it("accepts safely mapped plugin app elicitations when destructive actions are enabled", async () => {
911-
const result = await handleCodexAppServerElicitationRequest({
912-
requestParams: buildPluginApprovalElicitation(),
913-
paramsForRun: createParams(),
914-
...codexTestTurnIds(),
915-
pluginAppPolicyContext: createPluginAppPolicyContext({ allowDestructiveActions: true }),
916-
});
910+
it.each([false, true])(
911+
"accepts safely mapped plugin app elicitations only while the turn remains active (aborted: %s)",
912+
async (aborted) => {
913+
const controller = new AbortController();
914+
if (aborted) {
915+
controller.abort("permission-change");
916+
}
917+
const result = await handleCodexAppServerElicitationRequest({
918+
requestParams: buildPluginApprovalElicitation(),
919+
paramsForRun: createParams(),
920+
...codexTestTurnIds(),
921+
pluginAppPolicyContext: createPluginAppPolicyContext({ allowDestructiveActions: true }),
922+
signal: controller.signal,
923+
});
917924

918-
expect(result).toEqual({
919-
action: "accept",
920-
content: { approve: true },
921-
_meta: null,
922-
});
923-
expect(mockCallGatewayTool).not.toHaveBeenCalled();
924-
});
925+
expect(result).toEqual({
926+
action: aborted ? "cancel" : "accept",
927+
content: aborted ? null : { approve: true },
928+
_meta: null,
929+
});
930+
expect(mockCallGatewayTool).not.toHaveBeenCalled();
931+
},
932+
);
925933

926934
it("accepts connector-id plugin app elicitations when destructive actions are enabled", async () => {
927935
const result = await handleCodexAppServerElicitationRequest({

‎extensions/codex/src/app-server/elicitation-bridge.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ export async function routeCodexAppServerElicitationRequest(params: {
107107
if (!approvalShaped) {
108108
return { kind: "not-mine" };
109109
}
110+
if (params.signal?.aborted) {
111+
return handled(createCodexElicitationResponse("cancel"));
112+
}
110113
const pluginResolution = resolvePluginElicitation({
111114
requestParams,
112115
pluginAppPolicyContext: params.pluginAppPolicyContext,
@@ -674,6 +677,7 @@ async function requestPluginApprovalOutcome(params: {
674677
try {
675678
const requestResult = await requestPluginApproval({
676679
hostCapabilities: params.paramsForRun.hostCapabilities,
680+
signal: params.signal,
677681
title: params.title,
678682
description: params.description,
679683
severity: "warning",

‎extensions/codex/src/app-server/plugin-approval-roundtrip.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ type ApprovalRequestResult = {
5959
/** Starts a two-phase plugin approval request through the OpenClaw gateway. */
6060
export async function requestPluginApproval(params: {
6161
hostCapabilities: AgentHarnessHostCapabilities;
62+
signal?: AbortSignal;
6263
title: string;
6364
description: string;
6465
severity: "info" | "warning";
@@ -68,6 +69,7 @@ export async function requestPluginApproval(params: {
6869
}): Promise<ApprovalRequestResult | undefined> {
6970
const timeoutMs = DEFAULT_CODEX_APPROVAL_TIMEOUT_MS;
7071
return params.hostCapabilities.requestApproval({
72+
signal: params.signal,
7173
title: truncateCodexApprovalDisplayText(params.title, MAX_PLUGIN_APPROVAL_TITLE_LENGTH),
7274
description: truncateCodexApprovalDisplayText(
7375
params.description,

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,27 @@ export async function activateCodexAttemptTurn(
390390
runId: params.runId,
391391
startedAtMs: params.startedAtMs,
392392
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
393+
permissionChangeOwner: params.permissionChange?.owner,
394+
applyPermissionMode: async (
395+
mode: NonNullable<typeof params.permissionMode> | null,
396+
revokeApprovals: () => void,
397+
) => {
398+
if (
399+
!params.permissionChange ||
400+
terminalState.terminalOutcomeFrozen ||
401+
params.abortSignal?.aborted ||
402+
(!state.permissionChangeRestart && (state.completed || runAbortController.signal.aborted))
403+
) {
404+
return false;
405+
}
406+
const applied = params.permissionChange.request(mode);
407+
state.permissionChangeRestart ??= "requested";
408+
// A policy replacement cancels this native turn, not the admitted outer
409+
// run. Its successor must be prepared only after native stop and cleanup.
410+
runAbortController.abort("permission-change");
411+
revokeApprovals();
412+
return await applied;
413+
},
393414
claimPendingUserInputAnswer,
394415
cancelPendingUserInput,
395416
queueMessage,
@@ -444,33 +465,35 @@ export async function activateCodexAttemptTurn(
444465
})().finally(completeTurn);
445466
return;
446467
}
447-
const interrupted = interruptTurn(activeTurnId);
448-
if (terminalState.explicitCancellationObserved) {
449-
// turn/completed ends the turn, not its native background terminals.
450-
// Keep this attempt's route and lease until thread-scoped cleanup settles.
451-
state.abortCleanup = interrupted.then(async (confirmed) => {
452-
if (!confirmed) {
453-
throw new Error(
454-
"Codex cancellation could not confirm the turn stopped; background terminals may still be running.",
455-
);
456-
}
457-
await terminateCodexBackgroundTerminals(
458-
resourceState.client,
459-
resourceState.thread.threadId,
468+
state.abortCleanup = interruptTurn(activeTurnId).then(async (confirmed) => {
469+
if (!terminalState.explicitCancellationObserved && !state.permissionChangeRestart) {
470+
return;
471+
}
472+
if (!confirmed) {
473+
throw new Error(
474+
state.permissionChangeRestart
475+
? "Permission change could not confirm the previous Codex turn stopped."
476+
: "Codex cancellation could not confirm the turn stopped; background terminals may still be running.",
460477
);
461-
});
462-
}
463-
const cancellation = terminalState.explicitCancellationObserved
464-
? state.abortCleanup
465-
: interrupted;
466-
void cancellation.then(completeTurn, (error: unknown) => {
478+
}
479+
// turn/completed leaves native terminals running under their old policy.
480+
// Keep the route and lease until cancellation or policy replacement cleans them up.
481+
await terminateCodexBackgroundTerminals(resourceState.client, resourceState.thread.threadId);
482+
if (state.permissionChangeRestart) {
483+
state.permissionChangeRestart = "confirmed";
484+
}
485+
});
486+
void state.abortCleanup.then(completeTurn, (error: unknown) => {
467487
embeddedAgentLog.warn("codex app-server cancellation cleanup failed", { error });
468488
completeTurn();
469489
});
470490
};
471491
runAbortController.signal.addEventListener("abort", abortListener, { once: true });
472492
if (runAbortController.signal.aborted) {
473493
abortListener();
494+
} else if (params.permissionChange && !params.permissionChange.applied()) {
495+
state.permissionChangeRestart = "requested";
496+
runAbortController.abort("permission-change");
474497
}
475498
return {
476499
activeTurnId,

0 commit comments

Comments
 (0)