Commit Graph
6 Commits
Author SHA1 Message Date
Sure Admin (bot)andJuan José Mata f5d9a15c99 fix(wise): require encrypted SCA key registration (#3439)
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-09-08 00:00:56 +02:00
AnthonyandClaude Opus 5 9ec28abacc fix(wise): refuse an SCA private key when encryption is unavailable (#3415)
* fix(wise): refuse an SCA private key when encryption is unavailable

WiseItem wraps its `encrypts` declarations in `if encryption_ready?`, which is
false on any install that has not explicitly configured Active Record
encryption. On those installs the declaration never runs, so assigning
sca_private_key writes the PEM into the column verbatim.

That is a tolerable degraded mode for a display name. It is not one for the key
that signs Wise balance-statement requests, and nothing in the flow told the
user it had happened: the panel reported a keypair as generated either way.

generate_sca_keypair! now raises SCAEncryptionUnavailable instead of writing,
and a validation refuses the attribute on every other write path. The exception
is raised rather than returned so no caller can read "not stored" as "stored".
WiseItemsController#generate_sca_keypair already rescues broadly, so the user
sees the same panel error as any other keypair failure rather than a 500.

The three existing tests that generate a keypair now stub encryption_ready? to
true. The test environment configures no encryption keys, so without the stub
they would be exercising the refused path rather than the one they describe.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(wise): validate the SCA key only when it is being written

Review found a real regression in the first commit, and CI found a scanner hit.

The validation ran on every save. An install that generated a key before this
change still has that plaintext value in the column, so the record became
permanently unsaveable: renaming the connection failed, and the destroy path
failed worse. WiseItemsController#destroy calls unlink_all! and only then
destroy_later, whose update!(scheduled_for_deletion: true) would now raise, so
the accounts were already unlinked while the provider stayed active. Refusing a
NEW key is the point; refusing to let go of an old one is not. The validation
now returns unless sca_private_key is actually changing, and the explicit guard
in generate_sca_keypair! is unchanged.

The regression test fails without the guard, on the reload-and-save assertion.

pipelock flagged the literal "BEGIN RSA PRIVATE KEY" header in the test as a
critical Private Key Header finding in the diff, which is exactly what a secret
scanner should do. The value only ever needed to be non-blank, and the file
already uses a plain placeholder two tests above, so it now uses one too.

Also adds the encrypted-attributes assertion the other Encryptable models carry,
in their shape: it skips when encryption is unconfigured, because the suite
deliberately runs that way (see EncryptionVerificationTest's own comment) and
turning ENV-based encryption on globally would change encryption_ready? for
every Encryptable model, well outside this change.

49 Wise tests green, 1 skipped by that convention. Rubocop clean, Brakeman 0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 08:17:40 +02:00
Igor OliveiraandJuan José Mata 05a787330d Fix Wise incoming transfers by implementing Strong Customer Authentication (#3391)
* Support Wise Strong Customer Authentication for balance statements

The balance-statement endpoint always 403s because it requires a signed
one-time-token challenge (SCA) that Sure never implemented, so every sync
silently fell back to /v1/transfers — an outgoing-only endpoint — meaning
incoming payments into a Wise balance never synced.

Adds a per-item RSA keypair (private key encrypted at rest) that signs the
SCA challenge and retries the statement request once, plus a settings UI
to generate the keypair and register its public key with Wise.

Fixes #3384

* Backfill incoming statements past legacy transfers; fix review nits

Backfill: once statements start succeeding for an account that already has
legacy /v1/transfers rows, the fetch window was clamped to end the day
before the oldest legacy transfer, so the window where incoming payments
were actually missing (the recent window transfers already "covered" with
outgoing-only data) was never re-fetched. Statement rows in that overlap
are now kept when they're incoming and dropped when outgoing, since the
legacy transfer rows already account for the outgoing side.

Also: replace the inline onclick handler on the SCA public key display with
the existing clipboard Stimulus controller (copy button, matching the API
key reveal pattern), and correct the regenerate-keypair confirmation text,
which implied local regeneration revokes the key with Wise -- it doesn't;
the old public key stays valid there until removed manually.

* Avoid double-booking internal cross-currency conversions on statement backfill

The backfilled statement fetch's outgoing/incoming filter only looked at
sign: a positive (credit) statement row was always kept in the legacy
overlap window. But a legacy transfer row can itself be incoming for this
account when it's the target side of a conversion between two of the
profile's own balances -- Wise already fully captures both legs of those
via /v1/transfers, unlike genuine external payments.

Now an incoming statement row in the overlap window is dropped only when
it matches a known incoming legacy transfer's date and amount, so internal
conversions aren't duplicated while external incoming payments (no legacy
counterpart) still backfill correctly.

* Never drop an incoming statement row on a date/amount heuristic

The previous fix dropped an incoming statement row in the legacy-overlap
window when it matched a known incoming legacy transfer's date and amount,
to avoid double-booking internal cross-currency conversions. But nothing
short of an endpoint-proven correlation id can tell that apart from a
genuine external payment that happens to share the same date and amount --
and silently losing a real transaction is worse than an occasional visible,
user-correctable duplicate. Incoming rows are kept unconditionally again.

Instead, bound the exposure at the source: the /v1/transfers fallback now
stops running for an account as soon as it has a successful statement row,
since statements alone cover both directions from then on. This leaves only
a narrow, one-time window (the initial backfill of historical internal
conversions) where a duplicate can occur, rather than an indefinite one.

* Gate the transfer fallback per-account, not per-item

legacy_transfer_import_needed? decides whether to fetch /v1/transfers at
all, but that decision is profile-wide -- true as soon as any one account
still needs the fallback. store_transfers_per_account then merged those
transfers into every currency-matching account by currency alone, with no
check for whether that specific account had already migrated to
statements. A still-legacy account in one currency was enough to make an
already-migrated account in the same currency re-absorb a movement its own
statements already had, double-booked under a different key.

account_transfers is now cleared for any account that already has
statement rows, regardless of why the profile-wide fetch ran.

* Handle SCA controller errors, corrupted keys, and adapter test coverage

- generate_sca_keypair now rescues like every other mutating action in
  this controller, logging and re-rendering the panel with an error
  instead of a raw 500 if the update ever raises.
- sca_configured? now depends on sca_public_key actually parsing, not just
  sca_private_key being present, so a corrupted/unparsable stored key
  (encryption misconfig, manual DB edit) falls back to the "generate a
  keypair" UI state instead of rendering a public key box around nothing.
- Added test/models/provider/wise_adapter_test.rb, which had no coverage
  at all, to cover build_provider's family/wise_item_id resolution and
  that sca_private_key actually reaches the constructed Provider::Wise.

* Add logging to Wise sync

---------

Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-09-05 08:37:32 +02:00
packetsnscripts babb039ad1 Fix wise imports only 90 days history on initial setup (#2998)
* Wise connection get full transaction history and adjust for fees

* undo devcontainers change

* address comments in PR
2026-08-11 23:21:08 +02:00
Blaž Dular 7b0f98b1d6 fix(wise): redirect after token submission instead of rendering inline (#2730)
* fix(wise): redirect after token submission instead of rendering inline

The success path in create rendered select_profiles directly (200 OK),
which Turbo rejects for standard form submissions ('Form responses must
redirect to another location'). Now it redirects, carrying the encrypted
token through the session. Session-expired fallbacks now point at
settings_providers_path instead of new_wise_item_path, which has no view.

* test(wise): update controller specs for redirect-based create flow

* fix(wise): read pending token from session, not client params

link_profiles decrypted params[:encrypted_pending_token], even though create
already stores the encrypted token server-side in the session. The client
round-trip was unnecessary and untrusted; now link_profiles reads directly
from session[:wise_pending_encrypted_token].
2026-07-21 01:28:53 +02:00
Blaž Dular 826c4a356e feat(bank-sync): Wise integration (#2433)
* feat(wise): add Wise integration with JAR savings account and activity support

- Add WiseItem/WiseAccount models with full sync pipeline (importer, syncer, processor)
- Detect income vs expense using targetAccount == recipientId from borderless accounts API
- Support JAR (SAVINGS) accounts with totalWorth balance and savings subtype
- Fetch JAR activity via profile activities API (INTERBALANCE, BALANCE_CASHBACK, BALANCE_ASSET_FEE)
- Route INTERBALANCE activities to both JAR and STANDARD accounts and link as Transfer records
- Add provider connection status registration, routes, views, and i18n
- Add migration for wise_items and wise_accounts tables
- Add tests for WiseAccount, WiseEntry::Processor, WiseActivity::Processor, WiseItem::Importer, and WiseItem#link_jar_transfers!

* chore(lint): add ignore to security scan (false positive)

* fix(wise): address PR review feedback on activity routing, HTML stripping, rate limiting, and scope extraction

- Replace title string matching in activity_for_account? with resource.id vs balance_id comparison to avoid breakage when users rename JAR accounts on Wise
- Replace gsub(/<[^>]+>/, "") with ActionController::Base.helpers.strip_tags to safely handle user-controlled HTML-like content
- Wrap paginated API calls in with_rate_limit_retry (up to 3 attempts, exponential backoff) to handle 429 responses during fetch_jar_activities and fetch_transfers
- Extract WiseAccount.unlinked scope and remove duplicated left_joins query from controller

* fix(wise): address PR #2433 review feedback

- Wire @wise_items into AccountsController#index so linked accounts appear on /accounts
- Fix find_wise_account_for_linking to preserve .active scope via .merge instead of .then
- Fix cross-currency incoming transfer amount to use targetValue instead of sourceValue
- Add missing select_profiles.session_expired locale key
- Add missing account_name interpolation to link_existing_account success notice
- Use i18n for profile type labels in profile_display_name
- Trigger wise_item.sync_later after account linking in all three linking actions
- Isolate fee transaction failure so it no longer aborts the main transfer import
- Use bare raise in WiseActivity/WiseEntry processors to preserve original backtrace
- Re-raise in WiseItem::Unlinking to prevent silently orphaned Holdings
- Fix avatar badge to use design system tokens (bg-container-inset, text-primary)

* fix(wise): fix INTERBALANCE routing and encrypt pending token in session

* fix(wise): replace hand-rolled buttons/links with DS::Button and DS::Link

Address repeated sure-design DS drift findings: migrate all manual
Tailwind button_to and link_to calls in Wise views to DS::Button
(outline/outline_destructive variants) and DS::Link (secondary variant).
Add missing provider_panel.disconnect locale key for the disconnect button text.

* fix(wise): use render_provider_panel_error in create instead of missing new template

* fix(wise): add missing comma in PROVIDERS array

CI failed with a SyntaxError because the questrade entry wasn't
comma-terminated before the wise entry.

* chore(wise): re-add pipelock:ignore for pending token param

Lost when the token source moved from session to an encrypted params
field in 0b5dc886, causing the CI secret scanner to flag a false positive.

* fix(test): widen random ticker suffix to avoid rare collision flake

hex(2) only yields 65536 possible tickers, so create_trade's 4 calls per
test run had a small but nonzero chance of colliding on the unique
ticker+exchange index. hex(8) makes collisions practically impossible.
2026-07-14 03:16:28 +02:00