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

Feat/suite handle fw update check #16477

Merged
merged 2 commits into from
Feb 4, 2025
Merged

Conversation

szymonlesisz
Copy link
Contributor

Description

WIP Based on #16421
implementation of firmwareUpdate versionCheck and TrezorConnect UI.FIRMWARE_VERSION_CHANGED event

Copy link

github-actions bot commented Jan 20, 2025

🚀 Expo preview is ready!

  • Project → trezor-suite-preview
  • Platforms → android, ios
  • Scheme → trezorsuitelite
  • Runtime Version → 24
  • More info

Learn more about 𝝠 Expo Github Action

packages/connect/src/utils/firmwareUtils.ts Outdated Show resolved Hide resolved
packages/connect/src/utils/firmwareUtils.ts Outdated Show resolved Hide resolved
packages/connect/src/types/api/firmwareUpdate.ts Outdated Show resolved Hide resolved
@@ -67,6 +67,10 @@ const eventsMiddleware =
}
}

if (action.type === DEVICE.FIRMWARE_VERSION_CHANGED) {
// TODO: show warning? move this to different middleware?
Copy link
Contributor

Choose a reason for hiding this comment

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

TODO log to Sentry (I can do it).

Copy link
Contributor

Choose a reason for hiding this comment

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

Example log in Sentry
Mocked by changing this line.

@@ -165,6 +165,8 @@ export const firmwareUpdate = createThunk<
errorMessage: firmwareUpdateResponse.payload.checkError,
}),
);
} else if (!binary && !versionCheck) {
// TODO: log to sentry
Copy link
Contributor

Choose a reason for hiding this comment

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

I can do it.

Copy link
Contributor

Choose a reason for hiding this comment

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

Example log in Sentry 2
Mocked by changing installedVersion here.

@@ -29,6 +29,16 @@ const deviceDisconnect = createAction(DEVICE.DISCONNECT, (payload: TrezorDevice)
payload,
}));

// this action is not used but is required because of the typings
Copy link
Contributor

Choose a reason for hiding this comment

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

This is awkward... how should it be resolved, @peter-sanderson? I see you removed DeviceEvent here

Copy link
Contributor

Choose a reason for hiding this comment

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

I don't remember but I would guess it has to do something with this:

c02412b#diff-2ec00308835c01545c383eaef7034f26bef251f7e04e990e21aac46d0afb2c8bR71

As I read it, I think that idea was to define actions independently from Connect Event and map them instead of using them directly.

Copy link
Contributor

@peter-sanderson peter-sanderson Jan 29, 2025

Choose a reason for hiding this comment

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

I think this is the place where mapping was intended to happen: c02412b#diff-2e9d057f0bfe2cc92fe50d4ce28838622d9e79fcca010ab8847a0fa288da13fdR38

Copy link
Contributor

Choose a reason for hiding this comment

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

mapping is done only for 2 actions however the rest of DEVICE_EVENTs are dispatched directly from here not from the deviceActions, yet its required to be defined in deviceActions to satisfy the types.

this problem applies to any other DEVICE_EVENTs action.type like DEVICE.DISCONNECT or DEVICE.PASSPHRASE or DEVICE.PIN

Copy link
Contributor

Choose a reason for hiding this comment

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

I am looking into it. There is definitely a problem there.

