Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(exports): let screenshot creators retrieve their export (#69931)

posthog[bot]10d4808d1adb
diff --git a/frontend/src/lib/components/ExportButton/exporter.test.ts b/frontend/src/lib/components/ExportButton/exporter.test.ts
index 1d3601eb5f24..76fa59332e25 100644
--- a/frontend/src/lib/components/ExportButton/exporter.test.ts
+++ b/frontend/src/lib/components/ExportButton/exporter.test.ts
@@ -1,29 +1,68 @@
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
import { ExportedAssetType } from '~/types'
import { downloadExportedAsset } from './exporter'
+const getResponse = jest.fn()
+
jest.mock('lib/api', () => ({
- exports: {
- determineExportUrl: jest.fn((id: number) => `/api/environments/1/exports/${id}/content?download=true`),
+ __esModule: true,
+ default: {
+ getResponse: (...args: any[]) => getResponse(...args),
+ exports: {
+ determineExportUrl: jest.fn((id: number) => `/api/environments/1/exports/${id}/content?download=true`),
+ },
},
}))
+jest.mock('lib/lemon-ui/LemonToast', () => ({
+ lemonToast: { error: jest.fn() },
+}))
+
describe('downloadExportedAsset', () => {
+ let fakeAnchor: HTMLAnchorElement
+ let appendSpy: jest.SpyInstance
+ let removeSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ fakeAnchor = { style: {}, click: jest.fn() } as unknown as HTMLAnchorElement
+ jest.spyOn(document, 'createElement').mockReturnValue(fakeAnchor)
+ appendSpy = jest.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ removeSpy = jest.spyOn(document.body, 'removeChild').mockImplementation((node) => node)
+ })
+
afterEach(() => {
jest.restoreAllMocks()
+ getResponse.mockReset()
+ ;(lemonToast.error as jest.Mock).mockReset()
})
- it('uses anchor navigation instead of fetch to avoid buffering large files in memory', () => {
- const fakeAnchor = { style: {}, click: jest.fn() } as unknown as HTMLAnchorElement
- jest.spyOn(document, 'createElement').mockReturnValue(fakeAnchor)
- const appendSpy = jest.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
- const removeSpy = jest.spyOn(document.body, 'removeChild').mockImplementation((node) => node)
+ it('navigates via anchor once the content endpoint responds successfully', async () => {
+ // Cancelable body so we don't buffer large files in memory before the streaming download.
+ const cancel = jest.fn().mockResolvedValue(undefined)
+ getResponse.mockResolvedValue({ body: { cancel } })
- downloadExportedAsset({ id: 123 } as ExportedAssetType)
+ const result = await downloadExportedAsset({ id: 123 } as ExportedAssetType)
+ expect(result).toBe(true)
+ expect(getResponse).toHaveBeenCalledWith('/api/environments/1/exports/123/content?download=true')
+ expect(cancel).toHaveBeenCalled()
expect((fakeAnchor as any).href).toBe('/api/environments/1/exports/123/content?download=true')
- expect(appendSpy).toHaveBeenCalledWith(fakeAnchor)
expect((fakeAnchor as any).click).toHaveBeenCalled()
+ expect(appendSpy).toHaveBeenCalledWith(fakeAnchor)
expect(removeSpy).toHaveBeenCalledWith(fakeAnchor)
})
+
+ it('shows an error toast and does not navigate when retrieval fails', async () => {
+ // A failed content retrieval (e.g. an access-control 404) must not navigate the tab to the raw
+ // JSON error — that renders as a blank/black page. It should surface a toast instead.
+ getResponse.mockRejectedValue(new Error('Not found.'))
+
+ const result = await downloadExportedAsset({ id: 123 } as ExportedAssetType)
+
+ expect(result).toBe(false)
+ expect((fakeAnchor as any).click).not.toHaveBeenCalled()
+ expect(lemonToast.error).toHaveBeenCalledWith('Export download failed: Not found.')
+ })
})
diff --git a/frontend/src/lib/components/ExportButton/exporter.tsx b/frontend/src/lib/components/ExportButton/exporter.tsx
index ce1e61703da4..57539489e834 100644
--- a/frontend/src/lib/components/ExportButton/exporter.tsx
+++ b/frontend/src/lib/components/ExportButton/exporter.tsx
@@ -1,4 +1,5 @@
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { ExportedAssetType } from '~/types'
@@ -24,14 +25,30 @@ export async function exportedAssetBlob(asset: ExportedAssetType): Promise<Blob>
return await response.blob()
}
-export function downloadExportedAsset(asset: ExportedAssetType): void {
+export async function downloadExportedAsset(asset: ExportedAssetType): Promise<boolean> {
const downloadUrl = api.exports.determineExportUrl(asset.id)
+
+ // Probe the content endpoint before navigating to it. If retrieval fails (e.g. an access-control
+ // 404), the raw JSON error would otherwise render as a blank/black page. api.getResponse throws on
+ // a non-2xx status, so we can surface an error toast and keep the user where they are. We read only
+ // the headers and cancel the body — the anchor navigation below streams the actual download to disk
+ // without buffering large files (e.g. video exports) in memory.
+ try {
+ const response = await api.getResponse(downloadUrl)
+ await response.body?.cancel()
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ lemonToast.error('Export download failed: ' + message)
+ return false
+ }
+
const anchor = document.createElement('a')
anchor.style.display = 'none'
anchor.href = downloadUrl
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
+ return true
}
export type TriggerExportProps = Pick<ExportedAssetType, 'export_format' | 'dashboard' | 'insight' | 'export_context'>
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
index 3c8f5c110667..8d6e3f27a758 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
@@ -19,7 +19,7 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({
}))
jest.mock('./exporter', () => ({
...jest.requireActual('./exporter'),
- downloadExportedAsset: jest.fn(),
+ downloadExportedAsset: jest.fn().mockResolvedValue(true),
}))
const asset = (overrides: Partial<ExportedAssetType> = {}): ExportedAssetType => ({
@@ -180,6 +180,25 @@ describe('exportsLogic', () => {
expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual(freshIds)
})
+ it('does not confirm completion when the content download fails', async () => {
+ // The export toast must not settle as "Export complete!" if retrieval failed — otherwise
+ // the user sees success followed by a broken download (the reported black-screen symptom).
+ jest.mocked(downloadExportedAsset).mockResolvedValueOnce(false)
+ jest.spyOn(api.exports, 'create').mockResolvedValue(
+ asset({ id: 14, export_format: ExporterFormat.PNG, has_content: true })
+ )
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG } })
+ await flush()
+
+ // The export promise rejects instead of resolving to "Export complete!"...
+ const runPromise = jest.mocked(lemonToast.promise).mock.calls[0][0]
+ await expect(runPromise).rejects.toThrow('Export download failed')
+ // ...and the generic failure toast is dismissed, since downloadExportedAsset
+ // already surfaced the specific error.
+ expect(lemonToast.dismiss).toHaveBeenCalled()
+ })
+
it('replaces the failure toast with the upsell survey when the export limit is reached', async () => {
jest.spyOn(api.exports, 'create').mockRejectedValue({
data: { attr: 'export_limit_exceeded', detail: 'You hit the cap' },
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.ts
index 27df1fef3713..1c970216a0fa 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts
@@ -16,6 +16,10 @@ import { cohortsModel } from '~/models/cohortsModel'
import { AnyDataNode } from '~/queries/schema/schema-general'
import { APIErrorType, CohortType, ExportContext, ExportedAssetType, ExporterFormat, LocalExportContext } from '~/types'
+// Sentinel for a synchronous export whose content download failed after creation succeeded —
+// downloadExportedAsset has already shown the specific error toast by the time this is thrown.
+const EXPORT_DOWNLOAD_FAILED = 'Export download failed'
+
const POLL_DELAY_MS = 10000
// Long-running formats (e.g. MP4 session-replay renders) can take 30+ minutes,
// so polling every 10s produces unhelpful timeout noise. Back off when the
@@ -348,7 +352,11 @@ export const exportsLogic = kea<exportsLogicType>([
if (response.has_content) {
// Blocking export already finished in the request — download and confirm.
- downloadExportedAsset(response)
+ // Only celebrate once the content actually downloads; downloadExportedAsset
+ // surfaces its own error toast if retrieval fails (e.g. an access-control 404).
+ if (!(await downloadExportedAsset(response))) {
+ throw new Error(EXPORT_DOWNLOAD_FAILED)
+ }
return 'Export complete!'
}
if (response.exception) {
@@ -374,6 +382,12 @@ export const exportsLogic = kea<exportsLogicType>([
)
} catch (error) {
const apiError = error as { data?: APIErrorType }
+ if (error instanceof Error && error.message === EXPORT_DOWNLOAD_FAILED) {
+ // downloadExportedAsset already surfaced a specific error toast —
+ // drop the generic failure toast so the user isn't told twice.
+ lemonToast.dismiss(exportToastId)
+ return
+ }
// Show a survey when the user reaches the export limit, replacing the
// generic failure toast with the upsell.
if (apiError?.data?.attr === 'export_limit_exceeded') {
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index 56e4f75376e2..68202cf5b86e 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -495,9 +495,15 @@ class ExportedAssetViewSet(
if resource is not None:
if not self.user_access_control.check_access_level_for_object(resource, required_level="viewer"):
raise NotFound()
- elif session_recording_id:
+ elif session_recording_id and instance.created_by_id != self.request.user.id:
# No SessionRecording row — cannot run object-level RBAC; still enforce the team's
- # session_recording resource default so detail/content are not fail-open.
+ # session_recording resource default for other users so detail/content are not fail-open.
+ # The creator is exempt from this fallback only: they necessarily had the access required
+ # to create the export, so retrieval must not be stricter than creation — otherwise a
+ # session_recording default below viewer 404s the very user who just took the screenshot,
+ # surfacing as an "Export complete!" toast followed by a blank error page. Explicit
+ # object-level denies (the branch above) still apply to the creator once a
+ # SessionRecording row exists.
if not self.user_access_control.check_access_level_for_resource(
"session_recording", required_level="viewer"
):
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index 7c8be8c63e1f..0804bbe49742 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -902,6 +902,50 @@ class TestExports(APIBaseTest):
response = self.client.get(url_template.format(team_id=self.team.id, export_id=export.id))
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ @parameterized.expand(
+ [
+ ("retrieve", "/api/projects/{team_id}/exports/{export_id}"),
+ ("content", "/api/projects/{team_id}/exports/{export_id}/content"),
+ ]
+ )
+ def test_creator_can_access_own_session_recording_export_when_row_missing_and_resource_denied(
+ self, _name, url_template
+ ) -> None:
+ """
+ The user who created a session recording export must always be able to retrieve it — retrieval
+ cannot be stricter than creation. Otherwise the create call succeeds (firing an "Export complete!"
+ toast) and the immediate content fetch 404s, rendering as a blank page. This is the mirror of the
+ teammate case above: same denied resource default, but the creator is allowed through.
+ """
+ from posthog.models.organization import OrganizationMembership
+
+ owner = self.user
+ membership = OrganizationMembership.objects.get(user=owner, organization=self.organization)
+
+ export = ExportedAsset.objects.create(
+ team=self.team,
+ export_format="image/png",
+ export_context={"session_recording_id": "no-session-recording-row"},
+ created_by=owner,
+ content=b"png-bytes",
+ )
+
+ self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]
+ self.organization.save()
+
+ AccessControl.objects.create(
+ resource="session_recording",
+ resource_id=None,
+ team=self.team,
+ access_level="none",
+ organization_member=membership,
+ )
+
+ response = self.client.get(url_template.format(team_id=self.team.id, export_id=export.id))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ if "/content" in url_template:
+ self.assertEqual(response.content, b"png-bytes")
+
def test_list_exports_with_session_recording_only_shows_own_matching_exports(self) -> None:
from posthog.session_recordings.models.session_recording import SessionRecording