Skip to content

fix: harden supported-versions validation, recovery, and exception scoping - #3407

Merged
jeanfbrito merged 3 commits into
masterfrom
fix/supported-versions-hardening
Jul 10, 2026
Merged

jeanfbrito merged 3 commits into
masterfrom
fix/supported-versions-hardening

Conversation

@jeanfbrito

@jeanfbrito jeanfbrito commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Jira: CORE-2409

Stacked on #3404 — retarget to master after it merges.

What

Follow-up hardening pass over the supported-versions subsystem after the exception-scope investigation in #3404. Two independent audits (main-process flow and renderer surfaces) produced the findings below; every fix ships with a regression test.

Fixes

Validation robustness (main process)

  • Wrap the cache/builtin fallback validation in a helper with try/catch. A malformed cached payload could previously reject updateSupportedVersionsData before the error state was dispatched, leaving supportedVersionsFetchState stuck at 'loading' — which suppresses the UnsupportedServer block gate. The error state is now always dispatched and the prior verdict is preserved.
  • Catch rejections at all four fire-and-forget validation call sites (three listeners + the refresh-supported-versions IPC handler).
  • Fall back to the persisted workspace uniqueID when the fresh fetch fails, so the cloud lookup is not skipped for previously-known servers.
  • Revalidate all servers on powerMonitor 'resume' — the window 'online' event does not fire when waking with the same network still connected.

Exception scoping

  • Server, cloud, and cache payloads are fetched from or for the server being validated, so their exceptions block cannot belong to another tenant. For these sources a domain/uniqueId scope mismatch is now a diagnostic warning instead of disqualifying the exception. The bundled builtin payload — the only source that could carry another deployment's exceptions — keeps the strict scope requirement.
  • An unknown local uniqueID (e.g. settings.public restricted by API access controls) is never treated as a scope mismatch.
  • exceptions.domain comparison was already made case-insensitive in fix: honor uniqueId-scoped support exceptions on server-signed path #3404.

State integrity

  • WEBVIEW_SERVER_UNIQUE_ID_UPDATED, WEBVIEW_SERVER_VERSION_UPDATED, and WEBVIEW_GIT_COMMIT_HASH_CHANGED reducer cases switched from upsert to update: a late identity dispatch for a server deleted while a validation was in flight can no longer resurrect a ghost server entry.

Renderer

  • SupportedVersionDialog effect dependencies used the imported currentView reducer function (never changes) instead of the state value, so the dialog never re-checked when switching server views. Now selects the real state.
  • Guard getExpirationMessageTranslated against payloads whose i18n dictionary lacks both the user language and en; the unguarded lookup crashed the async check and silently suppressed the expiring-workspace warning dialog.
  • Add a Check again button to the unsupported-workspace screen so validation can be re-triggered without restarting the app (new unsupportedServer.checkAgain en key; other locales fall back).

Enforcement certainty

  • A missing or malformed enforcementStartDate no longer blocks the workspace: an Invalid Date previously failed the future-date comparison and fell through to the unsupported verdict on incomplete payload data. Blocking now requires a valid, past enforcement date.

Cosmetic

  • logRequestError printed a literal ${description} (single-quoted string).

Out of scope, tracked for follow-up

  • Signing-key rotation contingency (single hardcoded RS256 key; needs cloud-side coordination).
  • Expired exception + future enforcementStartDate ⇒ supported (global grace masks a lapsed exception) — needs product confirmation.
  • Test-fixture realism: default mocks include uniqueId/commit/full patch version in /api/info, which real unauthenticated servers do not send.

Tests

  • 143 tests across the four touched suites pass; full repo suite 152 suites / 1602 tests green. tsc --noEmit and yarn lint clean.

Summary by CodeRabbit

  • New Features
    • Added a “Check again” action for unsupported servers.
    • Supported-version checks now refresh when switching servers and when the device resumes.
  • Bug Fixes
    • Improved handling of malformed or incomplete support data to prevent incorrect blocking or stuck loading states.
    • Cloud checks can continue using the saved server identity when a fresh identity lookup fails.
    • Refined exception-scope validation and diagnostics for more accurate support decisions.

