freshyo/apps/backend/tests/api/uploads.test.ts
2026-09-26 22:29:54 +05:30

133 lines
4.7 KiB
TypeScript

/**
* Image uploads — the round trip, not just the response shape.
*
* The presigned PUT carries its own signature, so this suite needs no R2 credentials:
* it PUTs real bytes to the URL `common.generateUploadUrls` returns, then GETs the object
* back from the public assets domain (the same source the app renders from) and compares.
*
* Objects are left in the dev bucket, consistent with the rest of these tests.
*/
import { createHash } from 'crypto'
import { apiClient, uniqueSuffix } from '../helpers/api'
import { essentialConsts } from '../helpers/cache'
import { userSession } from '../helpers/sessions'
/** Two 1x1 PNGs that differ only in pixel data, so a mix-up is visible. */
const PNG_RED = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==',
'base64'
)
const PNG_BLUE = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAE/wH/9tH4WQAAAABJRU5ErkJggg==',
'base64'
)
const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
/** The object key, as extractKeyFromPresignedUrl derives it (last two path segments). */
const keyFromUploadUrl = (url: string) => {
const parts = new URL(url).pathname.split('/').filter(Boolean)
return decodeURIComponent(parts.slice(-2).join('/'))
}
const publicUrlFor = (assetsDomain: string, key: string) =>
`${assetsDomain.replace(/\/+$/, '')}/${key}`
/** Presign one file and return its URL plus the key it points at. */
async function presign(
client: ReturnType<typeof apiClient>,
contextString: string,
mimeType: string
) {
const { uploadUrls } = await client.common.generateUploadUrls.mutate({
contextString: contextString as never,
mimeTypes: [mimeType],
})
const url = uploadUrls[0]
return { url, key: keyFromUploadUrl(url) }
}
async function put(url: string, bytes: Buffer) {
const res = await fetch(url, {
method: 'PUT',
body: new Uint8Array(bytes),
})
if (!res.ok) {
throw new Error(
`[uploads] PUT failed: ${res.status} ${res.statusText} ${await res.text().catch(() => '')}`
)
}
}
/** GET the object from the public domain; returns null when it is not there. */
async function fetchObject(url: string) {
const res = await fetch(url)
if (!res.ok) return null
return Buffer.from(await res.arrayBuffer())
}
describe('image upload round trip', () => {
let client: ReturnType<typeof apiClient>
let assetsDomain: string
beforeAll(async () => {
const session = await userSession()
client = apiClient(session.token)
assetsDomain = (await essentialConsts()).assetsDomain
})
it('stores exactly the bytes that were uploaded', async () => {
const { url, key } = await presign(client, 'product_info', 'image/png')
expect(url).toContain('X-Amz-Signature')
await put(url, PNG_RED)
const served = await fetchObject(publicUrlFor(assetsDomain, key))
expect(served).not.toBeNull()
expect(served!.length).toBe(PNG_RED.length)
expect(served!.equals(PNG_RED)).toBe(true)
expect(sha(served!)).toBe(sha(PNG_RED))
})
it('keeps two uploads distinct — each URL serves its own object', async () => {
const first = await presign(client, 'product_info', 'image/png')
const second = await presign(client, 'tags', 'image/png')
expect(second.key).not.toBe(first.key)
await put(first.url, PNG_RED)
await put(second.url, PNG_BLUE)
const servedFirst = await fetchObject(publicUrlFor(assetsDomain, first.key))
const servedSecond = await fetchObject(publicUrlFor(assetsDomain, second.key))
expect(servedFirst!.equals(PNG_RED)).toBe(true)
expect(servedSecond!.equals(PNG_BLUE)).toBe(true)
// The two documents really are different files.
expect(sha(servedFirst!)).not.toBe(sha(servedSecond!))
})
it('gives every mime type in one call a usable URL', async () => {
const { uploadUrls } = await client.common.generateUploadUrls.mutate({
contextString: 'review',
mimeTypes: ['image/png', 'image/jpeg'],
})
expect(uploadUrls).toHaveLength(2)
const keys = uploadUrls.map(keyFromUploadUrl)
expect(new Set(keys).size).toBe(2)
await put(uploadUrls[0], PNG_RED)
await put(uploadUrls[1], PNG_BLUE)
expect((await fetchObject(publicUrlFor(assetsDomain, keys[0])))!.equals(PNG_RED)).toBe(true)
expect((await fetchObject(publicUrlFor(assetsDomain, keys[1])))!.equals(PNG_BLUE)).toBe(true)
})
it('returns 404 for an object that was never uploaded', async () => {
// Guards the read-back itself: a passing comparison must mean the object is really there.
const missing = publicUrlFor(assetsDomain, `product-images/never-${uniqueSuffix()}.png`)
expect(await fetchObject(missing)).toBeNull()
})
})