Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(api): require a writable account when creating or preflighting an import (#4000)

GFR4eac575d46d3
diff --git a/app/controllers/api/v1/imports_controller.rb b/app/controllers/api/v1/imports_controller.rb
index 9429802b7e..93275837cf 100644
--- a/app/controllers/api/v1/imports_controller.rb
+++ b/app/controllers/api/v1/imports_controller.rb
@@ -81,7 +81,21 @@ class Api::V1::ImportsController < Api::V1::BaseController
# 2. Build the import object with permitted config attributes
@import = family.imports.build(import_config_params.merge(type: type))
- @import.account_id = params[:account_id] if params[:account_id].present?
+
+ # The target account must be one the API user can write to.
+ if params[:account_id].present?
+ account = visible_import_account
+ unless account
+ return render json: {
+ error: "validation_failed",
+ message: "Import could not be created",
+ errors: [ "Account not found" ]
+ }, status: :unprocessable_entity
+ end
+ return unless require_api_account_permission!(account)
+
+ @import.account = account
+ end
# 3. Attach the uploaded file if present (with validation)
if params[:file].present?
@@ -151,6 +165,12 @@ class Api::V1::ImportsController < Api::V1::BaseController
end
def preflight
+ if params[:account_id].present?
+ account = visible_import_account
+ raise ActiveRecord::RecordNotFound unless account
+ return unless require_api_account_permission!(account)
+ end
+
preflight_result = Import::Preflight.new(family: current_resource_owner.family, params: preflight_params).call
render json: preflight_result.payload, status: preflight_result.status
rescue ActiveRecord::RecordNotFound
@@ -235,6 +255,18 @@ class Api::V1::ImportsController < Api::V1::BaseController
)
end
+ # The import's target account, when the API user can see it. Unknown,
+ # malformed, cross-family and unshared ids all give nil, so the response
+ # does not reveal which accounts exist; a visible account the user cannot
+ # write to is then a 403, as in the rest of the API.
+ def visible_import_account
+ return unless valid_uuid?(params[:account_id])
+
+ current_resource_owner.family.accounts
+ .accessible_by(current_resource_owner)
+ .find_by(id: params[:account_id])
+ end
+
def preflight_params
params.permit(*Import::Preflight::PARAM_KEYS)
end
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index baf61043fc..e0a3520a5b 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -8171,7 +8171,8 @@ paths:
schema:
"$ref": "#/components/schemas/ImportResponse"
'403':
- description: guest users cannot import family configuration
+ description: guest users cannot import family configuration, or the account
+ is shared without write access
content:
application/json:
schema:
@@ -8224,7 +8225,8 @@ paths:
account_id:
type: string
format: uuid
- description: Account ID to import into
+ description: Account ID to import into. Must be an account the API
+ user can write to
publish:
type: string
description: Set to "true" to automatically queue for processing
@@ -8337,7 +8339,8 @@ paths:
account_id:
type: string
format: uuid
- description: Account ID to import into
+ description: Account ID to import into. Must be an account the API
+ user can write to
publish:
type: string
description: Set to "true" to automatically queue for processing
@@ -8539,6 +8542,12 @@ paths:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: account is shared with the user without write access
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
'404':
description: account not found
content:
@@ -8577,7 +8586,8 @@ paths:
account_id:
type: string
format: uuid
- description: Account ID used for account-scoped CSV import validation
+ description: Account ID used for account-scoped CSV import validation.
+ Must be an account the API user can write to
date_col_label:
type: string
description: CSV imports only. Header name for the date column
@@ -8690,7 +8700,8 @@ paths:
account_id:
type: string
format: uuid
- description: Account ID used for account-scoped CSV import validation
+ description: Account ID used for account-scoped CSV import validation.
+ Must be an account the API user can write to
date_col_label:
type: string
description: CSV imports only. Header name for the date column
diff --git a/spec/requests/api/v1/imports_spec.rb b/spec/requests/api/v1/imports_spec.rb
index 6c5cbbd64a..d9a331df41 100644
--- a/spec/requests/api/v1/imports_spec.rb
+++ b/spec/requests/api/v1/imports_spec.rb
@@ -47,6 +47,7 @@ RSpec.describe 'API V1 Imports', type: :request do
let(:account) do
Account.create!(
family: family,
+ owner: user,
name: 'Test Checking',
balance: 1000,
currency: 'USD',
@@ -144,7 +145,7 @@ RSpec.describe 'API V1 Imports', type: :request do
account_id: {
type: :string,
format: :uuid,
- description: 'Account ID to import into'
+ description: 'Account ID to import into. Must be an account the API user can write to'
},
publish: {
type: :string,
@@ -250,7 +251,7 @@ RSpec.describe 'API V1 Imports', type: :request do
run_test!
end
- response '403', 'guest users cannot import family configuration' do
+ response '403', 'guest users cannot import family configuration, or the account is shared without write access' do
schema oneOf: [
{ '$ref' => '#/components/schemas/ErrorResponse' },
{ '$ref' => '#/components/schemas/ErrorResponseWithImportId' }
@@ -426,7 +427,7 @@ RSpec.describe 'API V1 Imports', type: :request do
account_id: {
type: :string,
format: :uuid,
- description: 'Account ID used for account-scoped CSV import validation'
+ description: 'Account ID used for account-scoped CSV import validation. Must be an account the API user can write to'
},
date_col_label: { type: :string, description: 'CSV imports only. Header name for the date column' },
amount_col_label: { type: :string, description: 'CSV imports only. Header name for the amount column' },
@@ -506,6 +507,33 @@ RSpec.describe 'API V1 Imports', type: :request do
run_test!
end
+ response '403', 'account is shared with the user without write access' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:read_only_account) do
+ owner = family.users.create!(
+ email: '[email protected]',
+ password: 'password123',
+ password_confirmation: 'password123'
+ )
+ Account.create!(
+ family: family,
+ owner: owner,
+ name: 'Shared Checking',
+ balance: 1000,
+ currency: 'USD',
+ accountable: Depository.new
+ ).tap { |shared| shared.account_shares.create!(user: user, permission: 'read_only') }
+ end
+ let(:body) do
+ {
+ raw_file_content: "date,amount,name\n01/15/2024,50.00,New Transaction",
+ account_id: read_only_account.id
+ }
+ end
+
+ run_test!
+ end
+
response '404', 'account not found' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
diff --git a/test/controllers/api/v1/imports_controller_test.rb b/test/controllers/api/v1/imports_controller_test.rb
index 3cb9f5c195..223eacb058 100644
--- a/test/controllers/api/v1/imports_controller_test.rb
+++ b/test/controllers/api/v1/imports_controller_test.rb
@@ -723,6 +723,43 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_empty data["errors"]
end
+ test "should not preflight against an account the user cannot write" do
+ member = users(:family_member)
+ member.api_keys.active.destroy_all
+ member_key = ApiKey.create!(
+ user: member,
+ name: "Member Read-Write Key",
+ scopes: [ "read_write" ],
+ source: "web",
+ display_key: "test_member_rw_#{SecureRandom.hex(8)}"
+ )
+ Redis.new.del("api_rate_limit:#{member_key.id}")
+ csv_content = "date,amount,name\n2023-01-01,-10.00,Test Transaction"
+ preflight = ->(account) do
+ post preflight_api_v1_imports_url,
+ params: {
+ raw_file_content: csv_content,
+ date_col_label: "date",
+ amount_col_label: "amount",
+ name_col_label: "name",
+ account_id: account.id
+ },
+ headers: api_headers(member_key)
+ end
+
+ # Not shared with the member: answered like an unknown id.
+ preflight.call(accounts(:investment))
+ assert_response :not_found
+
+ # Shared read only: visible, but not writable.
+ preflight.call(accounts(:credit_card))
+ assert_response :forbidden
+ assert_equal "forbidden", JSON.parse(response.body)["error"]
+
+ preflight.call(accounts(:depository))
+ assert_response :success
+ end
+
test "should report missing required CSV headers during preflight" do
csv_content = "name\nMissing Amount"
@@ -1320,7 +1357,22 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
json_response = JSON.parse(response.body)
- assert_includes json_response["errors"], "Account must belong to your family"
+ assert_equal [ "Account not found" ], json_response["errors"]
+ end
+
+ test "should not create import for unknown or malformed account id" do
+ csv_content = "date,amount,name\n2023-01-01,-10.00,Test Transaction"
+
+ [ SecureRandom.uuid, "not-a-uuid" ].each do |account_id|
+ assert_no_difference("Import.count") do
+ post api_v1_imports_url,
+ params: { raw_file_content: csv_content, account_id: account_id },
+ headers: api_headers(@api_key)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal [ "Account not found" ], JSON.parse(response.body)["errors"]
+ end
end
test "should reject file upload exceeding max size" do
@@ -1400,6 +1452,45 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_response :created
end
+ test "should not create import for account the user cannot write" do
+ member = users(:family_member)
+ member.api_keys.active.destroy_all
+ member_key = ApiKey.create!(
+ user: member,
+ name: "Member Read-Write Key",
+ scopes: [ "read_write" ],
+ source: "web",
+ display_key: "test_member_rw_#{SecureRandom.hex(8)}"
+ )
+ Redis.new.del("api_rate_limit:#{member_key.id}")
+ csv_content = "date,amount,name\n2023-01-01,-10.00,Test Transaction"
+
+ create_import = ->(account) do
+ post api_v1_imports_url,
+ params: {
+ raw_file_content: csv_content,
+ date_col_label: "date",
+ amount_col_label: "amount",
+ name_col_label: "name",
+ account_id: account.id
+ },
+ headers: api_headers(member_key)
+ end
+
+ # Not shared with the member: answered like an unknown id.
+ assert_no_difference("Import.count") { create_import.call(accounts(:investment)) }
+ assert_response :unprocessable_entity
+ assert_equal [ "Account not found" ], JSON.parse(response.body)["errors"]
+
+ # Shared read only: visible, but not writable.
+ assert_no_difference("Import.count") { create_import.call(accounts(:credit_card)) }
+ assert_response :forbidden
+ assert_equal "forbidden", JSON.parse(response.body)["error"]
+
+ assert_difference("Import.count", 1) { create_import.call(accounts(:depository)) }
+ assert_response :created
+ end
+
private
def build_ndjson(records)