Limit estimate and invoice PDFs by permission; clean up

Any logged-in user could open any estimate or invoice PDF by id. Now:
- estimates: View customers or Write estimates, or an estimate attached
  to an issue the user can see (the issue page links to it); users
  without the permission don't trigger a sync of uncached estimates
- invoices: View customers, Write invoices, View/Receive payments or
  Issue refunds, or invoices attached to issues the user can see
- share-link customers are unchanged (their own issue's documents)
- the sidebar's estimate search only shows to those who can use it

The issue PDF merges an estimate PDF with optional content, as it
already did for the issue's own PDF, instead of failing.

Removed dead code: the JSON branches of CustomersController#create
(Redmine refuses JSON there) and the scaffold views for
qbo#authenticate, #oauth_callback and #webhook, which those actions
never render. An invalid customer now shows the form with a 422.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-20 17:36:20 -05:00
1 parent 17f24f9641
commit b829593bc2
14 files changed
+167 -92

No files matched your search

+2 -13
View File
@@ -47,27 +47,16 @@ class CustomersController < ApplicationController
def create def create
@customer = Customer.new(allowed_params) @customer = Customer.new(allowed_params)
respond_to do |format|
if @customer.save if @customer.save
log "Customer ##{@customer.id} created successfully." log "Customer ##{@customer.id} created successfully."
format.html { redirect_to @customer, notice: l(:notice_successful_create) } redirect_to @customer, notice: l(:notice_successful_create)
format.json { render json: { id: @customer.id, name: @customer.name }, status: :created }
else else
format.html { render :new } render :new, status: :unprocessable_entity
format.json { render json: { errors: @customer.errors.full_messages }, status: :unprocessable_entity }
end
end end
rescue => e rescue => e
log "Failed to create customer: #{e.message}" log "Failed to create customer: #{e.message}"
respond_to do |format|
format.html {
flash[:error] = e.message flash[:error] = e.message
redirect_to new_customer_path redirect_to new_customer_path
}
format.json {
render json: { errors: [e.message] }, status: :internal_server_error
}
end
end end
def edit def edit
+12 -1
View File
@@ -10,7 +10,8 @@
class EstimatesController < ApplicationController class EstimatesController < ApplicationController
include AuthHelper include AuthHelper
# PDFs: logged-in users, or a customer with a share link (limited to their issue's estimate). # PDFs: logged-in users with View customers or Write estimates, other logged-in users for the estimates on
# issues they can see, and share-link customers for their issue's estimate.
# Redmine's own login check is replaced by require_login_or_customer_token for these actions. # Redmine's own login check is replaced by require_login_or_customer_token for these actions.
skip_before_action :check_if_login_required, only: [:show, :doc] skip_before_action :check_if_login_required, only: [:show, :doc]
before_action :require_login_or_customer_token, only: [:show, :doc] before_action :require_login_or_customer_token, only: [:show, :doc]
@@ -42,6 +43,7 @@ class EstimatesController < ApplicationController
# Share-link customers may only open the estimate attached to their issue (checked before any sync) # Share-link customers may only open the estimate attached to their issue (checked before any sync)
return load_customer_estimate if customer_token_only? return load_customer_estimate if customer_token_only?
return load_issue_estimate unless RedmineQboBilling.estimate_viewer?
@estimate = find_estimate || sync_and_find_estimate @estimate = find_estimate || sync_and_find_estimate
@@ -65,6 +67,15 @@ class EstimatesController < ApplicationController
@estimate = estimate @estimate = estimate
end end
# For logged-in users without a billing permission: only an estimate attached to an issue they can see,
# which is always cached locally (no sync from QuickBooks)
def load_issue_estimate
estimate = find_estimate
return render_403 unless estimate && estimate_pdf_allowed?(estimate)
@estimate = estimate
end
# Attempts to find the estimate locally by ID or doc number. # Attempts to find the estimate locally by ID or doc number.
def find_estimate def find_estimate
return Estimate.find_by(doc_number: params[:search]) if params[:search].present? return Estimate.find_by(doc_number: params[:search]) if params[:search].present?
+10 -1
View File
@@ -10,11 +10,13 @@
class InvoicesController < ApplicationController class InvoicesController < ApplicationController
include AuthHelper include AuthHelper
# PDFs: logged-in users, or a customer with a share link (limited to their issue's invoices). # PDFs: logged-in users with a billing permission (RedmineQboBilling.invoice_viewer?), other logged-in users for
# the invoices on issues they can see, and share-link customers for their issue's invoices.
# Redmine's own login check is replaced by require_login_or_customer_token for this action. # Redmine's own login check is replaced by require_login_or_customer_token for this action.
skip_before_action :check_if_login_required, only: :show skip_before_action :check_if_login_required, only: :show
before_action :require_login_or_customer_token, only: :show before_action :require_login_or_customer_token, only: :show
before_action :authorize_customer_invoices, only: :show before_action :authorize_customer_invoices, only: :show
before_action :authorize_user_invoices, only: :show
# Syncing is admin-only # Syncing is admin-only
before_action :require_admin, only: :sync before_action :require_admin, only: :sync
@@ -51,6 +53,13 @@ class InvoicesController < ApplicationController
render_403 if invoice_ids.empty? || (invoice_ids - allowed).any? render_403 if invoice_ids.empty? || (invoice_ids - allowed).any?
end end
# Logged-in users: a billing permission, or invoices attached to issues they can see
def authorize_user_invoices
return true unless User.current.logged?
render_403 unless invoice_pdfs_allowed?(invoice_ids)
end
# Logs messages with a consistent prefix for easier debugging. # Logs messages with a consistent prefix for easier debugging.
def log(msg) def log(msg)
Rails.logger.info "[InvoiceController] #{msg}" Rails.logger.info "[InvoiceController] #{msg}"
+15
View File
@@ -31,6 +31,21 @@ module AuthHelper
require_login require_login
end end
# A logged-in user may open the estimate's PDF with a billing permission (RedmineQboBilling.estimate_viewer?),
# or when it's attached to an issue they can see (the issue page links to it)
def estimate_pdf_allowed?(estimate)
RedmineQboBilling.estimate_viewer? || Issue.visible.where(estimate_id: estimate.id).exists?
end
# The same for invoices: every one of them must be attached to an issue the user can see
def invoice_pdfs_allowed?(invoice_ids)
return true if RedmineQboBilling.invoice_viewer?
ids = Array(invoice_ids).map(&:to_s).uniq
visible = Invoice.joins(:issues).merge(Issue.visible).where(id: ids).distinct.pluck(:id).map(&:to_s)
ids.any? && (ids - visible).empty?
end
def global_check_permission(permission) def global_check_permission(permission)
if !globaly_allowed_to?(permission) if !globaly_allowed_to?(permission)
flash[:error] = t :notice_forbidden flash[:error] = t :notice_forbidden
+2 -1
View File
@@ -4,6 +4,7 @@
<%= render partial: 'customers/sidebar' %> <%= render partial: 'customers/sidebar' %>
<% end %> <% end %>
<%= render partial: 'estimates/sidebar' %> <%# Finding an estimate by number needs View customers or Write estimates %>
<%= render partial: 'estimates/sidebar' if RedmineQboBilling.estimate_viewer? %>
<% end %> <% end %>
-32
View File
@@ -1,32 +0,0 @@
<!--
The MIT License (MIT)
Copyright (c) 2016 - 2026 rick barrette
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<h2>QboController#authenticate</h2>
<body>
<!-- REPLACE THE BODY of the default application.html.erb with this -->
<% unless session[:token] %>
<ipp:connectToIntuit></ipp:connectToIntuit>
<% end %>
<% if notice %>
<div style="padding: 10px;background: gainsboro;font-weight: 900;width: 50%;"><%= notice %></div>
<% end %>
<%= yield %>
<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
<script>
intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= authenticate_vendors_url %>'});
</script>
</body>
-13
View File
@@ -1,13 +0,0 @@
<!--
The MIT License (MIT)
Copyright (c) 2016 - 2026 rick barrette
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<h2>QboController#oauth_callback</h2>
-13
View File
@@ -1,13 +0,0 @@
<!--
The MIT License (MIT)
Copyright (c) 2016 - 2026 rick barrette
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<h2>QboController#webhook</h2>
+2 -1
View File
@@ -325,7 +325,8 @@ module RedmineQbo
if issue.estimate if issue.estimate
e_pdf, _ref = PdfService.new(entity: Estimate).fetch_pdf(doc_ids: [issue.estimate.id]) e_pdf, _ref = PdfService.new(entity: Estimate).fetch_pdf(doc_ids: [issue.estimate.id])
combined = CombinePDF.parse(pdf.output, allow_optional_content: true) combined = CombinePDF.parse(pdf.output, allow_optional_content: true)
combined << CombinePDF.parse(e_pdf) # The estimate may have optional content too (layers); merged the same way as the issue's PDF
combined << CombinePDF.parse(e_pdf, allow_optional_content: true)
combined.to_pdf combined.to_pdf
else else
pdf.output pdf.output
+13
View File
@@ -99,6 +99,19 @@ module RedmineQboBilling
writer?(user) && user.allowed_to?(:edit_linked_estimates, nil, global: true) writer?(user) && user.allowed_to?(:edit_linked_estimates, nil, global: true)
end end
# True when the user may open any estimate's PDF: View customers or Write estimates. Others open only the
# estimates attached to issues they can see (see AuthHelper#estimate_pdf_allowed?).
def self.estimate_viewer?(user = User.current)
user.allowed_to?(:view_customers, nil, global: true) || writer?(user)
end
# True when the user may open any invoice's PDF: View customers, Write invoices, View or Receive payments, or
# Issue refunds (those pages link to invoices). Others open only the invoices attached to issues they can see.
def self.invoice_viewer?(user = User.current)
user.allowed_to?(:view_customers, nil, global: true) || invoice_writer?(user) || payment_viewer?(user) ||
refunder?(user)
end
# True when the user may write invoices # True when the user may write invoices
def self.invoice_writer?(user = User.current) def self.invoice_writer?(user = User.current)
user.allowed_to?(:write_invoices, nil, global: true) user.allowed_to?(:write_invoices, nil, global: true)
+17 -3
View File
@@ -100,8 +100,7 @@ class CustomersControllerTest < Redmine::IntegrationTest
assert_equal 'new@example.com', @fake.created.last.email_address.address assert_equal 'new@example.com', @fake.created.last.email_address.address
end end
# The controller doesn't accept API keys (no accept_api_auth) and Redmine ignores the session on JSON # Customers are created from the page only; JSON requests are refused
# requests, so customers can't be created as JSON: the format.json branches of #create aren't reachable
def test_json_create_is_refused def test_json_create_is_refused
Role.find(1).add_permission!(:view_customers) Role.find(1).add_permission!(:view_customers)
Role.find(1).add_permission!(:add_customers) Role.find(1).add_permission!(:add_customers)
@@ -109,10 +108,25 @@ class CustomersControllerTest < Redmine::IntegrationTest
post '/customers.json', params: { customer: { name: 'Json Person' } }, post '/customers.json', params: { customer: { name: 'Json Person' } },
headers: { 'X-Redmine-API-Key' => User.find(2).api_key } headers: { 'X-Redmine-API-Key' => User.find(2).api_key }
end end
assert_includes [401, 403], response.status assert_includes [401, 403, 406], response.status
assert_not Customer.exists?(name: 'Json Person') assert_not Customer.exists?(name: 'Json Person')
end end
def test_invalid_customer_shows_the_form_again
grant(:view_customers, :add_customers)
post '/customers', params: { customer: { name: '' } }
assert_response :unprocessable_entity
assert_select '#errorExplanation'
end
def test_quickbooks_error_on_create_is_shown
grant(:view_customers, :add_customers)
@fake.define_singleton_method(:create) { |_doc| raise Quickbooks::IntuitRequestException, 'Duplicate Name Exists' }
post '/customers', params: { customer: { name: 'Jane Customer' } }
assert_redirected_to '/customers/new'
assert_match 'Duplicate Name Exists', flash[:error]
end
def test_update_needs_edit_customers def test_update_needs_edit_customers
grant(:view_customers) grant(:view_customers)
Role.find(1).remove_permission!(:edit_customers) Role.find(1).remove_permission!(:edit_customers)
+82 -12
View File
@@ -10,7 +10,8 @@
require File.expand_path('../test_helper', __dir__) require File.expand_path('../test_helper', __dir__)
# Estimate and invoice PDFs: logged-in users, or a share-link customer for their own issue's documents only # Estimate and invoice PDFs: users with a billing permission open any of them; other logged-in users only the
# documents attached to issues they can see; share-link customers only their own issue's documents
class DocumentPdfsTest < Redmine::IntegrationTest class DocumentPdfsTest < Redmine::IntegrationTest
include QboFakeServiceHelper include QboFakeServiceHelper
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers, fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
@@ -32,7 +33,15 @@ class DocumentPdfsTest < Redmine::IntegrationTest
@fake = install_fake_quickbooks @fake = install_fake_quickbooks
[qbo_estimate(id: 598, doc_number: '1068'), qbo_estimate(id: 599, doc_number: '1069'), [qbo_estimate(id: 598, doc_number: '1068'), qbo_estimate(id: 599, doc_number: '1069'),
qbo_invoice(id: 601, doc_number: '1234'), qbo_invoice(id: 602, doc_number: '1235')].each { |d| @fake.add(d) } qbo_invoice(id: 601, doc_number: '1234'), qbo_invoice(id: 602, doc_number: '1235')].each { |d| @fake.add(d) }
@fake.pdf_body = '%PDF-1.4 test' @fake.pdf_body = CombinePDF.new.tap { |pdf| pdf << CombinePDF.create_page }.to_pdf
Role.find(1).remove_permission!(:view_customers, :write_estimates, :write_invoices, :view_payments,
:receive_payments, :issue_refunds)
end
def login(*permissions)
permissions.each { |p| Role.find(1).add_permission!(p) }
reset!
log_user('jsmith', 'jsmith')
end end
def open_share_link def open_share_link
@@ -40,24 +49,85 @@ class DocumentPdfsTest < Redmine::IntegrationTest
assert_response :success assert_response :success
end end
def test_logged_in_user_gets_the_estimate_pdf def test_billing_users_open_any_estimate
log_user('jsmith', 'jsmith') %i[view_customers write_estimates].each do |permission|
get '/estimates/598' Role.find(1).remove_permission!(:view_customers, :write_estimates)
assert_response :success login(permission)
get '/estimates/599'
assert_response :success, permission
assert_equal 'application/pdf', response.media_type assert_equal 'application/pdf', response.media_type
assert_match 'estimate 1068.pdf', response.headers['Content-Disposition'] assert_match 'estimate 1069.pdf', response.headers['Content-Disposition']
get '/estimates/doc', params: { search: '1069' } get '/estimates/doc', params: { search: '1069' }
assert_response :success assert_response :success, permission
end
end end
def test_estimate_missing_locally_is_synced_first def test_other_users_open_only_estimates_on_issues_they_can_see
log_user('jsmith', 'jsmith') login
get '/estimates/598'
assert_response :success
get '/estimates/doc', params: { search: '1068' }
assert_response :success
get '/estimates/599'
assert_response :forbidden
get '/estimates/doc', params: { search: '1069' }
assert_response :forbidden
end
def test_estimate_on_a_hidden_issue_is_refused
Issue.find(1).update_column(:estimate_id, nil)
Issue.find(4).update_column(:estimate_id, 598)
Project.find(2).update_column(:is_public, false)
Member.where(user_id: 2, project_id: 2).destroy_all
login
get '/estimates/598'
assert_response :forbidden
end
def test_only_billing_users_sync_missing_estimates
login
Estimate.expects(:sync_by_id).never
get '/estimates/777'
assert_response :forbidden
login(:view_customers)
Estimate.expects(:sync_by_id).with('777') Estimate.expects(:sync_by_id).with('777')
get '/estimates/777' get '/estimates/777'
assert_response :redirect assert_response :redirect
assert_equal I18n.t(:notice_estimate_not_found), flash[:error] assert_equal I18n.t(:notice_estimate_not_found), flash[:error]
end end
def test_billing_users_open_any_invoice
%i[view_customers write_invoices view_payments receive_payments issue_refunds].each do |permission|
Role.find(1).remove_permission!(:view_customers, :write_invoices, :view_payments, :receive_payments, :issue_refunds)
login(permission)
get '/invoices/602'
assert_response :success, permission
get '/invoices/601', params: { invoice_ids: %w[601 602] }
assert_response :success, permission
end
end
def test_other_users_open_only_invoices_on_issues_they_can_see
login
get '/invoices/601'
assert_response :success
assert_match 'invoice 1234.pdf', response.headers['Content-Disposition']
get '/invoices/602'
assert_response :forbidden
get '/invoices/601', params: { invoice_ids: %w[601 602] }
assert_response :forbidden
end
def test_estimate_search_shows_only_to_billing_users
login
get '/projects/ecookbook/issues'
assert_select '#estimate-search-form', 0
login(:write_estimates)
get '/projects/ecookbook/issues'
assert_select '#estimate-search-form'
end
def test_anonymous_visitors_must_log_in def test_anonymous_visitors_must_log_in
get '/estimates/598' get '/estimates/598'
assert_redirected_to %r{/login} assert_redirected_to %r{/login}
@@ -96,14 +166,14 @@ class DocumentPdfsTest < Redmine::IntegrationTest
end end
def test_invoice_pdf_failure_redirects def test_invoice_pdf_failure_redirects
log_user('jsmith', 'jsmith') login(:write_invoices)
get '/invoices/999' get '/invoices/999'
assert_response :redirect assert_response :redirect
assert_equal I18n.t(:notice_invoice_not_found), flash[:error] assert_equal I18n.t(:notice_invoice_not_found), flash[:error]
end end
def test_syncs_are_admin_only def test_syncs_are_admin_only
log_user('jsmith', 'jsmith') login
get '/estimates/sync' get '/estimates/sync'
assert_response :forbidden assert_response :forbidden
get '/invoices/sync' get '/invoices/sync'
+2 -2
View File
@@ -190,8 +190,8 @@ class RedminePagesTest < Redmine::IntegrationTest
# ---- issue PDF ---- # ---- issue PDF ----
def test_issue_pdf_includes_the_estimate def test_issue_pdf_includes_the_estimate
# A plain one-page PDF, like QuickBooks' (Redmine's own PDFs have optional content, which the merge refuses) # Made by Redmine's own PDF writer, which adds optional content: merged like the issue's PDF
estimate_pdf = CombinePDF.new.tap { |p| p << CombinePDF.create_page }.to_pdf estimate_pdf = Redmine::Export::PDF::ITCPDF.new('en').tap { |p| p.add_page; p.write(5, 'ESTIMATE') }.output
PdfService.any_instance.expects(:fetch_pdf).with(doc_ids: [598]).returns([estimate_pdf, '1068']) PdfService.any_instance.expects(:fetch_pdf).with(doc_ids: [598]).returns([estimate_pdf, '1068'])
login login
get '/issues/1.pdf' get '/issues/1.pdf'
+10
View File
@@ -35,6 +35,16 @@ class RedmineQboBillingTest < ActiveSupport::TestCase
assert_not Billing.payment_viewer?(user) assert_not Billing.payment_viewer?(user)
end end
def test_document_viewers
assert RedmineQboBilling.estimate_viewer?(user(:view_customers))
assert RedmineQboBilling.estimate_viewer?(user(:write_estimates))
assert_not RedmineQboBilling.estimate_viewer?(user(:write_invoices))
%i[view_customers write_invoices view_payments receive_payments issue_refunds].each do |permission|
assert RedmineQboBilling.invoice_viewer?(user(permission)), permission
end
assert_not RedmineQboBilling.invoice_viewer?(user(:write_estimates))
end
def test_paid_invoice_editor def test_paid_invoice_editor
assert Billing.paid_invoice_editor?(true, user(:write_invoices, :edit_paid_invoices)) assert Billing.paid_invoice_editor?(true, user(:write_invoices, :edit_paid_invoices))
assert_not Billing.paid_invoice_editor?(false, user(:write_invoices, :edit_paid_invoices)) assert_not Billing.paid_invoice_editor?(false, user(:write_invoices, :edit_paid_invoices))