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
61 changes: 61 additions & 0 deletions src/components/scripts/sentry/__tests__/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,23 @@ const createConsentRateLimitHttpErrorEvent = (): Parameters<typeof beforeSendHan
},
}) as unknown as Parameters<typeof beforeSendHandler>[0]

const createConsentCheckpointHttpErrorEvent = (): Parameters<typeof beforeSendHandler>[0] =>
({
type: 'error',
request: { url: 'https://www.webstackbuilders.com/_actions/gdpr.consentCreate' },
exception: {
values: [
{
value: 'HTTP Client Error with status code: 403',
mechanism: {
type: 'auto.http.client.fetch',
handled: false,
},
},
],
},
}) as unknown as Parameters<typeof beforeSendHandler>[0]

const createDownloadsSubmitHttpErrorEvent = (): Parameters<typeof beforeSendHandler>[0] =>
({
type: 'error',
Expand Down Expand Up @@ -126,6 +143,28 @@ const createConsentLogRetryErrorEvent = (): Parameters<typeof beforeSendHandler>
},
}) as unknown as Parameters<typeof beforeSendHandler>[0]

const createConsentCheckpointClientErrorEvent = (): Parameters<typeof beforeSendHandler>[0] =>
({
type: 'error',
message: '<!DOCTYPE html><title>Vercel Security Checkpoint</title>',
request: { url: 'https://www.webstackbuilders.com/contact' },
tags: {
scriptName: 'cookieConsent',
operation: 'logConsentToAPI',
},
exception: {
values: [
{
value: '<!DOCTYPE html><title>Vercel Security Checkpoint</title>',
mechanism: {
type: 'generic',
handled: true,
},
},
],
},
}) as unknown as Parameters<typeof beforeSendHandler>[0]

const createHint = (): Parameters<typeof beforeSendHandler>[1] =>
({}) as Parameters<typeof beforeSendHandler>[1]

Expand Down Expand Up @@ -186,6 +225,17 @@ describe('sentry helpers', () => {
expect(result).toBeNull()
})

it('drops handled consent checkpoint http client failures', () => {
isProdMock.mockReturnValue(true)
getConsentSnapshotMock.mockReturnValue({ analytics: true })

const event = createConsentCheckpointHttpErrorEvent()

const result = beforeSendHandler(event, createHint())

expect(result).toBeNull()
})

