Harden attachment materialization and static file path handling

- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-02-27 21:30:46 -08:00
1 parent 992db16586
commit b5188e8cea
7 files changed
+364 -15

No files matched your search

@@ -247,6 +247,117 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("materializes only image data URLs and uses a safe extension whitelist", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-"));
const serverConfig = {
mode: "web",
port: 0,
host: undefined,
cwd: "/tmp/project-attachments",
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
stateDir,
staticDir: undefined,
devUrl: undefined,
noBrowser: true,
authToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
} satisfies ServerConfigShape;
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-attachments-safe"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-attachments-safe"),
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-attachments-safe"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-attachments-safe"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-attachments-safe"),
messageId: MessageId.makeUnsafe("message-attachments-safe"),
role: "user",
text: "Inspect this",
attachments: [
{
type: "image",
name: "untrusted.exe",
mimeType: "image/x-unknown",
sizeBytes: 5,
dataUrl: "data:image/x-unknown;base64,SGVsbG8=",
},
{
type: "image",
name: "not-image.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: "data:text/plain;base64,SGVsbG8=",
},
],
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
});
yield* projectionPipeline.bootstrap.pipe(Effect.provideService(ServerConfig, serverConfig));
const rows = yield* sql<{
readonly attachmentsJson: string | null;
}>`
SELECT
attachments_json AS "attachmentsJson"
FROM projection_thread_messages
WHERE message_id = 'message-attachments-safe'
`;
assert.equal(rows.length, 1);
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
name: "untrusted.exe",
mimeType: "image/x-unknown",
sizeBytes: 5,
dataUrl: "/attachments/thread-attachments-safe/message-attachments-safe/0.bin",
},
{
type: "image",
name: "not-image.png",
mimeType: "image/png",
sizeBytes: 5,
dataUrl: "data:text/plain;base64,SGVsbG8=",
},
]);
const firstAttachmentPath = path.join(
stateDir,
"attachments",
"thread-attachments-safe",
"message-attachments-safe",
"0.bin",
);
assert.equal(fs.existsSync(firstAttachmentPath), true);
assert.deepEqual(fs.readFileSync(firstAttachmentPath), Buffer.from("SGVsbG8=", "base64"));
const secondAttachmentPath = path.join(
stateDir,
"attachments",
"thread-attachments-safe",
"message-attachments-safe",
"1.png",
);
assert.equal(fs.existsSync(secondAttachmentPath), false);
fs.rmSync(stateDir, { recursive: true, force: true });
}),
);
it.effect("resumes from projector last_applied_sequence without replaying older events", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -70,6 +70,17 @@ const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
"image/tiff": ".tiff",
"image/heic": ".heic",
};
const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".jpg",
".jpeg",
".png",
".gif",
".webp",
".bmp",
".tiff",
".svg",
".ico",
]);
function parseBase64DataUrl(
dataUrl: string,
@@ -87,14 +98,18 @@ function parseBase64DataUrl(
}
function inferImageExtension(attachment: Extract<ChatAttachment, { type: "image" }>): string {
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[attachment.mimeType.toLowerCase()];
if (fromMime) {
return fromMime;
const normalizedMimeType = attachment.mimeType.trim().toLowerCase();
if (normalizedMimeType.startsWith("image/")) {
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[normalizedMimeType];
if (fromMime) {
return fromMime;
}
}
const fromName = attachment.name.includes(".")
? `.${attachment.name.split(".").slice(-1)[0]?.toLowerCase() ?? ""}`
: "";
if (/^\.[a-z0-9]{1,12}$/.test(fromName)) {
if (/^\.[a-z0-9]{1,12}$/.test(fromName) && SAFE_IMAGE_FILE_EXTENSIONS.has(fromName)) {
return fromName;
}
return ".bin";
@@ -132,13 +147,19 @@ const materializeAttachmentsForProjection = Effect.fn(function* (input: {
if (!parsed) {
return attachment;
}
if (!parsed.mimeType.startsWith("image/")) {
return attachment;
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0) {
return attachment;
}
const fileName = `${index}${inferImageExtension(attachment)}`;
const fileName = `${index}${inferImageExtension({
...attachment,
mimeType: parsed.mimeType,
})}`;
const relativePath = `${threadSegment}/${messageSegment}/${fileName}`;
const absolutePath = path.join(attachmentsRootDir, threadSegment, messageSegment, fileName);
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });