Refuse another family's category or merchant in the API (#4694)

* Refuse a tag id the caller's family does not own in the API

Api::V1::TransactionsController assigned whatever tag_ids it was sent, so
another family's tag could be linked to a transaction, and an unknown id
raised RecordNotFound into the broad rescue's 500. create and update now
resolve the ids through the family's own tags, as the assistant tools and
the web bulk update do, and answer 422 validation_failed before writing.

Clients sending their own ids, [], [""] or no tag_ids are unchanged.
Siblings: the splits API is already scoped by Entry::SplitReferences. The
web transaction and transfer forms are not, and are left for their own
change.

* Refuse a malformed tag_ids in the transactions API

Strong parameters drops a tag_ids that is not an array of scalars, so
the ownership check saw nothing to refuse. Update then read it as "no
tags" and cleared the transaction's tags with a 200, and create wrote
an untagged row with a 201. No foreign tag was linked either way.

create and update now answer 422 validation_failed unless tag_ids is
null or an array of strings, the rule the splits API already applies.
[], [""] and null still clear on update. A bare "" used to clear and is
now refused; transaction[tag_ids][]= is the form-encoded way to clear.

Siblings: the splits API already checks this shape. Category and
merchant ids are scalars, and are handled in their own change.

* Refuse another family's category or merchant in the API

Api::V1::TransactionsController stored whatever category_id and
merchant_id it was sent, so a caller could link another family's records
to its own transaction, and read the category's name back. create and
update now answer 422 validation_failed before writing.

A caller may use its family's categories, its family's merchants, and
provider merchants on transactions it can reach. A family merchant on a
reachable transaction is not enough, because it may be another family's.
Omitted and blank ids are unchanged. Re-sending the id a transaction
already holds still saves, because clients send back what they read, so
a row linked before this check stays editable. Existing foreign links
are left in place.

Siblings: the splits API already scopes these ids. The trades API has no
category_id column to write since 20260114002048, so its update returns
500 for any id and links nothing. The web forms are left for their own
change.

* Compare tag ids in canonical UUID form, and store each once

The unknown-tag check counted raw strings, so one tag sent in two cases
was two ids against one match, and the request failed as "Unknown tag
id". Correcting the count exposed the writes: tag_ids= was given the
raw list, so the same tag would have been stored twice.

requested_tag_ids casts each id with the tags' id type and removes
duplicates. The check, the create and the update all read it. An id
that is not a UUID casts to nil, matches no tag and is still refused.

* Refuse a tag list whose ids are all invalid

a625de55e dropped the explicit nil check as redundant, since a nil id
matches no tag and the count falls short. That holds only when a valid
id sits beside it. With only invalid ids the cast list is [nil],
[nil].any? is false, the check passed, and the collection writer dropped
the nil: an update cleared every tag and a create was saved untagged.

The check is back, with tests for an update and a create whose tag ids
are all invalid. Both fail without it.

* Compare category and merchant ids in canonical UUID form

An update that resent the category or merchant a transaction already holds, in another case, missed the already-held shortcut and was refused for a foreign one. Ids are now cast to Postgres' canonical form first. A value that is not a UUID is still refused.
This commit is contained in:
jaysbeekay
2026-11-09 00:00:39 -08:00
committed by GitHub
parent 1d52dc19a4
commit 4f2970b0f4
4 changed files with 486 additions and 4 deletions
@@ -99,6 +99,11 @@ class Api::V1::TransactionsController < Api::V1::BaseController
return 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::BaseController
return
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 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 do
if @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 specified
if 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::BaseController
entryable_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::BaseController
params[: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? ||
+9 -1
View File
@@ -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 use
content:
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:
+9 -1
View File
@@ -253,7 +253,7 @@ RSpec.describe 'API V1 Transactions', type: :request do
run_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' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
@@ -350,6 +350,14 @@ RSpec.describe 'API V1 Transactions', type: :request do
run_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!
end
end
delete 'Delete a transaction' do
@@ -803,6 +803,386 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
assert_equal original_tags.map(&:id).sort, @transaction.tag_ids.sort
end
# 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 @@ end
private
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