mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-30 21:49:18 +01:00
## 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>
171 lines
9.5 KiB
TypeScript
171 lines
9.5 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { createReadStream } from "node:fs";
|
|
import { createHash } from "node:crypto";
|
|
import { lstat, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import { pathToFileURL } from "node:url";
|
|
import { BoundedHistoryPublisher } from "./history-budget.js";
|
|
|
|
const execFileAsync = promisify(execFile);
|
|
export const PRIVATE_HISTORY_PREFIX = "runner-e2e-private/bounded-v1";
|
|
export const PRIVATE_ARCHIVE_BYTES = 264 * 1024 * 1024;
|
|
|
|
export function privateArtifactKey(kind: string, runId: string) {
|
|
if (!(["evidence", "report", "protocol-control", "protocol-report"].includes(kind)
|
|
|| /^protocol-cell-[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(kind)
|
|
|| /^manual-cell-[0-9a-f]{64}$/.test(kind) || kind === "manual-report") || !/^[1-9][0-9]{0,19}$/.test(runId)) {
|
|
throw new Error("Private history needs a supported artifact kind and numeric workflow run ID");
|
|
}
|
|
return `${PRIVATE_HISTORY_PREFIX}/campaigns/gha-${runId}-1/${kind}.zip`;
|
|
}
|
|
|
|
export async function archivePrivateEvidence(operation: "pack" | "unpack", source: string, destination: string) {
|
|
const result = await execFileAsync("python3", [path.join(import.meta.dirname, "private-history-archive.py"), operation, source, destination], {
|
|
timeout: 60_000, maxBuffer: 64 * 1024,
|
|
});
|
|
return JSON.parse(result.stdout) as { files: number; sourceBytes: number; archiveBytes?: number };
|
|
}
|
|
|
|
export async function verifyPrivateHistory(publisher: BoundedHistoryPublisher, bucket: string) {
|
|
if (!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket)) throw new Error("Invalid private history bucket");
|
|
await publisher.verifyRetention(bucket, PRIVATE_HISTORY_PREFIX);
|
|
const configuration = async (operation: string) => JSON.parse((await publisher.run(["s3api", operation, "--bucket", bucket])).stdout);
|
|
const block = (await configuration("get-public-access-block")).PublicAccessBlockConfiguration;
|
|
if (!["BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"].every(key => block?.[key] === true)) {
|
|
throw new Error("Private history requires all bucket public-access blocks");
|
|
}
|
|
const ownership = (await configuration("get-bucket-ownership-controls")).OwnershipControls?.Rules;
|
|
if (!Array.isArray(ownership) || ownership.length !== 1 || ownership[0]?.ObjectOwnership !== "BucketOwnerEnforced") {
|
|
throw new Error("Private history requires disabled object ACLs");
|
|
}
|
|
const policy = JSON.parse((await configuration("get-bucket-policy")).Policy);
|
|
if (!Array.isArray(policy.Statement) || policy.Statement.some((statement: { Effect?: string }) => statement.Effect !== "Deny")) {
|
|
throw new Error("Private history bucket policy must not grant access to external readers or a CDN");
|
|
}
|
|
}
|
|
|
|
export interface PrivateEvidenceCompleteness {
|
|
meaning: "available-files-and-transfer-only";
|
|
doesNotAttestFeatureOutcome: true;
|
|
cells: Array<{ executionId: string; availableFileInventoryComplete: true; requiredPassEvidenceComplete: boolean | null; missingRequiredEvidence: string[] }>;
|
|
}
|
|
|
|
type TransferOptions = {
|
|
operation: "upload" | "download";
|
|
kind: string;
|
|
runId: string;
|
|
directory: string;
|
|
bucket: string;
|
|
publisher: BoundedHistoryPublisher;
|
|
receiptIdentity?: string;
|
|
evidenceCompleteness?: PrivateEvidenceCompleteness;
|
|
};
|
|
|
|
function privateTransferReceiptKey(options: TransferOptions) {
|
|
const key = privateArtifactKey(options.kind, options.runId);
|
|
if (options.receiptIdentity !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(options.receiptIdentity)) {
|
|
throw new Error("Invalid private transfer receipt identity");
|
|
}
|
|
const identity = options.receiptIdentity === undefined ? "" : `.${createHash("sha256").update(options.receiptIdentity).digest("hex")}`;
|
|
return `${key}.${options.operation}${identity}-receipt.json`;
|
|
}
|
|
|
|
export async function transferPrivateArtifact(options: TransferOptions) {
|
|
privateArtifactKey(options.kind, options.runId);
|
|
await verifyPrivateHistory(options.publisher, options.bucket);
|
|
return transferVerifiedArtifact(options);
|
|
}
|
|
|
|
async function transferVerifiedArtifact(options: TransferOptions) {
|
|
const key = privateArtifactKey(options.kind, options.runId);
|
|
const temporary = await mkdtemp(path.join(os.tmpdir(), "paperclip-private-history-"));
|
|
const archive = path.join(temporary, "archive.zip");
|
|
try {
|
|
if (options.operation === "upload") {
|
|
const metadata = await archivePrivateEvidence("pack", options.directory, archive);
|
|
const hash = createHash("sha256");
|
|
for await (const chunk of createReadStream(archive)) hash.update(chunk);
|
|
const result = await options.publisher.upload(options.bucket, key, archive, "application/zip", "private, no-store", true);
|
|
const response = JSON.parse(result.stdout) as { VersionId?: string };
|
|
if (!response.VersionId) throw new Error("Private archive upload did not return a version identity");
|
|
return { private: true, ...metadata, uri: `s3://${options.bucket}/${key}`, versionId: response.VersionId, sha256: hash.digest("hex") };
|
|
}
|
|
await options.publisher.run(["s3api", "get-object", "--bucket", options.bucket, "--key", key,
|
|
"--range", `bytes=0-${PRIVATE_ARCHIVE_BYTES}`, archive]);
|
|
if ((await lstat(archive)).size > PRIVATE_ARCHIVE_BYTES) throw new Error("Private archive exceeds transfer allowance");
|
|
const metadata = await archivePrivateEvidence("unpack", archive, options.directory);
|
|
const hash = createHash("sha256");
|
|
for await (const chunk of createReadStream(archive)) hash.update(chunk);
|
|
return { ...metadata, uri: `s3://${options.bucket}/${key}`, sha256: hash.digest("hex") };
|
|
} finally {
|
|
await rm(temporary, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
export async function retainPrivateTransfer(options: TransferOptions, receipt: string, receiptPublisher?: () => BoundedHistoryPublisher) {
|
|
const receiptKey = privateTransferReceiptKey(options);
|
|
await verifyPrivateHistory(options.publisher, options.bucket);
|
|
let result: Awaited<ReturnType<typeof transferVerifiedArtifact>> | undefined;
|
|
let failure: unknown;
|
|
try {
|
|
result = await transferVerifiedArtifact(options);
|
|
} catch (error) {
|
|
failure = error;
|
|
}
|
|
if (receiptPublisher) {
|
|
await options.publisher.save();
|
|
const snapshot = JSON.stringify({ ...JSON.parse(await readFile(receipt, "utf8")),
|
|
...(options.receiptIdentity === undefined ? {} : { receiptIdentity: options.receiptIdentity }),
|
|
...(options.evidenceCompleteness === undefined ? {} : { evidenceCompleteness: options.evidenceCompleteness }),
|
|
transfer: result ? { status: "complete", ...result } : { status: "failed_or_unknown" },
|
|
receiptUpload: { status: "pending_at_snapshot", maxBytes: 1024 * 1024 } });
|
|
if (Buffer.byteLength(snapshot) > 1024 * 1024) throw new Error("Private transfer receipt exceeds allowance");
|
|
await writeFile(`${receipt}.transfer.json`, snapshot, { mode: 0o600, flag: "wx" });
|
|
try {
|
|
await receiptPublisher().upload(options.bucket, receiptKey, `${receipt}.transfer.json`, "application/json", "private, no-store", true);
|
|
} catch (retentionError) {
|
|
throw new AggregateError(failure ? [failure, retentionError] : [retentionError], "Private transfer receipt retention failed; local receipts remain authoritative");
|
|
}
|
|
}
|
|
if (failure) throw failure;
|
|
return result!;
|
|
}
|
|
|
|
async function main() {
|
|
const [operation, kind, runId, directory, receiptIdentity] = process.argv.slice(2);
|
|
if (!["verify", "upload", "download"].includes(operation ?? "") || !kind || !runId || !directory) {
|
|
throw new Error("Usage: private-history.ts verify|upload|download KIND RUN_ID DIRECTORY [RECEIPT_ID]");
|
|
}
|
|
privateArtifactKey(kind, runId);
|
|
if (receiptIdentity !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(receiptIdentity)
|
|
|| kind === "protocol-control" && operation === "download" && !receiptIdentity || process.argv.length > 7) {
|
|
throw new Error("Shared protocol downloads require a bounded unique receipt identity");
|
|
}
|
|
if (process.env.GITHUB_ACTIONS === "true" && (process.env.GITHUB_RUN_ATTEMPT !== "1" || process.env.GITHUB_RUN_ID !== runId)) {
|
|
throw new Error("Private bounded history accepts only the initial attempt of this workflow run");
|
|
}
|
|
const bucket = process.env.RUNNER_E2E_PRIVATE_HISTORY_S3_BUCKET ?? "";
|
|
const label = kind.startsWith("protocol-") ? createHash("sha256").update(`${kind}:${receiptIdentity ?? ""}`).digest("hex") : kind;
|
|
const receipt = path.resolve(`private-history-${operation}-${label}-${runId}.json`);
|
|
await (await open(receipt, "wx", 0o600)).close();
|
|
const publisher = new BoundedHistoryPublisher(receipt);
|
|
if (operation === "verify") {
|
|
await verifyPrivateHistory(publisher, bucket);
|
|
console.log("Private retention and access checks passed");
|
|
return;
|
|
}
|
|
const receiptPublisher = operation === "upload" || process.env.GITHUB_ACTIONS === "true"
|
|
? () => new BoundedHistoryPublisher(`${receipt}.retention.json`) : undefined;
|
|
const result = await retainPrivateTransfer({ operation: operation as "upload" | "download", kind, runId, directory, bucket, publisher, receiptIdentity }, receipt, receiptPublisher);
|
|
console.log(JSON.stringify(process.env.GITHUB_ACTIONS === "true" ? { version: 1, privateTransferCompleted: true } : result));
|
|
}
|
|
|
|
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
main().catch(error => {
|
|
console.error(process.env.GITHUB_ACTIONS === "true" ? "Private history transfer failed; inspect private retained evidence." : error instanceof Error ? error.message : String(error));
|
|
process.exitCode = 1;
|
|
});
|
|
}
|