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 on relation finders and sharpen the lookup guard

Guido Boyke408f07dbafbe
diff --git a/CLAUDE.md b/CLAUDE.md
index 9a27eb8..c0a9b4a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -787,6 +787,13 @@ unreadable tickets, but queries are not: discovering the unknown tenant reads on
numbers; this deliberately accepts query asymmetry instead of searching every
organisation the token reaches. It makes no constant-time guarantee.
+What a token holder can find is decided by `Tickets::ReadableForToken` alone (REST, MCP tools,
+`Tickets::RelationAccess`), reach before policy scope. `token:` is required on it and on
+`Tickets::RelationAccess`: `nil` means no second limit and is written out by the callers without
+a token. Guards: `spec/architecture/ticket_token_lookup_guard_spec.rb` (also refuses these
+finders and `TicketRelation.visible_to` without a token on the token surfaces) and
+`ticket_relation_actor_callers_guard_spec.rb`.
+
**`/api/v1` for programs** (REST R0, 2026-10-28; the terminal client moves from MCP to REST
feature by feature):
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index 78bb69a..5e156d4 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -13,8 +13,8 @@ Ausgenommene Subtrees mit eigenem Vertrag: `actors/`, `lalabase/tools/`).
„Actor-Pattern", Guard: `spec/services/actors/actor_contract_guard_spec.rb`). Triviales
Einzel-`update!` ohne Side-Effects bleibt im Controller.
-* An actor writes and checks no rights.
-* Finding belongs to one object per domain (`Tickets::ReadableForToken`, `Tickets::RelationAccess`, `People::Lookup`); they share the question, not code.
+* An actor writes and checks no rights. Exceptions lock first and authorize again under the lock (`AcceptTicketSuggestion`, `StartTicketSuggestionRun`).
+* Finding belongs to one object per domain (`Tickets::ReadableForToken`, `Tickets::RelationAccess`, `People::Lookup`); they share the question, not code. Where `nil` would drop a limit, the keyword is required.
* The policy decides yes or no.
* The caller words the answer (status, text, 404 form).
* A guard holds where a mistake discloses data (`ticket_token_lookup_guard_spec.rb`, `ticket_relation_actor_callers_guard_spec.rb`).
diff --git a/app/services/actors/create_ticket_relation.rb b/app/services/actors/create_ticket_relation.rb
index 38d1c30..7c7df99 100644
--- a/app/services/actors/create_ticket_relation.rb
+++ b/app/services/actors/create_ticket_relation.rb
@@ -13,7 +13,8 @@
# and save! run in this actor's one transaction, in that order.
#
# No rights checks here. The caller makes sure the user may write tickets in the project of
-# `ticket` and may read `other_ticket` (policy_scope(Ticket)); PR 2 does that in the controller.
+# `ticket` and may read `other_ticket`, found through Tickets::RelationAccess#other_ticket with
+# the caller's token.
# The ticket objects passed in do not learn about the new row (TicketRelation has no inverse on
# its belongs_to, on purpose): a caller that loaded ticket.outgoing_relations or
# incoming_relations before reads them fresh afterwards, or renders from a new query.
diff --git a/app/services/tickets/readable_for_token.rb b/app/services/tickets/readable_for_token.rb
index 05d2e55..792887f 100644
--- a/app/services/tickets/readable_for_token.rb
+++ b/app/services/tickets/readable_for_token.rb
@@ -7,9 +7,9 @@
# It decides what can be FOUND, never the answer: no authorize, no 404, no wording. Those stay
# with the caller.
#
-# 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 the caller writes token: nil out: the keyword is required, because a caller that forgot it
+# token: nil is legitimate. The web pages and the assistant, which calls the same tools as MCP,
+# have no token; their reach is the person's own, which is the policy scope alone. nil therefore
+# means "no second limit", 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.
#
diff --git a/app/services/tickets/relation_access.rb b/app/services/tickets/relation_access.rb
index a87e31e..46d6cc6 100644
--- a/app/services/tickets/relation_access.rb
+++ b/app/services/tickets/relation_access.rb
@@ -7,11 +7,12 @@
# foreign, unreadable and out of reach look the same to the caller.
#
# It only finds: no rights decision, no wording, no raising. Those stay with the caller. token:
-# means what it means in Tickets::ReadableForToken: nil is no second limit, and a caller that
-# holds a token must pass it.
+# means what it means in Tickets::ReadableForToken: nil is no second limit, so the web controller
+# writes it out, and the keyword is required: a tool that forgot it would find tickets out of its
+# token's reach, and the actors behind it check no rights.
module Tickets
class RelationAccess
- def initialize(user:, organisation:, token: nil)
+ def initialize(user:, organisation:, token:)
@user = user
@organisation = organisation
@token = token
diff --git a/app/services/time_sessions/open_hours.rb b/app/services/time_sessions/open_hours.rb
index b73aeff..76ccc6e 100644
--- a/app/services/time_sessions/open_hours.rb
+++ b/app/services/time_sessions/open_hours.rb
@@ -91,10 +91,10 @@ module TimeSessions
end
end
- # The tickets of one organisation's rows that the person may read, through
- # the same call as Lalabase::Tools::Base.readable_tickets and
- # Api::V1::ReadableTicket. Narrowed to the token's projects by the TICKET's
- # project: until 2026-09-16 a booking moved to another project kept the
+ # The tickets of one organisation's rows that the person may read: the same
+ # question as Tickets::ReadableForToken, asked here by hand for a reach that
+ # is already at hand, and not held by its guard. Narrowed to the token's
+ # projects by the TICKET's project: until 2026-09-16 a booking moved to another project kept the
# ticket of its old one. Looked up in the booking's organisation, so a
# booking that points at a ticket of another one (Codebase imports before
# 2026-09-16) shows none. Only readable tickets are read from the database
diff --git a/app/views/organisations/tickets/relations/_modal.html.erb b/app/views/organisations/tickets/relations/_modal.html.erb
index 40e05d7..5962ef6 100644
--- a/app/views/organisations/tickets/relations/_modal.html.erb
+++ b/app/views/organisations/tickets/relations/_modal.html.erb
@@ -8,8 +8,8 @@
Shape and lifecycle after docs/dokumentation/modal_pattern.md; its controller is the
pattern's reference implementation. One autosuggest only (plan, Fassung 3 §2.2b). The other
- ticket shown after a refused save came through policy_scope(Ticket), so its title is one
- the reader may see. %>
+ ticket shown after a refused save came through Tickets::RelationAccess, so its title is
+ one the reader may see. %>
<% rs = 'views.organisations.tickets.shared.relations.modal' %>
<% modal_id = ticket_relation_modal_id(ticket) %>
<% kind = TicketRelation::KINDS.key?(kind) ? kind : TicketRelation::KINDS.keys.first %>
diff --git a/spec/architecture/ticket_token_lookup_guard_spec.rb b/spec/architecture/ticket_token_lookup_guard_spec.rb
index 4efde90..8bd46c8 100644
--- a/spec/architecture/ticket_token_lookup_guard_spec.rb
+++ b/spec/architecture/ticket_token_lookup_guard_spec.rb
@@ -7,7 +7,9 @@ require 'prism'
# Lalabase::Tools) a single ticket is found through Tickets::ReadableForToken,
# by way of with_readable_ticket, with_readable_ticket_number or readable_tickets.
# A lookup that starts at the Ticket class or at a tickets association and goes
-# past that owner is refused.
+# past that owner is refused. So is a finder of this rule called without the
+# token: the owner, Tickets::RelationAccess or TicketRelation.visible_to with
+# token: left out, or written as nil, which means "no second limit" there.
# Why: the owner joins the policy scope and the token's reach. A lookup past it
# skips at least one of them, and the result reads as a working endpoint: a
# ticket out of the token's reach comes back as a ticket. A rule that has to be
@@ -20,7 +22,13 @@ require 'prism'
# (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), nor a condition built with Arel
-# (where(Ticket.arel_table[:id].eq(id))). Those are for the person who reads the diff.
+# (where(Ticket.arel_table[:id].eq(id))), nor a base that a method returns
+# (Pundit.policy_scope!(actor, base(context)).find_by(id: id)), nor a ticket reached
+# through another record (Post.find(id).ticket), nor a chain that widens what the
+# owner gave (readable_tickets(c, r).unscope(:where)). Those are for the person who
+# reads the diff. Known instance of the base: Tools::SummarizeTimeSessions.resolve_ticket
+# (see Tools::Base.readable_tickets), safe because on MCP its base is the project the
+# call passed the gate for.
# 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.
@@ -28,27 +36,32 @@ module TicketTokenLookupGuard
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 takes token:, and nil there is no second limit, which a token surface never wants.
+ TOKEN_FINDERS = /\A(?:::)?Tickets::(?:ReadableForToken|RelationAccess)\z/
+ TOKEN_FINDER_CALLS = %i[call new].freeze
+ RELATION_MODEL = /\A(?:::)?TicketRelation\z/
# Each returns one ticket, or tells whether it exists.
LOOKUPS = %i[
- find take take! sole exists? find_sole_by find_or_initialize_by find_or_create_by find_or_create_by!
+ find find_signed find_signed! 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
+ POSITIONAL = %i[first second third fourth fifth last second_to_last third_to_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.
- ADDRESS_KEYS = %w[id number].freeze
+ ADDRESS_KEYS = %w[id number tickets.id tickets.number].freeze
ADDRESS_IN_SQL = /\b(?:id|number)\b/
# The policy scope alone lacks the token's reach, so it does not gate a lookup.
SCOPES = %i[policy_scope policy_scope!].freeze
RECENT_ACTIVITY = 'app/services/lalabase/tools/recent_activity.rb'
- # Shrink-only. `code` names the one call that may stay: anything else in the same
- # file is still a finding. An entry whose call is gone fails too.
+ # Shrink-only. `code` names the one call that may stay, once, as the parser reads it:
+ # anything else in the same file is still a finding, also on the same line or behind a
+ # comment that quotes it. An entry whose call is gone fails too.
ALLOWED = {
'app/controllers/api/v1/tickets_controller.rb' => {
code: 'project.tickets.lock.find(ticket.id)',
@@ -64,16 +77,28 @@ module TicketTokenLookupGuard
# [line number, text] of every lookup past the owner in one file's source
def self.findings(source)
+ lines = source.lines
+ flagged(source).map { |line, _call| [line, lines[line - 1].strip] }.uniq
+ end
+
+ # [line number, source of the call] of what `code`, the file's allow-list entry, does not
+ # name. The steps of the named chain are flagged on their own and go with it.
+ def self.unallowed(source, code)
+ hits = flagged(source)
+ return hits if code.nil?
+
+ named, rest = hits.partition { |_line, call| call == code }
+ named.drop(1) + rest.reject { |_line, call| code.start_with?("#{call}.") }
+ end
+
+ # [line number, source of the call] of every lookup past the owner, in source order
+ def self.flagged(source)
result = Prism.parse(source)
raise ArgumentError, "unparsable source: #{result.errors.first&.message}" unless result.success?
- lines = source.lines
calls(result.value).filter_map do |node, untenanted|
- next unless past_the_owner?(node, untenanted)
-
- line = node.message_loc.start_line
- [line, lines[line - 1].strip]
- end.uniq.sort_by(&:first)
+ [node.message_loc.start_line, node.slice] if past_the_owner?(node, untenanted)
+ end.sort_by(&:first)
end
# Every call, each with whether it sits inside a without_tenant block
@@ -91,17 +116,26 @@ module TicketTokenLookupGuard
end
def self.past_the_owner?(node, untenanted)
- return true if owner_without_token?(node)
+ return true if token_finder?(node) && drops_the_token?(node)
return false unless tickets_at_root?(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)
+ def self.token_finder?(node)
+ receiver = node.receiver&.slice
+ return false if receiver.nil?
+ (TOKEN_FINDER_CALLS.include?(node.name) && receiver.match?(TOKEN_FINDERS)) ||
+ (node.name == :visible_to && receiver.match?(RELATION_MODEL))
+ end
+
+ def self.drops_the_token?(node)
last = node.arguments&.arguments&.last
- !(last.is_a?(Prism::KeywordHashNode) && key_named?(last, 'token'))
+ return true unless last.is_a?(Prism::KeywordHashNode)
+
+ token = last.elements.find { |element| keyword?(element, 'token') }
+ token.nil? || token.value.is_a?(Prism::NilNode)
end
def self.policy_scoped?(node)
@@ -117,7 +151,7 @@ module TicketTokenLookupGuard
def self.lookup?(node)
name = node.name
LOOKUPS.include?(name) || ESCAPES.include?(name) || name.to_s.start_with?('find_by') ||
- (name == :where && addressed?(node.arguments))
+ (%i[where rewhere].include?(name) && addressed?(node.arguments))
end
# Walks down the receivers: a chain that reached the owner has its call at the
@@ -168,10 +202,8 @@ module TicketTokenLookupGuard
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
+ def self.keyword?(element, name)
+ element.is_a?(Prism::AssocNode) && element.key.respond_to?(:unescaped) && element.key.unescaped == name
end
def self.files
@@ -196,14 +228,11 @@ end
RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guard, type: :architecture do
let(:allowed) { TicketTokenLookupGuard::ALLOWED }
- def findings_in(file)
- TicketTokenLookupGuard.findings(File.read(Rails.root.join(file)))
- end
-
it 'finds no lookup past Tickets::ReadableForToken outside the allow list' do
offenders = TicketTokenLookupGuard.files.flat_map do |file|
- findings_in(file).filter_map do |number, text|
- "#{file}:#{number}: #{text}" unless text.include?(allowed.dig(file, :code) || "\0")
+ source = File.read(Rails.root.join(file))
+ TicketTokenLookupGuard.unallowed(source, allowed.dig(file, :code)).map do |number, call|
+ "#{file}:#{number}: #{call}"
end
end
@@ -215,7 +244,8 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
it 'keeps no allow-list entry whose call is gone' do
stale = allowed.reject do |file, entry|
- Rails.root.join(file).exist? && findings_in(file).any? { |_number, text| text.include?(entry[:code]) }
+ Rails.root.join(file).exist? &&
+ TicketTokenLookupGuard.flagged(File.read(Rails.root.join(file))).any? { |_number, call| call == entry[:code] }
end
expect(stale.keys).to be_empty, "Remove these from TicketTokenLookupGuard::ALLOWED:\n#{stale.keys.join("\n")}"
@@ -295,7 +325,21 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
'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'
+ '::Tickets::ReadableForToken.new(user: u, organisation: o).call',
+ 'Tickets::ReadableForToken.call(user: u, organisation: o, token: nil)',
+ 'Tickets::ReadableForToken.call(user: u, organisation: o, **options)',
+ 'Tickets::RelationAccess.new(user: u, organisation: o)',
+ 'Tickets::RelationAccess.new(user: u, organisation: o, token: nil)',
+ '::Tickets::RelationAccess.new(user: u, organisation: o).other_ticket(id)',
+ 'TicketRelation.visible_to(u, o)',
+ 'TicketRelation.visible_to(u, o, token: nil)',
+ '::TicketRelation.visible_to(u, o).touching(ticket).find_by(id: id)',
+ 'Ticket.where("tickets.id" => id).pick(:title)',
+ 'Ticket.where("tickets.number": number).to_a',
+ 'project.tickets.where("tickets.id" => id)',
+ 'Ticket.find_signed(signed)', 'Ticket.find_signed!(signed)',
+ 'Ticket.second', 'project.tickets.second', 'project.tickets.order(:number).third',
+ 'Ticket.rewhere(id: id)', 'project.tickets.where(state: 1).rewhere(number: 1)'
].each do |source|
it("flags #{source}") { expect(past?("#{source}\n")).to be(true) }
end
@@ -333,7 +377,12 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
'ticket.posts.find(id)',
'tickets = load; tickets.first',
'scope = project.tickets; scope.find(id)',
- 'Ticket.where(Ticket.arel_table[:id].eq(id))'
+ 'Ticket.where(Ticket.arel_table[:id].eq(id))',
+ 'Tickets::RelationAccess.new(user: u, organisation: o, token: current_token).other_ticket(id)',
+ 'TicketRelation.visible_to(u, o, token: context.token).touching(ticket)',
+ 'MeetingAnalysis.visible_to(user)',
+ 'readable_tickets(context, base).second',
+ 'Ticket.where("tickets.project_id" => ids)'
].each do |source|
it("passes #{source}") { expect(past?("#{source}\n")).to be(false) }
end
@@ -344,6 +393,38 @@ RSpec.describe 'Token surfaces find a single ticket through the owner', :ci_guar
expect(past?("message = 'Ticket.find(id)'\n")).to be(false)
end
+ describe 'an allow-list entry names one call and nothing else' do
+ let(:code) { 'project.tickets.lock.find(ticket.id)' }
+
+ def unallowed(source)
+ TicketTokenLookupGuard.unallowed(source, code).map(&:last)
+ end
+
+ it 'lets the named call pass, with the steps of its chain' do
+ expect(unallowed("x = project.tickets.lock.find(ticket.id)\n")).to be_empty
+ end
+
+ it 'keeps another lookup on the same line' do
+ source = "a = project.tickets.lock.find(ticket.id); b = Ticket.find(id)\n"
+
+ expect(unallowed(source)).to eq(['Ticket.find(id)'])
+ end
+
+ it 'is not satisfied by a comment that quotes the call' do
+ expect(unallowed("Ticket.find(id) # project.tickets.lock.find(ticket.id)\n")).to eq(['Ticket.find(id)'])
+ end
+
+ it 'allows the call once' do
+ source = "a = project.tickets.lock.find(ticket.id)\nb = project.tickets.lock.find(ticket.id)\n"
+
+ expect(unallowed(source)).to eq([code])
+ end
+
+ it 'refuses everything in a file without an entry' do
+ expect(TicketTokenLookupGuard.unallowed("Ticket.find(id)\n", nil)).to eq([[1, 'Ticket.find(id)']])
+ end
+ end
+
it 'refuses source it cannot parse instead of calling it clean' do
expect { TicketTokenLookupGuard.findings("def broken(\n") }.to raise_error(ArgumentError)
end
diff --git a/spec/services/tickets/relation_access_spec.rb b/spec/services/tickets/relation_access_spec.rb
index 6b22fc6..a602071 100644
--- a/spec/services/tickets/relation_access_spec.rb
+++ b/spec/services/tickets/relation_access_spec.rb
@@ -68,10 +68,15 @@ RSpec.describe Tickets::RelationAccess, :ci_guard do
end
end
- def access(user, token: nil)
+ def access(user, token:)
described_class.new(user: user, organisation: organisation, token: token)
end
+ it 'requires the token keyword: leaving it out would drop the limit silently' do
+ expect { described_class.new(user: build(:user), organisation: organisation) }
+ .to raise_error(ArgumentError, /token/)
+ end
+
def other_ticket(user, id, token: nil)
ActsAsTenant.with_tenant(organisation) { access(user, token: token).other_ticket(id) }
end