The personal finance app for everyone (by everyone)
Ruby
Require write permission for API v1 transaction update and destroy (#3869)
Matrayu67765eefbe75
diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rbindex eaa5b467f1..0bb2301082 100644--- a/app/controllers/api/v1/base_controller.rb+++ b/app/controllers/api/v1/base_controller.rb@@ -230,6 +230,32 @@ class Api::V1::BaseController < ApplicationControllerfalseend+ # Account-level authorization for API writes. The token scope says what the+ # KEY may do; this says what its owner may do to this account, which+ # `Account.accessible_by` does not (it admits read-only shares). Renders a+ # 403 { error: "forbidden", message: } and returns false when the owner of+ # the credentials lacks `level` (:write, :annotate or :owner, see+ # AccountPolicy#permits?); returns true otherwise. A visible-but-not-writable+ # account is a 403, never a 404: the caller can already read it.+ #+ # `resource:` names the record being changed ("transaction", "trade") and+ # yields "You do not have permission to delete|change this <resource>",+ # choosing the verb from the action, so pass it only from update and+ # destroy on an existing record. Without it the message is the+ # account-level "You do not have write access to this account".+ def require_api_account_permission!(account, level = :write, resource: nil)+ return true if AccountPolicy.new(current_resource_owner, account).permits?(level)++ message = if resource+ "You do not have permission to #{action_name == 'destroy' ? 'delete' : 'change'} this #{resource}"+ else+ "You do not have write access to this account"+ end++ render_json({ error: "forbidden", message: message }, status: :forbidden)+ false+ end+# Consistent JSON response methoddef render_json(data, status: :ok)render json: data, status: statusdiff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rbindex f079633ae2..c8a4ec05a0 100644--- a/app/controllers/api/v1/splits_controller.rb+++ b/app/controllers/api/v1/splits_controller.rb@@ -110,16 +110,11 @@ class Api::V1::SplitsController < Api::V1::BaseController# The token scope says what the KEY may do; this says what its owner may do# to this account. `Account.accessible_by` admits every share, read-only# ones included, so without this a read-only share could rewrite someone- # else's transaction. SplitsController enforces the same thing through- # require_account_permission!.+ # else's transaction.def ensure_account_write_permissionreturn if performed?- return if @entry.account.permission_for(current_resource_owner).in?([ :owner, :full_control ])- render json: {- error: "forbidden",- message: "You do not have write access to this account"- }, status: :forbidden+ require_api_account_permission!(@entry.account, :write)enddef set_transactiondiff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rbindex 46e69b1d39..46c9a32cd1 100644--- a/app/controllers/api/v1/transactions_controller.rb+++ b/app/controllers/api/v1/transactions_controller.rb@@ -8,6 +8,7 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerbefore_action :ensure_read_scope, only: [ :index, :show ]before_action :ensure_write_scope, only: [ :create, :update, :destroy ]before_action :set_transaction, only: [ :show, :update, :destroy ]+ before_action :ensure_write_permission, only: [ :update, :destroy ]def indexfamily = current_resource_owner.family@@ -221,6 +222,27 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerload_accessible_transaction(params[:id])end+ # Reading needs access to the account. Deleting, or changing anything+ # outside the annotate fields, needs the write tier (AccountPolicy#update?);+ # a member in the annotate tier may only change the AccountShare annotate+ # fields (notes, category, merchant, tags), the same split the web UI+ # applies in TransactionsController#permitted_entry_params. A refused request is a 403,+ # not a silently trimmed update, so the client learns nothing was applied.+ def ensure_write_permission+ level = action_name == "update" && annotate_only_update? ? :annotate : :write++ require_api_account_permission!(@entry.account, level, resource: "transaction")+ end++ # Judged on the permitted params, not raw params: keys outside+ # transaction_params are ignored on update for every role (account_id+ # included), so they cannot widen what an annotate-tier member changes.+ def annotate_only_update?+ transaction_params.except(+ *AccountShare::ANNOTATE_ENTRY_ATTRIBUTES, *AccountShare::ANNOTATE_TRANSACTION_ATTRIBUTES+ ).empty?+ end+def ensure_read_scopeauthorize_scope!(:read)enddiff --git a/app/controllers/concerns/account_authorizable.rb b/app/controllers/concerns/account_authorizable.rbindex 8c051446fd..2b2279bb59 100644--- a/app/controllers/concerns/account_authorizable.rb+++ b/app/controllers/concerns/account_authorizable.rb@@ -8,16 +8,7 @@ module AccountAuthorizableprivatedef require_account_permission!(account, level = :write, redirect_path: nil)- permission = account.permission_for(Current.user)-- allowed = case level- when :write then permission.in?([ :owner, :full_control ])- when :annotate then permission == :owner || permission.to_s.in?(AccountShare::ANNOTATE_PERMISSIONS)- when :owner then permission == :owner- else false- end-- return true if allowed+ return true if AccountPolicy.new(Current.user, account).permits?(level)path = redirect_path || account_path(account)respond_to do |format|diff --git a/app/policies/account_policy.rb b/app/policies/account_policy.rbindex 2d1e5a036a..4364adc343 100644--- a/app/policies/account_policy.rb+++ b/app/policies/account_policy.rb@@ -9,15 +9,27 @@ class AccountPolicy < ApplicationPolicyuser.member? || user.admin?end+ # Full write tier: owner and full_control.def update?- permission = record.permission_for(user)- permission.in?([ :owner, :full_control ])+ record.permission_for(user).in?([ :owner, :full_control ])end- # For read_write users: categorize, tag, add notes/receipts on transactions+ # Annotate tier (categorize, tag, add notes/merchant): the owner plus every+ # share tier in AccountShare::ANNOTATE_PERMISSIONS.def annotate?permission = record.permission_for(user)- permission.in?([ :owner, :full_control, :read_write ])+ permission == :owner || permission.to_s.in?(AccountShare::ANNOTATE_PERMISSIONS)+ end++ # Maps the level names used by controllers (:write, :annotate, :owner) onto+ # the predicates above, so controller concerns share one mapping.+ def permits?(level)+ case level+ when :write then update?+ when :annotate then annotate?+ when :owner then record.owned_by?(user)+ else false+ endend# Only the owner can delete the account itself.diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex f521a60fdb..ea27d10cf6 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -10854,6 +10854,13 @@ paths:application/json:schema:"$ref": "#/components/schemas/Transaction"+ '403':+ description: account is shared with you without permission to change this+ transaction+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"'404':description: transaction not foundcontent:@@ -10929,6 +10936,12 @@ paths:application/json:schema:"$ref": "#/components/schemas/DeleteResponse"+ '403':+ description: account is shared with you without full control+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"'404':description: transaction not foundcontent:diff --git a/spec/requests/api/v1/transactions_spec.rb b/spec/requests/api/v1/transactions_spec.rbindex 4419af1cee..48a8bbb99c 100644--- a/spec/requests/api/v1/transactions_spec.rb+++ b/spec/requests/api/v1/transactions_spec.rb@@ -33,6 +33,26 @@ RSpec.describe 'API V1 Transactions', type: :request dolet(:'X-Api-Key') { api_key.plain_key }+ let(:read_only_transaction) do+ owner = family.users.create!(+ email: '[email protected]',+ password: 'password123',+ password_confirmation: 'password123'+ )+ shared_account = Account.create!(+ family: family,+ owner: owner,+ name: 'Shared Checking',+ balance: 1000,+ currency: 'USD',+ accountable: Depository.new+ )+ shared_account.account_shares.create!(user: user, permission: 'read_only', include_in_finances: true)+ shared_account.entries.create!(+ name: 'Shared transaction', amount: 10, currency: 'USD', date: Date.current, entryable: Transaction.new+ ).transaction+ end+let(:account) doAccount.create!(family: family,@@ -343,6 +363,14 @@ RSpec.describe 'API V1 Transactions', type: :request dorun_test!end+ response '403', 'account is shared with you without permission to change this transaction' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:id) { read_only_transaction.id }++ run_test!+ end+response '404', 'transaction not found' doschema '$ref' => '#/components/schemas/ErrorResponse'@@ -373,6 +401,14 @@ RSpec.describe 'API V1 Transactions', type: :request dorun_test!end+ response '403', 'account is shared with you without full control' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:id) { read_only_transaction.id }++ run_test!+ end+response '404', 'transaction not found' doschema '$ref' => '#/components/schemas/ErrorResponse'diff --git a/test/controllers/api/v1/splits_controller_test.rb b/test/controllers/api/v1/splits_controller_test.rbindex 8834c522e8..6658886f21 100644--- a/test/controllers/api/v1/splits_controller_test.rb+++ b/test/controllers/api/v1/splits_controller_test.rb@@ -196,6 +196,7 @@ class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTestpost api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(key), as: :jsonassert_response :forbidden+ assert_equal "You do not have write access to this account", JSON.parse(response.body)["message"]assert_not @entry.reload.split_parent?enddiff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex 338ea7c1de..1b93023379 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -1262,6 +1262,100 @@ endassert_response :unauthorizedend+ # Shared-account permission tests+ test "a member with read-only access can read but not change or delete a shared transaction" do+ key, entry = shared_member_key_and_entry("read_only")++ get api_v1_transaction_url(entry.transaction), headers: api_headers(key)+ assert_response :success++ patch api_v1_transaction_url(entry.transaction), params: { transaction: { notes: "hi" } }, headers: api_headers(key)+ assert_response :forbidden+ assert_nil entry.reload.notes++ assert_no_difference "Entry.count" do+ delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)+ end+ assert_response :forbidden+ assert_equal "You do not have permission to delete this transaction", JSON.parse(response.body)["message"]+ end++ test "a read_write member can annotate but not change financial fields or delete" do+ key, entry = shared_member_key_and_entry("read_write")++ patch api_v1_transaction_url(entry.transaction), params: { transaction: { notes: "annotated" } }, headers: api_headers(key)+ assert_response :success+ assert_equal "annotated", entry.reload.notes++ [ { amount: 999 }, { name: "Renamed" }, { date: 3.days.ago.to_date }, { notes: "x", amount: 999 } ].each do |attrs|+ patch api_v1_transaction_url(entry.transaction), params: { transaction: attrs }, headers: api_headers(key)+ assert_response :forbidden, "expected #{attrs.keys} to be refused"+ end+ assert_equal "annotated", entry.reload.notes+ assert_equal 42, entry.amount++ assert_no_difference "Entry.count" do+ delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)+ end+ assert_response :forbidden+ end++ test "a read_write member can change category, merchant and tags" do+ key, entry = shared_member_key_and_entry("read_write")+ category = @user.family.categories.first+ merchant = @user.family.merchants.first || FamilyMerchant.create!(family: @user.family, name: "Shared Cafe")+ tag = @user.family.tags.first || @user.family.tags.create!(name: "shared-tag")++ patch api_v1_transaction_url(entry.transaction),+ params: { transaction: { category_id: category.id, merchant_id: merchant.id, tag_ids: [ tag.id ] } },+ headers: api_headers(key)++ assert_response :success+ transaction = entry.transaction.reload+ assert_equal category.id, transaction.category_id+ assert_equal merchant.id, transaction.merchant_id+ assert_equal [ tag.id ], transaction.tag_ids+ end++ test "a read_write member cannot change description or user_modified" do+ key, entry = shared_member_key_and_entry("read_write")++ [ { description: "Renamed" }, { user_modified: true } ].each do |attrs|+ patch api_v1_transaction_url(entry.transaction), params: { transaction: attrs }, headers: api_headers(key)+ assert_response :forbidden, "expected #{attrs.keys} to be refused"+ assert_equal "forbidden", JSON.parse(response.body)["error"]+ assert_equal "You do not have permission to change this transaction", JSON.parse(response.body)["message"]+ end+ assert_equal "Shared txn", entry.reload.name+ end++ test "unpermitted keys are ignored for a read_write member, account_id included" do+ key, entry = shared_member_key_and_entry("read_write")+ other = @user.family.accounts.create!(name: "Other", owner: @user, balance: 0, currency: "USD", accountable: Depository.new)++ patch api_v1_transaction_url(entry.transaction),+ params: { transaction: { notes: "kept", account_id: other.id } },+ headers: api_headers(key)++ assert_response :success+ entry.reload+ assert_equal "kept", entry.notes+ assert_not_equal other.id, entry.account_id+ end++ test "a full_control member can change and delete a shared transaction" do+ key, entry = shared_member_key_and_entry("full_control")++ patch api_v1_transaction_url(entry.transaction), params: { transaction: { name: "Renamed" } }, headers: api_headers(key)+ assert_response :success+ assert_equal "Renamed", entry.reload.name++ assert_difference "Entry.count", -1 do+ delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)+ end+ assert_response :success+ end+# JSON structure teststest "transaction JSON should have expected structure" doget api_v1_transaction_url(@transaction), headers: api_headers(@api_key)@@ -1466,6 +1560,19 @@ endcurrency: "USD", nature: "expense" }.merge(references)end+ def shared_member_key_and_entry(permission)+ 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}")++ account = member.family.accounts.create!(name: "Admin Shared Checking", owner: @user, balance: 1_000,+ currency: "USD", accountable: Depository.new)+ account.account_shares.create!(user: member, permission: permission, include_in_finances: true)+ entry = account.entries.create!(name: "Shared txn", amount: 42, currency: "USD", date: Date.current, entryable: Transaction.new)+ [ key, entry ]+ end+def api_headers(api_key){ "X-Api-Key" => api_key.display_key }enddiff --git a/test/policies/account_policy_test.rb b/test/policies/account_policy_test.rbnew file mode 100644index 0000000000..7e52aede33--- /dev/null+++ b/test/policies/account_policy_test.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++require "test_helper"++class AccountPolicyTest < ActiveSupport::TestCase+ setup do+ @owner = users(:family_admin)+ @member = users(:family_member)+ @account = @owner.family.accounts.create!(+ name: "Policy Checking", owner: @owner, balance: 100, currency: "USD", accountable: Depository.new+ )+ end++ test "owner may update and annotate" do+ assert_tiers @owner, update: true, annotate: true+ end++ test "full_control may update and annotate" do+ share("full_control")+ assert_tiers @member, update: true, annotate: true+ end++ test "read_write may annotate but not update" do+ share("read_write")+ assert_tiers @member, update: false, annotate: true+ end++ test "read_only may do neither" do+ share("read_only")+ assert_tiers @member, update: false, annotate: false+ end++ test "a user with no share may do neither" do+ assert_tiers @member, update: false, annotate: false+ end++ test "permits? maps levels onto the tier predicates" do+ assert AccountPolicy.new(@owner, @account).permits?(:owner)+ assert AccountPolicy.new(@owner, @account).permits?(:write)++ share("full_control")+ policy = AccountPolicy.new(@member, @account)+ assert policy.permits?(:write)+ assert policy.permits?(:annotate)+ assert_not policy.permits?(:owner), ":owner is owner-only, even for full_control"++ assert_not policy.permits?(:bogus), "unknown levels are denied"+ assert_not policy.permits?("write"), "levels are symbols; a string is denied"+ end++ private++ def share(permission)+ @account.account_shares.create!(user: @member, permission: permission, include_in_finances: true)+ end++ def assert_tiers(user, update:, annotate:)+ policy = AccountPolicy.new(user, @account)+ assert_equal update, policy.update?, "update?"+ assert_equal annotate, policy.annotate?, "annotate?"+ end+end