Skip to content

Commit ba6034c

Browse files
authored
fix(audit): avoid duplicate exec approval receipts (#130560)
1 parent bdc0c92 commit ba6034c

5 files changed

Lines changed: 67 additions & 17 deletions

‎src/agents/agent-tools.before-tool-call.decision.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
bindAssembledAgentToolActionDescriptor,
1919
copyAgentToolMetadata,
2020
} from "./agent-tool-metadata.js";
21+
import { markToolDecisionRecorded } from "./agent-tools.before-tool-call.decision.js";
2122
import { wrapToolWithBeforeToolCallHook } from "./agent-tools.before-tool-call.js";
2223
import { createCoreCodingTools } from "./core-coding-tools.js";
2324
import { createOpenClawTools } from "./openclaw-tools.js";
@@ -220,7 +221,7 @@ describe("generic tool action decision receipts", () => {
220221
expect(JSON.stringify(works)).not.toMatch(/sessions_list|SECRET_GATEWAY|private\/gateway/u);
221222
});
222223

223-
it("keeps an execution failure separate from its prior generic decision", async () => {
224+
it("keeps an execution failure separate from its generic decision", async () => {
224225
const works: ExecutionDecisionWork[] = [];
225226
const tool = wrapToolWithBeforeToolCallHook(
226227
assembledTool(
@@ -437,6 +438,22 @@ describe("generic tool action decision receipts", () => {
437438
});
438439
});
439440

441+
it("does not duplicate an owner-native decision created during tool execution", async () => {
442+
const works: ExecutionDecisionWork[] = [];
443+
const execute = vi.fn(async () => {
444+
markToolDecisionRecorded();
445+
return { content: [], details: { ok: true } };
446+
});
447+
const tool = wrapToolWithBeforeToolCallHook(
448+
assembledTool("tool", "late_owner_subject", execute),
449+
);
450+
451+
await admittedRun({ works, run: () => tool.execute("late-owner-call", {}) });
452+
453+
expect(execute).toHaveBeenCalledOnce();
454+
expect(works).toEqual([]);
455+
});
456+
440457
it("records prepareControl disposal as suppression without launching the tool", async () => {
441458
const works: ExecutionDecisionWork[] = [];
442459
const execute = vi.fn().mockResolvedValue({ content: [], details: { ok: true } });

‎src/agents/agent-tools.before-tool-call.decision.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
12
import { createHash } from "node:crypto";
23
import { recordExecutionDecisionWork } from "../audit/execution-decision-work.js";
34
import { getAgentToolActionDescriptor } from "./agent-tool-metadata.js";
@@ -9,6 +10,31 @@ const genericDecisions = {
910
denied: ["denied", "enforced", "generic_action_policy_denied"],
1011
suppressed: ["not-applicable", "attribution-only", "generic_action_suppressed"],
1112
} as const;
13+
const toolDecisionOwner = new AsyncLocalStorage<{ recorded: boolean }>();
14+
15+
/** Marks the current tool call after its owner-native decision record is registered. */
16+
export function markToolDecisionRecorded(): void {
17+
const state = toolDecisionOwner.getStore();
18+
if (state) {
19+
state.recorded = true;
20+
}
21+
}
22+
23+
/** Records generic attribution only when execution creates no owner-native record. */
24+
export async function runWithGenericToolActionDecision<T>(
25+
tool: AnyAgentTool,
26+
toolCallId: string | undefined,
27+
run: () => Promise<T> | T,
28+
): Promise<T> {
29+
const state = { recorded: false };
30+
try {
31+
return await toolDecisionOwner.run(state, run);
32+
} finally {
33+
if (!state.recorded) {
34+
recordGenericToolActionDecision(tool, toolCallId, "allowed");
35+
}
36+
}
37+
}
1238

1339
export function recordGenericToolActionDecision(
1440
tool: AnyAgentTool,

‎src/agents/agent-tools.before-tool-call.wrapper.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ import {
2020
copyAgentToolSourceExecutionGuard,
2121
runAgentToolSourceExecutionGuard,
2222
} from "./agent-tool-source-execution-guard.js";
23-
import { recordGenericToolActionDecision } from "./agent-tools.before-tool-call.decision.js";
23+
import {
24+
recordGenericToolActionDecision,
25+
runWithGenericToolActionDecision,
26+
} from "./agent-tools.before-tool-call.decision.js";
2427
import {
2528
buildToolContentPrivateData,
2629
emitSkillUsedDiagnostic,
@@ -527,9 +530,6 @@ export function wrapToolWithBeforeToolCallHook(
527530
// Host capabilities can close while hooks, approval, validation, or
528531
// steering awaits. Recheck at the final synchronous source boundary.
529532
runAgentToolSourceExecutionGuard(tool);
530-
if (!outcome.ownerDecision) {
531-
recordGenericToolActionDecision(tool, toolCallId, "allowed");
532-
}
533533
onImplementationStart?.();
534534
recordAdjustedParamsForToolCall(toolCallId, executeParams, ctx?.runId);
535535
const eventBase = buildEventBase(executeParams);
@@ -544,13 +544,11 @@ export function wrapToolWithBeforeToolCallHook(
544544
try {
545545
let result: Awaited<ReturnType<ForwardedToolExecution>>;
546546
try {
547-
result = await (execute as ForwardedToolExecution)(
548-
toolCallId,
549-
executeParams,
550-
signal,
551-
forwardedOnUpdate,
552-
...executionArgs,
553-
);
547+
const args = [toolCallId, executeParams, signal, forwardedOnUpdate, ...executionArgs];
548+
const invoke = () => (execute as ForwardedToolExecution)(...args);
549+
result = outcome.ownerDecision
550+
? await invoke()
551+
: await runWithGenericToolActionDecision(tool, toolCallId, invoke);
554552
} catch (error) {
555553
throw tool.resultContentSource === "network" &&
556554
getBeforeToolCallFailureDisposition(error) === undefined

‎src/agents/bash-tools.exec-approval-request.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
resolveShellWrapperTransportArgv,
2424
} from "../infra/shell-wrapper-resolution.js";
2525
import { createLazyPromise } from "../shared/lazy-runtime.js";
26+
import { markToolDecisionRecorded } from "./agent-tools.before-tool-call.decision.js";
2627
import {
2728
DEFAULT_APPROVAL_REQUEST_TIMEOUT_MS,
2829
DEFAULT_APPROVAL_TIMEOUT_MS,
@@ -163,6 +164,7 @@ async function registerExecApprovalRequest(
163164
buildExecApprovalRequestToolParams(params),
164165
{ expectFinal: false },
165166
);
167+
markToolDecisionRecorded();
166168
const decision = parseDecision(registrationResult);
167169
const id = parseString(registrationResult?.id) ?? params.id;
168170
const expiresAtMs =

‎test/e2e/qa-lab/runtime/agent-run-decision-receipt.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,18 @@ function assertNoGenericApprovalDuplicate(
109109
.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = ?")
110110
.get("execution_decision_facts");
111111
if (table) {
112-
const count = database
113-
.prepare("SELECT COUNT(*) AS count FROM execution_decision_facts")
114-
.get() as { count: number };
115-
if (count.count !== 0) {
116-
throw new Error("operator approval was duplicated into execution_decision_facts");
112+
const rows = database
113+
.prepare(
114+
`SELECT action_family, reason_code, owner
115+
FROM execution_decision_facts
116+
WHERE owner = 'tool-action' AND reason_code = 'generic_action_attributed'
117+
ORDER BY occurred_at, receipt_id`,
118+
)
119+
.all();
120+
if (rows.length !== 0) {
121+
throw new Error(
122+
`operator approval was duplicated into execution_decision_facts: ${JSON.stringify(rows)}`,
123+
);
117124
}
118125
}
119126
} finally {

0 commit comments

Comments
 (0)