Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 allow untrusted event for httpRequest xhr event listeners #3123

Merged
merged 5 commits into from
Nov 12, 2024
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
34 changes: 22 additions & 12 deletions packages/core/src/transport/httpRequest.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { collectAsyncCalls, mockEndpointBuilder, interceptRequests } from '../../test'
import { collectAsyncCalls, mockEndpointBuilder, interceptRequests, createNewEvent } from '../../test'
import type { Request } from '../../test'
import type { EndpointBuilder, Configuration } from '../domain/configuration'
import type { EndpointBuilder } from '../domain/configuration'
import { createEndpointBuilder } from '../domain/configuration'
import { noop } from '../tools/utils/functionUtils'
import { createHttpRequest, fetchKeepAliveStrategy, sendXHR } from './httpRequest'
Expand All @@ -13,14 +13,12 @@ describe('httpRequest', () => {
let requests: Request[]
let endpointBuilder: EndpointBuilder
let request: HttpRequest
let configuration: Configuration

beforeEach(() => {
configuration = {} as Configuration
interceptor = interceptRequests()
requests = interceptor.requests
endpointBuilder = mockEndpointBuilder(ENDPOINT_URL)
request = createHttpRequest(configuration, endpointBuilder, BATCH_BYTES_LIMIT, noop)
request = createHttpRequest(endpointBuilder, BATCH_BYTES_LIMIT, noop)
})

describe('send', () => {
Expand Down Expand Up @@ -105,7 +103,6 @@ describe('httpRequest', () => {
interceptor.withFetch(() => Promise.resolve({ status: 429, type: 'cors' }))

fetchKeepAliveStrategy(
configuration,
endpointBuilder,
BATCH_BYTES_LIMIT,
{ data: '{"foo":"bar1"}\n{"foo":"bar2"}', bytesCount: 10 },
Expand All @@ -129,7 +126,6 @@ describe('httpRequest', () => {
})

fetchKeepAliveStrategy(
configuration,
endpointBuilder,
BATCH_BYTES_LIMIT,
{ data: '{"foo":"bar1"}\n{"foo":"bar2"}', bytesCount: 10 },
Expand All @@ -148,7 +144,6 @@ describe('httpRequest', () => {
})

fetchKeepAliveStrategy(
configuration,
endpointBuilder,
BATCH_BYTES_LIMIT,
{ data: '{"foo":"bar1"}\n{"foo":"bar2"}', bytesCount: BATCH_BYTES_LIMIT },
Expand Down Expand Up @@ -177,7 +172,7 @@ describe('httpRequest', () => {
})
})

sendXHR(configuration, 'foo', '', onResponseSpy)
sendXHR('foo', '', onResponseSpy)

setTimeout(() => {
expect(onResponseSpy).toHaveBeenCalledTimes(1)
Expand All @@ -187,6 +182,23 @@ describe('httpRequest', () => {
done()
}, 100)
})

it('should handle synthetic events', (done) => {
const onResponseSpy = jasmine.createSpy('xhrOnResponse')

interceptor.withMockXhr((xhr) => {
const syntheticEvent = createNewEvent('loadend', { __ddIsTrusted: false })

setTimeout(() => xhr.dispatchEvent(syntheticEvent))
})

sendXHR('foo', '', onResponseSpy)

setTimeout(() => {
expect(onResponseSpy).toHaveBeenCalledTimes(1)
done()
}, 100)
})
})

describe('sendOnExit', () => {
Expand Down Expand Up @@ -257,14 +269,12 @@ describe('httpRequest intake parameters', () => {
let requests: Request[]
let endpointBuilder: EndpointBuilder
let request: HttpRequest
let configuration: Configuration

beforeEach(() => {
configuration = {} as Configuration
interceptor = interceptRequests()
requests = interceptor.requests
endpointBuilder = createEndpointBuilder({ clientToken }, 'logs', [])
request = createHttpRequest(configuration, endpointBuilder, BATCH_BYTES_LIMIT, noop)
request = createHttpRequest(endpointBuilder, BATCH_BYTES_LIMIT, noop)
})

it('should have a unique request id', () => {
Expand Down
31 changes: 10 additions & 21 deletions packages/core/src/transport/httpRequest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { EndpointBuilder, Configuration } from '../domain/configuration'
import type { EndpointBuilder } from '../domain/configuration'
import { addTelemetryError } from '../domain/telemetry'
import type { Context } from '../tools/serialisation/context'
import { monitor } from '../tools/monitor'
Expand Down Expand Up @@ -35,14 +35,13 @@ export interface RetryInfo {
}

export function createHttpRequest(
configuration: Configuration,
endpointBuilder: EndpointBuilder,
bytesLimit: number,
reportError: (error: RawError) => void
) {
const retryState = newRetryState()
const sendStrategyForRetry = (payload: Payload, onResponse: (r: HttpResponse) => void) =>
fetchKeepAliveStrategy(configuration, endpointBuilder, bytesLimit, payload, onResponse)
fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse)

return {
send: (payload: Payload) => {
Expand All @@ -53,17 +52,12 @@ export function createHttpRequest(
* keep using sendBeaconStrategy on exit
*/
sendOnExit: (payload: Payload) => {
sendBeaconStrategy(configuration, endpointBuilder, bytesLimit, payload)
sendBeaconStrategy(endpointBuilder, bytesLimit, payload)
},
}
}

function sendBeaconStrategy(
configuration: Configuration,
endpointBuilder: EndpointBuilder,
bytesLimit: number,
payload: Payload
) {
function sendBeaconStrategy(endpointBuilder: EndpointBuilder, bytesLimit: number, payload: Payload) {
const canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit
if (canUseBeacon) {
try {
Expand All @@ -79,7 +73,7 @@ function sendBeaconStrategy(
}

const xhrUrl = endpointBuilder.build('xhr', payload)
sendXHR(configuration, xhrUrl, payload.data)
sendXHR(xhrUrl, payload.data)
}

let hasReportedBeaconError = false
Expand All @@ -92,7 +86,6 @@ function reportBeaconError(e: unknown) {
}

export function fetchKeepAliveStrategy(
configuration: Configuration,
endpointBuilder: EndpointBuilder,
bytesLimit: number,
payload: Payload,
Expand All @@ -106,12 +99,12 @@ export function fetchKeepAliveStrategy(
monitor(() => {
const xhrUrl = endpointBuilder.build('xhr', payload)
// failed to queue the request
sendXHR(configuration, xhrUrl, payload.data, onResponse)
sendXHR(xhrUrl, payload.data, onResponse)
})
)
} else {
const xhrUrl = endpointBuilder.build('xhr', payload)
sendXHR(configuration, xhrUrl, payload.data, onResponse)
sendXHR(xhrUrl, payload.data, onResponse)
}
}

Expand All @@ -124,12 +117,7 @@ function isKeepAliveSupported() {
}
}

export function sendXHR(
configuration: Configuration,
url: string,
data: Payload['data'],
onResponse?: (r: HttpResponse) => void
) {
export function sendXHR(url: string, data: Payload['data'], onResponse?: (r: HttpResponse) => void) {
const request = new XMLHttpRequest()
request.open('POST', url, true)
if (data instanceof Blob) {
Expand All @@ -139,7 +127,8 @@ export function sendXHR(
request.setRequestHeader('Content-Type', data.type)
}
addEventListener(
configuration,
// allow untrusted event to acount for synthetic event dispatched by third party xhr wrapper
{ allowUntrustedEvents: true },
request,
'loadend',
() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/transport/startBatchWithReplica.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function startBatchWithReplica<T extends Context>(
function createBatchFromConfig(configuration: Configuration, { endpoint, encoder }: BatchConfiguration) {
return batchFactoryImp({
encoder,
request: createHttpRequest(configuration, endpoint, configuration.batchBytesLimit, reportError),
request: createHttpRequest(endpoint, configuration.batchBytesLimit, reportError),
flushController: createFlushController({
messagesLimit: configuration.batchMessagesLimit,
bytesLimit: configuration.batchBytesLimit,
Expand Down
17 changes: 9 additions & 8 deletions packages/core/test/emulate/mockXhr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,12 @@ class MockEventEmitter {
this.listeners[name] = this.listeners[name].filter((listener) => listener !== callback)
}

protected dispatchEvent(name: string) {
if (!this.listeners[name]) {
dispatchEvent(evt: Event) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dispatchEvent is normally exposed on the native xhr, so I see no reason to not expose it for mockXHR, especially as I a change the signature to be more standard.

It's just a tiny bit more verbose where dispatchEvent is called

if (!this.listeners[evt.type]) {
return
}
this.listeners[name].forEach((listener) => listener.apply(this, [createNewEvent(name)]))

this.listeners[evt.type].forEach((listener) => listener.apply(this, [evt]))
}
}

Expand Down Expand Up @@ -85,8 +86,8 @@ export class MockXhr extends MockEventEmitter {
this.hasEnded = true
this.readyState = XMLHttpRequest.DONE
this.onreadystatechange()
this.dispatchEvent('abort')
this.dispatchEvent('loadend')
this.dispatchEvent(createNewEvent('abort'))
this.dispatchEvent(createNewEvent('loadend'))
}

complete(status: number, response?: string) {
Expand All @@ -102,11 +103,11 @@ export class MockXhr extends MockEventEmitter {
this.onreadystatechange()

if (status >= 200 && status < 500) {
this.dispatchEvent('load')
this.dispatchEvent(createNewEvent('load'))
}
if (isServerError(status)) {
this.dispatchEvent('error')
this.dispatchEvent(createNewEvent('error'))
}
this.dispatchEvent('loadend')
this.dispatchEvent(createNewEvent('loadend'))
}
}
3 changes: 1 addition & 2 deletions packages/rum/src/boot/startRecording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ export function startRecording(
}

const replayRequest =
httpRequest ||
createHttpRequest(configuration, configuration.sessionReplayEndpointBuilder, SEGMENT_BYTES_LIMIT, reportError)
httpRequest || createHttpRequest(configuration.sessionReplayEndpointBuilder, SEGMENT_BYTES_LIMIT, reportError)

let addRecord: (record: BrowserRecord) => void

Expand Down