Files
PaperClipAI/server/src/services/source-trust.ts
T
Dotta c5a705ce92 fix(trust): enforce low-trust sourceTrust quarantine on native comments and documents (#23621)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The low-trust review preset isolates untrusted agent runs and marks
their raw outputs with `sourceTrust` quarantine metadata so higher-trust
agents do not ingest raw output without promotion
> - HTTP route writes tagged low-trust comments and documents with
`sourceTrust`, but internal native completion replies, finalizer
recoveries, continuation summary updates, and non-Muse native runner
tool writes (`report_progress`, `write_document`) persisted
`sourceTrust: null`
> - Higher-trust non-Muse native runner reads (`list_documents`,
`read_document`) also bypassed document quarantine redaction
> - This pull request resolves `sourceTrust` centrally in
`issueService.addComment` and `documentService.upsertIssueDocument`
whenever an agent writes without an explicit `sourceTrust` value,
removes the `museRuntime` gate on native runner `report_progress` and
`write_document` writes, and redacts quarantined documents on
higher-trust non-Muse native runner reads
> - The benefit is that raw outputs from low-trust native runs retain
quarantine metadata across all comment and document write paths and stay
redacted from higher-trust agents until promoted

## Linked Issues or Issue Description

**What happened?**
When an agent running under the `low_trust_review` preset completed a
native run or called native runner tools (`report_progress`,
`write_document`), its comments and documents were saved with
`sourceTrust: null`. Because `sourceTrust` was null, higher-trust agents
could read the raw low-trust output directly through ordinary comment
and document access without promotion.

**Expected behavior**
All agent-authored comments and documents produced under
`low_trust_review`—including native run completion replies, recovered
finalizer replies, continuation summary updates, and non-Muse native
runner `report_progress` / `write_document` writes—must persist
`sourceTrust` with `preset: "low_trust_review"` and `disposition:
"quarantined"`, and higher-trust agents must receive the quarantined
redaction placeholder instead of the raw body.

**Steps to reproduce**
1. Configure an agent with `trustPreset: "low_trust_review"` and a valid
`trustBoundary`.
2. Run a native task on that agent so it writes a completion reply,
calls `report_progress` or `write_document`, or refreshes
`continuation-summary`.
3. Read the resulting comment or document as a standard-trust agent via
`get_task_history`, `list_documents`, `read_document`, or ordinary
comment reads.
4. Before this fix, `sourceTrust` is `null` and the raw body is returned
unredacted.

**Paperclip version or commit**
`master` (`ce204a223a`)

## What Changed

- **`server/src/services/issues.ts`**: Updated `issueService.addComment`
to select `projectId` and `executionPolicy` on the target issue and
resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever
`actor.agentId` is set and `options?.sourceTrust === undefined`. This
covers native run completion replies (`run-completion.ts`), recovered
finalizer replies (`native-run-finalizer.ts`), status decision committer
comments (`status-decision-committer.ts`), and internal agent comment
writes.
- **`server/src/services/documents.ts`**: Updated
`documentService.upsertIssueDocument` to select `projectId` and
`executionPolicy` on the target issue and resolve `sourceTrust` via
`resolveActorSourceTrustForIssue` whenever `input.createdByAgentId` is
set and `input.sourceTrust === undefined`. This covers continuation
summary refreshes (`issue-continuation-summary.ts`), native plan writes
(`native-session-executor.ts`), and internal agent document writes.
-
**`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`**:
Removed the `this.binding.museRuntime` guard on
`resolveActorSourceTrustForIssue` in `report_progress` and
`write_document` so all `paperclip_runner` runs tag writes consistently,
and added higher-trust quarantine redaction
(`redactQuarantinedBodyForHigherTrust`) for non-Muse `list_documents`
and `read_document` reads.
- **`server/src/__tests__/source-trust.test.ts`**: Added red-green
regression tests covering `addComment` without explicit `sourceTrust`,
`upsertIssueDocument` without explicit `sourceTrust`, and non-Muse
`PaperclipRunnerToolAuthority` `report_progress` / `write_document`
writes read by a higher-trust agent via `get_task_history`,
`list_documents`, and `read_document`.

## Verification

- Confirmed the new regression tests failed before the fix
(`sourceTrust` received `null` on `addComment` and
`upsertIssueDocument`).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/source-trust.test.ts` — 10/10 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/low-trust-red-team-routes.test.ts` — 14/14 passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-continuation-summary.test.ts` — 8/8 passed.
- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.
- `pnpm verify` exited 2 (broad CI coverage required); CI will run the
full required check matrix on this PR.

## Risks

- Low risk. Standard-trust agent writes continue to resolve to
`sourceTrust: null` (unchanged behavior).
- Callers that already pass an explicit `sourceTrust` value (such as
promotion flows or HTTP routes) keep their explicit value without extra
work.
- Only newly inserted comments and agent-authored document upserts
without an explicit `sourceTrust` perform the policy lookup inside the
existing transaction.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use and
local code/test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
2026-12-04 09:45:38 -06:00

208 lines
6.4 KiB
TypeScript

import { and, eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, heartbeatRuns, projects } from "@paperclipai/db";
import {
LOW_TRUST_REVIEW_PRESET,
type SourceTrustMetadata,
} from "@paperclipai/shared";
import { forbidden } from "../errors.js";
import { readObject } from "../lib/objects.js";
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
export const LOW_TRUST_QUARANTINED_BODY =
"[Quarantined low-trust output omitted from higher-trust agent context. A trusted reviewer can inspect and promote a sanitized artifact.]";
export type SourceTrustActor = {
actorType: "agent" | "user";
actorId: string;
agentId: string | null;
runId: string | null;
};
export type SourceTrustIssueContext = {
id: string;
companyId: string;
projectId?: string | null;
executionPolicy?: unknown;
};
export function isLowTrustQuarantined(sourceTrust: SourceTrustMetadata | null | undefined): boolean {
return sourceTrust?.preset === LOW_TRUST_REVIEW_PRESET && sourceTrust.disposition === "quarantined";
}
export function redactQuarantinedBodyForHigherTrust<T extends { body?: string | null; sourceTrust?: SourceTrustMetadata | null }>(
value: T,
): T {
if (!isLowTrustQuarantined(value.sourceTrust)) return value;
return {
...value,
body: LOW_TRUST_QUARANTINED_BODY,
} as T;
}
export function sanitizeQuarantinedCommentForHigherTrust<
T extends {
body: string;
presentation?: unknown;
metadata?: unknown;
sourceTrust?: SourceTrustMetadata | null;
},
>(comment: T): T {
if (!isLowTrustQuarantined(comment.sourceTrust)) return comment;
return {
...comment,
body: LOW_TRUST_QUARANTINED_BODY,
presentation: null,
metadata: null,
};
}
export function buildLowTrustSourceTrust(input: {
issueId: string;
runId?: string | null;
agentId?: string | null;
}): SourceTrustMetadata {
return {
preset: LOW_TRUST_REVIEW_PRESET,
disposition: "quarantined",
sourceIssueId: input.issueId,
sourceRunId: input.runId ?? null,
sourceAgentId: input.agentId ?? null,
};
}
export function buildPromotedSourceTrust(input: {
sourceIssueId: string;
sourceArtifactKind: "comment" | "document" | "work_product" | "issue";
sourceArtifactId: string;
promotedByActorType: "agent" | "user" | "system";
promotedByActorId: string;
promotedAt?: Date;
}): SourceTrustMetadata {
return {
preset: LOW_TRUST_REVIEW_PRESET,
disposition: "promoted",
sourceIssueId: input.sourceIssueId,
promotedFrom: {
artifactKind: input.sourceArtifactKind,
artifactId: input.sourceArtifactId,
issueId: input.sourceIssueId,
},
promotedByActorType: input.promotedByActorType,
promotedByActorId: input.promotedByActorId,
promotedAt: (input.promotedAt ?? new Date()).toISOString(),
};
}
export type ActorSourceTrustResolution =
| { kind: "standard"; sourceTrust: null }
| { kind: "low_trust_review"; sourceTrust: SourceTrustMetadata }
| { kind: "unverified_run"; sourceTrust: SourceTrustMetadata };
export async function resolveActorSourceTrustStateForIssue(input: {
db: Db;
issue: SourceTrustIssueContext;
actor: SourceTrustActor;
}): Promise<ActorSourceTrustResolution> {
if (input.actor.actorType !== "agent" || !input.actor.agentId) {
return { kind: "standard", sourceTrust: null };
}
const [agent, project, run] = await Promise.all([
input.db
.select({
companyId: agents.companyId,
permissions: agents.permissions,
})
.from(agents)
.where(and(eq(agents.id, input.actor.agentId), eq(agents.companyId, input.issue.companyId)))
.then((rows) => rows[0] ?? null),
input.issue.projectId
? input.db
.select({
companyId: projects.companyId,
executionWorkspacePolicy: projects.executionWorkspacePolicy,
})
.from(projects)
.where(and(eq(projects.id, input.issue.projectId), eq(projects.companyId, input.issue.companyId)))
.then((rows) => rows[0] ?? null)
: Promise.resolve(null),
input.actor.runId
? input.db
.select({
companyId: heartbeatRuns.companyId,
agentId: heartbeatRuns.agentId,
contextSnapshot: heartbeatRuns.contextSnapshot,
})
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, input.actor.runId), eq(heartbeatRuns.companyId, input.issue.companyId)))
.then((rows) => rows[0] ?? null)
: Promise.resolve(null),
]);
if (input.actor.runId && (!run || run.agentId !== input.actor.agentId)) {
// Fail closed on writes: an unknown or mismatched run cannot prove higher trust, so tag the write as quarantined.
// Callers on read paths use `kind` via `isPositivelyLowTrustReaderForIssue` so unverifiable runs also fail closed.
return {
kind: "unverified_run",
sourceTrust: buildLowTrustSourceTrust({
issueId: input.issue.id,
runId: input.actor.runId,
agentId: input.actor.agentId,
}),
};
}
const runContext = readObject(run?.contextSnapshot);
const runExecutionPolicy = readObject(runContext?.executionPolicy);
const resolution = resolveCoreTrustPreset({
companyId: input.issue.companyId,
agent,
project,
issue: {
companyId: input.issue.companyId,
executionPolicy: input.issue.executionPolicy,
},
run: run
? {
companyId: run.companyId,
executionPolicy: runExecutionPolicy,
}
: null,
});
if (resolution.kind === "denied") {
throw forbidden(resolution.detail);
}
if (resolution.kind !== "low_trust_review") {
return { kind: "standard", sourceTrust: null };
}
return {
kind: "low_trust_review",
sourceTrust: buildLowTrustSourceTrust({
issueId: input.issue.id,
runId: input.actor.runId,
agentId: input.actor.agentId,
}),
};
}
export async function resolveActorSourceTrustForIssue(input: {
db: Db;
issue: SourceTrustIssueContext;
actor: SourceTrustActor;
}): Promise<SourceTrustMetadata | null> {
const resolved = await resolveActorSourceTrustStateForIssue(input);
return resolved.sourceTrust;
}
export async function isPositivelyLowTrustReaderForIssue(input: {
db: Db;
issue: SourceTrustIssueContext;
actor: SourceTrustActor;
}): Promise<boolean> {
const resolved = await resolveActorSourceTrustStateForIssue(input);
return resolved.kind === "low_trust_review";
}