Files
PaperClipAI/tests/runner-e2e/manual-private-handoff.ts
T
DottaandPaperclip 018c4c9c9b Retain approved manual E2E evidence in private history (#18134)
## Thinking Path

> - Paperclip lets people manage AI agents and their work.
> - The manual AWS E2E workflow records browser and model evidence.
> - Public repository Actions artifacts are not a restricted evidence
store.
> - Some chat evidence needs the existing private-history store.
> - A target flag must not grant archive access or enable a public
fallback.
> - This pull request binds restricted runs to protected exact-source
approval and retains their standard evidence with trusted transfer code.
> - Operators can retain complete evidence without changing scanner
verdicts or scenario outcomes.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Manual AWS E2E evidence retention for exact reviewed chat-feature
selections.

**Subsystem affected**

The runner E2E manual workflow, standard evidence handoff and
private-history transfer.

**Current behavior**

Manual cell and merged evidence use Actions artifacts. In a public
repository, repository readers can download those files. Scheduled
private history does not authorize a manual target to use its role.

**Proposed behavior**

Classify sensitive selections in the trusted workflow. Require one
protected original-run approval. Verify existing private storage before
target setup or model secrets. Retain scanned standard originals and
final packaged results through a workflow-pinned runtime. Deny public
artifact and history fallback on failure.

**Reason and benefit**

Preserve inspectable standard evidence in restricted storage without
treating a private bucket as permission to retain credentials.

**Additional context**

Related source work is separate: #18067 changes paid runner routing,
#18100 changes scoped input delivery, and #17888 changes report catalog
parsing. This pull request does not include or revert those changes.

## What Changed

- Add a trusted manual classification and exact run, attempt, workflow,
target, selection and launcher approval contract.
- Add a protected manual private job. Prepare a second workflow-pinned
checkout and isolated publication dependencies before archive
credentials.
- Seal standard originals and final result bytes with exact inventories.
Reject credential contamination, unscanned carriers and changed files.
- Use existing immutable private-history archives and transfer receipts
for cells and merged reports. Keep the existing bounds.
- Use per-cell exact-key read sessions and a separate report writer.
Check every inline policy against the 2,048-character STS limit.
- Scan and seal fresh generated report logs and files with the actual
report-step credential roots before transfer.
- Require a positive nonprivate route for Actions uploads and public
history. Private failures have no public fallback. Preserve normal
catalog semantics for nonprivate selections with more than 32 IDs or
duplicate IDs.
- Authenticate generated-report fonts and every reserved trace-viewer
static asset against the exact trusted producer path and bytes,
including HTML and JavaScript. Keep standard cell evidence and unknown
carriers closed.
- Document the first eight supported IDs, deployment gates and the
operator trust boundary.

## Verification

- 57 new pure, actual-helper and actual-workflow-shell controls pass.
- 50 affected existing workflow, routing, target and private-history
controls pass. The final committed workflow security controls also pass.
- Targeted helper/test and actual launcher noEmit checks pass.
- `actionlint -shellcheck= -pyflakes=
.github/workflows/runner-full-stack-e2e.yml` passes.
- Parent `2f46336d7` required CI is green. The server 11/12 shard first
failed on database cleanup/test timing and passed one bounded recheck
with unchanged source. The original failure remains recorded.
- The preserved docs-only parent `d721c170f` had 59 terminal,
nonblocking checks and fresh Greptile 5/5. Three later review comments
exposed a genuine static-report asset failure and nonprivate selector
regression; their parent counterexamples remain recorded.
- The reviewed parent passes 76 focused controls across nine files. The
final dependency preflight successor passes all six affected controls,
including two new actual `prepare` subprocess controls, and targeted
helper/test noEmit. Unchanged suites were not repeated. A synthetic
Node-only Playwright HTML/blob/JUnit report and the real dashboard
renderer/brand stager pass the actual sealer, strict archive and
immutable receipt path; only AWS transport is synthetic. No browser or
product setup runs in that test.
- Default cell fonts/SVGs, unknown report files, forged paths, altered
static bytes, recomputed inventory tampering and registered credential
matches remain rejected. Eligibility and remaining-byte checks run
before body reads in both sealer and transfer validator; both
independent parent read-order failures are preserved.
- The pre-credential target comparison also binds the new
generated-report asset helper byte for byte. A genuine
tampered-dependency parent failure is preserved.
- Six additional actual sealer/validator controls expose the
standard-extension trace-owner bypass on the parent. All 34 affected
controls pass on its correction, including the real
producer/archive/receipt test; targeted noEmit passes. Ordinary dynamic
report HTML outside the reserved trace directory is unchanged.
- Final head `43683c4e0` passes both required gates, `ci / verify` and
`ci / e2e`, in normal CI run `40849916302` attempt 1. All 59 rollup
checks/statuses are terminal and nonblocking (55 success, two neutral,
two skipped).
- Fresh exact-head Greptile is 5/5; automated review is terminal and all
technical threads are resolved. Human CODEOWNER approval remains a
separate gate. Earlier source, genuine counterexamples and CI history
remain preserved.
- Full local build and live E2E were not run. This task prohibits local
SDK/native/server builds and paid or AWS operations. Normal pull request
CI must pass before merge readiness.
- No existing artifact bodies, archives, media or provider reasoning
were inspected. Synthetic owned fixtures prove the privacy boundaries.

## Risks

- Deployment still needs the existing private bucket, role and protected
environments. Both environments need the exact original-run approval
variable.
- Targets need the compatible handoff protocol and a separately reviewed
exact launcher digest. Existing target branches do not become ready
automatically.
- Complete duplicated originals and packaged evidence can exceed
existing archive limits. Such a transfer fails; files are not silently
removed.
- Required evidence omissions remain fatal to PASS. Safe failed evidence
is retained with an explicit missing list and incomplete
required-evidence verdict. Credential contamination still blocks all
original uploads. Restricted storage does not waive PNG, HTML, blob or
scanner checks.
- This is operator-approved source execution. Target processes can
inherit the job's OIDC request environment and may re-assume a role.
Inline session attenuation is not isolation from malicious approved
source.
- Operator authorization must bind the actual exact source and original
run. A proven administrator-controlled record may supply it without an
environment reviewer UI. No new approval UI or environment change is
required by this PR.
- Required repository CODEOWNER review is still pending. Commented
reviews and review requests are not approvals. This PR stays open and
unmerged.
- This PR does not deploy infrastructure, change IAM, dispatch
workflows, publish report payloads, change grades or transfer prior
scenario passes.

## Model Used

OpenAI `gpt-6.1-sol` in Codex. Used code execution, source analysis and
tool calls. The host does not expose the context window size.
Independent peer review used the same model family in a separate agent.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-29 08:51:40 -05:00

175 lines
13 KiB
TypeScript

import { constants } from "node:fs";
import { createHash } from "node:crypto";
import { copyFile, lstat, mkdir, open, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { packageEvidence, isStandardEvidencePath, isStandardEvidenceFile, type EvidencePackageResult } from "./evidence.js";
import { canonicalGeneratedReportAsset, isTrustedGeneratedReportAsset } from "./manual-private-report-assets.js";
import { assertSecretFree, normalizedSecrets } from "./redaction.js";
import { MANUAL_PRIVATE_PROTOCOL, manualCellKind, type ManualRetentionIdentity } from "./manual-private-retention.js";
export interface ManualPrivateHandoff extends ManualRetentionIdentity {
protocol: typeof MANUAL_PRIVATE_PROTOCOL; private: true; root: string;
}
export async function readManualPrivateHandoff(env: NodeJS.ProcessEnv, ids: string[]): Promise<ManualPrivateHandoff | undefined> {
const file = env.PAPERCLIP_RUNNER_E2E_PRIVATE_PREFLIGHT;
if (!file) return undefined;
const metadata = await lstat(file);
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 65536 || metadata.mode & 0o077
|| typeof process.getuid === "function" && metadata.uid !== process.getuid()) throw new Error("Invalid private evidence preflight custody");
const receipt = JSON.parse(await readFile(file, "utf8")) as ManualPrivateHandoff & { status: string };
if (receipt.protocol !== MANUAL_PRIVATE_PROTOCOL || receipt.status !== "verified" || receipt.private !== true
|| receipt.runId !== env.GITHUB_RUN_ID || receipt.attempt !== env.GITHUB_RUN_ATTEMPT || receipt.attempt !== "1"
|| receipt.workflowSha !== env.GITHUB_SHA || receipt.targetSha !== env.PAPERCLIP_RUNNER_E2E_SOURCE_SHA || receipt.executionIds.length !== ids.length
|| [...receipt.executionIds].sort().join() !== [...ids].sort().join()) throw new Error("Private evidence preflight does not match this exact attempt");
const root = await realpath(receipt.root), temporary = await realpath(env.RUNNER_TEMP ?? "");
const directory = await lstat(root);
if (!root.startsWith(`${temporary}${path.sep}`) || root !== path.dirname(await realpath(file))
|| !directory.isDirectory() || directory.isSymbolicLink() || directory.mode & 0o077
|| typeof process.getuid === "function" && directory.uid !== process.getuid()) throw new Error("Invalid private evidence staging ownership");
return Object.freeze({ ...receipt, root });
}
export async function preserveOriginalFrameworkResult(directory: string) {
const source = path.join(directory, "result.json");
const info = await lstat(source).catch(error => { if (error.code === "ENOENT") return undefined; throw error; });
if (!info) return;
if (!info.isFile() || info.isSymbolicLink()) throw new Error("Invalid original framework result");
const destination = path.join(directory, "snapshots", "manual-original-framework-result.json");
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
await copyFile(source, destination, constants.COPYFILE_EXCL);
}
export async function sealStandardOriginalEvidence(input: {
context: ManualPrivateHandoff; executionId: string; source: string; evidence: EvidencePackageResult; secrets: readonly string[]; expectPassScreenshot: boolean;
}) {
if (!input.context.executionIds.includes(input.executionId)) throw new Error("Private evidence execution is outside preflight");
const secrets = normalizedSecrets(input.secrets).flatMap(value => [value, encodeURIComponent(value), Buffer.from(value).toString("base64"), Buffer.from(value).toString("base64url")]);
const out = path.join(input.context.root, "originals", manualCellKind(input.executionId));
const root = await realpath(input.source), info = await lstat(input.source);
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("Invalid original standard evidence root");
if (input.evidence.leaks.length) {
await writeFile(path.join(input.context.root, "contamination.json"), JSON.stringify({ protocol: MANUAL_PRIVATE_PROTOCOL,
status: "withheld_credential_contamination", complete: false }), { mode: 0o600, flag: "wx" });
throw new Error("Credential-contaminated original evidence cannot be retained");
}
const parent = path.dirname(out);
await mkdir(parent, { recursive: true, mode: 0o700 });
if (!(await realpath(parent)).startsWith(`${await realpath(input.context.root)}${path.sep}`)) throw new Error("Private original handoff escaped its preflight root");
await mkdir(out, { mode: 0o700 });
const records: Array<{ path: string; bytes: number; sha256: string }> = [];
let visited = 0, bytes = 0;
let missingRequiredEvidence: string[] = [];
async function visit(relative: string) {
for (const entry of await readdir(path.join(root, relative), { withFileTypes: true })) {
if (++visited > 4096) throw new Error("Complete original evidence exceeds entry allowance");
const name = relative ? `${relative}/${entry.name}` : entry.name;
if (entry.isSymbolicLink() || !entry.isDirectory() && !entry.isFile()) throw new Error("Original evidence contains an unsupported entry");
if (entry.isDirectory()) {
if (name.split("/").length > 24) throw new Error("Original evidence exceeds depth allowance");
if (isStandardEvidencePath(`${name}/placeholder`)) await visit(name);
continue;
}
if (!isStandardEvidencePath(name)) continue;
if (!isStandardEvidenceFile(name)) throw new Error("Unsupported original evidence carrier cannot be retained");
assertSecretFree(name, secrets, "private evidence path");
const source = path.join(root, name), target = path.join(out, name);
if (!(await realpath(source)).startsWith(`${root}${path.sep}`)) throw new Error("Original evidence escaped its owned root");
const handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);
try {
const before = await handle.stat(); bytes += before.size;
if (!before.isFile() || !Number.isSafeInteger(bytes) || bytes > 256 * 1024 * 1024) throw new Error("Complete original evidence exceeds byte allowance");
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
const output = await open(target, "wx", 0o600), hash = createHash("sha256"), buffer = Buffer.alloc(65536);
try {
let copied = 0;
while (copied < before.size) {
const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, before.size - copied), copied);
if (!bytesRead) throw new Error("Original evidence changed during handoff");
hash.update(buffer.subarray(0, bytesRead)); let written = 0;
while (written < bytesRead) { const part = await output.write(buffer, written, bytesRead - written, copied + written); if (!part.bytesWritten) throw new Error("Original evidence copy stopped"); written += part.bytesWritten; }
copied += bytesRead;
}
const after = await handle.stat();
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new Error("Original evidence changed during handoff");
await output.sync(); records.push({ path: name, bytes: copied, sha256: hash.digest("hex") });
} finally { await output.close(); }
} finally { await handle.close(); }
}
}
try {
await visit("");
const validation = path.join(input.context.root, `validation-${manualCellKind(input.executionId)}`);
await mkdir(validation, { mode: 0o700 });
try {
const scan = await packageEvidence({ privateDir: out, uploadDir: validation, secrets, expectPassScreenshot: input.expectPassScreenshot });
missingRequiredEvidence = scan.missing;
if (scan.leaks.length) {
await writeFile(path.join(input.context.root, "contamination.json"), JSON.stringify({ protocol: MANUAL_PRIVATE_PROTOCOL, status: "withheld_credential_contamination", complete: false }), { mode: 0o600, flag: "wx" });
throw new Error("Original evidence failed unchanged privacy or required-file checks");
}
} finally { await rm(validation, { recursive: true, force: true }); }
records.sort((a, b) => a.path.localeCompare(b.path));
const receipt = { protocol: MANUAL_PRIVATE_PROTOCOL, executionId: input.executionId, targetSha: input.context.targetSha,
complete: true, requiredEvidenceComplete: input.expectPassScreenshot ? missingRequiredEvidence.length === 0 : null,
missingRequiredEvidence, sourceBytes: bytes, files: records, inventorySha256: createHash("sha256").update(JSON.stringify(records)).digest("hex") };
const serialized = `${JSON.stringify(receipt, null, 2)}\n`;
assertSecretFree(serialized, secrets, "private evidence inventory");
await writeFile(path.join(out, "original-evidence-inventory.json"), serialized, { mode: 0o600, flag: "wx" });
return receipt;
} catch (error) { await rm(out, { recursive: true, force: true }); throw error; }
}
export async function sealManualResultEvidence(context: ManualPrivateHandoff, secrets: readonly string[], source = path.join(context.root, "results"), treeKind: "standard" | "generated-report" = "standard") {
const root = await realpath(source), owned = await realpath(context.root);
if (!root.startsWith(`${owned}${path.sep}`)) throw new Error("Packaged evidence escaped its owned root");
const wrapper = path.join(context.root, "result-validation");
const { cp, rename } = await import("node:fs/promises");
await mkdir(wrapper, { mode: 0o700 });
const records: Array<{ path: string; bytes: number; sha256: string }> = [];
let bytes = 0;
const scanSecrets = normalizedSecrets(secrets).flatMap(value => [value, encodeURIComponent(value), Buffer.from(value).toString("base64"), Buffer.from(value).toString("base64url")]);
async function visit(relative: string) {
for (const entry of await readdir(path.join(root, relative), { withFileTypes: true })) {
const name = relative ? `${relative}/${entry.name}` : entry.name;
assertSecretFree(name, scanSecrets, "private packaged evidence path");
if (entry.isSymbolicLink() || !entry.isFile() && !entry.isDirectory() || name.split("/").length > 24) throw new Error("Invalid packaged evidence entry");
if (entry.isDirectory()) { await visit(name); continue; }
const standard = isStandardEvidenceFile(`html-report/${name}`);
const canonical = treeKind === "generated-report" ? canonicalGeneratedReportAsset(name) : undefined;
const staticReportOwner = treeKind === "generated-report" && (name.startsWith("html/trace/") || canonical !== undefined);
if (staticReportOwner ? !canonical : !standard) throw new Error("Unsupported packaged evidence carrier");
const file = path.join(root, name), metadata = await lstat(file);
if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error("Invalid packaged evidence entry");
if (metadata.size > 256 * 1024 * 1024 - bytes || records.length >= 4096) throw new Error("Complete packaged evidence exceeds allowance");
const data = await readFile(file);
if (staticReportOwner) {
if (!await isTrustedGeneratedReportAsset(name, data)) throw new Error("Unsupported packaged evidence carrier");
assertSecretFree(data, scanSecrets, "authenticated static report asset");
}
bytes += data.length;
if (bytes > 256 * 1024 * 1024) throw new Error("Complete packaged evidence exceeds allowance");
records.push({ path: name, bytes: data.length, sha256: createHash("sha256").update(data).digest("hex") });
}
}
try {
await visit("");
if (!records.length) throw new Error("No genuine packaged evidence was produced");
await cp(root, path.join(wrapper, "html-report"), { recursive: true, errorOnExist: true, force: false });
const validation = path.join(context.root, "packaged-scan");
try {
const scan = await packageEvidence({ privateDir: wrapper, uploadDir: validation, secrets: scanSecrets, expectPassScreenshot: false });
if (scan.leaks.length) throw new Error("Packaged evidence contains credential contamination");
for (const record of records) {
if (createHash("sha256").update(await readFile(path.join(wrapper, "html-report", record.path))).digest("hex") !== record.sha256)
throw new Error("Packaged evidence changed during handoff");
}
} finally { await rm(validation, { recursive: true, force: true }); }
records.sort((a, b) => a.path.localeCompare(b.path));
const receipt = { protocol: MANUAL_PRIVATE_PROTOCOL, treeKind, complete: true, sourceBytes: bytes, files: records,
inventorySha256: createHash("sha256").update(JSON.stringify(records)).digest("hex") };
const serialized = `${JSON.stringify(receipt, null, 2)}\n`;
assertSecretFree(serialized, scanSecrets, "private packaged inventory");
await writeFile(path.join(wrapper, "result-evidence-inventory.json"), serialized, { mode: 0o600, flag: "wx" });
await rename(wrapper, path.join(context.root, "sealed-results"));
return receipt;
} catch (error) { await rm(wrapper, { recursive: true, force: true }); throw error; }
}