The personal finance app for everyone (by everyone)
Ruby
Scope member access in categories and the trade/valuation API (#3786)
Matrayucf5db21fedcb
diff --git a/app/controllers/api/v1/trades_controller.rb b/app/controllers/api/v1/trades_controller.rbindex fdf77bc1b5..77cee2f498 100644--- a/app/controllers/api/v1/trades_controller.rb+++ b/app/controllers/api/v1/trades_controller.rb@@ -6,12 +6,13 @@ class Api::V1::TradesController < Api::V1::BaseControllerbefore_action :ensure_read_scope, only: [ :index, :show ]before_action :ensure_write_scope, only: [ :create, :update, :destroy ]before_action :set_trade, only: [ :show, :update, :destroy ]+ before_action :ensure_write_permission, only: [ :update, :destroy ]def indexfamily = current_resource_owner.familytrades_query = family.trades.visible- trades_query = apply_filters(trades_query)+ trades_query = apply_filters(accessible_trades)trades_query = trades_query.includes({ entry: :account }, :security, :category, :lot_source_entry).reverse_chronological@pagy, @trades = pagy(@@ -39,7 +40,7 @@ class Api::V1::TradesController < Api::V1::BaseControllerreturn render_validation_error("Account ID is required", [ "Account ID is required" ])end- account = current_resource_owner.family.accounts.visible.find(trade_params[:account_id])+ account = current_resource_owner.family.accounts.writable_by(current_resource_owner).visible.find(trade_params[:account_id])unless account.supports_trades?return render_validation_error(@@ -135,14 +136,27 @@ class Api::V1::TradesController < Api::V1::BaseControllerprivate- def set_trade+ # Trades on accounts the caller can at least read.+ def accessible_tradesfamily = current_resource_owner.family- @trade = family.trades.visible.find(params[:id])+ family.trades.visible+ .where(entries: { account_id: family.accounts.accessible_by(current_resource_owner).select(:id) })+ end++ def set_trade+ # Load through accessible accounts only: a trade on an account the caller+ # cannot see is a 404. Write access is checked next (ensure_write_permission).+ @trade = accessible_trades.find(params[:id])@entry = @trade.entryrescue ActiveRecord::RecordNotFoundrender json: { error: "not_found", message: "Trade not found" }, status: :not_foundend+ # A trade the caller can see but not change is a 403, not a 404.+ def ensure_write_permission+ require_api_account_permission!(@entry.account, resource: "trade")+ end+def ensure_read_scopeauthorize_scope!(:read)enddiff --git a/app/controllers/api/v1/valuations_controller.rb b/app/controllers/api/v1/valuations_controller.rbindex 24c9cfd215..41446c9c61 100644--- a/app/controllers/api/v1/valuations_controller.rb+++ b/app/controllers/api/v1/valuations_controller.rb@@ -9,12 +9,10 @@ class Api::V1::ValuationsController < Api::V1::BaseControllerbefore_action :ensure_read_scope, only: [ :index, :show ]before_action :ensure_write_scope, only: [ :create, :update ]before_action :set_valuation, only: [ :show, :update ]+ before_action :ensure_write_permission, only: [ :update ]def index- family = current_resource_owner.family- accessible_account_ids = family.accounts.accessible_by(current_resource_owner).select(:id)- valuations_query = family.entries- .where(entryable_type: "Valuation", account_id: accessible_account_ids)+ valuations_query = accessible_valuation_entries.includes(:account, :entryable)valuations_query = apply_filters(valuations_query).reverse_chronological@@ -83,7 +81,7 @@ class Api::V1::ValuationsController < Api::V1::BaseControllerreturnend- account = current_resource_owner.family.accounts.find(valuation_account_id)+ account = current_resource_owner.family.accounts.writable_by(current_resource_owner).find(valuation_account_id)requested_upsert = upsert_requested?existing_write = false@@ -231,11 +229,20 @@ class Api::V1::ValuationsController < Api::V1::BaseControllerprivate+ # Valuation entries on accounts the caller can at least read.+ def accessible_valuation_entries+ family = current_resource_owner.family+ family.entries.where(+ entryable_type: "Valuation",+ account_id: family.accounts.accessible_by(current_resource_owner).select(:id)+ )+ end+def set_valuation- @entry = current_resource_owner.family- .entries- .where(entryable_type: "Valuation")- .find(params[:id])+ # Load through accessible accounts only: a valuation on an account the+ # caller cannot see is a 404. Write access is checked next+ # (ensure_write_permission).+ @entry = accessible_valuation_entries.find(params[:id])@valuation = @entry.entryablerescue ActiveRecord::RecordNotFoundrender json: {@@ -244,6 +251,11 @@ class Api::V1::ValuationsController < Api::V1::BaseController}, status: :not_foundend+ # A valuation the caller can see but not change is a 403, not a 404.+ def ensure_write_permission+ require_api_account_permission!(@entry.account, resource: "valuation")+ end+def ensure_read_scopeauthorize_scope!(:read)enddiff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex bbaaa13a77..ed90e09dea 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -178,7 +178,12 @@ class CategoriesController < ApplicationControllerdef set_transactionif params[:transaction_id].present?- @transaction = Current.family.transactions.find(params[:transaction_id])+ # Assigning a category annotates the transaction, so the account must be+ # one this member may annotate, not merely one in the same family.+ @transaction = Current.family.transactions+ .joins(entry: :account)+ .merge(Account.annotatable_by(Current.user))+ .find(params[:transaction_id])endenddiff --git a/app/controllers/category/dropdowns_controller.rb b/app/controllers/category/dropdowns_controller.rbindex 98a75b7ee9..7a6372d94a 100644--- a/app/controllers/category/dropdowns_controller.rb+++ b/app/controllers/category/dropdowns_controller.rb@@ -13,7 +13,10 @@ class Category::DropdownsController < ApplicationControllerendif params[:transaction_id]- @transaction = Current.family.transactions.find(params[:transaction_id])+ @transaction = Current.family.transactions+ .joins(entry: :account)+ .merge(Account.accessible_by(Current.user))+ .find(params[:transaction_id])endenddiff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex e0a3520a5b..0db682519a 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -10550,7 +10550,8 @@ paths:schema:"$ref": "#/components/schemas/ErrorResponse"'403':- description: forbidden - api key missing read_write scope+ description: forbidden - api key missing read_write scope, or the account+ is shared with you without write accesscontent:application/json:schema:@@ -10619,7 +10620,8 @@ paths:schema:"$ref": "#/components/schemas/ErrorResponse"'403':- description: forbidden - api key missing read_write scope+ description: forbidden - api key missing read_write scope, or the account+ is shared with you without write accesscontent:application/json:schema:@@ -11374,6 +11376,12 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ '403':+ description: account is shared with you without write access+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"'404':description: valuation not foundcontent:diff --git a/spec/requests/api/v1/trades_spec.rb b/spec/requests/api/v1/trades_spec.rbindex 975b5e012c..7074702680 100644--- a/spec/requests/api/v1/trades_spec.rb+++ b/spec/requests/api/v1/trades_spec.rb@@ -54,6 +54,7 @@ RSpec.describe 'API V1 Trades', type: :request dolet(:account) doAccount.create!(family: family,+ owner: user,name: 'Investment Account',balance: 50_000,currency: 'USD',@@ -87,6 +88,30 @@ RSpec.describe 'API V1 Trades', type: :request doentry.entryableend+ let(:read_only_trade) do+ owner = family.users.create!(+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123'+ )+ shared_account = Account.create!(+ family: family,+ owner: owner,+ name: 'Shared Brokerage',+ balance: 50_000,+ currency: 'USD',+ accountable: Investment.create!+ )+ shared_account.account_shares.create!(user: user, permission: 'read_only', include_in_finances: true)+ shared_account.entries.create!(+ name: 'Buy shared shares',+ date: Date.current,+ amount: 1_000,+ currency: 'USD',+ entryable: Trade.new(security: security, qty: 10, price: 100, currency: 'USD', investment_activity_label: 'Buy')+ ).entryable+ end+path '/api/v1/trades' doget 'List trades' dotags 'Trades'@@ -614,7 +639,7 @@ RSpec.describe 'API V1 Trades', type: :request dorun_test!end- response '403', 'forbidden - api key missing read_write scope' do+ response '403', 'forbidden - api key missing read_write scope, or the account is shared with you without write access' doschema '$ref' => '#/components/schemas/ErrorResponse'let(:id) { trade.id }@@ -633,6 +658,14 @@ RSpec.describe 'API V1 Trades', type: :request dorun_test!end+ response '403', 'forbidden - api key missing read_write scope, or the account is shared with you without write access' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:id) { read_only_trade.id }++ run_test!+ end+response '404', 'trade not found' doschema '$ref' => '#/components/schemas/ErrorResponse'@@ -664,7 +697,7 @@ RSpec.describe 'API V1 Trades', type: :request dorun_test!end- response '403', 'forbidden - api key missing read_write scope' do+ response '403', 'forbidden - api key missing read_write scope, or the account is shared with you without write access' doschema '$ref' => '#/components/schemas/ErrorResponse'let(:id) { trade.id }@@ -683,6 +716,14 @@ RSpec.describe 'API V1 Trades', type: :request dorun_test!end+ response '403', 'forbidden - api key missing read_write scope, or the account is shared with you without write access' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:id) { read_only_trade.id }++ run_test!+ end+response '404', 'trade not found' doschema '$ref' => '#/components/schemas/ErrorResponse'diff --git a/spec/requests/api/v1/valuations_spec.rb b/spec/requests/api/v1/valuations_spec.rbindex b164812cf9..fc86980897 100644--- a/spec/requests/api/v1/valuations_spec.rb+++ b/spec/requests/api/v1/valuations_spec.rb@@ -36,6 +36,7 @@ RSpec.describe 'API V1 Valuations', type: :request dolet(:account) doAccount.create!(family: family,+ owner: user,name: 'Investment Account',balance: 10000,currency: 'USD',@@ -58,6 +59,30 @@ RSpec.describe 'API V1 Valuations', type: :request dolet!(:valuation) { valuation_entry.entryable }let!(:valuation_id) { valuation_entry.id }+ let(:read_only_valuation_id) do+ owner = family.users.create!(+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123'+ )+ shared_account = Account.create!(+ family: family,+ owner: owner,+ name: 'Shared Savings',+ balance: 1000,+ currency: 'USD',+ accountable: Depository.create!+ )+ shared_account.account_shares.create!(user: user, permission: 'read_only', include_in_finances: true)+ shared_account.entries.create!(+ name: 'Shared Reconciliation',+ date: Date.current,+ amount: 1000,+ currency: 'USD',+ entryable: Valuation.new(kind: 'reconciliation')+ ).id+ end+path '/api/v1/valuations' doget 'List valuations' dotags 'Valuations'@@ -323,6 +348,15 @@ RSpec.describe 'API V1 Valuations', type: :request dorun_test!end+ response '403', 'account is shared with you without write access' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:id) { read_only_valuation_id }+ let(:body) { { valuation: { notes: 'Not allowed' } } }++ run_test!+ end+response '404', 'valuation not found' doschema '$ref' => '#/components/schemas/ErrorResponse'diff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rbindex 9bac620643..fd38d8438a 100644--- a/test/controllers/api/v1/trades_controller_test.rb+++ b/test/controllers/api/v1/trades_controller_test.rb@@ -1095,6 +1095,71 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTestassert trade_data.key?("notes")end+ test "a member cannot list, read, change or add trades on accounts they cannot reach" do+ member = users(:family_member)+ member.api_keys.active.destroy_all+ key = ApiKey.create!(user: member, name: "Member RW", key: ApiKey.generate_secure_key, scopes: %w[read_write], source: "web")+ Redis.new.del("api_rate_limit:#{key.id}")++ private_account = member.family.accounts.create!(name: "Admin Private Brokerage", owner: @user, balance: 1_000,+ currency: "USD", accountable: Investment.new)+ read_only = member.family.accounts.create!(name: "Admin Read-only Brokerage", owner: @user, balance: 1_000,+ currency: "USD", accountable: Investment.new)+ read_only.account_shares.create!(user: member, permission: "read_only", include_in_finances: true)+ hidden = create_trade(securities(:aapl), account: private_account, qty: 1, date: Date.current, price: 100).trade+ visible = create_trade(securities(:aapl), account: read_only, qty: 1, date: Date.current, price: 100).trade++ get "/api/v1/trades", params: { per_page: 100 }, headers: api_headers(key)+ ids = JSON.parse(response.body)["trades"].map { |t| t["id"] }+ assert_includes ids, visible.id, "the read-only share must still be listed, or this proves nothing"+ assert_not_includes ids, hidden.id++ get "/api/v1/trades/#{hidden.id}", headers: api_headers(key)+ assert_response :not_found++ get "/api/v1/trades/#{visible.id}", headers: api_headers(key)+ assert_response :success++ # Visible but not writable: 403, the caller can already read it.+ patch "/api/v1/trades/#{visible.id}", params: { trade: { qty: 2 } }, headers: api_headers(key)+ assert_response :forbidden+ assert_equal "You do not have permission to change this trade", JSON.parse(response.body)["message"]+ delete "/api/v1/trades/#{visible.id}", headers: api_headers(key)+ assert_response :forbidden+ assert_equal "You do not have permission to delete this trade", JSON.parse(response.body)["message"]+ assert Trade.exists?(visible.id)++ # Not visible at all: 404, existence is not revealed.+ patch "/api/v1/trades/#{hidden.id}", params: { trade: { qty: 2 } }, headers: api_headers(key)+ assert_response :not_found+ delete "/api/v1/trades/#{hidden.id}", headers: api_headers(key)+ assert_response :not_found+ assert Trade.exists?(hidden.id)++ post "/api/v1/trades", params: { trade: { account_id: read_only.id, type: "buy", date: Date.current,+ qty: 1, price: 100, ticker: "AAPL|XNAS" } }, headers: api_headers(key)+ assert_response :not_found+ end++ test "a full_control member can change and delete trades on a shared account" do+ member = users(:family_member)+ member.api_keys.active.destroy_all+ key = ApiKey.create!(user: member, name: "Member RW", key: ApiKey.generate_secure_key, scopes: %w[read_write], source: "web")+ Redis.new.del("api_rate_limit:#{key.id}")++ shared = member.family.accounts.create!(name: "Admin Shared Brokerage", owner: @user, balance: 1_000,+ currency: "USD", accountable: Investment.new)+ shared.account_shares.create!(user: member, permission: "full_control", include_in_finances: true)+ trade = create_trade(securities(:aapl), account: shared, qty: 1, date: Date.current, price: 100).trade++ patch "/api/v1/trades/#{trade.id}", params: { trade: { qty: 2 } }, headers: api_headers(key)+ assert_response :success++ delete "/api/v1/trades/#{trade.id}", headers: api_headers(key)+ assert_response :success+ assert_not Trade.exists?(trade.id)+ end+test "a sale that names its lot reports the acquiring trade, in show and index" do@investment_account.update!(cost_basis_method: "fifo")diff --git a/test/controllers/api/v1/valuations_controller_test.rb b/test/controllers/api/v1/valuations_controller_test.rbindex b1a24bc977..765d2f2d81 100644--- a/test/controllers/api/v1/valuations_controller_test.rb+++ b/test/controllers/api/v1/valuations_controller_test.rb@@ -366,6 +366,62 @@ class Api::V1::ValuationsControllerTest < ActionDispatch::IntegrationTestassert valuation_data.key?("notes")end+ test "a member cannot read, change or add valuations on accounts they cannot reach" do+ member = users(:family_member)+ member.api_keys.active.destroy_all+ key = ApiKey.create!(user: member, name: "Member RW", scopes: [ "read_write" ], source: "web",+ display_key: "test_member_#{SecureRandom.hex(8)}")++ private_account = @family.accounts.create!(name: "Admin Private Savings", owner: @user, balance: 0,+ currency: "USD", accountable: Depository.new)+ read_only = @family.accounts.create!(name: "Admin Read-only Savings", owner: @user, balance: 0,+ currency: "USD", accountable: Depository.new)+ read_only.account_shares.create!(user: member, permission: "read_only", include_in_finances: true)+ hidden = private_account.entries.create!(name: "Balance", date: 1.day.ago.to_date, amount: 100,+ currency: "USD", entryable: Valuation.new(kind: "reconciliation"))+ shared = read_only.entries.create!(name: "Balance", date: 1.day.ago.to_date, amount: 100,+ currency: "USD", entryable: Valuation.new(kind: "reconciliation"))+ headers = api_headers(key)++ get "/api/v1/valuations/#{hidden.id}", headers: headers+ assert_response :not_found++ get "/api/v1/valuations/#{shared.id}", headers: headers+ assert_response :success, "the read-only share must still be readable, or this proves nothing"++ # Visible but not writable: 403, the caller can already read it.+ patch "/api/v1/valuations/#{shared.id}", params: { valuation: { amount: 999 } }, headers: headers+ assert_response :forbidden+ assert_equal "You do not have permission to change this valuation", JSON.parse(response.body)["message"]+ assert_equal 100, shared.reload.amount++ # Not visible at all: 404, existence is not revealed.+ patch "/api/v1/valuations/#{hidden.id}", params: { valuation: { amount: 999 } }, headers: headers+ assert_response :not_found+ assert_equal 100, hidden.reload.amount++ post "/api/v1/valuations", params: { valuation: { account_id: read_only.id, amount: 5, date: Date.current } }, headers: headers+ assert_response :not_found+ end++ test "a full_control member can change a valuation on a shared account" do+ member = users(:family_member)+ member.api_keys.active.destroy_all+ key = ApiKey.create!(user: member, name: "Member RW", scopes: [ "read_write" ], source: "web",+ display_key: "test_member_#{SecureRandom.hex(8)}")++ shared_account = @family.accounts.create!(name: "Admin Shared Savings", owner: @user, balance: 0,+ currency: "USD", accountable: Depository.new)+ shared_account.account_shares.create!(user: member, permission: "full_control", include_in_finances: true)+ entry = shared_account.entries.create!(name: "Balance", date: 1.day.ago.to_date, amount: 100,+ currency: "USD", entryable: Valuation.new(kind: "reconciliation"))++ patch "/api/v1/valuations/#{entry.id}", params: { valuation: { amount: 250, date: entry.date } }, headers: api_headers(key)++ assert_response :success+ assert_equal 250, entry.reload.amount+ end+privatedef api_headers(api_key)diff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rbindex fe5c03d7bc..a7a862fadc 100644--- a/test/controllers/categories_controller_test.rb+++ b/test/controllers/categories_controller_test.rb@@ -566,6 +566,39 @@ class CategoriesControllerTest < ActionDispatch::IntegrationTestassert_not @family.reload.categories_locked?end+ test "create does not categorize a transaction on an account the member cannot annotate" do+ member = users(:family_member)+ private_account = @family.accounts.create!(name: "Admin Private Checking", owner: @user, balance: 0,+ currency: "USD", accountable: Depository.new)+ private_entry = private_account.entries.create!(name: "Private", date: Date.current, amount: 10,+ currency: "USD", entryable: Transaction.new)+ read_only_entry = accounts(:credit_card).entries.create!(name: "Read only", date: Date.current, amount: 10,+ currency: "USD", entryable: Transaction.new)+ sign_in member++ [ private_entry, read_only_entry ].each do |entry|+ assert_no_difference "Category.count" do+ post categories_url, params: { transaction_id: entry.transaction.id, category: { name: "Leak #{entry.id}", color: "#000000" } }+ end+ assert_response :not_found+ assert_nil entry.transaction.reload.category+ end+ end++ test "create categorizes a transaction on an account shared with the member at the annotate tier" do+ member = users(:family_member)+ shared_account = @family.accounts.create!(name: "Admin Annotate Checking", owner: @user, balance: 0,+ currency: "USD", accountable: Depository.new)+ shared_account.account_shares.create!(user: member, permission: "read_write", include_in_finances: true)+ shared_entry = shared_account.entries.create!(name: "Shared", date: Date.current, amount: 10,+ currency: "USD", entryable: Transaction.new)+ sign_in member++ post categories_url, params: { transaction_id: shared_entry.transaction.id, category: { name: "Shared Category", color: "#000000" } }++ assert_equal "Shared Category", shared_entry.transaction.reload.category&.name+ end+privatedef capture_sql_queriesqueries = []diff --git a/test/controllers/category/dropdowns_controller_test.rb b/test/controllers/category/dropdowns_controller_test.rbindex 6f3741c0e7..d626ead6c1 100644--- a/test/controllers/category/dropdowns_controller_test.rb+++ b/test/controllers/category/dropdowns_controller_test.rb@@ -91,4 +91,16 @@ class Category::DropdownsControllerTest < ActionDispatch::IntegrationTestassert_select "[data-category-quick-create-target='createAsSubcategory']", count: 0assert_select "[data-category-quick-create-target='parentPicker']", count: 0end++ test "does not render for a transaction on an account the member cannot access" do+ admin = users(:family_admin)+ private_account = admin.family.accounts.create!(name: "Admin Private Checking", owner: admin, balance: 0,+ currency: "USD", accountable: Depository.new)+ private_entry = create_transaction(account: private_account, name: "Private")+ sign_in users(:family_member)++ get category_dropdown_url(transaction_id: private_entry.entryable.id)++ assert_response :not_found+ endend