Here it is typed TrezorConnect.on(DEVICE_EVENT, .... as DeviceEventMessage which contains only those types. I assume this is correct.

image

I have tried to play with it in this commit 29aaaf4 and this is a draft of how I think it shall be done.

But I am not sure how to make types work properly and also I need to run now.

Lets talk tomorrow.

Copy link
Contributor Author

@szymonlesisz szymonlesisz Jan 30, 2025

Choose a reason for hiding this comment

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

what is the benefit of doing things like this?
what i see is 1000% more lines of code, more complexity and added another todo's which will be forgotten until next the occurrence + one potential problem if someone add another DEVICE_EVENT to connect (throwing error)

Copy link
Contributor

@komret komret Jan 30, 2025

Choose a reason for hiding this comment

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

The idea is to be explicit and to unify syntax across the codebase. However, the current implementation is not finished and having to create actions that are not dispatched is indeed counter-intuitive. @peter-sanderson will try to finish the work he started in his branch - should he not succeed, I'll broaden the type again to remove the counter-intuitive behaviour.

Copy link
Contributor Author

@szymonlesisz szymonlesisz Jan 30, 2025

Choose a reason for hiding this comment

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

so in the future you want to duplicate all the definitions of the events emitted from TrezorConnect?
like for example 40+ ui-events? and create this looong if or switch to dispatch a proper action?

because this is how i undestand this comment:

TrezorConnectEvents // Todo: This should not be here, actions shall be defined independently from Connect Events (and they shall be mapped onto them)

instead of 4-6 lines of code (current state) there will be like 200-300 in multiple files?

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree this is too many events to map.

@szymonlesisz
Copy link
Contributor Author

/rebase

Copy link

Copy link

Rebasing failed, please rebase manually.

@szymonlesisz szymonlesisz force-pushed the feat/suite-handle-fw-update-check branch from c6bf766 to 160d0c1 Compare January 29, 2025 13:24
@szymonlesisz
Copy link
Contributor Author

rebased, forcepushed, only one commit is relevant (implementation in suite)

@@ -67,6 +67,10 @@ const eventsMiddleware =
}
}