Recreation of #3405, which was auto-closed when its stacked base branch was deleted during the merge of #3404. Same branch, same content.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Supported-version validation now handles scoped payload sources, malformed fallback data, persisted identities, and resume refreshes. Server reducers avoid creating unknown entries. Unsupported-server UI adds a check-again action, and the dialog rechecks when the selected server changes.

Changes

Supported-version and server state updates

Layer / File(s) Summary
Supported-version validation semantics
src/servers/supportedVersions/main.ts, src/servers/supportedVersions/main.main.spec.ts
Payload-source-aware exception scope handling, defensive enforcement-date parsing, and expanded scoped-exception tests are added.
Fallback, cloud identity, and refresh orchestration
src/servers/supportedVersions/main.ts, src/servers/supportedVersions/main.main.spec.ts
Fallback validation, persisted uniqueID cloud lookup, update error logging, resume refreshes, and related regression tests are added.
Existing-server reducer updates
src/servers/reducers.ts, src/servers/reducers/__tests__/servers.spec.ts
Webview identity, version, and commit-hash actions update existing servers without inserting unknown URLs.
Unsupported-server refresh interaction
src/i18n/en.i18n.json, src/ui/components/ServersView/*, src/ui/components/SupportedVersionDialog/*
The unsupported-server view exposes a localized refresh action through IPC, while the dialog rechecks when the selected server changes.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant UnsupportedServer
  participant ipcRenderer
  participant checkSupportedVersionServers
  participant updateSupportedVersionsData
  User->>UnsupportedServer: click check again
  UnsupportedServer->>ipcRenderer: invoke refresh-supported-versions with serverUrl
  ipcRenderer->>checkSupportedVersionServers: refresh selected server
  checkSupportedVersionServers->>updateSupportedVersionsData: update support data
  updateSupportedVersionsData-->>UnsupportedServer: updated supported-version state
Loading

Possibly related PRs

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main supported-versions hardening across validation, recovery, and exception scoping.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Audited the supported-versions subsystem end to end after the
uniqueId-scope escalation and fixed the confirmed defects:

- Wrap the cache/builtin fallback validation in a helper with try/catch
  so a malformed cached payload can no longer reject the update before
  the error state is dispatched, which left fetchState stuck at
  'loading' and suppressed the UnsupportedServer block gate.
- Catch rejections at all four fire-and-forget validation call sites.
- Fall back to the persisted workspace uniqueID when the fresh fetch
  fails so the cloud lookup is not skipped for previously-known servers.
- Switch uniqueID/version/gitCommitHash reducer cases from upsert to
  update so a late identity dispatch cannot resurrect a server deleted
  while a validation was in flight.
- Guard getExpirationMessageTranslated against payloads whose i18n
  dictionary lacks both the user language and 'en'; the missing guard
  crashed the async check and silently suppressed the expiring-
  workspace warning dialog.
- Revalidate all servers on powerMonitor 'resume' (the window 'online'
  event does not fire when waking with the same network connected).
- Use the real currentView state in SupportedVersionDialog's effect
  dependencies; the previous dependency was the imported reducer
  function, which never changes, so the dialog never re-checked on
  view switches.
- Add a 'Check again' button to the unsupported-workspace screen so
  users can re-trigger validation without restarting the app.
- Fix logRequestError printing a literal ${description}.

Also relax the exception scope check for UNKNOWN local identity: an
unfetchable workspace uniqueID (e.g. settings.public restricted by
enterprise API ACLs) no longer disqualifies a domain-matched exception;
a PROVEN uniqueID mismatch still rejects. The gate is client-side UX
enforcement rather than a security boundary, and wrongly blocking a
legitimate workspace is the worse failure mode.
Server, cloud, and cache supported-versions payloads are fetched from or
for the server being validated, so their exceptions block cannot belong
to another tenant. For these sources a domain/uniqueId scope mismatch is
now logged as a diagnostic warning instead of disqualifying the
exception. The bundled builtin payload is the only source that could
carry another deployment's exceptions and keeps the strict scope
requirement.

This removes the remaining paths where a valid, unexpired exception
could be rejected over unverifiable or drifted identity data (restricted
settings.public API, rotated workspace uniqueID, stale persisted
state).
A missing or unparseable enforcementStartDate previously produced an
Invalid Date that failed the future-date comparison and fell through to
the unsupported verdict — blocking the workspace based on incomplete
payload data. Blocking now requires a valid, past enforcement date:
uncertain data keeps the server usable until a payload with a valid
enforcement date proves enforcement is active.
@jeanfbrito
jeanfbrito force-pushed the fix/supported-versions-hardening branch from 92b3e1b to c3231e7 Compare July 10, 2026 12:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ui/components/SupportedVersionDialog/index.tsx (1)

86-90: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Pass supportedVersionsSource into both revalidation calls. isServerVersionSupported now treats payloadSource: 'builtin' strictly, but these calls fall back to the permissive path. Cached builtin payloads can then be re-evaluated differently from the initial updateSupportedVersionsData verdict.

🤖 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 `@src/ui/components/SupportedVersionDialog/index.tsx` around lines 86 - 90,
Update both revalidation calls in SupportedVersionDialog, including the call
containing isServerVersionSupported, to pass the server’s
supportedVersionsSource as the payloadSource argument. Ensure every invocation
uses the same source value used by updateSupportedVersionsData so cached builtin
payloads follow the strict validation path.
🧹 Nitpick comments (2)
src/servers/supportedVersions/main.main.spec.ts (1)

2586-2598: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider also asserting the resume-handler's behavior, not just its registration.

The test only checks that powerMonitor.on was called with 'resume' and a function; it doesn't invoke that callback to verify it actually calls updateSupportedVersionsData for each server (which is the behavior described in the surrounding comment). Optional strengthening.

🤖 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 `@src/servers/supportedVersions/main.main.spec.ts` around lines 2586 - 2598,
Strengthen the power resume revalidation test by capturing the callback passed
to powerMonitor.on in checkSupportedVersionServers, invoking it, and asserting
that updateSupportedVersionsData is called for every configured server. Retain
the existing registration assertion and use the test’s existing server fixtures
and mocks to verify the callback behavior.
src/servers/supportedVersions/main.ts (1)

809-850: 🧹 Nitpick | 🔵 Trivial

Resume handler fires unthrottled network refreshes for every server simultaneously.

powerMonitor.on('resume', ...) triggers updateSupportedVersionsData for every server in state at once, with no staggering. For accounts with many configured servers, this could cause a burst of concurrent server/cloud requests (each with up to 3 retries and 2s delays) right after resume. Worth keeping in mind operationally, though not blocking.

🤖 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 `@src/servers/supportedVersions/main.ts` around lines 809 - 850, The
powerMonitor resume handler refreshes all servers concurrently, creating an
unthrottled request burst. Update the resume logic in
checkSupportedVersionServers to stagger or throttle calls to
updateSupportedVersionsData, while preserving per-server error handling through
logUpdateError and ensuring each server is eventually refreshed.
🤖 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 `@src/servers/supportedVersions/main.main.spec.ts`:
- Around line 2491-2541: Add a companion success-path test for
validateFallbackAndDispatch using a well-formed cached fallback payload,
asserting it dispatches the supported-version/update actions and does not
dispatch WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR. Ensure the test exercises the
fallback path after the network failure and verifies the promise resolves, then
fix validateFallbackAndDispatch to return immediately after successful
dispatches so the error action is not emitted.

In `@src/servers/supportedVersions/main.ts`:
- Around line 558-599: Add an immediate return after the successful verdict and
supported-versions dispatches in validateFallbackAndDispatch, before execution
can reach the error dispatch. Keep the catch path unchanged so
WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR is dispatched only when validation
throws, and add or update coverage for the non-throwing success path.

---

Outside diff comments:
In `@src/ui/components/SupportedVersionDialog/index.tsx`:
- Around line 86-90: Update both revalidation calls in SupportedVersionDialog,
including the call containing isServerVersionSupported, to pass the server’s
supportedVersionsSource as the payloadSource argument. Ensure every invocation
uses the same source value used by updateSupportedVersionsData so cached builtin
payloads follow the strict validation path.

---

Nitpick comments:
In `@src/servers/supportedVersions/main.main.spec.ts`:
- Around line 2586-2598: Strengthen the power resume revalidation test by
capturing the callback passed to powerMonitor.on in
checkSupportedVersionServers, invoking it, and asserting that
updateSupportedVersionsData is called for every configured server. Retain the
existing registration assertion and use the test’s existing server fixtures and
mocks to verify the callback behavior.

In `@src/servers/supportedVersions/main.ts`:
- Around line 809-850: The powerMonitor resume handler refreshes all servers
concurrently, creating an unthrottled request burst. Update the resume logic in
checkSupportedVersionServers to stagger or throttle calls to
updateSupportedVersionsData, while preserving per-server error handling through
logUpdateError and ensuring each server is eventually refreshed.
🪄 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: b6e59b21-3ad1-4393-b1c9-3b481c515949

📥 Commits

Reviewing files that changed from the base of the PR and between fcc126f and c3231e7.

📒 Files selected for processing (10)
  • src/i18n/en.i18n.json
  • src/servers/reducers.ts
  • src/servers/reducers/__tests__/servers.spec.ts
  • src/servers/supportedVersions/main.main.spec.ts
  • src/servers/supportedVersions/main.ts
  • src/ui/components/ServersView/ServerPane.tsx
  • src/ui/components/ServersView/UnsupportedServer.spec.tsx
  • src/ui/components/ServersView/UnsupportedServer.tsx
  • src/ui/components/SupportedVersionDialog/index.spec.tsx
  • src/ui/components/SupportedVersionDialog/index.tsx
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: check (ubuntu-latest)
  • GitHub Check: check (macos-latest)
  • GitHub Check: check (windows-latest)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Use TypeScript for all new code unless explicitly told otherwise.
Use Fuselage components for all UI work; only create custom components when Fuselage does not provide what is needed.
Import UI components from @rocket.chat/fuselage.
Check Theme.d.ts for valid color tokens before using Fuselage theme colors.
Use optional chaining with fallbacks for platform-specific APIs, especially Linux-only process APIs like process.getuid(), process.getgid(), process.geteuid(), and process.getegid().
Only mock platform-specific APIs when defensive coding is not possible.
Use TypeScript strict mode.
Use React functional components with hooks.
Redux actions must follow the Flux Standard Action (FSA) pattern.
Use camelCase for file names and PascalCase for components.

**/*.{ts,tsx}: Use TypeScript for new code unless explicitly told otherwise.
Use Fuselage components from @rocket.chat/fuselage for UI work unless the design requires something Fuselage does not provide.
Check Theme.d.ts for valid color tokens before using Fuselage colors.
Verify library props, APIs, and tokens against official docs or local .d.ts files instead of assuming.
Use React functional components with hooks.
Redux actions follow FSA shape.
Use camelCase for file names and PascalCase for components.
Prefer clear names over unnecessary comments.
Prefer editing existing files over creating new abstractions unless the new abstraction removes real complexity or matches an existing pattern.

