Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(snaptrade): add device-flow OAuth alongside the browser redirect (#3126)

Juan José Matad6462f5fc9a2
diff --git a/.env.local.example b/.env.local.example
index 7d92c7ae22..dd2dca0763 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -12,9 +12,13 @@ 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 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 app (register one at https://dashboard.snaptrade.com).
+# The client ID on its own enables the device code flow: users confirm a short
+# code on SnapTrade, no redirect URI needed.
SNAPTRADE_OAUTH_CLIENT_ID=
+# Only needed for the browser redirect flow (authorization code + PKCE), which
+# also requires https://<your-host>/snaptrade_items/oauth_callback to be
+# registered as a redirect URI on the OAuth app.
SNAPTRADE_OAUTH_CLIENT_SECRET=
# Lunchflow runtime flags (default-off)
diff --git a/.env.test.example b/.env.test.example
index e8f7848deb..aaa44bbcf7 100644
--- a/.env.test.example
+++ b/.env.test.example
@@ -11,9 +11,13 @@ 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 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 app (register one at https://dashboard.snaptrade.com).
+# The client ID on its own enables the device code flow: users confirm a short
+# code on SnapTrade, no redirect URI needed.
SNAPTRADE_OAUTH_CLIENT_ID=
+# Only needed for the browser redirect flow (authorization code + PKCE), which
+# also requires https://<your-host>/snaptrade_items/oauth_callback to be
+# registered as a redirect URI on the OAuth app.
SNAPTRADE_OAUTH_CLIENT_SECRET=
# Lunchflow runtime flags (default-off)
diff --git a/app/controllers/snaptrade_items_controller.rb b/app/controllers/snaptrade_items_controller.rb
index b9e5a90138..84ae90774a 100644
--- a/app/controllers/snaptrade_items_controller.rb
+++ b/app/controllers/snaptrade_items_controller.rb
@@ -1,6 +1,22 @@
class SnaptradeItemsController < ApplicationController
- 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 ]
+ PERMITTED_OAUTH_SCOPES = %w[read].freeze
+ # RFC 8628 §3.5: the authorization server is telling us to keep waiting, not
+ # that anything went wrong.
+ DEVICE_FLOW_PENDING_ERRORS = %w[authorization_pending slow_down].freeze
+ # RFC 8628 §3.5: the two codes that mean this device code will never be
+ # redeemable. Everything else -- a 5xx, a dropped connection -- leaves it
+ # valid, so the user can just try again.
+ DEVICE_FLOW_TERMINAL_ERRORS = %w[expired_token access_denied].freeze
+ # What a pending device authorization needs to survive a retry render: the
+ # code to redeem, plus what the page shows the user. expires_in and interval
+ # are deliberately not kept -- nothing reads them, and the authorization
+ # server is the one that decides when a code is spent.
+ DEVICE_AUTHORIZATION_SESSION_FIELDS = %w[
+ device_code user_code verification_uri verification_uri_complete
+ ].freeze
+
+ before_action :set_snaptrade_item, only: [ :show, :destroy, :sync, :connect, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :complete_oauth_device_flow ]
+ before_action :require_admin!, only: [ :destroy, :sync, :connect, :callback, :setup_accounts, :complete_account_setup, :connections, :delete_connection, :oauth_authorize, :oauth_callback, :oauth_device_authorize, :start_oauth_device_flow, :complete_oauth_device_flow, :preload_accounts, :select_accounts, :select_existing_account, :link_existing_account ]
def index
@snaptrade_items = Current.family.snaptrade_items.ordered
@@ -185,7 +201,7 @@ class SnaptradeItemsController < ApplicationController
# Start the SnapTrade OAuth authorization-code + PKCE flow
def oauth_authorize
- unless Provider::Snaptrade.oauth_configured?
+ unless Provider::Snaptrade.authorization_code_configured?
redirect_to settings_providers_path, alert: t(".not_configured")
return
end
@@ -263,6 +279,97 @@ class SnaptradeItemsController < ApplicationController
redirect_to settings_providers_path, alert: t(".failed")
end
+ # Device flow, step 0: the drawer, before any network call is made.
+ def oauth_device_authorize
+ assign_device_flow_context
+ return render_device_flow_unconfigured unless Provider::Snaptrade.oauth_configured?
+
+ @snaptrade_item = if params[:item_id].present?
+ Current.family.snaptrade_items.find(params[:item_id])
+ else
+ current_snaptrade_item
+ end
+
+ render :oauth_device_flow
+ end
+
+ # Device flow, step 1: ask SnapTrade for the code the user confirms.
+ def start_oauth_device_flow
+ assign_device_flow_context
+ return render_device_flow_unconfigured unless Provider::Snaptrade.oauth_configured?
+
+ @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"))
+ end
+
+ @device_authorization = @snaptrade_item.start_oauth_device_flow(scope: @oauth_scope)
+ store_pending_device_flow(@device_authorization)
+
+ render :oauth_device_flow
+ rescue Provider::Snaptrade::Error => e
+ Rails.logger.error "SnapTrade device authorization failed: #{e.class} - #{e.message}"
+ @error_message = t(".failed")
+ render :oauth_device_flow, status: :unprocessable_entity
+ end
+
+ # Device flow, step 2: redeem the confirmed code. From here the item is
+ # indistinguishable from one authorized through the browser redirect.
+ def complete_oauth_device_flow
+ assign_device_flow_context
+
+ device_flow = pending_device_flow
+ if device_flow.blank?
+ @error_message = t(".device_code_required")
+ render :oauth_device_flow, status: :unprocessable_entity
+ return
+ end
+
+ # The session is what says where this flow came from, so it decides where
+ # it goes back to.
+ @return_to = device_flow[:return_to]
+ @accountable_type = device_flow[:accountable_type]
+
+ @snaptrade_item.complete_oauth_device_flow!(device_code: device_flow[:device_code])
+ session.delete(:snaptrade_device_flow)
+ @snaptrade_item.sync_later_with_follow_up
+
+ destination = if @return_to == "setup_accounts"
+ setup_accounts_snaptrade_item_path(@snaptrade_item, accountable_type: @accountable_type.presence)
+ else
+ settings_providers_path
+ end
+
+ redirect_after_device_flow destination, notice: t(".success")
+ rescue Provider::Snaptrade::Error => e
+ Rails.logger.error "SnapTrade device token request failed: #{e.class} - #{e.message}"
+
+ # Waiting on the user is the expected case, not a failure worth recording.
+ unless device_flow_pending?(e)
+ DebugLogEntry.capture(
+ category: "provider_auth",
+ level: :error,
+ message: "SnapTrade device code exchange failed: #{e.message}",
+ source: "SnaptradeItemsController#complete_oauth_device_flow",
+ provider_key: "snaptrade",
+ family: Current.family
+ )
+ end
+
+ @error_message = device_flow_error_message(e)
+
+ if DEVICE_FLOW_TERMINAL_ERRORS.include?(e.try(:oauth_error))
+ # The code is spent. Drop it so the page offers a fresh start rather than
+ # a button that can only fail.
+ session.delete(:snaptrade_device_flow)
+ else
+ restore_device_authorization_from_session
+ end
+
+ render :oauth_device_flow, status: :unprocessable_entity
+ end
+
# Delete a brokerage connection
def delete_connection
authorization_id = params[:authorization_id]
@@ -325,7 +432,7 @@ class SnaptradeItemsController < ApplicationController
snaptrade_item.sync_later_with_follow_up
redirect_to setup_accounts_snaptrade_item_path(snaptrade_item)
else
- redirect_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id)
+ redirect_to helpers.snaptrade_authorize_path(item_id: snaptrade_item.id)
end
end
@@ -342,7 +449,7 @@ class SnaptradeItemsController < ApplicationController
if snaptrade_item.oauth_configured?
redirect_to setup_accounts_snaptrade_item_path(snaptrade_item, accountable_type: @accountable_type, return_to: @return_to)
else
- redirect_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id, accountable_type: @accountable_type, return_to: @return_to)
+ redirect_to helpers.snaptrade_authorize_path(item_id: snaptrade_item.id, accountable_type: @accountable_type, return_to: @return_to)
end
end
@@ -405,6 +512,96 @@ class SnaptradeItemsController < ApplicationController
active_items.ordered.first
end
+ def assign_device_flow_context
+ @return_to = params[:return_to]
+ @accountable_type = params[:accountable_type]
+ @oauth_scope = permitted_oauth_scope
+ @device_flow_available = Provider::Snaptrade.oauth_configured?
+ end
+
+ def permitted_oauth_scope
+ requested_scope = params[:scope].to_s
+ return requested_scope if PERMITTED_OAUTH_SCOPES.include?(requested_scope)
+
+ "read"
+ end
+
+ # A device code redeems into tokens on its own and carries nothing that says
+ # who asked for it, so the client is expected to keep it to itself. Holding
+ # it in the session -- where the redirect flow already keeps its
+ # code_verifier -- keeps it off the wire entirely and binds redemption to
+ # the family and item that started the flow, which is the guarantee `state`
+ # gives the redirect flow. Without that, a code recovered from anywhere
+ # could be redeemed into someone else's item.
+ def store_pending_device_flow(payload)
+ pending = DEVICE_AUTHORIZATION_SESSION_FIELDS.index_with { |field| payload[field] }
+
+ session[:snaptrade_device_flow] = pending.merge(
+ "family_id" => Current.family.id,
+ "item_id" => @snaptrade_item.id,
+ "return_to" => @return_to,
+ "accountable_type" => @accountable_type
+ )
+ end
+
+ def pending_device_flow
+ device_flow = (session[:snaptrade_device_flow] || {}).with_indifferent_access
+
+ return nil if device_flow[:device_code].blank?
+ return nil unless device_flow[:family_id].to_s == Current.family.id.to_s
+ return nil unless device_flow[:item_id].to_s == @snaptrade_item.id.to_s
+
+ device_flow
+ end
+
+ # The device code survives a failed attempt: the user code is still valid,
+ # so re-rendering the same page lets them finish in SnapTrade and retry
+ # without starting over.
+ def restore_device_authorization_from_session
+ device_flow = (session[:snaptrade_device_flow] || {}).with_indifferent_access
+
+ @device_authorization = device_flow.slice(*DEVICE_AUTHORIZATION_SESSION_FIELDS).to_h
+ end
+
+ def render_device_flow_unconfigured
+ @device_flow_available = false
+ @error_message = t("snaptrade_items.oauth_device_flow.missing_client_id")
+ render :oauth_device_flow, status: :unprocessable_entity
+ end
+
+ # The drawer form posts into the `drawer` frame so errors re-render in
+ # place. A plain redirect would be followed as a frame navigation, and both
+ # destinations carry the layout's empty `drawer` frame -- Turbo would swap
+ # that in and just close the dialog, losing the notice and never advancing
+ # to account setup. A redirect stream action breaks out to the top level.
+ def redirect_after_device_flow(path, notice:)
+ if turbo_frame_request?
+ flash[:notice] = notice
+ render turbo_stream: turbo_stream.action(:redirect, path)
+ else
+ redirect_to path, notice: notice
+ end
+ end
+
+ def device_flow_pending?(error)
+ DEVICE_FLOW_PENDING_ERRORS.include?(error.try(:oauth_error))
+ end
+
+ # Chosen from the machine-readable OAuth code only. error.message can carry
+ # upstream detail, so it never reaches the page.
+ def device_flow_error_message(error)
+ return t("snaptrade_items.complete_oauth_device_flow.authorization_pending") if device_flow_pending?(error)
+
+ case error.try(:oauth_error)
+ when "expired_token"
+ t("snaptrade_items.complete_oauth_device_flow.expired")
+ when "access_denied"
+ t("snaptrade_items.complete_oauth_device_flow.access_denied")
+ else
+ t("snaptrade_items.complete_oauth_device_flow.failed")
+ end
+ end
+
def build_connections_list
api_connections = @snaptrade_item.fetch_connections
diff --git a/app/helpers/snaptrade_items_helper.rb b/app/helpers/snaptrade_items_helper.rb
new file mode 100644
index 0000000000..38d3a1c198
--- /dev/null
+++ b/app/helpers/snaptrade_items_helper.rb
@@ -0,0 +1,29 @@
+module SnaptradeItemsHelper
+ # Where an unauthorized SnapTrade item should be sent to get authorized.
+ #
+ # Both grants end with the same access token, so the choice is purely about
+ # what the deployment can run: the browser redirect needs a confidential
+ # client (client secret) and a registered redirect URI, while the device flow
+ # needs only the public client id. Prefer the redirect when it is available,
+ # since it is the shorter path for the user.
+ def snaptrade_authorize_path(item_id: nil, accountable_type: nil, return_to: nil)
+ query = {
+ item_id: item_id.presence,
+ accountable_type: accountable_type.presence,
+ return_to: return_to.presence
+ }.compact
+
+ if Provider::Snaptrade.authorization_code_configured?
+ oauth_authorize_snaptrade_items_path(query)
+ else
+ oauth_device_authorize_snaptrade_items_path(query)
+ end
+ end
+
+ # The redirect flow leaves the app entirely, and a cross-origin redirect
+ # cannot render inside a Turbo frame; the device flow is a page we render
+ # ourselves, so it belongs in the drawer.
+ def snaptrade_authorize_frame
+ Provider::Snaptrade.authorization_code_configured? ? "_top" : "drawer"
+ end
+end
diff --git a/app/models/provider/snaptrade.rb b/app/models/provider/snaptrade.rb
index 5cf4e598a7..6c7fdd04dd 100644
--- a/app/models/provider/snaptrade.rb
+++ b/app/models/provider/snaptrade.rb
@@ -2,14 +2,32 @@
#
# 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.
+# SNAPTRADE_OAUTH_CLIENT_ID (and, for the browser flow, SNAPTRADE_OAUTH_CLIENT_SECRET).
+# - Users authorize through either grant, and both end at the same place:
+# * authorization-code + PKCE -- a browser redirect. Needs a confidential
+# client (client secret) and a registered redirect URI.
+# * device code (RFC 8628) -- a user code confirmed on SnapTrade. Needs
+# only the public client id, so a deployment that cannot register a
+# confidential client still has a working path.
+# Either way the per-item access/refresh tokens are stored (encrypted) on
+# SnaptradeItem by #apply_oauth_tokens!.
# - Data calls send Authorization: Bearer <access_token>. The SnapTrade user
# is implicit in the token; there is no userId/userSecret.
class Provider::Snaptrade
class Error < StandardError; end
- class AuthenticationError < Error; end
+ # `oauth_error` carries the machine-readable `error` code from an OAuth error
+ # response when there was one (RFC 6749 §5.2, RFC 8628 §3.5). The device flow
+ # needs it to tell "the user hasn't approved this yet" apart from a real
+ # failure; the message itself is never safe to show, since it can carry
+ # upstream detail.
+ class AuthenticationError < Error
+ attr_reader :oauth_error
+
+ def initialize(message = nil, oauth_error: nil)
+ super(message)
+ @oauth_error = oauth_error
+ end
+ end
class ConfigurationError < Error; end
class ApiError < Error
attr_reader :status_code, :response_body
@@ -30,6 +48,16 @@ class Provider::Snaptrade
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
+ 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
+ # What the drawer needs to be usable at all: a code to show, a place to enter
+ # it, and a code to redeem afterwards. verification_uri_complete substitutes
+ # for verification_uri when present.
+ DEVICE_AUTHORIZATION_FIELDS = %w[device_code user_code verification_uri].freeze
+ # The discovery document is static; cached so device authorization doesn't pay
+ # a blocking round trip for it on every attempt.
+ OAUTH_METADATA_CACHE_KEY = "snaptrade:oauth_authorization_server_metadata".freeze
+ OAUTH_METADATA_CACHE_TTL = 12.hours
TOKEN_EXPIRY_LEEWAY = 60 # seconds; refresh this long before actual expiry
# Filtered out of get_positions so they never reach raw_holdings_payload:
@@ -40,7 +68,17 @@ class Provider::Snaptrade
UNSUPPORTED_INSTRUMENT_KINDS = %w[option future cfd].freeze
class << self
+ # Some OAuth flow is available. The device flow needs nothing but the public
+ # client id, so this is what gates syncing and the provider panel; only the
+ # browser redirect needs more (see authorization_code_configured?).
def oauth_configured?
+ oauth_client_id.present?
+ end
+
+ # The authorization-code + PKCE flow additionally needs a confidential
+ # client: this implementation authenticates the token request with the
+ # secret, and the redirect URI has to be registered on the OAuth app.
+ def authorization_code_configured?
oauth_client_id.present? && oauth_client_secret.present?
end
@@ -60,7 +98,7 @@ class Provider::Snaptrade
end
def authorize_url(redirect_uri:, state:, code_challenge:, scope: "read")
- raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+ raise ConfigurationError, "SnapTrade OAuth client secret is not configured" unless authorization_code_configured?
params = {
response_type: "code",
@@ -75,16 +113,103 @@ class Provider::Snaptrade
end
def exchange_code(code:, redirect_uri:, code_verifier:)
- token_request(
+ raise ConfigurationError, "SnapTrade OAuth client secret is not configured" unless authorization_code_configured?
+
+ params = {
grant_type: "authorization_code",
code: code,
redirect_uri: redirect_uri,
code_verifier: code_verifier
- )
+ }
+
+ token_request(params)
+ end
+
+ # --- Device flow (RFC 8628) ---
+
+ # Step 1: ask SnapTrade for a device code and the user code to confirm.
+ # Returns the parsed payload: device_code, user_code, verification_uri,
+ # verification_uri_complete, expires_in, interval.
+ def start_device_authorization(scope: "read")
+ raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+
+ endpoint = oauth_authorization_server_metadata["device_authorization_endpoint"]
+ raise ApiError.new("SnapTrade OAuth metadata missing device_authorization_endpoint") if endpoint.blank?
+
+ # Retried despite being a POST: a lost response means we never learned the
+ # user code, so the device code it created is useless to us and expires on
+ # its own. Nothing has been applied that a retry could duplicate.
+ response = with_retries("POST #{endpoint}") do
+ oauth_connection.post(endpoint) do |request|
+ request.headers["Authorization"] = basic_auth_header if confidential_client?
+ request.headers["Content-Type"] = "application/x-www-form-urlencoded"
+ request.body = URI.encode_www_form(with_client_credentials({ scope: scope }))
+ end
+ end
+
+ payload = parse_json(response.body)
+
+ unless response.success?
+ raise ApiError.new(
+ "SnapTrade OAuth device authorization failed: #{oauth_error_summary(payload, response.status)}",
+ status_code: response.status, response_body: response.body
+ )
+ end
+
+ # A 2xx missing any of these is a partial or schema-changed response, and
+ # every one of them is load-bearing: without them the drawer renders a
+ # blank code and a link to nowhere, which the user can only abandon.
+ # Better to fail with a message they can act on. Same reasoning as the
+ # results-array check in get_positions.
+ missing = DEVICE_AUTHORIZATION_FIELDS.reject { |field| payload[field].present? }
+ missing -= [ "verification_uri" ] if payload["verification_uri_complete"].present?
+
+ if missing.any?
+ raise ApiError.new(
+ "SnapTrade OAuth device authorization response is missing #{missing.join(', ')}",
+ status_code: response.status, response_body: response.body
+ )
+ end
+
+ payload
+ end
+
+ # Step 2: redeem the device code once the user has confirmed it. Until they
+ # do, SnapTrade answers 400 authorization_pending -- an AuthenticationError
+ # whose oauth_error the caller reads to keep waiting rather than give up.
+ def poll_device_token(device_code:)
+ raise ConfigurationError, "SnapTrade OAuth is not configured" unless oauth_configured?
+ raise ArgumentError, "device_code is required" if device_code.blank?
+
+ token_request({ grant_type: DEVICE_CODE_GRANT, device_code: device_code })
+ end
+
+ # Endpoints come from the authorization server's own metadata rather than
+ # being hardcoded, since SnapTrade's OAuth support is pre-release. Cached
+ # because the document is static and device authorization would otherwise
+ # pay for it twice per attempt.
+ def oauth_authorization_server_metadata
+ cached = Rails.cache.read(OAUTH_METADATA_CACHE_KEY)
+ return cached if cached.present?
+
+ response = with_retries("GET #{OAUTH_DISCOVERY_URL}") do
+ oauth_connection.get(OAUTH_DISCOVERY_URL)
+ end
+
+ payload = parse_json(response.body)
+ unless response.success? && payload.is_a?(Hash) && payload.present?
+ raise ApiError.new(
+ "SnapTrade OAuth metadata request failed: #{oauth_error_summary(payload, response.status)}",
+ status_code: response.status, response_body: response.body
+ )
+ end
+
+ Rails.cache.write(OAUTH_METADATA_CACHE_KEY, payload, expires_in: OAUTH_METADATA_CACHE_TTL)
+ payload
end
def refresh_tokens(refresh_token:)
- token_request(grant_type: "refresh_token", refresh_token: refresh_token)
+ token_request({ grant_type: "refresh_token", refresh_token: refresh_token })
end
# Best-effort revocation (RFC 7009). Returns true on success.
@@ -93,9 +218,9 @@ class Provider::Snaptrade
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["Authorization"] = basic_auth_header if confidential_client?
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
- request.body = URI.encode_www_form(token: token)
+ request.body = URI.encode_www_form(with_client_credentials({ token: token }))
end
response.success?
rescue Faraday::Error => e
@@ -105,27 +230,36 @@ class Provider::Snaptrade
private
+ # All three grants share TOKEN_URL. RFC 8628 §3.4 redeems a device code at
+ # the authorization server's token endpoint -- the same one the
+ # authorization code uses -- so there is one endpoint here, not one per
+ # grant, and nothing to keep in sync between issuing a token and
+ # refreshing it. Discovery is consulted only for
+ # device_authorization_endpoint, which has no hardcoded equivalent.
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.
+ # Not retried: a token request consumes a single-use authorization or
+ # device 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 succeeded.
response = without_retry("POST #{TOKEN_URL}") do
oauth_connection.post(TOKEN_URL) do |request|
- request.headers["Authorization"] = basic_auth_header
+ request.headers["Authorization"] = basic_auth_header if confidential_client?
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
- request.body = URI.encode_www_form(params)
+ request.body = URI.encode_www_form(with_client_credentials(params))
end
end
payload = parse_json(response.body)
return payload if response.success?
- error = payload["error_description"].presence || payload["error"].presence || "HTTP #{response.status}"
+ error = oauth_error_summary(payload, response.status)
if (400..499).cover?(response.status)
- raise AuthenticationError, "SnapTrade OAuth token request failed: #{error}"
+ raise AuthenticationError.new(
+ "SnapTrade OAuth token request failed: #{error}",
+ oauth_error: oauth_error_code(payload)
+ )
end
raise ApiError.new(
@@ -134,10 +268,34 @@ class Provider::Snaptrade
)
end
+ # A client secret means the token endpoint authenticates the client with
+ # HTTP Basic. Without one -- a device-flow-only deployment -- the client
+ # is public and identifies itself with client_id in the form body, which
+ # is also what RFC 8628 specifies for the device grant.
+ def confidential_client?
+ oauth_client_secret.present?
+ end
+
+ def with_client_credentials(params)
+ return params if confidential_client?
+
+ params.merge(client_id: oauth_client_id)
+ end
+
def basic_auth_header
"Basic #{Base64.strict_encode64("#{oauth_client_id}:#{oauth_client_secret}")}"
end
+ def oauth_error_summary(payload, status)
+ return "HTTP #{status}" unless payload.is_a?(Hash)
+
+ payload["error_description"].presence || payload["error"].presence || "HTTP #{status}"
+ end
+
+ def oauth_error_code(payload)
+ payload["error"].presence if payload.is_a?(Hash)
+ end
+
def oauth_connection
Faraday.new do |faraday|
faraday.options.timeout = 30
diff --git a/app/models/snaptrade_item/provided.rb b/app/models/snaptrade_item/provided.rb
index 66d6073cac..0718248cbb 100644
--- a/app/models/snaptrade_item/provided.rb
+++ b/app/models/snaptrade_item/provided.rb
@@ -23,6 +23,22 @@ module SnaptradeItem::Provided
payload
end
+ # Ask SnapTrade for a device code the user confirms on their side. Returns the
+ # device authorization payload; nothing is persisted until it is redeemed.
+ def start_oauth_device_flow(scope: "read")
+ Provider::Snaptrade.start_device_authorization(scope: scope)
+ end
+
+ # Redeem a confirmed device code. The payload has the same shape as the
+ # authorization-code response, so the item ends up in exactly the state
+ # complete_oauth_exchange! leaves it in -- one token model, two grants.
+ def complete_oauth_device_flow!(device_code:)
+ payload = Provider::Snaptrade.poll_device_token(device_code: device_code)
+ 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)
provider = snaptrade_provider
diff --git a/app/views/settings/providers/_snaptrade_panel.html.erb b/app/views/settings/providers/_snaptrade_panel.html.erb
index ff45d08d47..3d975f249d 100644
--- a/app/views/settings/providers/_snaptrade_panel.html.erb
+++ b/app/views/settings/providers/_snaptrade_panel.html.erb
@@ -10,7 +10,9 @@
items = local_assigns[:snaptrade_items] || @snaptrade_items || Current.family.snaptrade_items.active.ordered
snaptrade_item = items.reject(&:scheduled_for_deletion?).first
oauth_env_configured = Provider::Snaptrade.oauth_configured?
+ redirect_flow_available = Provider::Snaptrade.authorization_code_configured?
oauth_active = snaptrade_item&.oauth_token_active?
+ oauth_item_id = snaptrade_item&.persisted? ? snaptrade_item.id : nil
%>
<% if !oauth_env_configured %>
@@ -31,22 +33,44 @@
<p class="text-sm text-secondary">
<% if oauth_active %>
<%= t("providers.snaptrade.oauth_status_authorized") %>
- <% else %>
+ <% elsif redirect_flow_available %>
<%= t("providers.snaptrade.oauth_status_ready") %>
+ <% else %>
+ <%= t("providers.snaptrade.oauth_status_ready_device") %>
<% end %>
</p>
</div>
</div>
- <%= 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
- ) %>
+ <%# Both grants end with the same access token; which ones are offered %>
+ <%# depends only on what this deployment configured. %>
+ <% if redirect_flow_available %>
+ <%= 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: oauth_authorize_snaptrade_items_path(item_id: oauth_item_id)
+ ) %>
+
+ <%= render DS::Link.new(
+ text: t("providers.snaptrade.oauth_device_button"),
+ icon: "keyboard",
+ variant: :secondary,
+ full_width: true,
+ href: oauth_device_authorize_snaptrade_items_path(item_id: oauth_item_id),
+ frame: :drawer
+ ) %>
+ <% else %>
+ <%= render DS::Link.new(
+ text: oauth_active ? t("providers.snaptrade.oauth_reauthorize_button") : t("providers.snaptrade.oauth_device_button"),
+ icon: "keyboard",
+ variant: :primary,
+ full_width: true,
+ href: oauth_device_authorize_snaptrade_items_path(item_id: oauth_item_id),
+ frame: :drawer
+ ) %>
+ <% end %>
</div>
<% if snaptrade_item&.persisted? && snaptrade_item.oauth_configured? %>
diff --git a/app/views/snaptrade_items/_snaptrade_item.html.erb b/app/views/snaptrade_items/_snaptrade_item.html.erb
index 233b30df5c..441ec8e36b 100644
--- a/app/views/snaptrade_items/_snaptrade_item.html.erb
+++ b/app/views/snaptrade_items/_snaptrade_item.html.erb
@@ -3,9 +3,9 @@
<%= tag.div id: dom_id(snaptrade_item) do %>
<% unlinked_count = snaptrade_item.unlinked_accounts_count %>
<% 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 %>
- <% reconnect_href = oauth_authorize_snaptrade_items_path(item_id: snaptrade_item.id) %>
+ <% brokerage_connect_href = snaptrade_registered ? connect_snaptrade_item_path(snaptrade_item) : snaptrade_authorize_path(item_id: snaptrade_item.id) %>
+ <% brokerage_connect_frame = snaptrade_registered ? "_top" : snaptrade_authorize_frame %>
+ <% reconnect_href = snaptrade_authorize_path(item_id: snaptrade_item.id) %>
<%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>
<% disclosure.with_summary_content do %>
@@ -70,7 +70,7 @@
icon: "link",
variant: "secondary",
href: reconnect_href,
- frame: "_top"
+ frame: snaptrade_authorize_frame
) %>
<% else %>
<%= icon(
diff --git a/app/views/snaptrade_items/oauth_device_flow.html.erb b/app/views/snaptrade_items/oauth_device_flow.html.erb
new file mode 100644
index 0000000000..263d633dc0
--- /dev/null
+++ b/app/views/snaptrade_items/oauth_device_flow.html.erb
@@ -0,0 +1,103 @@
+<%= 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") %>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <p class="text-sm text-secondary">
+ <%= t("snaptrade_items.oauth_device_flow.subtitle") %>
+ </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") %>
+ </p>
+
+ <div class="space-y-1">
+ <p class="text-xs uppercase text-secondary">
+ <%= t("snaptrade_items.oauth_device_flow.code_label") %>
+ </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"),
+ 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 %>
+ <%# The device code and the flow's context are held in the session, not %>
+ <%# round-tripped through here: the code redeems into tokens on its own, %>
+ <%# so it stays server-side and the redemption stays bound to the family %>
+ <%# and item that started the flow. %>
+
+ <div class="flex justify-end gap-2">
+ <%= render DS::Link.new(
+ text: t("snaptrade_items.oauth_device_flow.cancel_button"),
+ 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"),
+ variant: :primary,
+ icon: "check",
+ type: :submit
+ ) %>
+ </div>
+ <% end %>
+ <% elsif @device_flow_available %>
+ <%= form_with url: start_oauth_device_flow_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"),
+ 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"),
+ 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"),
+ variant: :secondary,
+ href: connect_form_settings_providers_path(provider_key: "snaptrade"),
+ data: { turbo_frame: "drawer" }
+ ) %>
+ </div>
+ <% 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 aa886315c5..93e3f929b9 100644
--- a/app/views/snaptrade_items/setup_accounts.html.erb
+++ b/app/views/snaptrade_items/setup_accounts.html.erb
@@ -78,13 +78,13 @@
accountable_type: params[:accountable_type]
)
else
- oauth_authorize_snaptrade_items_path(
+ snaptrade_authorize_path(
item_id: @snaptrade_item.id,
accountable_type: params[:accountable_type],
return_to: params[:return_to]
)
end
- brokerage_connect_frame = @snaptrade_item.oauth_configured? ? "_top" : "drawer"
+ brokerage_connect_frame = @snaptrade_item.oauth_configured? ? "_top" : snaptrade_authorize_frame
%>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.try_again", default: "Connect Brokerage"),
diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb
index 0db59bec41..cf416ac214 100644
--- a/config/initializers/filter_parameter_logging.rb
+++ b/config/initializers/filter_parameter_logging.rb
@@ -7,5 +7,8 @@ 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,
+ # A device code redeems into tokens on its own, so it is a bearer credential in
+ # transit; verification_uri_complete embeds the user code, hence all three.
+ :device_code, :user_code, :verification_uri_complete,
:bank_username, :bank_password, :security_answers, :captcha_input
]
diff --git a/config/locales/views/snaptrade_items/en.yml b/config/locales/views/snaptrade_items/en.yml
index 2922a53f02..be225dee39 100644
--- a/config/locales/views/snaptrade_items/en.yml
+++ b/config/locales/views/snaptrade_items/en.yml
@@ -23,12 +23,31 @@ en:
select_accounts:
not_configured: "SnapTrade is not configured."
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."
+ not_configured: "The SnapTrade browser authorization needs SNAPTRADE_OAUTH_CLIENT_SECRET as well as SNAPTRADE_OAUTH_CLIENT_ID. Set it and restart, or authorize with a device code instead."
oauth_callback:
success: "SnapTrade authorization complete."
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."
+ oauth_device_flow:
+ title: "Connect SnapTrade"
+ subtitle: "Authorize Sure for SnapTrade with a device code."
+ instructions: "Open SnapTrade, confirm this device code, then come back here to finish."
+ 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 is not configured. Add SNAPTRADE_OAUTH_CLIENT_ID to .env.local, restart the app, then try again."
+ start_oauth_device_flow:
+ failed: "Unable to start SnapTrade device authorization. Please try again."
+ complete_oauth_device_flow:
+ success: "SnapTrade authorization complete."
+ device_code_required: "No SnapTrade device authorization is in progress for this connection. Start it again to get a new code."
+ authorization_pending: "SnapTrade hasn't seen your confirmation yet. Approve the code in SnapTrade, then try again."
+ expired: "This device code expired. Start the authorization again."
+ access_denied: "SnapTrade authorization was declined."
+ failed: "Unable to complete SnapTrade device authorization. Please try again."
select_existing_account:
not_found: "Account or SnapTrade configuration not found."
title: "Link to SnapTrade Account"
@@ -123,13 +142,15 @@ en:
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."
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"
+ oauth_setup_step_2_html: "For the browser flow only: add this app's callback URL (<code>%{callback_url}</code>) as a registered redirect URI"
+ oauth_setup_step_3: "Set SNAPTRADE_OAUTH_CLIENT_ID in your environment and restart. That alone enables the device code flow; add SNAPTRADE_OAUTH_CLIENT_SECRET for the browser flow too"
free_tier_warning: "SnapTrade's free tier covers 20 brokerage connections."
oauth_title: "SnapTrade OAuth"
oauth_status_ready: "Authorize Sure to read your SnapTrade account data."
+ oauth_status_ready_device: "Authorize Sure with a device code to read your SnapTrade account data."
oauth_status_authorized: "Authorized with SnapTrade."
oauth_connect_button: "Connect with SnapTrade"
+ oauth_device_button: "Use a device code"
oauth_reauthorize_button: "Reauthorize"
status_connected:
one: "%{count} account from SnapTrade"
diff --git a/config/routes.rb b/config/routes.rb
index 3afb308ab4..d4bec80824 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -157,6 +157,8 @@ Rails.application.routes.draw do
get :callback
get :oauth_authorize
get :oauth_callback
+ get :oauth_device_authorize
+ post :start_oauth_device_flow
end
member do
@@ -165,6 +167,7 @@ Rails.application.routes.draw do
get :setup_accounts
post :complete_account_setup
get :connections
+ post :complete_oauth_device_flow
delete :delete_connection
end
end
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index 8d93c088bf..26ec86be00 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -436,20 +436,38 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
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)
+ Provider::Snaptrade.stubs(:authorization_code_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")
+ # Both grants are available here, so the device code is offered alongside.
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_device_button")
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 offers only the device code without a confidential client" do
+ sign_in users(:empty)
+ Provider::Snaptrade.stubs(:oauth_configured?).returns(true)
+ Provider::Snaptrade.stubs(:authorization_code_configured?).returns(false)
+
+ get connect_form_settings_providers_path(provider_key: "snaptrade")
+
+ assert_response :success
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_device_button")
+ assert_includes response.body, I18n.t("providers.snaptrade.oauth_status_ready_device")
+ # The browser redirect needs a client secret this deployment does not have.
+ refute_includes response.body, I18n.t("providers.snaptrade.oauth_connect_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)
+ Provider::Snaptrade.stubs(:authorization_code_configured?).returns(true)
get connect_form_settings_providers_path(provider_key: "snaptrade")
diff --git a/test/controllers/snaptrade_items_controller_test.rb b/test/controllers/snaptrade_items_controller_test.rb
index 8d64f49791..4f9f832848 100644
--- a/test/controllers/snaptrade_items_controller_test.rb
+++ b/test/controllers/snaptrade_items_controller_test.rb
@@ -12,6 +12,46 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
end
end
+ # A deployment with a confidential OAuth client: both the browser redirect and
+ # the device code are available.
+ def with_oauth_app(&block)
+ with_snaptrade_oauth("client-id", "client-secret", &block)
+ end
+
+ # A deployment that only registered a public client: device code only.
+ def with_device_flow_only(&block)
+ with_snaptrade_oauth("client-id", nil, &block)
+ end
+
+ # Restores whatever was configured rather than clearing, so a test env that
+ # does set SnapTrade credentials doesn't leak nils into later tests.
+ def with_snaptrade_oauth(client_id, client_secret)
+ original_id = Rails.configuration.x.snaptrade.oauth_client_id
+ original_secret = Rails.configuration.x.snaptrade.oauth_client_secret
+ Rails.configuration.x.snaptrade.oauth_client_id = client_id
+ Rails.configuration.x.snaptrade.oauth_client_secret = client_secret
+ yield
+ ensure
+ Rails.configuration.x.snaptrade.oauth_client_id = original_id
+ Rails.configuration.x.snaptrade.oauth_client_secret = original_secret
+ end
+
+ DEVICE_AUTHORIZATION = {
+ "device_code" => "dev-c0de",
+ "user_code" => "WXYZ-1234",
+ "verification_uri" => "https://app.snaptrade.com/device",
+ "verification_uri_complete" => "https://app.snaptrade.com/device?code=WXYZ-1234",
+ "expires_in" => 600,
+ "interval" => 5
+ }.freeze
+
+ # The device code is held in the session, so completing a flow means starting
+ # one first -- the same two requests a user makes.
+ def start_device_flow(item, **params)
+ Provider::Snaptrade.stubs(:start_device_authorization).returns(DEVICE_AUTHORIZATION.dup)
+ post start_oauth_device_flow_snaptrade_items_url, params: { item_id: item.id }.merge(params)
+ end
+
test "connect redirects to portal when successful" do
portal_url = "https://app.snaptrade.com/portal/test123"
@@ -72,6 +112,217 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to settings_providers_path
end
+ test "oauth_authorize refuses when only the public client id is configured" do
+ with_device_flow_only do
+ get oauth_authorize_snaptrade_items_url
+
+ assert_redirected_to settings_providers_path
+ assert_match(/device code/, flash[:alert])
+ end
+ end
+
+ test "oauth_device_authorize offers to start authorization" do
+ Provider::Snaptrade.expects(:start_device_authorization).never
+
+ with_device_flow_only do
+ get oauth_device_authorize_snaptrade_items_url
+
+ assert_response :success
+ assert_select "form[action='#{start_oauth_device_flow_snaptrade_items_path}']"
+ end
+ end
+
+ test "oauth_device_authorize explains what to configure when the client id is missing" do
+ with_snaptrade_oauth(nil, nil) do
+ get oauth_device_authorize_snaptrade_items_url
+
+ assert_response :unprocessable_entity
+ assert_match(/SNAPTRADE_OAUTH_CLIENT_ID/, response.body)
+ end
+ end
+
+ test "start_oauth_device_flow shows the code the user confirms on SnapTrade" do
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:start_device_authorization).with(scope: "read").returns({
+ "device_code" => "dev-c0de",
+ "user_code" => "WXYZ-1234",
+ "verification_uri" => "https://app.snaptrade.com/device",
+ "verification_uri_complete" => "https://app.snaptrade.com/device?code=WXYZ-1234",
+ "expires_in" => 600,
+ "interval" => 5
+ })
+
+ post start_oauth_device_flow_snaptrade_items_url, params: { item_id: @snaptrade_item.id }
+
+ assert_response :success
+ assert_match "WXYZ-1234", response.body
+ # The user code is for the user to read; the device code redeems into
+ # tokens, so it stays in the session and never reaches the page.
+ assert_select "input[name='device_code']", count: 0
+ assert_no_match "dev-c0de", response.body
+ end
+ end
+
+ test "complete_oauth_device_flow stores tokens and queues a sync" do
+ item = snaptrade_items(:unauthorized_item)
+ sign_out
+ sign_in @user = users(:empty)
+
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).with(device_code: "dev-c0de").returns({
+ "access_token" => "device-at", "refresh_token" => "device-rt", "expires_in" => 900,
+ "token_type" => "Bearer", "scope" => "read"
+ })
+
+ start_device_flow(item)
+
+ assert_difference "Sync.count", 1 do
+ post complete_oauth_device_flow_snaptrade_item_url(item)
+ end
+
+ assert_redirected_to settings_providers_path
+ assert_equal "device-at", item.reload.oauth_access_token
+ assert item.good?
+ end
+ end
+
+ test "complete_oauth_device_flow leaves the drawer instead of navigating inside it" do
+ with_device_flow_only do
+ Provider::Snaptrade.stubs(:poll_device_token).returns({
+ "access_token" => "device-at", "refresh_token" => "device-rt", "expires_in" => 900
+ })
+
+ start_device_flow(@snaptrade_item)
+
+ post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item),
+ headers: { "Turbo-Frame" => "drawer" }
+
+ # A plain redirect would be followed as a frame navigation and swap in the
+ # layout's empty drawer frame, closing the dialog and going nowhere.
+ assert_response :success
+ assert_match "turbo-stream", response.body
+ assert_match "redirect", response.body
+ assert_match settings_providers_path, response.body
+ assert_equal I18n.t("snaptrade_items.complete_oauth_device_flow.success"), flash[:notice]
+ end
+ end
+
+ test "complete_oauth_device_flow resumes account setup when asked to" do
+ with_device_flow_only do
+ Provider::Snaptrade.stubs(:poll_device_token).returns({
+ "access_token" => "device-at", "refresh_token" => "device-rt", "expires_in" => 900
+ })
+
+ start_device_flow(@snaptrade_item, return_to: "setup_accounts", accountable_type: "Investment")
+
+ # Where to return to was recorded when the flow started, so completion
+ # needs nothing from the form to find its way back.
+ post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item)
+
+ assert_redirected_to setup_accounts_snaptrade_item_path(@snaptrade_item, accountable_type: "Investment")
+ end
+ end
+
+ test "complete_oauth_device_flow keeps the code when the user has not confirmed it yet" do
+ item = snaptrade_items(:unauthorized_item)
+ sign_out
+ sign_in @user = users(:empty)
+
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).raises(
+ Provider::Snaptrade::AuthenticationError.new("SnapTrade OAuth token request failed: authorization_pending", oauth_error: "authorization_pending")
+ )
+
+ start_device_flow(item)
+
+ post complete_oauth_device_flow_snaptrade_item_url(item)
+
+ assert_response :unprocessable_entity
+ # Still redeemable, so the page comes back with the same code rather than
+ # sending the user back to the start.
+ assert_match "WXYZ-1234", response.body
+ assert_select "form[action='#{complete_oauth_device_flow_snaptrade_item_path(item)}']"
+ assert_nil item.reload.oauth_access_token
+ end
+ end
+
+ test "complete_oauth_device_flow drops a code the server says is spent" do
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).raises(
+ Provider::Snaptrade::AuthenticationError.new("SnapTrade OAuth token request failed: expired_token", oauth_error: "expired_token")
+ )
+
+ start_device_flow(@snaptrade_item)
+ post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item)
+
+ assert_response :unprocessable_entity
+ # Nothing left to retry with, so the page offers a fresh start instead of
+ # a button that can only fail again.
+ assert_no_match "WXYZ-1234", response.body
+ assert_select "form[action='#{start_oauth_device_flow_snaptrade_items_path}']"
+ end
+ end
+
+ test "complete_oauth_device_flow requires a flow started in this session" do
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).never
+
+ post complete_oauth_device_flow_snaptrade_item_url(@snaptrade_item)
+
+ assert_response :unprocessable_entity
+ end
+ end
+
+ # The device code is a bearer credential that says nothing about who asked for
+ # it. If the request body could supply one, anyone who came by a code -- from a
+ # log, a shared screen -- could redeem someone else's pending authorization
+ # into an item of their own. Only the session that started the flow can finish
+ # it.
+ test "complete_oauth_device_flow ignores a device code supplied as a parameter" do
+ item = snaptrade_items(:unauthorized_item)
+ sign_out
+ sign_in @user = users(:empty)
+
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).never
+
+ post complete_oauth_device_flow_snaptrade_item_url(item), params: { device_code: "someone-elses-code" }
+
+ assert_response :unprocessable_entity
+ assert_nil item.reload.oauth_access_token
+ end
+ end
+
+ test "complete_oauth_device_flow will not redeem a code into a different item" do
+ other_item = @user.family.snaptrade_items.create!(name: "Another SnapTrade")
+
+ with_device_flow_only do
+ Provider::Snaptrade.expects(:poll_device_token).never
+
+ start_device_flow(@snaptrade_item)
+ post complete_oauth_device_flow_snaptrade_item_url(other_item)
+
+ assert_response :unprocessable_entity
+ assert_nil other_item.reload.oauth_access_token
+ end
+ end
+
+ # The device code is the whole capability check on complete_oauth_device_flow;
+ # nothing binds it to the family that requested it, the way state does in the
+ # redirect flow. So it must not reach the request log.
+ test "device flow codes are filtered from logs" do
+ parameter_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)
+ filtered_params = parameter_filter.filter(
+ device_code: "dev-c0de",
+ user_code: "WXYZ-1234",
+ verification_uri_complete: "https://app.snaptrade.com/device?code=WXYZ-1234"
+ )
+
+ assert_equal "[FILTERED]", filtered_params[:device_code]
+ assert_equal "[FILTERED]", filtered_params[:user_code]
+ assert_equal "[FILTERED]", filtered_params[:verification_uri_complete]
+ end
+
test "oauth_callback rejects state mismatch without exchanging the code" do
Provider::Snaptrade.expects(:exchange_code).never
@@ -193,10 +444,22 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
test "Reconnect starts OAuth authorization instead of adding a brokerage" do
@snaptrade_item.update!(status: :requires_update)
- get accounts_url
+ with_oauth_app do
+ get accounts_url
- assert_select "a[href='#{oauth_authorize_snaptrade_items_path(item_id: @snaptrade_item.id)}'][data-turbo-frame='_top']", text: /Reconnect/
- assert_select "a[href='#{connect_snaptrade_item_path(@snaptrade_item)}']", text: /Reconnect/, count: 0
+ assert_select "a[href='#{oauth_authorize_snaptrade_items_path(item_id: @snaptrade_item.id)}'][data-turbo-frame='_top']", text: /Reconnect/
+ assert_select "a[href='#{connect_snaptrade_item_path(@snaptrade_item)}']", text: /Reconnect/, count: 0
+ end
+ end
+
+ test "Reconnect uses the device flow when the deployment has no confidential client" do
+ @snaptrade_item.update!(status: :requires_update)
+
+ with_device_flow_only do
+ get accounts_url
+
+ assert_select "a[href='#{oauth_device_authorize_snaptrade_items_path(item_id: @snaptrade_item.id)}'][data-turbo-frame='drawer']", text: /Reconnect/
+ end
end
test "select_accounts redirects unregistered users into connect flow" do
@@ -204,13 +467,31 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
sign_in @user = users(:empty)
snaptrade_item = snaptrade_items(:unauthorized_item)
- get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "setup_accounts" }
+ with_oauth_app do
+ get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "setup_accounts" }
- assert_redirected_to oauth_authorize_snaptrade_items_path(
- item_id: snaptrade_item.id,
- accountable_type: "Investment",
- return_to: "setup_accounts"
- )
+ assert_redirected_to oauth_authorize_snaptrade_items_path(
+ item_id: snaptrade_item.id,
+ accountable_type: "Investment",
+ return_to: "setup_accounts"
+ )
+ end
+ end
+
+ test "select_accounts sends unregistered users to the device flow without a confidential client" do
+ sign_out
+ sign_in @user = users(:empty)
+ snaptrade_item = snaptrade_items(:unauthorized_item)
+
+ with_device_flow_only do
+ get select_accounts_snaptrade_items_url, params: { accountable_type: "Investment", return_to: "setup_accounts" }
+
+ assert_redirected_to oauth_device_authorize_snaptrade_items_path(
+ item_id: snaptrade_item.id,
+ accountable_type: "Investment",
+ return_to: "setup_accounts"
+ )
+ end
end
test "select_accounts redirects registered users to setup flow" do
@@ -222,11 +503,14 @@ class SnaptradeItemsControllerTest < ActionDispatch::IntegrationTest
test "preload_accounts redirects unregistered users into connect flow" do
sign_out
sign_in @user = users(:empty)
- assert_no_difference "Sync.count" do
- get preload_accounts_snaptrade_items_url
- end
- assert_redirected_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_items(:unauthorized_item).id)
+ with_oauth_app do
+ assert_no_difference "Sync.count" do
+ get preload_accounts_snaptrade_items_url
+ end
+
+ assert_redirected_to oauth_authorize_snaptrade_items_path(item_id: snaptrade_items(:unauthorized_item).id)
+ end
end
test "preload_accounts redirects registered users to setup flow and queues sync" do
diff --git a/test/models/provider/snaptrade_oauth_test.rb b/test/models/provider/snaptrade_oauth_test.rb
index d3c5bf64fb..f7f92cac07 100644
--- a/test/models/provider/snaptrade_oauth_test.rb
+++ b/test/models/provider/snaptrade_oauth_test.rb
@@ -11,14 +11,29 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
Rails.configuration.x.snaptrade = @original
end
- test "oauth_configured? requires both client id and secret" do
+ test "oauth_configured? needs only the public client id, the redirect flow needs the secret too" do
assert_not Provider::Snaptrade.oauth_configured?
+ assert_not Provider::Snaptrade.authorization_code_configured?
Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
- assert_not Provider::Snaptrade.oauth_configured?
+ assert Provider::Snaptrade.oauth_configured?
+ assert_not Provider::Snaptrade.authorization_code_configured?
Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
assert Provider::Snaptrade.oauth_configured?
+ assert Provider::Snaptrade.authorization_code_configured?
+ end
+
+ test "the redirect flow refuses to start without a confidential client" do
+ configure_device_flow_only!
+
+ assert_raises(Provider::Snaptrade::ConfigurationError) do
+ Provider::Snaptrade.authorize_url(redirect_uri: "https://sure.test/cb", state: "s", code_challenge: "c")
+ end
+
+ assert_raises(Provider::Snaptrade::ConfigurationError) do
+ Provider::Snaptrade.exchange_code(code: "c0de", redirect_uri: "https://sure.test/cb", code_verifier: "v")
+ end
end
# --- helpers ---
@@ -27,6 +42,19 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
Rails.configuration.x.snaptrade.oauth_client_secret = "client-secret"
end
+ # A deployment that registered only a public OAuth client: device flow only.
+ def configure_device_flow_only!
+ Rails.configuration.x.snaptrade.oauth_client_id = "client-id"
+ Rails.configuration.x.snaptrade.oauth_client_secret = nil
+ end
+
+ def discovery_body
+ {
+ device_authorization_endpoint: "https://api.snaptrade.com/oauth/device_authorization/",
+ token_endpoint: Provider::Snaptrade::TOKEN_URL
+ }.to_json
+ end
+
def faraday_response(status:, body:)
OpenStruct.new(status: status, body: body, success?: (200..299).cover?(status))
end
@@ -298,4 +326,180 @@ class Provider::SnaptradeOauthTest < ActiveSupport::TestCase
assert_equal "read", body["connectionType"]
assert_equal "QUESTRADE", body["broker"]
end
+
+
+ # --- Device flow (RFC 8628) ---
+
+ test "start_device_authorization posts the public client id to the discovered endpoint" do
+ configure_device_flow_only!
+
+ request = OpenStruct.new(headers: {})
+ connection = mock("faraday")
+ connection.expects(:get).with(Provider::Snaptrade::OAUTH_DISCOVERY_URL)
+ .returns(faraday_response(status: 200, body: discovery_body))
+ connection.expects(:post).with("https://api.snaptrade.com/oauth/device_authorization/").yields(request)
+ .returns(faraday_response(status: 200, body: {
+ device_code: "dev-c0de", user_code: "WXYZ-1234",
+ verification_uri: "https://app.snaptrade.com/device",
+ verification_uri_complete: "https://app.snaptrade.com/device?code=WXYZ-1234",
+ expires_in: 600, interval: 5
+ }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ payload = Provider::Snaptrade.start_device_authorization
+
+ assert_equal "dev-c0de", payload["device_code"]
+ assert_equal "WXYZ-1234", payload["user_code"]
+ body = Rack::Utils.parse_query(request.body)
+ assert_equal "client-id", body["client_id"]
+ assert_equal "read", body["scope"]
+ end
+
+ test "start_device_authorization authenticates a confidential client" do
+ configure_oauth!
+
+ request = OpenStruct.new(headers: {})
+ connection = mock("faraday")
+ connection.expects(:get).returns(faraday_response(status: 200, body: discovery_body))
+ connection.expects(:post).yields(request)
+ .returns(faraday_response(status: 200, body: {
+ device_code: "dev-c0de", user_code: "WXYZ-1234", verification_uri: "https://app.snaptrade.com/device"
+ }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ Provider::Snaptrade.start_device_authorization
+
+ assert_equal "Basic #{Base64.strict_encode64('client-id:client-secret')}", request.headers["Authorization"]
+ assert_nil Rack::Utils.parse_query(request.body)["client_id"]
+ end
+
+ test "start_device_authorization rejects a 2xx that cannot drive the flow" do
+ configure_device_flow_only!
+
+ connection = mock("faraday")
+ connection.expects(:get).returns(faraday_response(status: 200, body: discovery_body))
+ # A device code with nothing to show the user and nowhere to send them
+ # would render a blank drawer the user can only abandon.
+ connection.expects(:post).returns(faraday_response(status: 200, body: { device_code: "dev-c0de" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ error = assert_raises(Provider::Snaptrade::ApiError) { Provider::Snaptrade.start_device_authorization }
+ assert_match "user_code", error.message
+ assert_match "verification_uri", error.message
+ end
+
+ test "start_device_authorization accepts verification_uri_complete in place of verification_uri" do
+ configure_device_flow_only!
+
+ connection = mock("faraday")
+ connection.expects(:get).returns(faraday_response(status: 200, body: discovery_body))
+ connection.expects(:post).returns(faraday_response(status: 200, body: {
+ device_code: "dev-c0de", user_code: "WXYZ-1234",
+ verification_uri_complete: "https://app.snaptrade.com/device?code=WXYZ-1234"
+ }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ payload = Provider::Snaptrade.start_device_authorization
+
+ assert_equal "dev-c0de", payload["device_code"]
+ end
+
+ test "start_device_authorization raises when the metadata has no device endpoint" do
+ configure_device_flow_only!
+
+ connection = mock("faraday")
+ connection.expects(:get).returns(faraday_response(status: 200, body: { token_endpoint: Provider::Snaptrade::TOKEN_URL }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ error = assert_raises(Provider::Snaptrade::ApiError) { Provider::Snaptrade.start_device_authorization }
+ assert_match "device_authorization_endpoint", error.message
+ end
+
+ test "poll_device_token redeems the device code as a public client" do
+ configure_device_flow_only!
+
+ request = OpenStruct.new(headers: {})
+ connection = mock("faraday")
+ 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.poll_device_token(device_code: "dev-c0de")
+
+ assert_equal "at", payload["access_token"]
+ # A public client has no secret to authenticate with, so it identifies
+ # itself in the body instead of an Authorization header.
+ assert_nil request.headers["Authorization"]
+ body = Rack::Utils.parse_query(request.body)
+ assert_equal Provider::Snaptrade::DEVICE_CODE_GRANT, body["grant_type"]
+ assert_equal "dev-c0de", body["device_code"]
+ assert_equal "client-id", body["client_id"]
+ end
+
+ test "poll_device_token surfaces authorization_pending as a distinguishable error" do
+ configure_device_flow_only!
+
+ connection = mock("faraday")
+ connection.expects(:post).returns(faraday_response(status: 400, body: { error: "authorization_pending" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ error = assert_raises(Provider::Snaptrade::AuthenticationError) do
+ Provider::Snaptrade.poll_device_token(device_code: "dev-c0de")
+ end
+ assert_equal "authorization_pending", error.oauth_error
+ end
+
+ test "poll_device_token requires a device code" do
+ configure_device_flow_only!
+
+ assert_raises(ArgumentError) { Provider::Snaptrade.poll_device_token(device_code: "") }
+ end
+
+ # Refresh and revocation are shared by both grants, so they have to work for a
+ # deployment that only ever configured the public client id -- otherwise a
+ # device-authorized item would authorize fine and then fail at its first
+ # token rotation.
+ test "refresh_tokens authenticates a public client in the body and a confidential one with basic auth" do
+ configure_device_flow_only!
+
+ public_request = OpenStruct.new(headers: {})
+ public_connection = mock("faraday")
+ public_connection.expects(:post).yields(public_request)
+ .returns(faraday_response(status: 200, body: { access_token: "at" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(public_connection)
+
+ Provider::Snaptrade.refresh_tokens(refresh_token: "rt")
+
+ assert_nil public_request.headers["Authorization"]
+ assert_equal "client-id", Rack::Utils.parse_query(public_request.body)["client_id"]
+
+ configure_oauth!
+
+ confidential_request = OpenStruct.new(headers: {})
+ confidential_connection = mock("faraday")
+ confidential_connection.expects(:post).yields(confidential_request)
+ .returns(faraday_response(status: 200, body: { access_token: "at" }.to_json))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(confidential_connection)
+
+ Provider::Snaptrade.refresh_tokens(refresh_token: "rt")
+
+ assert_equal "Basic #{Base64.strict_encode64('client-id:client-secret')}", confidential_request.headers["Authorization"]
+ assert_nil Rack::Utils.parse_query(confidential_request.body)["client_id"]
+ end
+
+ test "revoke_token works for a public client" do
+ configure_device_flow_only!
+
+ request = OpenStruct.new(headers: {})
+ connection = mock("faraday")
+ connection.expects(:post).with(Provider::Snaptrade::REVOKE_URL).yields(request)
+ .returns(faraday_response(status: 200, body: ""))
+ Provider::Snaptrade.stubs(:oauth_connection).returns(connection)
+
+ assert Provider::Snaptrade.revoke_token(token: "rt")
+ assert_nil request.headers["Authorization"]
+ body = Rack::Utils.parse_query(request.body)
+ assert_equal "rt", body["token"]
+ assert_equal "client-id", body["client_id"]
+ end
end
diff --git a/test/models/snaptrade_item_oauth_test.rb b/test/models/snaptrade_item_oauth_test.rb
index 133acb1ecd..77d1cf116a 100644
--- a/test/models/snaptrade_item_oauth_test.rb
+++ b/test/models/snaptrade_item_oauth_test.rb
@@ -43,6 +43,31 @@ class SnaptradeItemOauthTest < ActiveSupport::TestCase
assert @item.good?
end
+ test "complete_oauth_device_flow! leaves the item where the redirect flow would" do
+ item = snaptrade_items(:unauthorized_item)
+ Provider::Snaptrade.expects(:poll_device_token)
+ .with(device_code: "dev-c0de")
+ .returns({ "access_token" => "at", "refresh_token" => "rt", "expires_in" => 900, "token_type" => "Bearer", "scope" => "read" })
+
+ item.complete_oauth_device_flow!(device_code: "dev-c0de")
+
+ assert_equal "at", item.oauth_access_token
+ assert_equal "rt", item.oauth_refresh_token
+ assert item.good?
+ # The whole point of the second grant: from here the item is an ordinary
+ # token-authorized item, so it syncs like any other.
+ assert item.oauth_configured?
+ assert_includes SnaptradeItem.syncable, item
+ end
+
+ test "start_oauth_device_flow asks the provider for a device code" do
+ Provider::Snaptrade.expects(:start_device_authorization)
+ .with(scope: "read")
+ .returns({ "device_code" => "dev-c0de", "user_code" => "WXYZ-1234" })
+
+ assert_equal "WXYZ-1234", @item.start_oauth_device_flow["user_code"]
+ 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