The personal finance app for everyone (by everyone)
Ruby
Share family accounts with invited members on every sign-up path (#2650)
Josh97391a27bad0
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex c92e80334b..6332f65f38 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -214,17 +214,41 @@ module Apiuser.role = User.role_for_new_family_creator(fallback_role: provider_default_role || :admin)end- if user.save- # Mark invitation as accepted if one was used- invitation&.update!(accepted_at: Time.current)+ identity = nil+ account_created = false- OidcIdentity.create_from_omniauth(build_omniauth_hash(cached), user)+ begin+ account_created = ActiveRecord::Base.transaction do+ unless user.save+ raise ActiveRecord::Rollback+ end- SsoAuditLog.log_jit_account_created!(- user: user,- provider: cached[:provider],- request: request- )+ # Mark invitation as accepted if one was used+ invitation&.update!(accepted_at: Time.current)++ # Joining an existing family via invitation must honor the family's+ # default sharing policy, matching Invitation#accept_for, so a mobile+ # SSO invitee sees the accounts the family shares by default.+ user.family.auto_share_existing_accounts_with(user) if invitation.present?++ identity = OidcIdentity.create_from_omniauth(build_omniauth_hash(cached), user)+ true+ end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e+ # Expected persistence failures (e.g. a duplicate identity) roll the+ # whole onboarding back and return the error response. Unexpected+ # errors propagate so they surface instead of being hidden.+ user.errors.add(:base, e.message)+ end++ if account_created+ if identity&.persisted?+ SsoAuditLog.log_jit_account_created!(+ user: user,+ provider: cached[:provider],+ request: request+ )+ endissue_mobile_tokens(user, cached[:device_info])elsediff --git a/app/controllers/oidc_accounts_controller.rb b/app/controllers/oidc_accounts_controller.rbindex a0e31e7a4b..6e26e5e3ae 100644--- a/app/controllers/oidc_accounts_controller.rb+++ b/app/controllers/oidc_accounts_controller.rb@@ -136,15 +136,41 @@ class OidcAccountsController < ApplicationController@user.role = User.role_for_new_family_creator(fallback_role: provider_default_role || :admin)end- if @user.save- # Create the OIDC (or other SSO) identity- identity = OidcIdentity.create_from_omniauth(- build_auth_hash(@pending_auth),- @user- )+ identity = nil+ account_created = false++ begin+ account_created = ActiveRecord::Base.transaction do+ unless @user.save+ raise ActiveRecord::Rollback+ end++ # Mark invitation as accepted if one was used+ invitation&.update!(accepted_at: Time.current)++ # Joining an existing family via invitation must honor the family's+ # default sharing policy, matching Invitation#accept_for. Without this a+ # JIT SSO invitee lands in the family but sees none of its accounts.+ @user.family.auto_share_existing_accounts_with(@user) if invitation.present?+ # Create the OIDC (or other SSO) identity+ identity = OidcIdentity.create_from_omniauth(+ build_auth_hash(@pending_auth),+ @user+ )++ true+ end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e+ # Expected persistence failures (e.g. a duplicate identity) roll the whole+ # onboarding back and re-render the form. Unexpected errors propagate so+ # they surface instead of being hidden as a form validation message.+ @user.errors.add(:base, e.message)+ end++ if account_created# Only log JIT account creation if identity was successfully created- if identity.persisted?+ if identity&.persisted?SsoAuditLog.log_jit_account_created!(user: @user,provider: @pending_auth["provider"],@@ -152,9 +178,6 @@ class OidcAccountsController < ApplicationController)end- # Mark invitation as accepted if one was used- invitation&.update!(accepted_at: Time.current)-# Clear pending auth from sessionsession.delete(:pending_oidc_auth)diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rbindex 5da04aaf37..14cdc48516 100644--- a/app/controllers/registrations_controller.rb+++ b/app/controllers/registrations_controller.rb@@ -73,6 +73,9 @@ class RegistrationsController < ApplicationControllerend@invitation&.update!(accepted_at: Time.current)+ # Joining an existing family must honor the family's default sharing+ # policy so the user sees the accounts the family shares.+ @user.family.auto_share_existing_accounts_with(@user)@session = create_session_for(@user)success = trueenddiff --git a/app/models/account.rb b/app/models/account.rbindex ebedd279fd..5392d0fdeb 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -609,8 +609,12 @@ class Account < ApplicationRecordenddef auto_share_with_family!- records = family.users.where.not(id: owner_id).pluck(:id).map do |user_id|- { account_id: id, user_id: user_id, permission: "read_write",+ # Guests get read_only, everyone else read_write. This mirrors+ # Family#auto_share_existing_accounts_with so a guest's permission on an+ # account is the same whether they joined before or after it was created.+ records = family.users.where.not(id: owner_id).pluck(:id, :role).map do |user_id, role|+ { account_id: id, user_id: user_id,+ permission: role == "guest" ? "read_only" : "read_write",include_in_finances: true, created_at: Time.current, updated_at: Time.current }enddiff --git a/app/models/family.rb b/app/models/family.rbindex 0645c6670c..afa6d40122 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -176,6 +176,33 @@ class Family < ApplicationRecorddefault_account_sharing == "shared"end+ # Shares every existing account in this family (except ones the user already+ # owns) with the given user, honoring the family's default sharing policy and+ # the user's role. Guests receive read_only; members/admins receive read_write.+ #+ # This is the single entry point for "a member just joined, give them the+ # accounts the family shares by default." It self-guards on the sharing policy+ # and family membership so every membership path (invitation accept, SSO JIT+ # sign-up, token registration, mobile SSO) can call it without reintroducing+ # the "member joined but sees nothing" bug. No-op when sharing is disabled or+ # there is nothing to share, and idempotent on re-run.+ def auto_share_existing_accounts_with(user)+ return unless share_all_by_default?+ # Load-bearing security guard: insert_all below bypasses AccountShare's+ # user_in_same_family / cannot_share_with_owner validations, so this+ # membership check is the ONLY thing preventing cross-family sharing.+ # Do not drop it when refactoring.+ return unless user&.persisted? && user.family_id == id++ permission = user.guest? ? "read_only" : "read_write"+ records = accounts.where.not(owner_id: user.id).pluck(:id).map do |account_id|+ { account_id: account_id, user_id: user.id, permission: permission,+ include_in_finances: true, created_at: Time.current, updated_at: Time.current }+ end++ AccountShare.insert_all(records, unique_by: %i[account_id user_id]) if records.any?+ end+def uses_custom_month_start?month_start_day != 1enddiff --git a/app/models/invitation.rb b/app/models/invitation.rbindex 35e59d15a7..59b10d1154 100644--- a/app/models/invitation.rb+++ b/app/models/invitation.rb@@ -38,7 +38,7 @@ class Invitation < ApplicationRecordtransaction douser.update!(family_id: family_id, role: role.to_s)update!(accepted_at: Time.current)- auto_share_existing_accounts(user) if family.share_all_by_default?+ family.auto_share_existing_accounts_with(user)endtrueend@@ -129,13 +129,4 @@ class Invitation < ApplicationRecorddef inviter_is_admininviter.admin?end-- def auto_share_existing_accounts(user)- records = family.accounts.where.not(owner_id: user.id).pluck(:id).map do |account_id|- { account_id: account_id, user_id: user.id, permission: "read_write",- include_in_finances: true, created_at: Time.current, updated_at: Time.current }- end-- AccountShare.insert_all(records, unique_by: %i[account_id user_id]) if records.any?- endenddiff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex 9760c22dcc..a091c4eee7 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -784,6 +784,33 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert response_data["errors"].any? { |e| e.match?(/email/i) }, "Expected email validation error in: #{response_data["errors"]}"end+ test "sso_create_account rolls back user when OIDC identity creation fails" do+ email = "[email protected]"+ linking_code = SecureRandom.urlsafe_base64(32)+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "google_oauth2",+ uid: "google-uid-rollback",+ email: email,+ first_name: "Mobile",+ last_name: "Rollback",+ name: "Mobile Rollback",+ device_info: @device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)+ OidcIdentity.stubs(:create_from_omniauth).raises(ActiveRecord::RecordNotUnique, "duplicate identity")++ assert_no_difference([ "User.count", "OidcIdentity.count", "Family.count" ]) do+ post "/api/v1/auth/sso_create_account", params: {+ linking_code: linking_code,+ first_name: "Mobile",+ last_name: "Rollback"+ }+ end++ assert_response :unprocessable_entity+ assert_nil User.find_by(email: email)+ end+test "sso_create_account linking_code single-use under race" dolinking_code = SecureRandom.urlsafe_base64(32)Rails.cache.write("mobile_sso_link:#{linking_code}", {@@ -837,4 +864,71 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_equal "AI is not available for your account", response_data["error"]assert_not user.reload.ai_enabledend++ test "mobile SSO onboarding via invitation shares existing family accounts when family shares by default" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ invitation = family.invitations.create!(+ email: "[email protected]", role: "member", inviter: users(:family_admin)+ )++ linking_code = SecureRandom.urlsafe_base64(32)+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "openid_connect",+ uid: "mobile-invite-uid-1",+ email: invitation.email,+ first_name: "Mobile",+ last_name: "Invitee",+ name: "Mobile Invitee",+ device_info: @device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)++ assert_difference("User.count", 1) do+ post "/api/v1/auth/sso_create_account", params: {+ linking_code: linking_code,+ first_name: "Mobile",+ last_name: "Invitee"+ }+ end++ assert_response :success+ invitee = User.find_by(email: invitation.email)+ assert_not_nil invitee+ assert_equal family.id, invitee.family_id+ assert_equal family.accounts.pluck(:id).sort,+ AccountShare.where(user: invitee).pluck(:account_id).sort+ end++ test "mobile SSO onboarding via invitation shares nothing when family sharing is private" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "private")+ invitation = family.invitations.create!(+ email: "[email protected]", role: "member", inviter: users(:family_admin)+ )++ linking_code = SecureRandom.urlsafe_base64(32)+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "openid_connect",+ uid: "mobile-private-uid-1",+ email: invitation.email,+ first_name: "Mobile",+ last_name: "Private",+ name: "Mobile Private",+ device_info: @device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)++ post "/api/v1/auth/sso_create_account", params: {+ linking_code: linking_code,+ first_name: "Mobile",+ last_name: "Private"+ }++ assert_response :success+ invitee = User.find_by(email: invitation.email)+ assert_not_nil invitee+ assert_equal family.id, invitee.family_id+ assert_equal 0, AccountShare.where(user: invitee).count+ endenddiff --git a/test/controllers/oidc_accounts_controller_test.rb b/test/controllers/oidc_accounts_controller_test.rbindex a24079931e..9663bc62e8 100644--- a/test/controllers/oidc_accounts_controller_test.rb+++ b/test/controllers/oidc_accounts_controller_test.rb@@ -215,6 +215,22 @@ class OidcAccountsControllerTest < ActionController::TestCaseassert_equal new_user_auth["last_name"], new_user.last_nameend+ test "create_user rolls back user when OIDC identity creation fails" do+ auth = new_user_auth.merge(+ "email" => "[email protected]",+ "uid" => "oidc-rollback-uid"+ )+ session[:pending_oidc_auth] = auth+ OidcIdentity.stubs(:create_from_omniauth).raises(ActiveRecord::RecordNotUnique, "duplicate identity")++ assert_no_difference [ "User.count", "OidcIdentity.count", "Family.count" ] do+ post :create_user+ end++ assert_response :unprocessable_entity+ assert_nil User.find_by(email: auth["email"])+ end+test "should create session after OIDC registration" dosession[:pending_oidc_auth] = new_user_auth@@ -257,4 +273,42 @@ class OidcAccountsControllerTest < ActionController::TestCasepassword: "anypassword"), "SSO-only user should not authenticate with password"end++ test "create_user via invitation shares existing family accounts when family shares by default" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ family.invitations.create!(email: "[email protected]", role: "member", inviter: users(:family_admin))++ session[:pending_oidc_auth] = {+ "provider" => "openid_connect", "uid" => "invite-uid-1",+ "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee"+ }++ post :create_user+ assert_redirected_to root_path++ invitee = User.find_by(email: "[email protected]")+ assert_not_nil invitee+ assert_equal family.id, invitee.family_id+ assert_equal family.accounts.pluck(:id).sort,+ AccountShare.where(user: invitee).pluck(:account_id).sort+ end++ test "create_user via invitation shares nothing when family sharing is private" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "private")+ family.invitations.create!(email: "[email protected]", role: "member", inviter: users(:family_admin))++ session[:pending_oidc_auth] = {+ "provider" => "openid_connect", "uid" => "invite-uid-2",+ "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee"+ }++ post :create_user+ assert_redirected_to root_path++ invitee = User.find_by(email: "[email protected]")+ assert_equal family.id, invitee.family_id+ assert_equal 0, AccountShare.where(user: invitee).count+ endenddiff --git a/test/controllers/registrations_controller_test.rb b/test/controllers/registrations_controller_test.rbindex b9916dea17..fb14a7b48b 100644--- a/test/controllers/registrations_controller_test.rb+++ b/test/controllers/registrations_controller_test.rb@@ -118,4 +118,58 @@ class RegistrationsControllerTest < ActionDispatch::IntegrationTestassert_not created_user.show_ai_sidebar?assert created_user.ai_enabled?end++ test "creating account from invitation shares existing family accounts when family shares by default" do+ invitation = invitations(:one)+ invitation.family.update!(default_account_sharing: "shared")++ post registration_url, params: { user: {+ email: invitation.email,+ password: "Password1!",+ invitation: invitation.token+ } }++ created_user = User.find_by(email: invitation.email)+ assert_not_nil created_user+ assert_equal invitation.family_id, created_user.family_id+ assert_equal invitation.family.accounts.pluck(:id).sort,+ AccountShare.where(user: created_user).pluck(:account_id).sort+ end++ test "creating account in invite-only default family shares existing family accounts" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ Setting.onboarding_state = "invite_only"+ Setting.invite_only_default_family_id = family.id++ assert_difference "User.count", +1 do+ post registration_url, params: { user: {+ email: "[email protected]",+ password: "Password1!"+ } }+ end++ created_user = User.find_by(email: "[email protected]")+ assert_not_nil created_user+ assert_equal family.id, created_user.family_id+ assert_equal "member", created_user.role+ assert_equal family.accounts.pluck(:id).sort,+ AccountShare.where(user: created_user).pluck(:account_id).sort+ assert AccountShare.where(user: created_user).all?(&:read_write?)+ end++ test "creating account from invitation shares nothing when family sharing is private" do+ invitation = invitations(:one)+ invitation.family.update!(default_account_sharing: "private")++ post registration_url, params: { user: {+ email: invitation.email,+ password: "Password1!",+ invitation: invitation.token+ } }++ created_user = User.find_by(email: invitation.email)+ assert_not_nil created_user+ assert_equal 0, AccountShare.where(user: created_user).count+ endenddiff --git a/test/models/account_test.rb b/test/models/account_test.rbindex db36249c60..a65715f547 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -442,6 +442,27 @@ class AccountTest < ActiveSupport::TestCaseassert share.include_in_finances?end+ test "auto_share_with_family grants guests read_only and other members read_write" do+ @family.update!(default_account_sharing: "private")+ guest = users(:empty)+ guest.update_columns(family_id: @family.id, role: "guest")++ account = Account.create_and_sync({+ family: @family,+ owner: @admin,+ name: "Guest Permission Account",+ balance: 100,+ currency: "USD",+ accountable_type: "Depository",+ accountable_attributes: {}+ })++ account.auto_share_with_family!++ assert_equal "read_only", account.account_shares.find_by(user: guest).permission+ assert_equal "read_write", account.account_shares.find_by(user: @member).permission+ end+test "current_holdings prefers latest provider snapshot holdings across currencies" doaccount = @family.accounts.create!(owner: @admin,diff --git a/test/models/family_test.rb b/test/models/family_test.rbindex f026ff6ab6..432a97ffd5 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -234,4 +234,82 @@ class FamilyTest < ActiveSupport::TestCaseassert_equal({ "type" => "financial_document" }, document.metadata)assert_equal "vs_test123", family.reload.vector_store_idend++ # auto_share_existing_accounts_with -----------------------------------------++ test "auto_share_existing_accounts_with shares existing family accounts read_write when sharing is default" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ newcomer = users(:empty)+ newcomer.update_columns(family_id: family.id, role: "member")++ expected_ids = family.accounts.where.not(owner_id: newcomer.id).pluck(:id).sort+ assert expected_ids.any?, "fixture family must have shareable accounts"++ family.auto_share_existing_accounts_with(newcomer)++ shares = AccountShare.where(user: newcomer)+ assert_equal expected_ids, shares.pluck(:account_id).sort+ assert shares.all?(&:read_write?), "shares must grant read_write"+ assert shares.all?(&:include_in_finances?), "shares must be included in finances"+ end++ test "auto_share_existing_accounts_with shares existing family accounts read_only for guests" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ newcomer = users(:empty)+ newcomer.update_columns(family_id: family.id, role: "guest")++ expected_ids = family.accounts.where.not(owner_id: newcomer.id).pluck(:id).sort+ assert expected_ids.any?, "fixture family must have shareable accounts"++ family.auto_share_existing_accounts_with(newcomer)++ shares = AccountShare.where(user: newcomer)+ assert_equal expected_ids, shares.pluck(:account_id).sort+ assert shares.all?(&:read_only?), "guest shares must grant read_only"+ assert shares.all?(&:include_in_finances?), "shares must be included in finances"+ end++ test "auto_share_existing_accounts_with is a no-op when family sharing is private" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "private")+ newcomer = users(:empty)+ newcomer.update_columns(family_id: family.id, role: "member")++ assert_no_difference "AccountShare.count" do+ family.auto_share_existing_accounts_with(newcomer)+ end+ end++ test "auto_share_existing_accounts_with does not share with a user outside the family" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ outsider = users(:empty)+ outsider.update_columns(family_id: families(:empty).id, role: "member")++ assert_no_difference "AccountShare.count" do+ family.auto_share_existing_accounts_with(outsider)+ end+ end++ test "auto_share_existing_accounts_with never shares a user's own account and is idempotent" do+ family = families(:dylan_family)+ family.update!(default_account_sharing: "shared")+ newcomer = users(:empty)+ newcomer.update_columns(family_id: family.id, role: "member")+ owned = family.accounts.first+ owned.update!(owner: newcomer)++ family.auto_share_existing_accounts_with(newcomer)+ count_after_first = AccountShare.where(user: newcomer).count++ assert_not AccountShare.exists?(user: newcomer, account: owned),+ "must not share a user's own account with themselves"++ family.auto_share_existing_accounts_with(newcomer) # re-run++ assert_equal count_after_first, AccountShare.where(user: newcomer).count,+ "re-running must not create duplicate shares"+ endenddiff --git a/test/models/invitation_test.rb b/test/models/invitation_test.rbindex 0e451fd7ac..2217bf04f4 100644--- a/test/models/invitation_test.rb+++ b/test/models/invitation_test.rb@@ -229,4 +229,47 @@ class InvitationTest < ActiveSupport::TestCaseassert_not user.show_ai_sidebar?assert user.ai_enabled?end++ test "accept_for auto-shares existing family accounts when family shares by default" do+ @family.update!(default_account_sharing: "shared")+ user = users(:empty)+ user.update_columns(family_id: families(:empty).id, role: "admin")+ invitation = @family.invitations.create!(email: user.email, role: "member", inviter: @inviter)++ expected_ids = @family.accounts.where.not(owner_id: user.id).pluck(:id).sort+ assert expected_ids.any?++ assert invitation.accept_for(user)++ assert_equal expected_ids, AccountShare.where(user: user).pluck(:account_id).sort+ end++ test "accept_for auto-shares read_only for guest invitations" do+ @family.update!(default_account_sharing: "shared")+ user = users(:empty)+ user.update_columns(family_id: families(:empty).id, role: "admin")+ invitation = @family.invitations.create!(email: user.email, role: "guest", inviter: @inviter)++ expected_ids = @family.accounts.where.not(owner_id: user.id).pluck(:id).sort+ assert expected_ids.any?++ assert invitation.accept_for(user)++ user.reload+ shares = AccountShare.where(user: user)+ assert_equal "guest", user.role+ assert_equal expected_ids, shares.pluck(:account_id).sort+ assert shares.all?(&:read_only?), "guest invitation shares must grant read_only"+ end++ test "accept_for does not auto-share when family sharing is private" do+ @family.update!(default_account_sharing: "private")+ user = users(:empty)+ user.update_columns(family_id: families(:empty).id, role: "admin")+ invitation = @family.invitations.create!(email: user.email, role: "member", inviter: @inviter)++ assert_no_difference "AccountShare.count" do+ assert invitation.accept_for(user)+ end+ endend