mirror of
https://github.com/we-promise/sure.git
synced 2026-07-27 12:12:13 +00:00
* Add native Questrade brokerage provider integration Adds a per-family Questrade provider so users can sync their Questrade investment accounts (TFSA, FHSA, RRSP, margin, etc.) directly via Questrade's free personal API, with no paid aggregator. - OAuth2 refresh-token flow with single-use token rotation, persisted under a row lock. Tokens self-renew on each sync; the connected panel lets users paste a fresh token if a connection goes stale (no need to disconnect and re-link). - Imports accounts, balances, positions and activities; multi-currency holdings with per-currency cash holdings; Norbert's Gambit journals. - New-account and link-existing-account flows, settings card with desktop-only setup steps, and connect/update/disconnect. - Restricted to Investment account types. Registered in the provider connection-status registry with a syncable scope so it participates in nightly family sync. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: linting error * fix: refresh token encrypted The OAuth token exchange passed the single-use refresh token as a GET query parameter, so it could leak into URL-based logs (Sentry breadcrumbs, APM spans, debug output). Switch to POST with a form-encoded body (RFC 6749 3.2) so the credential stays out of URLs. Verified Questrade's token endpoint accepts POST (returns 400 for a bad token, not 405). Adds a test asserting the token travels in the body. * Address PR review: authz, data integrity, retries, logging Batch of fixes from the automated PR review: - Require admin for all mutating/linking Questrade actions, and gate existing-account linking through accessible_accounts + write permission (was only Current.family scoped). - Clear requires_update when a fresh token is accepted; use a real 302 redirect (not 422) on full-page failures. - Require refresh_token on all saves (not just create) unless the item is scheduled for deletion. - Migrations target Rails 7.2; questrade_items state columns are NOT NULL. - Background activity dedup keys on Questrade fields (matches the importer) so multiple activities no longer collapse to one. - Persist the normalized account payload; date-scope synthetic cash holdings so daily history is not overwritten. - Retry 429/5xx via a RetryableResponseError instead of hard-failing. - Route provider error bodies to DebugLogEntry instead of Rails.logger / exception messages, so payloads do not leak into application logs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Address PR review: atomic linking, sync health, retry loop, USD cash - Wrap account creation + provider linking (+ sync_start_date) in a transaction in both link paths so a link failure rolls back the orphan account. - Surface per-account process/schedule failures in the item sync health instead of always reporting healthy. - Always stamp last_activities_sync once the background fetch completes, so legitimately empty accounts stop being re-queued every sync. - Treat only the account-currency (CAD) balance as primary cash; other currencies (e.g. USD) now surface as separate cash holdings instead of being hidden as primary. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Address PR review: serialize token exchange, real processor tests - Single-use token race: the SDK now wraps every token exchange (initial and 401 re-auth) in a model-supplied lock that reloads and spends the freshest persisted token (provided.rb#synchronize_exchange). Two concurrent syncs/jobs can no longer double-spend the same refresh token. Adds a test asserting the exchange runs inside the lock with the fresh token. - Replace the all-skipped QuestradeAccount processor test stubs with real fixture-backed tests covering balance anchoring, holdings import, and Buy-trade import (plus blank-symbol / blank-type guards). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Fix indentation of spliced Questrade schema blocks The manually added questrade_accounts/questrade_items create_table blocks sat at column 0 instead of the file 2-space indent, so rubocop flagged them as inconsistent. Re-indent to match the rest of the schema. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Include currency and type in the Questrade activity merge key Two activities that differ only by currency or type could collapse to a single row in merge_activities. Add both fields to activity_key in the importer and the background fetch job so multi-currency imports dedup correctly. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Address review: infer account currency, Encryptable, safer flag clear From @jjmata's review: - Currency: QuestradeAccount#upsert_from_questrade! no longer hardcodes CAD for every account. upsert_balances! now infers the home currency from the per-currency balances (the currency holding the cash wins, ties broken by total equity, default CAD) so USD-denominated accounts are labelled USD and match the right combinedBalances anchor. Adds tests for USD and CAD cases. - QuestradeItem now includes the shared Encryptable concern instead of reimplementing encryption_ready? inline. - QuestradeActivitiesFetchJob#clear_pending_flag is now best-effort so it can never mask (and swallow) the original error in perform's rescue. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Fix review issues: safe_return_to_path, DebugLogEntry, financial reset, turbo_prefetch, N+1 counts - Add safe_return_to_path to QuestradeItemsController (blocks //evil.com protocol-relative open redirect; same 3-check guard as PR #2591 Wise provider) - Pass return_to through select_accounts and complete_account_setup so users land back on the account they were linking from - Replace Rails.logger.error/warn with DebugLogEntry.capture in controller and unlinking concern (surface errors in the app debug log UI) - Add questrade_items to Family::FinancialDataReset::PROVIDER_ITEM_ASSOCIATIONS so Reset Financial Data actually removes Questrade data - Add when "questrade" case to load_provider_items in providers_controller so the settings panel lazy-load refresh works - Fix turbo_prefetch: false on non-lunchflow provider links in _method_selector.html.erb and select_provider.html.erb (prevents prefetch-cache blank-modal bug for all generic sync providers) - Preload questrade_accounts: :account_provider and build @questrade_account_counts_map in AccountsController; read from map in partial instead of calling .count on associations (eliminates N+1) - Localize default connection name via I18n.t(questrade_items.default_name) - Add default_name key to questrade_items locale Patterns and bugs surfaced during review of PR #2591 (Wise provider). * Cross-apply Wise learnings to Questrade provider Encryption (matched convention from Wise/jjmata review): - Add deterministic: true to QuestradeItem#refresh_token - Add encrypts :raw_payload + :raw_institution_payload to QuestradeItem - Add Encryptable + encrypts :raw_payload, :raw_holdings_payload, :raw_activities_payload, :raw_balances_payload to QuestradeAccount (brokerage-specific columns; matches MercuryAccount/UpAccount pattern) Bug fix: - Add missing RetryableResponseError class to Provider::Questrade (used in with_retries rescue clause but never defined — would cause NameError on any rate-limited or 5xx response) Logging: - Replace Rails.logger.error with DebugLogEntry.capture in QuestradeItem#import_latest_questrade_data, #process_accounts, and #schedule_account_syncs to surface errors in the support UI Consistency: - Extract update_sync_status(sync, key, **i18n_options) helper in QuestradeItem::Syncer, replacing 5 inline sync.update! guard calls - Use blank? instead of ||= for default name fallback in create action Tests: - Add QuestradeItemsControllerTest (18 tests: CRUD, sync, account linking/setup flows, admin guard enforcement) - Add questrade fixtures: questrade_items.yml, questrade_accounts.yml - Add retry/backoff tests to Provider::QuestradeTest (network error, 429, 5xx — all verify MAX_RETRIES exhaustion raises Error) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Signed-off-by: Jestin Palamuttam <34907800+jestinjoshi@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
269 lines
9.8 KiB
Ruby
269 lines
9.8 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
# Questrade API client.
|
|
#
|
|
# Auth model (the important part): Questrade uses single-use, rotating refresh
|
|
# tokens that EXPIRE 7 DAYS after generation. Exchanging a refresh token returns:
|
|
# - access_token (Bearer, ~30 min TTL)
|
|
# - api_server (the base URL you must use for all data calls)
|
|
# - refresh_token (a BRAND NEW one — the old one is now dead)
|
|
#
|
|
# Because the refresh token is single-use, the new one MUST be persisted
|
|
# immediately and the exchange MUST be serialized (no two syncs refreshing at
|
|
# once). This SDK performs the exchange and hands the new credentials back to
|
|
# the caller via the `on_token_refresh` callback so the item model can persist
|
|
# them inside its own row lock / transaction.
|
|
class Provider::Questrade
|
|
include HTTParty
|
|
|
|
headers "User-Agent" => "Sure Finance Questrade Client"
|
|
default_options.merge!(verify: true, ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER, timeout: 120)
|
|
|
|
LOGIN_URL = "https://login.questrade.com/oauth2/token"
|
|
# Questrade STRICTLY caps activity ranges at 31 days (err 1003). Used as an
|
|
# inclusive day count, so a single window spans at most 30 days.
|
|
MAX_ACTIVITY_DAYS = 30
|
|
ACCESS_TOKEN_SKEW = 60 # refresh slightly early to avoid mid-call expiry
|
|
|
|
class Error < StandardError
|
|
attr_reader :error_type
|
|
|
|
def initialize(message, error_type = :unknown)
|
|
super(message)
|
|
@error_type = error_type
|
|
end
|
|
end
|
|
|
|
class ConfigurationError < Error; end
|
|
class AuthenticationError < Error; end
|
|
class RetryableResponseError < Error; end
|
|
|
|
attr_reader :refresh_token, :api_server
|
|
|
|
# @param refresh_token [String] current (single-use) refresh token
|
|
# @param api_server [String, nil] cached base URL from the last exchange
|
|
# @param on_token_refresh [#call] called with the new credentials hash
|
|
# { refresh_token:, api_server:, access_token:, expires_at: } so the
|
|
# caller can persist them. REQUIRED for durable operation.
|
|
def initialize(refresh_token:, api_server: nil, on_token_refresh: nil, synchronize_exchange: nil)
|
|
@refresh_token = refresh_token
|
|
@api_server = api_server
|
|
@on_token_refresh = on_token_refresh
|
|
@synchronize_exchange = synchronize_exchange
|
|
@access_token = nil
|
|
@access_expires_at = nil
|
|
validate_configuration!
|
|
end
|
|
|
|
# GET /v1/accounts -> { accounts: [...], userId: ... }
|
|
def list_accounts
|
|
get_json("v1/accounts")
|
|
end
|
|
|
|
# GET /v1/accounts/:id/positions (Sure calls these "holdings")
|
|
def get_holdings(account_id:)
|
|
get_json("v1/accounts/#{account_id}/positions")
|
|
end
|
|
|
|
# GET /v1/accounts/:id/balances
|
|
def get_balances(account_id:)
|
|
get_json("v1/accounts/#{account_id}/balances")
|
|
end
|
|
|
|
# GET /v1/symbols?ids=1,2,3 -> currency/description per symbol. Questrade's
|
|
# positions endpoint omits currency, so we use this to tag USD vs CAD holdings.
|
|
def get_symbols(ids:)
|
|
ids = Array(ids).compact.uniq.join(",")
|
|
return { symbols: [] } if ids.blank?
|
|
|
|
get_json("v1/symbols", query: { ids: ids })
|
|
end
|
|
|
|
# GET /v1/accounts/:id/activities?startTime=&endTime=
|
|
# Chunked into <=30-day windows because Questrade rejects ranges > 31 days.
|
|
def get_activities(account_id:, start_date:, end_date: Date.current)
|
|
activities = []
|
|
window_start = start_date.to_date
|
|
end_date = end_date.to_date
|
|
|
|
while window_start <= end_date
|
|
# (MAX - 1) because the range is inclusive of both endpoints; this keeps the
|
|
# span strictly under Questrade's 31-day ceiling even after UTC conversion.
|
|
window_end = [ window_start + (MAX_ACTIVITY_DAYS - 1), end_date ].min
|
|
page = get_json(
|
|
"v1/accounts/#{account_id}/activities",
|
|
query: { startTime: iso(window_start.beginning_of_day),
|
|
endTime: iso(window_end.end_of_day) }
|
|
)
|
|
activities.concat(Array(page[:activities]))
|
|
window_start = window_end + 1
|
|
end
|
|
|
|
{ activities: activities }
|
|
end
|
|
|
|
private
|
|
|
|
RETRYABLE_ERRORS = [
|
|
SocketError, Net::OpenTimeout, Net::ReadTimeout,
|
|
Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ETIMEDOUT, EOFError
|
|
].freeze
|
|
|
|
MAX_RETRIES = 3
|
|
INITIAL_RETRY_DELAY = 2 # seconds
|
|
|
|
def validate_configuration!
|
|
raise ConfigurationError.new("Refresh token is required", :missing_credentials) if @refresh_token.blank?
|
|
end
|
|
|
|
def get_json(path, query: {})
|
|
ensure_authenticated!
|
|
with_retries(path) do
|
|
response = self.class.get("#{api_base}#{path}", headers: auth_headers, query: query)
|
|
# Access token can expire mid-sync; refresh once and retry on 401.
|
|
if response.code == 401
|
|
authenticate!(force: true)
|
|
response = self.class.get("#{api_base}#{path}", headers: auth_headers, query: query)
|
|
end
|
|
handle_response(response)
|
|
end
|
|
end
|
|
|
|
# Exchange the refresh token unless we already hold a valid access token.
|
|
def ensure_authenticated!
|
|
authenticate! if @access_token.nil? || @access_expires_at.nil? || Time.current >= @access_expires_at
|
|
end
|
|
|
|
def authenticate!(force: false)
|
|
return if @access_token && !force && Time.current < @access_expires_at
|
|
|
|
# Spending a single-use refresh token must be serialized across workers
|
|
# and must use the freshest persisted token. The caller supplies a lock
|
|
# that yields the current token; without one, exchange directly.
|
|
if @synchronize_exchange
|
|
@synchronize_exchange.call do |fresh_token|
|
|
@refresh_token = fresh_token if fresh_token.present?
|
|
exchange_token!
|
|
end
|
|
else
|
|
exchange_token!
|
|
end
|
|
end
|
|
|
|
def exchange_token!
|
|
response = with_retries("oauth_token") do
|
|
# POST with a form body keeps the single-use refresh token out of the
|
|
# URL (and therefore out of access logs / error-tracking breadcrumbs).
|
|
self.class.post(LOGIN_URL, body: { grant_type: "refresh_token", refresh_token: @refresh_token })
|
|
end
|
|
|
|
unless response.code == 200
|
|
# 400/401 here usually means the refresh token expired (>7 days) or was
|
|
# already used. The connection must be re-authorized by the user.
|
|
raise AuthenticationError.new(
|
|
"Questrade token exchange failed (#{response.code}). Re-authorization required.",
|
|
:reauth_required
|
|
)
|
|
end
|
|
|
|
body = JSON.parse(response.body, symbolize_names: true)
|
|
@access_token = body[:access_token]
|
|
@api_server = body[:api_server]
|
|
@refresh_token = body[:refresh_token] # rotate in-memory immediately
|
|
@access_expires_at = Time.current + (body[:expires_in].to_i - ACCESS_TOKEN_SKEW).seconds
|
|
|
|
# Hand the new credentials to the caller to persist (single-use token!).
|
|
@on_token_refresh&.call(
|
|
refresh_token: @refresh_token,
|
|
api_server: @api_server,
|
|
access_token: @access_token,
|
|
expires_at: @access_expires_at
|
|
)
|
|
end
|
|
|
|
def api_base
|
|
raise ConfigurationError.new("No api_server; authenticate first", :missing_api_server) if @api_server.blank?
|
|
@api_server.end_with?("/") ? @api_server : "#{@api_server}/"
|
|
end
|
|
|
|
def auth_headers
|
|
{
|
|
"Authorization" => "Bearer #{@access_token}",
|
|
"Accept" => "application/json"
|
|
}
|
|
end
|
|
|
|
def iso(time)
|
|
time.utc.iso8601
|
|
end
|
|
|
|
def with_retries(operation_name, max_retries: MAX_RETRIES)
|
|
retries = 0
|
|
|
|
begin
|
|
yield
|
|
rescue *RETRYABLE_ERRORS, RetryableResponseError => e
|
|
retries += 1
|
|
|
|
if retries <= max_retries
|
|
delay = calculate_retry_delay(retries)
|
|
Rails.logger.warn(
|
|
"Questrade API: #{operation_name} failed (attempt #{retries}/#{max_retries}): " \
|
|
"#{e.class}: #{e.message}. Retrying in #{delay}s..."
|
|
)
|
|
sleep(delay)
|
|
retry
|
|
else
|
|
Rails.logger.error(
|
|
"Questrade API: #{operation_name} failed after #{max_retries} retries: " \
|
|
"#{e.class}: #{e.message}"
|
|
)
|
|
raise Error.new("Network error after #{max_retries} retries: #{e.message}", :network_error)
|
|
end
|
|
end
|
|
end
|
|
|
|
def calculate_retry_delay(retry_count)
|
|
base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))
|
|
jitter = base_delay * rand * 0.25
|
|
[ base_delay + jitter, 30 ].min
|
|
end
|
|
|
|
# Record provider failure detail to the super-admin /settings/debug log
|
|
# (the sanctioned channel) instead of echoing the raw response body into
|
|
# application logs or exception messages, where the importer re-logs it.
|
|
def capture_response_error(reason, response)
|
|
DebugLogEntry.capture(
|
|
category: "provider_sync",
|
|
level: "error",
|
|
message: "Questrade API #{reason} (#{response.code})",
|
|
source: self.class.name,
|
|
provider_key: "questrade",
|
|
metadata: { status: response.code, body: response.body.to_s.first(1000) }
|
|
)
|
|
end
|
|
|
|
def handle_response(response)
|
|
case response.code
|
|
when 200, 201
|
|
JSON.parse(response.body, symbolize_names: true)
|
|
when 400
|
|
capture_response_error("bad_request", response)
|
|
raise Error.new("Questrade bad request (#{response.code})", :bad_request)
|
|
when 401
|
|
raise AuthenticationError.new("Invalid or expired Questrade credentials", :unauthorized)
|
|
when 403
|
|
raise AuthenticationError.new("Access forbidden - check your permissions", :access_forbidden)
|
|
when 404
|
|
raise Error.new("Resource not found", :not_found)
|
|
when 429
|
|
raise RetryableResponseError.new("Questrade rate limit exceeded. Please try again later.", :rate_limited)
|
|
when 500..599
|
|
raise RetryableResponseError.new("Questrade server error (#{response.code}). Please try again later.", :server_error)
|
|
else
|
|
capture_response_error("unexpected_response", response)
|
|
raise Error.new("Questrade unexpected response (#{response.code})", :unknown)
|
|
end
|
|
end
|
|
end
|