Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let household members own provider connections (Plaid) (#3613)

Brian Espinoza811baf5ba7ea
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 1208643da1..99730c2b95 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -347,9 +347,24 @@ class AccountsController < ApplicationController
end
def visible_provider_items(items)
+ accessible_ids = @accessible_account_ids.to_a
+
items.select do |item|
- Current.user.admin? ||
- (item.respond_to?(:accounts) && (item.accounts.map(&:id) & @accessible_account_ids).any?)
+ next true if Current.user.admin?
+
+ account_ids = item.respond_to?(:accounts) ? item.accounts.map(&:id) : []
+
+ # Ownership shows a member their own connection, importantly including
+ # one just created that has not synced any accounts yet. It must not
+ # widen what they can see: the card renders the item's accounts
+ # unfiltered, and is re-rendered by a family-wide broadcast with no
+ # viewer, so an owner is shown the card only while every account on it
+ # is already accessible to them.
+ if item.respond_to?(:owned_by?) && item.owned_by?(Current.user)
+ next true if (account_ids - accessible_ids).empty?
+ end
+
+ (account_ids & accessible_ids).any?
end
end
diff --git a/app/controllers/concerns/connector_authorizable.rb b/app/controllers/concerns/connector_authorizable.rb
new file mode 100644
index 0000000000..92d06f7ed4
--- /dev/null
+++ b/app/controllers/concerns/connector_authorizable.rb
@@ -0,0 +1,72 @@
+# Authorization for provider connector controllers.
+#
+# Replaces a blanket `require_admin!` with a check driven by the provider's
+# declared credential scope (see ProviderItemOwnable). A controller opts in by
+# naming its item class:
+#
+# class PlaidItemsController < ApplicationController
+# include ConnectorAuthorizable
+# connects_provider PlaidItem
+#
+# Controllers that do not opt in are unaffected and keep their own gating, so
+# this is safe to roll out one provider at a time.
+module ConnectorAuthorizable
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :connector_item_class, instance_accessor: false
+ end
+
+ class_methods do
+ def connects_provider(klass)
+ self.connector_item_class = klass
+ end
+ end
+
+ private
+ # Gate for creating a new connection. Admins always may; a member may only
+ # when the provider's credential is scoped to the single connection they
+ # are authenticating. Guests never may -- they are read-only by design.
+ def require_connector_create!
+ return if Current.user&.admin?
+ return if connector_item_class&.member_connectable? && Current.user&.member?
+
+ deny_connector_access!
+ end
+
+ # Gate for mutating an existing connection (edit/destroy/sync). Ownership,
+ # not just role: a member may manage the connections they added and no
+ # others.
+ def require_connector_manage!
+ return if connector_item.present? && connector_item.manageable_by?(Current.user)
+
+ deny_connector_access!
+ end
+
+ def connector_item_class
+ self.class.connector_item_class
+ end
+
+ # The item loaded by the controller's own `before_action`. Convention over
+ # configuration: PlaidItemsController sets @plaid_item.
+ def connector_item
+ return nil if connector_item_class.nil?
+
+ instance_variable_get(:"@#{connector_item_class.name.underscore}")
+ end
+
+ def deny_connector_access!
+ message = if connector_item_class&.member_connectable?
+ t("shared.require_connector_owner")
+ else
+ t("shared.require_admin")
+ end
+
+ respond_to do |format|
+ format.html { redirect_to accounts_path, alert: message }
+ format.turbo_stream { head :forbidden }
+ format.json { head :forbidden }
+ format.any { head :forbidden }
+ end
+ end
+end
diff --git a/app/controllers/plaid_items_controller.rb b/app/controllers/plaid_items_controller.rb
index bd58445682..043d8d05f0 100644
--- a/app/controllers/plaid_items_controller.rb
+++ b/app/controllers/plaid_items_controller.rb
@@ -1,8 +1,11 @@
class PlaidItemsController < ApplicationController
- include StreamExtensions
+ include StreamExtensions, ConnectorAuthorizable
+
+ connects_provider PlaidItem
before_action :set_plaid_item, only: %i[edit destroy sync]
- before_action :require_admin!, only: %i[new create select_existing_account link_existing_account edit destroy sync]
+ before_action :require_connector_create!, only: %i[new create select_existing_account link_existing_account]
+ before_action :require_connector_manage!, only: %i[edit destroy sync]
def new
region = params[:region] == "eu" ? :eu : :us
@@ -58,10 +61,18 @@ class PlaidItemsController < ApplicationController
@account = Current.family.accounts.find(params[:account_id])
@region = params[:region] || "us"
+ # A non-admin reaches this action now, so the target account needs its own
+ # check -- family membership alone is not authorisation to attach a feed to
+ # someone else's account.
+ return if !Current.user.admin? && !require_account_permission!(@account)
+
# Get all Plaid accounts from this family's Plaid items for the specified region
- # that are not yet linked to any account
- @available_plaid_accounts = Current.family.plaid_items
- .where(plaid_region: @region)
+ # that are not yet linked to any account. A member only sees the items they
+ # own; an admin sees the family's.
+ scope = Current.family.plaid_items.where(plaid_region: @region)
+ scope = scope.owned_by(Current.user) unless Current.user.admin?
+
+ @available_plaid_accounts = scope
.includes(:plaid_accounts)
.flat_map(&:plaid_accounts)
.select { |pa| pa.account_provider.nil? && pa.account.nil? } # Not linked via new or legacy system
@@ -75,12 +86,17 @@ class PlaidItemsController < ApplicationController
@account = Current.family.accounts.find(params[:account_id])
plaid_account = PlaidAccount.find(params[:plaid_account_id])
- # Verify the Plaid account belongs to this family's Plaid items
- unless Current.family.plaid_items.include?(plaid_account.plaid_item)
+ # Verify the Plaid account belongs to this family's Plaid items, and that
+ # this user may act on that connection at all -- a member must not be able
+ # to attach a connection someone else owns.
+ unless Current.family.plaid_items.include?(plaid_account.plaid_item) &&
+ plaid_account.plaid_item.manageable_by?(Current.user)
redirect_to account_path(@account), alert: t(".invalid_account")
return
end
+ return if !Current.user.admin? && !require_account_permission!(@account)
+
# Verify the Plaid account is not already linked
if plaid_account.account_provider.present? || plaid_account.account.present?
redirect_to account_path(@account), alert: t(".already_linked")
diff --git a/app/models/concerns/provider_item_ownable.rb b/app/models/concerns/provider_item_ownable.rb
new file mode 100644
index 0000000000..14f9dca9aa
--- /dev/null
+++ b/app/models/concerns/provider_item_ownable.rb
@@ -0,0 +1,104 @@
+# Per-user ownership for provider connections.
+#
+# Every provider item table is family-scoped and, historically, carried no
+# notion of *who* connected it -- so the only safe gate on the connector
+# controllers was a blanket `require_admin!`. That forced a household to choose
+# between sharing every connection or giving a member no automation at all.
+#
+# This concern adds an owner and lets each provider declare whether its
+# credential is safe for a non-admin member to supply:
+#
+# per_connection -- the credential covers only what the person supplying it
+# authenticated to (Plaid Link, an exchange API key). A
+# member connecting their own bank exposes nothing of
+# anyone else's.
+# tenant_wide -- one credential enumerates accounts the supplier may not
+# own (SimpleFIN: a single access_url reads the whole
+# bridge). Admin-only remains correct.
+#
+# The default is :tenant_wide, so a provider that has not been classified stays
+# admin-only. Opening a provider up must be a deliberate declaration, never an
+# oversight.
+module ProviderItemOwnable
+ extend ActiveSupport::Concern
+
+ CREDENTIAL_SCOPES = %i[per_connection tenant_wide].freeze
+
+ # Item classes that carry an owner. Listed explicitly rather than discovered,
+ # so it does not depend on autoload order -- add a provider here when wiring
+ # one up. Callers that must sweep ownership across providers (a user changing
+ # families, say) iterate this.
+ OWNED_ITEM_CLASS_NAMES = %w[PlaidItem].freeze
+
+ def self.owned_item_classes
+ OWNED_ITEM_CLASS_NAMES.map(&:constantize)
+ end
+
+ included do
+ class_attribute :declared_credential_scope, instance_writer: false, default: :tenant_wide
+
+ belongs_to :owner, class_name: "User", optional: true
+
+ before_validation :assign_default_owner, if: -> { owner_id.blank? }
+ validate :owner_belongs_to_family, if: -> { owner_id.present? && family_id.present? }
+
+ scope :owned_by, ->(user) { where(owner_id: user&.id) }
+ end
+
+ class_methods do
+ # Declares how far this provider's credential reaches. See the module docs.
+ def credential_scope(scope)
+ scope = scope.to_sym
+ unless CREDENTIAL_SCOPES.include?(scope)
+ raise ArgumentError, "unknown credential scope #{scope.inspect} (expected one of #{CREDENTIAL_SCOPES.inspect})"
+ end
+
+ self.declared_credential_scope = scope
+ end
+
+ # May a non-admin member create one of these?
+ def member_connectable?
+ declared_credential_scope == :per_connection
+ end
+ end
+
+ def owned_by?(user)
+ user.present? && owner_id == user.id
+ end
+
+ # Admins keep full oversight of every connection in the family -- this change
+ # is purely additive. A member may only manage a connection they own, and
+ # only for a provider whose credential is scoped to that connection.
+ def manageable_by?(user)
+ return false if user.blank?
+ return true if user.admin?
+
+ # `user.member?` is re-checked rather than trusting ownership alone: a role
+ # can change under an existing owner (Admin::UsersController#update edits it
+ # in place), and a user demoted to guest must lose manage rights on a
+ # connection they added while they were a member.
+ self.class.member_connectable? && owned_by?(user) && user.member?
+ end
+
+ private
+ # Mirrors Account#assign_default_owner. Items are usually created in a
+ # request (so Current.user is the connector), but the fallback matters for
+ # backfills and console work.
+ def assign_default_owner
+ return if owner.present?
+
+ self.owner =
+ if Current.user.present? && Current.user.family_id == family_id
+ Current.user
+ else
+ family&.users&.where(role: "admin")&.order(:created_at, :id)&.first ||
+ family&.users&.where(role: "super_admin")&.order(:created_at, :id)&.first
+ end
+ end
+
+ def owner_belongs_to_family
+ return if owner.blank?
+
+ errors.add(:owner, :invalid) unless owner.family_id == family_id
+ end
+end
diff --git a/app/models/family/plaid_connectable.rb b/app/models/family/plaid_connectable.rb
index bb37900720..4512d30629 100644
--- a/app/models/family/plaid_connectable.rb
+++ b/app/models/family/plaid_connectable.rb
@@ -21,7 +21,8 @@ module Family::PlaidConnectable
name: item_name,
plaid_id: public_token_response.item_id,
access_token: public_token_response.access_token,
- plaid_region: region
+ plaid_region: region,
+ owner: Current.user
)
plaid_item.sync_later
diff --git a/app/models/invitation.rb b/app/models/invitation.rb
index 59b10d1154..de5a1c5728 100644
--- a/app/models/invitation.rb
+++ b/app/models/invitation.rb
@@ -36,6 +36,7 @@ class Invitation < ApplicationRecord
return false if would_orphan_owned_accounts?(user)
transaction do
+ release_provider_item_ownership(user)
user.update!(family_id: family_id, role: role.to_s)
update!(accepted_at: Time.current)
family.auto_share_existing_accounts_with(user)
@@ -43,6 +44,23 @@ class Invitation < ApplicationRecord
true
end
+ # would_orphan_owned_accounts? blocks the move when the user owns accounts
+ # that would be left behind, but a provider item can be owned without owning
+ # any account (it may have generated none yet, or its accounts belong to
+ # someone else). Such an item keeps its old family_id while its owner leaves,
+ # and the next save fails ProviderItemOwnable's same-family validation --
+ # which would leave the connection unsyncable. Release ownership instead: the
+ # item reverts to admin-managed, exactly as before ownership existed.
+ def release_provider_item_ownership(user)
+ return if user.family_id.blank? || user.family_id == family_id
+
+ ProviderItemOwnable.owned_item_classes.each do |item_class|
+ item_class.where(owner_id: user.id)
+ .where.not(family_id: family_id)
+ .update_all(owner_id: nil, updated_at: Time.current)
+ end
+ end
+
def would_orphan_owned_accounts?(user)
return false if user.blank?
return false if user.family_id.blank?
diff --git a/app/models/plaid_account/processor.rb b/app/models/plaid_account/processor.rb
index 35279040fc..c8e04115fd 100644
--- a/app/models/plaid_account/processor.rb
+++ b/app/models/plaid_account/processor.rb
@@ -41,7 +41,12 @@ class PlaidAccount::Processor
# Initialize new account if not found
if account.nil?
- account = family.accounts.new
+ # Accounts are created here, inside the sync job, where Current.user
+ # is nil -- so Account#assign_default_owner would fall back to the
+ # family's first admin and silently hand a member's own connection to
+ # someone else. Seed the owner from the item that produced it, before
+ # the enrich_attributes calls below run validations.
+ account = family.accounts.new(owner: plaid_account.plaid_item&.owner)
account.accountable = map_accountable(plaid_account.plaid_type)
end
diff --git a/app/models/plaid_item.rb b/app/models/plaid_item.rb
index 14191302c1..2e3a985e0d 100644
--- a/app/models/plaid_item.rb
+++ b/app/models/plaid_item.rb
@@ -1,5 +1,10 @@
class PlaidItem < ApplicationRecord
- include Syncable, Provided, Encryptable, DestroyableLater
+ include Syncable, Provided, Encryptable, DestroyableLater, ProviderItemOwnable
+
+ # A Plaid access_token only covers the institution the user authenticated
+ # to through Link, so a household member may connect their own bank without
+ # gaining any visibility into anyone else's connections.
+ credential_scope :per_connection
enum :plaid_region, { us: "us", eu: "eu" }
enum :status, { good: "good", requires_update: "requires_update" }, default: :good
diff --git a/app/models/provider/base.rb b/app/models/provider/base.rb
index 37f63577a6..20bf2b3265 100644
--- a/app/models/provider/base.rb
+++ b/app/models/provider/base.rb
@@ -48,10 +48,27 @@ class Provider::Base
# - can_connect: Boolean, whether family can connect to this provider
# - new_account_path: Proc that generates path for new account flow
# - existing_account_path: Proc that generates path for linking existing account
+ # - member_connectable: Boolean, whether a non-admin member may connect it
def self.connection_configs(family:)
[]
end
+ # The provider item class that represents a connection for this adapter, if
+ # the provider has one. Used to read the item's declared credential scope.
+ # @return [Class, nil]
+ def self.connection_item_class
+ nil
+ end
+
+ # May a non-admin household member create one of these connections? False
+ # unless the item class has declared `credential_scope :per_connection`, so
+ # an unclassified provider stays admin-only.
+ # @return [Boolean]
+ def self.member_connectable?
+ klass = connection_item_class
+ klass.respond_to?(:member_connectable?) && klass.member_connectable?
+ end
+
# Returns the provider type (class name)
# @return [String] The provider account class name
def provider_type
diff --git a/app/models/provider/plaid_adapter.rb b/app/models/provider/plaid_adapter.rb
index f75c5d97f6..f147d7e380 100644
--- a/app/models/provider/plaid_adapter.rb
+++ b/app/models/provider/plaid_adapter.rb
@@ -17,6 +17,10 @@ class Provider::PlaidAdapter < Provider::Base
# Register this adapter with the factory for ALL PlaidAccount instances
Provider::Factory.register("PlaidAccount", self)
+ def self.connection_item_class
+ PlaidItem
+ end
+
# Define which account types this provider supports (US region)
def self.supported_account_types
%w[Depository CreditCard Loan Investment]
@@ -34,6 +38,7 @@ class Provider::PlaidAdapter < Provider::Base
name: "Plaid",
description: "Connect to your US bank via Plaid",
can_connect: true,
+ member_connectable: member_connectable?,
new_account_path: ->(accountable_type, return_to) {
Rails.application.routes.url_helpers.new_plaid_item_path(
region: "us",
@@ -56,6 +61,7 @@ class Provider::PlaidAdapter < Provider::Base
name: "Plaid (EU)",
description: "Connect to your EU bank via Plaid",
can_connect: true,
+ member_connectable: member_connectable?,
new_account_path: ->(accountable_type, return_to) {
Rails.application.routes.url_helpers.new_plaid_item_path(
region: "eu",
diff --git a/app/models/user.rb b/app/models/user.rb
index 31ea5c4762..1fc5741278 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -383,7 +383,16 @@ class User < ApplicationRecord
AccountStatement.where(account: accounts_to_move).update_all(family_id: new_family.id, updated_at: Time.current) if accounts_to_move.any?
provider_items_to_move.each do |provider_item|
- provider_item.update!(family: new_family)
+ attrs = { family: new_family }
+
+ # provider_items_for_transfer only returns items whose accounts all
+ # belong to this user, so the connection genuinely follows them. Its
+ # owner has to follow too: the previous owner stays behind in the old
+ # family, and ProviderItemOwnable validates that an owner and its item
+ # share a family.
+ attrs[:owner] = self if provider_item.respond_to?(:owner_id)
+
+ provider_item.update!(**attrs)
end
new_family.auto_share_existing_accounts_with(self)
diff --git a/app/views/accounts/new/_method_selector.html.erb b/app/views/accounts/new/_method_selector.html.erb
index 4bc598a9a8..a267c562c9 100644
--- a/app/views/accounts/new/_method_selector.html.erb
+++ b/app/views/accounts/new/_method_selector.html.erb
@@ -18,9 +18,11 @@
<%= icon("chevron-right", size: "sm", class: "ml-auto shrink-0 text-subdued transition-colors group-hover:text-secondary") %>
<% end %>
- <%# Dynamic provider links - only admins can create provider connections %>
- <% if Current.user&.admin? %>
+ <%# Dynamic provider links. Admins may connect anything; a member may only
+ connect providers whose credential is scoped to the single connection
+ they authenticate (see ProviderItemOwnable). %>
<% provider_configs.each do |config| %>
+ <% next unless Current.user&.admin? || config[:member_connectable] %>
<% link_path = config[:new_account_path].call(accountable_type, params[:return_to]) %>
<% is_lunchflow = config[:key] == "lunchflow" %>
@@ -48,7 +50,6 @@
<%= icon("chevron-right", size: "sm", class: "ml-auto shrink-0 text-subdued transition-colors group-hover:text-secondary") %>
<% end %>
<% end %>
- <% end %>
</div>
<% end %>
diff --git a/app/views/plaid_items/_plaid_item.html.erb b/app/views/plaid_items/_plaid_item.html.erb
index 9e6a7badcb..5860b7349d 100644
--- a/app/views/plaid_items/_plaid_item.html.erb
+++ b/app/views/plaid_items/_plaid_item.html.erb
@@ -40,7 +40,7 @@
</div>
</div>
- <% if Current.user&.admin? %>
+ <% if plaid_item.manageable_by?(Current.user) %>
<div class="flex items-center gap-2">
<% if plaid_item.requires_update? %>
<%= render DS::Link.new(
@@ -83,6 +83,13 @@
<% unless plaid_item.scheduled_for_deletion? %>
<div class="space-y-4 mt-4">
+ <%# NOTE: no per-viewer filtering here. This partial is also rendered
+ by PlaidItem::SyncCompleteEvent from the sync job, where
+ Current.user is nil (same gotcha as accounts/_sync_controls), so a
+ viewer-dependent filter would empty the list for everyone on every
+ broadcast. Visibility is decided in AccountsController#visible_provider_items
+ instead, which only shows an owner a card whose accounts they can
+ already see. %>
<% if plaid_item.accounts.any? %>
<%= render "accounts/index/account_groups", accounts: plaid_item.accounts %>
<% end %>
diff --git a/config/locales/views/shared/en.yml b/config/locales/views/shared/en.yml
index 661bb4c8fb..9bfbfa10af 100644
--- a/config/locales/views/shared/en.yml
+++ b/config/locales/views/shared/en.yml
@@ -25,6 +25,7 @@ en:
syncing_notice:
syncing: Syncing accounts data...
require_admin: "Only admins can perform this action"
+ require_connector_owner: "You can only manage connections you added"
custom_confirm:
default_title: "Are you sure?"
default_body: "This is not reversible."
diff --git a/db/migrate/20260916220129_add_owner_to_plaid_items.rb b/db/migrate/20260916220129_add_owner_to_plaid_items.rb
new file mode 100644
index 0000000000..0508d84935
--- /dev/null
+++ b/db/migrate/20260916220129_add_owner_to_plaid_items.rb
@@ -0,0 +1,11 @@
+class AddOwnerToPlaidItems < ActiveRecord::Migration[8.1]
+ def change
+ # Nullable and not backfilled on purpose: an item with no owner is
+ # manageable by admins only, which is exactly the behaviour every existing
+ # connection has today. Ownership is stamped going forward, and
+ # ProviderItemOwnable#assign_default_owner fills in a sensible default the
+ # next time an older item is saved.
+ add_reference :plaid_items, :owner, type: :uuid, null: true, index: true
+ add_foreign_key :plaid_items, :users, column: :owner_id, on_delete: :nullify
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 26bda9969b..40ae8b50ef 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_09_14_200000) do
+ActiveRecord::Schema[8.1].define(version: 2026_09_16_220129) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -1741,6 +1741,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_14_200000) do
t.string "institution_url"
t.string "name"
t.string "next_cursor"
+ t.uuid "owner_id"
t.string "plaid_id", null: false
t.string "plaid_region", default: "us", null: false
t.jsonb "raw_institution_payload", default: {}
@@ -1749,6 +1750,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_14_200000) do
t.string "status", default: "good", null: false
t.datetime "updated_at", null: false
t.index ["family_id"], name: "index_plaid_items_on_family_id"
+ t.index ["owner_id"], name: "index_plaid_items_on_owner_id"
t.index ["plaid_id"], name: "index_plaid_items_on_plaid_id", unique: true
end
@@ -2821,6 +2823,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_14_200000) do
add_foreign_key "onchain_wallet_items", "families"
add_foreign_key "plaid_accounts", "plaid_items"
add_foreign_key "plaid_items", "families"
+ add_foreign_key "plaid_items", "users", column: "owner_id", on_delete: :nullify
add_foreign_key "push_subscriptions", "users"
add_foreign_key "questrade_accounts", "questrade_items"
add_foreign_key "questrade_items", "families"
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index 43a5f8a3db..3f53fb3c3a 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -789,6 +789,96 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
ActionView::Base.logger = original_view_logger
Rails.logger = original_rails_logger
end
+
+ # --- member-owned connections (issue #3579) ------------------------------
+
+ test "an owner is not shown a connection carrying an account they cannot see" do
+ # Ownership must not widen exposure: the card renders the item's accounts
+ # unfiltered (and is re-rendered by a viewer-less broadcast), so the whole
+ # card is withheld rather than shown with a filtered list.
+ member = users(:family_member)
+ family = families(:dylan_family)
+ item = PlaidItem.create!(
+ family: family, plaid_id: "item_card_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Owned Bank", owner: member
+ )
+ hidden = Account.create!(
+ family: family, owner: users(:family_admin), name: "Not Shared With Member",
+ balance: 100, currency: "USD", accountable: Depository.new
+ )
+ hidden.account_shares.destroy_all
+ plaid_account = PlaidAccount.create!(
+ plaid_item: item, name: "Hidden Feed", plaid_id: "acct_card_#{SecureRandom.hex(4)}",
+ plaid_type: "depository", plaid_subtype: "checking", currency: "USD",
+ current_balance: 100, available_balance: 100
+ )
+ AccountProvider.create!(account: hidden, provider: plaid_account)
+
+ sign_in member
+ get accounts_url
+
+ assert_response :success
+ assert_select "##{ActionView::RecordIdentifier.dom_id(item)}", count: 0
+ assert_no_match(/Not Shared With Member/, response.body)
+ end
+
+ test "an owner is shown their freshly connected item before it has any accounts" do
+ # The case ownership visibility exists for: just connected, nothing synced.
+ member = users(:family_member)
+ item = PlaidItem.create!(
+ family: families(:dylan_family), plaid_id: "item_fresh_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Fresh Bank", owner: member
+ )
+
+ sign_in member
+ get accounts_url
+
+ assert_response :success
+ assert_select "##{ActionView::RecordIdentifier.dom_id(item)}", count: 1
+ end
+
+
+ test "an owner sees the management controls on their own connection card" do
+ member = users(:family_member)
+ item = PlaidItem.create!(
+ family: families(:dylan_family), plaid_id: "item_ctrl_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Controls Bank", owner: member
+ )
+
+ sign_in member
+ get accounts_url
+
+ assert_response :success
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 1
+ end
+
+ test "a member demoted to guest loses the controls on a connection they own" do
+ member = users(:family_member)
+ item = PlaidItem.create!(
+ family: families(:dylan_family), plaid_id: "item_demote_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Demoted Bank", owner: member
+ )
+ member.update!(role: :guest)
+
+ sign_in member
+ get accounts_url
+
+ assert_response :success
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
+ end
+
+ test "a member sees no controls on a connection someone else owns" do
+ item = PlaidItem.create!(
+ family: families(:dylan_family), plaid_id: "item_noctrl_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Admin Bank", owner: users(:family_admin)
+ )
+
+ sign_in users(:family_member)
+ get accounts_url
+
+ assert_response :success
+ assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
+ end
end
class AccountsControllerSimplefinCtaTest < ActionDispatch::IntegrationTest
diff --git a/test/controllers/depositories_controller_test.rb b/test/controllers/depositories_controller_test.rb
index 192823a48d..d340d2c16b 100644
--- a/test/controllers/depositories_controller_test.rb
+++ b/test/controllers/depositories_controller_test.rb
@@ -65,4 +65,44 @@ class DepositoriesControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "input[name='account[enable_category_matcher]']", 0
end
+
+ # --- member-owned connections (issue #3579) ------------------------------
+
+ test "a member sees only member-connectable providers in the method selector" do
+ Provider::Registry.stubs(:plaid_provider_for_region).returns(stub("plaid"))
+ Family.any_instance.stubs(:can_connect_plaid_us?).returns(true)
+ Family.any_instance.stubs(:can_connect_plaid_eu?).returns(false)
+
+ sign_in users(:family_member)
+ get new_depository_path(step: "method_select")
+
+ assert_response :success
+ assert_select "a[href=?]", new_plaid_item_path(region: "us", accountable_type: "Depository"), count: 1
+ # SimpleFIN is tenant-wide, so it must not be offered to a member even
+ # when it is configured.
+ assert_select "a[href*=?]", "simplefin", count: 0
+ end
+
+ test "an admin still sees every configured provider in the method selector" do
+ Provider::Registry.stubs(:plaid_provider_for_region).returns(stub("plaid"))
+ Family.any_instance.stubs(:can_connect_plaid_us?).returns(true)
+ Family.any_instance.stubs(:can_connect_plaid_eu?).returns(false)
+
+ sign_in users(:family_admin)
+ get new_depository_path(step: "method_select")
+
+ assert_response :success
+ assert_select "a[href=?]", new_plaid_item_path(region: "us", accountable_type: "Depository"), count: 1
+ end
+
+ test "a member is offered manual entry even with no connectable providers" do
+ Family.any_instance.stubs(:can_connect_plaid_us?).returns(false)
+ Family.any_instance.stubs(:can_connect_plaid_eu?).returns(false)
+
+ sign_in users(:family_member)
+ get new_depository_path(step: "method_select")
+
+ assert_response :success
+ assert_select "a[href=?]", new_depository_path, count: 1
+ end
end
diff --git a/test/controllers/plaid_items_controller_test.rb b/test/controllers/plaid_items_controller_test.rb
index 8084038c7c..5b8e022795 100644
--- a/test/controllers/plaid_items_controller_test.rb
+++ b/test/controllers/plaid_items_controller_test.rb
@@ -166,4 +166,160 @@ class PlaidItemsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to accounts_path
assert_equal "Account successfully linked to Plaid", flash[:notice]
end
+
+ # --- member-owned connections (issue #3579) ------------------------------
+ #
+ # Plaid declares `credential_scope :per_connection`, so a household member
+ # may connect their own bank. Admin behaviour is unchanged: an admin still
+ # sees and manages every connection in the family.
+
+ test "a member may open the Plaid link flow" do
+ sign_in users(:family_member)
+ plaid_provider = mock
+ Provider::Registry.stubs(:plaid_provider_for_region).with(:us).returns(plaid_provider)
+ plaid_provider.expects(:get_link_token).returns(OpenStruct.new(link_token: "link-token-member"))
+
+ get new_plaid_item_url
+
+ assert_response :success
+ end
+
+ test "a guest may not open the Plaid link flow" do
+ guest = users(:family_member)
+ guest.update!(role: :guest)
+ sign_in guest
+
+ get new_plaid_item_url
+
+ assert_redirected_to accounts_path
+ assert_equal I18n.t("shared.require_connector_owner"), flash[:alert]
+ end
+
+ test "a member who creates an item becomes its owner" do
+ member = users(:family_member)
+ sign_in member
+
+ plaid_provider = mock
+ Provider::Registry.expects(:plaid_provider_for_region).with("us").returns(plaid_provider)
+ plaid_provider.expects(:exchange_public_token).returns(
+ OpenStruct.new(access_token: "access-sandbox-member", item_id: "item-sandbox-member")
+ )
+
+ post plaid_items_url, params: {
+ plaid_item: {
+ public_token: "public-sandbox-member",
+ region: "us",
+ metadata: { institution: { name: "Member Bank" } }
+ }
+ }
+
+ assert_equal member, PlaidItem.order(:created_at).last.owner
+ end
+
+ test "a member may destroy a connection they own" do
+ member = users(:family_member)
+ plaid_items(:one).update!(owner: member)
+ sign_in member
+
+ delete plaid_item_url(plaid_items(:one))
+
+ assert_enqueued_with job: DestroyJob
+ assert_redirected_to accounts_path
+ end
+
+ test "a member may not destroy a connection owned by someone else" do
+ plaid_items(:one).update!(owner: users(:family_admin))
+ sign_in users(:family_member)
+
+ assert_no_enqueued_jobs only: DestroyJob do
+ delete plaid_item_url(plaid_items(:one))
+ end
+
+ assert_redirected_to accounts_path
+ assert_equal I18n.t("shared.require_connector_owner"), flash[:alert]
+ end
+
+ test "a member may not sync a connection owned by someone else" do
+ plaid_items(:one).update!(owner: users(:family_admin))
+ sign_in users(:family_member)
+ PlaidItem.any_instance.expects(:sync_later_with_provider_refresh).never
+
+ post sync_plaid_item_url(plaid_items(:one))
+
+ assert_redirected_to accounts_path
+ end
+
+ test "an admin may still manage a connection a member owns" do
+ plaid_items(:one).update!(owner: users(:family_member))
+ sign_in users(:family_admin)
+ PlaidItem.any_instance.expects(:sync_later_with_provider_refresh).once
+
+ post sync_plaid_item_url(plaid_items(:one))
+
+ assert_redirected_to accounts_path
+ end
+
+ test "a member may not link an account to a connection someone else owns" do
+ plaid_items(:one).update!(owner: users(:family_admin))
+ member = users(:family_member)
+ account = Account.create!(
+ family: families(:dylan_family), owner: member, name: "Member Checking",
+ balance: 100, currency: "USD", accountable: Depository.new
+ )
+ plaid_account = PlaidAccount.create!(
+ plaid_item: plaid_items(:one), name: "Not Theirs", plaid_id: "acct_not_theirs",
+ plaid_type: "depository", plaid_subtype: "checking", currency: "USD",
+ current_balance: 100, available_balance: 100
+ )
+ sign_in member
+
+ assert_no_difference "AccountProvider.count" do
+ post link_existing_account_plaid_items_url, params: {
+ account_id: account.id, plaid_account_id: plaid_account.id
+ }
+ end
+
+ assert_redirected_to account_path(account)
+ end
+
+ test "a member may not attach their own connection to an account they cannot write" do
+ member = users(:family_member)
+ plaid_items(:one).update!(owner: member)
+ other_account = Account.create!(
+ family: families(:dylan_family), owner: users(:family_admin),
+ name: "Admin Only Checking", balance: 100, currency: "USD", accountable: Depository.new
+ )
+ plaid_account = PlaidAccount.create!(
+ plaid_item: plaid_items(:one), name: "Theirs", plaid_id: "acct_theirs",
+ plaid_type: "depository", plaid_subtype: "checking", currency: "USD",
+ current_balance: 100, available_balance: 100
+ )
+ sign_in member
+
+ assert_no_difference "AccountProvider.count" do
+ post link_existing_account_plaid_items_url, params: {
+ account_id: other_account.id, plaid_account_id: plaid_account.id
+ }
+ end
+ end
+
+ test "select_existing_account offers a member only the connections they own" do
+ member = users(:family_member)
+ plaid_items(:one).update!(owner: users(:family_admin))
+ account = Account.create!(
+ family: families(:dylan_family), owner: member, name: "Member Savings",
+ balance: 100, currency: "USD", accountable: Depository.new
+ )
+ PlaidAccount.create!(
+ plaid_item: plaid_items(:one), name: "Admin Feed", plaid_id: "acct_admin_feed",
+ plaid_type: "depository", plaid_subtype: "checking", currency: "USD",
+ current_balance: 100, available_balance: 100
+ )
+ sign_in member
+
+ get select_existing_account_plaid_items_url(account_id: account.id, region: "us")
+
+ assert_redirected_to account_path(account)
+ assert_equal "No available Plaid accounts to link. Please connect a new Plaid account first.", flash[:alert]
+ end
end
diff --git a/test/integration/plaid_item_broadcast_render_test.rb b/test/integration/plaid_item_broadcast_render_test.rb
new file mode 100644
index 0000000000..4d955c7636
--- /dev/null
+++ b/test/integration/plaid_item_broadcast_render_test.rb
@@ -0,0 +1,23 @@
+require "test_helper"
+
+class PlaidItemBroadcastRenderTest < ActiveSupport::TestCase
+ # PlaidItem::SyncCompleteEvent#broadcast re-renders this partial from the
+ # sync job, outside any request, so Current.user is nil there. A
+ # viewer-dependent filter in the partial would silently empty the account
+ # list for every family member on every completed sync.
+ test "the connection card still renders its accounts with no current user" do
+ item = plaid_items(:one)
+ account = item.accounts.first
+ assert account.present?, "fixture item needs at least one account"
+
+ Current.reset
+ assert_nil Current.user
+
+ html = ApplicationController.render(
+ partial: "plaid_items/plaid_item",
+ locals: { plaid_item: item }
+ )
+
+ assert_includes html, account.name
+ end
+end
diff --git a/test/models/invitation_test.rb b/test/models/invitation_test.rb
index 2217bf04f4..d099d36935 100644
--- a/test/models/invitation_test.rb
+++ b/test/models/invitation_test.rb
@@ -272,4 +272,27 @@ class InvitationTest < ActiveSupport::TestCase
assert invitation.accept_for(user)
end
end
+
+ test "accepting an invitation releases provider items left behind" do
+ # The item's owner is leaving the family but the item stays. Without
+ # releasing it, the orphaned owner fails ProviderItemOwnable's same-family
+ # validation on the next save and the connection becomes unsyncable.
+ user = users(:family_member)
+ old_family = user.family
+ item = PlaidItem.create!(
+ family: old_family, plaid_id: "item_invite_#{SecureRandom.hex(4)}",
+ access_token: "token", name: "Left Behind Bank", owner: user
+ )
+ new_family = Family.create!(name: "Invited Family")
+ invitation = Invitation.create!(
+ family: new_family, email: user.email, role: "member",
+ inviter: users(:family_admin)
+ )
+
+ assert invitation.accept_for(user)
+
+ assert_nil item.reload.owner_id
+ assert_equal old_family, item.family
+ assert item.valid?, "the left-behind item must still be savable"
+ end
end
diff --git a/test/models/plaid_account/processor_test.rb b/test/models/plaid_account/processor_test.rb
index dc7bbca2c8..6a6f48ee2c 100644
--- a/test/models/plaid_account/processor_test.rb
+++ b/test/models/plaid_account/processor_test.rb
@@ -43,6 +43,26 @@ class PlaidAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal "PlaidAccount", account.account_providers.first.provider_type
end
+ test "a new account inherits the owner of the item that produced it" do
+ # Accounts are created inside the sync job, where Current.user is nil. If
+ # the owner were left to Account#assign_default_owner it would fall back to
+ # the family's first admin, quietly taking a member's own connection away
+ # from them (issue #3579).
+ Account.destroy_all
+ member = users(:family_member)
+ @plaid_account.plaid_item.update!(owner: member)
+
+ expect_default_subprocessor_calls
+
+ Current.reset
+
+ assert_difference "Account.count" do
+ PlaidAccount::Processor.new(@plaid_account).process
+ end
+
+ assert_equal member, Account.order(created_at: :desc).first.owner
+ end
+
test "processing is idempotent with updates and enrichments" do
expect_default_subprocessor_calls
diff --git a/test/models/provider/member_connectable_test.rb b/test/models/provider/member_connectable_test.rb
new file mode 100644
index 0000000000..c76e62a6a5
--- /dev/null
+++ b/test/models/provider/member_connectable_test.rb
@@ -0,0 +1,42 @@
+require "test_helper"
+
+class Provider::MemberConnectableTest < ActiveSupport::TestCase
+ test "Plaid is member connectable" do
+ assert Provider::PlaidAdapter.member_connectable?
+ assert_equal PlaidItem, Provider::PlaidAdapter.connection_item_class
+ end
+
+ test "SimpleFIN is not member connectable" do
+ # One access_url reads every account on the bridge, so it is tenant-wide
+ # and stays admin-only.
+ assert_not Provider::SimplefinAdapter.member_connectable?
+ end
+
+ test "an adapter that declares no item class is not member connectable" do
+ # The fail-closed default: every provider that has not been classified
+ # behaves exactly as it does today.
+ assert_nil Provider::Base.connection_item_class
+ assert_not Provider::Base.member_connectable?
+ end
+
+ test "no adapter is member connectable without declaring per_connection" do
+ Provider::Factory.registered_adapters.each do |adapter|
+ next unless adapter.member_connectable?
+
+ item_class = adapter.connection_item_class
+ assert_equal :per_connection, item_class.declared_credential_scope,
+ "#{adapter.name} is member-connectable but #{item_class} does not declare per_connection"
+ end
+ end
+
+ test "plaid connection configs carry the member_connectable flag" do
+ family = families(:dylan_family)
+ family.stubs(:can_connect_plaid_us?).returns(true)
+ family.stubs(:can_connect_plaid_eu?).returns(false)
+
+ configs = Provider::PlaidAdapter.connection_configs(family: family)
+
+ assert configs.any?, "expected at least one Plaid connection config"
+ assert configs.all? { |config| config[:member_connectable] }
+ end
+end
diff --git a/test/models/provider_item_ownable_test.rb b/test/models/provider_item_ownable_test.rb
new file mode 100644
index 0000000000..717cae40c8
--- /dev/null
+++ b/test/models/provider_item_ownable_test.rb
@@ -0,0 +1,95 @@
+require "test_helper"
+
+class ProviderItemOwnableTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @admin = users(:family_admin)
+ @member = users(:family_member)
+ Current.reset
+ end
+
+ teardown { Current.reset }
+
+ # An anonymous model that includes the concern without declaring a scope,
+ # standing in for any of the 24 providers that have not been classified yet.
+ def undeclared_item_class
+ Class.new(ApplicationRecord) do
+ self.table_name = "plaid_items"
+ belongs_to :family
+ include ProviderItemOwnable
+
+ def self.name = "UndeclaredItem"
+ end
+ end
+
+ test "credential scope defaults to tenant_wide so an unclassified provider stays admin-only" do
+ klass = undeclared_item_class
+
+ assert_equal :tenant_wide, klass.declared_credential_scope
+ assert_not klass.member_connectable?
+ end
+
+ test "credential scope rejects an unknown value" do
+ error = assert_raises(ArgumentError) { undeclared_item_class.credential_scope(:sometimes) }
+ assert_match(/unknown credential scope/, error.message)
+ end
+
+ test "PlaidItem declares per_connection" do
+ assert_equal :per_connection, PlaidItem.declared_credential_scope
+ assert PlaidItem.member_connectable?
+ end
+
+ test "owner defaults to the current user" do
+ Current.session = @member.sessions.create!
+
+ item = @family.plaid_items.create!(
+ name: "Member Bank", plaid_id: "item_owner_default", access_token: "token_owner_default"
+ )
+
+ assert_equal @member, item.owner
+ end
+
+ test "owner falls back to a family admin when there is no current user" do
+ item = @family.plaid_items.create!(
+ name: "Console Bank", plaid_id: "item_owner_fallback", access_token: "token_owner_fallback"
+ )
+
+ assert_equal @admin, item.owner
+ end
+
+ test "owner must belong to the same family" do
+ outsider = users(:empty)
+
+ item = @family.plaid_items.new(
+ name: "Cross Family", plaid_id: "item_cross", access_token: "token_cross", owner: outsider
+ )
+
+ assert_not item.valid?
+ assert_includes item.errors[:owner], "is invalid"
+ end
+
+ test "an admin may manage any connection in the family" do
+ item = plaid_items(:one)
+ item.update!(owner: @member)
+
+ assert item.manageable_by?(@admin)
+ end
+
+ test "a member may manage a per_connection item they own" do
+ item = plaid_items(:one)
+ item.update!(owner: @member)
+
+ assert item.manageable_by?(@member)
+ end
+
+ test "a member may not manage a connection owned by someone else" do
+ item = plaid_items(:one)
+ item.update!(owner: @admin)
+
+ assert_not item.manageable_by?(@member)
+ end
+
+ test "manageable_by? is false without a user" do
+ assert_not plaid_items(:one).manageable_by?(nil)
+ end
+end
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index a16e1a0660..8cc7b95651 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -718,6 +718,10 @@ class UserTest < ActiveSupport::TestCase
assert_equal new_family, account.reload.family
assert_equal new_family, plaid_item.reload.family
assert_equal new_family, statement.reload.family
+
+ # The connection's owner has to follow it across, or it would be left
+ # pointing at a user in the family it just left.
+ assert_equal user, plaid_item.owner
end
test "transfer_to_family! rejects provider items linked to accounts outside the transfer" do