Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(serverSettingsLayer),
Layer.provideMerge(secretScrubberLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
);
Expand Down
4 changes: 2 additions & 2 deletions apps/server/integration/providerService.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ import {
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
import { ThreadSessionAdmissionPermissive } from "../src/provider/Services/ThreadSessionAdmission.ts";
import { layerTest as SecretScrubberTest } from "../src/secrets/SecretScrubber.ts";
import { layer as SecretScrubberLive } from "../src/secrets/SecretScrubber.ts";

/** The provider service with an empty registry of watched keys (SecretScrubber). */
const makeProviderServiceWithScrubber = (...args: Parameters<typeof makeProviderServiceLive>) =>
makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberTest));
makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberLive));

const codexInstanceId = ProviderInstanceId.make("codex");

Expand Down
20 changes: 18 additions & 2 deletions apps/server/src/commandRuns/CommandRuns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type { McpInvocationScope } from "../mcp/McpSessionRegistry.ts";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionThreadCommandRepository } from "../persistence/Services/ProjectionThreadCommands.ts";
import { SecretScrubber } from "../secrets/SecretScrubber.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { TerminalManager, type TerminalCommandRunUpdate } from "../terminal/Services/Manager.ts";

Expand Down Expand Up @@ -104,6 +105,7 @@ const make = Effect.gen(function* () {
const commandRows = yield* ProjectionThreadCommandRepository;
const terminals = yield* TerminalManager;
const settings = yield* ServerSettingsService;
const secretScrubber = yield* SecretScrubber;

/** The thread each run of this process belongs to; run updates carry only the run id. */
const runThreads = new Map<string, ThreadId>();
Expand Down Expand Up @@ -149,6 +151,15 @@ const make = Effect.gen(function* () {
detail: `Keep the command under ${MAX_SHELL_COMMAND_LENGTH} characters and ${MAX_SHELL_COMMAND_LINES} lines; put longer scripts in a file and ask to run that.`,
};
}
// A card shows its command, and the run prints it: a saved key in it
// would be on screen and in the output (docs/design/secret-scrubbing.md).
const [watched] = secretScrubber.contains([command, reason]);
if (watched !== undefined) {
return {
outcome: "refused" as const,
detail: `This command contains ${watched}. Read it from its file inside the command instead.`,
};
}
const dialect = serverCommandDialect();
const assessment = assessShellCommand(command, dialect);
if (assessment.blocked !== null) {
Expand Down Expand Up @@ -213,7 +224,7 @@ const make = Effect.gen(function* () {
commandId: CommandId.make(`command-run:${progress.runId}:${key}`),
threadId,
progress,
...(output !== undefined ? { output } : {}),
...(output !== undefined ? { output: secretScrubber.scrubText(output).text } : {}),
createdAt: yield* nowIso,
});
});
Expand Down Expand Up @@ -256,7 +267,12 @@ const make = Effect.gen(function* () {
threadId,
runId: run.runId,
automatic,
message: { messageId, text: buildCommandOutputMessage({ run, output }) },
message: {
messageId,
// The whole message, command and folder included: a card or a
// record made before a key was saved still holds it whole.
text: secretScrubber.scrubText(buildCommandOutputMessage({ run, output })).text,
},
createdAt: yield* nowIso,
})
.pipe(Effect.mapError((error) => failWith(error.message)));
Expand Down
27 changes: 23 additions & 4 deletions apps/server/src/diagnostics/BackgroundRunOutput.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";

import { makeSecretScrubber, type SecretScrubberShape } from "../secrets/SecretScrubber.ts";
import { canMakeSymlinks } from "../testUtils/symlinks.ts";
import { makeBackgroundRunOutputReader } from "./BackgroundRunOutput.ts";

Expand All @@ -27,7 +28,10 @@ afterEach(async () => {
});

/** A thread whose only activity is Claude's reply naming `announcedFile`. */
function readerForThreadAnnouncing(announcedFile: string) {
function readerForThreadAnnouncing(
announcedFile: string,
scrubber: SecretScrubberShape = makeSecretScrubber(),
) {
const thread = {
activities: [
{
Expand All @@ -37,9 +41,10 @@ function readerForThreadAnnouncing(announcedFile: string) {
},
],
} as unknown as OrchestrationThread;
return makeBackgroundRunOutputReader({
getThreadDetailById: () => Effect.succeed(Option.some(thread)),
});
return makeBackgroundRunOutputReader(
{ getThreadDetailById: () => Effect.succeed(Option.some(thread)) },
scrubber,
);
}

describe("readBackgroundRunOutput", () => {
Expand All @@ -49,6 +54,20 @@ describe("readBackgroundRunOutput", () => {
expect(result.tail).toContain("http://localhost:5173/");
});

it("hides a saved key whole even when it reaches into the end from before it", async () => {
// A key of many lines, long enough that the 8 KB end starts inside it:
// cut first, the lines after the cut would show.
const key = Array.from({ length: 12 }, (_, line) => `${line}a1b2c3d4`.repeat(8)).join("\n");
const scrubber = makeSecretScrubber();
scrubber.watch("DEPLOY_KEY", key);
await writeFile(outputFile, `${"x".repeat(9_000)}\n${key}\n${"y".repeat(8_000)}\ndone\n`);
const read = readerForThreadAnnouncing(outputFile, scrubber);
const result = await Effect.runPromise(read({ threadId: THREAD_ID, outputFile }));
expect(result.tail).toContain("[DEPLOY_KEY hidden]");
expect(result.tail).not.toContain("a1b2c3d4");
expect(result.tail).toContain("done");
});

it("refuses a file the thread never named, even one shaped like Claude's", async () => {
const read = readerForThreadAnnouncing(path.join(directory, "tasks", "other.output"));
const result = await Effect.runPromise(read({ threadId: THREAD_ID, outputFile }));
Expand Down
36 changes: 29 additions & 7 deletions apps/server/src/diagnostics/BackgroundRunOutput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,21 @@ export function announcedOutputFiles(
* platform supports it (not Windows). */
const OPEN_NO_FOLLOW = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);

/** The end of a regular file as text, from a whole line on. Null for a
* symlink, or a path whose real location is not a `tasks/<id>.output` file. */
async function readFileTail(file: string): Promise<string | null> {
/** Hides saved keys in text, and says how far back to read to catch one whole. */
export interface OutputScrubber {
readonly scrubText: (
text: string,
options?: { readonly cutTail?: boolean },
) => { readonly text: string };
readonly longestFormBytes: () => number;
}

/**
* The end of a regular file as text, from a whole line on, with saved keys
* hidden. Null for a symlink, or a path whose real location is not a
* `tasks/<id>.output` file.
*/
async function readFileTail(file: string, scrubber: OutputScrubber): Promise<string | null> {
const linkStats = await lstat(file);
if (!linkStats.isFile()) return null;
// A symlinked parent directory could still move the read elsewhere; the
Expand All @@ -85,19 +97,29 @@ async function readFileTail(file: string): Promise<string | null> {
if (!stats.isFile() || stats.ino !== linkStats.ino || stats.dev !== linkStats.dev) {
return null;
}
const length = Math.min(stats.size, OUTPUT_TAIL_BYTES);
// Read further back by the longest key's length, hide keys, then keep
// the end: a key reaching into the end starts inside the read, so it is
// hidden whole rather than cut (docs/design/secret-scrubbing.md).
const length = Math.min(stats.size, OUTPUT_TAIL_BYTES + scrubber.longestFormBytes());
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, stats.size - length);
const text = buffer.subarray(0, bytesRead).toString("utf8");
// The file may still be written: a tail that could start a key goes too.
const read = scrubber.scrubText(buffer.subarray(0, bytesRead).toString("utf8"), {
cutTail: true,
}).text;
const text = read.length > OUTPUT_TAIL_BYTES ? read.slice(-OUTPUT_TAIL_BYTES) : read;
// A read that starts mid-file starts mid-line; drop the partial line.
return length < stats.size ? text.slice(text.indexOf("\n") + 1) : text;
return length < stats.size || text.length < read.length
? text.slice(text.indexOf("\n") + 1)
: text;
} finally {
await handle.close();
}
}

export function makeBackgroundRunOutputReader(
projectionSnapshotQuery: Pick<ProjectionSnapshotQueryShape, "getThreadDetailById">,
scrubber: OutputScrubber,
now: () => number = Date.now,
) {
/** When each file was last confirmed, per thread. */
Expand Down Expand Up @@ -134,7 +156,7 @@ export function makeBackgroundRunOutputReader(
Effect.orElseSucceed(() => false),
);
if (!announced) return UNREADABLE;
const tail = yield* Effect.tryPromise(() => readFileTail(file)).pipe(
const tail = yield* Effect.tryPromise(() => readFileTail(file, scrubber)).pipe(
Effect.orElseSucceed(() => null),
);
return { tail } satisfies ServerReadBackgroundRunOutputResult;
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ Settings that give agents more reach ({place:threads.agentThreads}, {place:threa

What this promises: Threadlines doesn't put the key in the chat, its stored events, logs or other apps. What it doesn't: the agent runs as you on that computer, so it can still read the file, and if it prints the key, the model sees it. A key pasted into chat is already in the conversation; replace it if that matters. Answering needs an encrypted connection to that computer. Archiving, moving or deleting the thread removes its private files, and a saved row for a private file has Remove now.

If the agent later prints a saved key, or a tool reads it, Threadlines replaces it with [NAME hidden] before it stores, logs or shows that text, and a row in the thread says so. The model may still have seen it, and the provider's own transcript keeps it; replace the key if that matters. Keys under 8 characters, or made only of letters or only of digits, aren't hidden. Your terminal, files in the project and voice audio aren't covered, and a key changed by hand in the env file is hidden from the next restart.`,
If the agent later prints a saved key, or a tool reads it, Threadlines replaces it with [NAME hidden] before it stores, logs or shows that text, and a row in the thread says so. An agent's message to another agent or thread, a page, or a command it asks you to run is refused while it holds one. The model may still have seen it, and the provider's own transcript keeps it; replace the key if that matters. Keys under 8 characters, or made only of letters or only of digits, aren't hidden. Your terminal, files in the project and voice audio aren't covered, and a key changed by hand in the env file is hidden from the next restart.`,
},
{
id: "updates",
Expand Down
46 changes: 46 additions & 0 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ import * as PreviewAutomationBroker from "../preview/PreviewAutomationBroker.ts"
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
import { ProviderService } from "../provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
makeSecretScrubber,
SecretScrubber,
type SecretScrubberShape,
} from "../secrets/SecretScrubber.ts";
import { AgentSecretRequests } from "../secrets/AgentSecretRequests.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
Expand Down Expand Up @@ -200,6 +205,7 @@ const ROOM_THREAD = {
const roomServerStubs = (
settings?: Parameters<typeof ServerSettingsService.layerTest>[0],
thread: object = ROOM_THREAD,
secretScrubber: SecretScrubberShape = makeSecretScrubber(),
) =>
Layer.mergeAll(
Layer.succeed(OrchestrationEngineService, {
Expand All @@ -217,6 +223,7 @@ const roomServerStubs = (
Layer.succeed(ProviderService, { listSessions: () => Effect.succeed([]) } as never),
Layer.succeed(GitVcsDriver, {} as never),
Layer.succeed(AgentSecretRequests, { destinations: {} } as never),
Layer.succeed(SecretScrubber, secretScrubber),
ServerSettingsService.layerTest(settings),
PreviewAutomationBroker.layer,
);
Expand Down Expand Up @@ -381,6 +388,45 @@ describe("MCP endpoints", () => {
);
});

it("refuses a call that would carry a saved key to another agent or thread", async () => {
const secretScrubber = makeSecretScrubber();
secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz");
await Effect.runPromise(
Effect.scoped(
Effect.gen(function* () {
const base = yield* serve(
McpRoomServer.layer.pipe(
Layer.provide(roomServerStubs(undefined, ROOM_THREAD, secretScrubber)),
),
);
const agent = yield* mcpSessionRegistry.credentialFor({
sessionKey: THREAD,
browser: true,
room: true,
});
const result = yield* Effect.promise(async () => ({
send: await callTool(`${base}/mcp/room`, agent.token, "thread_send", {
threadId: "child-1",
message: "Use sk_test_51Hq9xYz for the webhook.",
}),
ask: await callTool(`${base}/mcp/room`, agent.token, "room_ask", {
agent: "Reviewer",
question: "Is sk_test_51Hq9xYz the live key?",
}),
}));
for (const call of [result.send, result.ask]) {
expect(call.structuredContent).toMatchObject({
outcome: "refused",
detail:
"Your call contains STRIPE_SECRET_KEY. Don't pass a key through this tool. The other agent can ask the user for it.",
});
}
yield* mcpSessionRegistry.revoke(THREAD, agent.generation);
}),
).pipe(onLoopback),
);
});

it("lists only its own tools on each endpoint, and keeps side runtimes off the browser", async () => {
await Effect.runPromise(
Effect.scoped(
Expand Down
Loading
Loading