SnapTrade: sync with a Personal API key when no OAuth app is configured

Merged
AR
15d ago
+721-55

Fixes #5031

Why

Sure's SnapTrade integration only accepts an OAuth app (SNAPTRADE_OAUTH_CLIENT_ID), and registering one needs a Commercial SnapTrade account. A self-hoster who wants their own brokerage accounts (tastytrade, Schwab, …) has a free SnapTrade Personal key instead: one clientId + consumerKey, already bound to its own SnapTrade user. Today that key can't be used at all, and the old registerUser path fails with code 1012 (#2387).

SnapTrade's documented Personal mode is small:

The connection portal (/snapTrade/login) works the same way.

What

  • POST /snaptrade_items/personal_key (admin only, scoped to Current.family, and 404 when an OAuth client is configured) stores the key on the family's item, creating the item if needed. Both fields are required.
    • It sets oauth_token_type to "personal_key". That is the explicit mode marker; nothing else reads that column.
    • It clears any stale OAuth token, so the key is what signs requests. It also clears the legacy user id/secret, sets status: :good and queues a sync.
  • SnaptradeItem
    • personal_key_configured? checks only that marker. Items from the pre-OAuth integration (#737) stored client_id/consumer_key too, but they never carry the marker, so they are never treated as Personal keys.
    • credentials_configured? (already an alias) now means "OAuth token or Personal key".
    • syncable includes the marked items.
    • The call sites that meant "is this item authorized" (syncer, snaptrade_provider, setup/select/preload routing, the item card, the provider summary) use credentials_configured? instead of oauth_configured?.
  • Provider::Snaptrade#request_json is the one place every data call goes through. For a Personal key item without an OAuth token it calls signed_request_json. An OAuth token always wins, so authorizing with OAuth later (apply_oauth_tokens!) switches the item back.
    • Each attempt, retries included, gets a fresh timestamp and signature.
    • The query is built with Faraday's own params encoder, so re-encoding the URL leaves the signed bytes unchanged.
    • The body is sent as the same canonical JSON (sorted keys, JSON.generate) that is signed.
    • There is no refresh-and-retry: a 401/403 means the key itself was rejected, which handle_response already turns into requires_update.
  • Rate limit (10 requests a minute per account for Personal keys).
    • A 429 now raises RateLimitError, a subclass of ApiError, so existing rescues are unchanged.
    • SnapTrade keeps one Personal bucket per account, so the provider does too: after a 429, later calls for that same account (the /accounts/:id/ segment of the path, or one shared bucket for account-less paths) raise straight away without a request, while the other accounts in the same sync carry on. If any account was rate-limited, the importer re-raises at the end, so the sync fails with "Rate limit exceeded" instead of quietly keeping that account's stale balances and positions; the next sync resumes.
    • The post-connect activities poll now waits SnapTrade's recommended 15 s between attempts (was 10 s; one constant for both modes), and it retries a 429 on that schedule.
    • Known limit: activities are fetched in pages of 1,000, and a 429 partway through drops the pages already fetched in that call. Each retry and each later sync starts again at offset 0. So a Personal-key account whose activity history needs more pages than fit in one minute's budget (about 10,000 rows or more in the range) cannot import that history. Resuming from the next offset, or waiting for the window and retrying the page, is a follow-up.
  • Settings panel. When no OAuth client is configured, the panel shows a client ID / consumer key form (password field, never pre-filled) above the existing OAuth setup steps. "Manage connections" also shows for Personal key items.
    • snaptrade_authorize_path sends unauthorized items to the provider settings when there is no OAuth client, instead of to a device-flow drawer that can only say "not configured".
  • .env.local.example notes that leaving the OAuth vars unset means Personal keys.

Unchanged when SNAPTRADE_OAUTH_CLIENT_ID is set: the panel, both grants, token refresh and revocation, and the Bearer requests (apart from the 15 s activities poll spacing). The Personal-key endpoint returns 404. An instance that configures OAuth after saving a Personal key keeps syncing that item with the key, but can only rotate or replace it by authorizing with OAuth, which switches the item to Bearer: any OAuth authorization clears the "personal_key" marker, even if the token response has no token_type. No migration: the encrypted client_id/consumer_key columns already exist.

Security

  • client_id and consumer_key were already encrypts'd on SnaptradeItem (deterministic, as in #737), and both are already in filter_parameters.
  • The consumer key never leaves the server. Only the HMAC is sent, and error messages include only the method and path, never the query.
  • The form never echoes stored values, and the consumer key is a password field.
  • The action is admin-only and scoped to Current.family. It is refused server-side on OAuth deployments.
  • Switching an OAuth item to a key drops its tokens without revoking them. The endpoint only runs when the instance has no OAuth client, and revocation needs one.

Tests

  • test/models/provider/snaptrade_personal_key_test.rb (new, WebMock):
    • checks the signature on GET /accounts, recomputed from the request as received;
    • checks there is no Authorization header and no userId/userSecret;
    • checks that query params are covered by the signature;
    • signs a hand-built known vector for POST /snapTrade/login;
    • checks that a retry after a network error is re-signed with a fresh timestamp;
    • checks that a 401 marks the item requires_update without attempting a token refresh;
    • checks that a 429 stops further requests for that account, but not for another account;
    • checks that an OAuth authorization without token_type clears the Personal key marker;
    • checks that authorizing with OAuth switches the item back to Bearer.
  • test/models/snaptrade_item_test.rb: the Personal key authorizes an item; a pre-OAuth item with keys but no registered user is not a Personal key; and the syncable scope.
  • test/controllers/snaptrade_items_controller_test.rb:
    • saving the key starts a sync and clears the legacy secret;
    • saving the key switches a formerly OAuth item (stale token) to signed requests;
    • the action returns 404 when an OAuth app is configured;
    • the action creates the item when the family has none;
    • a missing half of the key returns 422 (these tests clear any configured OAuth app first, so they pass with SNAPTRADE_OAUTH_CLIENT_ID set);
    • without an OAuth app, select_accounts routes to the provider settings.
  • Importer and activities-fetch job tests cover the rate-limit handling.
  • test/controllers/settings/providers_controller_test.rb checks the form renders. test/helpers/settings_helper_test.rb stubs now use credentials_configured?.

All SnapTrade, settings, helper and i18n tests pass: 433 runs, 0 failures, 4 skips (i18n's usual skips). Rubocop and erb_lint are clean on the changed files.

🤖 Generated with Claude Code


Summary by cubic

Adds support for SnapTrade Personal API keys, so self-hosters can connect their own brokerage accounts without registering a Commercial OAuth app. Fixes #5031.

  • New admin-only POST /snaptrade_items/personal_key endpoint (404 when an OAuth client is configured) stores the key on the family's item and starts a sync.
  • Items with a saved key sign all requests with the consumer key (clientId + timestamp query params, Signature header) instead of a Bearer token, with no userId/userSecret; an OAuth token always wins, so authorizing later switches the item back.
  • Paged activities requests sign each page for its own limit/offset.
  • Pre-OAuth items that stored keys are never treated as Personal keys.
  • 429 responses now raise RateLimitError; a rate-limited Personal key stops further requests for that account and fails the sync instead of keeping stale data, with the activities poll backing off to SnapTrade's 15 s and retrying on a 429.
  • A rate-limited activities fetch that never succeeds is recorded to DebugLogEntry instead of being treated as an empty account.
  • The provider settings panel shows the key form only when no OAuth app is configured; the consumer key is a password field, never pre-filled, and never leaves the server.
  • The Panel now acts on the same item the controller does, so a saved key shows Manage Connections even when a newer item exists.
  • In the panel, an OAuth item lists its connections only while the OAuth app is configured; a Personal key lists them either way.

Summary by CodeRabbit

  • New Features
    • Connect a brokerage through SnapTrade using a Personal API key entered in Settings > Providers > SnapTrade, without requiring an OAuth app. OAuth remains available as an alternative.
    • Saving a Personal API key starts an account sync.
  • Bug Fixes
    • SnapTrade activity syncs now retry after rate limits, with a longer delay between attempts. When retries are exhausted, the sync completes and reports the rate-limit error.
  • Documentation
    • Clarified in the SnapTrade environment-variable example how unset or configured credentials affect account setup.