Files
puter/extensions/thumbnails.test.ts
T
Nariman Jelveh e62418f7a9 fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard (#4691)
* fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard

An overwrite clears a file's thumbnail and nothing made a new one, so a file
an app saved over lost its picture, and files apps created never had one.

The dashboard now makes a thumbnail for a file with none as its row comes
into view, with the upload thumbnail generator, within budgets on size,
downloads at a time, files per minute, and bytes per page load. A version
that gives no thumbnail is remembered so it isn't downloaded again.

/update-fsentry-thumbnail takes an optional expectedModified and refuses a
thumbnail made from an older version with 409, tells the owner's other
clients about the new thumbnail, and has its own rate-limit scope instead of
sharing the one opening a file uses. Overwrites and replacements emit
thumbnail.discarded, and the thumbnails extension deletes the object behind
it, so replaced thumbnails no longer stay in the bucket.

* fix(thumbnails): expectedModified must be a whole number of seconds the column can hold

A fraction or a value past the column's range reached the UPDATE, which
Postgres refuses with an error after the thumbnail was already uploaded.
The route now answers 400 before it uploads anything.

* fix(thumbnails): setting a thumbnail keeps the current one when the new one can't be stored

The route stored whatever the thumbnail.created listeners left behind:
a pointer whose upload failed, or the null left for an image that can't
be decoded. Either replaced a working thumbnail and answered 200. It now
answers 500 or 400 and leaves the entry as it was.

* fix(thumbnails): the update announced after setting a thumbnail carries the entry's current name and path

The event was built from the entry read before the thumbnail was
uploaded, so a rename or move that landed during the upload was
announced with the name and path it had just replaced, and open clients
put the row back on a path that no longer exists. The entry is read
again after the thumbnail is stored.

* fix(thumbnails): a file that stops needing a thumbnail is no longer downloaded for one

A file waiting its turn, or already downloading, was still read and its
thumbnail stored after another tab had made one, or after the file was
saved again as something the generator can't read. A queued file is now
checked again before its download starts, and a change that makes the
thumbnail unwanted drops the queued job and cancels the download.

* fix(thumbnails): refreshing the folder on screen keeps its thumbnail downloads

A refresh of the folder on screen (a sort, a view switch, an upload
finishing, coming back to the tab) cancelled the downloads under way.
The rows drawn right after were skipped, because their files still
counted as being tried, so they stayed without a thumbnail until some
later render. The rest were downloaded again from the start.

A download is now cancelled only if its file's row isn't drawn again in
the same task, and the new row takes it over. A row that comes back
while a cancelled download is still ending is queued again.

* fix(thumbnails): a stored thumbnail is recorded on the row's own entry

The filler handed its callback a copy of the row's entry, so the
thumbnail was written to an object nothing else reads, and the row's
entry kept saying the file had none. It now passes the row's entry, and
skips a row whose file was saved again while the thumbnail was being
stored, which would otherwise show the older version's picture.

* fix(thumbnails): the download budget counts the bytes that were downloaded

A cancelled download gave its whole size back to the page's download
budget, though the bytes it had received were already billed as egress.
A file saved over and over while its row was on screen could be started
again each time, well past the budget. A download the server refused
kept its size charged with nothing downloaded.

The file is now read as a stream and the budget is charged what arrived.
Reading also stops as soon as a file turns out to be over the size cap,
where before a file larger than its listed size was buffered whole.

* fix(thumbnails): a thumbnail download that fails to connect is tried again

A download that failed on the network counted as tried, so the file went
without a thumbnail for the rest of the page load. A laptop waking before
its Wi-Fi is back marked every row on screen that way. A failed
connection now pauses the filler like a 429 does, and the file is tried
again after the pause.

* fix(thumbnails): a thumbnail that couldn't be stored yet is sent again, not made again

When storing a thumbnail got a 429, the file was queued again and
downloaded a second time after the pause. When the request failed to
connect, the thumbnail was dropped and the file went without one. The
thumbnail is now kept with the queued job and sent again after the
pause, as long as the file is still at the version it shows.

* fix(thumbnails): a file whose thumbnail the server refuses isn't downloaded again on every page load

When the server answers 400 for a thumbnail, the file's version is now
remembered like one that gave no thumbnail at all. It counted as tried
for the page load only, so each later page load downloaded the file and
sent the same image again.

* fix(thumbnails): only pictures a browser can draw are downloaded for a thumbnail

Any file typed image/ counted as one the generator reads, so TIFF scans,
CAD drawings, DjVu books and the like were each downloaded in full, up
to 20 MiB, to make a thumbnail no browser can draw. A file is now
downloaded only when its type or name is one browsers decode. Uploads
are unchanged: the generator still tries any image there, where the file
is already local.

* fix(thumbnails): missing thumbnails are downloaded one file at a time

Each download holds one of the account's concurrent file reads until it
ends. Two at a time left a temporary account, which has three, a single
read for everything its apps do, so an app reading two files at once got
a 429 while a folder's thumbnails were being filled in. The per-minute
cap of 20 files already bounds how fast they're made.

* fix(thumbnails): an update refreshes the icon of every item it matches

An update can match the Files row and the same item in a file dialog
open over the dashboard. The row updater set the new thumbnail on the
first match only, where it used to set it on all of them.

* perf(thumbnails): an update works out a row's icon again only when its thumbnail changed

Every update event carries a thumbnail key, so the row updater worked
out the icon on each one. For a .app file or a web link that reads the
file, once per event. The icon is now refreshed only when the event's
thumbnail differs from the one the row has.

* perf(thumbnails): drawing a large folder doesn't rescan the thumbnail queue for every row

Each row handed to the filler went through every row queued before it,
looking for a job to start, so drawing a folder of files without
thumbnails took the square of its length: about a second for 20,000
rows. A row that isn't on screen yet has nothing to start, so the queue
is now only gone through when a row is reported on screen, a job ends,
or a wait is over.

* fix(thumbnails): one tab no longer drops the failed files another tab remembered

Each tab read the list of files that gave no thumbnail once, then wrote
its own copy back whole on every addition, which dropped whatever
another tab had added in between. Those files were downloaded again on
a later page load. The stored list is now read again and merged before
each write.

* perf(thumbnails): files downloaded for a thumbnail stay out of the browser's HTTP cache

The download asked the cache to revalidate, which still writes each
response to it, up to 100 MiB of originals per page load that nothing
reads back. The read route doesn't answer conditional requests, so a
cached copy could never save a download either.

* bench(thumbnails): scenario for setting a file's thumbnail from the dashboard

The dashboard calls the route for each file it fills in a thumbnail
for, up to 20 a minute, so its round trips are measured from here on.

* docs(thumbnails): list the picture formats downloaded for a missing thumbnail

* perf(thumbnails): setting a thumbnail reads the entry again alongside the write, not after it

The read that keeps the announced name and path current ran after the
update, which added a serial round trip to the route. It now runs with
the update. The window it closes is the upload before both.

* feat(thumbnails): a file saved over keeps showing its old thumbnail until the new one is ready

A save cleared the row to its type icon for the few seconds it takes to
make the new thumbnail, so a file an app saves repeatedly flashed
between the two. The row now keeps the old thumbnail while a new one is
on its way.

It goes back to the type icon at once when no thumbnail will be made
(the file is too large, the download budget is spent, the filler is
paused), as soon as the attempt fails, and after 10 seconds at most,
counted from the first save, so an old picture can't stay on a file
that keeps changing.

* fix(thumbnails): a document gets its thumbnail when the view goes to the list and back while it's made

A list row shows a document's type icon, so switching to the list gave up
on the thumbnail being made for it. Switching back before that ended found
the version already tried and queued nothing, and the row kept its type
icon until the folder was drawn again. The row now takes the job back.

* fix(thumbnails): a file being saved waits to settle whatever the computer's clock says

The wait before a saved file is downloaded was measured from its modified
time, which the server sets, against the browser's clock. On a computer
whose clock runs a few seconds ahead the wait came out as zero, so every
save of a file an app keeps saving started a download that the next save
cancelled. A file an update just arrived for now waits at least two
seconds, the least it waits when the clocks agree.

* fix(thumbnails): an item in a file dialog gets a new thumbnail when its folder isn't the one on screen

The row updater only set a thumbnail through the entry a Files row
carries. An update for a file shown only in a file dialog, with another
folder open in Files, matched an item that has no entry, and the item
kept the picture it had.

* refactor(thumbnails): the row observer asks for no margin around the screen

The 200px margin never took effect. The rows scroll inside the listing's
own pane, and a margin on the viewport doesn't widen what that pane clips,
so a row was only ever reported once it was on screen. That's also what
the download budget is written for, so the option goes rather than being
made to work.

* test(thumbnails): a version tried once, a hidden tab, and a browser saving data

Three of the filler's cost guards had no test: a version whose thumbnail
the server turned away isn't downloaded again in the page load, nothing
starts while the tab is hidden, and nothing is downloaded when the
browser asks to use less data.
2026-11-18 18:58:43 -07:00

1223 lines
43 KiB
TypeScript

import {
GetObjectCommand,
HeadObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import type { Request, Response } from 'express';
import crypto from 'node:crypto';
import {
afterAll,
beforeAll,
describe,
expect,
it,
vi,
} from 'vitest';
import type { FSController } from '../src/backend/controllers/fs/FSController.ts';
import type {
ClientSignedWriteResponse,
CompleteWriteRequest,
SignedWriteRequest,
} from '../src/backend/controllers/fs/requestTypes.ts';
import type { Actor } from '../src/backend/core/actor.ts';
import { runWithContext } from '../src/backend/core/context.ts';
import { PuterServer } from '../src/backend/server.ts';
import { setupTestServer } from '../src/backend/testUtil.ts';
import { generateDefaultFsentries } from '../src/backend/util/userProvisioning.ts';
import {
handleFsCopyNodeThumbnail,
handleFsRemoveNodeThumbnail,
handleThumbnailCreated,
handleThumbnailRead,
handleThumbnailUploadPrepare,
} from './thumbnails.ts';
// 1x1 transparent PNG — smallest valid image sharp will accept.
const TINY_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
const BUCKET = 'puter-local';
const BUCKET_ENDPOINT = 'http://127.0.0.1:4566/puter-local/';
// Keys the extension mints: `thumbnails/<entry uuid>/<uuid>`.
const mintedKey = (entryUuid: string = crypto.randomUUID()) =>
`thumbnails/${entryUuid}/${crypto.randomUUID()}`;
// Minted before keys were bound to an entry.
const legacyKey = () => `thumbnails/${crypto.randomUUID()}`;
const putObject = async (s3: S3Client, key: string, body: Buffer) => {
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: body,
ContentType: 'image/png',
}),
);
};
const objectExists = async (s3: S3Client, key: string) => {
try {
await s3.send(new HeadObjectCommand({ Bucket: BUCKET, Key: key }));
return true;
} catch {
return false;
}
};
const streamToBuffer = async (
body: { transformToByteArray: () => Promise<Uint8Array> } | undefined,
): Promise<Buffer> => {
if (!body) throw new Error('s3 GetObject returned no body');
return Buffer.from(await body.transformToByteArray());
};
describe('thumbnails extension — handleThumbnailCreated', () => {
let server: PuterServer;
let s3: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3 = server.clients.s3.get();
});
afterAll(async () => {
await server?.shutdown();
});
const created = async (url: unknown, uuid?: unknown) => {
const event: Record<string, unknown> = { url, uuid };
await handleThumbnailCreated(event, {
s3,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
});
return event.url;
};
it('uploads a valid data: URL thumbnail under a key bound to the entry', async () => {
const entryUuid = crypto.randomUUID();
const newUrl = await created(
`data:image/png;base64,${TINY_PNG_BASE64}`,
entryUuid,
);
expect(typeof newUrl).toBe('string');
expect(
(newUrl as string).startsWith(
`s3://${BUCKET}/thumbnails/${entryUuid}/`,
),
).toBe(true);
const key = (newUrl as string).slice(`s3://${BUCKET}/`.length);
const obj = await s3.send(
new GetObjectCommand({ Bucket: BUCKET, Key: key }),
);
expect(obj.ContentType).toBe('image/png');
const expected = Buffer.from(TINY_PNG_BASE64, 'base64');
const actual = await streamToBuffer(obj.Body as never);
expect(actual.equals(expected)).toBe(true);
});
it('sets event.url to null when the data: URL does not decode to a valid image', async () => {
const url = await created(
`data:image/png;base64,${Buffer.from('not an image').toString('base64')}`,
crypto.randomUUID(),
);
expect(url).toBeNull();
});
it('sets event.url to null for a data: URL with no entry to bind it to', async () => {
const url = await created(`data:image/png;base64,${TINY_PNG_BASE64}`);
expect(url).toBeNull();
});
// A documented SDK input: `thumbnail` / `thumbnailGenerator` may return
// a plain URL. It never names our storage, so it is stored as given.
it('leaves an external image URL untouched', async () => {
const original = 'https://example.com/thumb.png';
expect(await created(original, crypto.randomUUID())).toBe(original);
});
it('returns without writing to S3 when event.url is missing', async () => {
const event: Record<string, unknown> = {};
await handleThumbnailCreated(event, {
s3,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
});
expect(event.url).toBeUndefined();
});
it('keeps an uploaded pointer minted for the entry, normalised to our bucket', async () => {
const entryUuid = crypto.randomUUID();
const key = mintedKey(entryUuid);
await putObject(s3, key, Buffer.from(TINY_PNG_BASE64, 'base64'));
expect(
await created(`s3://client-named-bucket/${key}`, entryUuid),
).toBe(`s3://${BUCKET}/${key}`);
});
// A thumbnail key is visible to anyone who can list the entry holding it.
// Planting it on a file of one's own used to hand its deletion to them.
it.each([
['a key minted for another entry', () => mintedKey()],
['a key that predates entry binding', legacyKey],
])('drops a pointer naming %s', async (_label, makeKey) => {
const key = makeKey();
await putObject(s3, key, Buffer.from(TINY_PNG_BASE64, 'base64'));
expect(
await created(`s3://${BUCKET}/${key}`, crypto.randomUUID()),
).toBeNull();
expect(await objectExists(s3, key)).toBe(true);
});
it('drops a pointer whose object was never uploaded', async () => {
const entryUuid = crypto.randomUUID();
expect(
await created(`s3://${BUCKET}/${mintedKey(entryUuid)}`, entryUuid),
).toBeNull();
});
it('drops and removes an uploaded object over the size bound', async () => {
const entryUuid = crypto.randomUUID();
const key = mintedKey(entryUuid);
await putObject(s3, key, Buffer.alloc(2 * 1024 * 1024 + 1));
expect(await created(`s3://${BUCKET}/${key}`, entryUuid)).toBeNull();
expect(await objectExists(s3, key)).toBe(false);
});
});
describe('thumbnails extension — handleThumbnailUploadPrepare', () => {
let server: PuterServer;
let s3Presign: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3Presign = server.clients.s3.getForPresign();
});
afterAll(async () => {
await server?.shutdown();
});
it('returns early when event has no items array', async () => {
const event: Record<string, unknown> = {};
await handleThumbnailUploadPrepare(event, {
s3Presign,
bucketName: BUCKET,
});
// No items property added — handler is a no-op.
expect(event).toEqual({});
});
it('throws when items array contains a non-object entry', async () => {
await expect(
handleThumbnailUploadPrepare(
{ items: ['not-an-object'] } as unknown as Record<
string,
unknown
>,
{ s3Presign, bucketName: BUCKET },
),
).rejects.toThrow('thumbnail.upload.prepare item is invalid');
});
it('skips items without a contentType (no upload URL minted)', async () => {
const item: Record<string, unknown> = { contentType: '' };
await handleThumbnailUploadPrepare(
{ items: [item] },
{ s3Presign, bucketName: BUCKET },
);
expect(item.uploadUrl).toBeUndefined();
expect(item.thumbnailUrl).toBeUndefined();
});
it.each([
['exceeds the max thumbnail bytes', { size: 999_999_999 }],
['is not declared', {}],
['is not a whole number', { size: 10.5 }],
])('skips items whose size %s', async (_label, sizeField) => {
const item: Record<string, unknown> = {
contentType: 'image/png',
item_uid: crypto.randomUUID(),
...sizeField,
};
await handleThumbnailUploadPrepare(
{ items: [item] },
{ s3Presign, bucketName: BUCKET },
);
expect(item.uploadUrl).toBeUndefined();
expect(item.thumbnailUrl).toBeUndefined();
});
it('skips items with no entry to bind the key to', async () => {
const item: Record<string, unknown> = {
contentType: 'image/png',
size: 1024,
item_uid: 'not-a-uuid',
};
await handleThumbnailUploadPrepare(
{ items: [item] },
{ s3Presign, bucketName: BUCKET },
);
expect(item.uploadUrl).toBeUndefined();
expect(item.thumbnailUrl).toBeUndefined();
});
it('mints a size-bound upload URL for a key bound to the entry', async () => {
const entryUuid = crypto.randomUUID();
const item: Record<string, unknown> = {
contentType: 'image/png',
size: 1024,
item_uid: entryUuid,
};
await handleThumbnailUploadPrepare(
{ items: [item] },
{ s3Presign, bucketName: BUCKET },
);
expect(typeof item.uploadUrl).toBe('string');
expect((item.uploadUrl as string).startsWith('http')).toBe(true);
expect(typeof item.thumbnailUrl).toBe('string');
expect(
(item.thumbnailUrl as string).startsWith(
`s3://${BUCKET}/thumbnails/${entryUuid}/`,
),
).toBe(true);
// A signed `content-length` makes the store refuse any other body size.
const signedHeaders = new URL(
item.uploadUrl as string,
).searchParams.get('X-Amz-SignedHeaders');
expect(signedHeaders).toContain('content-length');
});
});
describe('thumbnails extension — handleThumbnailRead', () => {
let server: PuterServer;
let s3: S3Client;
let s3Presign: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3 = server.clients.s3.get();
s3Presign = server.clients.s3.getForPresign();
});
afterAll(async () => {
await server?.shutdown();
});
it('keeps read URLs stable within an hour and rotates them at the next hour', async () => {
const key = mintedKey();
const signedAt = Date.UTC(2026, 9, 26, 10);
const read = async () => {
const entry: Record<string, unknown> = {
thumbnail: `s3://${BUCKET}/${key}`,
};
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry: server.stores.fsEntry,
});
return entry.thumbnail as string;
};
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(signedAt + 1000);
const first = await read();
vi.setSystemTime(signedAt + 3599_000);
expect(await read()).toBe(first);
expect(new URL(first).searchParams.get('X-Amz-Date')).toBe(
'20261026T100000Z',
);
expect(new URL(first).searchParams.get('X-Amz-Expires')).toBe(
'604800',
);
vi.setSystemTime(signedAt + 3600_000);
expect(await read()).not.toBe(first);
} finally {
vi.useRealTimers();
}
});
it('reuses a URL signed this hour and signs afresh under a new signing key', async () => {
// Short-lived credentials are fetched again on every signing, so a
// swapped secret shows whether a read was signed or served from cache.
const creds = { accessKeyId: 'AKIDFIRST', secretAccessKey: 'one' };
const client = new S3Client({
region: 'us-west-2',
endpoint: 'http://127.0.0.1:4566',
forcePathStyle: true,
credentials: async () => ({
...creds,
expiration: new Date(Date.now() + 60_000),
}),
});
const keys = [mintedKey(), mintedKey(), mintedKey()];
const read = async (key: string) => {
const entry: Record<string, unknown> = {
thumbnail: `s3://${BUCKET}/${key}`,
};
await handleThumbnailRead(entry, {
s3,
s3Presign: client,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry: server.stores.fsEntry,
});
return entry.thumbnail as string;
};
const listing = () => Promise.all(keys.map(read));
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(Date.UTC(2026, 9, 26, 10, 30));
// A cold client's first listing signs its entries concurrently.
const first = await listing();
creds.secretAccessKey = 'two';
expect(await listing()).toEqual(first);
creds.accessKeyId = 'AKIDSECOND';
const rotated = await read(keys[0]);
expect(rotated).not.toBe(first[0]);
expect(
new URL(rotated).searchParams.get('X-Amz-Credential'),
).toMatch(/^AKIDSECOND\//);
} finally {
vi.useRealTimers();
}
});
// Thumbnails stored before keys were bound to entries keep displaying.
it.each([
['an entry-bound key', () => mintedKey()],
['a key that predates entry binding', legacyKey],
])(
'rewrites an s3:// thumbnail naming %s into a presigned https URL',
async (_label, makeKey) => {
// Seed an object so the presigned URL points at something real
// (the signer itself doesn't validate existence, but this keeps
// the test honest).
const key = makeKey();
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: Buffer.from(TINY_PNG_BASE64, 'base64'),
ContentType: 'image/png',
}),
);
const entry: Record<string, unknown> = {
thumbnail: `s3://${BUCKET}/${key}`,
};
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
fsEntry: server.stores.fsEntry,
});
expect(typeof entry.thumbnail).toBe('string');
expect((entry.thumbnail as string).startsWith('http')).toBe(true);
},
);
// `fsentries.thumbnail` is writable through the FS API, so a stored
// pointer is attacker input. Signing one the extension didn't mint would
// hand out a presigned read of an arbitrary object — including another
// user's file, whose key is its fsentry uuid in this same bucket.
it.each([
// Shaped exactly like an fs object key (and like a legacy thumbnail
// row) — indistinguishable from a planted pointer, so it fails closed.
[
"another user's file object",
`s3://${BUCKET}/${crypto.randomUUID()}`,
],
[
'a key outside the thumbnails namespace',
`s3://${BUCKET}/secrets/dump`,
],
[
'a namespace-lookalike key',
`s3://${BUCKET}/thumbnails/../${crypto.randomUUID()}`,
],
['a non-uuid inside the namespace', `s3://${BUCKET}/thumbnails/etc`],
[
'a key nested deeper than the namespace allows',
`s3://${BUCKET}/${mintedKey()}/${crypto.randomUUID()}`,
],
])('refuses to presign a pointer naming %s', async (_label, thumbnail) => {
const entry: Record<string, unknown> = { thumbnail };
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
fsEntry: server.stores.fsEntry,
});
expect(entry.thumbnail).toBeNull();
});
it('signs against its own bucket, ignoring the one in the pointer', async () => {
const key = mintedKey();
const entry: Record<string, unknown> = {
thumbnail: `s3://attacker-named-bucket/${key}`,
};
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
fsEntry: server.stores.fsEntry,
});
// Signed for OUR bucket; `attacker-named-bucket` never reached S3.
const signed = entry.thumbnail as string;
expect(signed.startsWith('http')).toBe(true);
expect(signed).not.toContain('attacker-named-bucket');
expect(signed).toContain(BUCKET);
});
it('leaves the thumbnail untouched when not s3/https/data', async () => {
const entry: Record<string, unknown> = { thumbnail: 'about:blank' };
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
fsEntry: server.stores.fsEntry,
});
expect(entry.thumbnail).toBe('about:blank');
});
it('returns early when the thumbnail is missing or non-string', async () => {
const entry: Record<string, unknown> = {};
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: 'http://127.0.0.1:4566/puter-local/',
fsEntry: server.stores.fsEntry,
});
expect(entry.thumbnail).toBeUndefined();
});
// -- inline data: URL migration --
// A file whose thumbnail was stored inline, as rows from before storage
// pointers are. Creating it leaves it in the entry cache.
const inlineThumbnailEntry = async (thumbnail: string) => {
const username = `thumb-${Math.random().toString(36).slice(2, 10)}`;
const user = await server.stores.user.create({
username,
uuid: crypto.randomUUID(),
password: null,
email: `${username}@test.local`,
free_storage: 100 * 1024 * 1024,
requires_email_confirmation: false,
});
await generateDefaultFsentries(
server.clients.db,
server.stores.user,
user,
);
const documents = (await server.stores.fsEntry.getEntryByPath(
`/${username}/Documents`,
))!;
return server.stores.fsEntry.createNonFileEntry({
parent: documents,
name: 'legacy.png',
kind: 'empty-file',
thumbnail,
});
};
// Passes every command through, keeping the keys of the uploads.
const recordingClient = () => {
const putKeys: string[] = [];
const client = {
send: async (command: unknown) => {
if (command instanceof PutObjectCommand) {
putKeys.push(command.input.Key!);
}
return s3.send(command as never);
},
} as unknown as S3Client;
return { client, putKeys };
};
// What a listing does: read the entry through the store, then sign it.
const readThumbnail = async (uuid: string, client: S3Client) => {
const stored = (await server.stores.fsEntry.getEntryByUuid(uuid))!;
const entry: Record<string, unknown> = {
uuid,
thumbnail: stored.thumbnail,
};
await handleThumbnailRead(entry, {
s3: client,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry: server.stores.fsEntry,
});
return entry.thumbnail;
};
it('migrates an inline data: URL to storage once, then serves the stored pointer', async () => {
const entry = await inlineThumbnailEntry(
`data:image/png;base64,${TINY_PNG_BASE64}`,
);
const { client, putKeys } = recordingClient();
const first = await readThumbnail(entry.uuid, client);
const second = await readThumbnail(entry.uuid, client);
expect(putKeys).toHaveLength(1);
const [key] = putKeys;
expect(key).toMatch(new RegExp(`^thumbnails/${entry.uuid}/`));
const pointer = `s3://${BUCKET}/${key}`;
// The cached entry and the row both hold the new pointer.
expect(
(await server.stores.fsEntry.getEntryByUuid(entry.uuid))!.thumbnail,
).toBe(pointer);
expect(
(await server.stores.fsEntry.getEntryByUuidFromPrimary(entry.uuid))!
.thumbnail,
).toBe(pointer);
for (const signed of [first, second]) {
expect(signed).toMatch(/^http/);
expect(signed).toContain(key);
}
});
it('keeps one object when reads of the same entry migrate it concurrently', async () => {
const thumbnail = `data:image/png;base64,${TINY_PNG_BASE64}`;
const entry = await inlineThumbnailEntry(thumbnail);
const { client, putKeys } = recordingClient();
const read = async () => {
const payload: Record<string, unknown> = {
uuid: entry.uuid,
thumbnail,
};
await handleThumbnailRead(payload, {
s3: client,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry: server.stores.fsEntry,
});
return payload.thumbnail;
};
await Promise.all([read(), read()]);
expect(putKeys).toHaveLength(2);
const stored = (await server.stores.fsEntry.getEntryByUuidFromPrimary(
entry.uuid,
))!.thumbnail;
const winner = putKeys.find(
(key) => stored === `s3://${BUCKET}/${key}`,
);
expect(winner).toBeDefined();
// The losing read's upload is not left behind.
for (const key of putKeys) {
expect(await objectExists(s3, key)).toBe(key === winner);
}
});
it.each([
[
'does not decode to an image',
`data:image/png;base64,${Buffer.from('not an image').toString('base64')}`,
],
['has no payload', 'data:image/png;base64'],
])(
'does not migrate an inline thumbnail that %s',
async (_label, thumbnail) => {
const entry = await inlineThumbnailEntry(thumbnail);
const { client, putKeys } = recordingClient();
expect(await readThumbnail(entry.uuid, client)).toBe(thumbnail);
expect(putKeys).toHaveLength(0);
expect(
(await server.stores.fsEntry.getEntryByUuidFromPrimary(
entry.uuid,
))!.thumbnail,
).toBe(thumbnail);
},
);
it('leaves an inline data: URL as is when there is no entry to bind it to', async () => {
const thumbnail = `data:image/png;base64,${TINY_PNG_BASE64}`;
const entry: Record<string, unknown> = { thumbnail };
await handleThumbnailRead(entry, {
s3,
s3Presign,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry: server.stores.fsEntry,
});
expect(entry.thumbnail).toBe(thumbnail);
});
});
describe('thumbnails extension — handleFsRemoveNodeThumbnail', () => {
let server: PuterServer;
let s3: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3 = server.clients.s3.get();
});
afterAll(async () => {
await server?.shutdown();
});
const remove = (target: { thumbnail?: string | null; uuid?: string }) =>
handleFsRemoveNodeThumbnail(
{ target },
{ s3, bucketName: BUCKET, bucketEndpoint: BUCKET_ENDPOINT },
);
it('deletes the object minted for the removed entry', async () => {
const entryUuid = crypto.randomUUID();
const key = mintedKey(entryUuid);
await putObject(s3, key, Buffer.from(TINY_PNG_BASE64, 'base64'));
await remove({ thumbnail: `s3://${BUCKET}/${key}`, uuid: entryUuid });
expect(await objectExists(s3, key)).toBe(false);
});
// The destructive half of the same confused deputy: the stored pointer
// decides which object is deleted, so only a key minted for the removed
// entry may reach DeleteObject.
it.each([
// Shaped like an fs object key.
[
'an object outside the thumbnails namespace',
() => crypto.randomUUID(),
],
// Visible to anyone who can list the entry it belongs to.
["another entry's thumbnail", () => mintedKey()],
// Can't be told apart from a planted or shared pointer.
['a thumbnail that predates entry binding', legacyKey],
])('does not delete %s', async (_label, makeKey) => {
const victimKey = makeKey();
await putObject(s3, victimKey, Buffer.from(TINY_PNG_BASE64, 'base64'));
await remove({
thumbnail: `s3://${BUCKET}/${victimKey}`,
uuid: crypto.randomUUID(),
});
expect(await objectExists(s3, victimKey)).toBe(true);
});
it('does not delete through an external URL that names our key', async () => {
const entryUuid = crypto.randomUUID();
const key = mintedKey(entryUuid);
await putObject(s3, key, Buffer.from(TINY_PNG_BASE64, 'base64'));
await remove({
thumbnail: `https://cdn.example.com/${BUCKET}/${key}`,
uuid: entryUuid,
});
expect(await objectExists(s3, key)).toBe(true);
});
it('is a no-op when the target has no thumbnail', async () => {
// Should not throw or attempt a delete.
await remove({});
});
});
describe('thumbnails extension — handleFsCopyNodeThumbnail', () => {
let server: PuterServer;
let s3: S3Client;
beforeAll(async () => {
server = await setupTestServer();
s3 = server.clients.s3.get();
});
afterAll(async () => {
await server?.shutdown();
});
const copyNode = async (
thumbnail: string | null,
copyUuid: string,
client: S3Client = s3,
) => {
const fsEntry = {
updateEntryThumbnailByUuid: vi.fn().mockResolvedValue(true),
};
await handleFsCopyNodeThumbnail(
{ copy: { thumbnail, uuid: copyUuid } },
{
s3: client,
bucketName: BUCKET,
bucketEndpoint: BUCKET_ENDPOINT,
fsEntry,
},
);
return fsEntry.updateEntryThumbnailByUuid;
};
// The key the copied row was repointed at, asserting it is bound to it.
const repointedKey = (
update: Awaited<ReturnType<typeof copyNode>>,
copyUuid: string,
): string => {
expect(update).toHaveBeenCalledTimes(1);
const [uuid, pointer] = update.mock.calls[0] as [string, string];
expect(uuid).toBe(copyUuid);
expect(pointer).toMatch(
new RegExp(`^s3://${BUCKET}/thumbnails/${copyUuid}/`),
);
return pointer.slice(`s3://${BUCKET}/`.length);
};
it.each([
['an entry-bound key', () => mintedKey()],
['a key that predates entry binding', legacyKey],
])(
'duplicates a thumbnail naming %s under a key bound to the copy',
async (_label, makeKey) => {
const sourceKey = makeKey();
const body = Buffer.from(TINY_PNG_BASE64, 'base64');
await putObject(s3, sourceKey, body);
const copyUuid = crypto.randomUUID();
const update = await copyNode(
`s3://${BUCKET}/${sourceKey}`,
copyUuid,
);
// The copied row was repointed at a fresh object of its own...
expect(update).toHaveBeenCalledTimes(1);
const [updatedUuid, newPointer] = update.mock.calls[0] as [
string,
string,
];
expect(updatedUuid).toBe(copyUuid);
expect(
newPointer.startsWith(`s3://${BUCKET}/thumbnails/${copyUuid}/`),
).toBe(true);
// ...whose content matches, while the source object survives — so
// deleting either entry can no longer break the other's thumbnail.
const newKey = newPointer.slice(`s3://${BUCKET}/`.length);
const duplicated = await s3.send(
new GetObjectCommand({ Bucket: BUCKET, Key: newKey }),
);
expect(duplicated.ContentType).toBe('image/png');
expect(
(await streamToBuffer(duplicated.Body as never)).equals(body),
).toBe(true);
expect(await objectExists(s3, sourceKey)).toBe(true);
},
);
// The SDK puts an endpoint's path in front of every Bucket/Key request but
// not in front of a CopyObject source, so on such a store HeadObject finds
// the source and CopyObject reports NoSuchKey.
it('duplicates through a client whose endpoint carries a path', async () => {
const endpoint = await s3.config.endpoint!();
const client = new S3Client({
region: await s3.config.region(),
endpoint: `${endpoint.protocol}//${endpoint.hostname}:${endpoint.port}/${BUCKET}`,
credentials: await s3.config.credentials(),
forcePathStyle: true,
});
const sourceKey = mintedKey();
const body = Buffer.from(TINY_PNG_BASE64, 'base64');
await putObject(client, sourceKey, body);
const copyUuid = crypto.randomUUID();
const update = await copyNode(
`s3://${BUCKET}/${sourceKey}`,
copyUuid,
client,
);
const duplicated = await client.send(
new GetObjectCommand({
Bucket: BUCKET,
Key: repointedKey(update, copyUuid),
}),
);
expect(duplicated.ContentType).toBe('image/png');
expect(
(await streamToBuffer(duplicated.Body as never)).equals(body),
).toBe(true);
});
it("lets either entry's removal leave the other's thumbnail in place", async () => {
const sourceUuid = crypto.randomUUID();
const sourceKey = mintedKey(sourceUuid);
const sourcePointer = `s3://${BUCKET}/${sourceKey}`;
await putObject(s3, sourceKey, Buffer.from(TINY_PNG_BASE64, 'base64'));
const remove = (thumbnail: string, uuid: string) =>
handleFsRemoveNodeThumbnail(
{ target: { thumbnail, uuid } },
{ s3, bucketName: BUCKET, bucketEndpoint: BUCKET_ENDPOINT },
);
// Removing a copy leaves the source's object...
const firstUuid = crypto.randomUUID();
const firstKey = repointedKey(
await copyNode(sourcePointer, firstUuid),
firstUuid,
);
await remove(`s3://${BUCKET}/${firstKey}`, firstUuid);
expect(await objectExists(s3, firstKey)).toBe(false);
expect(await objectExists(s3, sourceKey)).toBe(true);
// ...and removing the source leaves a copy's.
const secondUuid = crypto.randomUUID();
const secondKey = repointedKey(
await copyNode(sourcePointer, secondUuid),
secondUuid,
);
await remove(sourcePointer, sourceUuid);
expect(await objectExists(s3, sourceKey)).toBe(false);
expect(await objectExists(s3, secondKey)).toBe(true);
});
it('drops the pointer when the shared object is already gone', async () => {
const copyUuid = crypto.randomUUID();
const update = await copyNode(
`s3://${BUCKET}/${mintedKey()}`, // never uploaded
copyUuid,
);
expect(update.mock.calls).toEqual([[copyUuid, null]]);
});
// Only reachable for objects uploaded before upload URLs were size-bound;
// copying one would multiply bytes no allowance counts.
it('drops the pointer instead of duplicating an object over the size bound', async () => {
const sourceKey = legacyKey();
await putObject(s3, sourceKey, Buffer.alloc(2 * 1024 * 1024 + 1));
const copyUuid = crypto.randomUUID();
const update = await copyNode(`s3://${BUCKET}/${sourceKey}`, copyUuid);
expect(update.mock.calls).toEqual([[copyUuid, null]]);
});
it('drops the pointer when the object outgrows the bound after its size was checked', async () => {
const sourceKey = mintedKey();
await putObject(s3, sourceKey, Buffer.from(TINY_PNG_BASE64, 'base64'));
const sent: unknown[] = [];
// Replaces the object between the HEAD and the GET.
const racing = {
send: async (command: unknown) => {
sent.push(command);
const result = await s3.send(command as never);
if (command instanceof HeadObjectCommand) {
await putObject(
s3,
sourceKey,
Buffer.alloc(2 * 1024 * 1024 + 1),
);
}
return result;
},
} as unknown as S3Client;
const copyUuid = crypto.randomUUID();
const update = await copyNode(
`s3://${BUCKET}/${sourceKey}`,
copyUuid,
racing,
);
expect(update.mock.calls).toEqual([[copyUuid, null]]);
expect(sent.some((c) => c instanceof PutObjectCommand)).toBe(false);
});
it('does not duplicate an object the pointer names but we did not mint', async () => {
const foreignKey = crypto.randomUUID(); // shaped like an fs object key
const update = await copyNode(
`s3://${BUCKET}/${foreignKey}`,
crypto.randomUUID(),
);
expect(update).not.toHaveBeenCalled();
});
it('leaves an external image URL to ride along as is', async () => {
const sourceKey = legacyKey();
await putObject(s3, sourceKey, Buffer.from(TINY_PNG_BASE64, 'base64'));
const update = await copyNode(
`https://cdn.example.com/${BUCKET}/${sourceKey}`,
crypto.randomUUID(),
);
expect(update).not.toHaveBeenCalled();
});
it('is a no-op when the copy has no thumbnail', async () => {
const update = await copyNode(null, crypto.randomUUID());
expect(update).not.toHaveBeenCalled();
});
});
// The flow `puter.fs.upload()` runs — start, PUT to the signed URLs, complete
// with the returned pointer — through the real controller and the listeners
// this extension registers.
describe('thumbnails extension — signed batch upload through /fs', () => {
let server: PuterServer;
let controller: FSController;
const png = Buffer.from(TINY_PNG_BASE64, 'base64');
beforeAll(async () => {
server = await setupTestServer();
controller = server.controllers.fs as unknown as FSController;
});
afterAll(async () => {
await server?.shutdown();
});
const makeActor = async (): Promise<{ actor: Actor; username: string }> => {
const username = `thumb-${Math.random().toString(36).slice(2, 10)}`;
const user = await server.stores.user.create({
username,
uuid: crypto.randomUUID(),
password: null,
email: `${username}@test.local`,
free_storage: 100 * 1024 * 1024,
requires_email_confirmation: false,
});
await generateDefaultFsentries(
server.clients.db,
server.stores.user,
user,
);
return {
username,
actor: {
user: {
id: user.id,
uuid: user.uuid,
username,
email: user.email ?? null,
email_confirmed: true,
} as Actor['user'],
},
};
};
const call = async <B>(
actor: Actor,
handler: (req: Request, res: Response) => Promise<void>,
body: B,
): Promise<unknown> => {
let captured: unknown;
const res = {
json: (value: unknown) => {
captured = value;
return res;
},
status: () => res,
setHeader: () => res,
};
const req = {
body,
query: {},
headers: { 'content-type': 'application/json' },
actor,
user: { id: actor.user!.id, username: actor.user!.username },
};
await runWithContext({ actor }, () =>
handler.call(
controller,
req as unknown as Request,
res as unknown as Response,
),
);
return captured;
};
const upload = async (
actor: Actor,
path: string,
thumbnailData: (
started: ClientSignedWriteResponse,
) => string | undefined,
) => {
const [started] = (await call<SignedWriteRequest[]>(
actor,
controller.startBatchWrites,
[
{
fileMetadata: { path, size: 4 },
thumbnailMetadata: {
contentType: 'image/png',
size: png.length,
},
},
],
)) as ClientSignedWriteResponse[];
await fetch(started!.url!, { method: 'PUT', body: 'abcd' });
if (started!.thumbnailUploadUrl) {
await fetch(started!.thumbnailUploadUrl, {
method: 'PUT',
body: png,
headers: { 'content-type': 'image/png' },
});
}
const thumbnail = thumbnailData(started!);
await call<CompleteWriteRequest[]>(
actor,
controller.completeBatchWrites,
[
{
uploadId: started!.sessionId,
...(thumbnail === undefined
? {}
: { thumbnailData: thumbnail }),
},
],
);
return {
started: started!,
entry: (await server.stores.fsEntry.getEntryByPath(path))!,
};
};
it('stores the pointer minted for the uploaded entry', async () => {
const { actor, username } = await makeActor();
const { started, entry } = await upload(
actor,
`/${username}/Documents/photo.png`,
(s) => s.thumbnailUrl,
);
expect(started.thumbnailUrl).toMatch(
new RegExp(`^s3://${BUCKET}/thumbnails/${entry.uuid}/`),
);
expect(entry.thumbnail).toBe(started.thumbnailUrl);
});
it("drops a pointer minted for another user's entry", async () => {
const victim = await makeActor();
const { entry: victimEntry } = await upload(
victim.actor,
`/${victim.username}/Documents/photo.png`,
(s) => s.thumbnailUrl,
);
const attacker = await makeActor();
const { entry } = await upload(
attacker.actor,
`/${attacker.username}/Documents/decoy.png`,
() => victimEntry.thumbnail!,
);
expect(entry.thumbnail).toBeNull();
});
it('keeps an external image URL as given', async () => {
const { actor, username } = await makeActor();
const { entry } = await upload(
actor,
`/${username}/Documents/linked.png`,
() => 'https://example.com/thumb.png',
);
expect(entry.thumbnail).toBe('https://example.com/thumb.png');
});
it('gives a copy its own thumbnail that survives moves and the source being removed', async () => {
const { actor, username } = await makeActor();
const s3 = server.clients.s3.get();
const fs = server.services.fs;
const { entry: source } = await upload(
actor,
`/${username}/Documents/photo.png`,
(s) => s.thumbnailUrl,
);
const userId = source.userId;
const sourceKey = source.thumbnail!.slice(`s3://${BUCKET}/`.length);
const desktop = (await server.stores.fsEntry.getEntryByPath(
`/${username}/Desktop`,
))!;
// Through the entry cache, which the listener's write refreshes.
const storedThumbnail = async (uuid: string) =>
(await server.stores.fsEntry.getEntryByUuid(uuid))?.thumbnail ??
null;
const copy = await runWithContext({ actor }, () =>
fs.copy(userId, { source, destinationParent: desktop }),
);
// `fs.copy.node` is fire-and-forget.
const copyPointer = await vi.waitFor(async () => {
const pointer = await storedThumbnail(copy.uuid);
expect(pointer).toMatch(
new RegExp(`^s3://${BUCKET}/thumbnails/${copy.uuid}/`),
);
return pointer!;
});
const copyKey = copyPointer.slice(`s3://${BUCKET}/`.length);
const documents = (await server.stores.fsEntry.getEntryByPath(
`/${username}/Documents`,
))!;
const moved = await runWithContext({ actor }, () =>
fs.move(userId, {
source: copy,
destinationParent: documents,
newName: 'moved.png',
}),
);
expect(moved.uuid).toBe(copy.uuid);
expect(await storedThumbnail(moved.uuid)).toBe(copyPointer);
await runWithContext({ actor }, () =>
fs.remove(userId, { entry: source }),
);
await vi.waitFor(async () => {
expect(await objectExists(s3, sourceKey)).toBe(false);
});
expect(await objectExists(s3, copyKey)).toBe(true);
});
it('deletes the thumbnail object an overwrite drops', async () => {
const { actor, username } = await makeActor();
const s3 = server.clients.s3.get();
const path = `/${username}/Documents/edited.png`;
const { entry } = await upload(actor, path, (s) => s.thumbnailUrl);
const key = entry.thumbnail!.slice(`s3://${BUCKET}/`.length);
expect(await objectExists(s3, key)).toBe(true);
// An app saving over the file sends no thumbnail.
await server.services.fs.write(actor.user!.id!, {
fileMetadata: { path, size: 4, overwrite: true },
fileContent: 'efgh',
} as never);
expect(
(await server.stores.fsEntry.getEntryByPath(path))?.thumbnail,
).toBeNull();
// `thumbnail.discarded` is fire-and-forget.
await vi.waitFor(async () => {
expect(await objectExists(s3, key)).toBe(false);
});
});
});