From c1bbd35d2335b248e38cdb9265baf8c43a69d614 Mon Sep 17 00:00:00 2001 From: Dante Date: Fri, 16 Oct 2026 01:41:49 +0000 Subject: [PATCH] ING-212 fix(auth): keep asset redirects off credentialed CORS (#21145) ## Summary Cloud asset downloads now keep the session cookie on the same-origin ingest request without requiring credentialed CORS after ingest redirects to a signed storage URL. Workspace/CSRF headers and retries are preserved; genuinely cross-origin ingest requests retain the authorizer's `include` policy. Fixes https://linear.app/comfyorg/issue/ING-212/bug-cloud-completed-video-download-fails-with-cors-redirect-error **Root cause / why now:** the existing download path already used `api.fetchApi` to preserve workspace authentication (PR 18421). PR 18716 introduced `credentials: 'include'` for session authorization, and PR 18875 routed Cloud ingest requests through it. With `unified_web_session` enabled, `/api/assets/{id}/content` still returns a 302 to GCS, but the followed fetch remains credentialed. GCS's XML API does not support `Access-Control-Allow-Credentials`, so the browser rejects the bytes. This was a latent flag-on incompatibility, not a newly changed download button: [Oct 15 QA records the 100% ramp at 10:04 EDT](https://comfy-organization.slack.com/archives/C0932CGKT5K/p1792075311777139), and a [later update explicitly confirms 100% in production](https://comfy-organization.slack.com/archives/C0C6V3NUXPU/p1792093817831899). The previous tests checked authenticated requests against fetch doubles without exercising a storage redirect in a browser. **How:** select `same-origin` at the Cloud session transport boundary when the request URL resolves to the page's origin. Keep the shared account-core authorizer unchanged for clients that need cookies across origins. Passing a download-only option to `fetchApi` would not fix this because the transport overwrites it with the authorizer's credentials. ## Verification - RED: with the original source, the new actual-app browser test fails to download and Chromium logs the missing `Access-Control-Allow-Credentials` error with credentials mode `include`. Restoring the fix makes it pass. - Browser: 2 passed, personal and team workspaces. Actual Media Assets context-menu Download, authenticated ingest 302 double, separate real HTTP storage server without ACAC, saved filename and byte comparison. A cookie seeded for the storage host is not sent; the first hop retains the session cookie and selected workspace. - Unit: 364 passed in the 5 affected session/auth, asset-action and download-utility suites. The URL table covers relative, absolute same-origin and remote ingest requests. Existing flag-off, CSRF retry and workspace-denial coverage passes. - App + browser typechecks, touched-file oxlint/ESLint/oxfmt and knip passed. Commit and push hooks run without bypasses. - Browser proof uses the repository-pinned Chromium 153. System Chrome 155 aborts Playwright-intercepted redirects before reaching the storage server; it is not used as a passing regression result. ### AS IS / TO BE AS IS: [production report with the PNG screenshot](https://comfy-organization.slack.com/archives/C0A4XMHANP3/p1792109025101229). TO BE: actual-app Download regressions pass for personal/team workspaces with this PR. Live production-storage check also passed from `https://cloud.comfy.org`: a DevTools request using the PR's `same-origin` credentials policy and workspace/client headers followed the real authenticated asset-content redirect to `storage.googleapis.com`, returned HTTP 200 (`image/png`, 2,620,563 bytes), and saved `Nano_Banana_2_00002_.png` (1024 x 1024; SHA-256 `54e4dc472f12a02c702ef71f0853490132e116b84475a9480ab0b03b3e3a9971`). This validates the production request policy, not a deployed PR bundle or production UI rollout. The local PR frontend cannot complete that live GCS check because the production bucket does not allow the localhost origin; an OPTIONS probe returned ACAO for Cloud but none for localhost. No signed URL or credentials are included in the evidence. Follow-up validation: 243 affected session/remote-widget unit tests and both personal/team browser regressions passed. CI exposed an additional remote-widget `include` expectation, now aligned with the same-origin policy. The fixture also handles a missing cookie header via `Headers.get()` before returning its intended 401 (CodeRabbit feedback). ### Plan position | Item | Ticket | PR | Status | | --- | --- | --- | --- | | Session authorization policy | FE-2895 | [PR 18716](https://github.com/Comfy-Org/ComfyUI_frontend/pull/18716) | Merged | | Cloud ingest on web session | FE-2904 | [PR 18875](https://github.com/Comfy-Org/ComfyUI_frontend/pull/18875) | Merged | | **Storage redirect compatibility + browser regression** | **ING-212** | **This PR** | **Ready for review** | ```mermaid flowchart LR auth["FE-2895 / PR 18716"] --> ingest["FE-2904 / PR 18875"] ingest --> fix["ING-212 / this PR"] classDef current fill:#ffe08a,stroke:#b8860b,stroke-width:3px,color:#000 class fix current ``` --------- Co-authored-by: GitHub Action --- .../fixtures/assetDownloadRedirectFixture.ts | 115 ++++++++++++++++++ .../workspace/assetDownloadRedirect.spec.ts | 47 +++++++ .../auth/session/webSessionFetch.test.ts | 63 ++++++++++ src/platform/auth/session/webSessionFetch.ts | 9 +- src/platform/auth/webSessionFlagOn.test.ts | 4 +- .../useRemoteWidget.webSession.test.ts | 2 +- 6 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 browser_tests/fixtures/assetDownloadRedirectFixture.ts create mode 100644 browser_tests/tests/workspace/assetDownloadRedirect.spec.ts create mode 100644 src/platform/auth/session/webSessionFetch.test.ts diff --git a/browser_tests/fixtures/assetDownloadRedirectFixture.ts b/browser_tests/fixtures/assetDownloadRedirectFixture.ts new file mode 100644 index 00000000000..c36f54942cb --- /dev/null +++ b/browser_tests/fixtures/assetDownloadRedirectFixture.ts @@ -0,0 +1,115 @@ +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' + +import type { ListAssetsResponse } from '@comfyorg/ingest-types' + +import { STABLE_OUTPUT } from '@e2e/fixtures/data/assetFixtures' +import { WEB_SESSION_COOKIE } from '@e2e/fixtures/data/webSession' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { assetPath } from '@e2e/fixtures/utils/paths' +import { mockViewFiles } from '@e2e/fixtures/utils/viewFileMocks' +import { webSessionTest } from '@e2e/fixtures/webSessionFixture' + +interface AssetRedirect { + bytes: Buffer + requestHeaders: Record[] + storageCookies: (string | undefined)[] +} + +export const assetDownloadRedirectTest = webSessionTest.extend<{ + assetRedirect: AssetRedirect +}>({ + assetRedirect: [ + async ({ page, networkPolicy, initialLocalStorage }, use) => { + const bytes = await readFile(assetPath('test_upload_image.png')) + const requestHeaders: Record[] = [] + const storageCookies: (string | undefined)[] = [] + const storage = createServer((request, response) => { + response.setHeader( + 'Access-Control-Allow-Origin', + request.headers.origin ?? '*' + ) + response.setHeader('Access-Control-Allow-Methods', 'GET') + response.setHeader( + 'Access-Control-Allow-Headers', + request.headers['access-control-request-headers'] ?? '*' + ) + if (request.method === 'OPTIONS') { + response.writeHead(204).end() + return + } + storageCookies.push(request.headers.cookie) + response.writeHead(200, { 'Content-Type': 'image/png' }).end(bytes) + }) + await new Promise((resolve) => + storage.listen(0, '127.0.0.1', resolve) + ) + const address = storage.address() + if (!address || typeof address === 'string') + throw new Error('TCP address required') + const storageOrigin = `http://127.0.0.1:${address.port}` + networkPolicy.origins.add(storageOrigin) + + try { + await page.context().addCookies([ + { + name: 'storage_session', + value: 'storage-only', + url: storageOrigin + } + ]) + await mockViewFiles(page, { [STABLE_OUTPUT.name]: {} }) + await page.route(/\/api\/assets(?:\?.*)?$/, (route) => { + const params = new URL(route.request().url()).searchParams + const assets = params.get('tags_any')?.includes('output') + ? [ + { + ...STABLE_OUTPUT, + preview_url: `/api/view?filename=${STABLE_OUTPUT.name}&type=output` + } + ] + : [] + return route.fulfill( + jsonRoute({ + assets, + total: assets.length, + has_more: false + } satisfies ListAssetsResponse) + ) + }) + await page.route( + `**/api/assets/${STABLE_OUTPUT.id}/content**`, + async (route) => { + const headers = await route.request().allHeaders() + const cookie = new Headers(headers).get('cookie') + requestHeaders.push(headers) + const workspace = + initialLocalStorage['Comfy.Workspace.LastWorkspaceId'] ?? + 'ws-personal' + if ( + !cookie?.includes( + `${WEB_SESSION_COOKIE.name}=${WEB_SESSION_COOKIE.value}` + ) + ) { + await route.fulfill({ status: 401 }) + return + } + if (headers['x-comfy-workspace-id'] !== workspace) { + await route.fulfill({ status: 404 }) + return + } + await route.fulfill({ + status: 302, + headers: { Location: `${storageOrigin}/signed.png` } + }) + } + ) + await use({ bytes, requestHeaders, storageCookies }) + } finally { + networkPolicy.origins.delete(storageOrigin) + await new Promise((resolve) => storage.close(() => resolve())) + } + }, + { auto: true } + ] +}) diff --git a/browser_tests/tests/workspace/assetDownloadRedirect.spec.ts b/browser_tests/tests/workspace/assetDownloadRedirect.spec.ts new file mode 100644 index 00000000000..439e521006d --- /dev/null +++ b/browser_tests/tests/workspace/assetDownloadRedirect.spec.ts @@ -0,0 +1,47 @@ +import { readFile } from 'node:fs/promises' + +import { expect } from '@playwright/test' + +import { assetDownloadRedirectTest as test } from '@e2e/fixtures/assetDownloadRedirectFixture' +import { STABLE_OUTPUT } from '@e2e/fixtures/data/assetFixtures' +import { WEB_SESSION_COOKIE } from '@e2e/fixtures/data/webSession' + +test.use({ + firebaseLogin: false, + serverFeatures: { assets: true, unified_cloud_auth: true } +}) + +for (const workspace of ['ws-personal', 'ws-team']) { + test.describe(`Asset download in ${workspace}`, { tag: '@cloud' }, () => { + test.use({ + initialLocalStorage: { 'Comfy.Workspace.LastWorkspaceId': workspace } + }) + + test('downloads through a storage redirect without credentialed CORS', async ({ + comfyPage, + assetRedirect + }, testInfo) => { + const tab = comfyPage.menu.assetsTab + await tab.open() + await tab.waitForAssets(1) + await tab.rightClickAsset('ComfyUI_00001_') + const downloadPromise = comfyPage.page.waitForEvent('download') + await comfyPage.contextMenu.clickMenuItemExact('Download') + const download = await downloadPromise + const file = testInfo.outputPath(STABLE_OUTPUT.name) + await download.saveAs(file) + + expect(download.suggestedFilename()).toBe(STABLE_OUTPUT.name) + expect(await readFile(file)).toEqual(assetRedirect.bytes) + expect(assetRedirect.storageCookies).toEqual([undefined]) + expect(assetRedirect.requestHeaders).toEqual([ + expect.objectContaining({ + cookie: expect.stringContaining( + `${WEB_SESSION_COOKIE.name}=${WEB_SESSION_COOKIE.value}` + ), + 'x-comfy-workspace-id': workspace + }) + ]) + }) + }) +} diff --git a/src/platform/auth/session/webSessionFetch.test.ts b/src/platform/auth/session/webSessionFetch.test.ts new file mode 100644 index 00000000000..6c1a98ec65d --- /dev/null +++ b/src/platform/auth/session/webSessionFetch.test.ts @@ -0,0 +1,63 @@ +import { + COMFY_CLIENT, + createRequestAuthorizer +} from '@comfyorg/account-core/requestAuth' +import { describe, expect, it, vi } from 'vitest' + +import { fetchOnWebSession } from './webSessionFetch' +import type { WebSessionRequestScope } from './webSessionFetch' + +describe('web-session request credentials', () => { + it.for([ + { + name: 'relative ingest URL', + url: '/api/assets/image/content', + credentials: 'same-origin' + }, + { + name: 'absolute same-origin URL', + url: new URL('/api/assets/image/content', location.href).href, + credentials: 'same-origin' + }, + { + name: 'remote ingest URL', + url: 'https://testcloud.comfy.org/api/assets/image/content', + credentials: 'include' + } + ] as const)( + 'keeps cookie authentication for $name', + async ({ url, credentials }) => { + const send = vi.mocked(fetch).mockResolvedValue(new Response('asset')) + const scope: WebSessionRequestScope = { + epoch: 1, + workspaceId: 'team-workspace', + session: { + user: { id: 'user', email: 'user@example.com', emailVerified: true }, + csrfToken: 'csrf-token', + expiresAt: Number.MAX_SAFE_INTEGER, + absoluteExpiresAt: Number.MAX_SAFE_INTEGER + } + } + + await fetchOnWebSession(url, { method: 'POST', body: 'asset' }, scope, { + authorize: createRequestAuthorizer({ + getWorkspaceToken: async () => 'unused' + }), + refresh: async () => undefined, + workspaceDenied: vi.fn(), + ssoRequired: vi.fn() + }) + + expect(send).toHaveBeenCalledWith(url, { + method: 'POST', + body: 'asset', + credentials, + headers: new Headers({ + 'X-Comfy-Client': COMFY_CLIENT, + 'X-Comfy-Workspace-ID': 'team-workspace', + 'X-CSRF-Token': 'csrf-token' + }) + }) + } + ) +}) diff --git a/src/platform/auth/session/webSessionFetch.ts b/src/platform/auth/session/webSessionFetch.ts index 22f0d1346e6..6b2fa7f86d4 100644 --- a/src/platform/auth/session/webSessionFetch.ts +++ b/src/platform/auth/session/webSessionFetch.ts @@ -71,7 +71,14 @@ export async function fetchOnWebSession( ) const merged = new Headers(init.headers) for (const [name, value] of Object.entries(headers)) merged.set(name, value) - return fetch(url, { ...init, headers: merged, credentials }) + return fetch(url, { + ...init, + headers: merged, + credentials: + new URL(url, location.href).origin === location.origin + ? 'same-origin' + : credentials + }) } const response = await send(scope) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index dd04946e99e..1e9f072043e 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -859,7 +859,7 @@ const sessionRequest = ( method, path, headers: { 'x-comfy-client': COMFY_CLIENT, ...headers }, - credentials: 'include' + credentials: 'same-origin' }) const LISTED = { @@ -2778,7 +2778,7 @@ describe.for([{ unified: false }, { unified: true }])( await vi.advanceTimersByTimeAsync(60_000) await response expect(queueReads().map(([, init]) => init?.credentials)).toEqual([ - 'include' + 'same-origin' ]) }) diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts index a184328272c..16252c56df1 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts @@ -136,7 +136,7 @@ const sessionRequest = (path: string, workspace: string): IngestRequest => ({ method: 'GET', path, headers: { 'x-comfy-client': COMFY_CLIENT, ...workspaceHeader(workspace) }, - credentials: 'include' + credentials: 'same-origin' }) describe('remote widgets on the shared web session', () => {