The personal finance app for everyone (by everyone)
Ruby
SnapTrade: sync with a Personal API key when no OAuth app is configured (#5032)
arnaurodondevad7005406c64
diff --git a/.env.local.example b/.env.local.exampleindex 0cca79bb3f..97e2daa184 100644--- a/.env.local.example+++ b/.env.local.example@@ -12,6 +12,10 @@ SIMPLEFIN_DEBUG_RAW=false# SIMPLEFIN_INCLUDE_PENDING: when truthy, forces `pending=1` on SimpleFIN fetches when caller doesn't specify `pending:`SIMPLEFIN_INCLUDE_PENDING=false+# SnapTrade: leave both unset to connect your own brokerage accounts with a free+# SnapTrade Personal API key (client ID + consumer key), entered per family in+# Settings > Providers > SnapTrade. Set them to use an OAuth app instead.+## SnapTrade OAuth app (register one at https://dashboard.snaptrade.com).# The client ID on its own enables the device code flow: users confirm a short# code on SnapTrade, no redirect URI needed.diff --git a/app/controllers/snaptrade_items_controller.rb b/app/controllers/snaptrade_items_controller.rbindex 84ae90774a..c2053d90a8 100644--- a/app/controllers/snaptrade_items_controller.rb+++ b/app/controllers/snaptrade_items_controller.rb@@ -16,7 +16,7 @@ class SnaptradeItemsController < ApplicationController].freezebefore_action :set_snaptrade_item, only: [ :show, :destroy, :sync, :connect, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :complete_oauth_device_flow ]- before_action :require_admin!, only: [ :destroy, :sync, :connect, :callback, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :oauth_authorize, :oauth_callback, :oauth_device_authorize, :start_oauth_device_flow, :complete_oauth_device_flow, :preload_accounts, :select_accounts, :select_existing_account, :link_existing_account ]+ before_action :require_admin!, only: [ :destroy, :sync, :connect, :callback, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :oauth_authorize, :oauth_callback, :oauth_device_authorize, :start_oauth_device_flow, :complete_oauth_device_flow, :personal_key, :preload_accounts, :select_accounts, :select_existing_account, :link_existing_account ]def index@snaptrade_items = Current.family.snaptrade_items.ordered@@ -95,7 +95,7 @@ class SnaptradeItemsController < ApplicationControllerlatest_sync = @snaptrade_item.syncs.ordered.firstshould_sync = latest_sync.nil? || !latest_sync.completed?- if @snaptrade_item.oauth_configured? && no_accounts && !@snaptrade_item.syncing? && should_sync+ if @snaptrade_item.credentials_configured? && no_accounts && !@snaptrade_item.syncing? && should_sync@snaptrade_item.sync_laterend@@ -370,6 +370,26 @@ class SnaptradeItemsController < ApplicationControllerrender :oauth_device_flow, status: :unprocessable_entityend+ # Save a SnapTrade Personal API key (clientId + consumerKey) on the family's+ # item. Personal keys come with their own SnapTrade user, so there is nothing+ # to register: the item can sync as soon as the key is stored. Only offered+ # when the instance has no OAuth app.+ def personal_key+ return head :not_found if Provider::Snaptrade.oauth_configured?++ snaptrade_item = current_snaptrade_item || Current.family.snaptrade_items.build(name: t("snaptrade_items.default_name"))+ client_id, consumer_key = personal_key_params.values_at(:client_id, :consumer_key).map { |value| value.to_s.strip }++ if client_id.blank? || consumer_key.blank?+ return render_provider_panel("snaptrade", alert: t(".missing_fields"))+ end++ snaptrade_item.apply_personal_key!(client_id: client_id, consumer_key: consumer_key)+ snaptrade_item.sync_later_with_follow_up++ render_provider_panel("snaptrade", notice: t(".success"))+ end+# Delete a brokerage connectiondef delete_connectionauthorization_id = params[:authorization_id]@@ -428,7 +448,7 @@ class SnaptradeItemsController < ApplicationControllerreturnend- if snaptrade_item.oauth_configured?+ if snaptrade_item.credentials_configured?snaptrade_item.sync_later_with_follow_upredirect_to setup_accounts_snaptrade_item_path(snaptrade_item)else@@ -446,7 +466,7 @@ class SnaptradeItemsController < ApplicationControllerreturnend- if snaptrade_item.oauth_configured?+ if snaptrade_item.credentials_configured?redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: @accountable_type, return_to: @return_to)elseredirect_to helpers.snaptrade_authorize_path(item_id: snaptrade_item.id, accountable_type: @accountable_type, return_to: @return_to)@@ -512,6 +532,10 @@ class SnaptradeItemsController < ApplicationControlleractive_items.ordered.firstend+ def personal_key_params+ params.require(:snaptrade_item).permit(:client_id, :consumer_key)+ end+def assign_device_flow_context@return_to = params[:return_to]@accountable_type = params[:accountable_type]diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rbindex ed21543d52..05ded4b7d3 100644--- a/app/helpers/settings_helper.rb+++ b/app/helpers/settings_helper.rb@@ -116,7 +116,7 @@ module SettingsHelperreturn { status: :off } unless @trading212_items&.any?sync_based_summary(key)when "snaptrade"- configured_item = @snaptrade_items&.find(&:oauth_configured?)+ configured_item = @snaptrade_items&.find(&:credentials_configured?)return { status: :off } unless configured_itemsync_based_summary(key)when "ibkr"diff --git a/app/helpers/snaptrade_items_helper.rb b/app/helpers/snaptrade_items_helper.rbindex 38d3a1c198..f429d68988 100644--- a/app/helpers/snaptrade_items_helper.rb+++ b/app/helpers/snaptrade_items_helper.rb@@ -5,8 +5,11 @@ module SnaptradeItemsHelper# what the deployment can run: the browser redirect needs a confidential# client (client secret) and a registered redirect URI, while the device flow# needs only the public client id. Prefer the redirect when it is available,- # since it is the shorter path for the user.+ # since it is the shorter path for the user. Without an OAuth app, the only+ # way to authorize is a Personal API key, entered in the provider panel.def snaptrade_authorize_path(item_id: nil, accountable_type: nil, return_to: nil)+ return settings_providers_path unless Provider::Snaptrade.oauth_configured?+query = {item_id: item_id.presence,accountable_type: accountable_type.presence,@@ -24,6 +27,8 @@ module SnaptradeItemsHelper# cannot render inside a Turbo frame; the device flow is a page we render# ourselves, so it belongs in the drawer.def snaptrade_authorize_frame+ return "_top" unless Provider::Snaptrade.oauth_configured?+Provider::Snaptrade.authorization_code_configured? ? "_top" : "drawer"endenddiff --git a/app/jobs/snaptrade_activities_fetch_job.rb b/app/jobs/snaptrade_activities_fetch_job.rbindex a0d45e3e86..50f20a98a4 100644--- a/app/jobs/snaptrade_activities_fetch_job.rb+++ b/app/jobs/snaptrade_activities_fetch_job.rb@@ -18,7 +18,8 @@ class SnaptradeActivitiesFetchJob < ApplicationJobon_conflict: :log# Configuration for retry behavior- RETRY_DELAY = 10.seconds+ # SnapTrade asks to poll an account no more than every 15 seconds.+ RETRY_DELAY = 15.secondsMAX_RETRIES = 6def perform(snaptrade_account, start_date:, end_date: nil, retry_count: 0)@@ -40,8 +41,15 @@ class SnaptradeActivitiesFetchJob < ApplicationJobreturnend- # Fetch activities from API- activities_data = fetch_activities(snaptrade_account, provider, start_date, end_date)+ # Fetch activities from API. Over the rate limit, retry on the schedule+ # below like "no activities yet", but remember why for the last attempt.+ rate_limited = false+ activities_data = begin+ fetch_activities(snaptrade_account, provider, start_date, end_date)+ rescue Provider::Snaptrade::RateLimitError+ rate_limited = true+ []+ endif activities_data.any?Rails.logger.info(@@ -68,6 +76,25 @@ class SnaptradeActivitiesFetchJob < ApplicationJobend_date: end_date,retry_count: retry_count + 1)+ elsif rate_limited+ # Still rate limited: activities are missing, not absent, so record it+ # for support before clearing the flag.+ Rails.logger.error(+ "SnaptradeActivitiesFetchJob - Max retries reached for account #{snaptrade_account.id} while rate limited"+ )+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "error",+ message: "SnapTrade activities fetch was still rate limited after #{MAX_RETRIES} retries",+ source: self.class.name,+ provider_key: "snaptrade",+ family: snaptrade_item.family,+ account_provider: snaptrade_account.account_provider,+ metadata: { snaptrade_account_id: snaptrade_account.id, start_date: start_date.to_s, end_date: end_date.to_s }+ )++ snaptrade_account.update!(activities_fetch_pending: false)+ snaptrade_item.broadcast_sync_completeelseRails.logger.warn("SnaptradeActivitiesFetchJob - Max retries reached for account #{snaptrade_account.id}, " \diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rbindex b3542eb4b1..a8d0a3aa18 100644--- a/app/models/provider/snaptrade.rb+++ b/app/models/provider/snaptrade.rb@@ -1,4 +1,5 @@-# SnapTrade API client using SnapTrade OAuth apps (pre-release feature).+# SnapTrade API client: SnapTrade OAuth apps (pre-release feature) or a+# SnapTrade Personal API key.## Auth model:# - Instance admin registers an OAuth app on dashboard.snaptrade.com and sets@@ -13,6 +14,13 @@# SnaptradeItem by #apply_oauth_tokens!.# - Data calls send Authorization: Bearer <access_token>. The SnapTrade user# is implicit in the token; there is no userId/userSecret.+#+# Personal API key mode (an item with client_id + consumer_key and no OAuth+# token): a SnapTrade Personal key is its own user, so data calls are signed+# with the consumer key instead (clientId + timestamp query params and a+# Signature header) and still carry no userId/userSecret. See+# https://docs.snaptrade.com/docs/authentication-methods and+# https://docs.snaptrade.com/docs/request-signatures.class Provider::Snaptradeclass Error < StandardError; end# `oauth_error` carries the machine-readable `error` code from an OAuth error@@ -38,6 +46,7 @@ class Provider::Snaptrade@response_body = response_bodyendend+ class RateLimitError < ApiError; endMAX_RETRIES = 3INITIAL_RETRY_DELAY = 2 # seconds@@ -362,6 +371,13 @@ class Provider::Snaptradedef initialize(snaptrade_item)raise ConfigurationError, "snaptrade_item is required" if snaptrade_item.nil?@snaptrade_item = snaptrade_item+ @rate_limit_errors = {}+ end++ # Set once a Personal key request hits the rate limit (10 requests a minute+ # per account); later calls for that account raise it without a request.+ def rate_limit_error+ @rate_limit_errors.values.firstend# --- Data methods. The SnapTrade user is implicit in the Bearer token. ---@@ -498,6 +514,8 @@ class Provider::Snaptradeenddef request_json(method, path, params: {}, body: nil, retry_on_auth_failure: true)+ return signed_request_json(method, path, params: params, body: body) if personal_key?+ensure_fresh_token!operation = "#{method.to_s.upcase} #{path}"used_access_token = snaptrade_item.oauth_access_token@@ -526,6 +544,54 @@ class Provider::Snaptradehandle_response(response, operation)end+ # OAuth wins when both are present, so an authorized item never changes mode.+ def personal_key?+ snaptrade_item.oauth_access_token.blank? && snaptrade_item.personal_key_configured?+ end++ # Personal key request. The signature covers the path, the query string and+ # the body exactly as sent, so both are built here rather than by Faraday:+ # the query with Faraday's own (sorting) params encoder, so re-encoding the+ # URL leaves it byte-for-byte unchanged, and the body as the same canonical+ # JSON that is signed. Each attempt is signed afresh, since the timestamp is+ # part of the signature. No refresh-and-retry: a 401/403 means the key itself+ # was rejected, which handle_response turns into requires_update.+ def signed_request_json(method, path, params:, body:)+ bucket = path[%r{/accounts/([^/]+)}, 1]+ raise @rate_limit_errors[bucket] if @rate_limit_errors[bucket]++ operation = "#{method.to_s.upcase} #{path}"+ content = body.presence && body.transform_keys(&:to_s).sort.to_h++ retrier = method == :get ? method(:with_retries) : method(:without_retry)+ response = retrier.call(operation) do+ query = Faraday::Utils.default_params_encoder.encode(+ params.to_h.merge(clientId: snaptrade_item.client_id, timestamp: Time.current.to_i)+ )+ signature = request_signature(path: path, query: query, content: content)+ api_connection.public_send(method, "#{API_BASE_URL}#{path}?#{query}") do |request|+ request.headers["Signature"] = signature+ request.headers["Accept"] = "application/json"+ if content+ request.headers["Content-Type"] = "application/json"+ request.body = JSON.generate(content)+ end+ end+ end++ handle_response(response, operation)+ rescue RateLimitError => e+ raise @rate_limit_errors[bucket] = e+ end++ # HMAC-SHA256 (keyed with the consumer key, Base64) of the JSON object+ # {content, path, query} with keys sorted and no whitespace (the bodies we+ # send are flat). content is null for a request without a body.+ def request_signature(path:, query:, content:)+ message = JSON.generate({ content: content, path: path, query: query })+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", snaptrade_item.consumer_key.to_s, message))+ end+def ensure_fresh_token!raise AuthenticationError, "SnapTrade item has no access token" if snaptrade_item.oauth_access_token.blank?@@ -621,8 +687,8 @@ class Provider::Snaptrademark_requires_update!raise AuthenticationError, "Authentication failed (#{operation}): HTTP #{response.status}"when 429- raise ApiError.new("Rate limit exceeded. Please try again later.",- status_code: response.status, response_body: response.body)+ raise RateLimitError.new("Rate limit exceeded. Please try again later.",+ status_code: response.status, response_body: response.body)when 500..599raise ApiError.new("SnapTrade server error (#{response.status}). Please try again later.",status_code: response.status, response_body: response.body)diff --git a/app/models/provider/snaptrade_adapter.rb b/app/models/provider/snaptrade_adapter.rbindex 46db1b64ce..dd8e2c9275 100644--- a/app/models/provider/snaptrade_adapter.rb+++ b/app/models/provider/snaptrade_adapter.rb@@ -40,12 +40,15 @@ class Provider::SnaptradeAdapter < Provider::Base# Build a SnapTrade provider instance for a family's authorized item# @param family [Family] The family to get an authorized item for (required)- # @return [Provider::Snaptrade, nil] Returns nil if OAuth is not configured/authorized+ # @return [Provider::Snaptrade, nil] Returns nil if the family has no authorized itemdef self.build_provider(family: nil)return nil unless family.present?- return nil unless Provider::Snaptrade.oauth_configured?- snaptrade_item = family.snaptrade_items.syncable.first+ # Without an OAuth app an OAuth token cannot be refreshed, so only a+ # Personal-key item can be used.+ items = family.snaptrade_items.syncable+ items = items.where(oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE) unless Provider::Snaptrade.oauth_configured?+ snaptrade_item = items.ordered.firstreturn nil unless snaptrade_itemProvider::Snaptrade.new(snaptrade_item)diff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rbindex 77d6fadf59..b3724531e4 100644--- a/app/models/snaptrade_item.rb+++ b/app/models/snaptrade_item.rb@@ -25,11 +25,15 @@ class SnaptradeItem < ApplicationRecordhas_many :snaptrade_accounts, dependent: :destroyhas_many :linked_accounts, through: :snaptrade_accounts+ # Requests are signed with the stored consumer key instead of a Bearer token.+ PERSONAL_KEY_TOKEN_TYPE = "personal_key".freeze+scope :active, -> { where(scheduled_for_deletion: false) }- # Syncable = active + authorized via OAuth (has an access token).+ # Syncable = active + authorized, via OAuth (has an access token) or a+ # SnapTrade Personal API key (see #personal_key_configured?).# oauth_access_token is non-deterministically encrypted, so it can only be# queried with an IS NULL check (never persisted as "" -- see apply_oauth_tokens!).- scope :syncable, -> { active.where.not(oauth_access_token: nil) }+ scope :syncable, -> { active.where.not(oauth_access_token: nil).or(active.where(oauth_token_type: PERSONAL_KEY_TOKEN_TYPE)) }scope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }@@ -106,12 +110,28 @@ class SnaptradeItem < ApplicationRecordupdate!(oauth_access_token: payload["access_token"],oauth_refresh_token: payload["refresh_token"].presence || oauth_refresh_token,- oauth_token_type: payload["token_type"].presence || oauth_token_type,+ oauth_token_type: payload["token_type"].presence || (oauth_token_type unless personal_key_configured?),oauth_scope: payload["scope"].presence || oauth_scope,oauth_token_expires_at: payload["expires_in"].present? ? Time.current + payload["expires_in"].to_i.seconds : oauth_token_expires_at)end+ # Switch the item to a SnapTrade Personal API key. Any OAuth token or legacy+ # user is cleared, so the key is what signs requests from now on.+ def apply_personal_key!(client_id:, consumer_key:)+ update!(+ client_id: client_id,+ consumer_key: consumer_key,+ oauth_access_token: nil,+ oauth_refresh_token: nil,+ oauth_token_expires_at: nil,+ oauth_token_type: PERSONAL_KEY_TOKEN_TYPE,+ snaptrade_user_id: nil,+ snaptrade_user_secret: nil,+ status: :good+ )+ end+def has_completed_initial_setup?# Setup is complete if we have any linked accountsaccounts.any?@@ -173,10 +193,21 @@ class SnaptradeItem < ApplicationRecorddef oauth_configured?oauth_access_token.present?end- alias_method :credentials_configured?, :oauth_configured?++ # A SnapTrade Personal API key: the family's own clientId + consumerKey, which+ # SnapTrade provisions together with its user, so there is no userId or+ # userSecret. Marked explicitly when the key is saved, because items from the+ # pre-OAuth integration also stored client_id and consumer_key.+ def personal_key_configured?+ oauth_token_type == PERSONAL_KEY_TOKEN_TYPE+ end++ def credentials_configured?+ oauth_configured? || personal_key_configured?+ enddef fully_configured?- oauth_configured?+ credentials_configured?end# Override Syncable#syncing? to also show syncing state when activities are beingdiff --git a/app/models/snaptrade_item/importer.rb b/app/models/snaptrade_item/importer.rbindex b4f0f5123f..540165904d 100644--- a/app/models/snaptrade_item/importer.rb+++ b/app/models/snaptrade_item/importer.rb@@ -36,6 +36,8 @@ class SnaptradeItem::Importerendsnaptrade_item.upsert_snaptrade_snapshot!(stats)+ # A Personal key hit its rate limit: fail this sync, the next one resumes.+ raise snaptrade_provider.rate_limit_error if snaptrade_provider.rate_limit_errorrescue Provider::Snaptrade::AuthenticationError => esnaptrade_item.update!(status: :requires_update)raise@@ -215,7 +217,7 @@ class SnaptradeItem::Importer# cleared here. Active Job raises some enqueue failures and reports# an adapter's EnqueueError by returning false.begin- queued = SnaptradeActivitiesFetchJob.set(wait: 10.seconds).perform_later(+ queued = SnaptradeActivitiesFetchJob.set(wait: SnaptradeActivitiesFetchJob::RETRY_DELAY).perform_later(snaptrade_account,start_date: start_date)diff --git a/app/models/snaptrade_item/provided.rb b/app/models/snaptrade_item/provided.rbindex 0718248cbb..cfce0ee025 100644--- a/app/models/snaptrade_item/provided.rb+++ b/app/models/snaptrade_item/provided.rb@@ -6,7 +6,7 @@ module SnaptradeItem::Providedenddef snaptrade_provider- return nil unless oauth_configured?+ return nil unless credentials_configured?Provider::Snaptrade.new(self)enddiff --git a/app/models/snaptrade_item/syncer.rb b/app/models/snaptrade_item/syncer.rbindex 02118f9e82..86ed7dee78 100644--- a/app/models/snaptrade_item/syncer.rb+++ b/app/models/snaptrade_item/syncer.rb@@ -11,7 +11,7 @@ class SnaptradeItem::SyncerRails.logger.info "SnaptradeItem::Syncer - Starting sync for item #{snaptrade_item.id}"# Verify the item is authorized- unless snaptrade_item.oauth_configured?+ unless snaptrade_item.credentials_configured?raise StandardError, "SnapTrade is not authorized"enddiff --git a/app/views/settings/providers/_snaptrade_credential_card.html.erb b/app/views/settings/providers/_snaptrade_credential_card.html.erbnew file mode 100644index 0000000000..5514b065c0--- /dev/null+++ b/app/views/settings/providers/_snaptrade_credential_card.html.erb@@ -0,0 +1,15 @@+<%# locals: (title:, description:) %>+<%# How this instance authorizes SnapTrade: heading, status line, then the action(s) passed as the block. %>+<div class="bg-surface-inset rounded-xl p-4 space-y-3">+ <div class="flex items-start gap-3">+ <span class="w-9 h-9 rounded-lg bg-success/10 flex items-center justify-center shrink-0">+ <%= icon "key-round", class: "w-4 h-4 text-success" %>+ </span>+ <div class="min-w-0">+ <p class="text-sm font-medium text-primary"><%= title %></p>+ <p class="text-sm text-secondary"><%= description %></p>+ </div>+ </div>++ <%= yield %>+</div>diff --git a/app/views/settings/providers/_snaptrade_panel.html.erb b/app/views/settings/providers/_snaptrade_panel.html.erbindex 8190de2d03..c2ab788dcb 100644--- a/app/views/settings/providers/_snaptrade_panel.html.erb+++ b/app/views/settings/providers/_snaptrade_panel.html.erb@@ -8,7 +8,10 @@<%items = local_assigns[:snaptrade_items] || @snaptrade_items || Current.family.snaptrade_items.active.ordered- snaptrade_item = items.reject(&:scheduled_for_deletion?).first+ # Same item SnaptradeItemsController#current_snaptrade_item acts on: the+ # newest authorized one, else the newest.+ active_items = items.reject(&:scheduled_for_deletion?)+ snaptrade_item = active_items.find(&:credentials_configured?) || active_items.firstoauth_env_configured = Provider::Snaptrade.oauth_configured?redirect_flow_available = Provider::Snaptrade.authorization_code_configured?oauth_active = snaptrade_item&.oauth_token_active?@@ -16,6 +19,34 @@%><% if !oauth_env_configured %>+ <%# Without an OAuth app, a SnapTrade Personal API key (the family's own %>+ <%# clientId + consumerKey) is how this instance reads SnapTrade data. %>+ <%= render layout: "settings/providers/snaptrade_credential_card",+ locals: {+ title: t("providers.snaptrade.personal_key_title"),+ description: t("providers.snaptrade.personal_key_description_html").html_safe+ } do %>+ <%= styled_form_with url: personal_key_snaptrade_items_path,+ scope: :snaptrade_item,+ method: :post,+ data: { turbo: true },+ class: "space-y-3" do |form| %>+ <%= form.text_field :client_id,+ label: t("providers.snaptrade.personal_key_client_id_label"),+ autocomplete: "off",+ value: nil %>++ <%= form.text_field :consumer_key,+ label: t("providers.snaptrade.personal_key_consumer_key_label"),+ type: :password,+ autocomplete: "off",+ value: nil %>++ <%= form.submit t("providers.snaptrade.personal_key_save_button") %>+ <% end %>+ <% end %>++ <p class="text-sm text-secondary"><%= t("providers.snaptrade.oauth_alternative") %></p><%= render "settings/providers/setup_steps",steps: [t("providers.snaptrade.oauth_setup_step_1_html").html_safe,@@ -23,25 +54,19 @@t("providers.snaptrade.oauth_setup_step_3")] %><% else %>- <div class="bg-surface-inset rounded-xl p-4 space-y-3">- <div class="flex items-start gap-3">- <span class="w-9 h-9 rounded-lg bg-success/10 flex items-center justify-center shrink-0">- <%= icon "key-round", class: "w-4 h-4 text-success" %>- </span>- <div class="min-w-0">- <p class="text-sm font-medium text-primary"><%= t("providers.snaptrade.oauth_title") %></p>- <p class="text-sm text-secondary">- <% if oauth_active %>- <%= t("providers.snaptrade.oauth_status_authorized") %>- <% elsif redirect_flow_available %>- <%= t("providers.snaptrade.oauth_status_ready") %>- <% else %>- <%= t("providers.snaptrade.oauth_status_ready_device") %>- <% end %>- </p>- </div>- </div>-+ <%+ oauth_status = if oauth_active+ t("providers.snaptrade.oauth_status_authorized")+ elsif snaptrade_item&.personal_key_configured? && !snaptrade_item.requires_update?+ t("providers.snaptrade.oauth_status_personal_key")+ elsif redirect_flow_available+ t("providers.snaptrade.oauth_status_ready")+ else+ t("providers.snaptrade.oauth_status_ready_device")+ end+ %>+ <%= render layout: "settings/providers/snaptrade_credential_card",+ locals: { title: t("providers.snaptrade.oauth_title"), description: oauth_status } do %><%# Both grants end with the same access token; which ones are offered %><%# depends only on what this deployment configured. %><% if redirect_flow_available %>@@ -71,9 +96,13 @@frame: :drawer) %><% end %>- </div>+ <% end %>+ <% end %>- <% if snaptrade_item&.persisted? && snaptrade_item.oauth_configured? %>+ <%# An OAuth token needs the instance's OAuth app to keep working, so it only %>+ <%# lists connections while that app is configured. A Personal key carries %>+ <%# its own credentials and lists them either way. %>+ <% if snaptrade_item&.persisted? && (snaptrade_item.personal_key_configured? || (oauth_env_configured && snaptrade_item.oauth_configured?)) %><div class="border-t border-primary pt-4 mt-4"><%# "Manage Connections" in the item menu links here with ?manage=1. %><%# The row's auto-open reads and drops it, so open from the server. %>@@ -115,5 +144,4 @@<% end %></div><% end %>- <% end %></div>diff --git a/app/views/snaptrade_items/_snaptrade_item.html.erb b/app/views/snaptrade_items/_snaptrade_item.html.erbindex 07a16bf748..c319744345 100644--- a/app/views/snaptrade_items/_snaptrade_item.html.erb+++ b/app/views/snaptrade_items/_snaptrade_item.html.erb@@ -2,7 +2,7 @@<%= tag.div id: dom_id(snaptrade_item) do %><% unlinked_count = snaptrade_item.unlinked_accounts_count %>- <% snaptrade_registered = snaptrade_item.oauth_configured? %>+ <% snaptrade_registered = snaptrade_item.credentials_configured? %><% brokerage_connect_href = snaptrade_registered ? connect_snaptrade_item_path(snaptrade_item) : snaptrade_authorize_path(item_id: snaptrade_item.id) %><% brokerage_connect_frame = snaptrade_registered ? "_top" : snaptrade_authorize_frame %><% reconnect_href = snaptrade_authorize_path(item_id: snaptrade_item.id) %>diff --git a/app/views/snaptrade_items/setup_accounts.html.erb b/app/views/snaptrade_items/setup_accounts.html.erbindex b74054b78b..1410356a3d 100644--- a/app/views/snaptrade_items/setup_accounts.html.erb+++ b/app/views/snaptrade_items/setup_accounts.html.erb@@ -71,7 +71,7 @@</div><div class="flex gap-3 justify-center"><%- brokerage_connect_href = if @snaptrade_item.oauth_configured?+ brokerage_connect_href = if @snaptrade_item.credentials_configured?connect_snaptrade_item_path(@snaptrade_item,return_to: "setup_accounts",@@ -84,7 +84,7 @@return_to: params[:return_to])end- brokerage_connect_frame = @snaptrade_item.oauth_configured? ? "_top" : snaptrade_authorize_frame+ brokerage_connect_frame = @snaptrade_item.credentials_configured? ? "_top" : snaptrade_authorize_frame%><%= render DS::Link.new(text: t("snaptrade_items.setup_accounts.try_again", default: "Connect Brokerage"),diff --git a/config/locales/views/snaptrade_items/en.yml b/config/locales/views/snaptrade_items/en.ymlindex be225dee39..d77a3ff09f 100644--- a/config/locales/views/snaptrade_items/en.yml+++ b/config/locales/views/snaptrade_items/en.yml@@ -41,6 +41,9 @@ en:missing_client_id: "SnapTrade OAuth is not configured. Add SNAPTRADE_OAUTH_CLIENT_ID to .env.local, restart the app, then try again."start_oauth_device_flow:failed: "Unable to start SnapTrade device authorization. Please try again."+ personal_key:+ success: "SnapTrade Personal API key saved. Syncing your accounts..."+ missing_fields: "Enter both the SnapTrade client ID and consumer key."complete_oauth_device_flow:success: "SnapTrade authorization complete."device_code_required: "No SnapTrade device authorization is in progress for this connection. Start it again to get a new code."@@ -145,10 +148,17 @@ en:oauth_setup_step_2_html: "For the browser flow only: add this app's callback URL (<code>%{callback_url}</code>) as a registered redirect URI"oauth_setup_step_3: "Set SNAPTRADE_OAUTH_CLIENT_ID in your environment and restart. That alone enables the device code flow; add SNAPTRADE_OAUTH_CLIENT_SECRET for the browser flow too"free_tier_warning: "SnapTrade's free tier covers 20 brokerage connections."+ personal_key_title: "SnapTrade Personal API key"+ personal_key_description_html: "Use the free Personal key for your own brokerage accounts. Create it at <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline\">dashboard.snaptrade.com</a> and paste the client ID and consumer key here."+ personal_key_client_id_label: "Client ID"+ personal_key_consumer_key_label: "Consumer key"+ personal_key_save_button: "Save key"+ oauth_alternative: "Running Sure for other people? Register a SnapTrade OAuth app instead:"oauth_title: "SnapTrade OAuth"oauth_status_ready: "Authorize Sure to read your SnapTrade account data."oauth_status_ready_device: "Authorize Sure with a device code to read your SnapTrade account data."oauth_status_authorized: "Authorized with SnapTrade."+ oauth_status_personal_key: "Syncing with your SnapTrade Personal API key. Authorizing with OAuth switches this connection to OAuth."oauth_connect_button: "Connect with SnapTrade"oauth_device_button: "Use a device code"oauth_reauthorize_button: "Reauthorize"diff --git a/config/routes.rb b/config/routes.rbindex 0185f34293..e51fa41ae5 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -177,6 +177,7 @@ Rails.application.routes.draw doget :oauth_callbackget :oauth_device_authorizepost :start_oauth_device_flow+ post :personal_keyendmember dodiff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rbindex 9db9a1950b..5134467346 100644--- a/test/controllers/settings/providers_controller_test.rb+++ b/test/controllers/settings/providers_controller_test.rb@@ -898,6 +898,32 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestrefute_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready")end+ test "GET index lists SnapTrade connections for an OAuth item only while the OAuth app is configured" do+ item = snaptrade_items(:configured_item)++ Provider::Snaptrade.stubs(:oauth_configured?).returns(false)+ get settings_providers_path(manage: 1)+ assert_response :success+ refute_includes response.body, connections_snaptrade_item_path(item)++ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)+ get settings_providers_path(manage: 1)+ assert_response :success+ assert_includes response.body, connections_snaptrade_item_path(item)+ end++ test "GET connect_form for snaptrade offers the Personal API key form when instance is not configured" do+ Provider::Snaptrade.stubs(:oauth_configured?).returns(false)++ get connect_form_settings_providers_path(provider_key: "snaptrade")++ assert_response :success+ assert_select "form[action='#{personal_key_snaptrade_items_path}']" do+ assert_select "input[name='snaptrade_item[client_id]']"+ assert_select "input[name='snaptrade_item[consumer_key]'][type=password]"+ end+ end+test "GET connect_form for snaptrade shows connect CTA when configured but item is not authorized" dosign_in users(:empty)Provider::Snaptrade.stubs(:oauth_configured?).returns(true)@@ -914,6 +940,34 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestrefute_includes response.body, I18n.t("providers.snaptrade.oauth_reauthorize_button")end+ test "GET connect_form for snaptrade shows a Personal-key item as syncing when an OAuth app is configured later" do+ sign_in users(:empty)+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)+ Provider::Snaptrade.stubs(:authorization_code_configured?).returns(false)+ users(:empty).family.snaptrade_items.create!(name: "SnapTrade").apply_personal_key!(client_id: "c", consumer_key: "k")++ get connect_form_settings_providers_path(provider_key: "snaptrade")++ assert_response :success+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_status_personal_key")+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready_device")+ end++ test "GET connect_form for snaptrade asks to authorize a rejected Personal key once an OAuth app is configured" do+ sign_in users(:empty)+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)+ Provider::Snaptrade.stubs(:authorization_code_configured?).returns(false)+ item = users(:empty).family.snaptrade_items.create!(name: "SnapTrade")+ item.apply_personal_key!(client_id: "c", consumer_key: "k")+ item.update!(status: :requires_update)++ get connect_form_settings_providers_path(provider_key: "snaptrade")++ assert_response :success+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_status_personal_key")+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready_device")+ end+test "GET connect_form for snaptrade offers only the device code without a confidential client" dosign_in users(:empty)Provider::Snaptrade.stubs(:oauth_configured?).returns(true)diff --git a/test/controllers/snaptrade_items_controller_test.rb b/test/controllers/snaptrade_items_controller_test.rbindex 6f2cefcee4..0ced2ba11e 100644--- a/test/controllers/snaptrade_items_controller_test.rb+++ b/test/controllers/snaptrade_items_controller_test.rb@@ -535,6 +535,112 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to setup_accounts_snaptrade_item_path(@snaptrade_item, accountable_type: "Investment", return_to: "/accounts")end+ test "personal_key stores a SnapTrade Personal API key and starts a sync" do+ sign_out+ sign_in @user = users(:empty)+ snaptrade_item = snaptrade_items(:unauthorized_item)+ snaptrade_item.update!(snaptrade_user_id: "legacy-user", snaptrade_user_secret: "legacy-secret")++ with_snaptrade_oauth(nil, nil) do+ assert_difference "Sync.count", 1 do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: " PERSONAL-CLIENT ", consumer_key: "personal-key" } },+ as: :turbo_stream+ end+ end++ assert_response :success+ snaptrade_item.reload+ assert_equal "PERSONAL-CLIENT", snaptrade_item.client_id+ assert_equal "personal-key", snaptrade_item.consumer_key+ assert_nil snaptrade_item.snaptrade_user_secret+ assert snaptrade_item.good?+ assert snaptrade_item.personal_key_configured?+ assert_includes SnaptradeItem.syncable, snaptrade_item+ end++ # The instance dropped its OAuth app: the stale token must not win over the new key.+ test "personal_key switches a formerly OAuth item to the key" do+ @snaptrade_item.update!(oauth_token_expires_at: 1.minute.ago)++ with_snaptrade_oauth(nil, nil) do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: "PERSONAL", consumer_key: "pk" } }, as: :turbo_stream++ signed = stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts\?clientId=PERSONAL&}).to_return(status: 200, body: "[]")+ @snaptrade_item.reload.snaptrade_provider.list_accounts+ assert_requested signed+ end+ end++ test "personal_key re-renders the panel for the item it saved the key on" do+ @user.family.snaptrade_items.create!(name: "Newer, never authorized", created_at: 1.minute.from_now)++ with_snaptrade_oauth(nil, nil) do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: "PERSONAL", consumer_key: "pk" } }, as: :turbo_stream+ end++ assert_response :success+ assert @snaptrade_item.reload.personal_key_configured?+ assert_includes response.body, connections_snaptrade_item_path(@snaptrade_item)+ end++ test "personal_key is refused when an OAuth app is configured" do+ sign_out+ sign_in @user = users(:empty)++ with_snaptrade_oauth("oauth-client", nil) do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: "PERSONAL", consumer_key: "pk" } }, as: :turbo_stream+ end++ assert_response :not_found+ assert_not snaptrade_items(:unauthorized_item).reload.personal_key_configured?+ end++ test "personal_key creates the family's item when it has none" do+ @user.family.snaptrade_items.update_all(scheduled_for_deletion: true)++ with_snaptrade_oauth(nil, nil) do+ assert_difference "@user.family.snaptrade_items.active.count", 1 do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: "PERSONAL-CLIENT", consumer_key: "personal-key" } }+ end+ end++ assert_redirected_to settings_providers_path+ assert @user.family.snaptrade_items.active.sole.personal_key_configured?+ end++ test "personal_key rejects a missing half of the key" do+ sign_out+ sign_in @user = users(:empty)++ with_snaptrade_oauth(nil, nil) do+ assert_no_difference "Sync.count" do+ post personal_key_snaptrade_items_url,+ params: { snaptrade_item: { client_id: "PERSONAL-CLIENT", consumer_key: "" } },+ as: :turbo_stream+ end+ end++ assert_response :unprocessable_entity+ assert_includes response.body, I18n.t("snaptrade_items.personal_key.missing_fields")+ assert_not snaptrade_items(:unauthorized_item).reload.personal_key_configured?+ end++ test "select_accounts sends unregistered users to the Personal key form without an OAuth app" do+ sign_out+ sign_in @user = users(:empty)++ with_snaptrade_oauth(nil, nil) do+ get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "setup_accounts" }++ assert_redirected_to settings_providers_path+ end+ end+test "preload_accounts redirects unregistered users into connect flow" dosign_outsign_in @user = users(:empty)diff --git a/test/helpers/settings_helper_test.rb b/test/helpers/settings_helper_test.rbindex 0161866981..5cb341e48a 100644--- a/test/helpers/settings_helper_test.rb+++ b/test/helpers/settings_helper_test.rb@@ -12,15 +12,15 @@ class SettingsHelperTest < ActionView::TestCaseassert_equal({ status: :off }, provider_summary("snaptrade"))end- test "provider_summary for snaptrade is off when no item has completed OAuth" do- item = OpenStruct.new(oauth_configured?: false)+ test "provider_summary for snaptrade is off when no item is authorized" do+ item = OpenStruct.new(credentials_configured?: false)@snaptrade_items = [ item ]assert_equal({ status: :off }, provider_summary("snaptrade"))end- test "provider_summary for snaptrade reports sync-based status once an item is oauth configured" do- item = OpenStruct.new(oauth_configured?: true)+ test "provider_summary for snaptrade reports sync-based status once an item is authorized" do+ item = OpenStruct.new(credentials_configured?: true)@snaptrade_items = [ item ]@provider_sync_health = {}@@ -54,7 +54,7 @@ class SettingsHelperTest < ActionView::TestCase# shipped that way. One key at a time, so a branch that reads another# provider's items fails too.test "provider_summary is not off for any connected family panel provider" do- item = OpenStruct.new(oauth_configured?: true)+ item = OpenStruct.new(credentials_configured?: true)off = Settings::ProvidersController::FAMILY_PANEL_KEYS.select do |key|instance_variable_set(:"@#{key}_items", [ item ])diff --git a/test/jobs/snaptrade_activities_fetch_job_test.rb b/test/jobs/snaptrade_activities_fetch_job_test.rbindex c2cb108d31..298210aa74 100644--- a/test/jobs/snaptrade_activities_fetch_job_test.rb+++ b/test/jobs/snaptrade_activities_fetch_job_test.rb@@ -1,7 +1,50 @@require "test_helper"class SnaptradeActivitiesFetchJobTest < ActiveJob::TestCase- setup do+ test "a rate-limited Personal key retries no faster than every 15 seconds" do+ snaptrade_account = snaptrade_accounts(:fidelity_401k)+ snaptrade_account.snaptrade_item.update!(oauth_access_token: nil, oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE)+ Provider::Snaptrade.any_instance.stubs(:get_account_activities).raises(Provider::Snaptrade::RateLimitError.new("Rate limit exceeded"))++ freeze_time do+ assert_enqueued_with job: SnaptradeActivitiesFetchJob, at: 15.seconds.from_now do+ SnaptradeActivitiesFetchJob.perform_now(snaptrade_account, start_date: 1.year.ago.to_date)+ end+ end+ end++ test "a Personal key still rate limited after the last retry is captured, not treated as an empty account" do+ snaptrade_account = snaptrade_accounts(:fidelity_401k)+ snaptrade_account.update!(activities_fetch_pending: true)+ snaptrade_account.snaptrade_item.update!(oauth_access_token: nil, oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE)+ Provider::Snaptrade.any_instance.stubs(:get_account_activities).raises(Provider::Snaptrade::RateLimitError.new("Rate limit exceeded"))++ assert_no_enqueued_jobs(only: SnaptradeActivitiesFetchJob) do+ assert_difference -> { DebugLogEntry.where(provider_key: "snaptrade", level: "error").count }, 1 do+ SnaptradeActivitiesFetchJob.perform_now(snaptrade_account, start_date: 1.year.ago.to_date,+ retry_count: SnaptradeActivitiesFetchJob::MAX_RETRIES)+ end+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal [ "SnaptradeActivitiesFetchJob", "provider_sync", snaptrade_account.snaptrade_item.family, snaptrade_account.id ],+ [ entry.source, entry.category, entry.family, entry.metadata["snaptrade_account_id"] ]+ assert_not snaptrade_account.reload.activities_fetch_pending?+ end++ test "an account still empty after the last retry is not captured as a failure" do+ snaptrade_account = snaptrade_accounts(:fidelity_401k)+ Provider::Snaptrade.any_instance.stubs(:get_account_activities).returns([])++ assert_no_difference -> { DebugLogEntry.count } do+ SnaptradeActivitiesFetchJob.perform_now(snaptrade_account, start_date: 1.year.ago.to_date,+ retry_count: SnaptradeActivitiesFetchJob::MAX_RETRIES)+ end+ end++ # The tests below replace the provider with a mock; the ones above need the+ # real Provider::Snaptrade, so this is not a setup block.+ def stub_provider@snaptrade_account = snaptrade_accounts(:fidelity_401k)@snaptrade_account.update!(activities_fetch_pending: true)@provider = mock("snaptrade_provider")@@ -12,6 +55,7 @@ class SnaptradeActivitiesFetchJobTest < ActiveJob::TestCase# Provider::Snaptrade returns an empty first page as it is, even when its# total is positive, so a connection SnapTrade is still importing is polled.test "an empty result is fetched again later" do+ stub_provider@provider.expects(:get_account_activities).returns({ "data" => [], "pagination" => { "total" => 50 } })assert_enqueued_with(job: SnaptradeActivitiesFetchJob) do@@ -23,6 +67,7 @@ class SnaptradeActivitiesFetchJobTest < ActiveJob::TestCase# A raised fetch ends the job without another attempt, which is why the# provider must not raise on that empty first page.test "a fetch that raises is not retried and clears the pending flag" do+ stub_provider@provider.expects(:get_account_activities).raises(Provider::Snaptrade::ApiError.new("incomplete"))assert_no_enqueued_jobs(only: SnaptradeActivitiesFetchJob) dodiff --git a/test/models/provider/snaptrade_adapter_test.rb b/test/models/provider/snaptrade_adapter_test.rbindex 3fefcc336d..f4ca972468 100644--- a/test/models/provider/snaptrade_adapter_test.rb+++ b/test/models/provider/snaptrade_adapter_test.rb@@ -32,4 +32,28 @@ class Provider::SnaptradeAdapterTest < ActiveSupport::TestCaseassert_instance_of Provider::Snaptrade, providerassert_equal item, provider.snaptrade_itemend++ test "build_provider returns a Personal-key item's provider when no OAuth app is configured" do+ Provider::Snaptrade.stubs(:oauth_configured?).returns(false)+ item = snaptrade_items(:configured_item)+ item.update!(oauth_access_token: nil, oauth_refresh_token: nil, oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE,+ client_id: "personal-client", consumer_key: "personal-consumer-key")++ provider = Provider::SnaptradeAdapter.build_provider(family: families(:dylan_family))++ assert_instance_of Provider::Snaptrade, provider+ assert_equal item, provider.snaptrade_item+ end++ test "build_provider picks the newest Personal-key item, as the settings controller does" do+ Provider::Snaptrade.stubs(:oauth_configured?).returns(false)+ family = families(:dylan_family)+ older = snaptrade_items(:configured_item)+ older.update!(created_at: 2.days.ago)+ older.apply_personal_key!(client_id: "old-client", consumer_key: "old-key")+ newer = family.snaptrade_items.create!(name: "Newer")+ newer.apply_personal_key!(client_id: "new-client", consumer_key: "new-key")++ assert_equal newer, Provider::SnaptradeAdapter.build_provider(family: family).snaptrade_item+ endenddiff --git a/test/models/provider/snaptrade_personal_key_test.rb b/test/models/provider/snaptrade_personal_key_test.rbnew file mode 100644index 0000000000..f946d29ed7--- /dev/null+++ b/test/models/provider/snaptrade_personal_key_test.rb@@ -0,0 +1,153 @@+require "test_helper"++# SnapTrade Personal API key mode: requests are signed with the family's own+# consumer key (https://docs.snaptrade.com/docs/request-signatures) and carry+# no userId/userSecret (https://docs.snaptrade.com/docs/authentication-methods).+class Provider::SnaptradePersonalKeyTest < ActiveSupport::TestCase+ CLIENT_ID = "PERSONAL-CLIENT".freeze+ CONSUMER_KEY = "personal-consumer-key".freeze+ TIMESTAMP = 1_715_123_456++ setup do+ @item = families(:dylan_family).snaptrade_items.create!(+ name: "SnapTrade Personal",+ client_id: CLIENT_ID,+ consumer_key: CONSUMER_KEY,+ oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE+ )+ @provider = Provider::Snaptrade.new(@item)+ end++ test "data calls are signed with the consumer key, without a bearer token or user credentials" do+ Provider::Snaptrade.expects(:refresh_tokens).never+ stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts\?})+ .to_return { |request| @request = request; { status: 200, body: [ { id: "acc-1" } ].to_json } }++ travel_to Time.zone.at(TIMESTAMP) do+ assert_equal [ { "id" => "acc-1" } ], @provider.list_accounts+ end++ assert_nil @request.headers["Authorization"]+ assert_equal "clientId=#{CLIENT_ID}×tamp=#{TIMESTAMP}", @request.uri.query+ assert_not_includes @request.uri.query, "userId"+ assert_not_includes @request.uri.query, "userSecret"+ assert_equal expected_signature(@request), @request.headers["Signature"]+ end++ test "the signature covers query params exactly as sent" do+ stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts/acc-1/activities\?})+ .to_return { |request| @request = request; { status: 200, body: { data: [] }.to_json } }++ travel_to Time.zone.at(TIMESTAMP) do+ @provider.get_account_activities(account_id: "acc-1", start_date: Date.new(2024, 1, 1), end_date: Date.new(2024, 12, 31))+ end++ assert_equal "clientId=#{CLIENT_ID}&endDate=2024-12-31&limit=1000&offset=0&startDate=2024-01-01×tamp=#{TIMESTAMP}",+ @request.uri.query+ assert_equal expected_signature(@request), @request.headers["Signature"]+ end++ test "activities are paged with each page signed for its own offset" do+ requests = []+ pages = [+ { data: Array.new(1000) { |i| { id: "a#{i}" } }, pagination: { offset: 0, limit: 1000, total: 1002 } },+ { data: [ { id: "a1000" }, { id: "a1001" } ], pagination: { offset: 1000, limit: 1000, total: 1002 } }+ ]+ stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts/acc-1/activities\?})+ .to_return { |request| requests << request; { status: 200, body: pages[requests.size - 1].to_json } }++ response = travel_to(Time.zone.at(TIMESTAMP)) { @provider.get_account_activities(account_id: "acc-1") }++ assert_equal 1002, response["data"].size+ assert_equal %w[0 1000], requests.map { |r| URI.decode_www_form(r.uri.query).to_h["offset"] }+ requests.each do |request|+ assert_nil request.headers["Authorization"]+ assert_equal expected_signature(request), request.headers["Signature"]+ end+ end++ # A known vector, built by hand from the documented canonical form: keys+ # sorted at every level, no whitespace, and the body URL's "&" left as is.+ test "connection portal login signs and sends the canonical JSON body" do+ redirect = "https://sure.test/snaptrade_items/callback?item_id=1&return_to=setup_accounts"+ canonical_body = %({"connectionType":"read","customRedirect":"#{redirect}"})+ signed = %({"content":#{canonical_body},"path":"/api/v1/snapTrade/login","query":"clientId=#{CLIENT_ID}×tamp=#{TIMESTAMP}"})+ signature = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", CONSUMER_KEY, signed))++ stub = stub_request(:post, "https://api.snaptrade.com/api/v1/snapTrade/login?clientId=#{CLIENT_ID}×tamp=#{TIMESTAMP}")+ .with(body: canonical_body, headers: { "Signature" => signature, "Content-Type" => "application/json" })+ .to_return(status: 200, body: { redirectURI: "https://app.snaptrade.com/portal" }.to_json)++ url = travel_to(Time.zone.at(TIMESTAMP)) { @provider.get_connection_url(redirect_url: redirect) }++ assert_equal "https://app.snaptrade.com/portal", url+ assert_requested stub+ end++ # SnapTrade documents no timestamp tolerance, and network retries can be+ # minutes apart, so each attempt must be signed afresh.+ test "a retried request is re-signed with a fresh timestamp" do+ @provider.stubs(:sleep)+ stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts\?})+ .to_raise(Faraday::ConnectionFailed.new("boom")).then+ .to_return { |request| @request = request; { status: 200, body: "[]" } }+ Time.stubs(:current).returns(Time.zone.at(TIMESTAMP), Time.zone.at(TIMESTAMP + 120))++ @provider.list_accounts++ assert_equal "clientId=#{CLIENT_ID}×tamp=#{TIMESTAMP + 120}", @request.uri.query+ assert_equal expected_signature(@request), @request.headers["Signature"]+ end++ test "a rejected key marks the item for update instead of refreshing a token" do+ Provider::Snaptrade.expects(:refresh_tokens).never+ stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts\?}).to_return(status: 401, body: "{}")++ assert_raises(Provider::Snaptrade::AuthenticationError) { @provider.list_accounts }+ assert @item.reload.requires_update?+ end++ # Personal keys allow 10 requests a minute per account.+ test "a rate-limited key stops further requests from this provider" do+ stub = stub_request(:get, %r{\Ahttps://api\.snaptrade\.com/api/v1/accounts\?}).to_return(status: 429, body: "{}")++ 2.times { assert_raises(Provider::Snaptrade::RateLimitError) { @provider.list_accounts } }++ assert_requested stub, times: 1+ assert_instance_of Provider::Snaptrade::RateLimitError, @provider.rate_limit_error+ end++ test "a rate-limited account does not block requests for another account" do+ stub_request(:get, %r{/api/v1/accounts/A/positions}).to_return(status: 429, body: "{}")+ stub_request(:get, %r{/api/v1/accounts/B/positions}).to_return(status: 200, body: { results: [] }.to_json)++ assert_raises(Provider::Snaptrade::RateLimitError) { @provider.get_positions(account_id: "A") }+ assert_equal [], @provider.get_positions(account_id: "B")+ end++ test "OAuth authorization without a token_type clears the Personal key marker" do+ @item.apply_oauth_tokens!("access_token" => "at", "expires_in" => 3600)++ assert_not @item.reload.personal_key_configured?+ end++ test "authorizing with OAuth switches the item back to Bearer requests" do+ @item.apply_oauth_tokens!("access_token" => "at-1", "token_type" => "Bearer", "expires_in" => 3600)+ stub = stub_request(:get, "https://api.snaptrade.com/api/v1/accounts")+ .with(headers: { "Authorization" => "Bearer at-1" })+ .to_return(status: 200, body: "[]")++ Provider::Snaptrade.new(@item).list_accounts++ assert_requested stub+ end++ private++ # Recomputed from what actually went over the wire.+ def expected_signature(request)+ content = request.body.presence && JSON.parse(request.body)+ signed = JSON.generate({ "content" => content, "path" => request.uri.path, "query" => request.uri.query })+ Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", CONSUMER_KEY, signed))+ end+enddiff --git a/test/models/snaptrade_item/importer_test.rb b/test/models/snaptrade_item/importer_test.rbindex 6a10858f26..d5b1c08a57 100644--- a/test/models/snaptrade_item/importer_test.rb+++ b/test/models/snaptrade_item/importer_test.rb@@ -11,6 +11,14 @@ class SnaptradeItem::ImporterTest < ActiveSupport::TestCase@importer = SnaptradeItem::Importer.new(snaptrade_items(:configured_item), snaptrade_provider: @provider)end+ test "a rate-limited Personal key fails the import instead of being swallowed" do+ @provider.stubs(:list_accounts).returns([])+ @provider.stubs(:get_positions).returns([])+ @provider.stubs(:rate_limit_error).returns(Provider::Snaptrade::RateLimitError.new("Rate limit exceeded"))++ assert_raises(Provider::Snaptrade::RateLimitError) { @importer.import }+ end+# The flag is how anything outside the job chain (the item's syncing state,# SnaptradeAccount::SplitSecurityRepair) sees that a fetch is on its way,# so the job must never be queued without it.@@ -24,6 +32,14 @@ class SnaptradeItem::ImporterTest < ActiveSupport::TestCaseassert @snaptrade_account.reload.activities_fetch_pending?end+ test "the first background fetch waits the same 15 seconds as its retries" do+ freeze_time do+ assert_enqueued_with(job: SnaptradeActivitiesFetchJob, at: SnaptradeActivitiesFetchJob::RETRY_DELAY.from_now) do+ @importer.send(:import_activities, @snaptrade_account)+ end+ end+ end+test "no background fetch is queued when the pending flag cannot be set" do@snaptrade_account.stubs(:update!).with(activities_fetch_pending: true).raises(ActiveRecord::ActiveRecordError, "boom")diff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rbindex 6f39ec2008..06a3213223 100644--- a/test/models/snaptrade_item_test.rb+++ b/test/models/snaptrade_item_test.rb@@ -43,6 +43,58 @@ class SnaptradeItemTest < ActiveSupport::TestCaseassert item.credentials_configured?end+ test "a Personal API key authorizes the item without OAuth tokens" do+ item = SnaptradeItem.new(family: @family, name: "Personal", client_id: "personal-client", consumer_key: "personal-key",+ oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE)++ assert item.personal_key_configured?+ assert item.credentials_configured?+ assert_not item.oauth_configured?+ assert_instance_of Provider::Snaptrade, item.snaptrade_provider+ end++ test "apply_personal_key! replaces OAuth tokens and the legacy user with the key" do+ item = snaptrade_items(:configured_item)+ item.update!(snaptrade_user_id: "legacy-user", snaptrade_user_secret: "legacy-secret", status: :requires_update)++ item.apply_personal_key!(client_id: "personal-client", consumer_key: "personal-key")+ item.reload++ assert item.personal_key_configured?+ assert_not item.oauth_configured?+ assert_equal [ "personal-client", "personal-key", nil, nil, nil, nil, "good" ],+ [ item.client_id, item.consumer_key, item.oauth_refresh_token, item.oauth_token_expires_at,+ item.snaptrade_user_id, item.snaptrade_user_secret, item.status ]+ assert_includes SnaptradeItem.syncable, item+ end++ # Pre-OAuth items that stored keys but never registered a user (or whose+ # re-registration failed) have keys and no user secret, like a Personal key.+ test "a pre-OAuth item that never registered a user is not a Personal API key" do+ legacy = @family.snaptrade_items.create!(name: "Legacy", client_id: "commercial-client", consumer_key: "commercial-key", status: :requires_update)+ blank_secret = @family.snaptrade_items.create!(name: "Blank", client_id: "c", consumer_key: "k", snaptrade_user_secret: "")++ assert_not legacy.personal_key_configured?+ assert_not_includes SnaptradeItem.syncable, legacy+ assert_equal blank_secret.personal_key_configured?, SnaptradeItem.syncable.include?(blank_secret)+ end++ test "syncable includes Personal API key items and excludes pre-OAuth items" do+ personal = @family.snaptrade_items.create!(name: "Personal", client_id: "personal-client", consumer_key: "personal-key",+ oauth_token_type: SnaptradeItem::PERSONAL_KEY_TOKEN_TYPE)+ legacy = @family.snaptrade_items.create!(+ name: "Legacy", client_id: "commercial-client", consumer_key: "commercial-key",+ snaptrade_user_id: "user-1", snaptrade_user_secret: "secret-1"+ )+ unauthorized = @family.snaptrade_items.create!(name: "Unauthorized")++ syncable = SnaptradeItem.syncable+ assert_includes syncable, personal+ assert_includes syncable, snaptrade_items(:configured_item)+ assert_not_includes syncable, legacy+ assert_not_includes syncable, unauthorized+ end+test "an unlinked account awaiting activities does not keep the item syncing" doitem = snaptrade_items(:configured_item)account = snaptrade_accounts(:fidelity_401k)