The personal finance app for everyone (by everyone)
Ruby
Refuse another family's category or merchant in the API (#4694)
jaysbeekay4f2970b0f4a2
diff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rbindex 766b1dd6d9..46e69b1d39 100644--- a/app/controllers/api/v1/transactions_controller.rb+++ b/app/controllers/api/v1/transactions_controller.rb@@ -99,6 +99,11 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerreturn render_existing_idempotent_entry(existing_entry)end+ return render_validation_error("tag_ids must be an array of tag ids") if malformed_tag_ids?+ return render_validation_error("Unknown tag id") if unknown_tag_ids?+ return render_validation_error("Unknown category id") if unknown_category_id?+ return render_validation_error("Unknown merchant id") if unknown_merchant_id?+@entry = account.entries.new(entry_params_for_create)if @entry.save@@ -144,6 +149,11 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerreturnend+ return render_validation_error("tag_ids must be an array of tag ids") if malformed_tag_ids?+ return render_validation_error("Unknown tag id") if tags_provided? && unknown_tag_ids?+ return render_validation_error("Unknown category id") if unknown_category_id?+ return render_validation_error("Unknown merchant id") if unknown_merchant_id?+Entry.transaction doif @entry.update(entry_params_for_update)sync_needed = @entry.saved_changes_affect_balances?@@ -151,7 +161,7 @@ class Api::V1::TransactionsController < Api::V1::BaseController# Handle tags separately - only when explicitly provided in the request# This allows clearing tags with tag_ids: [] while preserving tags when not specifiedif tags_provided?- @entry.transaction.tag_ids = transaction_params[:tag_ids] || []+ @entry.transaction.tag_ids = requested_tag_ids@entry.transaction.save!@entry.transaction.lock_attr!(:tag_ids) if @entry.transaction.tags.any?end@@ -334,7 +344,7 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerentryable_attributes: {category_id: transaction_params[:category_id],merchant_id: transaction_params[:merchant_id],- tag_ids: transaction_params[:tag_ids] || []+ tag_ids: requested_tag_ids}}if idempotency_key_requested?@@ -373,6 +383,69 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerparams[:transaction].key?(:tag_ids)end+ # Strong parameters drops a tag_ids of any other shape, which would read as+ # "no tags" and clear them on update.+ def malformed_tag_ids?+ tag_ids = params.require(:transaction)[:tag_ids]+ !(tag_ids.nil? || (tag_ids.is_a?(Array) && tag_ids.all?(String)))+ end++ # Tags belong to a family: ids are resolved through the caller's own, so+ # another family's tag is refused like one that does not exist.+ # An id that is not a UUID casts to nil and is unknown. It has to be refused+ # here: with only such ids the list is [nil], and the collection writer+ # would drop the nil and clear every tag.+ def unknown_tag_ids?+ ids = requested_tag_ids+ return true if ids.include?(nil)++ ids.any? && current_resource_owner.family.tags.where(id: ids).count != ids.size+ end++ # A client re-sends the ids it read back, so the category or merchant a+ # transaction already holds is not refused: no new link is made.+ def unknown_category_id?+ raw = transaction_params[:category_id].presence+ return false if raw.nil?++ id = canonical_uuid(raw)+ return true if id.nil?+ return false if id == @entry&.transaction&.category_id++ !current_resource_owner.family.categories.exists?(id: id)+ end++ # The family's own merchants, and provider merchants the caller can reach.+ # A family merchant on a reachable transaction isn't enough: it may be+ # another family's, linked before this check.+ def unknown_merchant_id?+ raw = transaction_params[:merchant_id].presence+ return false if raw.nil?++ id = canonical_uuid(raw)+ return true if id.nil?+ return false if id == @entry&.transaction&.merchant_id++ family = current_resource_owner.family+ !family.merchants.exists?(id: id) &&+ !family.available_merchants_for(current_resource_owner).where(type: "ProviderMerchant").exists?(id: id)+ end++ # The lowercase hyphenated form Postgres stores, so an id resent in another+ # case still matches the one a transaction holds. Nil for a non-UUID.+ def canonical_uuid(value)+ Category.type_for_attribute(:id).cast(value)+ end++ # The request's tag ids in canonical UUID form, each once. Postgres matches+ # a UUID in any case, so one tag spelled two ways is one tag, and writing+ # the raw list would store it twice.+ def requested_tag_ids+ @requested_tag_ids ||= Array(transaction_params[:tag_ids]).compact_blank+ .map { |id| Tag.type_for_attribute(:id).cast(id) }+ .uniq+ end+def split_financial_fields_changed?params.dig(:transaction, :amount).present? ||params.dig(:transaction, :date).present? ||diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 3382d7f5e8..d9537cf58d 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -10421,7 +10421,8 @@ paths:schema:"$ref": "#/components/schemas/Transaction"'422':- description: validation error - missing required fields+ description: validation error - missing required fields, malformed tag_ids,+ or a tag, category or merchant id the family cannot usecontent:application/json:schema:@@ -10548,6 +10549,13 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ '422':+ description: validation error - malformed tag_ids, or a tag, category or+ merchant id the family cannot use+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"requestBody:content:application/json:diff --git a/spec/requests/api/v1/transactions_spec.rb b/spec/requests/api/v1/transactions_spec.rbindex fc138ebd09..4419af1cee 100644--- a/spec/requests/api/v1/transactions_spec.rb+++ b/spec/requests/api/v1/transactions_spec.rb@@ -253,7 +253,7 @@ RSpec.describe 'API V1 Transactions', type: :request dorun_test!end- response '422', 'validation error - missing required fields' do+ response '422', 'validation error - missing required fields, malformed tag_ids, or a tag, category or merchant id the family cannot use' doschema '$ref' => '#/components/schemas/ErrorResponse'let(:body) do@@ -350,6 +350,14 @@ RSpec.describe 'API V1 Transactions', type: :request dorun_test!end++ response '422', 'validation error - malformed tag_ids, or a tag, category or merchant id the family cannot use' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:body) { { transaction: { tag_ids: [ SecureRandom.uuid ] } } }++ run_test!+ endenddelete 'Delete a transaction' dodiff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex 1f12f96a7f..dee8ac5687 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -803,6 +803,386 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTestassert_equal original_tags.map(&:id).sort, @transaction.tag_ids.sortend+ # Tags belong to a family: another family's tag id is never linked.+ test "update with another family's tag id is refused and leaves the tags unchanged" do+ own_tag = @family.tags.first+ @transaction.update!(tag_ids: [ own_tag.id ])+ foreign_tag = families(:empty).tags.create!(name: "Foreign", color: "#e99537")++ assert_no_difference -> { Tagging.where(tag_id: foreign_tag.id).count } do+ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ own_tag.id, foreign_tag.id ] } },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal [ own_tag.id ], @transaction.reload.tag_ids+ end++ test "update with a tag id no family owns is refused and leaves the tags unchanged" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids.sort++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ SecureRandom.uuid ] } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal before_ids, @transaction.reload.tag_ids.sort+ end++ test "create with another family's tag id is refused and creates nothing" do+ foreign_tag = families(:empty).tags.create!(name: "Foreign", color: "#e99537")++ assert_no_difference [ "@account.entries.count", "Tagging.count" ] do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: [ foreign_tag.id ] } },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end++ test "update with the family's own tags still assigns them" do+ tags = @family.tags.limit(2).to_a+ @transaction.update!(tag_ids: [])++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: tags.map(&:id) } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal tags.map(&:id).sort, @transaction.reload.tag_ids.sort+ end++ # One tag named in two spellings is one tag: Postgres matches a UUID in any+ # case, so counting raw strings would call it unknown.+ test "create with one tag spelled in two cases tags it once" do+ tag = @family.tags.first++ assert_difference "Tagging.count", 1 do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: [ tag.id, tag.id.upcase ] } },+ headers: api_headers(@api_key)+ end++ assert_response :success+ end++ test "update with one tag spelled in two cases assigns it once" do+ tag = @family.tags.first+ @transaction.update!(tag_ids: [])++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ tag.id, tag.id.upcase ] } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal [ tag.id ], @transaction.reload.tag_ids+ end++ test "update with a tag id that is not a UUID is refused and changes nothing" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ @family.tags.first.id, "not-a-uuid" ] } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal before_ids, @transaction.reload.tag_ids+ end++ # With only invalid ids the cast list is [nil], which is not "any?", and the+ # collection writer drops the nil, so this would clear every tag.+ test "update with only ids that are not UUIDs is refused and keeps the tags" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])+ before_ids = @transaction.reload.tag_ids++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: [ "not-a-uuid" ] } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal before_ids, @transaction.reload.tag_ids+ end++ test "create with only ids that are not UUIDs is refused and creates nothing" do+ assert_no_difference [ "@account.entries.count", "Tagging.count" ] do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: [ "not-a-uuid" ] } },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ end++ # Strong parameters drops a tag_ids of any other shape, which would otherwise+ # read as "no tags" and clear them.+ [+ [ "an array holding a hash", ->(id) { [ id, {} ] } ],+ [ "an array holding a false", ->(id) { [ id, false ] } ],+ [ "a bare string", ->(id) { id } ],+ [ "a hash", ->(id) { { id: id } } ]+ ].each do |shape, build|+ test "update with #{shape} as tag_ids is refused and changes nothing" do+ own_tag = @family.tags.first+ @transaction.update!(tag_ids: [ own_tag.id ])+ name_before = @transaction.entry.reload.name++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Renamed", tag_ids: build.call(own_tag.id) } },+ headers: api_headers(@api_key),+ as: :json++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal [ own_tag.id ], @transaction.reload.tag_ids+ assert_equal name_before, @transaction.entry.reload.name+ end++ test "create with #{shape} as tag_ids is refused and creates nothing" do+ assert_no_difference -> { Entry.count } do+ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "Refused", amount: 10, date: Date.current,+ currency: "USD", nature: "expense", tag_ids: build.call(@family.tags.first.id) } },+ headers: api_headers(@api_key),+ as: :json+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end+ end++ [ [ "an empty array", [] ], [ "a null", nil ], [ "a blank entry", [ "" ] ] ].each do |shape, value|+ test "update with #{shape} as tag_ids still clears the tags" do+ @transaction.update!(tag_ids: [ @family.tags.first.id ])++ put api_v1_transaction_url(@transaction),+ params: { transaction: { tag_ids: value } },+ headers: api_headers(@api_key),+ as: :json++ assert_response :success+ assert_empty @transaction.reload.tag_ids+ end+ end++ # Categories and merchants are used through the family: another family's id+ # is never linked.+ test "update with another family's category is refused and changes nothing" do+ own_category = @family.categories.first+ @transaction.update!(category: own_category)+ name_before = @transaction.entry.reload.name++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Renamed", category_id: foreign_category.id } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal own_category.id, @transaction.reload.category_id+ assert_equal name_before, @transaction.entry.reload.name+ end++ test "update with another family's merchant is refused and changes nothing" do+ own_merchant = @family.merchants.create!(name: "Own Merchant")+ @transaction.update!(merchant: own_merchant)+ name_before = @transaction.entry.reload.name++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Renamed", merchant_id: foreign_merchant.id } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal own_merchant.id, @transaction.reload.merchant_id+ assert_equal name_before, @transaction.entry.reload.name+ end++ %w[category_id merchant_id].each do |attribute|+ test "update with a #{attribute} that does not exist is refused" do+ before = @transaction.reload.public_send(attribute)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { attribute => SecureRandom.uuid } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_equal before, @transaction.reload.public_send(attribute)+ end++ test "create with a #{attribute} that does not exist is refused and creates nothing" do+ assert_no_difference -> { Entry.count } do+ post api_v1_transactions_url,+ params: { transaction: reference_create_params(attribute => SecureRandom.uuid) },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ end++ test "update with #{attribute} omitted or blank keeps its value" do+ own = { "category_id" => @family.categories.first.id,+ "merchant_id" => @family.merchants.create!(name: "Kept Merchant").id }.fetch(attribute)+ @transaction.update!(attribute => own)++ [ { name: "Omitted" }, { name: "Blank", attribute => "" } ].each do |fields|+ put api_v1_transaction_url(@transaction),+ params: { transaction: fields },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal fields[:name], @transaction.entry.reload.name+ assert_equal own, @transaction.reload.public_send(attribute)+ end+ end+ end++ test "create with another family's category is refused and creates nothing" do+ assert_no_difference -> { Entry.count } do+ post api_v1_transactions_url,+ params: { transaction: reference_create_params(category_id: foreign_category.id) },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end++ test "create with another family's merchant is refused and creates nothing" do+ assert_no_difference -> { Entry.count } do+ post api_v1_transactions_url,+ params: { transaction: reference_create_params(merchant_id: foreign_merchant.id) },+ headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end++ test "create and update still assign the family's own category and merchant" do+ category = @family.categories.first+ merchant = @family.merchants.create!(name: "Assigned Merchant")++ post api_v1_transactions_url,+ params: { transaction: reference_create_params(category_id: category.id, merchant_id: merchant.id) },+ headers: api_headers(@api_key)++ assert_response :created+ created = Transaction.find(JSON.parse(response.body)["id"])+ assert_equal category.id, created.category_id+ assert_equal merchant.id, created.merchant_id++ @transaction.update!(category: nil, merchant: nil)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { category_id: category.id, merchant_id: merchant.id } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal category.id, @transaction.reload.category_id+ assert_equal merchant.id, @transaction.merchant_id+ end++ test "a provider merchant the user can reach still assigns, and one they cannot is refused" do+ reachable = ProviderMerchant.create!(name: "Reachable Provider", source: "plaid")+ unreachable = ProviderMerchant.create!(name: "Unreachable Provider", source: "plaid")+ other_transaction = @family.transactions.where.not(id: @transaction.id).first+ other_transaction.update!(merchant: reachable)+ @transaction.update!(merchant: nil)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { merchant_id: unreachable.id } },+ headers: api_headers(@api_key)+ assert_response :unprocessable_entity+ assert_nil @transaction.reload.merchant_id++ put api_v1_transaction_url(@transaction),+ params: { transaction: { merchant_id: reachable.id } },+ headers: api_headers(@api_key)+ assert_response :success+ assert_equal reachable.id, @transaction.reload.merchant_id++ post api_v1_transactions_url,+ params: { transaction: reference_create_params(merchant_id: reachable.id) },+ headers: api_headers(@api_key)+ assert_response :created+ assert_equal reachable.id, Transaction.find(JSON.parse(response.body)["id"]).merchant_id+ end++ # A client re-sends the ids it read back, so a row already holding a foreign+ # category must stay editable. No new link is made.+ test "update re-sending a foreign category the transaction already holds still saves" do+ @transaction.update_columns(category_id: foreign_category.id)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Still editable", category_id: foreign_category.id } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal "Still editable", @transaction.entry.reload.name+ end++ test "update re-sending a held foreign category or merchant in upper case still saves" do+ @transaction.update_columns(category_id: foreign_category.id, merchant_id: foreign_merchant.id)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Still editable", category_id: foreign_category.id.upcase,+ merchant_id: foreign_merchant.id.upcase } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal "Still editable", @transaction.entry.reload.name+ end++ test "a category or merchant id that is not a UUID is refused" do+ { category_id: "not-a-uuid", merchant_id: "not-a-uuid" }.each do |key, value|+ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Renamed", key => value } },+ headers: api_headers(@api_key)++ assert_response :unprocessable_entity, "#{key} was accepted"+ end+ assert_not_equal "Renamed", @transaction.entry.reload.name+ end++ test "update re-sending a foreign merchant the transaction already holds still saves" do+ @transaction.update_columns(merchant_id: foreign_merchant.id)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { name: "Still editable", merchant_id: foreign_merchant.id } },+ headers: api_headers(@api_key)++ assert_response :success+ assert_equal "Still editable", @transaction.entry.reload.name+ end++ test "a foreign merchant already on one transaction cannot be linked to another" do+ holder = @family.transactions.where.not(id: @transaction.id).first+ holder.update_columns(merchant_id: foreign_merchant.id)+ @transaction.update!(merchant: nil)++ put api_v1_transaction_url(@transaction),+ params: { transaction: { merchant_id: foreign_merchant.id } },+ headers: api_headers(@api_key)+ assert_response :unprocessable_entity+ assert_nil @transaction.reload.merchant_id++ assert_no_difference -> { Entry.count } do+ post api_v1_transactions_url,+ params: { transaction: reference_create_params(merchant_id: foreign_merchant.id) },+ headers: api_headers(@api_key)+ end+ assert_response :unprocessable_entity+ end+test "should clear tags when empty tag_ids explicitly provided in update" do# Set up transaction with existing tags@transaction.tags = [ Tag.first, Tag.second ]@@ -1074,6 +1454,19 @@ endprivate+ def foreign_category+ @foreign_category ||= families(:empty).categories.create!(name: "Foreign", color: "#e99537", lucide_icon: "circle")+ end++ def foreign_merchant+ @foreign_merchant ||= families(:empty).merchants.create!(name: "Foreign")+ end++ def reference_create_params(references)+ { account_id: @account.id, name: "With references", amount: 10, date: Date.current,+ currency: "USD", nature: "expense" }.merge(references)+ end+def api_headers(api_key){ "X-Api-Key" => api_key.display_key }end