Skip to content

fix(android): MM-68210 guard WebSocket methods against missing client NPE - #170

Open
pavelzeman wants to merge 3 commits into
masterfrom
fix/websocket-invalidate-npe
Open

fix(android): MM-68210 guard WebSocket methods against missing client NPE#170
pavelzeman wants to merge 3 commits into
masterfrom
fix/websocket-invalidate-npe

Conversation

@pavelzeman

@pavelzeman pavelzeman commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes a NullPointerException crash in WebSocketClientModuleImpl affecting 1,074 users (1,568 events) tracked in Sentry #7153287556.

Root Cause

invalidateClientFor() used Kotlin's force-unwrap operator (!!) on a map lookup:

clients[wsUri]!!.webSocket?.close(1000, null)

When JS calls invalidateClientFor for a URL that was never created or was already invalidated, clients[wsUri] returns null and !! throws NullPointerException. This crashes the app because the call is not wrapped in try/catch.

The same !! pattern existed in connectFor, disconnectFor, sendDataFor, and ensureClientFor — those were wrapped in try/catch so they rejected the promise instead of crashing, but they still used unsafe patterns.

Fix

  • invalidateClientFor: Safe access with ?.let. Resolves the promise even if the client doesn't exist (idempotent — the desired end state is "no client", which is already true).
  • connectFor, disconnectFor, sendDataFor: Explicit null checks with descriptive error messages via promise.reject().
  • ensureClientFor: Replaced containsKey + !! with ?.let pattern.

All 5 !! non-null assertions on clients[wsUri] have been removed.

Ticket Link

This was logged by Sentry on April 6, 2026:

https://mattermost.atlassian.net/browse/MM-68210

Release Note

Fixed a crash (NullPointerException) on Android when invalidating a WebSocket client that was already disconnected or never created.

Replace non-null assertion operators (!!) with safe access patterns
across all WebSocket client methods to prevent NullPointerException
when a client doesn't exist for a given URI.

- invalidateClientFor: use ?.let for safe access, resolve even if
  client doesn't exist (desired state is already achieved)
- connectFor, disconnectFor, sendDataFor: explicit null check with
  promise rejection instead of relying on NPE caught by try/catch
- ensureClientFor: use ?.let instead of containsKey + !!

Fixes Sentry #7153287556 (1,568 events / 1,074 affected users)

Co-authored-by: Claude <claude@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

WebSocketClientModuleImpl and ApiClientModuleImpl replace forced non-null lookups with null-safe access and explicit Promise rejection when clients are missing. A new test file covers force-unwrap versus safe-access behaviour.

Changes

Null-safe client handling

