Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Require the token keyword and widen the lookup guard

Guido Boyke2192809e75e5
diff --git a/app/services/lalabase/tools/base.rb b/app/services/lalabase/tools/base.rb
index 0c93270..7a60e98 100644
--- a/app/services/lalabase/tools/base.rb
+++ b/app/services/lalabase/tools/base.rb
@@ -413,9 +413,11 @@ module Lalabase
# The tickets of `relation` the caller can find: the actor's read rights and,
# on an MCP call, the reach of its token (Tickets::ReadableForToken owns both;
- # the assistant has no token and is limited by the rights alone). Every tool
- # that addresses ONE ticket looks it up in here, so a ticket without read
- # access answers exactly like a missing one. A lookup outside the scope
+ # the assistant has no token and is limited by the rights alone). get_ticket,
+ # post_comment, create_time_session and update_ticket look their ticket up in
+ # here, so a ticket without read access answers exactly like a missing one.
+ # One exception: summarize_time_sessions (resolve_ticket) calls the policy
+ # scope itself and does not pass through here. A lookup outside the scope
# followed by authorize! answered "Not authorized." instead, which told a
# caller with access to the project, but not to its tickets, which ticket
# numbers exist; numbers count up and can be tried one by one
diff --git a/app/services/tickets/readable_for_token.rb b/app/services/tickets/readable_for_token.rb
index a8a9391..05d2e55 100644
--- a/app/services/tickets/readable_for_token.rb
+++ b/app/services/tickets/readable_for_token.rb
@@ -9,7 +9,8 @@
#
# token: nil is legitimate. The assistant calls the same tools as MCP and has no token; its reach
# is the person's own, which is the policy scope alone. nil therefore means "no second limit",
-# and a caller that holds a token must pass it. A token's reach of nil means every project of the
+# and the caller writes token: nil out: the keyword is required, because a caller that forgot it
+# would silently widen an account admin to every project. A token's reach of nil means every project of the
# organisation, [] means none, also for an organisation outside the token.
#
# The reach comes before the policy scope. An organisation the token no longer reaches (a
@@ -27,7 +28,7 @@ module Tickets
new(**).call
end
- def initialize(user:, organisation:, relation: Ticket, token: nil)
+ def initialize(user:, organisation:, token:, relation: Ticket)
@user = user
@organisation = organisation
@relation = relation
diff --git a/spec/architecture/ticket_token_lookup_guard_spec.rb b/spec/architecture/ticket_token_lookup_guard_spec.rb
index ec33d57..4efde90 100644
--- a/spec/architecture/ticket_token_lookup_guard_spec.rb
+++ b/spec/architecture/ticket_token_lookup_guard_spec.rb
@@ -19,12 +19,24 @@ require 'prism'
# ⚠️ A tripwire, not a proof. A receiver held in a variable is not seen
# (scope = project.tickets; scope.find(id)), nor a class picked at run time
# (viewable_type.constantize.find), nor an association under another name
-# (ticket.subtasks). Those are for the person who reads the diff.
+# (ticket.subtasks), nor a condition built with Arel
+# (where(Ticket.arel_table[:id].eq(id))). Those are for the person who reads the diff.
+# The door itself: Api::V1::ReadableTicket must find the ticket's organisation before
+# it can ask the owner, so OWNER_DOOR is left out of the scan. In its place a test
+# holds that file to exactly one lookup, DOOR_DISCOVERY.
module TicketTokenLookupGuard
- ROOTS = %w[app/controllers/api app/services/lalabase/tools].freeze
+ ROOTS = %w[app/controllers/api app/controllers/concerns/api app/services/lalabase/tools].freeze
+ OWNER_DOOR = 'app/controllers/concerns/api/v1/readable_ticket.rb'
+ DOOR_DISCOVERY = 'Ticket.where(id: id).pick(:organisation_id, :project_id)'
+ OWNER = /\A(?:::)?Tickets::ReadableForToken\z/
# Each returns one ticket, or tells whether it exists.
- LOOKUPS = %i[find take take! sole exists?].freeze
+ LOOKUPS = %i[
+ find take take! sole exists? find_sole_by find_or_initialize_by find_or_create_by find_or_create_by!
+ ].freeze
+ # One ticket by position. After the policy scope these are a list read, so they
+ # count only when the chain starts at the class or an association.
+ POSITIONAL = %i[first last].freeze
# Each leaves the rows the policy scope would have bound, or locks what no gate chose.
ESCAPES = %i[lock unscoped].freeze
# A where on one of these addresses a ticket rather than building a list.
@@ -79,9 +91,27 @@ module TicketTokenLookupGuard
end
def self.past_the_owner?(node, untenanted)
+ return true if owner_without_token?(node)
return false unless tickets_at_root?(node)
- untenanted || lookup?(node)
+ untenanted || lookup?(node) || (POSITIONAL.include?(node.name) && !policy_scoped?(node))
+ end
+
+ def self.owner_without_token?(node)
+ return false unless %i[call new].include?(node.name) && node.receiver&.slice&.match?(OWNER)
+
+ last = node.arguments&.arguments&.last
+ !(last.is_a?(Prism::KeywordHashNode) && key_named?(last, 'token'))
+ end
+
+ def self.policy_scoped?(node)
+ current = node
+ while current.is_a?(Prism::CallNode)
+ return true if SCOPES.include?(current.name)
+
+ current = current.receiver
+ end
+ false
end
def self.lookup?(node)
@@ -116,25 +146,38 @@ module TicketTokenLookupGuard
end
def self.addressed?(arguments)
- arguments&.arguments.to_a.any? do |argument|
- case argument
- when Prism::StringNode then argument.unescaped.match?(ADDRESS_IN_SQL)
- when Prism::KeywordHashNode, Prism::HashNode then address_key?(argument)
- else false
- end
+ arguments&.arguments.to_a.any? { |argument| address?(argument) }
+ end
+
+ def self.address?(argument)
+ case argument
+ when Prism::StringNode then argument.unescaped.match?(ADDRESS_IN_SQL)
+ when Prism::ArrayNode then address?(argument.elements.first)
+ when Prism::KeywordHashNode, Prism::HashNode then address_key?(argument)
+ else false
end
end
+ # { id: 1 }, and { tickets: { id: 1 } } for the same column named by its table
def self.address_key?(hash)
hash.elements.any? do |element|
- key = element.is_a?(Prism::AssocNode) ? element.key : nil
- key.respond_to?(:unescaped) && ADDRESS_KEYS.include?(key.unescaped)
+ next false unless element.is_a?(Prism::AssocNode) && element.key.respond_to?(:unescaped)
+
+ name = element.key.unescaped
+ ADDRESS_KEYS.include?(name) || (name == 'tickets' && address?(element.value))
+ end
+ end
+
+ def self.key_named?(hash, name)
+ hash.elements.any? do |element|
+ element.is_a?(Prism::AssocNode) && element.key.respond_to?(:unescaped) && element.key.unescaped == name
end
end
def self.files
ROOTS.flat_map { |root| Dir[Rails.root.join("#{root}/**/*.rb")] }
- .map { |path| Pathname(path).relative_path_from(Rails.root).to_s }.sort
+ .map { |path| Pathname(path).relative_path_from(Rails.root).to_s }
+ .sort - [OWNER_DOOR]
end
# The source of one method, found by name, so a neighbour in the file does not count
@@ -185,6 +228,7 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
it 'reads both trees, or the scan proves nothing' do
expect(TicketTokenLookupGuard.files).to include('app/controllers/api/v1/posts_controller.rb',
+ 'app/controllers/concerns/api/token_authenticatable.rb',
'app/services/lalabase/tools/post_comment.rb')
expect(TicketTokenLookupGuard.files).to(be_none { |file| file.match?(%r{\Aapp/services/(?!lalabase/tools/)}) })
end
@@ -198,13 +242,18 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
let(:base_owner) { TicketTokenLookupGuard.method_source('app/services/lalabase/tools/base.rb', :readable_tickets) }
it 'runs through the REST concern' do
- expect(concern).to include('Tickets::ReadableForToken.call(')
+ expect(concern).to match(/Tickets::ReadableForToken\.call\([^)]*token: current_token/m)
expect(concern).not_to include('Pundit.policy_scope!')
end
+ it 'holds the door to its one discovery read' do
+ lookups = TicketTokenLookupGuard.findings(concern).map(&:last)
+
+ expect(lookups).to contain_exactly(a_string_including(TicketTokenLookupGuard::DOOR_DISCOVERY))
+ end
+
it 'runs through the base of the tools' do
- expect(base_owner).to include('Tickets::ReadableForToken.call(')
- expect(base_owner).to include('token: context.token')
+ expect(base_owner).to match(/Tickets::ReadableForToken\.call\([^)]*token: context\.token/m)
expect(base_owner).not_to include('Pundit.policy_scope!')
end
end
@@ -235,7 +284,18 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
'project.tickets.find_by_number(1)', 'project.tickets.lock.find(id)', 'project.tickets.where(id: id)',
'project&.tickets&.find(id)', '@project.tickets.find(id)', 'context.project.tickets.find_by(id: id)',
'organisation.tickets.includes(:creator).where(number: 1).take',
- 'policy_scope(project.tickets).find(id)', 'Pundit.policy_scope!(user, Ticket).find(id)'
+ 'policy_scope(project.tickets).find(id)', 'Pundit.policy_scope!(user, Ticket).find(id)',
+ 'Ticket.find_sole_by(id: id)', 'project.tickets.find_sole_by(number: 1)',
+ 'Ticket.find_or_initialize_by(id: id)', 'project.tickets.find_or_initialize_by(number: 1)',
+ 'Ticket.find_or_create_by(id: id)', 'project.tickets.find_or_create_by(title: title)',
+ 'Ticket.find_or_create_by!(id: id)', 'project.tickets.find_or_create_by!(title: title)',
+ 'Ticket.first', 'Ticket.last', 'project.tickets.first', 'project.tickets.last',
+ 'Ticket.where(organisation_id: org.id).order(:number).first', 'project.tickets.order(:number).last',
+ "Ticket.where(['id = ?', id])", "project.tickets.where(['id = ?', id])",
+ 'Ticket.where(tickets: { id: id })', 'project.tickets.where(tickets: { number: 1 })',
+ 'Tickets::ReadableForToken.call(user: u, organisation: o, relation: Ticket).find(id)',
+ 'Tickets::ReadableForToken.call(user: u, organisation: o)',
+ '::Tickets::ReadableForToken.new(user: u, organisation: o).call'
].each do |source|
it("flags #{source}") { expect(past?("#{source}\n")).to be(true) }
end
@@ -253,7 +313,13 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
[
'readable_tickets(context, context.project.tickets).find_by(id: ticket_id)',
'readable_tickets(context, base).includes(:creator).find(id)',
- 'Tickets::ReadableForToken.call(user: u, organisation: o, relation: Ticket).find(id)',
+ 'Tickets::ReadableForToken.call(user: u, organisation: o, relation: Ticket, token: t).find(id)',
+ 'readable_tickets(context, project.tickets).first',
+ 'readable_tickets(context, base).order(:number).last',
+ 'policy_scope(project.tickets).first',
+ 'policy_scope(project.tickets).order(:number).last',
+ 'Pundit.policy_scope!(user, Ticket).first',
+ 'Ticket.where(project: { id: id })',
'Ticket.where(organisation_id: context.organisation.id, project_id: ids)',
'policy_scope(project.tickets)',
'filter.ordered(filter.filtered(policy_scope(project.tickets)))',
@@ -266,7 +332,8 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
'Foo::Ticket.find(id)',
'ticket.posts.find(id)',
'tickets = load; tickets.first',
- 'scope = project.tickets; scope.find(id)'
+ 'scope = project.tickets; scope.find(id)',
+ 'Ticket.where(Ticket.arel_table[:id].eq(id))'
].each do |source|
it("passes #{source}") { expect(past?("#{source}\n")).to be(false) }
end
diff --git a/spec/services/tickets/readable_for_token_spec.rb b/spec/services/tickets/readable_for_token_spec.rb
index a444d28..7e88aa1 100644
--- a/spec/services/tickets/readable_for_token_spec.rb
+++ b/spec/services/tickets/readable_for_token_spec.rb
@@ -164,6 +164,10 @@ RSpec.describe Tickets::ReadableForToken, :ci_guard do
end
describe 'without a token' do
+ it 'must be said out loud: leaving token: out raises' do
+ expect { described_class.call(user: reader, organisation: organisation) }.to raise_error(ArgumentError, /token/)
+ end
+
it 'gives a reader what the policy scope gives' do
expect(found(reader, ticket_b.id)).to eq(ticket_b)
expect(found(reader, hidden_ticket.id)).to be_nil
@@ -216,7 +220,7 @@ RSpec.describe Tickets::ReadableForToken, :ci_guard do
end
it 'answers with a relation, so the caller can narrow it further and nothing raises' do
- relation = ActsAsTenant.with_tenant(organisation) { described_class.call(user: reader, organisation: organisation) }
+ relation = ActsAsTenant.with_tenant(organisation) { described_class.call(user: reader, organisation: organisation, token: nil) }
expect(relation).to be_a(ActiveRecord::Relation)
expect(ActsAsTenant.with_tenant(organisation) { relation.where(id: ticket_a.id).first }).to eq(ticket_a)