Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(snaptrade): replace device-flow OAuth with authorization-code + PKCE flow (#2747)

Max Barbare51c93649dab8
diff --git a/.env.local.example b/.env.local.example
index afc38f3389..383fb71ac3 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -12,8 +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 OAuth device flow client ID (public OAuth client identifier, configured by Sure deployments)
+# SnapTrade OAuth app credentials (register an OAuth app at https://dashboard.snaptrade.com,
+# add https://<your-host>/snaptrade_items/oauth_callback as a redirect URI)
SNAPTRADE_OAUTH_CLIENT_ID=
+SNAPTRADE_OAUTH_CLIENT_SECRET=
# Lunchflow runtime flags (default-off)
# LUNCHFLOW_DEBUG_RAW: when truthy, logs the raw payload returned by Lunchflow (debug-only; can be noisy)
diff --git a/.env.test.example b/.env.test.example
index e62ad7ecf7..e8f7848deb 100644
--- a/.env.test.example
+++ b/.env.test.example
@@ -11,8 +11,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 OAuth device flow client ID (public OAuth client identifier, configured by Sure deployments)
+# SnapTrade OAuth app credentials (register an OAuth app at https://dashboard.snaptrade.com,
+# add https://<your-host>/snaptrade_items/oauth_callback as a redirect URI)
SNAPTRADE_OAUTH_CLIENT_ID=
+SNAPTRADE_OAUTH_CLIENT_SECRET=
# Lunchflow runtime flags (default-off)
# LUNCHFLOW_DEBUG_RAW: when truthy, logs the raw payload returned by Lunchflow (debug-only; can be noisy)
diff --git a/Gemfile b/Gemfile
index 9fbaa440db..f38a1a3a36 100644
--- a/Gemfile
+++ b/Gemfile
@@ -81,7 +81,6 @@ gem "rchardet" # Character encoding detection
gem "redcarpet"
gem "stripe"
gem "plaid"
-gem "snaptrade", "~> 2.0"
gem "httparty"
gem "rotp", "~> 6.3"
gem "rqrcode", "~> 3.0"
diff --git a/Gemfile.lock b/Gemfile.lock
index 2ecfceedaa..bde1923403 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -761,9 +761,6 @@ GEM
snaky_hash (2.0.3)
hashie (>= 0.1.0, < 6)
version_gem (>= 1.1.8, < 3)
- snaptrade (2.0.156)
- faraday (>= 1.0.1, < 3.0)
- faraday-multipart (~> 1.0, >= 1.0.4)
ssrf_filter (1.5.0)
stackprof (0.2.27)
standardwebhooks (1.1.0)
@@ -948,7 +945,6 @@ DEPENDENCIES
sidekiq-unique-jobs
simplecov
skylight
- snaptrade (~> 2.0)
stackprof
stimulus-rails
stripe
diff --git a/app/controllers/snaptrade_items_controller.rb b/app/controllers/snaptrade_items_controller.rb
index ab3733e20f..d3d1f3a1e1 100644
--- a/app/controllers/snaptrade_items_controller.rb
+++ b/app/controllers/snaptrade_items_controller.rb
@@ -1,8 +1,6 @@
class SnaptradeItemsController < ApplicationController
- PERMITTED_OAUTH_SCOPES = %w[read].freeze
-
- before_action :set_snaptrade_item, only: [ :show, :edit, :update, :destroy, :sync, :connect, :setup_accounts, :complete_account_setup, :connections, :start_oauth_device_flow, :complete_oauth_device_flow, :delete_connection, :delete_orphaned_user ]
- before_action :require_admin!, only: [ :new, :create, :preload_accounts, :select_accounts, :link_accounts, :select_existing_account, :link_existing_account, :oauth_connect, :start_oauth_connect, :edit, :update, :destroy, :sync, :connect, :callback, :setup_accounts, :complete_account_setup, :connections, :start_oauth_device_flow, :complete_oauth_device_flow, :delete_connection, :delete_orphaned_user ]
+ before_action :set_snaptrade_item, only: [ :show, :destroy, :sync, :connect, :setup_accounts, :complete_account_setup, :connections, :delete_connection ]
+ before_action :require_admin!, only: [ :destroy, :sync, :connect, :callback, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :oauth_authorize, :oauth_callback, :preload_accounts, :select_accounts, :select_existing_account, :link_existing_account ]
def index
@snaptrade_items = Current.family.snaptrade_items.ordered
@@ -11,88 +9,6 @@ class SnaptradeItemsController < ApplicationController
def show
end
- def new
- @snaptrade_item = Current.family.snaptrade_items.build
- end
-
- def edit
- end
-
- def create
- @snaptrade_item = Current.family.snaptrade_items.build(snaptrade_item_params)
- @snaptrade_item.name ||= t("snaptrade_items.default_name")
-
- if @snaptrade_item.save
- # Register user with SnapTrade after saving credentials
- if @snaptrade_item.credentials_configured?
- begin
- @snaptrade_item.ensure_user_registered!
- rescue => e
- Rails.logger.error "SnapTrade user registration failed: #{e.message}"
- # Don't fail the whole operation - user can retry connection later
- end
- end
-
- if turbo_frame_request?
- flash.now[:notice] = t(".success", default: "Successfully configured SnapTrade.")
- @snaptrade_items = Current.family.snaptrade_items.ordered
- render turbo_stream: [
- turbo_stream.replace(
- "snaptrade-providers-panel",
- partial: "settings/providers/snaptrade_panel",
- locals: { snaptrade_items: @snaptrade_items }
- ),
- *flash_notification_stream_items
- ]
- else
- redirect_to settings_providers_path, notice: t(".success"), status: :see_other
- end
- else
- @error_message = @snaptrade_item.errors.full_messages.join(", ")
-
- if turbo_frame_request?
- render turbo_stream: turbo_stream.replace(
- "snaptrade-providers-panel",
- partial: "settings/providers/snaptrade_panel",
- locals: { error_message: @error_message }
- ), status: :unprocessable_entity
- else
- redirect_to settings_providers_path, alert: @error_message, status: :unprocessable_entity
- end
- end
- end
-
- def update
- if @snaptrade_item.update(snaptrade_item_params)
- if turbo_frame_request?
- flash.now[:notice] = t(".success", default: "Successfully updated SnapTrade configuration.")
- @snaptrade_items = Current.family.snaptrade_items.ordered
- render turbo_stream: [
- turbo_stream.replace(
- "snaptrade-providers-panel",
- partial: "settings/providers/snaptrade_panel",
- locals: { snaptrade_items: @snaptrade_items }
- ),
- *flash_notification_stream_items
- ]
- else
- redirect_to settings_providers_path, notice: t(".success"), status: :see_other
- end
- else
- @error_message = @snaptrade_item.errors.full_messages.join(", ")
-
- if turbo_frame_request?
- render turbo_stream: turbo_stream.replace(
- "snaptrade-providers-panel",
- partial: "settings/providers/snaptrade_panel",
- locals: { error_message: @error_message }
- ), status: :unprocessable_entity
- else
- redirect_to settings_providers_path, alert: @error_message, status: :unprocessable_entity
- end
- end
- end
-
def destroy
@snaptrade_item.destroy_later
redirect_to settings_providers_path, notice: t(".success", default: "Scheduled SnapTrade connection for deletion.")
@@ -111,9 +27,11 @@ class SnaptradeItemsController < ApplicationController
# Redirect user to SnapTrade connection portal
def connect
- @snaptrade_item.ensure_user_registered! unless @snaptrade_item.user_registered?
-
- redirect_url = callback_snaptrade_items_url(item_id: @snaptrade_item.id)
+ redirect_url = callback_snaptrade_items_url(
+ item_id: @snaptrade_item.id,
+ return_to: params[:return_to].presence,
+ accountable_type: params[:accountable_type].presence
+ )
portal_url = @snaptrade_item.connection_portal_url(redirect_url: redirect_url)
redirect_to portal_url, allow_other_host: true
rescue ActiveRecord::Encryption::Errors::Decryption => e
@@ -138,17 +56,12 @@ class SnaptradeItemsController < ApplicationController
if snaptrade_item
snaptrade_item.sync_later unless snaptrade_item.syncing?
- stored_return_to, stored_accountable_type = clear_snaptrade_resume_context
- return_to = params[:return_to].presence || stored_return_to
- accountable_type = params[:accountable_type].presence || stored_accountable_type
-
- if return_to == "setup_accounts"
- redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: accountable_type.presence), notice: t(".success")
+ if params[:return_to].presence == "setup_accounts"
+ redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: params[:accountable_type].presence), notice: t(".success")
else
redirect_to accounts_path, notice: t(".success")
end
else
- clear_snaptrade_resume_context
redirect_to settings_providers_path, alert: t(".no_item")
end
end
@@ -166,7 +79,7 @@ class SnaptradeItemsController < ApplicationController
latest_sync = @snaptrade_item.syncs.ordered.first
should_sync = latest_sync.nil? || !latest_sync.completed?
- if @snaptrade_item.user_registered? && no_accounts && !@snaptrade_item.syncing? && should_sync
+ if @snaptrade_item.oauth_configured? && no_accounts && !@snaptrade_item.syncing? && should_sync
@snaptrade_item.sync_later
end
@@ -255,119 +168,89 @@ class SnaptradeItemsController < ApplicationController
data = build_connections_list
render partial: "snaptrade_items/connections_list", layout: false, locals: {
connections: data[:connections],
- orphaned_users: data[:orphaned_users],
snaptrade_item: @snaptrade_item,
error: @error
}
end
- def oauth_connect
- assign_oauth_connect_context
-
- unless Provider::Snaptrade.oauth_client_id_configured?
- @error_message = snaptrade_oauth_client_id_missing_message
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
+ # Start the SnapTrade OAuth authorization-code + PKCE flow
+ def oauth_authorize
+ unless Provider::Snaptrade.oauth_configured?
+ redirect_to settings_providers_path, alert: t(".not_configured")
return
end
- @snaptrade_item = if params[:item_id].present?
+ snaptrade_item = if params[:item_id].present?
Current.family.snaptrade_items.find(params[:item_id])
else
- current_snaptrade_item
+ current_snaptrade_item || Current.family.snaptrade_items.create!(name: t("snaptrade_items.default_name"))
end
- render :oauth_device_flow
- rescue ActiveRecord::Encryption::Errors::Decryption => e
- Rails.logger.error "SnapTrade decryption error for item #{@snaptrade_item&.id}: #{e.class} - #{e.message}"
- @error_message = t("snaptrade_items.connect.decryption_failed")
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
- rescue ActiveRecord::ActiveRecordError, ActiveRecord::Encryption::Errors::Base => e
- Rails.logger.error "SnapTrade OAuth connect error: #{e.class} - #{e.message}"
- @error_message = start_oauth_device_flow_error_message
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
+ pkce = Provider::Snaptrade.generate_pkce
+ state = SecureRandom.hex(32)
+
+ session[:snaptrade_oauth] = {
+ "state" => state,
+ "code_verifier" => pkce[:verifier],
+ "item_id" => snaptrade_item.id,
+ "return_to" => params[:return_to].presence,
+ "accountable_type" => params[:accountable_type].presence
+ }
+
+ redirect_to Provider::Snaptrade.authorize_url(
+ redirect_uri: oauth_callback_snaptrade_items_url,
+ state: state,
+ code_challenge: pkce[:challenge]
+ ), allow_other_host: true
end
- def start_oauth_connect
- assign_oauth_connect_context
+ # Registered OAuth redirect URI: verify state, exchange code, store tokens
+ def oauth_callback
+ oauth_session = (session.delete(:snaptrade_oauth) || {}).with_indifferent_access
- unless Provider::Snaptrade.oauth_client_id_configured?
- @error_message = snaptrade_oauth_client_id_missing_message
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
+ if params[:error].present?
+ Rails.logger.warn "SnapTrade OAuth callback error: #{params[:error]}"
+ alert = params[:error] == "access_denied" ? t(".access_denied") : t(".failed")
+ redirect_to settings_providers_path, alert: alert
return
end
- @snaptrade_item = if params[:item_id].present?
- Current.family.snaptrade_items.find(params[:item_id])
- else
- current_snaptrade_item || Current.family.snaptrade_items.create!(name: t("snaptrade_items.default_name"))
+ unless params[:state].present? && oauth_session[:state].present? &&
+ ActiveSupport::SecurityUtils.secure_compare(params[:state].to_s, oauth_session[:state].to_s)
+ redirect_to settings_providers_path, alert: t(".state_mismatch")
+ return
end
- @device_authorization = @snaptrade_item.start_oauth_device_flow(scope: @oauth_scope)
-
- render :oauth_device_flow
- rescue ActiveRecord::Encryption::Errors::Decryption => e
- Rails.logger.error "SnapTrade decryption error for item #{@snaptrade_item&.id}: #{e.class} - #{e.message}"
- @error_message = t("snaptrade_items.connect.decryption_failed")
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
- rescue Provider::Snaptrade::Error, ActiveRecord::ActiveRecordError, ActiveRecord::Encryption::Errors::Base => e
- Rails.logger.error "SnapTrade OAuth connect error: #{e.class} - #{e.message}"
- @error_message = oauth_connect_error_message(e)
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
- end
-
- def start_oauth_device_flow
- render json: @snaptrade_item.start_oauth_device_flow(scope: permitted_oauth_scope)
- rescue ActiveRecord::Encryption::Errors::Decryption => e
- Rails.logger.error "SnapTrade decryption error for item #{@snaptrade_item.id}: #{e.class} - #{e.message}"
- render json: { error: t("snaptrade_items.connect.decryption_failed") }, status: :unprocessable_entity
- rescue Provider::Snaptrade::Error => e
- Rails.logger.error "SnapTrade OAuth device authorization error: #{e.class} - #{e.message}"
- render json: { error: start_oauth_device_flow_error_message }, status: :unprocessable_entity
- end
-
- def complete_oauth_device_flow
- if params[:device_code].blank?
- render json: { error: "device_code is required" }, status: :unprocessable_entity
+ snaptrade_item = Current.family.snaptrade_items.find_by(id: oauth_session[:item_id])
+ unless snaptrade_item && params[:code].present?
+ redirect_to settings_providers_path, alert: t(".failed")
return
end
- token_response = @snaptrade_item.complete_oauth_device_flow!(device_code: params[:device_code])
- if request.format.json?
- render json: {
- token_type: token_response["token_type"],
- scope: token_response["scope"],
- expires_in: token_response["expires_in"],
- expires_at: @snaptrade_item.oauth_token_expires_at&.iso8601
- }
- else
- if prepare_snaptrade_item_for_setup_after_oauth
- redirect_after_oauth_completion setup_accounts_snaptrade_item_path(
- @snaptrade_item,
- accountable_type: params[:accountable_type].presence,
- return_to: params[:return_to].presence
- ), notice: t(".success", default: "SnapTrade authorization complete.")
- else
- redirect_after_oauth_completion settings_providers_path, alert: snaptrade_oauth_setup_incomplete_message
- end
- end
- rescue Provider::Snaptrade::ApiError => e
- if request.format.json?
- render json: oauth_error_payload(e), status: e.status_code || :unprocessable_entity
- else
- payload = oauth_error_payload(e)
- @error_message = payload["error_description"].presence || payload["error"]
- restore_device_authorization_from_params
- render :oauth_device_flow, status: e.status_code || :unprocessable_entity, formats: :html
- end
- rescue Provider::Snaptrade::Error, ActiveRecord::ActiveRecordError, ActiveRecord::Encryption::Errors::Base => e
- Rails.logger.error "SnapTrade OAuth device token error: #{e.class} - #{e.message}"
- if request.format.json?
- render json: { error: complete_oauth_device_flow_error_message }, status: :unprocessable_entity
+ snaptrade_item.complete_oauth_exchange!(
+ code: params[:code],
+ redirect_uri: oauth_callback_snaptrade_items_url,
+ code_verifier: oauth_session[:code_verifier]
+ )
+
+ snaptrade_item.sync_later unless snaptrade_item.syncing?
+
+ if oauth_session[:return_to] == "setup_accounts"
+ redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: oauth_session[:accountable_type].presence), notice: t(".success")
else
- @error_message = complete_oauth_device_flow_error_message
- restore_device_authorization_from_params
- render :oauth_device_flow, status: :unprocessable_entity, formats: :html
+ redirect_to settings_providers_path, notice: t(".success")
end
+ rescue Provider::Snaptrade::Error => e
+ Rails.logger.error "SnapTrade OAuth exchange failed: #{e.class} - #{e.message}"
+ DebugLogEntry.capture(
+ category: "provider_auth",
+ level: :error,
+ message: "SnapTrade OAuth code exchange failed: #{e.message}",
+ source: "SnaptradeItemsController#oauth_callback",
+ provider_key: "snaptrade",
+ family: Current.family
+ )
+ redirect_to settings_providers_path, alert: t(".failed")
end
# Delete a brokerage connection
@@ -389,16 +272,10 @@ class SnaptradeItemsController < ApplicationController
api_deletion_failed = false
if accounts_deleted == 0
provider = @snaptrade_item.snaptrade_provider
- creds = @snaptrade_item.snaptrade_credentials
-
- if provider && creds&.dig(:user_id) && creds&.dig(:user_secret)
- provider.delete_connection(
- user_id: creds[:user_id],
- user_secret: creds[:user_secret],
- authorization_id: authorization_id
- )
+ if provider
+ provider.delete_connection(authorization_id: authorization_id)
else
- Rails.logger.warn "SnapTrade: Cannot delete orphaned connection #{authorization_id} - missing credentials"
+ Rails.logger.warn "SnapTrade: Cannot delete orphaned connection #{authorization_id} - item not authorized"
api_deletion_failed = true
end
end
@@ -425,38 +302,6 @@ class SnaptradeItemsController < ApplicationController
end
end
- # Delete an orphaned SnapTrade user (and all their connections)
- def delete_orphaned_user
- user_id = params[:user_id]
-
- # Security: verify this is actually an orphaned user
- unless @snaptrade_item.orphaned_users.include?(user_id)
- respond_to do |format|
- format.html { redirect_to settings_providers_path, alert: t(".failed") }
- format.turbo_stream do
- flash.now[:alert] = t(".failed")
- render turbo_stream: flash_notification_stream_items
- end
- end
- return
- end
-
- if @snaptrade_item.delete_orphaned_user(user_id)
- respond_to do |format|
- format.html { redirect_to settings_providers_path, notice: t(".success") }
- format.turbo_stream { render turbo_stream: turbo_stream.remove("orphaned_user_#{user_id.parameterize}") }
- end
- else
- respond_to do |format|
- format.html { redirect_to settings_providers_path, alert: t(".failed") }
- format.turbo_stream do
- flash.now[:alert] = t(".failed")
- render turbo_stream: flash_notification_stream_items
- end
- end
- end
- end
-
# Collection actions for account linking flow
def preload_accounts
@@ -466,11 +311,11 @@ class SnaptradeItemsController < ApplicationController
return
end
- if snaptrade_item.user_registered?
+ if snaptrade_item.oauth_configured?
snaptrade_item.sync_later unless snaptrade_item.syncing?
redirect_to setup_accounts_snaptrade_item_path(snaptrade_item)
else
- redirect_to oauth_connect_snaptrade_items_path(item_id: snaptrade_item.id)
+ redirect_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id)
end
end
@@ -484,18 +329,13 @@ class SnaptradeItemsController < ApplicationController
return
end
- if snaptrade_item.user_registered?
+ if snaptrade_item.oauth_configured?
redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: @accountable_type, return_to: @return_to)
else
- store_snaptrade_resume_context(return_to: @return_to, accountable_type: @accountable_type)
- redirect_to oauth_connect_snaptrade_items_path(item_id: snaptrade_item.id, accountable_type: @accountable_type, return_to: @return_to)
+ redirect_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id, accountable_type: @accountable_type, return_to: @return_to)
end
end
- def link_accounts
- redirect_to settings_providers_path, alert: t(".use_setup_flow")
- end
-
def select_existing_account
@account_id = params[:account_id]
@account = Current.family.accounts.find_by(id: @account_id)
@@ -552,99 +392,26 @@ class SnaptradeItemsController < ApplicationController
active_items = Current.family.snaptrade_items.active
active_items.syncable.ordered.first ||
- active_items.credentials_configured.ordered.first ||
active_items.ordered.first
end
- def store_snaptrade_resume_context(return_to:, accountable_type:)
- session[:snaptrade_resume] = {
- return_to: return_to,
- accountable_type: accountable_type
- }
- end
-
- def clear_snaptrade_resume_context
- resume = (session.delete(:snaptrade_resume) || {}).with_indifferent_access
- [ resume[:return_to], resume[:accountable_type] ]
- end
-
- def restore_device_authorization_from_params
- @device_authorization = params.permit(
- :device_code,
- :user_code,
- :verification_uri,
- :verification_uri_complete,
- :expires_in,
- :interval
- ).to_h
- @return_to = params[:return_to]
- @accountable_type = params[:accountable_type]
- end
-
- def assign_oauth_connect_context
- @return_to = params[:return_to]
- @accountable_type = params[:accountable_type]
- @oauth_scope = permitted_oauth_scope
- end
-
- def permitted_oauth_scope
- requested_scope = params[:scope].to_s
- return requested_scope if PERMITTED_OAUTH_SCOPES.include?(requested_scope)
-
- "read"
- end
-
- def prepare_snaptrade_item_for_setup_after_oauth
- if !@snaptrade_item.user_registered? && @snaptrade_item.credentials_configured?
- @snaptrade_item.ensure_user_registered!
- end
-
- return false unless @snaptrade_item.user_registered?
-
- @snaptrade_item.sync_later unless @snaptrade_item.syncing?
- true
- end
-
- def redirect_after_oauth_completion(path, notice: nil, alert: nil)
- if turbo_frame_request?
- flash[:notice] = notice if notice.present?
- flash[:alert] = alert if alert.present?
- render turbo_stream: turbo_stream.action(:redirect, path)
- else
- redirect_to path, notice: notice, alert: alert
- end
- end
-
- def snaptrade_item_params
- params.require(:snaptrade_item).permit(
- :name,
- :sync_start_date,
- :client_id,
- :consumer_key
- )
- end
-
def build_connections_list
- # Fetch connections for current user from API
api_connections = @snaptrade_item.fetch_connections
- # Get local accounts grouped by authorization_id
local_accounts = @snaptrade_item.snaptrade_accounts
.includes(:account_provider)
.group_by(&:snaptrade_authorization_id)
- # Build unified list
- result = { connections: [], orphaned_users: [] }
+ result = { connections: [] }
- # Add connections from API for current user
api_connections.each do |api_conn|
- auth_id = api_conn.id
+ auth_id = api_conn["id"]
local_accts = local_accounts[auth_id] || []
result[:connections] << {
authorization_id: auth_id,
- brokerage_name: api_conn.brokerage&.name || I18n.t("snaptrade_items.connections.unknown_brokerage"),
- brokerage_slug: api_conn.brokerage&.slug,
+ brokerage_name: api_conn.dig("brokerage", "name") || I18n.t("snaptrade_items.connections.unknown_brokerage"),
+ brokerage_slug: api_conn.dig("brokerage", "slug"),
accounts: local_accts.map { |acct|
{ id: acct.id, name: acct.name, linked: acct.account_provider.present? }
},
@@ -652,71 +419,10 @@ class SnaptradeItemsController < ApplicationController
}
end
- # Add orphaned users (users registered but not current)
- orphaned = @snaptrade_item.orphaned_users
- orphaned.each do |user_id|
- result[:orphaned_users] << {
- user_id: user_id,
- display_name: user_id.truncate(30)
- }
- end
-
result
rescue Provider::Snaptrade::ApiError => e
@error = e.message
- { connections: [], orphaned_users: [] }
- end
-
- def oauth_error_payload(error)
- parsed_body = parse_oauth_error_body(error.response_body)
- payload = parsed_body.slice("error", "error_description", "error_uri", "interval")
- payload["error"] ||= error.message
- payload
- end
-
- def start_oauth_device_flow_error_message
- t(
- "snaptrade_items.start_oauth_device_flow.failed",
- default: "Unable to start SnapTrade OAuth device authorization. Please try again."
- )
- end
-
- def oauth_connect_error_message(error)
- if error.is_a?(Provider::Snaptrade::ConfigurationError) && error.message.include?("OAuth client ID")
- snaptrade_oauth_client_id_missing_message
- else
- start_oauth_device_flow_error_message
- end
- end
-
- def snaptrade_oauth_client_id_missing_message
- t(
- "snaptrade_items.oauth_device_flow.missing_client_id",
- default: "SnapTrade OAuth client ID is not configured. Add SNAPTRADE_OAUTH_CLIENT_ID to .env.local, restart the app, then try again."
- )
- end
-
- def snaptrade_oauth_setup_incomplete_message
- t(
- "snaptrade_items.complete_oauth_device_flow.setup_incomplete",
- default: "SnapTrade authorization is complete, but API credentials are required before accounts can sync."
- )
- end
-
- def complete_oauth_device_flow_error_message
- t(
- "snaptrade_items.complete_oauth_device_flow.failed",
- default: "Unable to complete SnapTrade OAuth device authorization. Please try again."
- )
- end
-
- def parse_oauth_error_body(response_body)
- return {} if response_body.blank?
-
- parsed_body = JSON.parse(response_body)
- parsed_body.is_a?(Hash) ? parsed_body : {}
- rescue JSON::ParserError
- {}
+ { connections: [] }
end
def link_snaptrade_account(snaptrade_account)
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 9a4d6b1d7a..10b880f718 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -91,12 +91,9 @@ module SettingsHelper
return { status: :off } unless @kraken_items&.any?
sync_based_summary(key)
when "snaptrade"
- configured_item = @snaptrade_items&.find { |item| item.credentials_configured? || item.oauth_configured? }
+ configured_item = @snaptrade_items&.find(&:oauth_configured?)
return { status: :off } unless configured_item
- unless configured_item.user_registered?
- return { status: :warn, meta: t("settings.providers.meta.registration_needed") }
- end
sync_based_summary(key)
when "ibkr"
return { status: :off } unless @ibkr_items&.any?
diff --git a/app/jobs/snaptrade_activities_fetch_job.rb b/app/jobs/snaptrade_activities_fetch_job.rb
index 18ecd39933..a0d45e3e86 100644
--- a/app/jobs/snaptrade_activities_fetch_job.rb
+++ b/app/jobs/snaptrade_activities_fetch_job.rb
@@ -29,20 +29,19 @@ class SnaptradeActivitiesFetchJob < ApplicationJob
"retry #{retry_count}/#{MAX_RETRIES}, range: #{start_date} to #{end_date}"
)
- # Get provider and credentials
+ # Get provider (nil when the item is not authorized)
snaptrade_item = snaptrade_account.snaptrade_item
provider = snaptrade_item.snaptrade_provider
- credentials = snaptrade_item.snaptrade_credentials
- unless provider && credentials
- Rails.logger.error("SnaptradeActivitiesFetchJob - No provider/credentials for account #{snaptrade_account.id}")
+ if provider.nil?
+ Rails.logger.error("SnaptradeActivitiesFetchJob - Item not authorized for account #{snaptrade_account.id}")
snaptrade_account.update!(activities_fetch_pending: false)
snaptrade_account.snaptrade_item.broadcast_sync_complete
return
end
# Fetch activities from API
- activities_data = fetch_activities(snaptrade_account, provider, credentials, start_date, end_date)
+ activities_data = fetch_activities(snaptrade_account, provider, start_date, end_date)
if activities_data.any?
Rails.logger.info(
@@ -95,25 +94,21 @@ class SnaptradeActivitiesFetchJob < ApplicationJob
private
- def fetch_activities(snaptrade_account, provider, credentials, start_date, end_date)
+ def fetch_activities(snaptrade_account, provider, start_date, end_date)
response = provider.get_account_activities(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
account_id: snaptrade_account.snaptrade_account_id,
start_date: start_date,
end_date: end_date
)
- # Handle paginated response
- activities = if response.respond_to?(:data)
- response.data || []
+ activities = if response.is_a?(Hash)
+ response["data"] || []
elsif response.is_a?(Array)
response
else
[]
end
- # Convert SDK objects to hashes
activities.map { |a| sdk_object_to_hash(a) }
end
diff --git a/app/jobs/snaptrade_connection_cleanup_job.rb b/app/jobs/snaptrade_connection_cleanup_job.rb
index 2320cb9d0f..d5d418184b 100644
--- a/app/jobs/snaptrade_connection_cleanup_job.rb
+++ b/app/jobs/snaptrade_connection_cleanup_job.rb
@@ -33,11 +33,10 @@ class SnaptradeConnectionCleanupJob < ApplicationJob
end
provider = snaptrade_item.snaptrade_provider
- credentials = snaptrade_item.snaptrade_credentials
- unless provider && credentials
+ unless provider
Rails.logger.warn(
- "SnaptradeConnectionCleanupJob - No provider/credentials for item #{snaptrade_item_id}"
+ "SnaptradeConnectionCleanupJob - Item #{snaptrade_item_id} not authorized, skipping API deletion"
)
return
end
@@ -46,11 +45,7 @@ class SnaptradeConnectionCleanupJob < ApplicationJob
"SnaptradeConnectionCleanupJob - Deleting SnapTrade connection #{authorization_id}"
)
- provider.delete_connection(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
- authorization_id: authorization_id
- )
+ provider.delete_connection(authorization_id: authorization_id)
Rails.logger.info(
"SnaptradeConnectionCleanupJob - Successfully deleted connection #{authorization_id}"
diff --git a/app/models/family/snaptrade_connectable.rb b/app/models/family/snaptrade_connectable.rb
index c8c8876aac..867a972dab 100644
--- a/app/models/family/snaptrade_connectable.rb
+++ b/app/models/family/snaptrade_connectable.rb
@@ -6,25 +6,7 @@ module Family::SnaptradeConnectable
end
def can_connect_snaptrade?
- # Families can configure their own Snaptrade credentials
+ # Families can connect to SnapTrade via OAuth (env-level app configuration).
true
end
-
- def create_snaptrade_item!(client_id:, consumer_key:, snaptrade_user_secret:, snaptrade_user_id: nil, item_name: nil)
- snaptrade_item = snaptrade_items.create!(
- name: item_name || "Snaptrade Connection",
- client_id: client_id,
- consumer_key: consumer_key,
- snaptrade_user_id: snaptrade_user_id,
- snaptrade_user_secret: snaptrade_user_secret
- )
-
- snaptrade_item.sync_later
-
- snaptrade_item
- end
-
- def has_snaptrade_credentials?
- snaptrade_items.where.not(client_id: nil).exists?
- end
end
diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rb
index fabe507e69..39b59d0693 100644
--- a/app/models/provider/snaptrade.rb
+++ b/app/models/provider/snaptrade.rb
@@ -1,3 +1,12 @@
+# SnapTrade API client using SnapTrade OAuth apps (pre-release feature).
+#
+# Auth model:
+# - Instance admin registers an OAuth app on dashboard.snaptrade.com and sets
+# SNAPTRADE_OAUTH_CLIENT_ID / SNAPTRADE_OAUTH_CLIENT_SECRET.
+# - Users authorize via authorization-code + PKCE; per-item access/refresh
+# tokens are stored (encrypted) on SnaptradeItem.
+# - Data calls send Authorization: Bearer <access_token>. The SnapTrade user
+# is implicit in the token; there is no userId/userSecret.
class Provider::Snaptrade
class Error < StandardError; end
class AuthenticationError < Error; end
@@ -12,324 +21,359 @@ class Provider::Snaptrade
end
end
- # Retry configuration for transient network failures
MAX_RETRIES = 3
INITIAL_RETRY_DELAY = 2 # seconds
MAX_RETRY_DELAY = 30 # seconds
- OAUTH_DISCOVERY_URL = "https://api.snaptrade.com/.well-known/oauth-authorization-server".freeze
- DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code".freeze
- attr_reader :client_id, :consumer_key
+ API_BASE_URL = "https://api.snaptrade.com".freeze
+ AUTHORIZE_URL = "https://dashboard.snaptrade.com/oauth/authorize".freeze
+ TOKEN_URL = "https://api.snaptrade.com/oauth/token/".freeze
+ REVOKE_URL = "https://api.snaptrade.com/oauth/revoke_token/".freeze
+ DASHBOARD_URL = "https://dashboard.snaptrade.com".freeze
+ TOKEN_EXPIRY_LEEWAY = 60 # seconds; refresh this long before actual expiry
- def initialize(client_id: nil, consumer_key: nil)
- @client_id = client_id
- @consumer_key = consumer_key
+ class << self
+ def oauth_configured?
+ oauth_client_id.present? && oauth_client_secret.present?
+ end
- return if client_id.blank? && consumer_key.blank?
- raise ConfigurationError, "client_id is required" if client_id.blank?
- raise ConfigurationError, "consumer_key is required" if consumer_key.blank?
+ def oauth_client_id
+ Rails.configuration.x.snaptrade&.oauth_client_id
+ end
- configuration = SnapTrade::Configuration.new
- configuration.client_id = client_id
- configuration.consumer_key = consumer_key
- @client = SnapTrade::Client.new(configuration)
- end
+ def oauth_client_secret
+ Rails.configuration.x.snaptrade&.oauth_client_secret
+ end
- def self.oauth_client_id_configured?
- Rails.configuration.x.snaptrade&.oauth_client_id.present?
- end
+ # PKCE pair per RFC 7636 (S256)
+ def generate_pkce
+ verifier = SecureRandom.urlsafe_base64(64).delete("=")[0, 128]
+ challenge = Base64.urlsafe_encode64(OpenSSL::Digest::SHA256.digest(verifier), padding: false)
+ { verifier: verifier, challenge: challenge }
+ end
- def oauth_authorization_server_metadata
- with_retries("oauth_authorization_server_metadata") do
- response = oauth_connection.get(OAUTH_DISCOVERY_URL)
- parse_oauth_response(response, "oauth_authorization_server_metadata")
+ def authorize_url(redirect_uri:, state:, code_challenge:, scope: "read")
+ raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+
+ params = {
+ response_type: "code",
+ client_id: oauth_client_id,
+ redirect_uri: redirect_uri,
+ scope: scope,
+ state: state,
+ code_challenge: code_challenge,
+ code_challenge_method: "S256"
+ }
+ "#{AUTHORIZE_URL}?#{params.to_query}"
end
- end
- def start_device_authorization(scope: "read")
- metadata = oauth_authorization_server_metadata
- endpoint = metadata.fetch("device_authorization_endpoint") do
- raise ApiError.new("SnapTrade OAuth metadata missing device_authorization_endpoint")
+ def exchange_code(code:, redirect_uri:, code_verifier:)
+ token_request(
+ grant_type: "authorization_code",
+ code: code,
+ redirect_uri: redirect_uri,
+ code_verifier: code_verifier
+ )
end
- with_retries("start_device_authorization") do
- response = oauth_connection.post(endpoint) do |request|
+ def refresh_tokens(refresh_token:)
+ token_request(grant_type: "refresh_token", refresh_token: refresh_token)
+ end
+
+ # Best-effort revocation (RFC 7009). Returns true on success.
+ def revoke_token(token:)
+ return false if token.blank?
+ raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+
+ response = oauth_connection.post(REVOKE_URL) do |request|
+ request.headers["Authorization"] = basic_auth_header
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
- request.body = URI.encode_www_form(
- client_id: oauth_client_id,
- scope: scope
- )
+ request.body = URI.encode_www_form(token: token)
end
-
- parse_oauth_response(response, "start_device_authorization")
+ response.success?
+ rescue Faraday::Error => e
+ Rails.logger.warn("SnapTrade token revocation failed: #{e.class} - #{e.message}")
+ false
end
- end
- def poll_device_token(device_code:)
- raise ConfigurationError, "device_code is required" if device_code.blank?
+ private
+
+ def token_request(params)
+ raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+
+ # Not retried: a token request consumes a single-use authorization code
+ # or rotates the refresh token. If the response is lost after SnapTrade
+ # processed it, replaying the same params would fail with invalid_grant
+ # even though the original request actually succeeded.
+ response = without_retry("POST #{TOKEN_URL}") do
+ oauth_connection.post(TOKEN_URL) do |request|
+ request.headers["Authorization"] = basic_auth_header
+ request.headers["Content-Type"] = "application/x-www-form-urlencoded"
+ request.body = URI.encode_www_form(params)
+ end
+ end
+
+ payload = parse_json(response.body)
+ return payload if response.success?
- metadata = oauth_authorization_server_metadata
- endpoint = metadata.fetch("token_endpoint") do
- raise ApiError.new("SnapTrade OAuth metadata missing token_endpoint")
- end
+ error = payload["error_description"].presence || payload["error"].presence || "HTTP #{response.status}"
+ if (400..499).cover?(response.status)
+ raise AuthenticationError, "SnapTrade OAuth token request failed: #{error}"
+ end
- with_retries("poll_device_token") do
- response = oauth_connection.post(endpoint) do |request|
- request.headers["Content-Type"] = "application/x-www-form-urlencoded"
- request.body = URI.encode_www_form(
- grant_type: DEVICE_CODE_GRANT,
- device_code: device_code,
- client_id: oauth_client_id
+ raise ApiError.new(
+ "SnapTrade OAuth token request failed: #{error}",
+ status_code: response.status, response_body: response.body
)
end
- parse_oauth_response(response, "poll_device_token")
- end
- end
+ def basic_auth_header
+ "Basic #{Base64.strict_encode64("#{oauth_client_id}:#{oauth_client_secret}")}"
+ end
- # Register a new SnapTrade user
- # Returns { user_id: String, user_secret: String }
- def register_user(user_id)
- with_retries("register_user") do
- response = client.authentication.register_snap_trade_user(
- user_id: user_id
- )
- {
- user_id: response.user_id,
- user_secret: response.user_secret
- }
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "register_user")
- end
+ def oauth_connection
+ Faraday.new do |faraday|
+ faraday.options.timeout = 30
+ faraday.options.open_timeout = 10
+ end
+ end
- # Delete a SnapTrade user (resets all connections)
- def delete_user(user_id:)
- with_retries("delete_user") do
- client.authentication.delete_snap_trade_user(
- user_id: user_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "delete_user")
- end
+ def parse_json(body)
+ body.present? ? JSON.parse(body) : {}
+ rescue JSON::ParserError
+ {}
+ end
- # List all registered users
- def list_users
- with_retries("list_users") do
- client.authentication.list_snap_trade_users
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "list_users")
- end
+ def with_retries(operation_name, max_retries: MAX_RETRIES)
+ retries = 0
+
+ begin
+ yield
+ rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Errno::ECONNRESET, Errno::ETIMEDOUT => e
+ retries += 1
+
+ if retries <= max_retries
+ delay = calculate_retry_delay(retries)
+ Rails.logger.warn(
+ "SnapTrade OAuth: #{operation_name} failed (attempt #{retries}/#{max_retries}): " \
+ "#{e.class}: #{e.message}. Retrying in #{delay}s..."
+ )
+ sleep(delay)
+ retry
+ else
+ Rails.logger.error(
+ "SnapTrade OAuth: #{operation_name} failed after #{max_retries} retries: " \
+ "#{e.class}: #{e.message}"
+ )
+ raise ApiError.new("Network error after #{max_retries} retries: #{e.message}")
+ end
+ end
+ end
- # List all brokerage connections/authorizations
- def list_connections(user_id:, user_secret:)
- with_retries("list_connections") do
- client.connections.list_brokerage_authorizations(
- user_id: user_id,
- user_secret: user_secret
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "list_connections")
- end
+ # For requests that must not be replayed (single-use codes, token rotation):
+ # translate a network failure into an ApiError without retrying.
+ def without_retry(operation_name)
+ yield
+ rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Errno::ECONNRESET, Errno::ETIMEDOUT => e
+ Rails.logger.error("SnapTrade OAuth: #{operation_name} failed (not retried, non-idempotent): #{e.class}: #{e.message}")
+ raise ApiError.new("Network error (not retried, non-idempotent request): #{e.message}")
+ end
- # Delete a specific brokerage connection/authorization
- # This frees up one of your connection slots
- def delete_connection(user_id:, user_secret:, authorization_id:)
- with_retries("delete_connection") do
- client.connections.remove_brokerage_authorization(
- user_id: user_id,
- user_secret: user_secret,
- authorization_id: authorization_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "delete_connection")
+ def calculate_retry_delay(retry_count)
+ base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))
+ jitter = base_delay * rand * 0.25
+ [ base_delay + jitter, MAX_RETRY_DELAY ].min
+ end
end
- # Get connection portal URL (OAuth-like redirect to SnapTrade)
- # Returns the redirect URL string
- def get_connection_url(user_id:, user_secret:, redirect_url:, broker: nil)
- with_retries("get_connection_url") do
- response = client.authentication.login_snap_trade_user(
- user_id: user_id,
- user_secret: user_secret,
- custom_redirect: redirect_url,
- connection_type: "read",
- broker: broker
- )
- response.redirect_uri
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_connection_url")
- end
+ attr_reader :snaptrade_item
- # List connected brokerage accounts
- # Returns array of account objects
- def list_accounts(user_id:, user_secret:)
- with_retries("list_accounts") do
- client.account_information.list_user_accounts(
- user_id: user_id,
- user_secret: user_secret
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "list_accounts")
+ def initialize(snaptrade_item)
+ raise ConfigurationError, "snaptrade_item is required" if snaptrade_item.nil?
+ @snaptrade_item = snaptrade_item
end
- # Get account details
- def get_account_details(user_id:, user_secret:, account_id:)
- with_retries("get_account_details") do
- client.account_information.get_user_account_details(
- user_id: user_id,
- user_secret: user_secret,
- account_id: account_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_account_details")
- end
+ # --- Data methods. The SnapTrade user is implicit in the Bearer token. ---
- # Get positions/holdings for an account
- # Returns array of position objects
- def get_positions(user_id:, user_secret:, account_id:)
- with_retries("get_positions") do
- client.account_information.get_user_account_positions(
- user_id: user_id,
- user_secret: user_secret,
- account_id: account_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_positions")
+ # Returns Array<Hash> of brokerage accounts
+ def list_accounts
+ get_json("/api/v1/accounts")
end
- # Get all holdings across all accounts
- def get_all_holdings(user_id:, user_secret:)
- with_retries("get_all_holdings") do
- client.account_information.get_all_user_holdings(
- user_id: user_id,
- user_secret: user_secret
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_all_holdings")
+ # Returns Array<Hash> of balance entries
+ def get_balances(account_id:)
+ get_json("/api/v1/accounts/#{account_id}/balances")
end
- # Get holdings for a specific account (includes more details)
- def get_holdings(user_id:, user_secret:, account_id:)
- with_retries("get_holdings") do
- client.account_information.get_user_holdings(
- user_id: user_id,
- user_secret: user_secret,
- account_id: account_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_holdings")
+ # Returns Array<Hash> of positions
+ def get_positions(account_id:)
+ get_json("/api/v1/accounts/#{account_id}/positions")
end
- # Get balances for an account
- def get_balances(user_id:, user_secret:, account_id:)
- with_retries("get_balances") do
- client.account_information.get_user_account_balance(
- user_id: user_id,
- user_secret: user_secret,
- account_id: account_id
- )
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_balances")
+ # Returns raw JSON: paginated form is {"data" => [...]}, may also be a plain Array
+ def get_account_activities(account_id:, start_date: nil, end_date: nil)
+ params = {}
+ params[:startDate] = start_date.to_date.to_s if start_date
+ params[:endDate] = end_date.to_date.to_s if end_date
+ get_json("/api/v1/accounts/#{account_id}/activities", params)
end
- # Get activity/transaction history for a specific account
- # Supports pagination via start_date and end_date
- def get_account_activities(user_id:, user_secret:, account_id:, start_date: nil, end_date: nil)
- with_retries("get_account_activities") do
- params = {
- user_id: user_id,
- user_secret: user_secret,
- account_id: account_id
- }
- params[:start_date] = start_date.to_date.to_s if start_date
- params[:end_date] = end_date.to_date.to_s if end_date
+ # Cross-account activities endpoint. Returns Array<Hash>.
+ def get_activities(start_date: nil, end_date: nil, accounts: nil, brokerage_authorizations: nil, type: nil)
+ params = {}
+ params[:startDate] = start_date.to_date.to_s if start_date
+ params[:endDate] = end_date.to_date.to_s if end_date
+ params[:accounts] = accounts if accounts
+ params[:brokerageAuthorizations] = brokerage_authorizations if brokerage_authorizations
+ params[:type] = type if type
+ get_json("/api/v1/activities", params)
+ end
- client.account_information.get_account_activities(**params)
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_account_activities")
+ # Returns Array<Hash> of brokerage authorizations (connections)
+ def list_connections
+ get_json("/api/v1/authorizations")
end
- # Get activities across all accounts (alternative endpoint)
- def get_activities(user_id:, user_secret:, start_date: nil, end_date: nil, accounts: nil, brokerage_authorizations: nil, type: nil)
- with_retries("get_activities") do
- params = {
- user_id: user_id,
- user_secret: user_secret
- }
- params[:start_date] = start_date.to_date.to_s if start_date
- params[:end_date] = end_date.to_date.to_s if end_date
- params[:accounts] = accounts if accounts
- params[:brokerage_authorizations] = brokerage_authorizations if brokerage_authorizations
- params[:type] = type if type
+ def delete_connection(authorization_id:)
+ request_json(:delete, "/api/v1/authorizations/#{authorization_id}")
+ end
- client.transactions_and_reporting.get_activities(**params)
- end
- rescue SnapTrade::ApiError => e
- handle_api_error(e, "get_activities")
+ # Connection portal URL (loginUser). Returns the redirect URL string.
+ def get_connection_url(redirect_url:, broker: nil)
+ body = { customRedirect: redirect_url, connectionType: "read" }
+ body[:broker] = broker if broker
+ response = request_json(:post, "/api/v1/snapTrade/login", body: body)
+ response["redirectURI"] || response["redirectUri"]
end
private
- def client
- @client || raise(ConfigurationError, "SnapTrade API credentials are required")
+ def get_json(path, params = {})
+ request_json(:get, path, params: params)
end
- def handle_api_error(error, operation)
- status = error.code
- body = error.response_body
-
- Rails.logger.error("SnapTrade API error (#{operation}): #{status} - #{error.message}")
+ def request_json(method, path, params: {}, body: nil, retry_on_auth_failure: true)
+ ensure_fresh_token!
+ operation = "#{method.to_s.upcase} #{path}"
+ used_access_token = snaptrade_item.oauth_access_token
+
+ # Only GET is safe to retry: a lost response to a POST/DELETE (e.g.
+ # get_connection_url, delete_connection) may already have been applied by
+ # SnapTrade, so replaying it risks duplicate side effects.
+ retrier = method == :get ? method(:with_retries) : method(:without_retry)
+ response = retrier.call(operation) do
+ api_connection.public_send(method, "#{API_BASE_URL}#{path}") do |request|
+ request.headers["Authorization"] = "Bearer #{used_access_token}"
+ request.headers["Accept"] = "application/json"
+ request.params.update(params) if params.present?
+ if body
+ request.headers["Content-Type"] = "application/json"
+ request.body = body.to_json
+ end
+ end
+ end
- case status
- when 401, 403
- raise AuthenticationError, "Authentication failed: #{error.message}"
- when 429
- raise ApiError.new("Rate limit exceeded. Please try again later.", status_code: status, response_body: body)
- when 500..599
- raise ApiError.new("SnapTrade server error (#{status}). Please try again later.", status_code: status, response_body: body)
- else
- raise ApiError.new("SnapTrade API error: #{error.message}", status_code: status, response_body: body)
+ if response.status == 401 && retry_on_auth_failure
+ refresh_access_token!(previous_access_token: used_access_token)
+ return request_json(method, path, params: params, body: body, retry_on_auth_failure: false)
end
+
+ handle_response(response, operation)
end
- def oauth_connection
- @oauth_connection ||= Faraday.new do |faraday|
- faraday.options.timeout = 30
- faraday.options.open_timeout = 10
- end
+ def ensure_fresh_token!
+ raise AuthenticationError, "SnapTrade item has no access token" if snaptrade_item.oauth_access_token.blank?
+
+ expires_at = snaptrade_item.oauth_token_expires_at
+ return if expires_at.blank? || expires_at > TOKEN_EXPIRY_LEEWAY.seconds.from_now
+
+ refresh_access_token!
end
- def oauth_client_id
- configured_client_id = Rails.configuration.x.snaptrade&.oauth_client_id
- return configured_client_id if configured_client_id.present?
+ # Guards against a concurrent refresh-token rotation race: multiple threads/processes
+ # (e.g. per-account jobs sharing one SnapTrade item) may all observe an expiring/rejected
+ # token and attempt to refresh at once. If SnapTrade rotates refresh tokens as single-use,
+ # every refresh after the first would fail with invalid_grant and needlessly brick the
+ # item. Taking a DB row lock and re-checking freshness after reload ensures only one
+ # caller actually performs the HTTP refresh; the rest observe the winner's fresh token.
+ #
+ # `previous_access_token`, when present, means we're refreshing reactively after a 401 on
+ # that specific token (called from request_json). In that case we skip the HTTP refresh
+ # only if the DB row's access token has already changed since we made the failed request
+ # (i.e. another caller already won the race) -- an expiry-based freshness check would be
+ # wrong here since the server rejected a token we believed was still time-valid.
+ # When `previous_access_token` is absent, we're refreshing proactively (from
+ # ensure_fresh_token!) and skip only if the reloaded row is still time-fresh.
+ def refresh_access_token!(previous_access_token: nil)
+ snaptrade_item.with_lock do
+ snaptrade_item.reload
+
+ if previous_access_token.present?
+ next if snaptrade_item.oauth_access_token != previous_access_token
+ else
+ expires_at = snaptrade_item.oauth_token_expires_at
+ next if expires_at.present? && expires_at > TOKEN_EXPIRY_LEEWAY.seconds.from_now
+ end
+
+ refresh_token = snaptrade_item.oauth_refresh_token
+ raise AuthenticationError, "SnapTrade item has no refresh token" if refresh_token.blank?
- raise ConfigurationError, "SnapTrade OAuth client ID is not configured"
+ payload = self.class.refresh_tokens(refresh_token: refresh_token)
+ snaptrade_item.apply_oauth_tokens!(payload)
+ end
+ rescue AuthenticationError => e
+ mark_requires_update!
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: :error,
+ message: "SnapTrade token refresh failed: #{e.message}",
+ source: "Provider::Snaptrade",
+ provider_key: "snaptrade",
+ family: snaptrade_item.try(:family),
+ metadata: { snaptrade_item_id: snaptrade_item.try(:id) }
+ )
+ raise
end
- def parse_oauth_response(response, operation)
- payload = response.body.present? ? JSON.parse(response.body) : {}
+ def mark_requires_update!
+ snaptrade_item.update!(status: :requires_update)
+ rescue StandardError => e
+ Rails.logger.warn("SnapTrade: could not mark item requires_update: #{e.message}")
+ end
+ def handle_response(response, operation)
if response.success?
- payload
+ return {} if response.body.blank?
+ begin
+ JSON.parse(response.body)
+ rescue JSON::ParserError
+ raise ApiError.new("SnapTrade API error (#{operation}): invalid JSON response",
+ status_code: response.status, response_body: response.body)
+ end
else
- error = payload["error_description"].presence || payload["error"].presence || response.reason_phrase
- raise ApiError.new("SnapTrade OAuth error (#{operation}): #{error}", status_code: response.status, response_body: response.body)
+ Rails.logger.error("SnapTrade API error (#{operation}): #{response.status}")
+ case response.status
+ when 401, 403
+ mark_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)
+ when 500..599
+ raise ApiError.new("SnapTrade server error (#{response.status}). Please try again later.",
+ status_code: response.status, response_body: response.body)
+ else
+ raise ApiError.new("SnapTrade API error (#{operation}): HTTP #{response.status}",
+ status_code: response.status, response_body: response.body)
+ end
+ end
+ end
+
+ def api_connection
+ @api_connection ||= Faraday.new do |faraday|
+ faraday.options.timeout = 30
+ faraday.options.open_timeout = 10
end
- rescue JSON::ParserError
- raise ApiError.new("SnapTrade OAuth error (#{operation}): invalid JSON response", status_code: response.status, response_body: response.body)
end
def with_retries(operation_name, max_retries: MAX_RETRIES)
@@ -358,6 +402,13 @@ class Provider::Snaptrade
end
end
+ def without_retry(operation_name)
+ yield
+ rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Errno::ECONNRESET, Errno::ETIMEDOUT => e
+ Rails.logger.error("SnapTrade API: #{operation_name} failed (not retried, non-idempotent): #{e.class}: #{e.message}")
+ raise ApiError.new("Network error (not retried, non-idempotent request): #{e.message}")
+ end
+
def calculate_retry_delay(retry_count)
base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))
jitter = base_delay * rand * 0.25
diff --git a/app/models/provider/snaptrade_adapter.rb b/app/models/provider/snaptrade_adapter.rb
index 8f9a946fb0..46db1b64ce 100644
--- a/app/models/provider/snaptrade_adapter.rb
+++ b/app/models/provider/snaptrade_adapter.rb
@@ -38,20 +38,17 @@ class Provider::SnaptradeAdapter < Provider::Base
"snaptrade"
end
- # Build a SnapTrade provider instance with family-specific credentials
- # @param family [Family] The family to get credentials for (required)
- # @return [Provider::Snaptrade, nil] Returns nil if credentials are not configured
+ # 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
def self.build_provider(family: nil)
return nil unless family.present?
+ return nil unless Provider::Snaptrade.oauth_configured?
- # Get family-specific credentials
- snaptrade_item = family.snaptrade_items.where.not(client_id: nil).first
- return nil unless snaptrade_item&.credentials_configured?
+ snaptrade_item = family.snaptrade_items.syncable.first
+ return nil unless snaptrade_item
- Provider::Snaptrade.new(
- client_id: snaptrade_item.client_id,
- consumer_key: snaptrade_item.consumer_key
- )
+ Provider::Snaptrade.new(snaptrade_item)
end
def sync_path
diff --git a/app/models/snaptrade_account.rb b/app/models/snaptrade_account.rb
index a57d9323b8..932a72b915 100644
--- a/app/models/snaptrade_account.rb
+++ b/app/models/snaptrade_account.rb
@@ -202,11 +202,6 @@ class SnaptradeAccount < ApplicationRecord
snaptrade_item.snaptrade_provider
end
- # Get SnapTrade credentials for API calls
- def snaptrade_credentials
- snaptrade_item.snaptrade_credentials
- end
-
private
def normalized_balance_entries
diff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rb
index 171cdbaaef..4c055337e9 100644
--- a/app/models/snaptrade_item.rb
+++ b/app/models/snaptrade_item.rb
@@ -25,10 +25,6 @@ class SnaptradeItem < ApplicationRecord
end
validates :name, presence: true
- validates :client_id, presence: true, if: -> { consumer_key.present? }
- validates :consumer_key, presence: true, if: -> { client_id.present? }
- # Note: snaptrade_user_id and snaptrade_user_secret are populated after user registration
- # via ensure_user_registered!, so we don't validate them on create
belongs_to :family
has_one_attached :logo, dependent: :purge_later
@@ -37,10 +33,10 @@ class SnaptradeItem < ApplicationRecord
has_many :linked_accounts, through: :snaptrade_accounts
scope :active, -> { where(scheduled_for_deletion: false) }
- scope :credentials_configured, -> { active.where.not(client_id: [ nil, "" ]).where.not(consumer_key: [ nil, "" ]) }
- # Syncable = active + fully configured (user registered with SnapTrade API)
- # Items without user registration will fail sync, so exclude them from auto-sync
- scope :syncable, -> { active.where.not(snaptrade_user_id: [ nil, "" ]).where.not(snaptrade_user_secret: [ nil, "" ]) }
+ # Syncable = active + authorized via OAuth (has an access token).
+ # 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 :ordered, -> { order(created_at: :desc) }
scope :needs_update, -> { where(status: :requires_update) }
@@ -52,13 +48,8 @@ class SnaptradeItem < ApplicationRecord
def import_latest_snaptrade_data(sync: nil)
provider = snaptrade_provider
unless provider
- Rails.logger.error "SnaptradeItem #{id} - Cannot import: provider is not configured"
- raise StandardError, "SnapTrade provider is not configured"
- end
-
- unless user_registered?
- Rails.logger.error "SnaptradeItem #{id} - Cannot import: user not registered"
- raise StandardError, "SnapTrade user not registered"
+ Rails.logger.error "SnaptradeItem #{id} - Cannot import: OAuth not authorized"
+ raise StandardError, "SnapTrade is not authorized"
end
SnaptradeItem::Importer.new(self, snaptrade_provider: provider, sync: sync).import
@@ -119,6 +110,20 @@ class SnaptradeItem < ApplicationRecord
save!
end
+ # Persist an OAuth token payload (string keys, as returned by the token endpoint).
+ # A rotation response may omit refresh_token; keep the existing one in that case.
+ def apply_oauth_tokens!(payload)
+ raise ArgumentError, "OAuth token payload missing access_token" if payload["access_token"].blank?
+
+ update!(
+ 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_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
+
def has_completed_initial_setup?
# Setup is complete if we have any linked accounts
accounts.any?
@@ -177,13 +182,14 @@ class SnaptradeItem < ApplicationRecord
end
end
- def credentials_configured?
- client_id.present? && consumer_key.present?
- end
-
def oauth_configured?
oauth_access_token.present?
end
+ alias_method :credentials_configured?, :oauth_configured?
+
+ def fully_configured?
+ oauth_configured?
+ end
# Override Syncable#syncing? to also show syncing state when activities are being
# fetched in the background. This ensures the UI shows the spinner until all data
@@ -192,10 +198,6 @@ class SnaptradeItem < ApplicationRecord
super || snaptrade_accounts.where(activities_fetch_pending: true).exists?
end
- def fully_configured?
- credentials_configured? && user_registered?
- end
-
# Get accounts linked via AccountProvider
def linked_snaptrade_accounts
snaptrade_accounts.joins(:account_provider)
diff --git a/app/models/snaptrade_item/importer.rb b/app/models/snaptrade_item/importer.rb
index 478f6c3ac2..967839fdf7 100644
--- a/app/models/snaptrade_item/importer.rb
+++ b/app/models/snaptrade_item/importer.rb
@@ -18,22 +18,13 @@ class SnaptradeItem::Importer
@sync = sync
end
- class CredentialsError < StandardError; end
-
def import
Rails.logger.info "SnaptradeItem::Importer - Starting import for item #{snaptrade_item.id}"
- credentials = snaptrade_item.snaptrade_credentials
- unless credentials
- raise CredentialsError, "No SnapTrade credentials configured for item #{snaptrade_item.id}"
- end
-
# Step 1: Fetch and store all accounts
- import_accounts(credentials)
+ import_accounts
# Step 2: For LINKED accounts only, fetch holdings and activities
- # Unlinked accounts just need basic info (name, balance) for the setup modal
- # Query directly to avoid any association caching issues
linked_accounts = SnaptradeAccount
.where(snaptrade_item_id: snaptrade_item.id)
.joins(:account_provider)
@@ -41,11 +32,9 @@ class SnaptradeItem::Importer
Rails.logger.info "SnaptradeItem::Importer - Found #{linked_accounts.count} linked accounts to process"
linked_accounts.each do |snaptrade_account|
- Rails.logger.info "SnaptradeItem::Importer - Processing linked account #{snaptrade_account.id} (#{snaptrade_account.snaptrade_account_id})"
- import_account_data(snaptrade_account, credentials)
+ import_account_data(snaptrade_account)
end
- # Update raw payload on the item
snaptrade_item.upsert_snaptrade_snapshot!(stats)
rescue Provider::Snaptrade::AuthenticationError => e
snaptrade_item.update!(status: :requires_update)
@@ -58,13 +47,9 @@ class SnaptradeItem::Importer
# get_account_activities returns a paginated object with .data accessor
# This handles both paginated responses and plain arrays
def extract_activities_from_response(response)
- if response.respond_to?(:data)
- # Paginated response (e.g., SnapTrade::PaginatedUniversalActivity)
- Rails.logger.info "SnaptradeItem::Importer - Paginated response, extracting .data (#{response.data&.size || 0} items)"
- response.data || []
+ if response.is_a?(Hash)
+ response["data"] || []
elsif response.is_a?(Array)
- # Direct array response
- Rails.logger.info "SnaptradeItem::Importer - Array response (#{response.size} items)"
response
else
Rails.logger.warn "SnaptradeItem::Importer - Unexpected response type: #{response.class}"
@@ -82,13 +67,10 @@ class SnaptradeItem::Importer
sync.update_columns(sync_stats: merged)
end
- def import_accounts(credentials)
+ def import_accounts
Rails.logger.info "SnaptradeItem::Importer - Fetching accounts"
- accounts_data = snaptrade_provider.list_accounts(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret]
- )
+ accounts_data = snaptrade_provider.list_accounts
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
stats["total_accounts"] = accounts_data.size
@@ -98,8 +80,8 @@ class SnaptradeItem::Importer
accounts_data.each do |account_data|
begin
- import_account(account_data, credentials)
- upstream_account_ids << account_data.id.to_s if account_data.id
+ import_account(account_data)
+ upstream_account_ids << account_data["id"].to_s if account_data["id"]
rescue => e
Rails.logger.error "SnaptradeItem::Importer - Failed to import account: #{e.message}"
stats["accounts_skipped"] = stats.fetch("accounts_skipped", 0) + 1
@@ -113,28 +95,24 @@ class SnaptradeItem::Importer
prune_removed_accounts(upstream_account_ids)
end
- def import_account(account_data, credentials)
+ def import_account(account_data)
# Find or create the SnaptradeAccount by SnapTrade's account ID
- snaptrade_account_id = account_data.id.to_s
+ snaptrade_account_id = account_data["id"].to_s
return if snaptrade_account_id.blank?
snaptrade_account = snaptrade_item.snaptrade_accounts.find_or_initialize_by(
snaptrade_account_id: snaptrade_account_id
)
- # Update from API data - pass raw SDK object, model handles conversion
+ # Update from API data - pass raw hash, model handles conversion
snaptrade_account.upsert_from_snaptrade!(account_data)
# Fetch and store balances
begin
- balances = snaptrade_provider.get_balances(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
- account_id: snaptrade_account_id
- )
+ balances = snaptrade_provider.get_balances(account_id: snaptrade_account_id)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
- # Pass raw SDK objects - model handles conversion
+ # Pass raw hashes - model handles conversion
snaptrade_account.upsert_balances!(balances)
rescue => e
Rails.logger.warn "SnaptradeItem::Importer - Failed to fetch balances for account #{snaptrade_account_id}: #{e.message}"
@@ -143,26 +121,22 @@ class SnaptradeItem::Importer
stats["accounts_imported"] = stats.fetch("accounts_imported", 0) + 1
end
- def import_account_data(snaptrade_account, credentials)
+ def import_account_data(snaptrade_account)
snaptrade_account_id = snaptrade_account.snaptrade_account_id
return if snaptrade_account_id.blank?
# Import holdings
- import_holdings(snaptrade_account, credentials)
+ import_holdings(snaptrade_account)
# Import activities (chunked for history)
- import_activities(snaptrade_account, credentials)
+ import_activities(snaptrade_account)
end
- def import_holdings(snaptrade_account, credentials)
+ def import_holdings(snaptrade_account)
Rails.logger.info "SnaptradeItem::Importer - Fetching holdings for account #{snaptrade_account.id} (#{snaptrade_account.snaptrade_account_id})"
begin
- holdings = snaptrade_provider.get_positions(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
- account_id: snaptrade_account.snaptrade_account_id
- )
+ holdings = snaptrade_provider.get_positions(account_id: snaptrade_account.snaptrade_account_id)
stats["api_requests"] = stats.fetch("api_requests", 0) + 1
Rails.logger.info "SnaptradeItem::Importer - Got #{holdings.size} holdings from API"
@@ -190,7 +164,7 @@ class SnaptradeItem::Importer
end
end
- def import_activities(snaptrade_account, credentials)
+ def import_activities(snaptrade_account)
Rails.logger.info "SnaptradeItem::Importer - Fetching activities for account #{snaptrade_account.id} (#{snaptrade_account.snaptrade_account_id})"
# Determine date range for fetching activities
@@ -213,7 +187,7 @@ class SnaptradeItem::Importer
# Respect user's sync_start_date floor
start_date = [ start_date, user_sync_start ].compact.max
Rails.logger.info "SnaptradeItem::Importer - Incremental activities fetch from #{start_date} (existing: #{existing_count})"
- fetch_all_activities(snaptrade_account, credentials, start_date: start_date)
+ fetch_all_activities(snaptrade_account, start_date: start_date)
else
# Full history - use user's sync_start_date if set, otherwise first_transaction_date
# Default to MAX_ACTIVITY_CHUNKS years ago to match chunk size
@@ -222,7 +196,7 @@ class SnaptradeItem::Importer
Rails.logger.info "SnaptradeItem::Importer - Full history fetch from #{start_date} (user_sync_start: #{user_sync_start || 'none'}, first_tx_date: #{first_tx_date || 'unknown'}, existing: #{existing_count})"
# Try to fetch activities synchronously first
- fetched_count = fetch_all_activities(snaptrade_account, credentials, start_date: start_date)
+ fetched_count = fetch_all_activities(snaptrade_account, start_date: start_date)
if fetched_count == 0 && existing_count == 0
# On fresh connection, SnapTrade may need time to sync data from brokerage
@@ -278,7 +252,7 @@ class SnaptradeItem::Importer
# Fetch all activities using per-account endpoint with proper date range
# Uses get_account_activities which returns paginated data for the specific account
- def fetch_all_activities(snaptrade_account, credentials, start_date:, end_date: nil)
+ def fetch_all_activities(snaptrade_account, start_date:, end_date: nil)
# Ensure dates are proper Date objects (not strings or other types)
start_date = ensure_date(start_date) || 5.years.ago.to_date
end_date = ensure_date(end_date) || Date.current
@@ -289,8 +263,6 @@ class SnaptradeItem::Importer
begin
# Use get_account_activities (per-account endpoint) for better results
response = snaptrade_provider.get_account_activities(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
account_id: snaptrade_account.snaptrade_account_id,
start_date: start_date,
end_date: end_date
@@ -309,7 +281,7 @@ class SnaptradeItem::Importer
if activities_data.size < 10 && (end_date - start_date).to_i > 365
Rails.logger.info "SnaptradeItem::Importer - Few results from per-account endpoint, trying cross-account endpoint"
cross_account_activities = fetch_via_cross_account_endpoint(
- snaptrade_account, credentials, start_date: start_date, end_date: end_date
+ snaptrade_account, start_date: start_date, end_date: end_date
)
if cross_account_activities.size > activities_data.size
@@ -337,10 +309,8 @@ class SnaptradeItem::Importer
end
# Fallback: try the cross-account endpoint which may work better for some brokerages
- def fetch_via_cross_account_endpoint(snaptrade_account, credentials, start_date:, end_date:)
+ def fetch_via_cross_account_endpoint(snaptrade_account, start_date:, end_date:)
activities = snaptrade_provider.get_activities(
- user_id: credentials[:user_id],
- user_secret: credentials[:user_secret],
start_date: start_date,
end_date: end_date,
accounts: snaptrade_account.snaptrade_account_id
diff --git a/app/models/snaptrade_item/provided.rb b/app/models/snaptrade_item/provided.rb
index b2bc91dece..8756cdd0c2 100644
--- a/app/models/snaptrade_item/provided.rb
+++ b/app/models/snaptrade_item/provided.rb
@@ -2,197 +2,56 @@ module SnaptradeItem::Provided
extend ActiveSupport::Concern
included do
- before_destroy :delete_snaptrade_user
+ before_destroy :revoke_oauth_tokens
end
def snaptrade_provider
- return nil unless credentials_configured?
+ return nil unless oauth_configured?
- Provider::Snaptrade.new(
- client_id: client_id,
- consumer_key: consumer_key
- )
- end
-
- def oauth_snaptrade_provider
- snaptrade_provider || Provider::Snaptrade.new
- end
-
- # Clean up SnapTrade user when item is destroyed
- def delete_snaptrade_user
- return unless user_registered?
-
- provider = snaptrade_provider
- return unless provider
-
- Rails.logger.info "SnapTrade: Deleting user #{snaptrade_user_id} for family #{family_id}"
-
- provider.delete_user(user_id: snaptrade_user_id)
-
- Rails.logger.info "SnapTrade: Successfully deleted user #{snaptrade_user_id}"
- rescue => e
- # Log but don't block deletion - user may not exist or credentials may be invalid
- Rails.logger.warn "SnapTrade: Failed to delete user #{snaptrade_user_id}: #{e.class} - #{e.message}"
- end
-
- # User ID and secret for SnapTrade API calls
- def snaptrade_credentials
- return nil unless snaptrade_user_id.present? && snaptrade_user_secret.present?
-
- {
- user_id: snaptrade_user_id,
- user_secret: snaptrade_user_secret
- }
- end
-
- # Check if user is registered with SnapTrade
- def user_registered?
- snaptrade_user_id.present? && snaptrade_user_secret.present?
- end
-
- # Register user with SnapTrade if not already registered
- # Returns true if registration succeeded or already registered
- # If existing credentials are invalid (user was deleted), clears them and re-registers
- def ensure_user_registered!
- # If we think we're registered, verify the user still exists
- if user_registered?
- if verify_user_exists?
- return true
- else
- # User was deleted from SnapTrade API - clear local credentials and re-register
- Rails.logger.warn "SnapTrade: User #{snaptrade_user_id} no longer exists, clearing credentials and re-registering"
- update!(snaptrade_user_id: nil, snaptrade_user_secret: nil)
- end
- end
-
- provider = snaptrade_provider
- raise StandardError, "SnapTrade provider not configured" unless provider
-
- # Use family ID with current timestamp to ensure uniqueness (avoids conflicts from previous deletions)
- unique_user_id = "family_#{family_id}_#{Time.current.to_i}"
-
- Rails.logger.info "SnapTrade: Registering user #{unique_user_id} for family #{family_id}"
-
- result = provider.register_user(unique_user_id)
-
- Rails.logger.info "SnapTrade: Successfully registered user #{result[:user_id]}"
-
- update!(
- snaptrade_user_id: result[:user_id],
- snaptrade_user_secret: result[:user_secret]
- )
-
- true
- rescue Provider::Snaptrade::ApiError => e
- Rails.logger.error "SnapTrade user registration failed: #{e.class} - #{e.message}"
- # Log status code but not response_body to avoid credential exposure
- Rails.logger.error "SnapTrade error details: status=#{e.status_code}" if e.respond_to?(:status_code)
- Rails.logger.debug { "SnapTrade response body: #{e.response_body&.truncate(500)}" } if e.respond_to?(:response_body)
-
- # Check if user already exists (shouldn't happen with timestamp suffix, but handle gracefully)
- if e.message.include?("already registered") || e.message.include?("already exists")
- Rails.logger.warn "SnapTrade: User already exists. Generating new unique ID."
- raise StandardError, "User registration conflict. Please try again."
- end
-
- raise
+ Provider::Snaptrade.new(self)
end
- # Verify that the stored user actually exists in SnapTrade
- # Returns false if user doesn't exist, credentials are invalid, or verification fails
- def verify_user_exists?
- return false unless snaptrade_user_id.present?
-
- provider = snaptrade_provider
- return false unless provider
-
- # Try to list connections - this will fail with 401/403 if user doesn't exist
- provider.list_connections(
- user_id: snaptrade_user_id,
- user_secret: snaptrade_user_secret
+ # Exchange an authorization code for tokens and mark the item usable.
+ def complete_oauth_exchange!(code:, redirect_uri:, code_verifier:)
+ payload = Provider::Snaptrade.exchange_code(
+ code: code,
+ redirect_uri: redirect_uri,
+ code_verifier: code_verifier
)
- true
- rescue Provider::Snaptrade::AuthenticationError => e
- Rails.logger.warn "SnapTrade: User verification failed - #{e.message}"
- false
- rescue Provider::Snaptrade::ApiError => e
- # Return false on API errors - caller can retry registration if needed
- Rails.logger.warn "SnapTrade: User verification error - #{e.message}"
- false
+ apply_oauth_tokens!(payload)
+ update!(status: :good)
+ payload
end
# Get the connection portal URL for linking brokerages
def connection_portal_url(redirect_url:, broker: nil)
- raise StandardError, "User not registered with SnapTrade" unless user_registered?
-
provider = snaptrade_provider
- raise StandardError, "SnapTrade provider not configured" unless provider
+ raise StandardError, "SnapTrade is not authorized" unless provider
- provider.get_connection_url(
- user_id: snaptrade_user_id,
- user_secret: snaptrade_user_secret,
- redirect_url: redirect_url,
- broker: broker
- )
+ provider.get_connection_url(redirect_url: redirect_url, broker: broker)
end
- def start_oauth_device_flow(scope: "read")
- oauth_snaptrade_provider.start_device_authorization(scope: scope)
- end
-
- def complete_oauth_device_flow!(device_code:)
- token_response = oauth_snaptrade_provider.poll_device_token(device_code: device_code)
- update!(
- oauth_access_token: token_response["access_token"],
- oauth_refresh_token: token_response["refresh_token"],
- oauth_token_type: token_response["token_type"],
- oauth_scope: token_response["scope"],
- oauth_token_expires_at: token_response["expires_in"].present? ? Time.current + token_response["expires_in"].to_i.seconds : nil
- )
- token_response
- end
-
- # Fetch all brokerage connections from SnapTrade API
- # Returns array of connection objects
+ # Fetch all brokerage connections from SnapTrade API. Returns Array<Hash>.
def fetch_connections
- return [] unless credentials_configured? && user_registered?
-
provider = snaptrade_provider
- creds = snaptrade_credentials
- provider.list_connections(user_id: creds[:user_id], user_secret: creds[:user_secret])
+ return [] unless provider
+
+ provider.list_connections
rescue Provider::Snaptrade::ApiError => e
Rails.logger.error "SnaptradeItem #{id} - Failed to list connections: #{e.message}"
raise
end
- # List all SnapTrade users registered under this client ID
- def list_all_users
- return [] unless credentials_configured?
-
- snaptrade_provider.list_users
- rescue Provider::Snaptrade::ApiError => e
- Rails.logger.error "SnaptradeItem #{id} - Failed to list users: #{e.message}"
- []
- end
+ private
- # Find orphaned SnapTrade users (registered but not current user)
- def orphaned_users
- return [] unless credentials_configured? && user_registered?
+ # Best-effort token revocation when the item is destroyed.
+ def revoke_oauth_tokens
+ token = oauth_refresh_token.presence || oauth_access_token
+ return if token.blank?
- all_users = list_all_users
- all_users.select { |uid| uid != snaptrade_user_id && uid.start_with?("family_#{family_id}_") }
- end
-
- # Delete an orphaned SnapTrade user and all their connections
- def delete_orphaned_user(user_id)
- return false unless credentials_configured?
- return false if user_id == snaptrade_user_id # Don't delete current user
- return false unless user_id.start_with?("family_#{family_id}_")
-
- snaptrade_provider.delete_user(user_id: user_id)
- true
- rescue Provider::Snaptrade::ApiError => e
- Rails.logger.error "SnaptradeItem #{id} - Failed to delete orphaned user #{user_id}: #{e.message}"
- false
- end
+ Provider::Snaptrade.revoke_token(token: token)
+ rescue => e
+ # Never block deletion on revocation failures
+ Rails.logger.warn "SnapTrade: Failed to revoke tokens for item #{id}: #{e.class} - #{e.message}"
+ end
end
diff --git a/app/models/snaptrade_item/syncer.rb b/app/models/snaptrade_item/syncer.rb
index 7e69a967f3..327f507eea 100644
--- a/app/models/snaptrade_item/syncer.rb
+++ b/app/models/snaptrade_item/syncer.rb
@@ -10,9 +10,9 @@ class SnaptradeItem::Syncer
def perform_sync(sync)
Rails.logger.info "SnaptradeItem::Syncer - Starting sync for item #{snaptrade_item.id}"
- # Verify user is registered
- unless snaptrade_item.user_registered?
- raise StandardError, "User not registered with SnapTrade"
+ # Verify the item is authorized
+ unless snaptrade_item.oauth_configured?
+ raise StandardError, "SnapTrade is not authorized"
end
# Phase 1: Import data from SnapTrade API
diff --git a/app/views/settings/providers/_snaptrade_panel.html.erb b/app/views/settings/providers/_snaptrade_panel.html.erb
index 565e89724a..ff45d08d47 100644
--- a/app/views/settings/providers/_snaptrade_panel.html.erb
+++ b/app/views/settings/providers/_snaptrade_panel.html.erb
@@ -8,154 +8,86 @@
<%
items = local_assigns[:snaptrade_items] || @snaptrade_items || Current.family.snaptrade_items.active.ordered
- active_items = items.select { |item| !item.scheduled_for_deletion? }
- snaptrade_item =
- active_items.first ||
- Current.family.snaptrade_items.build(name: "SnapTrade Connection")
- is_new_record = snaptrade_item.new_record?
- oauth_href =
- if snaptrade_item.persisted?
- oauth_connect_snaptrade_items_path(item_id: snaptrade_item.id)
- else
- oauth_connect_snaptrade_items_path
- end
- oauth_active = snaptrade_item.persisted? && snaptrade_item.oauth_token_active?
- oauth_button_text =
- if oauth_active
- t("providers.snaptrade.oauth_reauthorize_button", default: "Reauthorize")
- else
- t("providers.snaptrade.oauth_connect_button", default: "Authorize")
- end
+ snaptrade_item = items.reject(&:scheduled_for_deletion?).first
+ oauth_env_configured = Provider::Snaptrade.oauth_configured?
+ oauth_active = snaptrade_item&.oauth_token_active?
%>
- <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", default: "SnapTrade OAuth") %></p>
- <p class="text-sm text-secondary">
- <% if oauth_active %>
- <%= t("providers.snaptrade.oauth_status_authorized", default: "Authorized for SnapTrade.") %>
- <% else %>
- <%= t("providers.snaptrade.oauth_status_ready", default: "Use a device code to authorize Sure for SnapTrade.") %>
- <% end %>
- </p>
- </div>
- </div>
-
- <%= render DS::Link.new(
- text: oauth_button_text,
- icon: "external-link",
- variant: :primary,
- full_width: true,
- href: oauth_href,
- data: { turbo_frame: "drawer" }
- ) %>
- </div>
-
- <%= render DS::Disclosure.new(variant: :card_inset) do |disclosure| %>
- <% disclosure.with_summary_content do %>
- <div class="flex items-start justify-between gap-3">
- <div>
- <p class="text-sm font-medium text-primary">
- <%= t("providers.snaptrade.legacy_credentials_title", default: "Use legacy API credentials") %>
- </p>
- <p class="text-xs text-secondary mt-1">
- <%= t("providers.snaptrade.legacy_credentials_description", default: "Use Client ID and Consumer Key setup if your SnapTrade account has not enabled OAuth.") %>
+ <% if !oauth_env_configured %>
+ <%= render "settings/providers/setup_steps",
+ steps: [
+ t("providers.snaptrade.oauth_setup_step_1_html").html_safe,
+ t("providers.snaptrade.oauth_setup_step_2_html", callback_url: oauth_callback_snaptrade_items_url).html_safe,
+ 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") %>
+ <% else %>
+ <%= t("providers.snaptrade.oauth_status_ready") %>
+ <% end %>
</p>
</div>
- <%= icon(
- "chevron-down",
- class: "mt-0.5 text-secondary group-open:rotate-180 motion-safe:transition-transform motion-safe:duration-150"
- ) %>
</div>
- <% end %>
- <div class="mt-4 space-y-3">
- <%= render "settings/providers/setup_steps",
- steps: [
- t("providers.snaptrade.step_1_html").html_safe,
- t("providers.snaptrade.step_2"),
- t("providers.snaptrade.step_3"),
- t("providers.snaptrade.step_4")
- ] %>
-
- <%= styled_form_with model: snaptrade_item,
- url: is_new_record ? snaptrade_items_path : snaptrade_item_path(snaptrade_item),
- scope: :snaptrade_item,
- method: is_new_record ? :post : :patch,
- data: { turbo: true },
- class: "space-y-3" do |form| %>
- <%= form.text_field :client_id,
- label: t("providers.snaptrade.client_id_label"),
- placeholder: is_new_record ?
- t("providers.snaptrade.client_id_placeholder") :
- t("providers.snaptrade.client_id_update_placeholder"),
- type: :password %>
-
- <%= form.text_field :consumer_key,
- label: t("providers.snaptrade.consumer_key_label"),
- placeholder: is_new_record ?
- t("providers.snaptrade.consumer_key_placeholder") :
- t("providers.snaptrade.consumer_key_update_placeholder"),
- type: :password %>
-
- <div class="flex justify-end">
- <%= form.submit is_new_record ? t("providers.snaptrade.save_button") : t("providers.snaptrade.update_button") %>
- </div>
- <% end %>
+ <%= render DS::Link.new(
+ text: oauth_active ? t("providers.snaptrade.oauth_reauthorize_button") : t("providers.snaptrade.oauth_connect_button"),
+ icon: "external-link",
+ variant: :primary,
+ full_width: true,
+ href: snaptrade_item&.persisted? ?
+ oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id) :
+ oauth_authorize_snaptrade_items_path
+ ) %>
</div>
- <% end %>
- <% if snaptrade_item.persisted? %>
- <% unless snaptrade_item.user_registered? %>
- <div class="flex items-center gap-2 border-t border-primary pt-4 mt-4">
- <span class="w-2 h-2 bg-warning rounded-full"></span>
- <p class="text-sm text-secondary"><%= t("providers.snaptrade.status_needs_registration") %></p>
- </div>
- <% end %>
- <% end %>
-
- <% if snaptrade_item.persisted? && snaptrade_item.user_registered? %>
- <div class="border-t border-primary pt-4 mt-4">
- <%= render DS::Disclosure.new(
- variant: :inline,
- data: {
- controller: "lazy-load",
- action: "toggle->lazy-load#toggled",
- lazy_load_url_value: connections_snaptrade_item_path(snaptrade_item),
- lazy_load_auto_open_param_value: "manage"
- }
- ) do |disclosure| %>
- <% disclosure.with_summary_content do %>
- <div class="flex items-center justify-between">
- <div class="flex items-center gap-2">
- <p class="text-sm text-secondary">
- <%= t("providers.snaptrade.status_connected", count: snaptrade_item.snaptrade_accounts.count) %>
- <% if snaptrade_item.unlinked_accounts_count > 0 %>
- <span class="text-warning">(<%= t("providers.snaptrade.needs_setup", count: snaptrade_item.unlinked_accounts_count) %>)</span>
- <% end %>
- </p>
+ <% if snaptrade_item&.persisted? && snaptrade_item.oauth_configured? %>
+ <div class="border-t border-primary pt-4 mt-4">
+ <%= render DS::Disclosure.new(
+ variant: :inline,
+ data: {
+ controller: "lazy-load",
+ action: "toggle->lazy-load#toggled",
+ lazy_load_url_value: connections_snaptrade_item_path(snaptrade_item),
+ lazy_load_auto_open_param_value: "manage"
+ }
+ ) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-2">
+ <p class="text-sm text-secondary">
+ <%= t("providers.snaptrade.status_connected", count: snaptrade_item.snaptrade_accounts.count) %>
+ <% if snaptrade_item.unlinked_accounts_count > 0 %>
+ <span class="text-warning">(<%= t("providers.snaptrade.needs_setup", count: snaptrade_item.unlinked_accounts_count) %>)</span>
+ <% end %>
+ </p>
+ </div>
+ <span class="flex items-center gap-1 text-sm text-secondary hover:text-primary">
+ <%= t("providers.snaptrade.manage_connections") %>
+ <%= icon "chevron-right", class: "w-3 h-3 group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+ </span>
</div>
- <span class="flex items-center gap-1 text-sm text-secondary hover:text-primary">
- <%= t("providers.snaptrade.manage_connections") %>
- <%= icon "chevron-right", class: "w-3 h-3 group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
- </span>
- </div>
- <% end %>
+ <% end %>
- <div class="mt-3 space-y-3" data-lazy-load-target="content">
- <div data-lazy-load-target="loading" class="flex items-center gap-2 text-sm text-secondary py-2">
- <%= icon "loader-2", class: "w-4 h-4 animate-spin" %>
- <%= t("providers.snaptrade.loading_connections") %>
- </div>
+ <div class="mt-3 space-y-3" data-lazy-load-target="content">
+ <div data-lazy-load-target="loading" class="flex items-center gap-2 text-sm text-secondary py-2">
+ <%= icon "loader-2", class: "w-4 h-4 animate-spin" %>
+ <%= t("providers.snaptrade.loading_connections") %>
+ </div>
- <div data-lazy-load-target="frame">
+ <div data-lazy-load-target="frame">
+ </div>
</div>
- </div>
- <% end %>
- </div>
+ <% end %>
+ </div>
+ <% end %>
<% end %>
</div>
diff --git a/app/views/snaptrade_items/_connections_list.html.erb b/app/views/snaptrade_items/_connections_list.html.erb
index 3b329a7e62..b9118584cc 100644
--- a/app/views/snaptrade_items/_connections_list.html.erb
+++ b/app/views/snaptrade_items/_connections_list.html.erb
@@ -1,10 +1,10 @@
-<%# locals: (connections:, orphaned_users: [], snaptrade_item:, error: nil) %>
+<%# locals: (connections:, snaptrade_item:, error: nil) %>
<% if error.present? %>
<div class="p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
<%= t("providers.snaptrade.connections_error", message: error) %>
</div>
-<% elsif connections.empty? && orphaned_users.empty? %>
+<% elsif connections.empty? %>
<p class="text-sm text-secondary py-2">
<%= t("providers.snaptrade.no_connections") %>
</p>
@@ -65,50 +65,14 @@
</div>
<% end %>
- <%# Orphaned users (from previous registrations) %>
- <% if orphaned_users.any? %>
- <div class="border-t border-secondary pt-3 mt-3">
- <p class="text-xs text-warning font-medium mb-2">
- <%= icon "alert-triangle", size: "xs", class: "inline-block mr-1" %>
- <%= t("providers.snaptrade.orphaned_users_title", count: orphaned_users.size) %>
- </p>
- <p class="text-xs text-secondary mb-3">
- <%= t("providers.snaptrade.orphaned_users_description") %>
- </p>
-
- <% orphaned_users.each do |orphan| %>
- <div id="orphaned_user_<%= orphan[:user_id].parameterize %>"
- class="border rounded-lg p-3 border-warning/50 bg-warning/5 mb-2">
- <div class="flex items-center justify-between gap-3">
- <div class="min-w-0 flex-1">
- <p class="text-sm font-medium text-warning">
- <%= t("providers.snaptrade.orphaned_user") %>
- </p>
- <p class="text-xs text-secondary font-mono truncate" title="<%= orphan[:user_id] %>">
- <%= orphan[:display_name] %>
- </p>
- </div>
-
- <%= render DS::Menu.new do |menu| %>
- <% menu.with_item(
- variant: "button",
- text: t("providers.snaptrade.delete_orphaned_user"),
- icon: "trash-2",
- href: delete_orphaned_user_snaptrade_item_path(snaptrade_item, user_id: orphan[:user_id]),
- method: :delete,
- confirm: CustomConfirm.new(
- title: t("providers.snaptrade.delete_orphaned_user_title"),
- body: t("providers.snaptrade.delete_orphaned_user_body"),
- btn_text: t("providers.snaptrade.delete_orphaned_user_confirm"),
- destructive: true,
- high_severity: true
- )
- ) %>
- <% end %>
- </div>
- </div>
- <% end %>
- </div>
- <% end %>
+ <div class="border-t border-secondary pt-3 mt-3">
+ <%= render DS::Link.new(
+ text: t("providers.snaptrade.manage_at_snaptrade"),
+ icon: "external-link",
+ variant: :ghost,
+ href: Provider::Snaptrade::DASHBOARD_URL,
+ target: "_blank"
+ ) %>
+ </div>
</div>
<% end %>
diff --git a/app/views/snaptrade_items/_snaptrade_item.html.erb b/app/views/snaptrade_items/_snaptrade_item.html.erb
index 9ae436a5b4..35a9dbc741 100644
--- a/app/views/snaptrade_items/_snaptrade_item.html.erb
+++ b/app/views/snaptrade_items/_snaptrade_item.html.erb
@@ -2,8 +2,8 @@
<%= tag.div id: dom_id(snaptrade_item) do %>
<% unlinked_count = snaptrade_item.unlinked_accounts_count %>
- <% snaptrade_registered = snaptrade_item.user_registered? %>
- <% brokerage_connect_href = snaptrade_registered ? connect_snaptrade_item_path(snaptrade_item) : oauth_connect_snaptrade_items_path(item_id: snaptrade_item.id) %>
+ <% snaptrade_registered = snaptrade_item.oauth_configured? %>
+ <% brokerage_connect_href = snaptrade_registered ? connect_snaptrade_item_path(snaptrade_item) : oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id) %>
<% brokerage_connect_frame = snaptrade_registered ? "_top" : :drawer %>
<%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>
diff --git a/app/views/snaptrade_items/oauth_device_flow.html.erb b/app/views/snaptrade_items/oauth_device_flow.html.erb
deleted file mode 100644
index dead922369..0000000000
--- a/app/views/snaptrade_items/oauth_device_flow.html.erb
+++ /dev/null
@@ -1,112 +0,0 @@
-<%= render DS::Dialog.new(frame: "drawer", responsive: true, auto_open: true) do |dialog| %>
- <% dialog.with_header(custom_header: true) do %>
- <%= render "settings/providers/drawer_header",
- provider_key: "snaptrade",
- title: t("snaptrade_items.oauth_device_flow.title", default: "Connect SnapTrade") %>
- <% end %>
-
- <% dialog.with_body do %>
- <div class="space-y-4">
- <p class="text-sm text-secondary">
- <%= t("snaptrade_items.oauth_device_flow.subtitle", default: "Authorize Sure from SnapTrade") %>
- </p>
-
- <% if @error_message.present? %>
- <%= render DS::Alert.new(message: @error_message, variant: :error) %>
- <% end %>
-
- <% if @device_authorization.present? %>
- <div class="bg-surface-inset rounded-xl p-4 space-y-4">
- <p class="text-sm text-secondary">
- <%= t(
- "snaptrade_items.oauth_device_flow.instructions",
- default: "Open SnapTrade and confirm this device code, then return here to complete authorization."
- ) %>
- </p>
-
- <div class="space-y-1">
- <p class="text-xs uppercase text-secondary">
- <%= t("snaptrade_items.oauth_device_flow.code_label", default: "Device code") %>
- </p>
- <p class="text-2xl font-semibold text-primary font-mono"><%= @device_authorization["user_code"] %></p>
- </div>
-
- <%= render DS::Link.new(
- text: t("snaptrade_items.oauth_device_flow.open_snaptrade", default: "Open SnapTrade"),
- href: @device_authorization["verification_uri_complete"].presence || @device_authorization["verification_uri"],
- variant: :primary,
- icon: "external-link",
- target: "_blank",
- rel: "noopener noreferrer",
- full_width: true
- ) %>
- </div>
-
- <%= form_with url: complete_oauth_device_flow_snaptrade_item_path(@snaptrade_item),
- method: :post,
- data: { turbo_frame: "drawer" },
- class: "space-y-3" do %>
- <%= hidden_field_tag :device_code, @device_authorization["device_code"] %>
- <%= hidden_field_tag :user_code, @device_authorization["user_code"] %>
- <%= hidden_field_tag :verification_uri, @device_authorization["verification_uri"] %>
- <%= hidden_field_tag :verification_uri_complete, @device_authorization["verification_uri_complete"] %>
- <%= hidden_field_tag :expires_in, @device_authorization["expires_in"] %>
- <%= hidden_field_tag :interval, @device_authorization["interval"] %>
- <%= hidden_field_tag :return_to, @return_to if @return_to.present? %>
- <%= hidden_field_tag :accountable_type, @accountable_type if @accountable_type.present? %>
-
- <div class="flex justify-end gap-2">
- <%= render DS::Link.new(
- text: t("snaptrade_items.oauth_device_flow.cancel_button", default: "Cancel"),
- variant: :secondary,
- href: connect_form_settings_providers_path(provider_key: "snaptrade"),
- data: { turbo_frame: "drawer" }
- ) %>
- <%= render DS::Button.new(
- text: t("snaptrade_items.oauth_device_flow.complete_button", default: "I've authorized SnapTrade"),
- variant: :primary,
- icon: "check",
- type: :submit
- ) %>
- </div>
- <% end %>
- <% else %>
- <% if @error_message.blank? %>
- <%= form_with url: start_oauth_connect_snaptrade_items_path,
- method: :post,
- data: { turbo_frame: "drawer" },
- class: "space-y-3" do %>
- <%= hidden_field_tag :item_id, @snaptrade_item.id if @snaptrade_item&.persisted? %>
- <%= hidden_field_tag :scope, @oauth_scope if @oauth_scope.present? %>
- <%= hidden_field_tag :return_to, @return_to if @return_to.present? %>
- <%= hidden_field_tag :accountable_type, @accountable_type if @accountable_type.present? %>
-
- <div class="flex justify-end gap-2">
- <%= render DS::Link.new(
- text: t("snaptrade_items.oauth_device_flow.cancel_button", default: "Cancel"),
- variant: :secondary,
- href: connect_form_settings_providers_path(provider_key: "snaptrade"),
- data: { turbo_frame: "drawer" }
- ) %>
- <%= render DS::Button.new(
- text: t("snaptrade_items.oauth_device_flow.start_button", default: "Start authorization"),
- variant: :primary,
- icon: "external-link",
- type: :submit
- ) %>
- </div>
- <% end %>
- <% else %>
- <div class="flex justify-end">
- <%= render DS::Link.new(
- text: t("snaptrade_items.oauth_device_flow.cancel_button", default: "Cancel"),
- variant: :secondary,
- href: connect_form_settings_providers_path(provider_key: "snaptrade"),
- data: { turbo_frame: "drawer" }
- ) %>
- </div>
- <% end %>
- <% end %>
- </div>
- <% end %>
-<% end %>
diff --git a/app/views/snaptrade_items/setup_accounts.html.erb b/app/views/snaptrade_items/setup_accounts.html.erb
index 7bacde6f78..f736e9686e 100644
--- a/app/views/snaptrade_items/setup_accounts.html.erb
+++ b/app/views/snaptrade_items/setup_accounts.html.erb
@@ -71,16 +71,20 @@
</div>
<div class="flex gap-3 justify-center">
<%
- brokerage_connect_href = if @snaptrade_item.user_registered?
- connect_snaptrade_item_path(@snaptrade_item)
+ brokerage_connect_href = if @snaptrade_item.oauth_configured?
+ connect_snaptrade_item_path(
+ @snaptrade_item,
+ return_to: "setup_accounts",
+ accountable_type: params[:accountable_type]
+ )
else
- oauth_connect_snaptrade_items_path(
+ oauth_authorize_snaptrade_items_path(
item_id: @snaptrade_item.id,
accountable_type: params[:accountable_type],
return_to: params[:return_to]
)
end
- brokerage_connect_frame = @snaptrade_item.user_registered? ? "_top" : "drawer"
+ brokerage_connect_frame = @snaptrade_item.oauth_configured? ? "_top" : "drawer"
%>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.try_again", default: "Connect Brokerage"),
diff --git a/config/brakeman.ignore b/config/brakeman.ignore
index 07b34ca3e4..df46de563f 100644
--- a/config/brakeman.ignore
+++ b/config/brakeman.ignore
@@ -3,25 +3,48 @@
{
"warning_type": "Redirect",
"warning_code": 18,
- "fingerprint": "556f2fdd1f091ed50811cb2cce28dd2b987cd0a2eed4d19bea138c8c083a3a5d",
+ "fingerprint": "6d0cf62d5751106cd05dd3b4622beacaba9bdf91aaf798c2003a2a65e6bb903c",
"check_name": "Redirect",
"message": "Possible unprotected redirect",
"file": "app/controllers/snaptrade_items_controller.rb",
- "line": 125,
+ "line": 36,
"link": "https://brakemanscanner.org/docs/warning_types/redirect/",
- "code": "redirect_to(Current.family.snaptrade_items.find(params[:id]).connection_portal_url(:redirect_url => callback_snaptrade_items_url(:item_id => Current.family.snaptrade_items.find(params[:id]).id)), :allow_other_host => true)",
+ "code": "redirect_to(Current.family.snaptrade_items.find(params[:id]).connection_portal_url(:redirect_url => callback_snaptrade_items_url(:item_id => Current.family.snaptrade_items.find(params[:id]).id, :return_to => params[:return_to], :accountable_type => params[:accountable_type])), :allow_other_host => true)",
"render_path": null,
"location": {
"type": "method",
"class": "SnaptradeItemsController",
"method": "connect"
},
- "user_input": "Current.family.snaptrade_items.find(params[:id]).connection_portal_url(:redirect_url => callback_snaptrade_items_url(:item_id => Current.family.snaptrade_items.find(params[:id]).id))",
+ "user_input": "Current.family.snaptrade_items.find(params[:id]).connection_portal_url(:redirect_url => callback_snaptrade_items_url(:item_id => Current.family.snaptrade_items.find(params[:id]).id, :return_to => params[:return_to], :accountable_type => params[:accountable_type]))",
"confidence": "Weak",
"cwe_id": [
601
],
- "note": "Intentional redirect to SnapTrade's external OAuth portal for brokerage connection"
+ "note": "Intentional redirect to SnapTrade's external OAuth portal for brokerage connection. return_to/accountable_type are only used to route the user back to setup_accounts after the portal callback and are echoed verbatim, not used to build the redirect target itself."
+ },
+ {
+ "warning_type": "Redirect",
+ "warning_code": 18,
+ "fingerprint": "fc14dec97ce908f7483a8eb1f3aa6ea38f4369b8f9fe656e089c91a91c01a125",
+ "check_name": "Redirect",
+ "message": "Possible unprotected redirect",
+ "file": "app/controllers/snaptrade_items_controller.rb",
+ "line": 201,
+ "link": "https://brakemanscanner.org/docs/warning_types/redirect/",
+ "code": "redirect_to(Provider::Snaptrade.authorize_url(:redirect_uri => oauth_callback_snaptrade_items_url, :state => SecureRandom.hex(32), :code_challenge => Provider::Snaptrade.generate_pkce[:challenge]), :allow_other_host => true)",
+ "render_path": null,
+ "location": {
+ "type": "method",
+ "class": "SnaptradeItemsController",
+ "method": "oauth_authorize"
+ },
+ "user_input": "Provider::Snaptrade.authorize_url(:redirect_uri => oauth_callback_snaptrade_items_url, :state => SecureRandom.hex(32), :code_challenge => Provider::Snaptrade.generate_pkce[:challenge])",
+ "confidence": "Weak",
+ "cwe_id": [
+ 601
+ ],
+ "note": "Intentional redirect to SnapTrade's external OAuth authorize endpoint. URL is built entirely from Provider::Snaptrade::AUTHORIZE_URL (hardcoded constant), server-side oauth_client_id config, the internal oauth_callback_snaptrade_items_url named route, and locally generated SecureRandom state/PKCE values -- no request params are interpolated into the redirect target."
},
{
"warning_type": "Redirect",
diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb
index 5e4690a352..0db59bec41 100644
--- a/config/initializers/filter_parameter_logging.rb
+++ b/config/initializers/filter_parameter_logging.rb
@@ -6,5 +6,6 @@
Rails.application.config.filter_parameters += [
:passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :openai_access_token,
:client_id, :consumer_key, :snaptrade_user_id, :snaptrade_user_secret,
+ :oauth_access_token, :oauth_refresh_token, :code_verifier, :code_challenge,
:bank_username, :bank_password, :security_answers, :captcha_input
]
diff --git a/config/initializers/snaptrade.rb b/config/initializers/snaptrade.rb
index 990f8e9b39..25e55c08e2 100644
--- a/config/initializers/snaptrade.rb
+++ b/config/initializers/snaptrade.rb
@@ -2,4 +2,6 @@ Rails.application.configure do
config.x.snaptrade ||= ActiveSupport::OrderedOptions.new
config.x.snaptrade.oauth_client_id = ENV["SNAPTRADE_OAUTH_CLIENT_ID"].presence ||
Rails.application.credentials.dig(:snaptrade, :oauth_client_id)
+ config.x.snaptrade.oauth_client_secret = ENV["SNAPTRADE_OAUTH_CLIENT_SECRET"].presence ||
+ Rails.application.credentials.dig(:snaptrade, :oauth_client_secret)
end
diff --git a/config/locales/views/application/fr.yml b/config/locales/views/application/fr.yml
index 2b55cac33e..3b1d8e9773 100644
--- a/config/locales/views/application/fr.yml
+++ b/config/locales/views/application/fr.yml
@@ -198,7 +198,6 @@ fr:
one: Re-consentement nécessaire dans 1 jour
other: Renouvellement du consentement requis dans %{count} jours
reconsent_required: Re-consentement requis
- registration_needed: Inscription nécessaire
sync_error: Erreur de synchronisation
not_found: Fournisseur introuvable.
plaid_eu_panel:
diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.yml
index 61f70140df..0c8e99a954 100644
--- a/config/locales/views/settings/ca.yml
+++ b/config/locales/views/settings/ca.yml
@@ -442,7 +442,6 @@ ca:
one: Cal renovar el consentiment en 1 dia
other: Cal renovar el consentiment en %{count} dies
reconsent_required: Cal renovar el consentiment
- registration_needed: Cal registrar-se
sync_error: Error de sincronització
not_authorized: No autoritzat
not_found: Proveïdor no trobat.
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index f384e860c6..03b150ac1c 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -381,7 +381,6 @@ en:
meta:
sync_error: Sync error
no_recent_sync: Sync overdue
- registration_needed: Registration needed
reconsent_required: Re-consent required
reconsent_needed:
one: Re-consent needed in 1 day
diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.yml
index 4f9aa076fe..b443888003 100644
--- a/config/locales/views/settings/fr.yml
+++ b/config/locales/views/settings/fr.yml
@@ -414,7 +414,6 @@ fr:
one: Consentement requis dans 1 jour
other: Consentement requis dans %{count} jours
reconsent_required: Consentement requis
- registration_needed: Enregistrement requis
sync_error: Erreur de synchro
not_authorized: Non autorisé
not_found: Fournisseur non trouvé.
diff --git a/config/locales/views/settings/hu.yml b/config/locales/views/settings/hu.yml
index 5c5b7777b7..16c9ba68d3 100644
--- a/config/locales/views/settings/hu.yml
+++ b/config/locales/views/settings/hu.yml
@@ -262,7 +262,6 @@ hu:
meta:
sync_error: Szinkronizálási hiba
no_recent_sync: Szinkronizálás lejárt
- registration_needed: Regisztráció szükséges
reconsent_required: Újrahozzájárulás szükséges
reconsent_needed:
one: Újrahozzájárulás szükséges 1 napon belül
diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.yml
index afcb25a811..013cb4783e 100644
--- a/config/locales/views/settings/ru.yml
+++ b/config/locales/views/settings/ru.yml
@@ -493,7 +493,6 @@ ru:
one: Повторное согласие требуется через %{count} день
other: Повторное согласие требуется через %{count} дня
reconsent_required: Требуется повторное согласие
- registration_needed: Требуется регистрация
sync_error: Ошибка синхронизации
not_authorized: Не авторизован
not_found: Поставщик не найден.
diff --git a/config/locales/views/settings/vi.yml b/config/locales/views/settings/vi.yml
index dc6fc26bf5..612751b195 100644
--- a/config/locales/views/settings/vi.yml
+++ b/config/locales/views/settings/vi.yml
@@ -304,7 +304,6 @@ vi:
meta:
sync_error: Lỗi đồng bộ
no_recent_sync: Đồng bộ quá hạn
- registration_needed: Cần đăng ký
reconsent_required: Cần đồng ý lại
reconsent_needed:
one: Cần đồng ý lại sau 1 ngày
diff --git a/config/locales/views/settings/zh-CN.yml b/config/locales/views/settings/zh-CN.yml
index 4ff5487bd5..ef5dabeed9 100644
--- a/config/locales/views/settings/zh-CN.yml
+++ b/config/locales/views/settings/zh-CN.yml
@@ -304,7 +304,6 @@ zh-CN:
meta:
sync_error: 同步错误
no_recent_sync: 同步已逾期
- registration_needed: 需要注册
reconsent_required: 需要重新授权
reconsent_needed:
one: 1 天后需要重新授权
diff --git a/config/locales/views/snaptrade_items/ca.yml b/config/locales/views/snaptrade_items/ca.yml
index d270af3cf0..17df5f5425 100644
--- a/config/locales/views/snaptrade_items/ca.yml
+++ b/config/locales/views/snaptrade_items/ca.yml
@@ -5,28 +5,17 @@ ca:
accounts_count:
one: "%{count} compte"
other: "%{count} comptes"
- client_id_label: Client ID
- client_id_placeholder: Introdueix el teu Client ID de SnapTrade
- client_id_update_placeholder: Introdueix un nou Client ID per actualitzar
connect_button: Connecta un broker
connected_brokerages: 'Connectats:'
connection_description: Connecta't al teu broker a través de SnapTrade (25+
brokers admesos)
connections_error: 'No s''han pogut carregar les connexions: %{message}'
- consumer_key_label: Consumer Key
- consumer_key_placeholder: Introdueix la teva Consumer Key de SnapTrade
- consumer_key_update_placeholder: Introdueix un nou Consumer Key per actualitzar
delete_connection: Elimina
delete_connection_body: Això eliminarà permanentment la connexió de %{brokerage}
de SnapTrade. Tots els comptes d'aquest broker quedaran sense enllaçar. Hauràs
de reconnectar per sincronitzar aquests comptes de nou.
delete_connection_confirm: Elimina la connexió
delete_connection_title: Vols eliminar la connexió amb el broker?
- delete_orphaned_user: Elimina
- delete_orphaned_user_body: Això eliminarà permanentment aquest usuari orfe de
- SnapTrade i totes les seves connexions de broker, alliberant places de connexió.
- delete_orphaned_user_confirm: Elimina el registre
- delete_orphaned_user_title: Vols eliminar el registre orfe?
description: SnapTrade connecta amb més de 25 brokers importants (Fidelity,
Vanguard, Schwab, Robinhood, etc.) i proporciona l'historial complet d'operacions
amb etiquetes d'activitat i cost base.
@@ -41,28 +30,11 @@ ca:
other: "%{count} necessiten configuració"
no_connections: No s'han trobat connexions de broker.
orphaned_connection: Connexió orfe (no sincronitzada localment)
- orphaned_user: Registre orfe
- orphaned_users_description: Aquests són registres d'usuari de SnapTrade anteriors
- que ocupen places de connexió. Elimina'ls per alliberar places.
- orphaned_users_title:
- one: "%{count} registre orfe"
- other: "%{count} registres orfes"
- save_button: Desa la configuració
setup_accounts_button: Configura comptes
- setup_title: 'Instruccions de configuració:'
status_connected:
one: "%{count} compte de SnapTrade"
other: "%{count} comptes de SnapTrade"
- status_needs_registration: Credencials desades. Finalitza la configuració per
- connectar un broker.
status_ready: Llest per connectar brokers
- step_1_html: Crea un compte a <a href="https://dashboard.snaptrade.com" target="_blank"
- rel="noopener noreferrer" class="text-primary underline">dashboard.snaptrade.com</a>
- step_2: Copia el teu Client ID i Consumer Key des del panell
- step_3: Introdueix les teves credencials a continuació i fes clic a Desa
- step_4: Ves a la pàgina de comptes i utilitza 'Connecta un altre broker' per
- enllaçar els teus comptes d'inversió
- update_button: Actualitza la configuració
snaptrade_item:
brokerage_summary:
count:
@@ -108,8 +80,6 @@ ca:
aquesta connexió i torna-la a crear.
connections:
unknown_brokerage: Broker desconegut
- create:
- success: SnapTrade s'ha configurat correctament.
default_name: Connexió SnapTrade
delete_connection:
api_deletion_failed: No s'ha pogut eliminar la connexió de SnapTrade — falten
@@ -117,13 +87,8 @@ ca:
failed: 'No s''ha pogut eliminar la connexió: %{message}'
missing_authorization_id: Falta l'ID d'autorització
success: La connexió s'ha eliminat correctament. S'ha alliberat una plaça.
- delete_orphaned_user:
- failed: No s'ha pogut eliminar el registre orfe.
- success: El registre orfe s'ha eliminat correctament.
destroy:
success: S'ha programat la connexió SnapTrade per a la seva eliminació.
- link_accounts:
- use_setup_flow: Utilitza en el seu lloc el flux de configuració de comptes
link_existing_account:
failed: 'No s''ha pogut enllaçar el compte: %{message}'
not_found: No s'ha trobat el compte.
@@ -205,5 +170,3 @@ ca:
status: Darrera sincronització fa %{timestamp} - %{summary}
status_never: Mai sincronitzat
syncing: Sincronitzant...
- update:
- success: La configuració de SnapTrade s'ha actualitzat correctament.
diff --git a/config/locales/views/snaptrade_items/de.yml b/config/locales/views/snaptrade_items/de.yml
index 6ab8c28cf9..cf6a6775cf 100644
--- a/config/locales/views/snaptrade_items/de.yml
+++ b/config/locales/views/snaptrade_items/de.yml
@@ -2,10 +2,6 @@
de:
snaptrade_items:
default_name: "SnapTrade-Verbindung"
- create:
- success: "SnapTrade wurde erfolgreich eingerichtet."
- update:
- success: "SnapTrade-Konfiguration wurde erfolgreich aktualisiert."
destroy:
success: "SnapTrade-Verbindung wurde zur Löschung vorgemerkt."
connect:
@@ -50,9 +46,6 @@ de:
failed: "Löschen der Verbindung fehlgeschlagen: %{message}"
missing_authorization_id: "Autorisierungs-ID fehlt"
api_deletion_failed: "Verbindung konnte bei SnapTrade nicht gelöscht werden – Zugangsdaten fehlen. Die Verbindung kann in Ihrem SnapTrade-Konto noch existieren."
- delete_orphaned_user:
- success: "Verwaiste Registrierung wurde erfolgreich gelöscht."
- failed: "Löschen der verwaisten Registrierung fehlgeschlagen."
setup_accounts:
title: "SnapTrade-Konten einrichten"
header: "SnapTrade-Konten einrichten"
@@ -113,20 +106,7 @@ de:
name: "SnapTrade"
connection_description: "Verbinden Sie Ihren Broker über SnapTrade (25+ Broker unterstützt)"
description: "SnapTrade verbindet mit 25+ großen Brokern (Fidelity, Vanguard, Schwab, Robinhood usw.) und liefert vollständige Handelshistorie mit Aktivitätslabels und Einstandskosten."
- setup_title: "Einrichtungsanleitung:"
- step_1_html: "Konto erstellen unter <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a>"
- step_2: "Client ID und Consumer Key aus dem Dashboard kopieren"
- step_3: "Zugangsdaten unten eintragen und auf Speichern klicken"
- step_4: "Auf die Konten-Seite gehen und „Weiteren Broker verbinden“ nutzen, um Ihre Anlagekonten zu verknüpfen"
free_tier_warning: "Free Tier enthält 5 Broker-Verbindungen. Weitere erfordern einen kostenpflichtigen SnapTrade-Plan."
- client_id_label: "Client ID"
- client_id_placeholder: "SnapTrade Client ID eingeben"
- client_id_update_placeholder: "Neue Client ID zum Aktualisieren eingeben"
- consumer_key_label: "Consumer Key"
- consumer_key_placeholder: "SnapTrade Consumer Key eingeben"
- consumer_key_update_placeholder: "Neuen Consumer Key zum Aktualisieren eingeben"
- save_button: "Konfiguration speichern"
- update_button: "Konfiguration aktualisieren"
status_connected:
one: "%{count} Konto von SnapTrade"
other: "%{count} Konten von SnapTrade"
@@ -151,15 +131,6 @@ de:
delete_connection_title: "Broker-Verbindung löschen?"
delete_connection_body: "Die Verbindung zu %{brokerage} wird dauerhaft von SnapTrade entfernt. Alle Konten dieses Brokers werden getrennt. Zum erneuten Sync müssen Sie sich wieder verbinden."
delete_connection_confirm: "Verbindung löschen"
- orphaned_users_title:
- one: "%{count} verwaiste Registrierung"
- other: "%{count} verwaiste Registrierungen"
- orphaned_users_description: "Das sind frühere SnapTrade-Registrierungen, die Ihre Verbindungsplätze belegen. Löschen Sie sie, um Plätze freizugeben."
- orphaned_user: "Verwaiste Registrierung"
- delete_orphaned_user: "Löschen"
- delete_orphaned_user_title: "Verwaiste Registrierung löschen?"
- delete_orphaned_user_body: "Diese verwaiste SnapTrade-Registrierung und alle zugehörigen Broker-Verbindungen werden dauerhaft gelöscht, Verbindungsplätze werden frei."
- delete_orphaned_user_confirm: "Registrierung löschen"
snaptrade_item:
sync_status:
diff --git a/config/locales/views/snaptrade_items/en.yml b/config/locales/views/snaptrade_items/en.yml
index d176d71f9f..b327a85132 100644
--- a/config/locales/views/snaptrade_items/en.yml
+++ b/config/locales/views/snaptrade_items/en.yml
@@ -1,12 +1,6 @@
en:
snaptrade_items:
default_name: "SnapTrade Connection"
- link_accounts:
- use_setup_flow: Use the account setup flow instead
- create:
- success: "Successfully configured SnapTrade."
- update:
- success: "Successfully updated SnapTrade configuration."
destroy:
success: "Scheduled SnapTrade connection for deletion."
connect:
@@ -28,22 +22,13 @@ en:
not_configured: "SnapTrade is not configured."
select_accounts:
not_configured: "SnapTrade is not configured."
- oauth_device_flow:
- title: "Connect SnapTrade"
- subtitle: "Authorize Sure for SnapTrade"
- instructions: "Open SnapTrade and confirm this device code, then return here to complete authorization."
- code_label: "Device code"
- open_snaptrade: "Open SnapTrade"
- start_button: "Start authorization"
- complete_button: "I've authorized SnapTrade"
- cancel_button: "Cancel"
- missing_client_id: "SnapTrade OAuth client ID is not configured. Add SNAPTRADE_OAUTH_CLIENT_ID to .env.local, restart the app, then try again."
- complete_oauth_device_flow:
+ oauth_authorize:
+ not_configured: "SnapTrade OAuth is not configured. Set SNAPTRADE_OAUTH_CLIENT_ID and SNAPTRADE_OAUTH_CLIENT_SECRET, restart the app, then try again."
+ oauth_callback:
success: "SnapTrade authorization complete."
- setup_incomplete: "SnapTrade authorization is complete, but API credentials are required before accounts can sync."
- failed: "Unable to complete SnapTrade OAuth device authorization. Please try again."
- start_oauth_device_flow:
- failed: "Unable to start SnapTrade OAuth device authorization. Please try again."
+ access_denied: "SnapTrade authorization was cancelled."
+ state_mismatch: "SnapTrade authorization failed a security check. Please try again."
+ failed: "Unable to complete SnapTrade authorization. Please try again."
select_existing_account:
not_found: "Account or SnapTrade configuration not found."
title: "Link to SnapTrade Account"
@@ -66,10 +51,7 @@ en:
success: "Connection deleted successfully. One slot freed up."
failed: "Failed to delete connection: %{message}"
missing_authorization_id: "Missing authorization ID"
- api_deletion_failed: "Could not delete connection from SnapTrade - missing credentials. The connection may still exist in your SnapTrade account."
- delete_orphaned_user:
- success: "Orphaned registration deleted successfully."
- failed: "Failed to delete orphaned registration."
+ api_deletion_failed: "Could not delete connection from SnapTrade - this item is not authorized. The connection may still exist in your SnapTrade account."
setup_accounts:
title: "Set Up SnapTrade Accounts"
header: "Set Up Your SnapTrade Accounts"
@@ -132,31 +114,18 @@ en:
name: "SnapTrade"
connection_description: "Connect to your brokerage via SnapTrade (25+ brokers supported)"
description: "SnapTrade connects to 25+ major brokerages (Fidelity, Vanguard, Schwab, Robinhood, etc.) and provides full trade history with activity labels and cost basis."
- setup_title: "Setup instructions:"
- step_1_html: "Create an account at <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a>"
- step_2: "Copy your Client ID and Consumer Key from the dashboard"
- step_3: "Enter your credentials below and click Save"
- step_4: "Go to the Accounts page and use 'Connect another brokerage' to link your investment accounts"
+ oauth_setup_step_1_html: "Register an OAuth app at <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"underline\">dashboard.snaptrade.com</a>"
+ oauth_setup_step_2_html: "Add this app's callback URL (<code>%{callback_url}</code>) as a registered redirect URI"
+ oauth_setup_step_3: "Set SNAPTRADE_OAUTH_CLIENT_ID and SNAPTRADE_OAUTH_CLIENT_SECRET in your environment and restart"
free_tier_warning: "SnapTrade's free tier covers 20 brokerage connections."
oauth_title: "SnapTrade OAuth"
- oauth_status_ready: "Use a device code to authorize Sure for SnapTrade."
+ oauth_status_ready: "Authorize Sure to read your SnapTrade account data."
oauth_status_authorized: "Authorized with SnapTrade."
oauth_connect_button: "Connect with SnapTrade"
oauth_reauthorize_button: "Reauthorize"
- legacy_credentials_title: "Use legacy API credentials"
- legacy_credentials_description: "Use Client ID and Consumer Key setup if your SnapTrade account has not enabled OAuth."
- client_id_label: "Client ID"
- client_id_placeholder: "Enter your SnapTrade Client ID"
- client_id_update_placeholder: "Enter new Client ID to update"
- consumer_key_label: "Consumer Key"
- consumer_key_placeholder: "Enter your SnapTrade Consumer Key"
- consumer_key_update_placeholder: "Enter new Consumer Key to update"
- save_button: "Save Configuration"
- update_button: "Update Configuration"
status_connected:
one: "%{count} account from SnapTrade"
other: "%{count} accounts from SnapTrade"
- status_needs_registration: "Credentials saved. Finish setup to connect a brokerage."
needs_setup:
one: "%{count} needs setup"
other: "%{count} need setup"
@@ -177,15 +146,7 @@ en:
delete_connection_title: "Delete Brokerage Connection?"
delete_connection_body: "This will permanently remove the %{brokerage} connection from SnapTrade. All accounts from this brokerage will be unlinked. You'll need to reconnect to sync these accounts again."
delete_connection_confirm: "Delete Connection"
- orphaned_users_title:
- one: "%{count} orphaned registration"
- other: "%{count} orphaned registrations"
- orphaned_users_description: "These are previous SnapTrade user registrations that are using your connection slots. Delete them to free up slots."
- orphaned_user: "Orphaned Registration"
- delete_orphaned_user: "Delete"
- delete_orphaned_user_title: "Delete Orphaned Registration?"
- delete_orphaned_user_body: "This will permanently delete this orphaned SnapTrade user and all their brokerage connections, freeing up connection slots."
- delete_orphaned_user_confirm: "Delete Registration"
+ manage_at_snaptrade: "Manage connections at SnapTrade"
snaptrade_item:
sync_status:
diff --git a/config/locales/views/snaptrade_items/es.yml b/config/locales/views/snaptrade_items/es.yml
index db087fff93..333fc10d24 100644
--- a/config/locales/views/snaptrade_items/es.yml
+++ b/config/locales/views/snaptrade_items/es.yml
@@ -2,10 +2,6 @@
es:
snaptrade_items:
default_name: "Conexión de SnapTrade"
- create:
- success: "SnapTrade configurado correctamente."
- update:
- success: "Configuración de SnapTrade actualizada correctamente."
destroy:
success: "Conexión de SnapTrade programada para su eliminación."
connect:
@@ -50,9 +46,6 @@ es:
failed: "Error al eliminar la conexión: %{message}"
missing_authorization_id: "Falta el ID de autorización"
api_deletion_failed: "No se pudo eliminar la conexión de SnapTrade por falta de credenciales. Es posible que la conexión aún exista en tu cuenta de SnapTrade."
- delete_orphaned_user:
- success: "Registro huérfano eliminado correctamente."
- failed: "Error al eliminar el registro huérfano."
setup_accounts:
title: "Configurar cuentas de SnapTrade"
header: "Configura tus cuentas de SnapTrade"
@@ -113,20 +106,7 @@ es:
name: "SnapTrade"
connection_description: "Conecta con tu bróker a través de SnapTrade (más de 25 brókers compatibles)"
description: "SnapTrade conecta con más de 25 brókers principales (Fidelity, Vanguard, Schwab, Robinhood, etc.) y proporciona un historial completo de operaciones con etiquetas de actividad y base de costes."
- setup_title: "Instrucciones de configuración:"
- step_1_html: "Crea una cuenta en <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a>"
- step_2: "Copia tu Client ID y tu Consumer Key desde el panel"
- step_3: "Introduce tus credenciales a continuación y haz clic en Guardar"
- step_4: "Ve a la página de Cuentas y usa 'Conectar otro bróker' para vincular tus cuentas de inversión"
free_tier_warning: "El nivel gratuito incluye 5 conexiones de bróker. Las conexiones adicionales requieren un plan de pago de SnapTrade."
- client_id_label: "Client ID"
- client_id_placeholder: "Introduce tu Client ID de SnapTrade"
- client_id_update_placeholder: "Introduce el nuevo Client ID para actualizar"
- consumer_key_label: "Consumer Key"
- consumer_key_placeholder: "Introduce tu Consumer Key de SnapTrade"
- consumer_key_update_placeholder: "Introduce la nueva Consumer Key para actualizar"
- save_button: "Guardar configuración"
- update_button: "Actualizar configuración"
status_connected:
one: "%{count} cuenta de SnapTrade"
other: "%{count} cuentas de SnapTrade"
@@ -151,15 +131,6 @@ es:
delete_connection_title: "¿Eliminar conexión del bróker?"
delete_connection_body: "Esto eliminará permanentemente la conexión de %{brokerage} de SnapTrade. Todas las cuentas de este bróker se desvincularán. Deberás volver a conectar para sincronizar estas cuentas de nuevo."
delete_connection_confirm: "Eliminar conexión"
- orphaned_users_title:
- one: "%{count} registro huérfano"
- other: "%{count} registros huérfanos"
- orphaned_users_description: "Estos son registros de usuario de SnapTrade anteriores que están ocupando tus espacios de conexión. Elimínalos para liberar espacio."
- orphaned_user: "Registro huérfano"
- delete_orphaned_user: "Eliminar"
- delete_orphaned_user_title: "¿Eliminar registro huérfano?"
- delete_orphaned_user_body: "Esto eliminará permanentemente este usuario de SnapTrade huérfano y todas sus conexiones de bróker, liberando espacios de conexión."
- delete_orphaned_user_confirm: "Eliminar registro"
snaptrade_item:
sync_status:
diff --git a/config/locales/views/snaptrade_items/fr.yml b/config/locales/views/snaptrade_items/fr.yml
index 02452712fc..8b9335060b 100644
--- a/config/locales/views/snaptrade_items/fr.yml
+++ b/config/locales/views/snaptrade_items/fr.yml
@@ -5,29 +5,17 @@ fr:
accounts_count:
one: "%{count} compte"
other: "%{count} comptes"
- client_id_label: Client ID
- client_id_placeholder: Saisissez votre Client ID SnapTrade
- client_id_update_placeholder: Saisissez un nouveau Client ID pour mettre à jour
connect_button: Connecter un courtier
connected_brokerages: 'Connectés :'
connection_description: Connectez-vous à votre courtier via SnapTrade (plus de 25 courtiers pris en charge)
connection_limit_info: L'offre gratuite SnapTrade autorise 5 connexions de courtier. Supprimez les connexions inutilisées pour libérer des emplacements.
connections_error: 'Échec du chargement des connexions : %{message}'
- consumer_key_label: Consumer Key
- consumer_key_placeholder: Saisissez votre Consumer Key SnapTrade
- consumer_key_update_placeholder: Saisissez une nouvelle Consumer Key pour mettre à jour
delete_connection: Supprimer
delete_connection_body: Cela supprimera définitivement la connexion %{brokerage} de SnapTrade. Tous les comptes de ce courtier seront déliés. Vous devrez vous reconnecter pour synchroniser à nouveau ces comptes.
delete_connection_confirm: Supprimer la connexion
delete_connection_title: Supprimer la connexion de courtier ?
- delete_orphaned_user: Supprimer
- delete_orphaned_user_body: Cela supprimera définitivement cet utilisateur SnapTrade orphelin et toutes ses connexions de courtier, libérant ainsi des emplacements de connexion.
- delete_orphaned_user_confirm: Supprimer l'enregistrement
- delete_orphaned_user_title: Supprimer l'enregistrement orphelin ?
description: SnapTrade se connecte à plus de 25 courtiers majeurs (Fidelity, Vanguard, Schwab, Robinhood, etc.) et fournit l'historique complet des transactions avec des libellés d'activité et le coût d'acquisition.
free_tier_warning: L'offre gratuite inclut 5 connexions de courtier. Les connexions supplémentaires nécessitent un forfait SnapTrade payant.
- legacy_credentials_description: Utilisez la configuration Client ID et Consumer Key si votre compte SnapTrade n'a pas activé OAuth.
- legacy_credentials_title: Utiliser les identifiants API hérités
loading_connections: Chargement des connexions…
manage_connections: Gérer les connexions
name: SnapTrade
@@ -42,24 +30,11 @@ fr:
oauth_status_ready: Utilisez un code d'appareil pour autoriser Sure pour SnapTrade.
oauth_title: SnapTrade OAuth
orphaned_connection: Connexion orpheline (non synchronisée localement)
- orphaned_user: Enregistrement orphelin
- orphaned_users_description: Il s'agit d'anciens enregistrements d'utilisateurs SnapTrade qui occupent vos emplacements de connexion. Supprimez-les pour libérer des emplacements.
- orphaned_users_title:
- one: "%{count} enregistrement orphelin"
- other: "%{count} enregistrements orphelins"
- save_button: Enregistrer la configuration
setup_accounts_button: Configurer les comptes
- setup_title: 'Instructions de configuration :'
status_connected:
one: "%{count} compte depuis SnapTrade"
other: "%{count} comptes depuis SnapTrade"
- status_needs_registration: Identifiants enregistrés. Terminez la configuration pour connecter une maison de courtage.
status_ready: Prêt à connecter des courtiers
- step_1_html: Créez un compte sur <a href="https://dashboard.snaptrade.com" target="_blank" rel="noopener noreferrer" class="text-primary underline">dashboard.snaptrade.com</a>
- step_2: Copiez votre Client ID et votre Consumer Key depuis le tableau de bord
- step_3: Saisissez vos identifiants ci-dessous et cliquez sur Enregistrer
- step_4: Rendez-vous sur la page Comptes et utilisez « Connecter un autre courtier » pour lier vos comptes d'investissement
- update_button: Mettre à jour la configuration
snaptrade_item:
brokerage_summary:
count:
@@ -98,44 +73,23 @@ fr:
success:
one: "%{count} compte lié avec succès."
other: "%{count} comptes liés avec succès."
- complete_oauth_device_flow:
- failed: Impossible de terminer l'autorisation d'appareil SnapTrade OAuth. Veuillez réessayer.
- setup_incomplete: L'autorisation SnapTrade est terminée, mais des identifiants API sont requis avant de pouvoir synchroniser les comptes.
- success: Autorisation SnapTrade terminée.
connect:
connection_failed: 'Échec de la connexion à SnapTrade : %{message}'
decryption_failed: Impossible de lire les identifiants SnapTrade. Veuillez supprimer et recréer cette connexion.
connections:
unknown_brokerage: Courtier inconnu
- create:
- success: Configuration SnapTrade réussie.
default_name: Connexion SnapTrade
delete_connection:
api_deletion_failed: Impossible de supprimer la connexion de SnapTrade - identifiants manquants. La connexion peut toujours exister dans votre compte SnapTrade.
failed: 'Échec de la suppression de la connexion : %{message}'
missing_authorization_id: Identifiant d'autorisation manquant
success: Connexion supprimée avec succès. Un emplacement libéré.
- delete_orphaned_user:
- failed: Échec de la suppression de l'enregistrement orphelin.
- success: Enregistrement orphelin supprimé avec succès.
destroy:
success: Connexion SnapTrade mise en file d'attente pour suppression.
- link_accounts:
- use_setup_flow: Utilisez plutôt le flux de configuration du compte
link_existing_account:
failed: 'Échec de la liaison du compte : %{message}'
not_found: Compte introuvable.
success: Compte SnapTrade lié avec succès.
- oauth_device_flow:
- cancel_button: Annuler
- code_label: Code d'appareil
- complete_button: J'ai autorisé SnapTrade
- instructions: Ouvrez SnapTrade et confirmez ce code d'appareil, puis revenez ici pour terminer l'autorisation.
- missing_client_id: L'identifiant client SnapTrade OAuth n'est pas configuré. Ajoutez SNAPTRADE_OAUTH_CLIENT_ID dans .env.local, redémarrez l'application, puis réessayez.
- open_snaptrade: Ouvrir SnapTrade
- start_button: Démarrer l'autorisation
- subtitle: Autoriser Sure pour SnapTrade
- title: Connecter SnapTrade
preload_accounts:
not_configured: SnapTrade n'est pas configuré.
select_accounts:
@@ -208,7 +162,3 @@ fr:
status: Dernière synchronisation il y a %{timestamp} - %{summary}
status_never: Jamais synchronisé
syncing: Synchronisation…
- start_oauth_device_flow:
- failed: Impossible de démarrer l'autorisation d'appareil SnapTrade OAuth. Veuillez réessayer.
- update:
- success: Configuration SnapTrade mise à jour.
diff --git a/config/locales/views/snaptrade_items/hu.yml b/config/locales/views/snaptrade_items/hu.yml
index dab3d05ce8..d8799bdae5 100644
--- a/config/locales/views/snaptrade_items/hu.yml
+++ b/config/locales/views/snaptrade_items/hu.yml
@@ -2,12 +2,6 @@
hu:
snaptrade_items:
default_name: "SnapTrade kapcsolat"
- link_accounts:
- use_setup_flow: Használd helyette a számlabeállítási folyamatot
- create:
- success: "SnapTrade sikeresen beállítva."
- update:
- success: "SnapTrade konfiguráció sikeresen frissítve."
destroy:
success: "SnapTrade kapcsolat törlése ütemezve."
connect:
@@ -52,9 +46,6 @@ hu:
failed: "Nem sikerült törölni a kapcsolatot: %{message}"
missing_authorization_id: "Hiányzó engedélyezési azonosító"
api_deletion_failed: "Nem sikerült törölni a kapcsolatot a SnapTrade-ből — hiányzó hitelesítő adatok. A kapcsolat még mindig létezhet a SnapTrade fiókodon."
- delete_orphaned_user:
- success: "Árva regisztráció sikeresen törölve."
- failed: "Nem sikerült törölni az árva regisztrációt."
setup_accounts:
title: "SnapTrade számlák beállítása"
header: "SnapTrade számlák beállítása"
@@ -117,27 +108,13 @@ hu:
name: "SnapTrade"
connection_description: "Csatlakozás a brókereidhez a SnapTrade-en keresztül (25+ bróker támogatott)"
description: "A SnapTrade 25+ nagyobb brókercéghez csatlakozik (Fidelity, Vanguard, Schwab, Robinhood stb.), és teljes kereskedési előzményeket biztosít tevékenységcímkékkel és bekerülési értékkel."
- setup_title: "Beállítási utasítások:"
- step_1_html: "Hozz létre fiókot a <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a> oldalon"
- step_2: "Másold ki az Ügyfél-azonosítót és a Fogyasztói kulcsot az irányítópultból"
- step_3: "Add meg a hitelesítő adatokat alább, majd kattints a Mentésre"
- step_4: "Menj a Számlák oldalra, és az 'Másik brókercég csatlakoztatása' opcióval kapcsold össze a befektetési számláidat"
free_tier_warning: "Az ingyenes szint 5 bróker kapcsolatot tartalmaz. További kapcsolatokhoz fizetős SnapTrade előfizetés szükséges."
- client_id_label: "Ügyfél-azonosító"
- client_id_placeholder: "Add meg a SnapTrade ügyfél-azonosítódat"
- client_id_update_placeholder: "Add meg az új ügyfél-azonosítót a frissítéshez"
- consumer_key_label: "Fogyasztói kulcs"
- consumer_key_placeholder: "Add meg a SnapTrade fogyasztói kulcsodat"
- consumer_key_update_placeholder: "Add meg az új fogyasztói kulcsot a frissítéshez"
- save_button: "Konfiguráció mentése"
- update_button: "Konfiguráció frissítése"
status_connected:
one: "%{count} számla a SnapTrade-ből"
other: "%{count} számla a SnapTrade-ből"
needs_setup:
one: "%{count} beállítást igényel"
other: "%{count} beállítást igényel"
- status_needs_registration: "Hitelesítő adatok elmentve. Fejezd be a beállítást egy brókercég csatlakoztatásához."
status_ready: "Készen áll brókercégek csatlakoztatásához"
setup_accounts_button: "Számlák beállítása"
connect_button: "Brókercég csatlakoztatása"
@@ -156,15 +133,6 @@ hu:
delete_connection_title: "Brókeri kapcsolat törlése?"
delete_connection_body: "Ez véglegesen eltávolítja a(z) %{brokerage} kapcsolatot a SnapTrade-ből. Az ehhez a brókercéghez tartozó összes számla szétkapcsolásra kerül. A számlák újbóli szinkronizálásához újra kell csatlakoznod."
delete_connection_confirm: "Kapcsolat törlése"
- orphaned_users_title:
- one: "%{count} árva regisztráció"
- other: "%{count} árva regisztráció"
- orphaned_users_description: "Ezek korábbi SnapTrade felhasználói regisztrációk, amelyek a kapcsolati helyeidet foglalják. Töröl őket a helyek felszabadításához."
- orphaned_user: "Árva regisztráció"
- delete_orphaned_user: "Törlés"
- delete_orphaned_user_title: "Árva regisztráció törlése?"
- delete_orphaned_user_body: "Ez véglegesen törli ezt az árva SnapTrade felhasználót és az összes brókeri kapcsolatát, felszabadítva a kapcsolati helyeket."
- delete_orphaned_user_confirm: "Regisztráció törlése"
snaptrade_item:
sync_status:
diff --git a/config/locales/views/snaptrade_items/pl.yml b/config/locales/views/snaptrade_items/pl.yml
index 1f45a3aa18..c6819616c6 100644
--- a/config/locales/views/snaptrade_items/pl.yml
+++ b/config/locales/views/snaptrade_items/pl.yml
@@ -2,10 +2,6 @@
pl:
snaptrade_items:
default_name: Połączenie SnapTrade
- create:
- success: Pomyślnie skonfigurowano SnapTrade.
- update:
- success: Pomyślnie zaktualizowano konfigurację SnapTrade.
destroy:
success: Zaplanowano usunięcie połączenia SnapTrade.
connect:
@@ -54,9 +50,6 @@ pl:
failed: 'Nie udało się usunąć połączenia: %{message}'
missing_authorization_id: Brak identyfikatora autoryzacji
api_deletion_failed: Nie można usunąć połączenia z SnapTrade — brak danych uwierzytelniających. Połączenie może nadal istnieć na koncie SnapTrade.
- delete_orphaned_user:
- success: Osierocona rejestracja została usunięta pomyślnie.
- failed: Nie udało się usunąć osieroconej rejestracji.
setup_accounts:
title: Skonfiguruj konta SnapTrade
header: Skonfiguruj swoje konta SnapTrade
@@ -120,20 +113,7 @@ pl:
name: SnapTrade
connection_description: Połącz się ze swoim biurem maklerskim przez SnapTrade (obsługuje 25+ brokerów)
description: SnapTrade łączy się z ponad 25 głównymi biurami maklerskimi (Fidelity, Vanguard, Schwab, Robinhood itp.) i udostępnia pełną historię transakcji z etykietami aktywności oraz podstawą kosztową.
- setup_title: 'Instrukcje konfiguracji:'
- step_1_html: Utwórz konto na <a href="https://dashboard.snaptrade.com" target="_blank" rel="noopener noreferrer" class="text-primary underline">dashboard.snaptrade.com</a>
- step_2: Skopiuj swój Client ID i Consumer Key z pulpitu nawigacyjnego
- step_3: Wprowadź swoje dane uwierzytelniające poniżej i kliknij Zapisz
- step_4: Przejdź do strony Konta i użyj opcji „Połącz kolejne biuro maklerskie", aby połączyć swoje konta inwestycyjne
free_tier_warning: Plan bezpłatny obejmuje 5 połączeń z biurami maklerskimi. Dodatkowe połączenia wymagają płatnego planu SnapTrade.
- client_id_label: Client ID
- client_id_placeholder: Wprowadź Client ID SnapTrade
- client_id_update_placeholder: Wprowadź nowy Client ID, aby zaktualizować
- consumer_key_label: Consumer Key
- consumer_key_placeholder: Wprowadź Consumer Key SnapTrade
- consumer_key_update_placeholder: Wprowadź nowy Consumer Key, aby zaktualizować
- save_button: Zapisz konfigurację
- update_button: Zaktualizuj konfigurację
status_connected:
one: "%{count} konto z SnapTrade"
few: "%{count} konta z SnapTrade"
@@ -164,17 +144,6 @@ pl:
delete_connection_title: Usunąć połączenie z biurem maklerskim?
delete_connection_body: Spowoduje to trwałe usunięcie połączenia %{brokerage} z SnapTrade. Wszystkie konta tego biura maklerskiego zostaną odłączone. Będziesz musiał ponownie się połączyć, aby synchronizować te konta.
delete_connection_confirm: Usuń połączenie
- orphaned_users_title:
- one: "%{count} osierocona rejestracja"
- few: "%{count} osierocone rejestracje"
- many: "%{count} osieroconych rejestracji"
- other: "%{count} osieroconych rejestracji"
- orphaned_users_description: Są to poprzednie rejestracje użytkowników SnapTrade, które zajmują Twoje miejsca połączeń. Usuń je, aby zwolnić miejsca.
- orphaned_user: Osierocona rejestracja
- delete_orphaned_user: Usuń
- delete_orphaned_user_title: Usunąć osieroconą rejestrację?
- delete_orphaned_user_body: Spowoduje to trwałe usunięcie tej osieroconej rejestracji użytkownika SnapTrade i wszystkich jego połączeń z biurami maklerskimi, zwalniając miejsca połączeń.
- delete_orphaned_user_confirm: Usuń rejestrację
snaptrade_item:
sync_status:
no_accounts: Nie znaleziono kont
diff --git a/config/locales/views/snaptrade_items/ru.yml b/config/locales/views/snaptrade_items/ru.yml
index a5ee5dc75f..9ff33cf80f 100644
--- a/config/locales/views/snaptrade_items/ru.yml
+++ b/config/locales/views/snaptrade_items/ru.yml
@@ -7,36 +7,22 @@ ru:
many: "%{count} счетов"
one: "%{count} счёт"
other: "%{count} счёта"
- client_id_label: Client ID
- client_id_placeholder: Введите ваш SnapTrade Client ID
- client_id_update_placeholder: Введите новый Client ID для обновления
connect_button: Подключить брокера
connected_brokerages: 'Подключено:'
connection_description: Подключитесь к вашему брокеру через SnapTrade (поддерживается
более 25 брокеров)
connections_error: 'Не удалось загрузить подключения: %{message}'
- consumer_key_label: Consumer Key
- consumer_key_placeholder: Введите ваш SnapTrade Consumer Key
- consumer_key_update_placeholder: Введите новый Consumer Key для обновления
delete_connection: Удалить
delete_connection_body: Это навсегда удалит подключение %{brokerage} из SnapTrade.
Все счета этого брокера будут отвязаны. Вам нужно будет переподключиться,
чтобы снова синхронизировать эти счета.
delete_connection_confirm: Удалить подключение
delete_connection_title: Удалить подключение брокера?
- delete_orphaned_user: Удалить
- delete_orphaned_user_body: Это навсегда удалит этого неиспользуемого пользователя
- SnapTrade и все его подключения брокеров, освобождая слоты подключения.
- delete_orphaned_user_confirm: Удалить регистрацию
- delete_orphaned_user_title: Удалить неиспользуемую регистрацию?
description: SnapTrade подключается к более чем 25 крупным брокерам (Fidelity,
Vanguard, Schwab, Robinhood и др.) и предоставляет полную историю торгов с
метками активности и стоимостью.
free_tier_warning: Бесплатный тариф SnapTrade покрывает 5 подключений брокеров.
Обновите на SnapTrade для большего количества.
- legacy_credentials_description: Используйте Client ID и Consumer Key, если в
- вашем аккаунте SnapTrade не включён OAuth.
- legacy_credentials_title: Использовать устаревшие API-данные
loading_connections: Загрузка подключений...
manage_connections: Управление подключениями
name: SnapTrade
@@ -53,32 +39,13 @@ ru:
oauth_status_ready: Используйте код устройства, чтобы авторизовать Sure в SnapTrade.
oauth_title: SnapTrade OAuth
orphaned_connection: Неиспользуемое подключение (не синхронизировано локально)
- orphaned_user: Неиспользуемая регистрация
- orphaned_users_description: Это предыдущие регистрации пользователей SnapTrade,
- которые занимают ваши слоты подключения. Удалите их, чтобы освободить слоты.
- orphaned_users_title:
- few: "%{count} неиспользуемые регистрации"
- many: "%{count} неиспользуемых регистраций"
- one: "%{count} неиспользуемая регистрация"
- other: "%{count} неиспользуемые регистрации"
- save_button: Сохранить конфигурацию
setup_accounts_button: Настроить счета
- setup_title: 'Инструкции по настройке:'
status_connected:
few: "%{count} счёта из SnapTrade"
many: "%{count} счетов из SnapTrade"
one: "%{count} счёт из SnapTrade"
other: "%{count} счёта из SnapTrade"
- status_needs_registration: Учетные данные сохранены. Завершите настройку для
- подключения брокера.
status_ready: Готово к подключению брокеров
- step_1_html: Создайте аккаунт на <a href="https://dashboard.snaptrade.com" target="_blank"
- rel="noopener noreferrer" class="text-primary underline">dashboard.snaptrade.com</a>
- step_2: Скопируйте ваш Client ID и Consumer Key из панели управления
- step_3: Введите ваши учетные данные ниже и нажмите Сохранить
- step_4: Перейдите на страницу Счета и используйте 'Подключить другого брокера',
- чтобы связать ваши инвестиционные счета
- update_button: Обновить конфигурацию
snaptrade_item:
brokerage_summary:
count:
@@ -128,20 +95,12 @@ ru:
many: Успешно связано %{count} счетов.
one: Успешно связан %{count} счёт.
other: Успешно связаны %{count} счёта.
- complete_oauth_device_flow:
- failed: Не удалось завершить авторизацию SnapTrade через device flow.
- Попробуйте ещё раз.
- setup_incomplete: Авторизация SnapTrade завершена, но для синхронизации счетов
- требуются API-данные.
- success: Авторизация SnapTrade завершена.
connect:
connection_failed: 'Не удалось подключиться к SnapTrade: %{message}'
decryption_failed: Не удалось прочитать учетные данные SnapTrade. Пожалуйста,
удалите и создайте это подключение заново.
connections:
unknown_brokerage: Неизвестный брокер
- create:
- success: SnapTrade успешно настроен.
default_name: Подключение SnapTrade
delete_connection:
api_deletion_failed: Не удалось удалить подключение из SnapTrade - отсутствуют
@@ -149,29 +108,12 @@ ru:
failed: 'Не удалось удалить подключение: %{message}'
missing_authorization_id: Отсутствует ID авторизации
success: Подключение успешно удалено. Один слот освобождён.
- delete_orphaned_user:
- failed: Не удалось удалить неиспользуюмую регистрацию.
- success: Неиспользуюмая регистрация успешно удалена.
destroy:
success: Подключение SnapTrade запланировано на удаление.
- link_accounts:
- use_setup_flow: Используйте процесс настройки счёта вместо этого
link_existing_account:
failed: 'Не удалось связать счёт: %{message}'
not_found: Счёт не найден.
success: Успешно связан со счётом SnapTrade.
- oauth_device_flow:
- cancel_button: Отмена
- code_label: Код устройства
- complete_button: Я авторизовал SnapTrade
- instructions: Откройте SnapTrade и подтвердите этот код устройства, затем вернитесь
- сюда, чтобы завершить авторизацию.
- missing_client_id: Не настроен SnapTrade OAuth client ID. Добавьте
- SNAPTRADE_OAUTH_CLIENT_ID в .env.local, перезапустите приложение и попробуйте снова.
- open_snaptrade: Открыть SnapTrade
- start_button: Начать авторизацию
- subtitle: Авторизуйте Sure в SnapTrade
- title: Подключение SnapTrade
preload_accounts:
not_configured: SnapTrade не настроен.
select_accounts:
@@ -252,8 +194,3 @@ ru:
status: Последняя синхронизация %{timestamp} назад - %{summary}
status_never: Никогда не синхронизировалось
syncing: Синхронизация...
- start_oauth_device_flow:
- failed: Не удалось начать авторизацию SnapTrade по коду устройства. Попробуйте
- ещё раз.
- update:
- success: Конфигурация SnapTrade успешно обновлена.
diff --git a/config/locales/views/snaptrade_items/vi.yml b/config/locales/views/snaptrade_items/vi.yml
index 61a95981d0..0c963ddc65 100644
--- a/config/locales/views/snaptrade_items/vi.yml
+++ b/config/locales/views/snaptrade_items/vi.yml
@@ -1,12 +1,6 @@
vi:
snaptrade_items:
default_name: "Kết nối SnapTrade"
- link_accounts:
- use_setup_flow: Sử dụng luồng thiết lập tài khoản
- create:
- success: "Đã cấu hình SnapTrade thành công."
- update:
- success: "Đã cập nhật cấu hình SnapTrade thành công."
destroy:
success: "Đã lên lịch xóa kết nối SnapTrade."
connect:
@@ -51,9 +45,6 @@ vi:
failed: "Xóa kết nối thất bại: %{message}"
missing_authorization_id: "Thiếu ID ủy quyền"
api_deletion_failed: "Không thể xóa kết nối khỏi SnapTrade - thiếu thông tin xác thực. Kết nối có thể vẫn tồn tại trong tài khoản SnapTrade của bạn."
- delete_orphaned_user:
- success: "Đã xóa đăng ký mồ côi thành công."
- failed: "Xóa đăng ký mồ côi thất bại."
setup_accounts:
title: "Thiết lập tài khoản SnapTrade"
header: "Thiết lập tài khoản SnapTrade của bạn"
@@ -116,24 +107,10 @@ vi:
name: "SnapTrade"
connection_description: "Kết nối với brokerage qua SnapTrade (hỗ trợ 25+ sàn)"
description: "SnapTrade kết nối với 25+ brokerage lớn (Fidelity, Vanguard, Schwab, Robinhood, v.v.) và cung cấp lịch sử giao dịch đầy đủ với nhãn hoạt động và cơ sở chi phí."
- setup_title: "Hướng dẫn thiết lập:"
- step_1_html: "Tạo tài khoản tại <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a>"
- step_2: "Sao chép Client ID và Consumer Key từ bảng điều khiển"
- step_3: "Nhập thông tin xác thực bên dưới và nhấn Lưu"
- step_4: "Đi đến trang Tài khoản và dùng 'Kết nối thêm brokerage' để liên kết tài khoản đầu tư"
free_tier_warning: "Gói miễn phí SnapTrade hỗ trợ 5 kết nối brokerage. Nâng cấp trên SnapTrade để có thêm."
- client_id_label: "Client ID"
- client_id_placeholder: "Nhập Client ID SnapTrade của bạn"
- client_id_update_placeholder: "Nhập Client ID mới để cập nhật"
- consumer_key_label: "Consumer Key"
- consumer_key_placeholder: "Nhập Consumer Key SnapTrade của bạn"
- consumer_key_update_placeholder: "Nhập Consumer Key mới để cập nhật"
- save_button: "Lưu cấu hình"
- update_button: "Cập nhật cấu hình"
status_connected:
one: "%{count} tài khoản từ SnapTrade"
other: "%{count} tài khoản từ SnapTrade"
- status_needs_registration: "Đã lưu thông tin xác thực. Hoàn tất thiết lập để kết nối brokerage."
needs_setup:
one: "%{count} cần thiết lập"
other: "%{count} cần thiết lập"
@@ -154,15 +131,6 @@ vi:
delete_connection_title: "Xóa kết nối Brokerage?"
delete_connection_body: "Thao tác này sẽ xóa vĩnh viễn kết nối %{brokerage} khỏi SnapTrade. Tất cả tài khoản từ brokerage này sẽ bị hủy liên kết. Bạn cần kết nối lại để đồng bộ các tài khoản này."
delete_connection_confirm: "Xóa kết nối"
- orphaned_users_title:
- one: "%{count} đăng ký mồ côi"
- other: "%{count} đăng ký mồ côi"
- orphaned_users_description: "Đây là các đăng ký người dùng SnapTrade cũ đang sử dụng slot kết nối của bạn. Xóa chúng để giải phóng slot."
- orphaned_user: "Đăng ký mồ côi"
- delete_orphaned_user: "Xóa"
- delete_orphaned_user_title: "Xóa đăng ký mồ côi?"
- delete_orphaned_user_body: "Thao tác này sẽ xóa vĩnh viễn người dùng SnapTrade mồ côi này và tất cả kết nối brokerage của họ, giải phóng slot kết nối."
- delete_orphaned_user_confirm: "Xóa đăng ký"
snaptrade_item:
sync_status:
diff --git a/config/locales/views/snaptrade_items/zh-CN.yml b/config/locales/views/snaptrade_items/zh-CN.yml
index caac3138db..ed0cb01073 100644
--- a/config/locales/views/snaptrade_items/zh-CN.yml
+++ b/config/locales/views/snaptrade_items/zh-CN.yml
@@ -2,12 +2,6 @@
zh-CN:
snaptrade_items:
default_name: "SnapTrade 连接"
- link_accounts:
- use_setup_flow: 请改用账户设置流程
- create:
- success: SnapTrade 配置成功。
- update:
- success: SnapTrade 配置已更新。
destroy:
success: SnapTrade 连接已安排删除。
connect:
@@ -52,9 +46,6 @@ zh-CN:
failed: 删除连接失败:%{message}
missing_authorization_id: 缺少授权 ID
api_deletion_failed: 无法从 SnapTrade 删除连接 - 缺少凭据。该连接可能仍存在于您的 SnapTrade 账户中。
- delete_orphaned_user:
- success: 孤立注册已成功删除。
- failed: 删除孤立注册失败。
setup_accounts:
title: 设置 SnapTrade 账户
header: 设置您的 SnapTrade 账户
@@ -116,24 +107,10 @@ zh-CN:
name: "SnapTrade"
connection_description: 通过 SnapTrade 连接您的券商(支持 25+ 券商)
description: "SnapTrade 连接 25+ 主流券商(Fidelity、Vanguard、Schwab、Robinhood 等),并提供带活动标签和成本基础的完整交易历史。"
- setup_title: "设置说明:"
- step_1_html: "在 <a href=\"https://dashboard.snaptrade.com\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"text-primary underline\">dashboard.snaptrade.com</a> 创建账户"
- step_2: "从仪表盘复制您的 Client ID 和 Consumer Key"
- step_3: "在下方输入您的凭据并点击保存"
- step_4: "前往账户页面,使用“连接另一个券商”来关联您的投资账户"
free_tier_warning: "SnapTrade 免费套餐覆盖 5 个券商连接。更多功能请在 SnapTrade 升级。"
- client_id_label: "Client ID"
- client_id_placeholder: "输入您的 SnapTrade Client ID"
- client_id_update_placeholder: "输入新的 Client ID 以更新"
- consumer_key_label: "Consumer Key"
- consumer_key_placeholder: "输入您的 SnapTrade Consumer Key"
- consumer_key_update_placeholder: "输入新的 Consumer Key 以更新"
- save_button: "保存配置"
- update_button: "更新配置"
status_connected:
one: "%{count} 个来自 SnapTrade 的账户"
other: "%{count} 个来自 SnapTrade 的账户"
- status_needs_registration: "凭据已保存。完成设置后即可连接券商。"
needs_setup:
one: "%{count} 个需要设置"
other: "%{count} 个需要设置"
@@ -154,15 +131,6 @@ zh-CN:
delete_connection_title: "删除券商连接?"
delete_connection_body: "这将永久从 SnapTrade 中移除 %{brokerage} 连接。该券商的所有账户都会取消关联。您需要重新连接才能再次同步这些账户。"
delete_connection_confirm: "删除连接"
- orphaned_users_title:
- one: "%{count} 个孤立注册"
- other: "%{count} 个孤立注册"
- orphaned_users_description: "这些是之前使用您连接名额的 SnapTrade 用户注册。删除它们可释放名额。"
- orphaned_user: "孤立注册"
- delete_orphaned_user: "删除"
- delete_orphaned_user_title: "删除孤立注册?"
- delete_orphaned_user_body: "这将永久删除该孤立的 SnapTrade 用户及其所有券商连接,释放连接名额。"
- delete_orphaned_user_confirm: "删除注册"
snaptrade_item:
sync_status:
no_accounts: "未找到账户"
diff --git a/config/routes.rb b/config/routes.rb
index 006108f576..b44bc74092 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -127,16 +127,15 @@ Rails.application.routes.draw do
end
end
- resources :snaptrade_items, only: [ :index, :new, :create, :show, :edit, :update, :destroy ] do
+ resources :snaptrade_items, only: [ :index, :show, :destroy ] do
collection do
get :preload_accounts
get :select_accounts
- post :link_accounts
get :select_existing_account
post :link_existing_account
get :callback
- get :oauth_connect
- post :start_oauth_connect
+ get :oauth_authorize
+ get :oauth_callback
end
member do
@@ -145,10 +144,7 @@ Rails.application.routes.draw do
get :setup_accounts
post :complete_account_setup
get :connections
- post :start_oauth_device_flow
- post :complete_oauth_device_flow
delete :delete_connection
- delete :delete_orphaned_user
end
end
diff --git a/db/migrate/20260710120000_mark_legacy_snaptrade_items_requiring_update.rb b/db/migrate/20260710120000_mark_legacy_snaptrade_items_requiring_update.rb
new file mode 100644
index 0000000000..937847420e
--- /dev/null
+++ b/db/migrate/20260710120000_mark_legacy_snaptrade_items_requiring_update.rb
@@ -0,0 +1,16 @@
+class MarkLegacySnaptradeItemsRequiringUpdate < ActiveRecord::Migration[7.2]
+ # Data-only: legacy items (connected via client_id/consumer_key, no OAuth
+ # tokens) can no longer sync and must be reconnected via the OAuth flow.
+ def up
+ execute <<~SQL
+ UPDATE snaptrade_items
+ SET status = 'requires_update'
+ WHERE (oauth_access_token IS NULL OR oauth_access_token = '')
+ AND scheduled_for_deletion = FALSE
+ SQL
+ end
+
+ def down
+ # Irreversible data migration; no-op
+ end
+end
diff --git a/test/controllers/api/v1/provider_connections_controller_test.rb b/test/controllers/api/v1/provider_connections_controller_test.rb
index 957b5aa31b..6b851077f7 100644
--- a/test/controllers/api/v1/provider_connections_controller_test.rb
+++ b/test/controllers/api/v1/provider_connections_controller_test.rb
@@ -144,7 +144,7 @@ class Api::V1::ProviderConnectionsControllerTest < ActionDispatch::IntegrationTe
end
test "excludes another family's provider connections" do
- other_item = snaptrade_items(:pending_registration_item)
+ other_item = snaptrade_items(:unauthorized_item)
get api_v1_provider_connections_url, headers: api_headers(@api_key)
assert_response :success
@@ -176,6 +176,20 @@ class Api::V1::ProviderConnectionsControllerTest < ActionDispatch::IntegrationTe
assert_equal brex_item.unlinked_accounts_count, brex_connection["accounts"]["unlinked_count"]
end
+ test "reports credentials_configured true for an authorized SnapTrade item" do
+ snaptrade_item = snaptrade_items(:configured_item)
+
+ get api_v1_provider_connections_url, headers: api_headers(@api_key)
+ assert_response :success
+
+ snaptrade_connection = JSON.parse(response.body)["data"].detect do |connection|
+ connection["id"] == snaptrade_item.id && connection["provider"] == "snaptrade"
+ end
+
+ assert_not_nil snaptrade_connection
+ assert_equal true, snaptrade_connection["credentials_configured"]
+ end
+
test "returns an empty list when no provider connections exist" do
ProviderConnectionStatus.stub(:for_family, []) do
get api_v1_provider_connections_url, headers: api_headers(@api_key)
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index 5137b3b578..8d93c088bf 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -422,6 +422,44 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
assert_match(/Query ID/i, response.body)
end
+ test "GET connect_form for snaptrade shows OAuth setup instructions 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_includes response.body, I18n.t("providers.snaptrade.oauth_setup_step_3")
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_connect_button")
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready")
+ end
+
+ test "GET connect_form for snaptrade shows connect CTA when configured but item is not authorized" do
+ sign_in users(:empty)
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+
+ get connect_form_settings_providers_path(provider_key: "snaptrade")
+
+ assert_response :success
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_connect_button")
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready")
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_status_authorized")
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_reauthorize_button")
+ end
+
+ test "GET connect_form for snaptrade shows authorized status and reauthorize CTA when item is connected" do
+ # Default signed-in user (family_admin) belongs to dylan_family, which owns
+ # the oauth-authorized `configured_item` fixture.
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+
+ get connect_form_settings_providers_path(provider_key: "snaptrade")
+
+ assert_response :success
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_status_authorized")
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_reauthorize_button")
+ assert_includes response.body, I18n.t("providers.snaptrade.manage_connections")
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_connect_button")
+ end
+
test "POST sync for ibkr without an active Ibkr sync enqueues SyncJob" do
item = ibkr_items(:configured_item)
Sync.where(syncable_type: "IbkrItem", syncable_id: item.id).delete_all
diff --git a/test/controllers/snaptrade_items_controller_test.rb b/test/controllers/snaptrade_items_controller_test.rb
index 9c8bcf212b..60dc27c63c 100644
--- a/test/controllers/snaptrade_items_controller_test.rb
+++ b/test/controllers/snaptrade_items_controller_test.rb
@@ -12,9 +12,19 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "connect redirects to portal when successful" do
+ portal_url = "https://app.snaptrade.com/portal/test123"
+
+ SnaptradeItem.any_instance.stubs(:connection_portal_url).returns(portal_url)
+
+ get connect_snaptrade_item_url(@snaptrade_item)
+
+ assert_redirected_to portal_url
+ end
+
test "connect handles decryption error gracefully" do
SnaptradeItem.any_instance
- .stubs(:user_registered?)
+ .stubs(:connection_portal_url)
.raises(ActiveRecord::Encryption::Errors::Decryption.new("cannot decrypt"))
get connect_snaptrade_item_url(@snaptrade_item)
@@ -25,7 +35,7 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
test "connect handles general error gracefully" do
SnaptradeItem.any_instance
- .stubs(:user_registered?)
+ .stubs(:connection_portal_url)
.raises(StandardError.new("something broke"))
get connect_snaptrade_item_url(@snaptrade_item)
@@ -34,306 +44,132 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
assert_match(/Failed to connect/, flash[:alert])
end
- test "connect redirects to portal when successful" do
- portal_url = "https://app.snaptrade.com/portal/test123"
-
- SnaptradeItem.any_instance.stubs(:user_registered?).returns(true)
- SnaptradeItem.any_instance.stubs(:connection_portal_url).returns(portal_url)
-
- get connect_snaptrade_item_url(@snaptrade_item)
-
- assert_redirected_to portal_url
+ test "oauth_authorize stores state and verifier in session and redirects to SnapTrade" do
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+
+ get oauth_authorize_snaptrade_items_url
+
+ assert_response :redirect
+ redirect = URI.parse(response.location)
+ assert_equal "dashboard.snaptrade.com", redirect.host
+ params = Rack::Utils.parse_query(redirect.query)
+ oauth_session = session[:snaptrade_oauth]
+ assert_equal oauth_session["state"], params["state"]
+ assert_equal "S256", params["code_challenge_method"]
+ assert oauth_session["code_verifier"].present?
+ assert oauth_session["item_id"].present?
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
end
- test "complete oauth device flow preserves provider oauth error fields" do
- error = Provider::Snaptrade::ApiError.new(
- "SnapTrade OAuth error (poll_device_token): authorization_pending",
- status_code: 400,
- response_body: {
- error: "authorization_pending",
- error_description: "The user has not completed authorization",
- error_uri: "https://api.snaptrade.com/docs/oauth",
- interval: 5
- }.to_json
- )
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .raises(error)
-
- post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item), params: { device_code: "device-code" }, as: :json
-
- assert_response :bad_request
- payload = JSON.parse(response.body)
- assert_equal "authorization_pending", payload["error"]
- assert_equal "The user has not completed authorization", payload["error_description"]
- assert_equal "https://api.snaptrade.com/docs/oauth", payload["error_uri"]
- assert_equal 5, payload["interval"]
- end
-
- test "complete oauth device flow falls back to api error message without json body" do
- error = Provider::Snaptrade::ApiError.new(
- "SnapTrade OAuth error (poll_device_token): invalid response",
- status_code: 502,
- response_body: "upstream unavailable"
- )
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .raises(error)
-
- post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item), params: { device_code: "device-code" }, as: :json
+ test "oauth_authorize redirects to settings when OAuth is not configured" do
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
- assert_response :bad_gateway
- payload = JSON.parse(response.body)
- assert_equal "SnapTrade OAuth error (poll_device_token): invalid response", payload["error"]
+ get oauth_authorize_snaptrade_items_url
+ assert_redirected_to settings_providers_path
end
- test "complete oauth device flow does not expose non-api provider error details" do
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .raises(Provider::Snaptrade::ConfigurationError.new("missing secret at /srv/app/config.yml"))
+ test "oauth_callback rejects state mismatch without exchanging the code" do
+ Provider::Snaptrade.expects(:exchange_code).never
- post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item), params: { device_code: "device-code" }, as: :json
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ get oauth_authorize_snaptrade_items_url
- assert_response :unprocessable_entity
- payload = JSON.parse(response.body)
- assert_equal "Unable to complete SnapTrade OAuth device authorization. Please try again.", payload["error"]
- end
+ get oauth_callback_snaptrade_items_url(code: "c0de", state: "wrong-state")
- test "start oauth device flow does not expose provider error details" do
- SnaptradeItem.any_instance
- .stubs(:start_oauth_device_flow)
- .raises(Provider::Snaptrade::ApiError.new("upstream leaked internal path /srv/app/config.yml"))
-
- post start_oauth_device_flow_snaptrade_item_url(@snaptrade_item)
-
- assert_response :unprocessable_entity
- payload = JSON.parse(response.body)
- assert_equal "Unable to start SnapTrade OAuth device authorization. Please try again.", payload["error"]
+ assert_redirected_to settings_providers_path
+ assert flash[:alert].present?
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
end
- test "start oauth device flow falls back to read for invalid scope" do
- SnaptradeItem.any_instance
- .expects(:start_oauth_device_flow)
- .with(scope: "read")
- .returns("device_code" => "device-code")
-
- post start_oauth_device_flow_snaptrade_item_url(@snaptrade_item), params: { scope: "write" }
-
- assert_response :success
- assert_equal "device-code", JSON.parse(response.body)["device_code"]
+ test "oauth_callback handles access_denied" do
+ get oauth_callback_snaptrade_items_url(error: "access_denied", state: "whatever")
+ assert_redirected_to settings_providers_path
+ assert flash[:alert].present?
end
- test "oauth_connect renders start form without side effects" do
- sign_out
- sign_in @user = users(:empty)
- @user.family.snaptrade_items.destroy_all
- Provider::Snaptrade.stubs(:oauth_client_id_configured?).returns(true)
- SnaptradeItem.any_instance
- .expects(:start_oauth_device_flow)
- .never
+ test "oauth_callback fails when code param is missing" do
+ Provider::Snaptrade.expects(:exchange_code).never
- assert_no_difference "SnaptradeItem.count" do
- get oauth_connect_snaptrade_items_url
- end
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ get oauth_authorize_snaptrade_items_url
+ oauth_session = session[:snaptrade_oauth]
- assert_response :success
- assert_match "turbo-frame id=\"drawer\"", response.body
- assert_match "Start authorization", response.body
- assert_no_match "Open SnapTrade", response.body
- end
+ get oauth_callback_snaptrade_items_url(state: oauth_session["state"])
- test "start_oauth_connect renders device authorization instructions" do
- Provider::Snaptrade.stubs(:oauth_client_id_configured?).returns(true)
- SnaptradeItem.any_instance
- .stubs(:start_oauth_device_flow)
- .returns(
- "device_code" => "device-code",
- "user_code" => "ABCD-EFGH",
- "verification_uri" => "https://dashboard.snaptrade.com/activate",
- "verification_uri_complete" => "https://dashboard.snaptrade.com/activate?user_code=ABCD-EFGH",
- "expires_in" => 600,
- "interval" => 5
- )
-
- post start_oauth_connect_snaptrade_items_url
-
- assert_response :success
- assert_match "turbo-frame id=\"drawer\"", response.body
- assert_match "ABCD-EFGH", response.body
- assert_match "Open SnapTrade", response.body
+ assert_redirected_to settings_providers_path
+ assert_equal "Unable to complete SnapTrade authorization. Please try again.", flash[:alert]
+ assert_nil session[:snaptrade_oauth]
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
end
- test "start_oauth_connect falls back to read for invalid scope" do
- Provider::Snaptrade.stubs(:oauth_client_id_configured?).returns(true)
- SnaptradeItem.any_instance
- .expects(:start_oauth_device_flow)
- .with(scope: "read")
- .returns(
- "device_code" => "device-code",
- "user_code" => "ABCD-EFGH",
- "verification_uri" => "https://dashboard.snaptrade.com/activate",
- "expires_in" => 600,
- "interval" => 5
- )
-
- post start_oauth_connect_snaptrade_items_url, params: { scope: "write" }
-
- assert_response :success
- assert_match "ABCD-EFGH", response.body
- end
+ test "oauth_callback handles exchange failures without applying tokens" do
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ get oauth_authorize_snaptrade_items_url
+ oauth_session = session[:snaptrade_oauth]
+ item = SnaptradeItem.find(oauth_session["item_id"])
+ original_token = item.oauth_access_token
- test "oauth_connect explains missing oauth client id without creating item" do
- sign_out
- sign_in @user = users(:empty)
- @user.family.snaptrade_items.destroy_all
- Provider::Snaptrade.stubs(:oauth_client_id_configured?).returns(false)
+ Provider::Snaptrade.expects(:exchange_code)
+ .with(code: "c0de", redirect_uri: oauth_callback_snaptrade_items_url, code_verifier: oauth_session["code_verifier"])
+ .raises(Provider::Snaptrade::Error.new("upstream exchange failed"))
- assert_no_difference "SnaptradeItem.count" do
- get oauth_connect_snaptrade_items_url
- end
+ get oauth_callback_snaptrade_items_url(code: "c0de", state: oauth_session["state"])
- assert_response :unprocessable_entity
- assert_match "SNAPTRADE_OAUTH_CLIENT_ID", response.body
+ assert_redirected_to settings_providers_path
+ assert_equal "Unable to complete SnapTrade authorization. Please try again.", flash[:alert]
+ assert_nil session[:snaptrade_oauth]
+ assert_equal original_token, item.reload.oauth_access_token
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
end
- test "start_oauth_connect creates oauth-only item when snaptrade is not configured" do
- sign_out
- sign_in @user = users(:empty)
- @user.family.snaptrade_items.destroy_all
- Provider::Snaptrade.stubs(:oauth_client_id_configured?).returns(true)
-
- SnaptradeItem.any_instance
- .stubs(:start_oauth_device_flow)
- .returns(
- "device_code" => "device-code",
- "user_code" => "ABCD-EFGH",
- "verification_uri" => "https://dashboard.snaptrade.com/activate",
- "expires_in" => 600,
- "interval" => 5
- )
-
- assert_difference "SnaptradeItem.count", 1 do
- post start_oauth_connect_snaptrade_items_url
- end
-
- assert_response :success
- assert_match "ABCD-EFGH", response.body
- assert_not @user.family.snaptrade_items.reload.last.credentials_configured?
+ test "oauth_callback exchanges code, stores tokens, queues sync, and resumes setup" do
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ get oauth_authorize_snaptrade_items_url(return_to: "setup_accounts")
+ oauth_session = session[:snaptrade_oauth]
+ item = SnaptradeItem.find(oauth_session["item_id"])
+
+ Provider::Snaptrade.expects(:exchange_code)
+ .with(code: "c0de", redirect_uri: oauth_callback_snaptrade_items_url, code_verifier: oauth_session["code_verifier"])
+ .returns({ "access_token" => "at", "refresh_token" => "rt", "expires_in" => 900 })
+
+ get oauth_callback_snaptrade_items_url(code: "c0de", state: oauth_session["state"])
+
+ assert_redirected_to setup_accounts_snaptrade_item_path(item, accountable_type: nil)
+ assert_equal "at", item.reload.oauth_access_token
+ assert_nil session[:snaptrade_oauth]
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = nil
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
end
test "select_accounts redirects unregistered users into connect flow" do
sign_out
sign_in @user = users(:empty)
- snaptrade_item = snaptrade_items(:pending_registration_item)
+ snaptrade_item = snaptrade_items(:unauthorized_item)
get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "setup_accounts" }
- assert_redirected_to oauth_connect_snaptrade_items_path(
+ assert_redirected_to oauth_authorize_snaptrade_items_path(
item_id: snaptrade_item.id,
accountable_type: "Investment",
return_to: "setup_accounts"
)
end
- test "complete oauth device flow registers credentialed items and routes to setup" do
- sign_out
- sign_in @user = users(:empty)
- snaptrade_item = snaptrade_items(:pending_registration_item)
-
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .returns(
- "token_type" => "Bearer",
- "scope" => "read",
- "expires_in" => 3600
- )
- SnaptradeItem.any_instance
- .stubs(:user_registered?)
- .returns(false, true)
- SnaptradeItem.any_instance
- .expects(:ensure_user_registered!)
- .once
- .returns(true)
-
- assert_difference "Sync.count", 1 do
- post complete_oauth_device_flow_snaptrade_item_url(snaptrade_item), params: {
- device_code: "device-code",
- accountable_type: "Investment",
- return_to: "setup_accounts"
- }
- end
-
- assert_redirected_to setup_accounts_snaptrade_item_path(
- snaptrade_item,
- accountable_type: "Investment",
- return_to: "setup_accounts"
- )
- assert_equal "SnapTrade authorization complete.", flash[:notice]
- end
-
- test "complete oauth device flow streams top-level navigation from drawer frame" do
- sign_out
- sign_in @user = users(:empty)
- snaptrade_item = snaptrade_items(:pending_registration_item)
-
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .returns(
- "token_type" => "Bearer",
- "scope" => "read",
- "expires_in" => 3600
- )
- SnaptradeItem.any_instance
- .stubs(:user_registered?)
- .returns(false, true)
- SnaptradeItem.any_instance
- .expects(:ensure_user_registered!)
- .once
- .returns(true)
- setup_path = setup_accounts_snaptrade_item_path(
- snaptrade_item,
- accountable_type: "Investment",
- return_to: "setup_accounts"
- )
-
- assert_difference "Sync.count", 1 do
- post complete_oauth_device_flow_snaptrade_item_url(snaptrade_item), params: {
- device_code: "device-code",
- accountable_type: "Investment",
- return_to: "setup_accounts"
- }, headers: { "Turbo-Frame" => "drawer" }
- end
-
- assert_response :success
- assert_equal "text/vnd.turbo-stream.html", response.media_type
- assert_match %(<turbo-stream action="redirect"), response.body
- assert_match ERB::Util.html_escape(setup_path), response.body
- assert_equal "SnapTrade authorization complete.", flash[:notice]
- end
-
- test "complete oauth device flow does not mark oauth-only items as setup complete" do
- sign_out
- sign_in @user = users(:empty)
- snaptrade_item = @user.family.snaptrade_items.create!(name: "OAuth-only SnapTrade")
-
- SnaptradeItem.any_instance
- .stubs(:complete_oauth_device_flow!)
- .returns(
- "token_type" => "Bearer",
- "scope" => "read",
- "expires_in" => 3600
- )
-
- assert_no_difference "Sync.count" do
- post complete_oauth_device_flow_snaptrade_item_url(snaptrade_item), params: {
- device_code: "device-code"
- }
- end
-
- assert_redirected_to settings_providers_path
- assert_match(/API credentials are required/, flash[:alert])
- end
-
test "select_accounts redirects registered users to setup flow" do
get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "/accounts" }
@@ -347,7 +183,7 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
get preload_accounts_snaptrade_items_url
end
- assert_redirected_to oauth_connect_snaptrade_items_path(item_id: snaptrade_items(:pending_registration_item).id)
+ assert_redirected_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_items(:unauthorized_item).id)
end
test "preload_accounts redirects registered users to setup flow and queues sync" do
@@ -361,8 +197,6 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
test "entry routing prefers a registered active item over a pending one" do
pending_item = @user.family.snaptrade_items.create!(
name: "Pending Registration",
- client_id: "pending_client_id",
- consumer_key: "pending_consumer_key",
status: :good,
scheduled_for_deletion: false,
pending_account_setup: true
@@ -376,7 +210,7 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
end
assert_redirected_to setup_accounts_snaptrade_item_path(@snaptrade_item)
- assert_not pending_item.user_registered?
+ assert_not pending_item.oauth_configured?
end
test "setup_accounts shows linkable investment and crypto accounts in dropdown" do
@@ -413,8 +247,6 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
test "select_existing_account prefers registered active item over pending one" do
pending_item = @user.family.snaptrade_items.create!(
name: "Pending Registration",
- client_id: "pending_client_id",
- consumer_key: "pending_consumer_key",
status: :good,
scheduled_for_deletion: false,
pending_account_setup: true
@@ -510,8 +342,8 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select ".no-accounts-found", count: 1, message: "Expected the no-accounts UI to be shown after a completed sync with zero accounts"
assert_select "#snaptrade-sync-spinner", count: 0, message: "Expected the spinner to be hidden when there is no active sync"
- assert_select "a[href=?]", connect_snaptrade_item_path(@snaptrade_item), text: /Connect Brokerage/
- assert_no_match oauth_connect_snaptrade_items_path(item_id: @snaptrade_item.id), response.body
+ assert_select "a[href=?]", connect_snaptrade_item_path(@snaptrade_item, return_to: "setup_accounts", accountable_type: nil), text: /Connect Brokerage/
+ assert_no_match oauth_authorize_snaptrade_items_path(item_id: @snaptrade_item.id), response.body
end
test "setup_accounts does not re-queue a sync when a sync is already in progress" do
diff --git a/test/fixtures/snaptrade_items.yml b/test/fixtures/snaptrade_items.yml
index df3753dbe9..497a7dd937 100644
--- a/test/fixtures/snaptrade_items.yml
+++ b/test/fixtures/snaptrade_items.yml
@@ -3,26 +3,20 @@
configured_item:
family: dylan_family
-
name: "SnapTrade Connection"
- client_id: "test_client_id"
- consumer_key: "test_consumer_key"
- snaptrade_user_id: "user_123"
- snaptrade_user_secret: "secret_abc"
+ oauth_access_token: "test-access-token"
+ oauth_refresh_token: "test-refresh-token"
+ oauth_token_type: "Bearer"
+ oauth_scope: "read"
+ oauth_token_expires_at: <%= 1.hour.from_now %>
status: good
scheduled_for_deletion: false
pending_account_setup: false
-# Item with credentials but not yet registered with SnapTrade
-# (user_id and user_secret are blank - represents state after saving credentials
-# but before connecting to SnapTrade portal)
-pending_registration_item:
+# Item that has never completed the OAuth flow (no tokens)
+unauthorized_item:
family: empty
-
- name: "Pending Registration"
- client_id: "pending_client_id"
- consumer_key: "pending_consumer_key"
- # snaptrade_user_id and snaptrade_user_secret intentionally blank
- status: good
+ name: "Unauthorized SnapTrade"
+ status: requires_update
scheduled_for_deletion: false
pending_account_setup: true
diff --git a/test/helpers/settings_helper_test.rb b/test/helpers/settings_helper_test.rb
new file mode 100644
index 0000000000..3ee9c41d81
--- /dev/null
+++ b/test/helpers/settings_helper_test.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class SettingsHelperTest < ActionView::TestCase
+ test "provider_summary for snaptrade is off when family has no snaptrade items" do
+ @snaptrade_items = []
+
+ assert_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)
+ @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)
+ @snaptrade_items = [ item ]
+ @provider_sync_health = {}
+
+ assert_equal({ status: :ok, last_synced_at: nil }, provider_summary("snaptrade"))
+ end
+end
diff --git a/test/models/provider/snaptrade_adapter_test.rb b/test/models/provider/snaptrade_adapter_test.rb
new file mode 100644
index 0000000000..3fefcc336d
--- /dev/null
+++ b/test/models/provider/snaptrade_adapter_test.rb
@@ -0,0 +1,35 @@
+require "test_helper"
+
+class Provider::SnaptradeAdapterTest < ActiveSupport::TestCase
+ test "supports Investment and Crypto accounts" do
+ assert_includes Provider::SnaptradeAdapter.supported_account_types, "Investment"
+ assert_includes Provider::SnaptradeAdapter.supported_account_types, "Crypto"
+ end
+
+ test "build_provider returns nil when family is nil" do
+ assert_nil Provider::SnaptradeAdapter.build_provider(family: nil)
+ end
+
+ test "build_provider returns nil when OAuth app is not configured" do
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(false)
+
+ assert_nil Provider::SnaptradeAdapter.build_provider(family: families(:dylan_family))
+ end
+
+ test "build_provider returns nil when family has no authorized snaptrade item" do
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+
+ assert_nil Provider::SnaptradeAdapter.build_provider(family: families(:empty))
+ end
+
+ test "build_provider returns a Provider::Snaptrade wrapping the authorized item" do
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+ family = families(:dylan_family)
+ item = snaptrade_items(:configured_item)
+
+ provider = Provider::SnaptradeAdapter.build_provider(family: family)
+
+ assert_instance_of Provider::Snaptrade, provider
+ assert_equal item, provider.snaptrade_item
+ end
+end
diff --git a/test/models/provider/snaptrade_oauth_test.rb b/test/models/provider/snaptrade_oauth_test.rb
index 76deb37767..7c65889faf 100644
--- a/test/models/provider/snaptrade_oauth_test.rb
+++ b/test/models/provider/snaptrade_oauth_test.rb
@@ -1,88 +1,228 @@
require "test_helper"
+require "ostruct"
class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
setup do
- @provider = Provider::Snaptrade.new(client_id: "snap_client", consumer_key: "snap_secret")
- Rails.configuration.x.snaptrade.oauth_client_id = "sure-oauth-client"
- stub_request(:get, Provider::Snaptrade::OAUTH_DISCOVERY_URL)
- .to_return(
- status: 200,
- headers: { "Content-Type" => "application/json" },
- body: {
- issuer: "https://api.snaptrade.com",
- device_authorization_endpoint: "https://api.snaptrade.com/oauth/device_authorization/",
- token_endpoint: "https://api.snaptrade.com/oauth/token/"
- }.to_json
- )
- end
-
- test "starts device authorization using well known metadata" do
- stub_request(:post, "https://api.snaptrade.com/oauth/device_authorization/")
- .with(body: "client_id=sure-oauth-client&scope=read")
- .to_return(
- status: 200,
- headers: { "Content-Type" => "application/json" },
- body: {
- device_code: "device-code",
- user_code: "ABCD-EFGH",
- verification_uri: "https://dashboard.snaptrade.com/activate",
- interval: 5,
- expires_in: 600
- }.to_json
- )
-
- response = @provider.start_device_authorization
-
- assert_equal "device-code", response["device_code"]
- assert_equal "ABCD-EFGH", response["user_code"]
- assert_equal 5, response["interval"]
- end
-
- test "polls token endpoint with device code grant" do
- stub_request(:post, "https://api.snaptrade.com/oauth/token/")
- .with(body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=device-code&client_id=sure-oauth-client")
- .to_return(
- status: 200,
- headers: { "Content-Type" => "application/json" },
- body: {
- access_token: "access-token",
- refresh_token: "refresh-token",
- token_type: "Bearer",
- expires_in: 3600,
- scope: "read"
- }.to_json
- )
-
- response = @provider.poll_device_token(device_code: "device-code")
-
- assert_equal "access-token", response["access_token"]
- assert_equal "refresh-token", response["refresh_token"]
- assert_equal "Bearer", response["token_type"]
- end
-
- test "raises configuration error when oauth client id is missing" do
- Rails.configuration.x.snaptrade.oauth_client_id = nil
-
- error = assert_raises Provider::Snaptrade::ConfigurationError do
- @provider.start_device_authorization
+ @original = Rails.configuration.x.snaptrade
+ Rails.configuration.x.snaptrade = ActiveSupport::OrderedOptions.new
+ end
+
+ teardown do
+ Rails.configuration.x.snaptrade = @original
+ end
+
+ test "oauth_configured? requires both client id and secret" do
+ assert_not Provider::Snaptrade.oauth_configured?
+
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ assert_not Provider::Snaptrade.oauth_configured?
+
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ assert Provider::Snaptrade.oauth_configured?
+ end
+
+ # --- helpers ---
+ def configure_oauth!
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
+ end
+
+ def faraday_response(status:, body:)
+ OpenStruct.new(status: status, body: body, success?: (200..299).cover?(status))
+ end
+
+ def fake_item(access_token: "at-1", refresh_token: "rt-1", expires_at: 1.hour.from_now)
+ item = OpenStruct.new(
+ oauth_access_token: access_token,
+ oauth_refresh_token: refresh_token,
+ oauth_token_expires_at: expires_at,
+ family: nil
+ )
+ def item.apply_oauth_tokens!(payload)
+ (@applied ||= []) << payload
+ self.oauth_access_token = payload["access_token"]
+ end
+ def item.applied = @applied || []
+ def item.update!(attrs) = (@updates ||= []) << attrs
+ def item.updates = @updates || []
+ # Stand in for ActiveRecord's row-locking API used by Provider::Snaptrade#refresh_access_token!.
+ # By default there's nothing concurrent to guard against in these tests, so locking is a no-op
+ # and reload leaves attributes untouched (they're already "current" in memory).
+ def item.with_lock
+ yield
end
+ def item.reload
+ self
+ end
+ item
+ end
+
+ test "generate_pkce returns S256 challenge of the verifier" do
+ pkce = Provider::Snaptrade.generate_pkce
+ expected = Base64.urlsafe_encode64(OpenSSL::Digest::SHA256.digest(pkce[:verifier]), padding: false)
+ assert_equal expected, pkce[:challenge]
+ assert pkce[:verifier].length.between?(43, 128)
+ end
- assert_equal "SnapTrade OAuth client ID is not configured", error.message
+ test "authorize_url contains all required OAuth params" do
+ configure_oauth!
+ url = Provider::Snaptrade.authorize_url(
+ redirect_uri: "https://sure.test/callback", state: "st4te", code_challenge: "ch4llenge"
+ )
+ uri = URI.parse(url)
+ params = Rack::Utils.parse_query(uri.query)
+ assert_equal "dashboard.snaptrade.com", uri.host
+ assert_equal "code", params["response_type"]
+ assert_equal "client-id", params["client_id"]
+ assert_equal "https://sure.test/callback", params["redirect_uri"]
+ assert_equal "read", params["scope"]
+ assert_equal "st4te", params["state"]
+ assert_equal "ch4llenge", params["code_challenge"]
+ assert_equal "S256", params["code_challenge_method"]
end
- test "raises api error for oauth error responses" do
- stub_request(:post, "https://api.snaptrade.com/oauth/token/")
- .to_return(
- status: 400,
- headers: { "Content-Type" => "application/json" },
- body: { error: "authorization_pending" }.to_json
- )
+ test "exchange_code posts grant with PKCE verifier and basic auth" do
+ configure_oauth!
+ connection = mock("faraday")
+ request = OpenStruct.new(headers: {})
+ connection.expects(:post).with(Provider::Snaptrade::TOKEN_URL).yields(request)
+ .returns(faraday_response(status: 200, body: { access_token: "at", refresh_token: "rt", expires_in: 900, token_type: "Bearer", scope: "read" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ payload = Provider::Snaptrade.exchange_code(code: "c0de", redirect_uri: "https://sure.test/cb", code_verifier: "v3rifier")
+
+ assert_equal "at", payload["access_token"]
+ assert_equal "Basic #{Base64.strict_encode64('client-id:client-secret')}", request.headers["Authorization"]
+ body = Rack::Utils.parse_query(request.body)
+ assert_equal "authorization_code", body["grant_type"]
+ assert_equal "c0de", body["code"]
+ assert_equal "v3rifier", body["code_verifier"]
+ assert_equal "https://sure.test/cb", body["redirect_uri"]
+ end
- error = assert_raises Provider::Snaptrade::ApiError do
- @provider.poll_device_token(device_code: "device-code")
+ test "token request raises AuthenticationError on 4xx with error description" do
+ configure_oauth!
+ connection = mock("faraday")
+ connection.expects(:post).returns(faraday_response(status: 400, body: { error: "invalid_grant", error_description: "expired" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ error = assert_raises(Provider::Snaptrade::AuthenticationError) do
+ Provider::Snaptrade.refresh_tokens(refresh_token: "dead-rt")
end
+ assert_match "expired", error.message
+ end
+
+ test "data calls send Bearer token on API base URL" do
+ configure_oauth!
+ item = fake_item
+ provider = Provider::Snaptrade.new(item)
+
+ request = OpenStruct.new(headers: {}, params: {})
+ connection = mock("faraday")
+ connection.expects(:get).with("#{Provider::Snaptrade::API_BASE_URL}/api/v1/accounts").yields(request)
+ .returns(faraday_response(status: 200, body: [ { id: "acct-1" } ].to_json))
+ provider.stubs(:api_connection).returns(connection)
+
+ accounts = provider.list_accounts
+ assert_equal "Bearer at-1", request.headers["Authorization"]
+ assert_equal [ { "id" => "acct-1" } ], accounts
+ end
+
+ test "expired token is refreshed before the data call and rotation persisted" do
+ configure_oauth!
+ item = fake_item(expires_at: 1.minute.ago)
+ provider = Provider::Snaptrade.new(item)
+
+ Provider::Snaptrade.expects(:refresh_tokens).with(refresh_token: "rt-1")
+ .returns({ "access_token" => "at-2", "refresh_token" => "rt-2", "expires_in" => 900 })
+
+ request = OpenStruct.new(headers: {}, params: {})
+ connection = mock("faraday")
+ connection.expects(:get).yields(request).returns(faraday_response(status: 200, body: "[]"))
+ provider.stubs(:api_connection).returns(connection)
+
+ provider.list_accounts
+ assert_equal "Bearer at-2", request.headers["Authorization"]
+ assert_equal "at-2", item.applied.last["access_token"]
+ end
+
+ test "401 triggers one refresh and retry" do
+ configure_oauth!
+ item = fake_item
+ provider = Provider::Snaptrade.new(item)
+
+ Provider::Snaptrade.expects(:refresh_tokens).with(refresh_token: "rt-1")
+ .returns({ "access_token" => "at-2", "expires_in" => 900 })
+
+ connection = mock("faraday")
+ responses = [ faraday_response(status: 401, body: "{}"), faraday_response(status: 200, body: "[]") ]
+ connection.expects(:get).twice.yields(OpenStruct.new(headers: {}, params: {})).returns(*responses)
+ provider.stubs(:api_connection).returns(connection)
+
+ assert_equal [], provider.list_accounts
+ end
+
+ test "failed refresh marks item requires_update and raises AuthenticationError" do
+ configure_oauth!
+ item = fake_item(expires_at: 1.minute.ago)
+ provider = Provider::Snaptrade.new(item)
+ DebugLogEntry.stubs(:capture)
+
+ Provider::Snaptrade.expects(:refresh_tokens).raises(Provider::Snaptrade::AuthenticationError, "invalid_grant")
+
+ assert_raises(Provider::Snaptrade::AuthenticationError) { provider.list_accounts }
+ assert_includes item.updates, { status: :requires_update }
+ end
+
+ test "blank refresh token raises AuthenticationError and marks requires_update exactly once" do
+ configure_oauth!
+ item = fake_item(refresh_token: nil, expires_at: 1.minute.ago)
+ provider = Provider::Snaptrade.new(item)
+ DebugLogEntry.stubs(:capture)
+
+ assert_raises(Provider::Snaptrade::AuthenticationError) { provider.list_accounts }
+ assert_equal [ { status: :requires_update } ], item.updates
+ end
+
+ test "concurrent refresh race: reload inside lock finds already-fresh token and skips HTTP refresh" do
+ configure_oauth!
+ item = fake_item(access_token: "at-stale", expires_at: 1.minute.ago)
+ # Simulate a concurrent caller having already rotated the tokens in the DB by the time
+ # this caller acquires the row lock and reloads -- the in-memory copy looked expired,
+ # but the reloaded row is fresh.
+ def item.reload
+ self.oauth_access_token = "at-fresh"
+ self.oauth_token_expires_at = 1.hour.from_now
+ self
+ end
+ provider = Provider::Snaptrade.new(item)
+
+ Provider::Snaptrade.expects(:refresh_tokens).never
+
+ request = OpenStruct.new(headers: {}, params: {})
+ connection = mock("faraday")
+ connection.expects(:get).yields(request).returns(faraday_response(status: 200, body: "[]"))
+ provider.stubs(:api_connection).returns(connection)
+
+ assert_equal [], provider.list_accounts
+ assert_equal "Bearer at-fresh", request.headers["Authorization"]
+ end
+
+ test "get_connection_url posts login and returns redirect URI" do
+ configure_oauth!
+ provider = Provider::Snaptrade.new(fake_item)
+
+ request = OpenStruct.new(headers: {}, params: {})
+ connection = mock("faraday")
+ connection.expects(:post).with("#{Provider::Snaptrade::API_BASE_URL}/api/v1/snapTrade/login").yields(request)
+ .returns(faraday_response(status: 200, body: { redirectURI: "https://app.snaptrade.com/connect/xyz" }.to_json))
+ provider.stubs(:api_connection).returns(connection)
- assert_equal 400, error.status_code
- assert_match "authorization_pending", error.message
+ url = provider.get_connection_url(redirect_url: "https://sure.test/return", broker: "QUESTRADE")
+ assert_equal "https://app.snaptrade.com/connect/xyz", url
+ body = JSON.parse(request.body)
+ assert_equal "https://sure.test/return", body["customRedirect"]
+ assert_equal "read", body["connectionType"]
+ assert_equal "QUESTRADE", body["broker"]
end
end
diff --git a/test/models/snaptrade_item_oauth_test.rb b/test/models/snaptrade_item_oauth_test.rb
index 8a151ce079..133acb1ecd 100644
--- a/test/models/snaptrade_item_oauth_test.rb
+++ b/test/models/snaptrade_item_oauth_test.rb
@@ -1,30 +1,62 @@
require "test_helper"
+require "ostruct"
class SnaptradeItemOauthTest < ActiveSupport::TestCase
- test "complete_oauth_device_flow stores token metadata" do
- item = snaptrade_items(:configured_item)
- provider = mock("snaptrade_provider")
- provider.expects(:poll_device_token).with(device_code: "device-code").returns(
- "access_token" => "access-token",
- "refresh_token" => "refresh-token",
- "token_type" => "Bearer",
- "scope" => "read",
- "expires_in" => 3600
+ setup do
+ @item = snaptrade_items(:configured_item)
+ end
+
+ test "syncable scope includes only active items with an access token" do
+ assert_includes SnaptradeItem.syncable, snaptrade_items(:configured_item)
+ assert_not_includes SnaptradeItem.syncable, snaptrade_items(:unauthorized_item)
+ end
+
+ test "oauth_configured? and fully_configured? reflect token presence" do
+ assert @item.oauth_configured?
+ assert @item.fully_configured?
+ assert_not snaptrade_items(:unauthorized_item).oauth_configured?
+ end
+
+ test "apply_oauth_tokens! persists rotated tokens and keeps old refresh token when omitted" do
+ @item.apply_oauth_tokens!(
+ "access_token" => "new-at", "refresh_token" => "new-rt",
+ "token_type" => "Bearer", "scope" => "read", "expires_in" => 900
)
- item.stubs(:snaptrade_provider).returns(provider)
+ assert_equal "new-at", @item.oauth_access_token
+ assert_equal "new-rt", @item.oauth_refresh_token
+ assert_in_delta 900, @item.oauth_token_expires_at - Time.current, 10
- expected_expiry = 1.hour.from_now
+ @item.apply_oauth_tokens!("access_token" => "newer-at", "expires_in" => 900)
+ assert_equal "newer-at", @item.oauth_access_token
+ assert_equal "new-rt", @item.oauth_refresh_token, "refresh token must survive rotation that omits it"
+ end
- travel_to expected_expiry - 1.hour do
- item.complete_oauth_device_flow!(device_code: "device-code")
- end
+ test "complete_oauth_exchange! stores tokens and marks item good" do
+ @item.update!(status: :requires_update)
+ Provider::Snaptrade.expects(:exchange_code)
+ .with(code: "c0de", redirect_uri: "https://sure.test/cb", code_verifier: "v")
+ .returns({ "access_token" => "at", "refresh_token" => "rt", "expires_in" => 900 })
- item.reload
- assert_equal "access-token", item.oauth_access_token
- assert_equal "refresh-token", item.oauth_refresh_token
- assert_equal "Bearer", item.oauth_token_type
- assert_equal "read", item.oauth_scope
- assert_in_delta expected_expiry.to_f, item.oauth_token_expires_at.to_f, 1
- assert item.oauth_token_active?
+ @item.complete_oauth_exchange!(code: "c0de", redirect_uri: "https://sure.test/cb", code_verifier: "v")
+
+ assert_equal "at", @item.oauth_access_token
+ assert @item.good?
+ end
+
+ test "snaptrade_provider returns provider only when token present" do
+ assert_instance_of Provider::Snaptrade, @item.snaptrade_provider
+ assert_nil snaptrade_items(:unauthorized_item).snaptrade_provider
+ end
+
+ test "destroy revokes tokens best-effort" do
+ Provider::Snaptrade.expects(:revoke_token).with(token: @item.oauth_refresh_token).returns(true)
+ @item.destroy!
+ end
+
+ test "destroy proceeds even when revocation raises" do
+ Provider::Snaptrade.expects(:revoke_token).raises(Provider::Snaptrade::ApiError.new("boom"))
+ assert_difference "SnaptradeItem.count", -1 do
+ @item.destroy!
+ end
end
end
diff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rb
index 008f71ba8a..fcb6bea4f7 100644
--- a/test/models/snaptrade_item_test.rb
+++ b/test/models/snaptrade_item_test.rb
@@ -6,116 +6,38 @@ class SnaptradeItemTest < ActiveSupport::TestCase
end
test "validates presence of name" do
- item = SnaptradeItem.new(family: @family, client_id: "test", consumer_key: "test")
+ item = SnaptradeItem.new(family: @family)
assert_not item.valid?
assert_includes item.errors[:name], "can't be blank"
end
- test "requires client_id when consumer_key is present" do
- item = SnaptradeItem.new(family: @family, name: "Test", consumer_key: "test")
- assert_not item.valid?
- assert_includes item.errors[:client_id], "can't be blank"
- end
-
- test "requires consumer_key when client_id is present" do
- item = SnaptradeItem.new(family: @family, name: "Test", client_id: "test")
- assert_not item.valid?
- assert_includes item.errors[:consumer_key], "can't be blank"
- end
-
test "allows oauth-only items without api credentials" do
item = SnaptradeItem.new(family: @family, name: "Test")
assert item.valid?
end
- test "credentials_configured? returns true when credentials are set" do
- item = SnaptradeItem.new(
- family: @family,
- name: "Test",
- client_id: "test_client_id",
- consumer_key: "test_consumer_key"
- )
- assert item.credentials_configured?
- end
-
- test "credentials_configured? returns false when credentials are missing" do
- item = SnaptradeItem.new(family: @family, name: "Test")
- assert_not item.credentials_configured?
- end
-
- test "user_registered? returns false when user_id and secret are blank" do
- item = SnaptradeItem.new(
- family: @family,
- name: "Test",
- client_id: "test",
- consumer_key: "test"
- )
- assert_not item.user_registered?
- end
-
- test "user_registered? returns true when user_id and secret are present" do
- item = SnaptradeItem.new(
- family: @family,
- name: "Test",
- client_id: "test",
- consumer_key: "test",
- snaptrade_user_id: "user_123",
- snaptrade_user_secret: "secret_abc"
- )
- assert item.user_registered?
- end
-
- test "snaptrade_provider returns nil when credentials not configured" do
+ test "snaptrade_provider returns nil when oauth token not present" do
item = SnaptradeItem.new(family: @family, name: "Test")
assert_nil item.snaptrade_provider
end
- test "snaptrade_provider returns provider instance when configured" do
+ test "snaptrade_provider returns provider instance when oauth token present" do
item = SnaptradeItem.new(
family: @family,
name: "Test",
- client_id: "test_client_id",
- consumer_key: "test_consumer_key"
+ oauth_access_token: "test-access-token"
)
provider = item.snaptrade_provider
assert_instance_of Provider::Snaptrade, provider
end
- test "orphaned_users only includes users for the same family" do
- item = SnaptradeItem.new(
- family: @family,
- name: "Test",
- client_id: "test",
- consumer_key: "test",
- snaptrade_user_id: "family_#{@family.id}_111",
- snaptrade_user_secret: "secret"
- )
-
- item.stubs(:list_all_users).returns([
- "family_#{@family.id}_111",
- "family_#{@family.id}_222",
- "family_999_333",
- "legacy_user_444"
- ])
-
- assert_equal([ "family_#{@family.id}_222" ], item.orphaned_users)
- end
-
- test "delete_orphaned_user rejects users outside the current family namespace" do
- item = SnaptradeItem.new(
- family: @family,
- name: "Test",
- client_id: "test",
- consumer_key: "test",
- snaptrade_user_id: "family_#{@family.id}_111",
- snaptrade_user_secret: "secret"
- )
-
- provider = mock
- provider.expects(:delete_user).never
- item.stubs(:snaptrade_provider).returns(provider)
+ test "credentials_configured? mirrors oauth_configured?" do
+ item = SnaptradeItem.new(family: @family, name: "Test")
+ assert_equal item.oauth_configured?, item.credentials_configured?
+ assert_not item.credentials_configured?
- assert_not item.delete_orphaned_user("family_999_222")
- assert_not item.delete_orphaned_user("legacy_user_333")
+ item.oauth_access_token = "test-access-token"
+ assert_equal item.oauth_configured?, item.credentials_configured?
+ assert item.credentials_configured?
end
end