diff --git a/Sources/Core/Tracker/WebViewMessageHandler.swift b/Sources/Core/Tracker/WebViewMessageHandler.swift index 93a0c79fd..486ef0cbe 100644 --- a/Sources/Core/Tracker/WebViewMessageHandler.swift +++ b/Sources/Core/Tracker/WebViewMessageHandler.swift @@ -40,6 +40,11 @@ class WebViewMessageHandler: NSObject, WKScriptMessageHandler { let context = body["context"] as? [[AnyHashable : Any]] ?? [] let trackers = body["trackers"] as? [String] ?? [] + if !JSONSerialization.isValidJSONObject(event) || !JSONSerialization.isValidJSONObject(context) { + logError(message: "WebView: Received event payload is not serializable to JSON, skipping.") + return + } + if command == "trackSelfDescribingEvent" { trackSelfDescribing(event, withContext: context, andTrackers: trackers) } else if command == "trackStructEvent" { diff --git a/Tests/TestWebViewMessageHandler.swift b/Tests/TestWebViewMessageHandler.swift index a2ebe5e76..a33ef9c7f 100644 --- a/Tests/TestWebViewMessageHandler.swift +++ b/Tests/TestWebViewMessageHandler.swift @@ -126,5 +126,41 @@ class TestWebViewMessageHandler: XCTestCase { let context = payload?["co"] as? String XCTAssert(context?.contains("{\"a\":\"b\"}") ?? false) } + + func testHandlesNonJSONSerializableDataInEvent() { + let message = MockWKScriptMessage( + body: [ + "command": "trackSelfDescribingEvent", + "event": [ + "schema": "http://schema.com", + "data": [ + "key": Double.nan + ] + ] + ]) + webViewMessageHandler?.receivedMesssage(message) // shouldn't crash + } + + func testHandlesNonJSONSerializableDataInContext() { + let message = MockWKScriptMessage( + body: [ + "command": "trackSelfDescribingEvent", + "event": [ + "schema": "http://schema.com", + "data": [ + "key": "val" + ] + ], + "context": [ + [ + "schema": "http://context-schema.com", + "data": [ + "a": Double.nan + ] + ] + ] + ]) + webViewMessageHandler?.receivedMesssage(message) // shouldn't crash + } } #endif