Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Close remaining Active Storage access gaps for receipts, previews and exports (#4205)

GFRcea0986c7e49
diff --git a/app/controllers/api/v1/family_exports_controller.rb b/app/controllers/api/v1/family_exports_controller.rb
index e3ad3fcfb3..1647570e01 100644
--- a/app/controllers/api/v1/family_exports_controller.rb
+++ b/app/controllers/api/v1/family_exports_controller.rb
@@ -2,6 +2,7 @@
class Api::V1::FamilyExportsController < Api::V1::BaseController
include Pagy::Backend
+ include ActiveStorage::Streaming
before_action :ensure_read_scope, only: [ :index, :show, :download ]
before_action :ensure_write_scope, only: [ :create ]
@@ -68,10 +69,14 @@ class Api::V1::FamilyExportsController < Api::V1::BaseController
return
end
- redirect_to rails_blob_url(@family_export.export_file, disposition: "attachment"), allow_other_host: true
+ # API keys carry no session, which the blob routes require, so the file is sent here.
+ send_blob_stream @family_export.export_file.blob, disposition: :attachment
rescue StandardError => e
Rails.logger.error "FamilyExportsController#download error: #{e.message}"
Rails.logger.error e.backtrace.join("\n")
+ # send_blob_stream has already answered with a bare 500; rendering JSON on
+ # top of it would raise DoubleRenderError.
+ return if performed?
render json: {
error: "internal_server_error",
diff --git a/app/controllers/archived_exports_controller.rb b/app/controllers/archived_exports_controller.rb
index f626141a6c..8606db198e 100644
--- a/app/controllers/archived_exports_controller.rb
+++ b/app/controllers/archived_exports_controller.rb
@@ -1,11 +1,15 @@
class ArchivedExportsController < ApplicationController
+ include ActiveStorage::Streaming
+
skip_authentication
+ # The archive's family is gone, so the token holder has no session for the
+ # blob routes; the token is the only credential and the file is sent here.
def show
export = ArchivedExport.find_by_download_token!(params[:token])
if export.downloadable?
- redirect_to rails_blob_path(export.export_file, disposition: "attachment")
+ send_blob_stream export.export_file.blob, disposition: :attachment
else
head :gone
end
diff --git a/config/initializers/active_storage_authorization.rb b/config/initializers/active_storage_authorization.rb
index c33f53c54a..7f4babda80 100644
--- a/config/initializers/active_storage_authorization.rb
+++ b/config/initializers/active_storage_authorization.rb
@@ -19,6 +19,10 @@ Rails.application.config.to_prepare do
attachments = authorized_attachments
raise ActiveRecord::RecordNotFound if attachments.empty?
+ # Archived exports belong to no family; ArchivedExportsController releases them by download token only.
+ raise ActiveRecord::RecordNotFound if attachments.any? { |attachment| attachment.record_type == "ArchivedExport" }
+ # Family exports hold the whole family's data; FamilyExportsController releases them to family admins only.
+ raise ActiveRecord::RecordNotFound if attachments.any? { |attachment| attachment.record_type == "FamilyExport" && !family_admin_export?(attachment) }
protected_attachments = attachments.select { |attachment| attachment.record_type.in?(PROTECTED_RECORD_TYPES) }
return if protected_attachments.empty?
@@ -44,11 +48,13 @@ Rails.application.config.to_prepare do
end
end
+ # Mirrors TransactionAttachmentsController#set_transaction: the account must be shared with the user.
def transaction_attachment_authorized?(attachment)
transaction = attachment.record
return false if transaction.nil?
- Current.family == transaction.entry.account.family
+ account = transaction.entry.account
+ account.family_id == Current.family&.id && account.shared_with?(Current.user)
rescue ActiveRecord::RecordNotFound, NoMethodError
false
end
@@ -94,7 +100,7 @@ Rails.application.config.to_prepare do
def authorized_attachments
return nil unless authorized_blob
- @authorized_attachments ||= ActiveStorage::Attachment.where(blob: authorized_blob).to_a
+ @authorized_attachments ||= attachments_with_sources(authorized_blob)
end
def authorized_blob
@@ -108,11 +114,50 @@ Rails.application.config.to_prepare do
return nil if key.blank?
blob_key = key.to_s[%r{\Avariants/([^/]+)/}, 1] || key
- ActiveStorage::Blob.find_by(key: blob_key)
+ # A signed key whose blob row is gone (e.g. purged, file not yet deleted) must not bypass the checks.
+ ActiveStorage::Blob.find_by!(key: blob_key)
rescue ActiveStorage::InvalidKeyError
nil
end
+ # Tracked variants and previews are blobs of their own, attached to an
+ # ActiveStorage::VariantRecord or to their source blob. They are authorized
+ # through the attachments of the blob they were made from; a variant of a
+ # preview is two steps away from its source.
+ MAX_DERIVED_BLOB_DEPTH = 2
+
+ def attachments_with_sources(blob, depth = 0)
+ ActiveStorage::Attachment.where(blob: blob).to_a.flat_map do |attachment|
+ next [ attachment ] unless derived_attachment?(attachment)
+
+ source = derived_source_blob(attachment)
+ raise ActiveRecord::RecordNotFound if source.nil? || depth >= MAX_DERIVED_BLOB_DEPTH
+
+ attachments_with_sources(source, depth + 1)
+ end
+ end
+
+ def derived_attachment?(attachment)
+ attachment.record_type == "ActiveStorage::VariantRecord" ||
+ (attachment.record_type == "ActiveStorage::Blob" && attachment.name == "preview_image")
+ end
+
+ def derived_source_blob(attachment)
+ record = attachment.record
+ record.is_a?(ActiveStorage::VariantRecord) ? record.blob : record
+ rescue ActiveRecord::RecordNotFound
+ nil
+ end
+
+ def family_admin_export?(attachment)
+ export = attachment.record
+ return false if export.nil?
+
+ export.family_id == Current.family&.id && Current.user.admin?
+ rescue ActiveRecord::RecordNotFound, NoMethodError
+ false
+ end
+
def new_session_url
Rails.application.routes.url_helpers.new_session_url(active_storage_auth_url_options)
end
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 7f79de449e..707360dd0f 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -6086,8 +6086,13 @@ paths:
security:
- apiKeyAuth: []
responses:
- '302':
- description: family export download redirected
+ '200':
+ description: family export zip file
+ content:
+ application/zip:
+ schema:
+ type: string
+ format: binary
'401':
description: unauthorized
content:
diff --git a/spec/requests/api/v1/family_exports_spec.rb b/spec/requests/api/v1/family_exports_spec.rb
index df3b140c7d..f9101f002e 100644
--- a/spec/requests/api/v1/family_exports_spec.rb
+++ b/spec/requests/api/v1/family_exports_spec.rb
@@ -124,7 +124,12 @@ RSpec.describe "Api::V1::FamilyExports", type: :request do
security [ apiKeyAuth: [] ]
produces "application/json"
- response "302", "family export download redirected" do
+ response "200", "family export zip file" do
+ # The file is streamed as application/zip; only the error responses are JSON.
+ metadata[:response][:content] = {
+ "application/zip" => { schema: { type: :string, format: :binary } }
+ }
+
before do
family_export.export_file.attach(
io: StringIO.new("test zip content"),
diff --git a/test/controllers/api/v1/family_exports_controller_test.rb b/test/controllers/api/v1/family_exports_controller_test.rb
index ec16da07c8..e269a71096 100644
--- a/test/controllers/api/v1/family_exports_controller_test.rb
+++ b/test/controllers/api/v1/family_exports_controller_test.rb
@@ -143,7 +143,7 @@ class Api::V1::FamilyExportsControllerTest < ActionDispatch::IntegrationTest
assert_equal "record_not_found", JSON.parse(response.body)["error"]
end
- test "redirects completed export downloads to the attached file" do
+ test "sends completed export downloads without a session" do
export = @family.family_exports.create!(status: "completed")
export.export_file.attach(
io: StringIO.new("test zip content"),
@@ -152,9 +152,10 @@ class Api::V1::FamilyExportsControllerTest < ActionDispatch::IntegrationTest
)
get download_api_v1_family_export_url(export), headers: api_headers(@read_only_api_key)
- assert_response :redirect
- assert_includes response.location, "/rails/active_storage/blobs/redirect/"
- assert_includes response.location, "test.zip"
+ assert_response :success
+ assert_equal "test zip content", response.body
+ assert_equal "application/zip", response.media_type
+ assert_match(/\Aattachment; filename="test.zip"/, response.headers["Content-Disposition"])
end
test "download returns conflict when export is not ready" do
@@ -167,7 +168,7 @@ class Api::V1::FamilyExportsControllerTest < ActionDispatch::IntegrationTest
assert_equal "export_not_ready", json_response["error"]
end
- test "download handles storage URL failures without leaking details" do
+ test "download handles storage failures without leaking details" do
export = @family.family_exports.create!(status: "completed")
export.export_file.attach(
io: StringIO.new("test zip content"),
@@ -175,16 +176,13 @@ class Api::V1::FamilyExportsControllerTest < ActionDispatch::IntegrationTest
content_type: "application/zip"
)
- Api::V1::FamilyExportsController.any_instance
- .stubs(:rails_blob_url)
+ ActiveStorage::Blob.any_instance
+ .stubs(:download)
.raises(StandardError, "storage down")
get download_api_v1_family_export_url(export), headers: api_headers(@read_only_api_key)
+ # The file is streamed, so a storage failure ends the response with a bare 500.
assert_response :internal_server_error
-
- json_response = JSON.parse(response.body)
- assert_equal "internal_server_error", json_response["error"]
- assert_equal "An unexpected error occurred", json_response["message"]
assert_not_includes response.body, "storage down"
end
diff --git a/test/controllers/archived_exports_controller_test.rb b/test/controllers/archived_exports_controller_test.rb
index 0e23cb2867..258907eb13 100644
--- a/test/controllers/archived_exports_controller_test.rb
+++ b/test/controllers/archived_exports_controller_test.rb
@@ -1,7 +1,7 @@
require "test_helper"
class ArchivedExportsControllerTest < ActionDispatch::IntegrationTest
- test "redirects to file with valid token" do
+ test "sends the file with a valid token" do
archive = ArchivedExport.create!(
family_name: "Test",
@@ -14,7 +14,10 @@ class ArchivedExportsControllerTest < ActionDispatch::IntegrationTest
)
get archived_export_path(token: archive.download_token)
- assert_response :redirect
+ assert_response :success
+ assert_equal "test zip content", response.body
+ assert_equal "application/zip", response.media_type
+ assert_match(/\Aattachment; filename="test.zip"/, response.headers["Content-Disposition"])
end
test "returns 410 gone for expired token" do
@@ -52,6 +55,43 @@ class ArchivedExportsControllerTest < ActionDispatch::IntegrationTest
# No sign_in call - should still work
get archived_export_path(token: archive.download_token)
- assert_response :redirect
+ assert_response :success
+ assert_equal "test zip content", response.body
+ end
+
+ test "blob routes do not serve archived exports to signed-in users" do
+ archive = ArchivedExport.create!(
+ email: "[email protected]",
+ family_name: "Test",
+ expires_at: 30.days.from_now
+ )
+ archive.export_file.attach(
+ io: StringIO.new("test zip content"),
+ filename: "test.zip",
+ content_type: "application/zip"
+ )
+
+ sign_in users(:family_admin)
+ get rails_blob_path(archive.export_file)
+
+ assert_response :not_found
+ end
+
+ test "returns not found when the archive file is missing from storage" do
+ archive = ArchivedExport.create!(
+ email: "[email protected]",
+ family_name: "Test",
+ expires_at: 30.days.from_now
+ )
+ archive.export_file.attach(
+ io: StringIO.new("test zip content"),
+ filename: "test.zip",
+ content_type: "application/zip"
+ )
+ ActiveStorage::Blob.any_instance.stubs(:download).raises(ActiveStorage::FileNotFoundError)
+
+ get archived_export_path(token: archive.download_token)
+
+ assert_response :not_found
end
end
diff --git a/test/integration/active_storage_derived_blob_authorization_test.rb b/test/integration/active_storage_derived_blob_authorization_test.rb
new file mode 100644
index 0000000000..ecf45557c5
--- /dev/null
+++ b/test/integration/active_storage_derived_blob_authorization_test.rb
@@ -0,0 +1,184 @@
+require "test_helper"
+
+# Receipts follow account sharing, and variant/preview blobs follow the blob they were made from.
+class ActiveStorageDerivedBlobAuthorizationTest < ActionDispatch::IntegrationTest
+ include EntriesTestHelper
+
+ setup do
+ @owner = users(:family_admin)
+ @member = users(:family_member)
+ @outsider = users(:empty)
+
+ @receipt_transaction = transactions(:one) # depository, shared with family_member
+ @receipt = attach_image(@receipt_transaction)
+ end
+
+ test "member cannot access a receipt on an account that is not shared with them" do
+ entry = create_transaction(account: accounts(:other_asset))
+ receipt = attach_pdf(entry.transaction)
+
+ sign_in @member
+ get rails_blob_path(receipt)
+
+ assert_response :not_found
+ end
+
+ test "member can access a receipt on an account shared with them" do
+ sign_in @member
+ get rails_blob_path(@receipt)
+
+ assert_response :redirect
+ follow_redirect!
+ assert_response :success
+ end
+
+ test "tracked variant disk urls follow the source receipt" do
+ disk_url = disk_url_for(rails_representation_path(@receipt.variant(resize_to_limit: [ 50, 50 ])))
+
+ sign_in @outsider
+ get disk_url
+ assert_response :not_found
+
+ sign_out @outsider
+ sign_in @owner
+ get disk_url
+ assert_response :success
+ end
+
+ test "tracked variant blobs follow the source receipt" do
+ variant = @receipt.variant(resize_to_limit: [ 50, 50 ]).processed
+ variant_blob = variant.image.blob
+
+ sign_in @outsider
+ get rails_blob_path(variant_blob)
+ assert_response :not_found
+
+ sign_out @outsider
+ sign_in @owner
+ get rails_blob_path(variant_blob)
+ assert_response :redirect
+ end
+
+ test "member cannot access previews of a receipt on an account that is not shared with them" do
+ entry = create_transaction(account: accounts(:other_asset))
+ preview = attach_preview(attach_pdf(entry.transaction).blob)
+ variant_blob = preview.variant(resize_to_limit: [ 20, 20 ]).processed.image.blob
+
+ sign_in @member
+ get rails_blob_path(preview)
+ assert_response :not_found
+
+ get rails_blob_path(variant_blob)
+ assert_response :not_found
+ end
+
+ test "member can access previews of a receipt on an account shared with them" do
+ preview = attach_preview(attach_pdf(@receipt_transaction).blob)
+
+ sign_in @member
+ get rails_blob_path(preview)
+
+ assert_response :redirect
+ end
+
+ test "preview images follow the source receipt" do
+ receipt = attach_pdf(@receipt_transaction)
+ preview = attach_preview(receipt.blob)
+
+ sign_in @outsider
+ get rails_blob_path(preview)
+ assert_response :not_found
+
+ sign_out @outsider
+ sign_in @owner
+ get rails_blob_path(preview)
+ assert_response :redirect
+ end
+
+ test "variants of preview images follow the source receipt" do
+ receipt = attach_pdf(@receipt_transaction)
+ preview = attach_preview(receipt.blob)
+ variant_blob = preview.variant(resize_to_limit: [ 20, 20 ]).processed.image.blob
+
+ sign_in @outsider
+ get rails_blob_path(variant_blob)
+ assert_response :not_found
+
+ sign_out @outsider
+ sign_in @owner
+ get rails_blob_path(variant_blob)
+ assert_response :redirect
+ end
+
+ test "disk urls fail closed once the blob row is gone" do
+ blob = @receipt.blob
+ disk_url = ActiveStorage::Current.set(url_options: { host: "www.example.com" }) { blob.url }
+ # Drop the rows but keep the file, as between a purge and its file deletion.
+ ActiveStorage::Attachment.where(id: @receipt.id).delete_all
+ ActiveStorage::Blob.where(id: blob.id).delete_all
+ assert ActiveStorage::Blob.service.exist?(blob.key)
+
+ sign_in @owner
+ get disk_url
+
+ assert_response :not_found
+ end
+
+ test "preview images of unattached blobs fail closed" do
+ source = ActiveStorage::Blob.create_and_upload!(
+ io: StringIO.new("%PDF-1.4 orphan"),
+ filename: "orphan.pdf",
+ content_type: "application/pdf"
+ )
+ preview = attach_preview(source)
+
+ sign_in @owner
+ get rails_blob_path(preview)
+
+ assert_response :not_found
+ end
+
+ private
+
+ def attach_image(transaction)
+ transaction.attachments.attach(
+ io: File.open(Rails.root.join("test/fixtures/files/square-placeholder.png")),
+ filename: "receipt.png",
+ content_type: "image/png"
+ )
+ transaction.attachments.last
+ end
+
+ def attach_pdf(transaction)
+ transaction.attachments.attach(
+ io: StringIO.new("%PDF-1.4 Secret Receipt"),
+ filename: "receipt.pdf",
+ content_type: "application/pdf"
+ )
+ transaction.attachments.last
+ end
+
+ def attach_preview(blob)
+ blob.preview_image.attach(
+ io: File.open(Rails.root.join("test/fixtures/files/square-placeholder.png")),
+ filename: "receipt.png",
+ content_type: "image/png"
+ )
+ blob.preview_image
+ end
+
+ def sign_out(user)
+ user.sessions.destroy_all
+ end
+
+ # The representation route redirects to the variant's own disk url.
+ def disk_url_for(representation_path)
+ sign_in @owner
+ get representation_path
+ assert_response :redirect
+ url = response.location
+ assert_match(/rails\/active_storage\/disk/, url)
+ sign_out @owner
+ url
+ end
+end
diff --git a/test/integration/active_storage_family_export_authorization_test.rb b/test/integration/active_storage_family_export_authorization_test.rb
new file mode 100644
index 0000000000..8bfb49ceb3
--- /dev/null
+++ b/test/integration/active_storage_family_export_authorization_test.rb
@@ -0,0 +1,33 @@
+require "test_helper"
+
+# Family exports hold the whole family's data; the blob routes release them to family admins only.
+class ActiveStorageFamilyExportAuthorizationTest < ActionDispatch::IntegrationTest
+ setup do
+ @admin = users(:family_admin)
+ @export = @admin.family.family_exports.create!(status: :completed)
+ @export.export_file.attach(io: StringIO.new("zip"), filename: "export.zip", content_type: "application/zip")
+ end
+
+ test "family admin can download their family export" do
+ sign_in @admin
+ get rails_blob_path(@export.export_file)
+
+ assert_response :redirect
+ follow_redirect!
+ assert_response :success
+ end
+
+ test "user from another family cannot download the family export" do
+ sign_in users(:empty)
+ get rails_blob_path(@export.export_file)
+
+ assert_response :not_found
+ end
+
+ test "non-admin family member cannot download the family export" do
+ sign_in users(:family_member)
+ get rails_blob_path(@export.export_file)
+
+ assert_response :not_found
+ end
+end