Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/platform/auth/session/useSessionCookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ vi.mock('@/scripts/api', () => ({
}
}))

const mockReportError = vi.fn()
vi.mock('@/platform/telemetry/reportError', () => ({
reportError: mockReportError
}))

describe('useSessionCookie', () => {
beforeEach(() => {
vi.resetModules()
Expand Down Expand Up @@ -122,6 +127,24 @@ describe('useSessionCookie', () => {
)
})

it('reports a swallowed createSession failure as session_cookie_creation_failure', async () => {
mockGetIdToken.mockResolvedValue('firebase-id-token')
vi.mocked(globalThis.fetch).mockResolvedValue(
new Response(JSON.stringify({ message: 'session denied' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
})
)
const { useSessionCookie } =
await import('@/platform/auth/session/useSessionCookie')

await useSessionCookie().createSession()

expect(mockReportError).toHaveBeenCalledExactlyOnceWith(expect.any(Error), {
errorType: 'session_cookie_creation_failure'
})
})

it('serializes strict session creation after the previous user response', async () => {
mockGetIdToken.mockImplementation(() =>
Promise.resolve(`firebase-${mockAuthState.currentUser?.uid}`)
Expand Down
4 changes: 4 additions & 0 deletions src/platform/auth/session/useSessionCookie.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isCloud } from '@/platform/distribution/types'
import { reportError } from '@/platform/telemetry/reportError'
import { api } from '@/scripts/api'
import { useAuthStore } from '@/stores/authStore'

Expand Down Expand Up @@ -123,6 +124,9 @@ export const useSessionCookie = () => {
try {
await establishSession(currentOwnerUidOrThrow(), true)
} catch (error) {
// The session cookie is the only credential <img>/media loads carry, so
// a swallowed creation failure means images break with no other signal.
reportError(error, { errorType: 'session_cookie_creation_failure' })
console.warn('Failed to create session cookie:', error)
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/platform/telemetry/TelemetryRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
HelpCenterClosedMetadata,
HelpCenterOpenedMetadata,
HelpResourceClickedMetadata,
ImageLoadFailureMetadata,
NamedValuesShadowDiffMismatchMetadata,
NamedValuesShadowDiffSummaryMetadata,
NodeAddedMetadata,
Expand Down Expand Up @@ -49,6 +50,7 @@ import type {
TemplateLibraryMetadata,
TemplateMetadata,
UiButtonClickMetadata,
UnifiedAuthRefreshMetadata,
UnifiedAuthRetryMetadata,
WidgetFavoriteToggledMetadata,
WorkflowCreatedMetadata,
Expand Down Expand Up @@ -99,6 +101,14 @@ export class TelemetryRegistry implements TelemetryDispatcher {
this.dispatch((provider) => provider.trackUnifiedAuthRetry?.(metadata))
}

trackUnifiedAuthRefresh(metadata: UnifiedAuthRefreshMetadata): void {
this.dispatch((provider) => provider.trackUnifiedAuthRefresh?.(metadata))
}

trackImageLoadFailed(metadata: ImageLoadFailureMetadata): void {
this.dispatch((provider) => provider.trackImageLoadFailed?.(metadata))
}

trackUserLoggedIn(): void {
this.dispatch((provider) => provider.trackUserLoggedIn?.())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,29 @@ describe('DatadogRumTelemetryProvider', () => {
)
})

it('records proactive unified refresh lifecycle outcomes', () => {
new DatadogRumTelemetryProvider().trackUnifiedAuthRefresh({
outcome: 'retries_exhausted',
retry_count: 3
})

expect(addAction).toHaveBeenCalledExactlyOnceWith(
TelemetryEvents.UNIFIED_AUTH_REFRESH_FAILED,
{ outcome: 'retries_exhausted', retry_count: 3 }
)
})

it('records image load failures by source', () => {
new DatadogRumTelemetryProvider().trackImageLoadFailed({
source: 'node_image_preview'
})

expect(addAction).toHaveBeenCalledExactlyOnceWith(
TelemetryEvents.IMAGE_LOAD_FAILED,
{ source: 'node_image_preview' }
)
})

it('records the same canonical billing name and context as PostHog', () => {
const event: BillingTelemetryEvent = {
operation: 'operation',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { datadogRum } from '@datadog/browser-rum'
import type {
BillingTelemetryEvent,
ExecutionOutcomeMetadata,
ImageLoadFailureMetadata,
TelemetryProvider,
UnifiedAuthRefreshMetadata,
UnifiedAuthRetryMetadata
} from '../../types'
import {
Expand All @@ -22,6 +24,19 @@ export class DatadogRumTelemetryProvider implements TelemetryProvider {
)
}

trackUnifiedAuthRefresh(metadata: UnifiedAuthRefreshMetadata): void {
datadogRum.addAction(
metadata.outcome === 'succeeded'
? TelemetryEvents.UNIFIED_AUTH_REFRESH_SUCCEEDED
: TelemetryEvents.UNIFIED_AUTH_REFRESH_FAILED,
metadata
)
}

trackImageLoadFailed(metadata: ImageLoadFailureMetadata): void {
datadogRum.addAction(TelemetryEvents.IMAGE_LOAD_FAILED, metadata)
}

trackBillingEvent(event: BillingTelemetryEvent): void {
datadogRum.addAction(
getBillingTelemetryEventName(event),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,46 @@ describe('PostHogTelemetryProvider', () => {
)
})

it('captures unified auth retry and refresh outcomes', async () => {
const provider = createProvider()
await vi.dynamicImportSettled()

provider.trackUnifiedAuthRetry({
transport: 'ws',
outcome: 'failed',
failure_reason: 'token_unavailable'
})
provider.trackUnifiedAuthRefresh({
outcome: 'retry_scheduled',
retry_count: 1
})

expect(hoisted.mockCapture).toHaveBeenCalledWith(
TelemetryEvents.UNIFIED_AUTH_RETRY_FAILED,
{
transport: 'ws',
outcome: 'failed',
failure_reason: 'token_unavailable'
}
)
expect(hoisted.mockCapture).toHaveBeenCalledWith(
TelemetryEvents.UNIFIED_AUTH_REFRESH_FAILED,
{ outcome: 'retry_scheduled', retry_count: 1 }
)
})

it('captures image load failures', async () => {
const provider = createProvider()
await vi.dynamicImportSettled()

provider.trackImageLoadFailed({ source: 'node_image_preview' })

expect(hoisted.mockCapture).toHaveBeenCalledWith(
TelemetryEvents.IMAGE_LOAD_FAILED,
{ source: 'node_image_preview' }
)
})

it('captures enriched execution starts with client attribution', async () => {
const provider = createProvider()
await vi.dynamicImportSettled()
Expand Down
25 changes: 25 additions & 0 deletions src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import type {
AddCreditsClickMetadata,
AuthErrorMetadata,
AuthMetadata,
ImageLoadFailureMetadata,
UnifiedAuthRefreshMetadata,
UnifiedAuthRetryMetadata,
BeginCheckoutMetadata,
BillingTelemetryEvent,
DefaultViewSetMetadata,
Expand Down Expand Up @@ -378,6 +381,28 @@ export class PostHogTelemetryProvider implements TelemetryProvider {
this.trackEvent(TelemetryEvents.USER_AUTH_FAILED, metadata)
}

trackUnifiedAuthRetry(metadata: UnifiedAuthRetryMetadata): void {
this.trackEvent(
metadata.outcome === 'succeeded'
? TelemetryEvents.UNIFIED_AUTH_RETRY_SUCCEEDED
: TelemetryEvents.UNIFIED_AUTH_RETRY_FAILED,
metadata
)
}

trackUnifiedAuthRefresh(metadata: UnifiedAuthRefreshMetadata): void {
this.trackEvent(
metadata.outcome === 'succeeded'
? TelemetryEvents.UNIFIED_AUTH_REFRESH_SUCCEEDED
: TelemetryEvents.UNIFIED_AUTH_REFRESH_FAILED,
metadata
)
}

trackImageLoadFailed(metadata: ImageLoadFailureMetadata): void {
this.trackEvent(TelemetryEvents.IMAGE_LOAD_FAILED, metadata)
}

trackUserLoggedIn(): void {
this.trackEvent(TelemetryEvents.USER_LOGGED_IN)
}
Expand Down
30 changes: 29 additions & 1 deletion src/platform/telemetry/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,35 @@ export type UnifiedAuthRetryFailureReason =
| 'remint_failed'
| 'retry_rejected'
| 'retry_request_failed'
| 'token_unavailable'

export interface UnifiedAuthRetryMetadata {
transport: 'axios' | 'fetch'
transport: 'axios' | 'fetch' | 'ws'
outcome: 'succeeded' | 'failed'
final_status?: number
failure_reason?: UnifiedAuthRetryFailureReason
}

export type UnifiedAuthRefreshOutcome =
| 'succeeded'
| 'retry_scheduled'
| 'retries_exhausted'
| 'permanent_failure'

/**
* Outcome of one proactive unified Cloud-JWT refresh attempt. This lifecycle
* drives session-cookie rotation, so a dead refresh chain breaks every
* cookie-authenticated <img>/media load (FE-1595).
*/
export interface UnifiedAuthRefreshMetadata {
outcome: UnifiedAuthRefreshOutcome
retry_count?: number
}

export interface ImageLoadFailureMetadata {
source: 'node_image_preview'
}

/**
* Survey field ids mapped to answers. Fields are backend-overridable, so all
* are optional.
Expand Down Expand Up @@ -921,6 +942,8 @@ export interface TelemetryProvider {
trackAuth?(metadata: AuthMetadata): void
trackAuthFailed?(metadata: AuthErrorMetadata): void
trackUnifiedAuthRetry?(metadata: UnifiedAuthRetryMetadata): void
trackUnifiedAuthRefresh?(metadata: UnifiedAuthRefreshMetadata): void
trackImageLoadFailed?(metadata: ImageLoadFailureMetadata): void
trackUserLoggedIn?(): void

// Subscription flow events
Expand Down Expand Up @@ -1066,6 +1089,9 @@ export const TelemetryEvents = {
USER_LOGGED_IN: 'app:user_logged_in',
UNIFIED_AUTH_RETRY_SUCCEEDED: 'auth.unified.request_retry.succeeded',
UNIFIED_AUTH_RETRY_FAILED: 'auth.unified.request_retry.failed',
UNIFIED_AUTH_REFRESH_SUCCEEDED: 'auth.unified.refresh.succeeded',
UNIFIED_AUTH_REFRESH_FAILED: 'auth.unified.refresh.failed',
IMAGE_LOAD_FAILED: 'app:image_load_failed',

// Subscription Flow
RUN_BUTTON_CLICKED: 'app:run_button_click',
Expand Down Expand Up @@ -1245,6 +1271,8 @@ export type TelemetryEventProperties =
| OnboardingTourMetadata
| AuthErrorMetadata
| UnifiedAuthRetryMetadata
| UnifiedAuthRefreshMetadata
| ImageLoadFailureMetadata
| SurveyResponses
| TemplateMetadata
| ExecutionContext
Expand Down
22 changes: 22 additions & 0 deletions src/platform/workspace/stores/useWorkspaceAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants'

const mockGetIdToken = vi.fn()
const mockNotifyTokenRefreshed = vi.fn()
const mockTrackUnifiedAuthRefresh = vi.fn()
const mockToastAdd = vi.fn()
const mockEnsureSessionCookie = vi.fn()
const mockCurrentUser = vi.hoisted((): { value: { uid: string } | null } => ({
Expand Down Expand Up @@ -58,6 +59,12 @@ vi.mock('@/platform/auth/session/useSessionCookie', () => ({
})
}))

vi.mock('@/platform/telemetry', () => ({
useTelemetry: () => ({
trackUnifiedAuthRefresh: mockTrackUnifiedAuthRefresh
})
}))

vi.mock('@/platform/updates/common/toastStore', () => ({
useToastStore: () => ({
add: mockToastAdd
Expand Down Expand Up @@ -2627,6 +2634,10 @@ describe('useWorkspaceAuthStore', () => {
expect(mockToastAdd).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'error', detail: detailKey })
)
expect(mockTrackUnifiedAuthRefresh).toHaveBeenLastCalledWith({
outcome: 'permanent_failure',
retry_count: 0
})
expect(unifiedToken.value).toBeNull()
}
)
Expand Down Expand Up @@ -2756,11 +2767,18 @@ describe('useWorkspaceAuthStore', () => {
await vi.advanceTimersByTimeAsync(refreshDelay)
expect(mockFetch).toHaveBeenCalledTimes(2)
expect(mockNotifyTokenRefreshed).not.toHaveBeenCalled()
expect(mockTrackUnifiedAuthRefresh).toHaveBeenLastCalledWith({
outcome: 'retry_scheduled',
retry_count: 1
})

await vi.advanceTimersByTimeAsync(5000)

expect(mockFetch).toHaveBeenCalledTimes(3)
expect(mockNotifyTokenRefreshed).toHaveBeenCalledTimes(1)
expect(mockTrackUnifiedAuthRefresh).toHaveBeenLastCalledWith({
outcome: 'succeeded'
})
expect(unifiedToken.value).toBe('unified-token-1')

// The successful retry re-arms the normal proactive schedule.
Expand Down Expand Up @@ -2805,6 +2823,10 @@ describe('useWorkspaceAuthStore', () => {

expect(mockFetch).toHaveBeenCalledTimes(5)
expect(mockToastAdd).not.toHaveBeenCalled()
expect(mockTrackUnifiedAuthRefresh).toHaveBeenLastCalledWith({
outcome: 'retries_exhausted',
retry_count: 3
})
expect(unifiedToken.value).toBe('unified-token-1')
})

Expand Down
Loading
Loading