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.

fix: lock the ticket in its project for the write and the answer of PATCH /api/v1/tickets/:id

Guido Boykeb4828581ed8d
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 97327ab..843f562 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -313,6 +313,7 @@ jobs:
spec/requests/api/v1/post_comment_format_spec.rb
spec/requests/api/v1/ticket_changes_spec.rb
spec/requests/api/v1/ticket_changes_concurrency_spec.rb
+ spec/requests/api/v1/ticket_update_concurrency_spec.rb
spec/requests/api/v1/ticket_changes_side_effects_spec.rb
spec/requests/api/v1/knowledge_spec.rb
spec/models/codebase_import_mapping_spec.rb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 117e267..7339ad5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -56,6 +56,11 @@ starts (`db:prepare lalabase:data_backfills`). Without Docker, run
ids.
- The code tools of the assistant (`search_code_symbols`, `get_symbol_details`) neutralise
code fences in the name and path of a symbol, which come from the repository.
+- `PATCH /api/v1/tickets/:id` writes and answers under a lock on the ticket in the project
+ it was authorized in. A ticket moved to another project in between used to be written
+ there, where the caller may not write, and its answer could show data of that project.
+ It is a 404 now, as if never found. A concurrent change to another attribute is no
+ longer written back with its old value.
### Upgrade notes
diff --git a/CLAUDE.md b/CLAUDE.md
index 5ac6b6f..2e7ca3c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -970,7 +970,10 @@ answers 200 with the ticket summary, like `PATCH /tickets/:id`, which stays as i
`assignee_ids` REPLACE the list, and `gboyke/lalabase-mcp` relies on that. `parent_id` on that
PATCH reaches the model (`Ticket#parent_unchanged`, a saved ticket keeps its parent): another
parent or an empty value is a 422 `validation_failed`/`invalid_input`, the current parent is no
-change, so a client may send back what it read. Status and assignees
+change, so a client may send back what it read. That PATCH writes and answers under the same row
+lock in the authorized project (`locked_ticket` in the controller, since 2026-11-05: a move after
+the rights check let it write into a project the caller may not write; guard
+`spec/requests/api/v1/ticket_update_concurrency_spec.rb`). Status and assignees
go through `Actors::ApplyTicketChanges` like a board drag (a `TicketBulkRun` included), the title
through `Actors::SaveTicket` alone under a lock on the row in its project, so the side effects are
the web's and MCP's, once. Order: read-only token 403, then the read gate (missing, malformed,
diff --git a/app/controllers/api/v1/tickets_controller.rb b/app/controllers/api/v1/tickets_controller.rb
index 0b2dffe..b495233 100644
--- a/app/controllers/api/v1/tickets_controller.rb
+++ b/app/controllers/api/v1/tickets_controller.rb
@@ -96,22 +96,21 @@ module Api
# Allowed fields: status, assignee_ids (replace semantics). parent_id passes through so
# the model answers it (Ticket#parent_unchanged): another parent is a 422, the current
# one is no change, and nothing is dropped silently.
+ #
+ # The write runs under the ticket's row lock in the authorized project, as
+ # the title write of POST /changes does (Tickets::Change#write_title):
+ # SaveTicket looks the ticket up across the organisation, and a move after
+ # the rights check let the write land in a project the caller may not
+ # write. A ticket that left the project, or was deleted, is a 404, as if
+ # never found. The status merges into the attributes read under the lock.
def update
with_readable_ticket(params[:id]) do |ticket, project|
authorize ticket, :update?
- result = Actors::SaveTicket.call(
- project: project,
- params: save_ticket_update_params(ticket),
- id: ticket.id,
- current_user: current_user
- )
+ result = save_in_project(ticket, project)
+ next render_actor_failure(result) unless result.success?
- if result.success?
- render json: { data: ticket_serializer.summary(result.resource) }
- else
- render_actor_failure(result)
- end
+ render json: { data: locked_summary(project, ticket) }
end
end
@@ -138,13 +137,7 @@ module Api
raise ActiveRecord::RecordNotFound if outcome.gone?
next render_change_failure(outcome) unless outcome.written?
- # The write released its lock. Keep the authorized project boundary
- # while reading the response, including the serializer's associations:
- # a move that won the race is a 404, and a later move waits for us.
- data = Ticket.transaction do
- ticket_serializer.summary(project.tickets.lock.find(ticket.id))
- end
- render json: { data: data }
+ render json: { data: locked_summary(project, ticket) }
end
end
@@ -253,6 +246,33 @@ module Api
# previous apply_status_change did. assignee_ids is forwarded only when the
# client sent the key, so a status-only update leaves assignees untouched
# while an explicit [] still clears them (SaveTicket treats [] as "remove all").
+ # Current.user wraps the whole transaction: the activities are written on
+ # commit and name Current.user, and this commit comes after SaveTicket's
+ # own with_actor_context restored the previous value (as write_title).
+ def save_in_project(ticket, project)
+ Current.set(user: current_user) do
+ Ticket.transaction do
+ locked = locked_ticket(project, ticket)
+ Actors::SaveTicket.call(project: project, params: save_ticket_update_params(locked), id: locked.id,
+ current_user: current_user)
+ end
+ end
+ end
+
+ # The write released its lock. Keep the authorized project boundary while
+ # reading the response, including the serializer's associations: a move
+ # that won the race is a 404, and a later move waits for us.
+ def locked_summary(project, ticket)
+ Ticket.transaction { ticket_serializer.summary(locked_ticket(project, ticket)) }
+ end
+
+ # The ticket that passed with_readable_ticket, read again under FOR UPDATE in
+ # the authorized project. Gone from it (moved or deleted): RecordNotFound, a 404.
+ # Call inside a transaction, or the lock ends with the statement.
+ def locked_ticket(project, ticket)
+ project.tickets.lock.find(ticket.id)
+ end
+
def save_ticket_update_params(ticket)
attrs = update_params
mapped = {}
diff --git a/spec/architecture/ticket_token_lookup_guard_spec.rb b/spec/architecture/ticket_token_lookup_guard_spec.rb
index 8bd46c8..2bbe580 100644
--- a/spec/architecture/ticket_token_lookup_guard_spec.rb
+++ b/spec/architecture/ticket_token_lookup_guard_spec.rb
@@ -66,7 +66,8 @@ module TicketTokenLookupGuard
'app/controllers/api/v1/tickets_controller.rb' => {
code: 'project.tickets.lock.find(ticket.id)',
reason: 'the ticket already passed with_readable_ticket; this re-reads it under a lock ' \
- 'to answer. Policy scope plus FOR UPDATE would be a different query'
+ 'in the same project to write (PATCH) and to answer (PATCH, /changes). Policy scope ' \
+ 'plus FOR UPDATE would be a different query'
},
RECENT_ACTIVITY => {
code: 'Ticket.where(id: ids)',
diff --git a/spec/requests/api/v1/ticket_update_concurrency_spec.rb b/spec/requests/api/v1/ticket_update_concurrency_spec.rb
new file mode 100644
index 0000000..fe30756
--- /dev/null
+++ b/spec/requests/api/v1/ticket_update_concurrency_spec.rb
@@ -0,0 +1,165 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# PATCH /api/v1/tickets/:id against a ticket that moves while the request runs.
+#
+# Until 2026-11-05 PATCH authorized the ticket in its project and then handed
+# the id to Actors::SaveTicket, which looks the ticket up across the whole
+# organisation. A move in between let the write land in a project the caller
+# may not write: found in the API review, a probe removed every assignee of a
+# ticket in such a project and answered 200. POST /changes locked the row for
+# its title write; PATCH did not. The status was also merged into a copy of
+# custom_attributes read before any lock, so a concurrent change to another
+# attribute was written back with its old value.
+RSpec.describe 'PATCH /api/v1/tickets/:id during a concurrent move', :ci_guard, type: :request do
+ def build_pat(user, organisation)
+ pat = build(:personal_access_token, user: user, organisations: [organisation], read_only: false)
+ pat.token_hash = nil
+ pat.token_prefix = nil
+ pat.generate_token!
+ pat
+ end
+
+ describe 'within one connection' do
+ let(:organisation) { create(:organisation) }
+ let(:user) { create(:user) }
+ let(:author) { create(:user) }
+ let(:role) { create(:role, organisation: organisation) }
+ let(:project) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ let(:elsewhere) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ let(:pat) { build_pat(user, organisation) }
+ let!(:ticket) do
+ ActsAsTenant.with_tenant(organisation) do
+ create(:ticket, project: project, organisation: organisation, creator: author,
+ custom_attributes: { 'status' => 'open', 'priority' => 'low' }).tap do |t|
+ TicketAssignment.create!(ticket: t, user: author)
+ end
+ end
+ end
+
+ before do
+ ActsAsTenant.with_tenant(organisation) do
+ [user, author].each do |member|
+ create(:membership, user: member, organisation: organisation, role: role, active: true)
+ create(:project_permission, user: member, project: project, tickets_access: :read_write)
+ end
+ # The author may write the destination, the caller may not.
+ create(:project_permission, user: author, project: elsewhere, tickets_access: :read_write)
+ end
+ end
+
+ # Runs `change` on the row right after the rights check said yes, which is
+ # where a concurrent request can commit before the write starts.
+ def after_the_rights_check(&change)
+ allow_any_instance_of(TicketPolicy).to receive(:update?).and_wrap_original do |original|
+ original.call.tap { ActsAsTenant.without_tenant(&change) }
+ end
+ end
+
+ def patch_ticket(attributes)
+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: attributes },
+ headers: { 'Authorization' => "Bearer #{pat.token}" }, as: :json
+ end
+
+ def stored
+ ActsAsTenant.without_tenant { Ticket.find(ticket.id) }
+ end
+
+ it 'answers a ticket that moved away as not found and writes nothing there' do
+ after_the_rights_check { Ticket.where(id: ticket.id).update_all(project_id: elsewhere.id) }
+
+ patch_ticket(assignee_ids: [''], status: 'done')
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.parsed_body).to include('error' => 'not_found', 'code' => 'not_found')
+ expect(stored.project_id).to eq(elsewhere.id)
+ expect(ActsAsTenant.without_tenant { TicketAssignment.where(ticket_id: ticket.id).count }).to eq(1)
+ expect(stored.custom_attributes['status']).to eq('open')
+ end
+
+ it 'merges the status into the attributes as they are under the lock' do
+ after_the_rights_check do
+ Ticket.where(id: ticket.id).update_all(custom_attributes: { 'status' => 'open', 'priority' => 'high' })
+ end
+
+ patch_ticket(status: 'in_progress')
+
+ expect(response).to have_http_status(:ok)
+ expect(stored.custom_attributes).to include('status' => 'in_progress', 'priority' => 'high')
+ end
+
+ it 'still writes a ticket that stayed where it was' do
+ patch_ticket(status: 'in_progress', assignee_ids: [user.id])
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body.dig('data', 'status')).to eq('in_progress')
+ expect(ActsAsTenant.without_tenant { TicketAssignment.where(ticket_id: ticket.id).pluck(:user_id) }).to eq([user.id])
+ end
+ end
+
+ # Real commits and a second connection: the row lock has to hold while the
+ # actor writes and while the response reads the ticket, or a move commits in
+ # between and the answer carries data of a project the caller cannot read.
+ describe 'with a second connection' do
+ self.use_transactional_tests = false
+
+ before do
+ DatabaseCleaner.clean
+ DatabaseCleaner.strategy = :truncation
+ DatabaseCleaner.start
+ Prosopite.pause
+ end
+
+ after { Prosopite.resume }
+
+ def try_to_move(ticket, organisation, destination)
+ Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do |connection|
+ ActsAsTenant.with_tenant(organisation) do
+ Ticket.transaction do
+ connection.execute("SET LOCAL lock_timeout = '100ms'")
+ Ticket.where(id: ticket.id).update_all(project_id: destination.id, title: 'Private destination title')
+ end
+ end
+ end
+ rescue ActiveRecord::LockWaitTimeout => e
+ e
+ end
+ end
+
+ it 'keeps a move waiting while the actor writes and while the response reads' do
+ organisation = create(:organisation)
+ user = create(:user)
+ ActsAsTenant.current_tenant = organisation
+ create(:membership, user: user, organisation: organisation, role: create(:role, organisation: organisation), active: true)
+ project = create(:project, organisation: organisation)
+ elsewhere = create(:project, organisation: organisation)
+ create(:project_permission, user: user, project: project, tickets_access: :read_write)
+ ticket = create(:ticket, project: project, organisation: organisation, creator: user, title: 'Original')
+ pat = build_pat(user, organisation)
+ moves = []
+
+ allow(Actors::SaveTicket).to receive(:call).and_wrap_original do |original, **arguments|
+ moves << try_to_move(ticket, organisation, elsewhere).tap { |worker| worker.join(10) }
+ original.call(**arguments)
+ end
+ allow_any_instance_of(Tickets::Serializer).to receive(:summary).and_wrap_original do |original, record|
+ moves << try_to_move(ticket, organisation, elsewhere).tap { |worker| worker.join(10) }
+ original.call(record)
+ end
+
+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'in_progress' } }.to_json,
+ headers: { 'Authorization' => "Bearer #{pat.token}", 'Content-Type' => 'application/json' }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body.dig('data', 'title')).to eq('Original')
+ expect(moves.size).to eq(2)
+ expect(moves.map(&:value)).to all(be_a(ActiveRecord::LockWaitTimeout))
+ # The request has finished: the move can now take the row.
+ expect(Ticket.where(id: ticket.id).update_all(project_id: elsewhere.id)).to eq(1)
+ ensure
+ moves&.each { |worker| worker.join(2) || worker.kill }
+ end
+ end
+end