mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart-chaos harness runs real agent tasks while it injects infrastructure faults > - `--storage s3` already puts a fault proxy between the server and a loopback MinIO (ST1 outage, ST2 latency, ST3 errors) > - Cloud deployments use the default AWS credential chain, and keys can expire or rotate during a run > - The harness had no fault for a rejected or rotated key, so this failure class was untested > - This pull request adds ST5 (a window of 403 credential rejections from the proxy) and ST5R (a real key rotation at MinIO) > - The benefit is that waves can prove runs wait out credential problems and pick up rotated keys ## Linked Issues or Issue Description **What existing behavior does this improve?** The restart-chaos storage faults cover outages, latency and 5xx errors only. **Subsystem affected** tests/restart-chaos (storage chaos). **Current behavior** No wave can reject the server's S3 credentials or rotate the store's key. **Proposed behavior** `--storage-faults ST5` answers every request in a window with 403 `ExpiredToken`, `InvalidAccessKeyId` or `SignatureDoesNotMatch`. `--storage-faults ST5R` restarts MinIO with a new root key (the old key stops working) and gives the server the new key through its credential source only when the window ends. **Reason and benefit** The first local ST5 wave (w-20261110T041556-s501) shows the gap: a 41 s `ExpiredToken` window failed 4 of 6 tasks with `adapter_failed`, and the automatic retries failed within one second. The product fix is a separate PR. ## What Changed - `tests/restart-chaos/storage-credentials.ts` (new): ST5 and ST5R rule planning, a wave-owned `AWS_CONFIG_FILE` profile whose `credential_process` prints the current key, MinIO restart with a new root key on the same loopback port, and a proxy wrapper that holds traffic during the restart and publishes the new key when the window ends. - `storage-proxy.ts`: the `expired_credentials` fault takes an S3 error code; a `credential_rotation` marker passes traffic through. - `storage-chaos.ts`, `types.ts`, `config.ts`, `main.ts`: registry lines for ST5/ST5R and the rotation wiring. - README: ST5/ST5R rows and the credential-source description. ## Verification - `PAPERCLIP_IN_WORKTREE=false npx vitest run --config tests/restart-chaos/vitest.config.ts` (28 files, 328 tests pass). The new `storage-credentials.test.ts` fails before this change (the kinds do not exist) and passes after. It includes a real MinIO test: after a rotation the old key gets 403 `InvalidAccessKeyId`, a client with a cached key fails, and the same client succeeds after it re-resolves its profile. - `node scripts/typecheck-test-projects.mjs tests/restart-chaos` passes. - Live wave: `--env local --workloads A1,C1 --faults K1,K2 --tasks 6 --storage s3 --storage-faults ST5,ST5R --storage-fault-seconds 30-90` ran and injected 62 credential 403s (storage-proxy.json). ## Risks - Test harness only. No product code changes. - ST5R restarts MinIO. Requests are held for up to 5 s during the restart, so a slow restart can also show as a short 502 blip. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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 - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
134 lines
6.3 KiB
TypeScript
134 lines
6.3 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import { mkdir, rename, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { launchMinio, type ObjectStore } from "./object-store.js";
|
|
import { CREDENTIAL_ERROR_CODES, type StorageFaultRule } from "./storage-proxy.js";
|
|
|
|
export type CredentialFaultKind = "ST5" | "ST5R";
|
|
export const ROTATING_PROFILE = "chaos-rotating";
|
|
export const ROTATION_HOLD_MS = 5_000;
|
|
|
|
export interface StoreCredentials { accessKeyId: string; secretAccessKey: string }
|
|
type ProxyControl = { setRules(rules: readonly StorageFaultRule[]): void; clear(): void };
|
|
type RecordEvent = (kind: string, data: { [key: string]: unknown }) => void;
|
|
|
|
export function credentialFaultRules(kind: CredentialFaultKind, random: () => number): StorageFaultRule[] {
|
|
if (kind === "ST5R") return [{ fault: { kind: "credential_rotation" } }];
|
|
const code = CREDENTIAL_ERROR_CODES[Math.floor(random() * CREDENTIAL_ERROR_CODES.length)]!;
|
|
return [{ fault: { kind: "expired_credentials", code } }];
|
|
}
|
|
|
|
const isRotation = (rule: StorageFaultRule) => rule.fault.kind === "credential_rotation";
|
|
|
|
export function needsCredentialRotation(options: { storageFaults?: readonly string[];
|
|
storageWindows?: ReadonlyArray<{ rules: readonly StorageFaultRule[] }> }): boolean {
|
|
return Boolean(options.storageFaults?.includes("ST5R") || options.storageWindows?.some(window => window.rules.some(isRotation)));
|
|
}
|
|
|
|
export function freshCredentials(): StoreCredentials {
|
|
return { accessKeyId: `chaos${randomBytes(6).toString("hex")}`, secretAccessKey: randomBytes(24).toString("hex") };
|
|
}
|
|
|
|
const CREDENTIAL_PROCESS = `import { readFileSync } from "node:fs";
|
|
const { accessKeyId, secretAccessKey } = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
process.stdout.write(JSON.stringify({ Version: 1, AccessKeyId: accessKeyId, SecretAccessKey: secretAccessKey }));
|
|
`;
|
|
|
|
export interface RotatingCredentialSource {
|
|
environment: { [key: string]: string };
|
|
publish(credentials: StoreCredentials): Promise<void>;
|
|
}
|
|
|
|
export async function writeRotatingCredentialSource(root: string, initial: StoreCredentials,
|
|
nodeBinary: string = process.execPath): Promise<RotatingCredentialSource> {
|
|
const dir = path.join(root, "aws-credentials");
|
|
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
const state = path.join(dir, "current.json");
|
|
const script = path.join(dir, "credential-process.mjs");
|
|
const configFile = path.join(dir, "config");
|
|
const credentialsFile = path.join(dir, "credentials");
|
|
const publish = async (credentials: StoreCredentials) => {
|
|
const staged = `${state}.${randomBytes(4).toString("hex")}`;
|
|
await writeFile(staged, JSON.stringify(credentials), { mode: 0o600 });
|
|
await rename(staged, state);
|
|
};
|
|
await publish(initial);
|
|
await writeFile(script, CREDENTIAL_PROCESS, { mode: 0o600 });
|
|
await writeFile(credentialsFile, "", { mode: 0o600 });
|
|
await writeFile(configFile, `[profile ${ROTATING_PROFILE}]\ncredential_process = "${nodeBinary}" "${script}" "${state}"\n`, { mode: 0o600 });
|
|
return {
|
|
environment: { AWS_ACCESS_KEY_ID: "", AWS_SECRET_ACCESS_KEY: "", AWS_PROFILE: ROTATING_PROFILE,
|
|
AWS_CONFIG_FILE: configFile, AWS_SHARED_CREDENTIALS_FILE: credentialsFile },
|
|
publish,
|
|
};
|
|
}
|
|
|
|
export async function restartMinioWithCredentials(store: ObjectStore, binary: string, next: StoreCredentials,
|
|
readyTimeoutMs = 30_000): Promise<void> {
|
|
await store.stop();
|
|
const stop = await launchMinio({ binary, dataDir: store.dataDir, address: new URL(store.endpoint).host, home: path.dirname(store.dataDir),
|
|
accessKeyId: next.accessKeyId, secretAccessKey: next.secretAccessKey, readyTimeoutMs });
|
|
Object.assign(store, { stop, accessKeyId: next.accessKeyId, secretAccessKey: next.secretAccessKey });
|
|
}
|
|
|
|
export class CredentialRotation {
|
|
private work: Promise<void> = Promise.resolve();
|
|
private generation = 0;
|
|
private unpublished: StoreCredentials | null = null;
|
|
rotations = 0;
|
|
readonly failures: string[] = [];
|
|
|
|
constructor(private readonly rotate: (next: StoreCredentials) => Promise<void>,
|
|
private readonly source: Pick<RotatingCredentialSource, "publish">, private readonly record: RecordEvent,
|
|
private readonly nextCredentials: () => StoreCredentials = freshCredentials) {}
|
|
|
|
wrap(proxy: ProxyControl): ProxyControl {
|
|
return {
|
|
setRules: rules => {
|
|
const generation = ++this.generation;
|
|
const rest = rules.filter(rule => !isRotation(rule));
|
|
if (rest.length === rules.length) { proxy.setRules(rest); return; }
|
|
proxy.setRules([{ fault: { kind: "latency", ms: ROTATION_HOLD_MS } }]);
|
|
this.work = this.work.then(async () => {
|
|
const next = this.nextCredentials();
|
|
const startedAt = Date.now();
|
|
try {
|
|
await this.rotate(next);
|
|
this.unpublished = next;
|
|
this.rotations += 1;
|
|
this.record("storage_credentials_rotated", { rotation: this.rotations, restartMs: Date.now() - startedAt });
|
|
} catch (error) {
|
|
this.failures.push(`rotation: ${String(error)}`);
|
|
this.record("storage_credentials_rotation_failed", { error: String(error) });
|
|
} finally {
|
|
if (generation === this.generation) { if (rest.length) proxy.setRules(rest); else proxy.clear(); }
|
|
}
|
|
});
|
|
},
|
|
clear: () => {
|
|
++this.generation;
|
|
proxy.clear();
|
|
this.work = this.work.then(async () => {
|
|
const next = this.unpublished;
|
|
if (!next) return;
|
|
this.unpublished = null;
|
|
await this.source.publish(next)
|
|
.then(() => this.record("storage_credentials_published", { rotation: this.rotations }))
|
|
.catch(error => {
|
|
this.failures.push(`publish: ${String(error)}`);
|
|
this.record("storage_credentials_publish_failed", { error: String(error) });
|
|
});
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
settled(): Promise<void> { return this.work; }
|
|
}
|
|
|
|
export async function startCredentialRotation(input: { store: ObjectStore; binary: string; root: string; record: RecordEvent }) {
|
|
const source = await writeRotatingCredentialSource(input.root, { accessKeyId: input.store.accessKeyId, secretAccessKey: input.store.secretAccessKey });
|
|
const rotation = new CredentialRotation(next => restartMinioWithCredentials(input.store, input.binary, next), source, input.record);
|
|
return { environment: source.environment, rotation };
|
|
}
|