diff --git a/apps/web/__tests__/unit/cookie-write-site.test.ts b/apps/web/__tests__/unit/cookie-write-site.test.ts index 564ff3db045..fe29ca6473d 100644 --- a/apps/web/__tests__/unit/cookie-write-site.test.ts +++ b/apps/web/__tests__/unit/cookie-write-site.test.ts @@ -47,6 +47,7 @@ const mocks = vi.hoisted(() => { update: () => ({ set: () => ({ where: async () => undefined }) }), }; return { + webUrl: "https://cap.so", cookieUser, keyUser, client, @@ -58,7 +59,7 @@ const mocks = vi.hoisted(() => { vi.mock("server-only", () => ({})); vi.mock("@cap/env", () => ({ - serverEnv: () => ({ WEB_URL: "https://cap.so" }), + serverEnv: () => ({ WEB_URL: mocks.webUrl }), buildEnv: { NEXT_PUBLIC_WEB_URL: "https://cap.so", NEXT_PUBLIC_IS_CAP: "true", @@ -103,8 +104,13 @@ const sameSite = { "sec-fetch-site": "same-site", origin: "https://www.cap.so", }; +const mediaHost = { + "sec-fetch-site": "same-site", + origin: "https://v.cap.so", +}; beforeEach(() => { + mocks.webUrl = "https://cap.so"; mocks.getServerSession.mockClear(); mocks.getSessionUser.mockClear(); }); @@ -138,6 +144,94 @@ describe("isCrossSiteCookieWrite", () => { expect(isCrossSiteCookieWrite(request("POST", headers))).toBe(false); }); + it.each([ + ["the media host", mediaHost], + [ + "another sibling subdomain", + { "sec-fetch-site": "same-site", origin: "https://uploads.cap.so" }, + ], + ["an opaque origin", { "sec-fetch-site": "same-site", origin: "null" }], + ["no Origin", { "sec-fetch-site": "same-site" }], + [ + "the www host on another scheme", + { "sec-fetch-site": "same-site", origin: "http://www.cap.so" }, + ], + ])("flags a same-site write from %s", (_label, headers) => { + expect(isCrossSiteCookieWrite(request("POST", headers))).toBe(true); + }); + + it("allows a same-site write from the app's own host", () => { + expect( + isCrossSiteCookieWrite( + request( + "POST", + { "sec-fetch-site": "same-site", origin: "https://www.cap.so" }, + "https://www.cap.so/api/test", + ), + ), + ).toBe(false); + }); + + it("allows a write from the extension's own pages", () => { + expect( + isCrossSiteCookieWrite( + request("POST", { + "sec-fetch-site": "none", + origin: "chrome-extension://abcdefghijklmnopabcdefghijklmnop", + }), + ), + ).toBe(false); + }); + + it.each([ + [ + "its www host", + "https://cap.acme.example", + "https://www.cap.acme.example", + false, + ], + [ + "its apex host", + "https://www.acme.example", + "https://acme.example", + false, + ], + [ + "a sibling host", + "https://cap.acme.example", + "https://media.acme.example", + true, + ], + ])( + "checks a same-site write to a self-hosted install from %s", + (_label, webUrl, origin, flagged) => { + mocks.webUrl = webUrl; + const host = new URL(webUrl).host; + expect( + isCrossSiteCookieWrite( + request( + "POST", + { "sec-fetch-site": "same-site", origin }, + `https://${host}/api/test`, + ), + ), + ).toBe(flagged); + }, + ); + + it("allows a plain-http self-hosted write without fetch metadata", () => { + mocks.webUrl = "http://cap.acme.example"; + expect( + isCrossSiteCookieWrite( + request( + "POST", + { origin: "http://cap.acme.example" }, + "http://cap.acme.example/api/test", + ), + ), + ).toBe(false); + }); + it("treats the request host as an own origin for custom domains and previews", () => { expect( isCrossSiteCookieWrite( @@ -241,9 +335,19 @@ describe("Hono cookie fallback", () => { expect(await response.json()).toEqual({ user: "cookie-user" }); }); - it("authenticates a bearer write from any site", async () => { + it("does not authenticate a cookie write from a page on the media host", async () => { + const response = await send("/required", "POST", mediaHost); + expect(response.status).toBe(401); + expect(mocks.getSessionUser).not.toHaveBeenCalled(); + }); + + it.each([ + ["any site", crossSite], + ["the media host", mediaHost], + ["a native client", {}], + ])("authenticates a bearer write from %s", async (_label, headers) => { const response = await send("/required", "POST", { - ...crossSite, + ...headers, authorization: `Bearer ${API_KEY}`, }); expect(response.status).toBe(200); @@ -273,6 +377,22 @@ describe("App Router cookie writes", () => { expect(mocks.getSessionUser).not.toHaveBeenCalled(); }); + it("does not rename the account from a page on the media host", async () => { + const response = await updateUserName( + new Request("https://cap.so/api/settings/user/name", { + method: "POST", + headers: { + host: "cap.so", + "content-type": "text/plain;charset=UTF-8", + ...mediaHost, + }, + body: JSON.stringify({ firstName: "A", lastName: "B" }), + }) as never, + ); + expect(response.status).toBe(401); + expect(mocks.getSessionUser).not.toHaveBeenCalled(); + }); + it("authenticates a same-origin cookie write", async () => { const response = await rename(sameOrigin); expect(response.status).toBe(200); @@ -310,6 +430,7 @@ describe("Effect getCurrentUser", () => { it.each([ ["plain cross-site write", request("POST", crossSite)], + ["write from the media host", request("POST", mediaHost)], [ "cross-site write carrying a bogus bearer", request("POST", { ...crossSite, authorization: "Bearer other" }), @@ -403,9 +524,18 @@ describe("HttpApi auth middleware", () => { expect(await response.json()).toEqual({ user: "cookie-user" }); }); - it("authenticates a bearer write from any site", async () => { + it("does not authenticate a cookie write from the media host", async () => { + const response = await send("POST", mediaHost); + expect(response.status).toBe(401); + }); + + it.each([ + ["any site", crossSite], + ["the media host", mediaHost], + ["a native client", {}], + ])("authenticates a bearer write from %s", async (_label, headers) => { const response = await send("POST", { - ...crossSite, + ...headers, authorization: `Bearer ${API_KEY}`, }); expect(response.status).toBe(200); @@ -453,6 +583,12 @@ describe("RPC auth middleware", () => { expect(JSON.stringify(exit.cause)).toContain("UnauthenticatedError"); }); + it("does not authenticate a cookie call from the media host", async () => { + const exit = await call(mediaHost); + expect(exit._tag).toBe("Failure"); + expect(JSON.stringify(exit.cause)).toContain("UnauthenticatedError"); + }); + it("reads fetch metadata from the HTTP request, not the RPC payload headers", async () => { const exit = await call(crossSite, [ ["sec-fetch-site", "same-origin"], diff --git a/apps/web/__tests__/unit/media-processing-policy.test.ts b/apps/web/__tests__/unit/media-processing-policy.test.ts index 06d4f1b19db..23e624625fc 100644 --- a/apps/web/__tests__/unit/media-processing-policy.test.ts +++ b/apps/web/__tests__/unit/media-processing-policy.test.ts @@ -24,6 +24,8 @@ import { MEDIA_INPUT_POLICY_STRIKE_WINDOW_MS, mediaProcessingSuspendedError, readMediaInputPolicyState, + toCompletedUploadContentType, + toStoredUploadContentType, unsupportedMediaInputError, } from "@/lib/media-processing-policy"; @@ -214,3 +216,56 @@ describe("getMediaProcessingRejection", () => { ); }); }); + +describe("toStoredUploadContentType", () => { + it.each([ + "video/mp4", + "video/webm;codecs=vp9,opus", + "Video/QuickTime", + "audio/mp4", + "image/png", + "image/jpeg", + ])("keeps %s", (contentType) => { + expect(toStoredUploadContentType(contentType)).toBe(contentType); + }); + + it.each([ + "text/html", + " TEXT/HTML ; charset=utf-8", + "application/xhtml+xml", + "image/svg+xml", + "text/xml", + "application/xml", + "text/javascript", + "application/pdf", + "multipart/x-mixed-replace", + "", + ])("stores %s as plain bytes", (contentType) => { + expect(toStoredUploadContentType(contentType)).toBe( + "application/octet-stream", + ); + }); +}); + +describe("toCompletedUploadContentType", () => { + it.each([ + ["owner/video/page.html", "application/octet-stream"], + ["owner/video/page", "application/octet-stream"], + ["owner/video/image.svg", "Application/Octet-Stream"], + ])("keeps %s stored as %s a download", (fileKey, stored) => { + expect(toCompletedUploadContentType(fileKey, stored)).toBe( + "application/octet-stream", + ); + }); + + it.each([ + ["owner/video/result.mp4", "application/octet-stream"], + ["owner/video/clip.webm", "application/octet-stream"], + ["owner/video/result.mp4", "video/mp4"], + ["owner/video/clip.webm", "video/webm"], + ["owner/video/result.mp4", undefined], + ["owner/video/page.html", undefined], + ])("completes %s stored as %s as video/mp4", (fileKey, stored) => { + expect(toCompletedUploadContentType(fileKey, stored)).toBe("video/mp4"); + }); +}); diff --git a/apps/web/__tests__/unit/mobile-upload-content-type.test.ts b/apps/web/__tests__/unit/mobile-upload-content-type.test.ts new file mode 100644 index 00000000000..d0568b4a9be --- /dev/null +++ b/apps/web/__tests__/unit/mobile-upload-content-type.test.ts @@ -0,0 +1,223 @@ +import * as Db from "@cap/database/schema"; +import { + CurrentUser, + DatabaseError, + HttpAuthMiddleware, + Organisation, + User, + Video, +} from "@cap/web-domain"; +import { type HttpApi, HttpApiBuilder, HttpServer } from "@effect/platform"; +import type { MySqlTable } from "drizzle-orm/mysql-core"; +import { Effect, Layer, Option } from "effect"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { + Database, + type DbClient, +} from "../../../../packages/web-backend/src/Database"; + +const mocks = vi.hoisted(() => ({ + createUploadTarget: vi.fn(), + createVideo: vi.fn(), + getWritableAccessForUser: vi.fn(), +})); + +vi.mock("server-only", () => ({})); +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })); +vi.mock("@cap/env", () => ({ + buildEnv: { NEXT_PUBLIC_IS_CAP: "false" }, + NODE_ENV: "test", + serverEnv: () => ({ WEB_URL: "https://cap.test" }), +})); +vi.mock("@cap/database", () => ({ db: () => database })); +vi.mock("@cap/database/auth/auth-options", () => ({ authOptions: () => ({}) })); +vi.mock("@cap/database/emails/config", () => ({ sendEmail: vi.fn() })); +vi.mock("@cap/database/video-sharing-default", () => ({ + getNewVideoPublic: vi.fn(async () => true), +})); +vi.mock("@/app/(org)/dashboard/analytics/data", () => ({})); +vi.mock("@/lib/account-deletion-request", () => ({})); +vi.mock("@/lib/desktop-segments-finalization", () => ({})); +vi.mock("@/lib/loom-concierge", () => ({})); +vi.mock("@/lib/loom-download-url", () => ({})); +vi.mock("@/lib/Notification", () => ({})); +vi.mock("@/lib/organization-provisioning", () => ({})); +vi.mock("@/lib/rate-limit", () => ({ + isRateLimited: vi.fn(async () => false), + RATE_LIMIT_IDS: {}, +})); +vi.mock("@/lib/sync-video-storage-names", () => ({})); +vi.mock("@/lib/video-processing", () => ({})); +vi.mock("@/workflows/import-loom-video", () => ({})); +vi.mock("workflow/api", () => ({ getRun: vi.fn(), start: vi.fn() })); +vi.mock("workflow/runtime", () => ({ getWorld: () => ({}) })); +vi.mock("@cap/web-backend", async () => { + const { Context } = await import("effect"); + const { Database } = await import( + "../../../../packages/web-backend/src/Database" + ); + return { + Database, + Storage: Object.assign(Context.GenericTag("mobile-upload-test/Storage"), { + getWritableAccessForUser: mocks.getWritableAccessForUser, + }), + Tinybird: Context.GenericTag("mobile-upload-test/Tinybird"), + VideosPolicy: Context.GenericTag("mobile-upload-test/VideosPolicy"), + VideosRepo: Context.GenericTag("mobile-upload-test/VideosRepo"), + Videos: Context.GenericTag("mobile-upload-test/Videos"), + ImageUploads: Context.GenericTag("mobile-upload-test/ImageUploads"), + }; +}); + +const user = { + id: User.UserId.make("uploader"), + email: "uploader@example.com", + activeOrganizationId: Organisation.OrganisationId.make("organization"), + iconUrlOrKey: Option.none(), +}; + +const database = { + select: () => ({ + from: (table: MySqlTable) => { + const rows = + table === Db.organizations ? [{ id: user.activeOrganizationId }] : []; + const query = { + leftJoin: () => query, + innerJoin: () => query, + where: () => Object.assign(Promise.resolve(rows), query), + limit: async () => rows, + }; + return query; + }, + }), + insert: () => ({ values: async () => undefined }), + update: () => ({ + set: () => ({ where: async () => [{ affectedRows: 1 }] }), + }), + transaction: (callback: (tx: unknown) => Promise) => callback(database), +}; + +let dispose: () => Promise; +vi.mock("@/lib/server", async () => { + const { Videos, VideosRepo, ImageUploads, Storage } = await import( + "@cap/web-backend" + ); + return { + runPromise: Effect.runPromise, + apiToHandler: ( + api: Layer.Layer, + ) => { + const web = HttpApiBuilder.toWebHandler( + api.pipe( + Layer.provide( + Layer.succeed( + Database, + Database.make({ + use: (callback) => + Effect.tryPromise({ + try: () => callback(database as unknown as DbClient), + catch: (cause) => new DatabaseError({ cause }), + }), + }), + ), + ), + Layer.provide(Layer.mock(Videos, { _tag: "Videos" })), + Layer.provide( + Layer.succeed(Storage, { + getWritableAccessForUser: mocks.getWritableAccessForUser, + } as never), + ), + Layer.provide( + Layer.succeed(VideosRepo, { + create: mocks.createVideo, + } as never), + ), + Layer.provide(Layer.mock(ImageUploads, { _tag: "ImageUploads" })), + Layer.provide( + Layer.succeed( + HttpAuthMiddleware, + Effect.succeed(CurrentUser.of(user)), + ), + ), + Layer.merge(HttpServer.layerContext), + ), + ); + dispose = web.dispose; + return web.handler; + }, + }; +}); + +const { POST } = await import("@/app/api/mobile/[...route]/route"); + +function createUpload(fileName: string, contentType: string) { + return POST( + new Request("http://localhost/api/mobile/uploads", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ fileName, contentType, contentLength: 1024 }), + }), + ); +} + +beforeEach(() => { + mocks.createVideo + .mockReset() + .mockReturnValue(Effect.succeed(Video.VideoId.make("video"))); + mocks.createUploadTarget + .mockReset() + .mockImplementation((_key: string, input: { contentType: string }) => + Effect.succeed({ + type: "put", + url: "https://storage.test/upload", + headers: { "Content-Type": input.contentType }, + }), + ); + mocks.getWritableAccessForUser.mockReset().mockReturnValue( + Effect.succeed({ + access: { createUploadTarget: mocks.createUploadTarget }, + bucketId: Option.none(), + storageIntegrationId: Option.none(), + }), + ); +}); + +afterAll(async () => { + await dispose(); +}); + +describe("POST /api/mobile/uploads", () => { + it.each([ + ["Clip.mov", "video/quicktime", "raw-upload.mov"], + ["Clip.mp4", "video/mp4", "raw-upload.mp4"], + ["Screen.png", "image/png", "screen-capture.png"], + ["Photo.jpg", "image/jpeg", "screen-capture.jpg"], + ])( + "keeps the real type of %s sent as %s", + async (fileName, contentType, objectName) => { + const response = await createUpload(fileName, contentType); + + expect(response.status).toBe(200); + const body = await response.json(); + expect(body.rawFileKey).toMatch(new RegExp(`/${objectName}$`)); + expect(body.upload.headers).toEqual({ "Content-Type": contentType }); + expect(mocks.createUploadTarget).toHaveBeenCalledWith( + body.rawFileKey, + expect.objectContaining({ + contentType, + fields: expect.objectContaining({ "Content-Type": contentType }), + }), + ); + }, + ); + + it.each([ + ["page.html", "text/html"], + ["drawing.svg", "image/svg+xml"], + ])("refuses %s sent as %s", async (fileName, contentType) => { + const response = await createUpload(fileName, contentType); + + expect(response.status).toBe(400); + expect(mocks.createUploadTarget).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/__tests__/unit/multipart-presign.test.ts b/apps/web/__tests__/unit/multipart-presign.test.ts index e11c55acab2..a4276f02882 100644 --- a/apps/web/__tests__/unit/multipart-presign.test.ts +++ b/apps/web/__tests__/unit/multipart-presign.test.ts @@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({ complete: vi.fn(), create: vi.fn(), abort: vi.fn(), + copy: vi.fn(), })); vi.mock("@cap/env", () => ({ serverEnv: () => ({ NEXTAUTH_SECRET: "test-reupload-secret" }), @@ -167,7 +168,10 @@ describe("desktop reupload completion", () => { const oldKey = "owner/video/.recording/outputs/original/result.mp4"; let events: string[]; let updates: Record[]; - let objects: Map; + let objects: Map< + string, + { ETag: string; ContentLength: number; ContentType?: string } + >; let video: { id: Video.VideoId; ownerId: User.UserId; @@ -309,11 +313,13 @@ describe("desktop reupload completion", () => { getPresignedUploadPartUrl: mocks.sign, }, headObject: (key: string) => Effect.suspend(() => mocks.head(key)), - copyObject: () => - Effect.succeed({ CopyObjectResult: { ETag: "new-video" } }), + copyObject: (...args: unknown[]) => mocks.copy(...args), }, ]), ); + mocks.copy.mockReturnValue( + Effect.succeed({ CopyObjectResult: { ETag: "new-video" } }), + ); mocks.sign.mockReturnValue(Effect.succeed("https://uploads.example/part")); mocks.prepareReplacement.mockImplementation( async ( @@ -610,6 +616,87 @@ describe("desktop reupload completion", () => { expect(objects.get(oldKey)?.ETag).toBe("original"); expect(mocks.complete).toHaveBeenCalledTimes(1); }); + it.each([ + ["raw-upload.html", "text/html", "application/octet-stream"], + ["raw-upload.mp4", "text/html; charset=utf-8", "application/octet-stream"], + ["raw-upload.svg", "image/svg+xml", "application/octet-stream"], + ["raw-upload.xhtml", "application/xhtml+xml", "application/octet-stream"], + [ + "raw-upload.webm", + "video/webm;codecs=vp9,opus", + "video/webm;codecs=vp9,opus", + ], + ["raw-upload.m4a", "audio/mp4", "audio/mp4"], + ["screenshot/screen-capture.png", "image/png", "image/png"], + ])( + "stores a %s upload sent as %s with content type %s", + async (subpath, contentType, stored) => { + const response = await app.request("/initiate", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ videoId: "video", subpath, contentType }), + }); + expect(response.status).toBe(200); + expect(mocks.create).toHaveBeenCalledWith( + `owner/video/${subpath}`, + expect.objectContaining({ ContentType: stored }), + ); + }, + ); + + it.each([ + ["page.html", "application/octet-stream", "application/octet-stream"], + ["result.mp4", "application/octet-stream", "video/mp4"], + ["result.mp4", "video/mp4", "video/mp4"], + ])( + "completes a %s upload stored as %s with content type %s", + async (subpath, storedType, completedType) => { + mocks.complete.mockImplementation((key: string) => + Effect.sync(() => { + objects.set(key, { + ETag: "upload", + ContentLength: 100, + ContentType: storedType, + }); + return { ETag: "upload" }; + }), + ); + const response = await app.request("/complete", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + videoId: "video", + uploadId: "backend-upload", + subpath, + parts: [{ partNumber: 1, etag: "part", size: 100 }], + }), + }); + expect(response.status).toBe(200); + expect(mocks.copy).toHaveBeenCalledWith( + expect.any(String), + `owner/video/${subpath}`, + expect.objectContaining({ ContentType: completedType }), + ); + }, + ); + + it("stores a replacement upload sent as a web page as plain bytes", async () => { + const response = await app.request("/initiate", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + videoId: "video", + contentType: "text/html", + replaceExisting: true, + }), + }); + expect(response.status).toBe(200); + expect(mocks.create).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ ContentType: "application/octet-stream" }), + ); + }); + it("signs only the authenticated replacement key and backend session", async () => { const response = await app.request("/presign-part", { method: "POST", diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts index 1ee5669f6c9..f6cd38de24c 100644 --- a/apps/web/app/api/mobile/[...route]/route.ts +++ b/apps/web/app/api/mobile/[...route]/route.ts @@ -83,6 +83,7 @@ import { resolveLinkAccessWrite, } from "@/lib/link-access"; import { importLoomVideoForOwner } from "@/lib/loom-csv-import"; +import { toStoredUploadContentType } from "@/lib/media-processing-policy"; import { mobileUserAgent, prepareMobileEvents } from "@/lib/mobile-events"; import { pushSessionHash } from "@/lib/mobile-push"; import { @@ -3426,11 +3427,12 @@ const createUpload = Effect.fn("Mobile.createUpload")(function* ( }, ); const rawFileKey = `${user.id}/${videoId}/raw-upload.${getFileExtension(input)}`; + const storedContentType = toStoredUploadContentType(input.contentType); const upload = yield* writable.access.createUploadTarget(rawFileKey, { - contentType: input.contentType, + contentType: storedContentType, method: "put", fields: { - "Content-Type": input.contentType, + "Content-Type": storedContentType, "x-amz-meta-userid": user.id, "x-amz-meta-source": "cap-mobile-ios", }, diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts index d3542bca119..958b0d57328 100644 --- a/apps/web/app/api/upload/[...route]/multipart.ts +++ b/apps/web/app/api/upload/[...route]/multipart.ts @@ -31,6 +31,8 @@ import { getMediaProcessingRejection, isNonMediaRawUploadKey, nonMediaUploadMessage, + toCompletedUploadContentType, + toStoredUploadContentType, } from "@/lib/media-processing-policy"; import { queueVideoTranscription, @@ -136,7 +138,7 @@ app.post( }); const outputKey = createDesktopReuploadKey(video); const result = yield* bucket.multipart.create(outputKey, { - ContentType: contentType || "video/mp4", + ContentType: toStoredUploadContentType(contentType || "video/mp4"), CacheControl: "public, max-age=31536000, immutable", Metadata: { userId: user.id, source: "cap-desktop-reupload" }, }); @@ -239,7 +241,9 @@ app.post( const [video] = maybeVideo.value; const [bucket] = yield* Storage.getAccessForVideo(video); - const finalContentType = contentType || "video/mp4"; + const finalContentType = toStoredUploadContentType( + contentType || "video/mp4", + ); console.log( `Creating multipart upload in bucket: ${bucket.bucketName}, content-type: ${finalContentType}, key: ${fileKey}`, ); @@ -797,6 +801,7 @@ app.post( ); console.log(`Complete response: ${JSON.stringify(result, null, 2)}`); + let storedContentType: string | undefined; yield* bucket.headObject(fileKey).pipe( Effect.tap((head) => isRawRecorderUpload(subpath) && @@ -818,11 +823,12 @@ app.post( ) : Effect.void, ), - Effect.tap((headResult) => - Effect.log( + Effect.tap((headResult) => { + storedContentType = headResult.ContentType; + return Effect.log( `Object verification successful: ContentType=${headResult.ContentType}, ContentLength=${headResult.ContentLength}`, - ), - ), + ); + }), Effect.retry({ times: 3, schedule: Schedule.exponential("50 millis"), @@ -894,7 +900,10 @@ app.post( yield* bucket .copyObject(`${bucket.bucketName}/${fileKey}`, fileKey, { - ContentType: "video/mp4", + ContentType: toCompletedUploadContentType( + fileKey, + storedContentType, + ), MetadataDirective: "REPLACE", ...(result.ETag ? { CopySourceIfMatch: result.ETag } : {}), }) diff --git a/apps/web/lib/media-processing-policy.ts b/apps/web/lib/media-processing-policy.ts index e3481e935df..d3708a34971 100644 --- a/apps/web/lib/media-processing-policy.ts +++ b/apps/web/lib/media-processing-policy.ts @@ -68,6 +68,43 @@ export function isNonMediaRawUploadKey(fileKey: string): boolean { return extension !== null && NON_MEDIA_UPLOAD_EXTENSIONS.has(extension); } +const STORED_IMAGE_UPLOAD_CONTENT_TYPES = new Set([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp", +]); + +// The media host serves objects with their stored Content-Type, so anything +// other than audio, video or a raster image is stored as a download. +export function toStoredUploadContentType(contentType: string): string { + const essence = contentType.split(";")[0]?.trim().toLowerCase() ?? ""; + if ( + essence.startsWith("video/") || + essence.startsWith("audio/") || + STORED_IMAGE_UPLOAD_CONTENT_TYPES.has(essence) + ) { + return contentType; + } + return "application/octet-stream"; +} + +// Completion rewrites the object's metadata. Keep the plain-download type set +// when the upload started unless the key names a video file. +export function toCompletedUploadContentType( + fileKey: string, + storedContentType: string | undefined, +): string { + const essence = storedContentType?.split(";")[0]?.trim().toLowerCase(); + if ( + essence === "application/octet-stream" && + !isProcessableMediaKey(fileKey) + ) { + return "application/octet-stream"; + } + return "video/mp4"; +} + export function isMediaPolicyProcessingError( error: string | null | undefined, ): error is string { diff --git a/packages/database/auth/request-site.ts b/packages/database/auth/request-site.ts index c9e82a039bc..c72d1c91b5e 100644 --- a/packages/database/auth/request-site.ts +++ b/packages/database/auth/request-site.ts @@ -17,6 +17,14 @@ const parseUrl = (value: string | null | undefined) => { } }; +const getWebUrl = () => { + try { + return parseUrl(serverEnv().WEB_URL); + } catch { + return null; + } +}; + const isOwnOrigin = (origin: URL, request: SiteCheckedRequest) => { const ownHosts = [ request.headers.get("x-forwarded-host")?.split(",")[0]?.trim(), @@ -24,14 +32,17 @@ const isOwnOrigin = (origin: URL, request: SiteCheckedRequest) => { parseUrl(request.url)?.host, ]; if (ownHosts.includes(origin.host)) return true; + return getWebUrl()?.origin === origin.origin; +}; - let webUrl: string | undefined; - try { - webUrl = serverEnv().WEB_URL; - } catch { - return false; - } - return parseUrl(webUrl)?.origin === origin.origin; +const isOwnSiteOrigin = (origin: URL, request: SiteCheckedRequest) => { + if (isOwnOrigin(origin, request)) return true; + const webUrl = getWebUrl(); + if (!webUrl || webUrl.protocol !== origin.protocol) return false; + const counterpart = webUrl.host.startsWith("www.") + ? webUrl.host.slice(4) + : `www.${webUrl.host}`; + return origin.host === counterpart; }; // Callers must only consult this on the cookie-auth path: a successfully @@ -46,7 +57,14 @@ export const isCrossSiteCookieWrite = (request: SiteCheckedRequest) => { // predate fetch metadata and for plain-http self-hosted installs, where // browsers do not send Sec-Fetch-* headers. const fetchSite = request.headers.get("sec-fetch-site"); - if (fetchSite) return fetchSite === "cross-site"; + if (fetchSite === "cross-site") return true; + // same-site also covers every sibling subdomain, so a same-site write must + // come from the app itself or its www counterpart. + if (fetchSite === "same-site") { + const sameSiteOrigin = parseUrl(request.headers.get("origin")); + return !sameSiteOrigin || !isOwnSiteOrigin(sameSiteOrigin, request); + } + if (fetchSite) return false; const origin = request.headers.get("origin"); if (!origin) return false;