Layer / File(s) Summary
WebSocket lifecycle null-safety
android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt
ensureClientFor and invalidateClientFor close and remove stored WebSocket clients only when an entry exists, using null-safe access instead of non-null assertions.
WebSocket operations and tests
android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt, android/src/test/java/com/mattermost/networkclient/WebSocketClientNullSafetyTest.kt
connectFor, disconnectFor, and sendDataFor reject when no WebSocket client exists, use null-safe webSocket calls when present, and the new test file checks force-unwrap versus safe-access behaviour.
API client null checks
android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt
getClientHeadersFor, addClientHeadersFor, importClientP12For, invalidateClientFor, download, and upload now reject when the NetworkClient for a baseUrl is missing instead of using forced non-null lookups.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main Android fix for missing WebSocket clients and NPE prevention.
Description check ✅ Passed The description is directly related to the WebSocket and client null-safety changes in this pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/websocket-invalidate-npe

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt`:
- Around line 149-151: The websocket send flow in WebSocketClientModuleImpl.send
is resolving the promise even when client.webSocket?.send(data) returns null or
false, so dropped frames are treated as successful sends. Update the send logic
to inspect the return value from client.webSocket?.send(data) and reject the
promise whenever the socket is missing or OkHttp declines the frame, keeping
promise.resolve(null) only for a confirmed send.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f9fe4df1-ad82-4557-8d6e-7839c8355646

📥 Commits

Reviewing files that changed from the base of the PR and between de45de9 and 73e4a1d.

📒 Files selected for processing (1)
  • android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt

Comment thread android/src/main/java/com/mattermost/networkclient/WebSocketClientModuleImpl.kt Outdated
Check the return value of webSocket.send() — returns false when OkHttp
declines the frame (e.g. socket closing) and null when the socket is
missing. Only resolve the promise on a confirmed send.

Addresses CodeRabbit review feedback on PR #170.

Co-authored-by: Claude <claude@anthropic.com>
@pavelzeman
pavelzeman requested review from enahum and jgheithcock June 24, 2026 17:06
@pavelzeman pavelzeman changed the title fix(android): guard WebSocket methods against missing client NPE fix(android): MM-68210 guard WebSocket methods against missing client NPE Jun 25, 2026

@jgheithcock jgheithcock left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This was actually caught by Sentry and the ticket created back on April 6. Interestingly, the user count then fell off under the >100 users/week on May 17 (though it still reports).

While this file looks good, the https://github.com/mattermost/react-native-network-client also has two instances where we have the unsafe clients[url]!! pattern:
ApiClientModuleImpl.kt: download and upload. Just FYI, not for this PR.

Replaced unsafe `clients[url]!!` pattern with null-safe checks across:
- getClientHeadersFor
- addClientHeadersFor
- importClientP12For
- invalidateClientFor
- download
- upload

All methods now reject promise with clear error when client doesn't exist
for the given URL, matching the pattern already established in WebSocket methods.

Sentry issue: MATTERMOST-ANDROID-TEST-2E / MM-68210

Co-authored-by: Claude <claude@anthropic.com>
@pavelzeman
pavelzeman force-pushed the fix/websocket-invalidate-npe branch from 977ee5b to f86a8b4 Compare June 25, 2026 17:36
@pavelzeman

Copy link
Copy Markdown
Contributor Author

Expanded scope: Added null guards for 6 additional methods in ApiClientModuleImpl that had the same unsafe clients[url]!! pattern:

  • getClientHeadersFor
  • addClientHeadersFor
  • importClientP12For
  • invalidateClientFor
  • download
  • upload

All now follow the same safe pattern as the WebSocket methods: check for null client and reject promise with clear error message if missing.

This force-push invalidates the previous approval — please re-review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt (1)

165-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a regular exception type for missing-client rejections.

These branches model an expected runtime miss, so Error(...) is the wrong throwable shape here. If this ever gets propagated or handled outside Promise.reject, it will not be caught by catch (Exception) blocks and reads like an unrecoverable JVM failure. Prefer IllegalStateException or a stable RN error code/message instead.

Proposed change
-            return promise.reject(Error("Client not found for baseUrl: $url"))
+            return promise.reject(IllegalStateException("Client not found for baseUrl: $url"))

Also applies to: 185-185, 206-206, 227-227, 279-279, 343-343

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt` at
line 165, The missing-client rejection branches in ApiClientModuleImpl should
not use Error(...) because these are expected runtime failures; update the
Promise.reject calls in the client lookup paths (for example the logic around
getClient and related baseUrl checks) to use a regular exception such as
IllegalStateException, or a stable React Native error code/message shape. Keep
the existing rejection behavior, but make sure the throwable type is catchable
by normal Exception handlers and clearly represents a recoverable missing-client
condition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt`:
- Line 165: The missing-client rejection branches in ApiClientModuleImpl should
not use Error(...) because these are expected runtime failures; update the
Promise.reject calls in the client lookup paths (for example the logic around
getClient and related baseUrl checks) to use a regular exception such as
IllegalStateException, or a stable React Native error code/message shape. Keep
the existing rejection behavior, but make sure the throwable type is catchable
by normal Exception handlers and clearly represents a recoverable missing-client
condition.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d48fd336-88df-4c20-adc1-d6f800313a80

📥 Commits

Reviewing files that changed from the base of the PR and between 977ee5b and f86a8b4.

📒 Files selected for processing (2)
  • android/src/main/java/com/mattermost/networkclient/ApiClientModuleImpl.kt
  • android/src/test/java/com/mattermost/networkclient/WebSocketClientNullSafetyTest.kt
✅ Files skipped from review due to trivial changes (1)
  • android/src/test/java/com/mattermost/networkclient/WebSocketClientNullSafetyTest.kt

@pavelzeman

Copy link
Copy Markdown
Contributor Author

Sorry about the force-push, that was unintentional.
My AI loves to ignores the rules we agreed on sometimes. Repeatedly.

The 1 additional change was fixing all remaining outstanding similar code paths where a similar NPE could theoretically happen - JG, thanks for pointing that out.

@pavelzeman
pavelzeman requested a review from jgheithcock June 25, 2026 17:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants