Files
PaperClipAI/tests/restart-chaos/storage-credentials.test.ts
T
DottaandClaude Opus 5.5 2444658c6f test(restart-chaos): add ST5 credential rejection and ST5R key rotation storage faults (#20455)
## 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>
2026-11-10 00:16:28 -06:00

189 lines
11 KiB
TypeScript

import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { minioBinary, startMinio, type ObjectStore } from "./object-store.js";
import { planStorageFaults } from "./storage-chaos.js";
import { CredentialRotation, ROTATION_HOLD_MS, credentialFaultRules, freshCredentials, needsCredentialRotation,
restartMinioWithCredentials, writeRotatingCredentialSource, type StoreCredentials } from "./storage-credentials.js";
import { faultResponse, startStorageFaultProxy, type StorageFaultRule } from "./storage-proxy.js";
const binary = minioBinary();
const s3 = createRequire(new URL("../../server/package.json", import.meta.url))("@aws-sdk/client-s3");
describe("ST5 credential faults", () => {
it("plans 403 credential windows with a seeded error code, and rotation windows as a pass-through marker", () => {
const windows = planStorageFaults({ kinds: ["ST5", "ST5R"], seed: 11, spanMs: 40 * 60_000 });
expect(new Set(windows.map(window => window.kind))).toEqual(new Set(["ST5", "ST5R"]));
const codes = new Set<string>();
for (const window of windows) {
const fault = window.rules[0]!.fault;
if (window.kind === "ST5R") expect(window.rules).toEqual([{ fault: { kind: "credential_rotation" } }]);
else if (fault.kind === "expired_credentials") codes.add(fault.code!);
else throw new Error(`unexpected ST5 rule ${JSON.stringify(fault)}`);
}
expect([...codes].every(code => ["ExpiredToken", "InvalidAccessKeyId", "SignatureDoesNotMatch"].includes(code))).toBe(true);
expect(credentialFaultRules("ST5", () => 0.99)).toEqual([{ fault: { kind: "expired_credentials", code: "SignatureDoesNotMatch" } }]);
expect(needsCredentialRotation({ storageFaults: ["ST5"] })).toBe(false);
expect(needsCredentialRotation({ storageFaults: ["ST1", "ST5R"] })).toBe(true);
expect(needsCredentialRotation({ storageWindows: windows.filter(window => window.kind === "ST5R") })).toBe(true);
});
it("answers each credential code as an S3 403 and passes rotation traffic through", () => {
for (const code of ["ExpiredToken", "InvalidAccessKeyId", "SignatureDoesNotMatch"] as const) {
const response = faultResponse({ kind: "expired_credentials", code });
expect(response).toMatchObject({ status: 403 });
expect((response as { body: string }).body).toContain(`<Code>${code}</Code>`);
}
expect(faultResponse({ kind: "expired_credentials" })).toMatchObject({ body: expect.stringContaining("ExpiredToken") });
expect(faultResponse({ kind: "credential_rotation" })).toBeNull();
});
it("holds traffic while the store rotates, then publishes the new key only when the window ends", async () => {
const applied: Array<readonly StorageFaultRule[] | "clear"> = [];
const events: string[] = [];
const published: StoreCredentials[] = [];
let finishRotation!: () => void;
const rotated = new Promise<void>(resolve => { finishRotation = resolve; });
const next = { accessKeyId: "new", secretAccessKey: "secret" };
const rotation = new CredentialRotation(() => rotated, { publish: async credentials => { published.push(credentials); } },
kind => events.push(kind), () => next);
const proxy = rotation.wrap({ setRules: rules => applied.push(rules), clear: () => applied.push("clear") });
proxy.setRules([{ fault: { kind: "outage" } }]);
expect(applied).toEqual([[{ fault: { kind: "outage" } }]]);
proxy.setRules([{ fault: { kind: "credential_rotation" } }]);
expect(applied.at(-1)).toEqual([{ fault: { kind: "latency", ms: ROTATION_HOLD_MS } }]);
finishRotation();
await vi.waitFor(() => expect(events).toEqual(["storage_credentials_rotated"]));
expect(applied.at(-1)).toBe("clear");
expect(published).toEqual([]);
proxy.clear();
await rotation.settled();
expect(published).toEqual([next]);
expect(events).toEqual(["storage_credentials_rotated", "storage_credentials_published"]);
});
it("does not undo a window that ended while the store was still rotating", async () => {
const applied: Array<readonly StorageFaultRule[] | "clear"> = [];
let finishRotation!: () => void;
const rotation = new CredentialRotation(() => new Promise<void>(resolve => { finishRotation = resolve; }),
{ publish: async () => undefined }, () => undefined);
const proxy = rotation.wrap({ setRules: rules => applied.push(rules), clear: () => applied.push("clear") });
proxy.setRules([{ fault: { kind: "credential_rotation" } }]);
proxy.clear();
await vi.waitFor(() => expect(finishRotation).toBeTypeOf("function"));
finishRotation();
await rotation.settled();
expect(applied.at(-1)).toBe("clear");
expect(applied.filter(entry => entry === "clear")).toHaveLength(1);
});
});
describe("ST5R rotation failures", () => {
it("keeps rotation and publish errors so the wave can fail", async () => {
const rotation = new CredentialRotation(async () => { throw new Error("minio did not restart"); },
{ publish: async () => { throw new Error("disk full"); } }, () => undefined);
const proxy = rotation.wrap({ setRules: () => undefined, clear: () => undefined });
proxy.setRules([{ fault: { kind: "credential_rotation" } }]);
proxy.clear();
await rotation.settled();
expect(rotation.failures).toEqual(["rotation: Error: minio did not restart"]);
const publishing = new CredentialRotation(async () => undefined, { publish: async () => { throw new Error("disk full"); } }, () => undefined);
const wrapped = publishing.wrap({ setRules: () => undefined, clear: () => undefined });
wrapped.setRules([{ fault: { kind: "credential_rotation" } }]);
wrapped.clear();
await publishing.settled();
expect(publishing.failures).toEqual(["publish: Error: disk full"]);
});
async function fakeMinio(root: string, health: "ok" | "hang") {
const binary = path.join(root, "fake-minio.mjs");
await writeFile(binary, `#!/usr/bin/env node
import { createServer } from "node:http";
import { writeFileSync } from "node:fs";
const [host, port] = process.argv[process.argv.indexOf("--address") + 1].split(":");
writeFileSync(${JSON.stringify(path.join(root, "seen.json"))}, JSON.stringify({ user: process.env.MINIO_ROOT_USER, args: process.argv.slice(2) }));
createServer((req, res) => { if (${JSON.stringify(health)} === "ok") res.end("ok"); }).listen(Number(port), host);
process.on("SIGTERM", () => process.exit(0));
`);
await chmod(binary, 0o755);
return binary;
}
async function storeOnFreePort(root: string): Promise<ObjectStore & { stopped: number }> {
const proxy = await startStorageFaultProxy("http://127.0.0.1:9");
const port = new URL(proxy.endpoint).port;
await proxy.close();
const store = { endpoint: `http://127.0.0.1:${port}`, bucket: "b", region: "us-east-1", accessKeyId: "old", secretAccessKey: "old-secret",
dataDir: path.join(root, "object-store"), stopped: 0, stop: async () => { store.stopped += 1; } };
return store;
}
it("restarts the store on the same address with the new root key and adopts its stop", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "restart-chaos-st5r-fake-"));
const store = await storeOnFreePort(root);
const oldStop = store.stop;
try {
await restartMinioWithCredentials(store, await fakeMinio(root, "ok"), { accessKeyId: "new", secretAccessKey: "new-secret" }, 10_000);
expect(store.stopped).toBe(1);
expect(store).toMatchObject({ accessKeyId: "new", secretAccessKey: "new-secret" });
expect(store.stop).not.toBe(oldStop);
const seen = JSON.parse(await readFile(path.join(root, "seen.json"), "utf8"));
expect(seen.user).toBe("new");
expect(seen.args.slice(0, 4)).toEqual(["server", store.dataDir, "--address", new URL(store.endpoint).host]);
} finally {
await store.stop();
await rm(root, { recursive: true, force: true });
}
}, 30_000);
it("gives up at its deadline when the restarted store accepts connections but never answers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "restart-chaos-st5r-hang-"));
const store = await storeOnFreePort(root);
try {
const started = Date.now();
await expect(restartMinioWithCredentials(store, await fakeMinio(root, "hang"), freshCredentials(), 1_500))
.rejects.toThrow(/did not become ready/);
expect(Date.now() - started).toBeLessThan(6_000);
} finally {
await store.stop();
await rm(root, { recursive: true, force: true });
}
}, 30_000);
});
describe("ST5R real rotation", () => {
afterEach(() => { vi.unstubAllEnvs(); });
it.skipIf(!binary)("revokes the old key at the store, and only a client that re-resolves its profile keeps going", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "restart-chaos-st5r-"));
const store = await startMinio({ binary: binary!, root });
const proxy = await startStorageFaultProxy(store.endpoint);
const first = { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey };
const source = await writeRotatingCredentialSource(root, first);
for (const [key, value] of Object.entries(source.environment)) vi.stubEnv(key, value);
const profileClient = new s3.S3Client({ endpoint: proxy.endpoint, region: store.region, forcePathStyle: true });
const staticClient = new s3.S3Client({ endpoint: proxy.endpoint, region: store.region, forcePathStyle: true, credentials: first });
const put = (client: typeof profileClient, key: string) => client.send(new s3.PutObjectCommand({ Bucket: store.bucket, Key: key, Body: key }));
try {
await put(profileClient, "before");
const next = freshCredentials();
await restartMinioWithCredentials(store, binary!, next);
await source.publish(next);
await expect(put(staticClient, "stale")).rejects.toMatchObject({ name: "InvalidAccessKeyId", $metadata: { httpStatusCode: 403 } });
await expect(put(profileClient, "cached")).rejects.toMatchObject({ $metadata: { httpStatusCode: 403 } });
await profileClient.config.credentials({ forceRefresh: true });
await put(profileClient, "after");
const listed = await profileClient.send(new s3.ListObjectsV2Command({ Bucket: store.bucket }));
expect(listed.Contents.map((entry: { Key: string }) => entry.Key).sort()).toEqual(["after", "before"]);
} finally {
profileClient.destroy();
staticClient.destroy();
await proxy.close();
await store.stop();
await rm(root, { recursive: true, force: true });
}
}, 90_000);
});