Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/web/app/approvals/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { PageHeader } from "@/components/ui/page-header";
import { Section } from "@/components/ui/section";
import { Skeleton } from "@/components/ui/skeleton";
import { api } from "@/lib/api";
import { approvalArguments } from "@/lib/approval-arguments";
import { queryKeys, unwrap, useApprovals } from "@/lib/queries";
import { errorMessage } from "@orbit/api-client";
import { formatDateTime, relativeTime, titleCase } from "@/lib/utils";
Expand Down Expand Up @@ -244,9 +245,9 @@ function ApprovalCard({
function approvalTitle(approval: ApprovalWithExecution): string {
const action = (approval.requestedAction ?? {}) as {
capability?: string;
arguments?: Record<string, unknown>;
arguments?: unknown;
};
const args = action.arguments ?? {};
const args = approvalArguments(action).args;
switch (action.capability) {
case "repo.commit":
return `Commit changes${args.message ? `: ${String(args.message).slice(0, 80)}` : ""}`;
Expand Down
23 changes: 17 additions & 6 deletions apps/web/components/approvals/approval-details.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"use client";

import { Badge } from "@/components/ui/badge";
import { Callout } from "@/components/ui/callout";
import { approvalArguments, rowValue, truncationNotice } from "@/lib/approval-arguments";
import { brandName, effectLabel, effectTone } from "@/lib/presentation";
import { titleCase } from "@/lib/utils";
import type { ApprovalWithExecution } from "@/lib/types";
Expand All @@ -11,9 +13,13 @@ export function ApprovalDetails({ approval }: { approval: ApprovalWithExecution
connector?: string;
connectionName?: string;
effect?: string;
arguments?: Record<string, unknown>;
arguments?: unknown;
argumentsBytes?: unknown;
argumentsTruncated?: unknown;
};
const args = action.arguments ?? {};
const shown = approvalArguments(action);
const args = shown.args;
const notice = truncationNotice(shown);
const rows = actionRows(action.capability, args);
const tone = effectTone(action.effect);
return (
Expand Down Expand Up @@ -46,13 +52,18 @@ export function ApprovalDetails({ approval }: { approval: ApprovalWithExecution
))}
</dl>
) : null}
{Object.keys(args).length ? (
<details>
{notice ? (
<Callout tone="warning" title="Arguments truncated">
{notice}
</Callout>
) : null}
{shown.text ? (
<details open={shown.truncated}>
<summary className="w-fit cursor-pointer select-none text-muted-foreground hover:text-foreground">
Full arguments
</summary>
<pre className="code-block mt-1.5 max-h-48 whitespace-pre-wrap break-words bg-card">
{JSON.stringify(args, null, 2)}
{shown.text}
</pre>
</details>
) : null}
Expand All @@ -67,7 +78,7 @@ function actionRows(
const rows: Array<[string, string]> = [];
const push = (label: string, value: unknown) => {
if (value !== undefined && value !== null && String(value).trim() !== "") {
rows.push([label, String(value).slice(0, 1000)]);
rows.push([label, rowValue(value)]);
}
};
// Where it happens comes first: the same action on another repository is another decision.
Expand Down
41 changes: 41 additions & 0 deletions apps/web/lib/approval-arguments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";

import { approvalArguments, rowValue, truncationNotice } from "./approval-arguments.ts";

test("complete arguments are shown whole without a notice", () => {
const value = approvalArguments({
arguments: { command: "ls" },
argumentsBytes: 16,
argumentsTruncated: false,
});
assert.deepEqual(value.args, { command: "ls" });
assert.equal(value.truncated, false);
assert.match(value.text, /"command": "ls"/);
assert.equal(truncationNotice(value), null);
});

test("truncated arguments carry the size in a visible notice", () => {
const value = approvalArguments({
arguments: '{"command":"echo … [4000 of 70000 bytes left out here] …\nrm -rf /"}',
argumentsBytes: 70000,
argumentsTruncated: true,
});
assert.equal(value.truncated, true);
assert.deepEqual(value.args, {});
assert.match(value.text, /rm -rf/);
assert.match(truncationNotice(value) ?? "", /too long to show in full, 70,000 bytes/);
});

test("a string from an older worker counts as truncated", () => {
const value = approvalArguments({ arguments: '{"command":"echo hi…' });
assert.equal(value.truncated, true);
assert.match(truncationNotice(value) ?? "", /too long to show in full\. /);
});

test("long summary values are marked, short ones are not", () => {
assert.equal(rowValue("short"), "short");
const long = rowValue("x".repeat(1500));
assert.ok(long.startsWith("x".repeat(1000)));
assert.match(long, /truncated; see Full arguments\)$/);
});
43 changes: 43 additions & 0 deletions apps/web/lib/approval-arguments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// What an approval request shows of a tool call's arguments. The worker keeps arguments up to
// 64 KiB whole; larger ones arrive as a string holding the head and the tail with the left-out
// middle named, plus `argumentsBytes` and `argumentsTruncated`. Approvals created by older
// workers carry a string cut at 4000 bytes and no flag: any string is treated as truncated.

export type ApprovalArguments = {
/** The arguments as an object, for the summary rows; empty when truncated. */
args: Record<string, unknown>;
/** Text for the full-arguments view. */
text: string;
truncated: boolean;
/** Size of the original serialised arguments, when the worker reported it. */
bytes?: number;
};

export function approvalArguments(action: {
arguments?: unknown;
argumentsBytes?: unknown;
argumentsTruncated?: unknown;
}): ApprovalArguments {
const bytes = typeof action.argumentsBytes === "number" ? action.argumentsBytes : undefined;
const raw = action.arguments;
if (typeof raw === "string") {
return { args: {}, text: raw, truncated: true, bytes };
}
const args =
raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
const text = raw === undefined || raw === null ? "" : JSON.stringify(raw, null, 2);
return { args, text, truncated: action.argumentsTruncated === true, bytes };
}

/** The warning shown above truncated arguments; null when they are complete. */
export function truncationNotice(value: ApprovalArguments): string | null {
if (!value.truncated) return null;
const size = value.bytes === undefined ? "" : `, ${value.bytes.toLocaleString("en-US")} bytes`;
return `This call's arguments are too long to show in full${size}. Only the start and the end are shown below; approving allows the whole call, including the part left out.`;
}

/** A summary-row value, cut with a visible marker when it is longer than `limit` characters. */
export function rowValue(value: unknown, limit = 1000): string {
const text = String(value);
return text.length <= limit ? text : `${text.slice(0, limit)}… (truncated; see Full arguments)`;
}
1 change: 1 addition & 0 deletions changelog.d/392.security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Approval requests no longer hide the end of a long tool call. The worker now sends arguments up to 64 KiB whole (they were cut at 4000 bytes), and longer ones keep both the start and the end with the number of bytes left out. The approval view shows an "Arguments truncated" warning with the full size, and long summary values say they are cut. Shortened arguments in execution events now end with `[truncated: N bytes in total]`. See [Approvals](docs/guide/approvals.md) ([#392](https://github.com/opsifyhq/orbit/issues/392)).
6 changes: 5 additions & 1 deletion docs/architecture/runtime-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,11 @@ harness tool call ──► worker broker /policy or /tools/call
if the agent requests the identical capability and arguments again in the same run.
- Management API: `GET/POST /api/v1/tool-policies`, `PATCH/DELETE
/api/v1/tool-policies/{id}` (`settings:read` / `settings:write`).
- Approvals record the rule, reason, impact and arguments for the reviewer. Every deny
- Approvals record the rule, reason, impact and arguments for the reviewer. The
`requestedAction` carries the arguments whole up to 64 KiB of serialised JSON, with
`argumentsBytes` and `argumentsTruncated`; larger arguments become a string with the head,
the tail and the number of bytes left out between them. Event and audit payloads keep
shorter copies, and a cut copy ends with `[truncated: N bytes in total]`. Every deny
and approval is audited and emitted as a `tool_call` execution event.

What is enforced for native tools today:
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/approvals.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ decided (409).

To decide, open **Approvals** in the sidebar. **Waiting for a decision** lists each request
with the agent, the call (for example "Comment on issue #12"), its arguments and when it
expires. Choose **Approve** or **Reject**. If a request has expired, the card says "Expired
expires. The arguments are shown in full up to 64 KiB. A longer call shows only its
start and its end, with an "Arguments truncated" warning that gives the full size; approving
it allows the whole call, so reject it if you need to see the rest. Choose **Approve** or **Reject**. If a request has expired, the card says "Expired
...; the action was refused" and both buttons are disabled. **Recent decisions** shows the
status (Approved, Rejected or Expired), the agent, the time, the comment if there is one,
and a link to the execution.
Expand Down
106 changes: 103 additions & 3 deletions services/worker/src/broker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1313,13 +1313,13 @@ async fn policy_check(
"connectionName": serde_json::Value::Null,
"effect": effect.as_str(),
"agentName": state.execution.agent_name,
"arguments": truncate_json(&call.arguments, 4000),
"argumentsHash": args_hash,
"reason": outcome.reason,
"impact": outcome.impact,
"rule": outcome.rule_name,
"source": "tool_policy",
});
let action = with_approval_arguments(action, &call.arguments);
match request_approval_action(&state, &call.tool, action, &call.arguments).await {
Ok(_) => respond(StatusCode::OK, &outcome),
Err(error) => (
Expand Down Expand Up @@ -1376,11 +1376,11 @@ async fn request_approval(
"connectionName": connection_name,
"effect": tool.effect.as_str(),
"agentName": state.execution.agent_name,
"arguments": truncate_json(arguments, 4000),
"reason": policy.and_then(|policy| policy.reason.clone()),
"impact": policy.and_then(|policy| policy.impact.clone()),
"rule": policy.and_then(|policy| policy.rule_name.clone()),
});
let action = with_approval_arguments(action, arguments);
request_approval_action(state, &tool.capability, action, arguments).await
}

Expand Down Expand Up @@ -1661,18 +1661,118 @@ fn truncate(value: &str, limit: usize) -> String {
}
}

/// Shortened arguments for events and audit payloads. A value over the limit becomes a
/// string that says it was cut and how large the original was, so a reader never takes a
/// shortened value for the whole one.
fn truncate_json(value: &Value, limit: usize) -> Value {
match serde_json::to_string(value) {
Ok(serialized) if serialized.len() <= limit => value.clone(),
Ok(serialized) => json!(truncate(&serialized, limit)),
Ok(serialized) => json!(format!(
"{} [truncated: {} bytes in total]",
truncate(&serialized, limit),
serialized.len()
)),
Err(_) => Value::Null,
}
}

/// How much of a call's arguments an approval request carries in full. A person decides
/// on what they are shown, so this is far above the event limit; the API body limit
/// (2 MiB by default) and the per-execution pending-approval cap bound the total.
const APPROVAL_ARGUMENTS_LIMIT: usize = 64 * 1024;

/// Add the arguments to an approval `requestedAction`, with `argumentsBytes` (size of the
/// serialised arguments) and `argumentsTruncated`. Arguments up to
/// [`APPROVAL_ARGUMENTS_LIMIT`] are kept whole. Larger ones become a string with the head
/// and the tail of the serialised arguments and a line naming how many bytes were left out
/// in between, so the end of a long command is never hidden from the approver.
fn with_approval_arguments(mut action: Value, arguments: &Value) -> Value {
let (shown, bytes, truncated) = approval_arguments(arguments, APPROVAL_ARGUMENTS_LIMIT);
if let Some(map) = action.as_object_mut() {
map.insert("arguments".into(), shown);
map.insert("argumentsBytes".into(), json!(bytes));
map.insert("argumentsTruncated".into(), json!(truncated));
}
action
}

fn approval_arguments(arguments: &Value, limit: usize) -> (Value, usize, bool) {
let Ok(serialized) = serde_json::to_string(arguments) else {
return (Value::Null, 0, true);
};
let bytes = serialized.len();
if bytes <= limit {
return (arguments.clone(), bytes, false);
}
let half = limit / 2;
let mut head_end = half;
while head_end > 0 && !serialized.is_char_boundary(head_end) {
head_end -= 1;
}
let mut tail_start = bytes - half;
while tail_start < bytes && !serialized.is_char_boundary(tail_start) {
tail_start += 1;
}
let omitted = tail_start - head_end;
let shown = format!(
"{}\n… [{omitted} of {bytes} bytes left out here] …\n{}",
&serialized[..head_end],
&serialized[tail_start..]
);
(json!(shown), bytes, true)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn approval_arguments_keep_a_5000_byte_command_whole() {
let command = format!("{}; rm -rf /important", "echo harmless ".repeat(360));
let arguments = json!({ "command": command });
let action = with_approval_arguments(json!({ "capability": "bash" }), &arguments);
assert!(serde_json::to_string(&arguments).unwrap().len() > 5000);
assert_eq!(action["arguments"], arguments);
assert_eq!(action["argumentsTruncated"], json!(false));
assert_eq!(
action["argumentsBytes"],
json!(serde_json::to_string(&arguments).unwrap().len())
);
}

#[test]
fn approval_arguments_over_the_limit_keep_head_and_tail_and_say_so() {
let command = format!("{}rm -rf /important", "é".repeat(APPROVAL_ARGUMENTS_LIMIT));
let arguments = json!({ "command": command });
let bytes = serde_json::to_string(&arguments).unwrap().len();
let action = with_approval_arguments(json!({ "capability": "bash" }), &arguments);
assert_eq!(action["argumentsTruncated"], json!(true));
assert_eq!(action["argumentsBytes"], json!(bytes));
let shown = action["arguments"]
.as_str()
.expect("truncated arguments are a string");
assert!(shown.starts_with("{\"command\":\"é"));
assert!(
shown.ends_with("rm -rf /important\"}"),
"the tail stays visible"
);
assert!(shown.contains("bytes left out here] …"));
assert!(shown.contains(&format!(" of {bytes} bytes")));
assert!(shown.len() < APPROVAL_ARGUMENTS_LIMIT + 200);
}

#[test]
fn truncated_event_arguments_say_they_are_truncated() {
let arguments = json!({ "command": "x".repeat(5000) });
let shown = truncate_json(&arguments, 4000);
let text = shown.as_str().unwrap();
assert!(text.ends_with(&format!(
"[truncated: {} bytes in total]",
serde_json::to_string(&arguments).unwrap().len()
)));
assert_eq!(truncate_json(&json!({ "a": 1 }), 4000), json!({ "a": 1 }));
}

#[tokio::test]
async fn connector_http_client_refuses_loopback_and_metadata_targets() {
let client = orbit_security::guarded_client_with_policy(
Expand Down