Files:

  • src/ui/components/ServersView/ServerPane.tsx
  • src/servers/reducers.ts
  • src/ui/components/SupportedVersionDialog/index.tsx
  • src/ui/components/ServersView/UnsupportedServer.spec.tsx
  • src/servers/reducers/__tests__/servers.spec.ts
  • src/ui/components/SupportedVersionDialog/index.spec.tsx
  • src/ui/components/ServersView/UnsupportedServer.tsx
  • src/servers/supportedVersions/main.main.spec.ts
  • src/servers/supportedVersions/main.ts
**/*.spec.tsx

📄 CodeRabbit inference engine (CLAUDE.md)

Use *.spec.tsx for renderer process tests.

Files:

  • src/ui/components/ServersView/UnsupportedServer.spec.tsx
  • src/ui/components/SupportedVersionDialog/index.spec.tsx
**/*.spec.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Renderer specs use *.spec.ts / *.spec.tsx.

Files:

  • src/ui/components/ServersView/UnsupportedServer.spec.tsx
  • src/servers/reducers/__tests__/servers.spec.ts
  • src/ui/components/SupportedVersionDialog/index.spec.tsx
  • src/servers/supportedVersions/main.main.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use *.spec.ts for renderer process tests.

Files:

  • src/servers/reducers/__tests__/servers.spec.ts
  • src/servers/supportedVersions/main.main.spec.ts