it('drops handled downloads action http client failures', () => {
isProdMock.mockReturnValue(true)
getConsentSnapshotMock.mockReturnValue({ analytics: true })
Expand Down Expand Up @@ -219,6 +269,17 @@ describe('sentry helpers', () => {
expect(result).toBeNull()
})

it('drops handled consent checkpoint client errors', () => {
isProdMock.mockReturnValue(true)
getConsentSnapshotMock.mockReturnValue({ analytics: true })

const event = createConsentCheckpointClientErrorEvent()

const result = beforeSendHandler(event, createHint())

expect(result).toBeNull()
})

it('scrubs PII when analytics consent is missing and preserves safe breadcrumbs', () => {
isProdMock.mockReturnValue(true)
getConsentSnapshotMock.mockReturnValue({ analytics: false })
Expand Down
34 changes: 28 additions & 6 deletions src/components/scripts/sentry/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,19 @@ const isHandledContactSubmitHttpError = (event: Parameters<BeforeSendHandler>[0]
)
}

const isHandledConsentRateLimitHttpError = (event: Parameters<BeforeSendHandler>[0]): boolean => {
const isHandledConsentHttpError = (event: Parameters<BeforeSendHandler>[0]): boolean => {
const requestUrl = event.request?.url
const exception = event.exception?.values?.[0]
const mechanismType = exception?.mechanism?.type
const errorMessage = exception?.value ?? event.message ?? ''
const statusCodeMatch = typeof errorMessage === 'string' ? errorMessage.match(/status code:\s*(\d{3})/i) : null
const statusCode = statusCodeMatch?.[1] ? Number(statusCodeMatch[1]) : undefined

return (
typeof requestUrl === 'string' &&
isConsentActionRequest(requestUrl) &&
mechanismType === 'auto.http.client.fetch' &&
typeof errorMessage === 'string' &&
errorMessage.includes('HTTP Client Error with status code: 429')
(statusCode === 403 || statusCode === 429)
)
}

Expand Down Expand Up @@ -87,6 +88,20 @@ const isHandledConsentLogRetryError = (event: Parameters<BeforeSendHandler>[0]):
)
}

const isHandledConsentCheckpointClientError = (event: Parameters<BeforeSendHandler>[0]): boolean => {
const errorMessage = event.exception?.values?.[0]?.value ?? event.message ?? ''
const tags = event.tags ?? {}

return (
tags['scriptName'] === 'cookieConsent' &&
tags['operation'] === 'logConsentToAPI' &&
typeof errorMessage === 'string' &&
(errorMessage.toLowerCase().includes('vercel security checkpoint') ||
(errorMessage.toLowerCase().includes('<!doctype html') &&
errorMessage.toLowerCase().includes('security checkpoint')))
)
}

function scrubBreadcrumbs(
breadcrumbs: NonNullable<Parameters<BeforeSendHandler>[0]['breadcrumbs']>
) {
Expand Down Expand Up @@ -117,9 +132,10 @@ export const beforeSendHandler: BeforeSendHandler = (event, _hint) => {
return null
}

// Consent logging is best-effort on the client. Rate limiting here is expected
// under bursty preference changes, so drop the browser-side auto-fetch event.
if (isHandledConsentRateLimitHttpError(event)) {
// Consent logging is best-effort on the client. Rate limiting and Vercel
// security checkpoints can block the action without any user-visible impact,
// so drop the browser-side auto-fetch event.
if (isHandledConsentHttpError(event)) {
return null
}

Expand All @@ -141,6 +157,12 @@ export const beforeSendHandler: BeforeSendHandler = (event, _hint) => {
return null
}

// If a consent checkpoint response is wrapped into a handled client error,
// drop that duplicate event as the action itself is already filtered.
if (isHandledConsentCheckpointClientError(event)) {
return null
}

const currentConsent = getConsentSnapshot()
if (!currentConsent.analytics) {
if (event.user) {
Expand Down
103 changes: 103 additions & 0 deletions src/components/scripts/store/__tests__/consent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,109 @@ describe('Consent side effects', () => {
expect(handleScriptErrorSpy).not.toHaveBeenCalled()
})

it('retries consent logging after a thrown 429 client error without reporting a script error', async () => {
vi.useFakeTimers()

consentCreateMock
.mockRejectedValueOnce(new Error('HTTP Client Error with status code: 429'))
.mockResolvedValueOnce({ data: { success: true, record: { id: 'consent-1' } } })

const handleScriptErrorSpy = vi.spyOn(errorHandlerModule, 'handleScriptError')

let consentListener:
| ((_state: ConsentState, _oldState?: ConsentState) => Promise<void> | void)
| undefined
vi.spyOn($consent, 'subscribe').mockImplementation(listener => {
consentListener = listener
return () => {}
})
vi.spyOn($isConsentBannerVisible, 'subscribe').mockImplementation(() => () => {})
vi.spyOn($hasFunctionalConsent, 'subscribe').mockImplementation(() => () => {})
vi.spyOn($hasAnalyticsConsent, 'subscribe').mockImplementation(() => () => {})

initConsentSideEffects()

const oldState = {
analytics: false,
marketing: false,
functional: false,
DataSubjectId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
}
const newState = {
analytics: true,
marketing: false,
functional: false,
DataSubjectId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
}

await consentListener?.(newState, oldState)

await vi.advanceTimersByTimeAsync(250)

await vi.waitFor(() => {
expect(consentCreateMock).toHaveBeenCalledTimes(1)
})

expect(handleScriptErrorSpy).not.toHaveBeenCalled()

await vi.advanceTimersByTimeAsync(5_000)

await vi.waitFor(() => {
expect(consentCreateMock).toHaveBeenCalledTimes(2)
})

expect(handleScriptErrorSpy).not.toHaveBeenCalled()
})

it('suppresses consent logging when Vercel security checkpoint blocks the action', async () => {
vi.useFakeTimers()

consentCreateMock.mockRejectedValueOnce(
new Error('<!DOCTYPE html><title>Vercel Security Checkpoint</title>')
)

const handleScriptErrorSpy = vi.spyOn(errorHandlerModule, 'handleScriptError')

let consentListener:
| ((_state: ConsentState, _oldState?: ConsentState) => Promise<void> | void)
| undefined
vi.spyOn($consent, 'subscribe').mockImplementation(listener => {
consentListener = listener
return () => {}
})
vi.spyOn($isConsentBannerVisible, 'subscribe').mockImplementation(() => () => {})
vi.spyOn($hasFunctionalConsent, 'subscribe').mockImplementation(() => () => {})
vi.spyOn($hasAnalyticsConsent, 'subscribe').mockImplementation(() => () => {})

initConsentSideEffects()

const oldState = {
analytics: false,
marketing: false,
functional: false,
DataSubjectId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
}
const newState = {
analytics: true,
marketing: false,
functional: false,
DataSubjectId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
}

await consentListener?.(newState, oldState)

await vi.advanceTimersByTimeAsync(250)

await vi.waitFor(() => {
expect(consentCreateMock).toHaveBeenCalledTimes(1)
})

await vi.advanceTimersByTimeAsync(30_000)

expect(consentCreateMock).toHaveBeenCalledTimes(1)
expect(handleScriptErrorSpy).not.toHaveBeenCalled()
})

it('deletes the data subject id when functional consent is revoked', () => {
let functionalListener: ((_hasConsent: boolean) => void) | undefined
vi.spyOn($hasFunctionalConsent, 'subscribe').mockImplementation(listener => {
Expand Down
Loading
Loading