mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
Merge approved-action rate admission into sleep-12-decision-target-invalidation
Co-Authored-By: Paperclip <noreply@paperclip.ing> * codex/sleep-11-decision-effect-recovery: Persist changed rate admission before approved tool execution
This commit is contained in:
commit
b8b32f2137
6 files changed
+256
-27
No files matched your search
@@ -48,7 +48,7 @@ Independent SQL writers or another process need a separate notification contract
|
||||
Agent actions retain their existing approved-to-executing claim. Test-tab
|
||||
foreground approval and recovery now share an equivalent claim before provider
|
||||
dispatch. The invocation then starts only if the request still holds that claim.
|
||||
Provider calls and target/policy lookup remain outside SQL transactions.
|
||||
Provider calls and target discovery remain outside SQL transactions. Current rate-policy admission and its receipt commit together in a short database transaction.
|
||||
|
||||
The Test-tab invocation outcome and terminal request status commit together.
|
||||
Claim timestamps fence late settlement. A later audit failure cannot overwrite
|
||||
@@ -187,3 +187,47 @@ proves the old owner cannot dispatch; the surviving approval later executes once
|
||||
A provider-error case proves that an already-started call is not requeued as a
|
||||
preparation failure. The existing Test-tab timeout and ownership cases exercise
|
||||
the other consumer of the shared boundary.
|
||||
|
||||
|
||||
## New or edited rate rules during approval
|
||||
|
||||
A reviewed invocation already has durable `consumedRateAdmissions` in its policy
|
||||
explanation. The original read-only recheck retained unchanged rules correctly,
|
||||
but new or edited rules only inspected their counters. Two approved actions could
|
||||
therefore both execute against one available slot. The real recovery regression
|
||||
failed for both a newly added limit and an increased limit before this repair.
|
||||
|
||||
The policy service now owns `admitInvocation`: lock the company-scoped invocation,
|
||||
validate its exact actor/task/tool/argument binding, recheck current policy, spend
|
||||
only admissions not already recorded for that policy generation, and save the
|
||||
receipt atomically. The gateway supplies its execution claim; that claim is locked
|
||||
and checked by ID, invocation, company, executing status and timestamp. This also
|
||||
supports historical approved requests whose invocation still says pending, without
|
||||
accepting a stale claimant. Existing claim/start/settlement owners still control
|
||||
provider execution. No queue table, periodic query, or per-route wrapper is added.
|
||||
|
||||
Counter updates preserve the number of already spent slots when the limit changes.
|
||||
A rejection by a later policy or failure to save the receipt rolls back new charges.
|
||||
A retry of a committed admission retains the saved receipt, including concurrent
|
||||
rechecks. Read-only approval preflight and browser authority probes stay read-only;
|
||||
trust-rule usage is not counted again during execution revalidation. The policy
|
||||
service and its metric helper accept only the database capabilities they use, so
|
||||
transaction clients do not require a cast to a root connection.
|
||||
|
||||
The owning gateway and policy suites pass all 181 cases against disposable real
|
||||
PostgreSQL databases. Coverage includes two competing invocations, concurrent
|
||||
retries of one invocation, changed limits, failed receipt writes, rejection after
|
||||
an earlier rate charge, unchanged admissions, historical approvals, scope mismatch,
|
||||
claim loss, quiet recovery and unknown provider outcomes. Server typechecking
|
||||
passes after preparing current runner dependencies.
|
||||
|
||||
Earlier verification failures remain part of this evidence: the first full run
|
||||
was stopped because an old claim-loss fixture held the policy table while trying
|
||||
to revoke the newly locked invocation. It now pauses discovery before admission
|
||||
and retains the no-provider-dispatch assertion. A new receipt assertion was fixed
|
||||
to permit the intended additional receipt while preserving original fields. The
|
||||
next full run exposed an overly strict historical-approval check; exact execution-
|
||||
claim validation fixed it. Typechecking then exposed root-client-only signatures,
|
||||
which were narrowed to their actual database capabilities. The final complete
|
||||
suites and TypeScript check pass; stack integration and current-head CI remain
|
||||
separate gates. This proves worker and admission behavior, not deployed host sleep.
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
@@ -34,7 +34,9 @@ import { toolAccessService } from "../services/tool-access.js";
|
||||
import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js";
|
||||
import { canonicalToolArguments, signToolArguments } from "../services/tool-content-guards.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_POLICY_TEST_DATABASE_URL");
|
||||
const embeddedPostgresSupport = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
function legacySideEffectKey(invocation: typeof toolInvocations.$inferSelect, argumentsHash: string) {
|
||||
@@ -215,8 +217,11 @@ describeEmbeddedPostgres("tool access policy service", () => {
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
if (externalDatabaseUrl) db = createDb(externalDatabaseUrl);
|
||||
else {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -244,6 +249,7 @@ describeEmbeddedPostgres("tool access policy service", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
@@ -1112,11 +1118,90 @@ describeEmbeddedPostgres("tool access policy service", () => {
|
||||
expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true });
|
||||
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
|
||||
expect((await db.select().from(toolRateLimitCounters))[0].remaining).toBe(0);
|
||||
// Neither a new invocation nor an accidental consuming recheck can borrow
|
||||
// another invocation's already-spent slot.
|
||||
// A fresh invocation cannot borrow another invocation's already-spent slot.
|
||||
// Execution revalidation retains its own durable admission.
|
||||
expect(await svc.decide(input, { admittedInvocationId: randomUUID() })).toMatchObject({ decision: "rate_limited" });
|
||||
expect(await svc.decide({ ...input, consumeRateLimit: true }, { admittedInvocationId: invocation.id }))
|
||||
.toMatchObject({ decision: "rate_limited" });
|
||||
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
|
||||
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
|
||||
});
|
||||
|
||||
it("atomically charges a new rule once across concurrent retries of the same invocation", async () => {
|
||||
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
|
||||
const added = await svc.createPolicy(company.id, { name: "New admission", policyType: "rate_limit", priority: 0,
|
||||
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
|
||||
const oldCounters = await db.select().from(toolRateLimitCounters);
|
||||
expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true });
|
||||
expect(await db.select().from(toolRateLimitCounters)).toEqual(oldCounters);
|
||||
const results = await Promise.all(Array.from({ length: 4 }, () => svc.admitInvocation(input, invocation.id)));
|
||||
expect(results.every(result => result.allowed)).toBe(true);
|
||||
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
|
||||
.toMatchObject([{ limit: 1, remaining: 0 }]);
|
||||
const [saved] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id));
|
||||
expect(saved.policyExplanation?.consumedRateAdmissions).toHaveLength(2);
|
||||
const { consumedRateAdmissions: oldAdmissions, ...oldExplanation } = invocation.policyExplanation!;
|
||||
expect(saved.policyExplanation).toMatchObject(oldExplanation);
|
||||
expect(saved.policyExplanation?.consumedRateAdmissions).toEqual(expect.arrayContaining(oldAdmissions as unknown[]));
|
||||
});
|
||||
|
||||
it("allows only one of two admitted invocations to spend a newly added final slot", async () => {
|
||||
const { company, input, invocation, svc } = await admittedRateLimitedInvocation(2);
|
||||
const initial = await svc.decide({ ...input, consumeRateLimit: true });
|
||||
expect(initial.allowed).toBe(true);
|
||||
const { invocation: second } = await svc.recordInvocation(input, initial);
|
||||
await db.update(toolInvocations).set({ status: "executing" }).where(eq(toolInvocations.id, second.id));
|
||||
const added = await svc.createPolicy(company.id, { name: "One competing slot", policyType: "rate_limit", priority: 0,
|
||||
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
|
||||
const results = await Promise.all([invocation.id, second.id].map(id => svc.admitInvocation(input, id)));
|
||||
expect(results.filter(result => result.allowed)).toHaveLength(1);
|
||||
expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1);
|
||||
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
|
||||
.toMatchObject([{ limit: 1, remaining: 0 }]);
|
||||
});
|
||||
|
||||
it("rolls back new rate charges when a later policy rejects the invocation", async () => {
|
||||
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
|
||||
await svc.createPolicy(company.id, { name: "Before rejection", policyType: "rate_limit", priority: 0,
|
||||
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
|
||||
await svc.createPolicy(company.id, { name: "Later rejection", policyType: "block", priority: 10,
|
||||
selectors: { toolName: "send_email" } });
|
||||
const counters = await db.select().from(toolRateLimitCounters);
|
||||
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ decision: "deny" });
|
||||
expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation)
|
||||
.toEqual(invocation.policyExplanation);
|
||||
});
|
||||
|
||||
it("rolls back rate charges when saving the admission receipt fails and admits a retry once", async () => {
|
||||
const { company, input, invocation, svc } = await admittedRateLimitedInvocation();
|
||||
const added = await svc.createPolicy(company.id, { name: "Receipt failure", policyType: "rate_limit", priority: 0,
|
||||
selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } });
|
||||
await db.execute(sql`create function sleep_admission_fail() returns trigger language plpgsql as $$ begin
|
||||
raise exception 'receipt write unavailable'; end $$`);
|
||||
await db.execute(sql`create trigger sleep_admission_fail before update of policy_explanation on tool_invocations
|
||||
for each row execute function sleep_admission_fail()`);
|
||||
try {
|
||||
await expect(svc.admitInvocation(input, invocation.id)).rejects.toThrow();
|
||||
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))).toEqual([]);
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation)
|
||||
.toEqual(invocation.policyExplanation);
|
||||
} finally {
|
||||
await db.execute(sql`drop trigger sleep_admission_fail on tool_invocations`);
|
||||
await db.execute(sql`drop function sleep_admission_fail()`);
|
||||
}
|
||||
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
|
||||
expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true });
|
||||
expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id)))
|
||||
.toMatchObject([{ limit: 1, remaining: 0 }]);
|
||||
});
|
||||
|
||||
it.each([2, 4])("preserves spent slots when a rate limit changes from three to %s", async limit => {
|
||||
const { company, input, ratePolicy, svc } = await admittedRateLimitedInvocation(3);
|
||||
await svc.updatePolicy({ companyId: company.id, policyId: ratePolicy.id,
|
||||
body: { config: { limit, windowSeconds: 3600, keyBy: ["agent", "tool"] } } });
|
||||
const results = await Promise.all(Array.from({ length: limit }, () => svc.decide({ ...input, consumeRateLimit: true })));
|
||||
expect(results.filter(result => result.allowed)).toHaveLength(limit - 1);
|
||||
expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1);
|
||||
expect(await db.select().from(toolRateLimitCounters)).toMatchObject([{ limit, remaining: 0 }]);
|
||||
});
|
||||
|
||||
it.each(["pending", "approved"] as const)("retains a waiting invocation's consumed slot without bypassing %s approval policy", async approvalState => {
|
||||
@@ -1188,10 +1273,13 @@ describeEmbeddedPostgres("tool access policy service", () => {
|
||||
for (const mutation of mutations) {
|
||||
await db.update(toolInvocations).set(mutation).where(eq(toolInvocations.id, invocation.id));
|
||||
expect(await svc.decide(input, options), JSON.stringify(mutation)).toMatchObject({ decision: "rate_limited" });
|
||||
expect(await svc.admitInvocation(input, invocation.id), JSON.stringify(mutation)).toMatchObject({ decision: "deny" });
|
||||
await db.update(toolInvocations).set({ ...invocation, status: "executing" }).where(eq(toolInvocations.id, invocation.id));
|
||||
}
|
||||
expect(await svc.decide({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, options))
|
||||
.toMatchObject({ decision: "rate_limited" });
|
||||
expect(await svc.admitInvocation({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, invocation.id))
|
||||
.toMatchObject({ decision: "deny" });
|
||||
});
|
||||
|
||||
it("rejects unsupported policy semantics at create and update time", async () => {
|
||||
|
||||
@@ -883,6 +883,31 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["new", "increased"] as const)("spends the newly available slot of a %s rate rule during approved recovery", async change => {
|
||||
const rate = { companyId: fixture.company.id, name: "Changed reviewed-note limit",
|
||||
policyType: "rate_limit" as const, priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" },
|
||||
config: { limit: 2, windowSeconds: 3600, keyBy: ["agent", "tool"] } };
|
||||
const original = change === "increased" ? (await db.insert(toolPolicies).values(rate).returning())[0] : null;
|
||||
const first = await request(), second = await request();
|
||||
if (original) {
|
||||
await db.update(toolPolicies).set({ config: { ...rate.config, limit: 3 }, updatedAt: new Date() })
|
||||
.where(eq(toolPolicies.id, original.id));
|
||||
} else {
|
||||
await db.insert(toolPolicies).values({ ...rate, config: { ...rate.config, limit: 1 } });
|
||||
}
|
||||
await approve(first); await approve(second);
|
||||
await startRecovery(); await settle(); await quiet();
|
||||
const requests = await db.select().from(toolActionRequests);
|
||||
expect(requests.filter(row => row.status === "executed")).toHaveLength(1);
|
||||
expect(requests.filter(row => row.status === "failed")).toHaveLength(1);
|
||||
const invocations = await db.select().from(toolInvocations);
|
||||
expect(invocations.filter(row => row.errorCode === "rate_limited")).toHaveLength(1);
|
||||
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1);
|
||||
const counters = await db.select().from(toolRateLimitCounters);
|
||||
expect(counters).toHaveLength(1);
|
||||
expect(counters[0]).toMatchObject({ limit: change === "increased" ? 3 : 1, remaining: 0 });
|
||||
});
|
||||
|
||||
it("reconstructs a saved approved action after restart", async () => {
|
||||
const pending = await request(); await approve(pending);
|
||||
await startRecovery(); await settle(); await executed(pending); await quiet();
|
||||
@@ -1194,7 +1219,9 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
const gate = new Promise<void>(resolve => { unlock = resolve; });
|
||||
const acquired = new Promise<void>(resolve => { locked = resolve; });
|
||||
const lock = db.transaction(async tx => {
|
||||
await tx.execute(sql`lock table tool_policies in access exclusive mode`);
|
||||
// Pause tool discovery before admission locks the invocation. Revocation
|
||||
// cannot legitimately take that lock from an in-flight admission.
|
||||
await tx.execute(sql`lock table tool_catalog_entries in access exclusive mode`);
|
||||
locked(); await gate;
|
||||
});
|
||||
await acquired;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { boundRunIssueIdSql } from "./run-task-binding.js";
|
||||
import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm";
|
||||
import type { ToolApprovalClaim } from "./tool-approval-execution.js";
|
||||
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
@@ -51,6 +52,12 @@ import {
|
||||
import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js";
|
||||
import { canonicalToolArguments, readSignedToolArgumentsPayload, toolRequestIdentityHash } from "./tool-content-guards.js";
|
||||
|
||||
class RejectedInvocationAdmission extends Error {
|
||||
constructor(readonly decision: ToolAccessDecision) {
|
||||
super(decision.explanation);
|
||||
}
|
||||
}
|
||||
|
||||
type ToolAccessContext = {
|
||||
companyId: string;
|
||||
actorType: "agent" | "user" | "system" | "plugin";
|
||||
@@ -715,7 +722,7 @@ function assertSupportedGenericPolicyShape(
|
||||
}
|
||||
}
|
||||
|
||||
async function getGenericPolicyRow(db: Db, companyId: string, policyId: string) {
|
||||
async function getGenericPolicyRow(db: Pick<Db, "select">, companyId: string, policyId: string) {
|
||||
const [policy] = await db
|
||||
.select()
|
||||
.from(toolPolicies)
|
||||
@@ -783,7 +790,7 @@ function scopeAllowsTool(scope: Record<string, unknown> | null, ctx: ToolAccessC
|
||||
return selectorMatches(selectors, ctx);
|
||||
}
|
||||
|
||||
export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecret?: string } = {}) {
|
||||
export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "update" | "delete" | "transaction">, options: { toolActionSigningSecret?: string } = {}) {
|
||||
async function listPolicies(companyId: string) {
|
||||
return db
|
||||
.select()
|
||||
@@ -1285,11 +1292,12 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
],
|
||||
set: {
|
||||
limit: rule.limit,
|
||||
remaining: sql`greatest(0, least(${toolRateLimitCounters.remaining}, ${rule.limit}) - 1)`,
|
||||
// Preserve the number already spent when an operator changes the limit.
|
||||
remaining: sql`greatest(0, ${rule.limit} - (${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining}) - 1)`,
|
||||
resetAt,
|
||||
updatedAt: now,
|
||||
},
|
||||
setWhere: gt(toolRateLimitCounters.remaining, 0),
|
||||
setWhere: sql`${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining} < ${rule.limit}`,
|
||||
})
|
||||
.returning({ remaining: toolRateLimitCounters.remaining });
|
||||
if (!counter) {
|
||||
@@ -1360,7 +1368,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
});
|
||||
}
|
||||
|
||||
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise<ConsumedRateAdmission[]> {
|
||||
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise<ConsumedRateAdmission[] | null> {
|
||||
const [invocation] = await db.select({
|
||||
actorType: toolInvocations.actorType, actorId: toolInvocations.actorId, agentId: toolInvocations.agentId,
|
||||
runId: toolInvocations.runId, issueId: toolInvocations.issueId, gatewayId: toolInvocations.gatewayId,
|
||||
@@ -1387,12 +1395,66 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
&& invocation.providerType === ctx.providerType && invocation.applicationKey === ctx.applicationKey
|
||||
&& invocation.upstreamToolName === ctx.upstreamToolName
|
||||
&& invocation.argumentsHash === ctx.argumentsHash;
|
||||
const stored = authorized ? invocation.policyExplanation?.consumedRateAdmissions : null;
|
||||
if (!authorized) return null;
|
||||
const stored = invocation.policyExplanation?.consumedRateAdmissions;
|
||||
return Array.isArray(stored) ? stored.filter((item): item is ConsumedRateAdmission => isRecord(item)
|
||||
&& typeof item.policyId === "string" && CANONICAL_UUID_RE.test(item.policyId)
|
||||
&& typeof item.versionHash === "string" && /^[a-f0-9]{64}$/.test(item.versionHash)) : [];
|
||||
}
|
||||
|
||||
/** Revalidate claimed work and persist new rate charges before provider dispatch. */
|
||||
async function admitInvocation(
|
||||
input: ToolAccessDecisionInput,
|
||||
invocationId: string,
|
||||
claim?: ToolApprovalClaim,
|
||||
): Promise<ToolAccessDecision> {
|
||||
try {
|
||||
return await db.transaction(async tx => {
|
||||
const [invocation] = await tx.select().from(toolInvocations)
|
||||
.where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId)))
|
||||
.for("update");
|
||||
// Historical reviewed requests can still have a pending invocation.
|
||||
// Accept that state only with the exact executing claim owned by the
|
||||
// gateway, locked in the same invocation-then-request order as dispatch.
|
||||
let ownsClaim = false;
|
||||
if (claim && claim.invocationId === invocationId) {
|
||||
const [request] = await tx.select().from(toolActionRequests).where(and(
|
||||
eq(toolActionRequests.id, claim.actionRequestId),
|
||||
eq(toolActionRequests.invocationId, invocationId),
|
||||
eq(toolActionRequests.companyId, input.companyId),
|
||||
)).for("update");
|
||||
ownsClaim = request?.status === "executing" && request.updatedAt.getTime() === claim.claimedAt.getTime();
|
||||
}
|
||||
if (!invocation || (claim && !ownsClaim)
|
||||
|| !(invocation.status === "executing" && invocation.policyDecision === "allow"
|
||||
|| ["awaiting_approval", "executing"].includes(invocation.status)
|
||||
&& invocation.policyDecision === "require_approval" && invocation.approvalState === "approved"
|
||||
|| invocation.status === "awaiting_approval" && invocation.policyDecision === "require_approval"
|
||||
&& invocation.approvalState === "pending" && ownsClaim)) {
|
||||
return decision("deny", "deny_policy_block", "Tool invocation admission is unavailable.", [], []);
|
||||
}
|
||||
const result = await toolAccessPolicyService(tx, options).decide(
|
||||
{ ...input, consumeRateLimit: true }, { admittedInvocationId: invocationId },
|
||||
);
|
||||
if (!result.allowed && result.decision !== "require_approval") {
|
||||
// A later policy can reject after an earlier rate rule spent a slot.
|
||||
// Roll back both the new charges and their receipt on any rejection.
|
||||
throw new RejectedInvocationAdmission(result);
|
||||
}
|
||||
const admissions = result.policyExplanation?.consumedRateAdmissions;
|
||||
if (Array.isArray(admissions) && admissions.length) {
|
||||
await tx.update(toolInvocations).set({
|
||||
policyExplanation: { ...invocation.policyExplanation, consumedRateAdmissions: admissions },
|
||||
}).where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId)));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedInvocationAdmission) return error.decision;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides one tool access request. Pass the same `cache` to every call of a
|
||||
* batch that shares one actor and run context (for example, one tools/list
|
||||
@@ -1423,9 +1485,14 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
// A final handoff rechecks current permissions for work already admitted by
|
||||
// the gateway. Its own last consumed slot cannot reject that same work.
|
||||
// Only durable consumption of an unchanged rule retains that slot; new or
|
||||
// edited rules still apply. This option never approves or consumes a call.
|
||||
const admittedRates = input.consumeRateLimit === false && options.admittedInvocationId
|
||||
// edited rules still apply. admitInvocation owns atomic consuming rechecks;
|
||||
// ordinary preflight and browser handoff callers remain read-only.
|
||||
const admittedRates = options.admittedInvocationId
|
||||
? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId) : [];
|
||||
if (options.admittedInvocationId && input.consumeRateLimit === true && admittedRates === null) {
|
||||
return decision("deny", "deny_policy_block", "Tool invocation no longer matches this admission.", [], []);
|
||||
}
|
||||
if (input.consumeRateLimit === true) consumedRateAdmissions.push(...(admittedRates ?? []));
|
||||
const profileState = await effectiveProfiles(ctx, cache);
|
||||
const effectiveProfileIds = profileState.profiles.map((profile) => profile.id);
|
||||
const permittedByProfile = profileState.profiles.some((profile) => {
|
||||
@@ -1498,7 +1565,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
);
|
||||
}
|
||||
const versionHash = ratePolicyVersionHash(policy);
|
||||
if (admittedRates.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue;
|
||||
if (admittedRates?.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue;
|
||||
const state = await enforceRateLimit(policy, ctx, input.consumeRateLimit === true);
|
||||
if (state?.limited) {
|
||||
return decision("rate_limited", "rate_limited", "Tool access rate limit exceeded.", effectiveProfileIds, [policy.id], { rateLimitState: state, redactionPlan: redaction.redactionPlan, policyExplanation });
|
||||
@@ -1524,7 +1591,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
{ redactionPlan: redaction.redactionPlan, policyExplanation },
|
||||
);
|
||||
}
|
||||
if (input.consumeRateLimit === true) {
|
||||
if (input.consumeRateLimit === true && !options.admittedInvocationId) {
|
||||
await recordTrustRuleHit(policy, ctx, redaction);
|
||||
}
|
||||
return decision("allow", "allow_trust_rule", policy.description ?? "Tool access allowed by trust rule.", effectiveProfileIds, [policy.id], { redactionPlan: redaction.redactionPlan, policyExplanation });
|
||||
@@ -2151,6 +2218,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr
|
||||
|
||||
return {
|
||||
decide,
|
||||
admitInvocation,
|
||||
writeAudit,
|
||||
recordInvocation,
|
||||
summarizeAndRedact,
|
||||
|
||||
@@ -7664,9 +7664,10 @@ export function createToolGatewayService(
|
||||
if (!(await approvedManagedArgumentsRemainCurrent(session, tool, signedPayload.arguments))) {
|
||||
throw new ToolGatewayHttpError(409, "Approved tool action managed arguments changed after review", "approved_tool_managed_arguments_changed");
|
||||
}
|
||||
const access = await policyService.decide(
|
||||
const access = await policyService.admitInvocation(
|
||||
policyInputForTool({ session, tool, parameters: signedPayload.arguments, consumeRateLimit: false }),
|
||||
{ admittedInvocationId: invocation.id },
|
||||
invocation.id,
|
||||
claim,
|
||||
);
|
||||
if (!access.allowed && access.decision !== "require_approval") {
|
||||
throw new ToolGatewayHttpError(403, access.explanation, access.reasonCode);
|
||||
@@ -8099,14 +8100,15 @@ export function createToolGatewayService(
|
||||
session,
|
||||
tool,
|
||||
);
|
||||
const currentAccess = await policyService.decide(
|
||||
const currentAccess = await policyService.admitInvocation(
|
||||
policyInputForTool({
|
||||
session,
|
||||
tool,
|
||||
parameters: signedPayload.arguments,
|
||||
consumeRateLimit: false,
|
||||
}),
|
||||
{ admittedInvocationId: invocation.id },
|
||||
invocation.id,
|
||||
claim,
|
||||
);
|
||||
if (
|
||||
!currentAccess.allowed &&
|
||||
|
||||
@@ -11,7 +11,7 @@ function minuteBucket(date: Date): Date {
|
||||
}
|
||||
|
||||
export async function incrementToolRuntimeMetricCounter(
|
||||
db: Db,
|
||||
db: Pick<Db, "insert">,
|
||||
input: {
|
||||
companyId: string;
|
||||
metric: string;
|
||||
@@ -42,7 +42,7 @@ export async function incrementToolRuntimeMetricCounter(
|
||||
});
|
||||
}
|
||||
|
||||
export async function recordToolRuntimeAuditWriteFailure(db: Db, companyId: string) {
|
||||
export async function recordToolRuntimeAuditWriteFailure(db: Pick<Db, "insert">, companyId: string) {
|
||||
try {
|
||||
await incrementToolRuntimeMetricCounter(db, {
|
||||
companyId,
|
||||
|
||||
Reference in new issue
Block a user