if (action.type === DEVICE.FIRMWARE_VERSION_CHANGED) {
Copy link
Contributor

@peter-sanderson peter-sanderson Jan 29, 2025

Choose a reason for hiding this comment

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

Despite this is working I think it shall be:

if (deviceActions.deviceFirmwareVersionChanged.match(action)) {

(More context coming in other comments).

@komret komret self-assigned this Feb 4, 2025
@komret komret force-pushed the feat/suite-handle-fw-update-check branch from 160d0c1 to b99495e Compare February 4, 2025 12:57
Copy link

coderabbitai bot commented Feb 4, 2025

Walkthrough

The changes span multiple parts of the codebase, focusing on updating firmware and device-related actions, payload structures, and error reporting. In the firmware actions file, the response payload was altered by removing the properties hash and challenge and adding check and versionCheck. The device settings actions were refactored to simplify variable handling within error reporting. The security check component updated the order and range of checkType options to include a new value. Additionally, the middleware now handles a firmware version change action by incorporating a new condition that triggers error reporting via reportCheckFail. Utility and type definitions in extra dependencies, as well as associated mocks and thunks, were extended to incorporate this new reporting function. A new action creator for firmware version changes was also introduced in the wallet core.

Suggested labels

no-project

Suggested reviewers

  • szymonlesisz
  • MiroslavProchazka
  • peter-sanderson

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@komret komret marked this pull request as ready for review February 4, 2025 12:57
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
suite-common/wallet-core/src/device/deviceActions.ts (1)

32-40: Consider removing the unused action creator.

The comment indicates this action creator is not used directly but is required for typings. This creates confusion and technical debt. Consider:

  1. Using the action directly instead of dispatching from connectInitThunk
  2. Or updating the types to avoid requiring unused action creators
packages/suite/src/middlewares/suite/eventsMiddleware.ts (1)

71-82: Improve action type checking using action matcher.

For consistency with other handlers in this file, use the action matcher pattern:

-if (action.type === DEVICE.FIRMWARE_VERSION_CHANGED) {
+if (deviceActions.deviceFirmwareVersionChanged.match(action)) {

Address the TODO comment about UI.

The TODO comment about adding UI should be tracked properly.

Would you like me to create an issue to track the UI implementation task?

suite-common/redux-utils/src/extraDependenciesType.ts (1)

141-145: Consider using an enum for checkType.

The implementation looks good. However, to improve type safety and maintainability, consider using an enum for the checkType parameter instead of string literals.

+export enum CheckType {
+  Entropy = 'Entropy',
+  FirmwareHash = 'Firmware hash',
+  FirmwareRevision = 'Firmware revision',
+  FirmwareVersion = 'Firmware version',
+}

-reportCheckFail: (
-  checkType: 'Entropy' | 'Firmware hash' | 'Firmware revision' | 'Firmware version',
-  contextData: Record<string, any>,
-  errorPayload?: unknown,
-) => void;
+reportCheckFail: (
+  checkType: CheckType,
+  contextData: Record<string, any>,
+  errorPayload?: unknown,
-) => void;
suite-common/firmware/src/firmwareThunks.ts (1)

181-192: Consider improving error handling for version check failures.

The version check implementation looks good, but consider:

  1. Adding a user-friendly error message in the UI.
  2. Providing guidance on how to resolve version mismatches.
  3. Adding retry logic for transient failures.

Consider implementing a dedicated error handling service that can:

  • Display user-friendly error messages
  • Provide troubleshooting steps
  • Track and report error metrics
  • Handle retries with backoff
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb781d8 and b99495e.

📒 Files selected for processing (9)
  • packages/suite/src/actions/firmware/__fixtures__/firmwareActions.ts (1 hunks)
  • packages/suite/src/actions/settings/deviceSettingsActions.ts (1 hunks)
  • packages/suite/src/components/suite/SecurityCheck/useReportDeviceCompromised.ts (1 hunks)
  • packages/suite/src/middlewares/suite/eventsMiddleware.ts (2 hunks)
  • packages/suite/src/support/extraDependencies.ts (2 hunks)
  • suite-common/firmware/src/firmwareThunks.ts (3 hunks)
  • suite-common/redux-utils/src/extraDependenciesType.ts (1 hunks)
  • suite-common/test-utils/src/extraDependenciesMock.ts (1 hunks)
  • suite-common/wallet-core/src/device/deviceActions.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/suite/src/actions/settings/deviceSettingsActions.ts
🔇 Additional comments (5)
packages/suite/src/components/suite/SecurityCheck/useReportDeviceCompromised.ts (1)

13-14: LGTM! The addition of 'Firmware version' check type is well-integrated.

The change maintains consistency with existing check types and aligns with the PR's objective.

suite-common/test-utils/src/extraDependenciesMock.ts (1)

149-150: LGTM! The mock implementation is consistent with the codebase patterns.

The warning message clearly indicates the mock nature of the implementation.

suite-common/firmware/src/firmwareThunks.ts (1)

180-180: TODO comment needs clarification.

The TODO comment "Add to the if-else block above and add handle in UI" is vague. Please clarify:

  1. What specific UI handling is needed?
  2. How should this be integrated into the existing if-else block?
packages/suite/src/support/extraDependencies.ts (1)

35-35: LGTM!

The integration of reportCheckFail into the extra dependencies is clean and follows the existing pattern.

Also applies to: 219-219

packages/suite/src/actions/firmware/__fixtures__/firmwareActions.ts (1)

29-31: Verify test coverage for version check scenarios.

The fixture updates look good but ensure test coverage for:

  1. Failed version checks (versionCheck: false)
  2. Different check values ('mismatch', 'other-error')
  3. Error reporting through reportCheckFail

Run this script to analyze test coverage:

✅ Verification successful

Firmware Version Check Test Coverage Confirmed

  • Failed Version Checks: The test case in packages/connect/src/core/__tests__/onCallFirmwareUpdate.test.ts verifies scenarios where versionCheck is false.
  • Different check Values: Test cases cover both 'mismatch' and 'other-error' scenarios, as evidenced by tests and implementation in packages/connect/src/core/__tests__/onCallFirmwareUpdate.test.ts and packages/connect/src/core/onCallFirmwareUpdate.ts.
  • Error Reporting (reportCheckFail): Usage of reportCheckFail with the 'Firmware version' context is verified in both packages/suite/src/middlewares/suite/eventsMiddleware.ts and suite-common/firmware/src/firmwareThunks.ts.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for firmware version checks

# Search for test cases covering version check scenarios
rg -A 5 "versionCheck.*false" --type ts
rg -A 5 "check.*mismatch" --type ts
rg -A 5 "check.*other-error" --type ts
rg -A 5 "reportCheckFail.*Firmware version" --type ts

Length of output: 7369

@komret komret force-pushed the feat/suite-handle-fw-update-check branch from b99495e to 8e155a8 Compare February 4, 2025 13:01
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/suite/src/middlewares/suite/eventsMiddleware.ts (1)

71-71: 🛠️ Refactor suggestion

Use action matcher pattern for consistency.

For consistency with other handlers in this file (e.g., lines 84, 100, 124), use the action matcher pattern.

-if (action.type === DEVICE.FIRMWARE_VERSION_CHANGED) {
+if (deviceActions.deviceFirmwareVersionChanged.match(action)) {
🧹 Nitpick comments (2)
packages/suite/src/middlewares/suite/eventsMiddleware.ts (2)

72-72: Enhance the TODO comment.

The TODO comment should be more descriptive about what UI needs to be added and why.

-            // TODO: Add UI.
+            // TODO: Add UI notification to inform the user about unexpected firmware version change.

73-82: Improve device access safety and error message clarity.

The code could be more defensive when accessing device properties and provide a more informative error message.

-            const { device, oldVersion, newVersion } = action.payload;
-            reportCheckFail('Firmware version', {
-                model: device?.features?.internal_model,
-                revision: device?.features?.revision,
-                oldVersion,
-                newVersion,
-                vendor: device?.features?.fw_vendor,
-                error: 'Firmware version changed unexpectedly.',
-            });
+            const { device, oldVersion, newVersion } = action.payload;
+            if (!device?.features) {
+                return;
+            }
+            reportCheckFail('Firmware version', {
+                model: device.features.internal_model,
+                revision: device.features.revision,
+                oldVersion,
+                newVersion,
+                vendor: device.features.fw_vendor,
+                error: `Unexpected firmware version change from ${oldVersion} to ${newVersion}.`,
+            });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b99495e and 8e155a8.

📒 Files selected for processing (9)
  • packages/suite/src/actions/firmware/__fixtures__/firmwareActions.ts (1 hunks)
  • packages/suite/src/actions/settings/deviceSettingsActions.ts (1 hunks)
  • packages/suite/src/components/suite/SecurityCheck/useReportDeviceCompromised.ts (1 hunks)
  • packages/suite/src/middlewares/suite/eventsMiddleware.ts (2 hunks)
  • packages/suite/src/support/extraDependencies.ts (2 hunks)
  • suite-common/firmware/src/firmwareThunks.ts (3 hunks)
  • suite-common/redux-utils/src/extraDependenciesType.ts (1 hunks)
  • suite-common/test-utils/src/extraDependenciesMock.ts (1 hunks)
  • suite-common/wallet-core/src/device/deviceActions.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/suite/src/actions/firmware/fixtures/firmwareActions.ts
  • suite-common/redux-utils/src/extraDependenciesType.ts
  • packages/suite/src/actions/settings/deviceSettingsActions.ts
  • suite-common/test-utils/src/extraDependenciesMock.ts
  • suite-common/firmware/src/firmwareThunks.ts
  • packages/suite/src/components/suite/SecurityCheck/useReportDeviceCompromised.ts
  • suite-common/wallet-core/src/device/deviceActions.ts
  • packages/suite/src/support/extraDependencies.ts
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: EAS Update
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: Analyze with CodeQL (javascript)
  • GitHub Check: prepare_android_test_app
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: build-web
  • GitHub Check: build-web
🔇 Additional comments (1)
packages/suite/src/middlewares/suite/eventsMiddleware.ts (1)

19-19: LGTM!

The import statement is correctly placed and follows the project's conventions.

@@ -216,5 +217,6 @@ export const extraDependencies: ExtraDependencies = {
utils: {
saveAs: (data, fileName) => saveAs(data, fileName),
connectInitSettings,
reportCheckFail,
Copy link
Contributor

@peter-sanderson peter-sanderson Feb 4, 2025

Choose a reason for hiding this comment

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

wouldn't be better to add generic report(Sentry)Error dependency rather then specific reporting?

Copy link
Contributor

Choose a reason for hiding this comment

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

I can imagine to move whole reportCheckFail to common, and use it both in common and suite then. But inject the generic error handler (for sentry).

This way we can utilise error handling in any share code.

Copy link
Contributor

Choose a reason for hiding this comment

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

(can be done in future PR, but please lets do it).

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree, I did it this way because it was minimal effort.

@komret komret enabled auto-merge (rebase) February 4, 2025 13:19
@komret komret self-requested a review February 4, 2025 13:21
@komret komret merged commit 69b9677 into develop Feb 4, 2025
32 of 33 checks passed
@komret komret deleted the feat/suite-handle-fw-update-check branch February 4, 2025 13:46
@STew790 STew790 added the QA OK Issue passed QA without any blocker label Feb 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA OK Issue passed QA without any blocker
Projects
Status: ✅ Approved
Development

Successfully merging this pull request may close these issues.

4 participants