**/*.main.spec.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use *.main.spec.ts for main process tests.

Main-process specs use *.main.spec.ts.

Files:

  • src/servers/supportedVersions/main.main.spec.ts
src/*/*/*.spec.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Renderer specs must live in a Jest-matched nested path, such as src/<module>/<subdir>/*.spec.ts(x); flat src/<module>/*.spec.ts files are not discovered by the current testMatch.

Files:

  • src/servers/supportedVersions/main.main.spec.ts
🧠 Learnings (1)
📚 Learning: 2026-06-26T18:14:15.295Z
Learnt from: jeanfbrito
Repo: RocketChat/Rocket.Chat.Electron PR: 3358
File: src/i18n/it-IT.i18n.json:39-42
Timestamp: 2026-06-26T18:14:15.295Z
Learning: In the i18n JSON files, the translation key `minimizeOnClose.disabledHint` is intentionally displayed when `isTrayIconEnabled` is true and the minimize-on-close toggle is disabled. The hint text should therefore instruct the user to disable the tray icon to make the setting available. During reviews, don’t “correct” this translation for seeming mismatches with the toggle state—first confirm it matches the component’s intended behavior; only update the wording if the underlying product logic/UX requirement changes.

Applied to files:

  • src/i18n/en.i18n.json
🔇 Additional comments (12)
src/servers/supportedVersions/main.ts (3)

5-5: LGTM!

Also applies to: 85-85, 302-304, 454-464


674-675: LGTM! payloadSource wiring and the effectiveUniqueId fallback (persisted uniqueID when the fresh fetch fails) are consistent with the described intent and covered by tests.

Also applies to: 718-726, 741-742, 784-792


345-383: 🎯 Functional Correctness

No issue: server.uniqueID is not treated as an 'UNKNOWN' sentinel. The scope check only skips falsy values, and the test case uses uniqueID: undefined for the “UNKNOWN” path; getUniqueId/dispatch only persist non-empty IDs.

			> Likely an incorrect or invalid review comment.
src/servers/supportedVersions/main.main.spec.ts (1)

34-36: LGTM! These additions align with the new payloadSource/enforcementStartDate/i18n-guard/resume-handler behavior in main.ts.

Also applies to: 478-514, 1019-1060, 2018-2073, 2075-2104, 2131-2181, 2569-2584, 2586-2598

src/servers/reducers.ts (1)

162-165: LGTM! Switching WEBVIEW_SERVER_UNIQUE_ID_UPDATED, WEBVIEW_SERVER_VERSION_UPDATED, and WEBVIEW_GIT_COMMIT_HASH_CHANGED from upsert to update correctly prevents late async identity/version updates from resurrecting a deleted server, and matches the regression tests covering unknown/deleted URLs.

Also applies to: 176-188, 220-223

src/ui/components/SupportedVersionDialog/index.tsx (1)

18-38: LGTM! The currentView dependency correctly triggers revalidation on view/server switch, matching the new regression test.

Also applies to: 142-144

src/ui/components/SupportedVersionDialog/index.spec.tsx (1)

1-9: LGTM!

Also applies to: 172-203

src/servers/reducers/__tests__/servers.spec.ts (1)

195-205: LGTM!

Also applies to: 241-251, 319-329

src/i18n/en.i18n.json (1)

492-493: LGTM!

src/ui/components/ServersView/UnsupportedServer.tsx (1)

19-27: LGTM!

Also applies to: 37-39, 76-78

src/ui/components/ServersView/ServerPane.tsx (1)

237-237: LGTM!

src/ui/components/ServersView/UnsupportedServer.spec.tsx (1)

1-96: LGTM!

Comment on lines +2491 to +2541

// ========== FIX-1: fallback path validation must not throw unguarded ==========
describe('fallback path validation failure (fail-open guard)', () => {
it('dispatches ERROR (not a rejection) and no IS_SUPPORTED_VERSION when the fallback payload is malformed', async () => {
const mockServer = createMockServer({ version: '7.5.0' });
selectMock.mockReturnValue(mockServer);
axiosMock.get = jest.fn().mockRejectedValue(new Error('Network error'));

// Cache returns a corrupt payload: `versions` is not an array, so
// isServerVersionSupported's `versions.find` throws synchronously.
const ElectronStoreMock = jest.requireMock('electron-store');
const storeGetMock = jest.spyOn(
ElectronStoreMock.prototype,
'get'
) as jest.Mock;
storeGetMock.mockReturnValue({
versions: { notAnArray: true },
enforcementStartDate: '2023-01-01T00:00:00Z',
timestamp: new Date().toISOString(),
});

const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();

jest.useFakeTimers();
const promise = updateSupportedVersionsData(mockServer.url);
await jest.advanceTimersByTimeAsync(4000);
// Must resolve, not reject.
await expect(promise).resolves.toBeUndefined();
jest.useRealTimers();

const errorDispatch = dispatchMock.mock.calls.find(
([action]) =>
(action as any).type === WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR
);
expect(errorDispatch).toBeDefined();

const isSupportedDispatches = dispatchMock.mock.calls.filter(
([action]) =>
(action as any).type === WEBVIEW_SERVER_IS_SUPPORTED_VERSION
);
expect(isSupportedDispatches.length).toBe(0);

expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining('Error validating fallback'),
expect.anything()
);

consoleErrorSpy.mockRestore();
storeGetMock.mockRestore();
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add a companion success-path test for validateFallbackAndDispatch.

This suite only covers the malformed-payload (throwing) branch of validateFallbackAndDispatch. As flagged in main.ts (the missing return after the success dispatches), a passing fallback validation currently also dispatches WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR right after WEBVIEW_SERVER_IS_SUPPORTED_VERSION/WEBVIEW_SERVER_SUPPORTED_VERSIONS_UPDATED. A test asserting that a well-formed fallback payload does NOT also dispatch the error action would have caught this and prevents regression once fixed.

🤖 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 `@src/servers/supportedVersions/main.main.spec.ts` around lines 2491 - 2541,
Add a companion success-path test for validateFallbackAndDispatch using a
well-formed cached fallback payload, asserting it dispatches the
supported-version/update actions and does not dispatch
WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR. Ensure the test exercises the fallback
path after the network failure and verifies the promise resolves, then fix
validateFallbackAndDispatch to return immediately after successful dispatches so
the error action is not emitted.

Comment on lines +558 to +599
// Validates the fallback (cache/builtin) payload and dispatches the verdict.
// isServerVersionSupported can throw on a malformed cached/builtin payload
// (e.g. `versions` not an array). Left unguarded, that throw would reject
// updateSupportedVersionsData before WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR
// is dispatched, leaving supportedVersionsFetchState stuck at 'loading' —
// which suppresses the UnsupportedServer block gate (fail-open). On failure,
// only the error state is dispatched; the prior verdict is left untouched.
const validateFallbackAndDispatch = async (
server: Server,
serverUrl: string,
fallbackVersions: SupportedVersions,
fallbackSource: 'cloud' | 'builtin',
freshCommitHash: string | undefined,
isStale: () => boolean
): Promise<void> => {
try {
const fallbackSupported = await isServerVersionSupported(
server,
fallbackVersions,
freshCommitHash,
fallbackSource
);
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_IS_SUPPORTED_VERSION,
payload: {
url: server.url,
isSupportedVersion: fallbackSupported.supported,
},
});
dispatchSupportedVersionsUpdated(server.url, fallbackVersions, {
source: fallbackSource,
});
} catch (error) {
console.error('Error validating fallback supported versions:', error);
}
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR,
payload: { url: serverUrl },
});
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Critical: success path also dispatches the ERROR action, corrupting supportedVersionsFetchState.

In validateFallbackAndDispatch, the try block has no return after the success dispatches (lines 581-590). Execution falls through past the catch block to lines 594-598, which unconditionally dispatches WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR — even on the success path. Per the reducer, this overwrites supportedVersionsFetchState from 'success' (just set by dispatchSupportedVersionsUpdated) to 'error' immediately after every successful fallback validation. This contradicts the function's own comment ("On failure, only the error state is dispatched; the prior verdict is left untouched") and defeats the fail-open guard for the normal (non-throwing) case.

The existing regression test only exercises the malformed-payload (throwing) branch, so it doesn't catch this.

🐛 Proposed fix: add missing `return` on the success path
   try {
     const fallbackSupported = await isServerVersionSupported(
       server,
       fallbackVersions,
       freshCommitHash,
       fallbackSource
     );
     if (isStale()) return;
     dispatch({
       type: WEBVIEW_SERVER_IS_SUPPORTED_VERSION,
       payload: {
         url: server.url,
         isSupportedVersion: fallbackSupported.supported,
       },
     });
     dispatchSupportedVersionsUpdated(server.url, fallbackVersions, {
       source: fallbackSource,
     });
+    return;
   } catch (error) {
     console.error('Error validating fallback supported versions:', error);
   }
   if (isStale()) return;
   dispatch({
     type: WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR,
     payload: { url: serverUrl },
   });
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Validates the fallback (cache/builtin) payload and dispatches the verdict.
// isServerVersionSupported can throw on a malformed cached/builtin payload
// (e.g. `versions` not an array). Left unguarded, that throw would reject
// updateSupportedVersionsData before WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR
// is dispatched, leaving supportedVersionsFetchState stuck at 'loading' —
// which suppresses the UnsupportedServer block gate (fail-open). On failure,
// only the error state is dispatched; the prior verdict is left untouched.
const validateFallbackAndDispatch = async (
server: Server,
serverUrl: string,
fallbackVersions: SupportedVersions,
fallbackSource: 'cloud' | 'builtin',
freshCommitHash: string | undefined,
isStale: () => boolean
): Promise<void> => {
try {
const fallbackSupported = await isServerVersionSupported(
server,
fallbackVersions,
freshCommitHash,
fallbackSource
);
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_IS_SUPPORTED_VERSION,
payload: {
url: server.url,
isSupportedVersion: fallbackSupported.supported,
},
});
dispatchSupportedVersionsUpdated(server.url, fallbackVersions, {
source: fallbackSource,
});
} catch (error) {
console.error('Error validating fallback supported versions:', error);
}
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR,
payload: { url: serverUrl },
});
};
// Validates the fallback (cache/builtin) payload and dispatches the verdict.
// isServerVersionSupported can throw on a malformed cached/builtin payload
// (e.g. `versions` not an array). Left unguarded, that throw would reject
// updateSupportedVersionsData before WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR
// is dispatched, leaving supportedVersionsFetchState stuck at 'loading' —
// which suppresses the UnsupportedServer block gate (fail-open). On failure,
// only the error state is dispatched; the prior verdict is left untouched.
const validateFallbackAndDispatch = async (
server: Server,
serverUrl: string,
fallbackVersions: SupportedVersions,
fallbackSource: 'cloud' | 'builtin',
freshCommitHash: string | undefined,
isStale: () => boolean
): Promise<void> => {
try {
const fallbackSupported = await isServerVersionSupported(
server,
fallbackVersions,
freshCommitHash,
fallbackSource
);
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_IS_SUPPORTED_VERSION,
payload: {
url: server.url,
isSupportedVersion: fallbackSupported.supported,
},
});
dispatchSupportedVersionsUpdated(server.url, fallbackVersions, {
source: fallbackSource,
});
return;
} catch (error) {
console.error('Error validating fallback supported versions:', error);
}
if (isStale()) return;
dispatch({
type: WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR,
payload: { url: serverUrl },
});
};
🤖 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 `@src/servers/supportedVersions/main.ts` around lines 558 - 599, Add an
immediate return after the successful verdict and supported-versions dispatches
in validateFallbackAndDispatch, before execution can reach the error dispatch.
Keep the catch path unchanged so WEBVIEW_SERVER_SUPPORTED_VERSIONS_ERROR is
dispatched only when validation throws, and add or update coverage for the
non-throwing success path.

@jeanfbrito
jeanfbrito merged commit 969563c into master Jul 10, 2026
8 checks passed
@jeanfbrito
jeanfbrito deleted the fix/supported-versions-hardening branch July 10, 2026 13:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant