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.

Add POST /api/v1/tickets/:id/changes

Guido Boyke84d4f1582a25
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 50b1971..5569782 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -306,6 +306,8 @@ jobs:
spec/requests/api/v1/people_spec.rb
spec/requests/api/people_parity_spec.rb
spec/requests/api/v1/post_comment_format_spec.rb
+ spec/requests/api/v1/ticket_changes_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
spec/services/codebase_import/time_session_importer_spec.rb
diff --git a/app/controllers/api/v1/tickets_controller.rb b/app/controllers/api/v1/tickets_controller.rb
index 694cd14..0b38abf 100644
--- a/app/controllers/api/v1/tickets_controller.rb
+++ b/app/controllers/api/v1/tickets_controller.rb
@@ -5,7 +5,7 @@ module Api
class TicketsController < BaseController
include Api::V1::ReadableTicket
- idempotent :create, :update
+ idempotent :create, :update, :changes
# Raised while the paging options are read, before any ticket is looked
# up: the 422 does not depend on whether the ticket exists.
@@ -113,6 +113,32 @@ module Api
end
end
+ # POST /api/v1/tickets/:id/changes
+ #
+ # One change per request by the rule the MCP tool update_ticket changes by
+ # (Tickets::Change, REST R3b): change[title], change[status], or
+ # change[add_assignee_ids] and change[remove_assignee_ids] against the
+ # current list. PATCH stays as it is: its assignee_ids REPLACE the list.
+ #
+ # Missing, foreign and unreadable tickets answer the same 404 whatever the
+ # input, a ticket the token may not write the same 403: the input is read
+ # after both, so a refusal of it only ever answers a caller who may write.
+ def changes
+ with_readable_ticket(params[:id]) do |ticket, project|
+ authorize ticket, :update?
+
+ change = Tickets::Change.parse(change_input, actor: current_user)
+ next render_change_refusal(change) if change.refused?
+
+ outcome = change.write(ticket: ticket, project: project)
+ # It left the project, or was deleted, after the lookup: as if never found.
+ raise ActiveRecord::RecordNotFound if outcome.gone?
+ next render_change_failure(outcome) unless outcome.written?
+
+ render json: { data: ticket_serializer.summary(ticket.reload) }
+ end
+ end
+
def activities
with_readable_ticket(params[:id]) do |ticket, project|
return render json: { data: [], meta: pagination_meta(0) } unless ProjectPolicy.new(current_user, project).view_activities?
@@ -225,6 +251,37 @@ module Api
mapped
end
+ # --- Change helpers --------------------------------------------------
+
+ # The keys and values as they came: strong parameters would drop a list
+ # where a text belongs and a key nobody permitted, and the rule refuses
+ # both. A change that is no object is none at all.
+ def change_input
+ input = params[:change]
+ input.is_a?(ActionController::Parameters) ? input.to_unsafe_h : {}
+ end
+
+ # What the request alone decides: 422 invalid_input, in the form of the
+ # comment's and the booking's refusals.
+ def render_change_refusal(change)
+ render_error(error: 'validation_failed',
+ errors: [I18n.t("services.ticket_change.#{change.refusal}", **change.refusal_details)],
+ status: :unprocessable_entity)
+ end
+
+ # What the project's state decides: 422 refused with its reason, which
+ # `error` carries as it does for every other refused actor code. The code
+ # is named: Api::V1::ErrorBody reads a `validation_failed` as invalid input,
+ # and here the input was fine. A failure the rule does not name answers
+ # 500 without a text, which may be an exception's.
+ def render_change_failure(outcome)
+ return render_error(error: 'internal_error', status: :internal_server_error) if outcome.unexpected?
+
+ render_error(error: outcome.reason, code: 'refused', reason: outcome.reason,
+ errors: [I18n.t("services.ticket_change_failure.#{outcome.failure}"), *outcome.messages],
+ status: :unprocessable_entity)
+ end
+
# --- Loaders ---------------------------------------------------------
def load_project_without_tenant(id)
diff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rb
index 9edcd53..73f9f7e 100644
--- a/app/services/api/v1/capabilities.rb
+++ b/app/services/api/v1/capabilities.rb
@@ -17,8 +17,8 @@ module Api
# never: an existing name, field or meaning does not change. 1.2.0 added
# the People API; 1.3.0 added the REST ticket view (R1); 1.4.0 adds
# time_sessions.book (R6); 1.5.0 adds posts.plain (R3a); 1.6.0 adds
- # knowledge.search (R2).
- API_VERSION = '1.6.0'
+ # knowledge.search (R2); 1.7.0 adds tickets.changes (R3b).
+ API_VERSION = '1.7.0'
# name => [verb, path as the router spells it]
ENDPOINTS = {
@@ -34,6 +34,7 @@ module Api
'tickets.by_number' => ['GET', '/api/v1/projects/:project_id/tickets/number/:number'],
'tickets.show' => ['GET', '/api/v1/tickets/:id'],
'tickets.update' => ['PATCH', '/api/v1/tickets/:id'],
+ 'tickets.changes' => ['POST', '/api/v1/tickets/:id/changes'],
'tickets.activities' => ['GET', '/api/v1/tickets/:id/activities'],
'tickets.attachments' => ['GET', '/api/v1/tickets/:id/attachments'],
'posts.create' => ['POST', '/api/v1/tickets/:ticket_id/posts'],
diff --git a/config/locales/services.de.yml b/config/locales/services.de.yml
index 7ea607a..9e3fccd 100644
--- a/config/locales/services.de.yml
+++ b/config/locales/services.de.yml
@@ -177,6 +177,33 @@ de:
body_invalid_utf8: "Der Kommentar (post[body]) lässt sich nicht als UTF-8 lesen."
body_nul: "Ein Kommentar im Format plain (post[body]) darf keine NUL-Bytes enthalten."
body_empty: "Bitte geben Sie einen Kommentartext (post[body]) an."
+ # The refusals of a ticket change through a token (Tickets::Change::REFUSALS),
+ # as the HTTP API answers them; the MCP tool update_ticket keeps its own
+ # English texts. None repeats what the client sent.
+ ticket_change:
+ unknown_keys: "Eine Änderung kennt nur title, status, add_assignee_ids und remove_assignee_ids."
+ invalid_utf8: "Die Änderung lässt sich nicht als UTF-8 lesen."
+ one_kind: "Bitte geben Sie genau eine Änderung an: title, status oder add_assignee_ids und remove_assignee_ids."
+ title_not_string: "Bitte geben Sie den Titel (change[title]) als Text an."
+ title_invalid_utf8: "Der Titel (change[title]) lässt sich nicht als UTF-8 lesen."
+ title_forbidden: "Der Titel (change[title]) muss eine Zeile ohne Steuerzeichen sein."
+ title_empty: "Der Titel (change[title]) enthält keinen sichtbaren Text."
+ title_too_long: "Der Titel (change[title]) ist länger als %{max} Zeichen."
+ status_not_string: "Bitte geben Sie den Status (change[status]) als Text an."
+ status_empty: "Der Status (change[status]) ist leer."
+ assignees_not_a_list: "Bitte geben Sie %{list} als Liste von Benutzer-IDs oder \"me\" an."
+ too_many_assignees: "Bitte nennen Sie höchstens %{max} Personen je Liste."
+ assignee_invalid: "%{list} enthält einen Wert, der weder eine Benutzer-ID noch \"me\" ist."
+ no_assignees: "Bitte nennen Sie mindestens eine Person in add_assignee_ids oder remove_assignee_ids."
+ assignees_overlap: "add_assignee_ids und remove_assignee_ids nennen dieselbe Person."
+ # Why a ticket change stops at the project's state (Tickets::Change::FAILURES).
+ ticket_change_failure:
+ no_status_field: "Dieses Projekt hat kein Statusfeld."
+ status_not_allowed: "Das ist kein Status dieses Projekts; bitte einen Schlüssel aus meta.available_statuses verwenden."
+ assignee_not_allowed: "Eine Person in dieser Änderung kann in diesem Projekt nicht zugewiesen werden."
+ user_not_assignable: "Nichts wurde geändert: Eine Person in dieser Änderung hat keinen Zugang mehr zu diesem Projekt."
+ title_not_saved: "Der Titel konnte nicht gespeichert werden."
+ ticket_not_saved: "Das Ticket konnte nicht gespeichert werden."
default_smart_folder:
my_tasks: "Meine Aufgaben"
high_priority: "Hohe Priorität"
diff --git a/config/locales/services.en.yml b/config/locales/services.en.yml
index f2c4ee3..91d6d5b 100644
--- a/config/locales/services.en.yml
+++ b/config/locales/services.en.yml
@@ -177,6 +177,33 @@ en:
body_invalid_utf8: "The comment (post[body]) cannot be read as UTF-8."
body_nul: "A plain comment (post[body]) must not contain NUL bytes."
body_empty: "The comment (post[body]) has no text."
+ # The refusals of a ticket change through a token (Tickets::Change::REFUSALS),
+ # as the HTTP API answers them; the MCP tool update_ticket keeps its own
+ # English texts. None repeats what the client sent.
+ ticket_change:
+ unknown_keys: "A change takes only title, status, add_assignee_ids and remove_assignee_ids."
+ invalid_utf8: "The change cannot be read as UTF-8."
+ one_kind: "Give exactly one change: title, status, or add_assignee_ids and remove_assignee_ids."
+ title_not_string: "Give the title (change[title]) as text."
+ title_invalid_utf8: "The title (change[title]) cannot be read as UTF-8."
+ title_forbidden: "The title (change[title]) must be one line without control characters."
+ title_empty: "The title (change[title]) has no visible text."
+ title_too_long: "The title (change[title]) is longer than %{max} characters."
+ status_not_string: "Give the status (change[status]) as text."
+ status_empty: "The status (change[status]) is empty."
+ assignees_not_a_list: "Give %{list} as a list of user ids or \"me\"."
+ too_many_assignees: "Name at most %{max} users per list."
+ assignee_invalid: "%{list} holds a value that is no user id and not \"me\"."
+ no_assignees: "Name at least one user in add_assignee_ids or remove_assignee_ids."
+ assignees_overlap: "add_assignee_ids and remove_assignee_ids name the same user."
+ # Why a ticket change stops at the project's state (Tickets::Change::FAILURES).
+ ticket_change_failure:
+ no_status_field: "This project has no status field."
+ status_not_allowed: "This is no status of this project; use a key from meta.available_statuses."
+ assignee_not_allowed: "A user in this change cannot be assigned in this project."
+ user_not_assignable: "Nothing was changed: a person in this change no longer has access to this project."
+ title_not_saved: "The title could not be saved."
+ ticket_not_saved: "The ticket could not be saved."
default_smart_folder:
my_tasks: "My Tasks"
high_priority: "High Priority"
diff --git a/config/routes.rb b/config/routes.rb
index b36b7ef..5af673c 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -945,6 +945,8 @@ Rails.application.routes.draw do
member do
get :activities
get :attachments
+ # REST R3b: one change, by the rule of the MCP tool update_ticket.
+ post :changes
end
resources :time_sessions, only: %i[index create]
resources :posts, only: %i[create show]
diff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rb
index dbd579e..cac2f99 100644
--- a/spec/contracts/mcp_contract_recorder.rb
+++ b/spec/contracts/mcp_contract_recorder.rb
@@ -565,7 +565,49 @@ module McpContract
# login ticket after every answer above, without advancing the clock.
'POST /api/v1/tickets/:ticket_id/posts' => rest_comment_calls,
# REST R2, appended last: reads only, over the deploy note of the website.
- 'GET /api/v1/projects/:project_id/knowledge' => rest_knowledge_calls
+ 'GET /api/v1/projects/:project_id/knowledge' => rest_knowledge_calls,
+ # REST R3b, appended last: it changes the export and the login ticket
+ # after every answer above, without advancing the clock.
+ 'POST /api/v1/tickets/:id/changes' => rest_ticket_change_calls
+ }
+ end
+
+ # Each request from its own line (Prosopite). The export ticket has Anna on
+ # it; on the login ticket Carla's assignment is stale (update_ticket_calls),
+ # so a change that does not name her leaves her there. user_not_assignable
+ # is left to a race, as on MCP: no case here.
+ def rest_ticket_change_calls
+ path = ->(ticket) { "/api/v1/tickets/#{id(ticket)}/changes" }
+ export = path.call(:export_ticket)
+ statuses = in_org { TicketAttributeDefinition.ordered_value_keys_for(@website, 'status') }
+ once = { change: { status: statuses.last } }
+ key = 'contract-rest-change-1'
+ {
+ 'ok_status' => rest_send(:post, :write, export, params: { change: { status: statuses.first } }),
+ 'ok_assign' => rest_send(:post, :write, export, params: { change: { add_assignee_ids: [id(:ben)] } }),
+ 'ok_unassign' => rest_send(:post, :write, export, params: { change: { remove_assignee_ids: [id(:ben)] } }),
+ 'ok_assign_and_unassign' => rest_send(:post, :write, export,
+ params: { change: { add_assignee_ids: [id(:ben)], remove_assignee_ids: ['me'] } }),
+ 'ok_title' => rest_send(:post, :write, export, params: { change: { title: 'Export als CSV, XLSX und PDF' } }),
+ 'ok_beside_stale' => rest_send(:post, :write, path.call(:login_ticket), params: { change: { remove_assignee_ids: [id(:ben)] } }),
+ 'invalid_input_mixed' => rest_send(:post, :write, export, params: { change: { title: 'x', status: statuses.first } }),
+ 'invalid_input_unknown_key' => rest_send(:post, :write, export, params: { change: { priority: 'low' } }),
+ 'invalid_input_no_change' => rest_send(:post, :write, export, params: {}),
+ 'invalid_input_title' => rest_send(:post, :write, export, params: { change: { title: "zwei\nZeilen" } }),
+ 'invalid_input_same_person' => rest_send(:post, :write, export,
+ params: { change: { add_assignee_ids: ['me'], remove_assignee_ids: [id(:anna)] } }),
+ 'refused_status' => rest_send(:post, :write, export, params: { change: { status: 'erledigt' } }),
+ 'refused_person' => rest_send(:post, :write, export, params: { change: { add_assignee_ids: [id(:missing)] } }),
+ 'refused_no_status_field' => rest_send(:post, :write, path.call(:internal_ticket), params: { change: { status: statuses.first } }),
+ 'not_found' => rest_send(:post, :write, path.call(:missing), params: { change: { status: statuses.first } }),
+ # No read access to the ticket: answered like a missing one.
+ 'hidden' => rest_send(:post, :write, path.call(:hidden_ticket), params: { change: { status: statuses.first } }),
+ # Anna reads the archive's tickets, she may not write them.
+ 'forbidden' => rest_send(:post, :write, path.call(:archived_ticket), params: { change: { status: statuses.first } }),
+ 'read_only' => rest_send(:post, :read, export, params: { change: { status: statuses.first } }),
+ 'idempotency_first' => rest_send(:post, :write, export, params: once, key: key),
+ 'idempotency_replay' => rest_send(:post, :write, export, params: once, key: key),
+ 'idempotency_mismatch' => rest_send(:post, :write, export, params: { change: { status: statuses.first } }, key: key)
}
end
diff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.json
index a622300..5d1e2ce 100644
--- a/spec/fixtures/mcp_contract.json
+++ b/spec/fixtures/mcp_contract.json
@@ -1,9 +1,9 @@
{
"header": {
"regenerate": "RAILS_ENV=test bin/rails mcp:contract",
- "core_commit": "3237c54efb6341fa863a2f71e25360cfd13ad46a",
+ "core_commit": "44bc4f0b91ee75a3a4bbc0a1fec7d8f18747952f",
"core_dirty": true,
- "contract_sha256": "104823b69a072b45fcb7c10148435d0d4bd5e94df62ad7e7e8cf5b52c426805b"
+ "contract_sha256": "8a85b28c00bd355eee3ae577db4757959078cc7a5f34d8e7c461bdfe2d26b73d"
},
"contract": {
"mcp": {
@@ -3764,7 +3764,7 @@
"all_projects": true
}
],
- "api_version": "1.6.0",
+ "api_version": "1.7.0",
"capabilities": [
"error_codes",
"idempotency",
@@ -3785,6 +3785,7 @@
"tickets.activities",
"tickets.attachments",
"tickets.by_number",
+ "tickets.changes",
"tickets.create",
"tickets.list",
"tickets.paging",
@@ -3829,7 +3830,7 @@
"all_projects": true
}
],
- "api_version": "1.6.0",
+ "api_version": "1.7.0",
"capabilities": [
"error_codes",
"idempotency",
@@ -3850,6 +3851,7 @@
"tickets.activities",
"tickets.attachments",
"tickets.by_number",
+ "tickets.changes",
"tickets.create",
"tickets.list",
"tickets.paging",
@@ -6052,6 +6054,629 @@
}
}
}
+ },
+ "POST /api/v1/tickets/:id/changes": {
+ "ok_status": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV und XLSX",
+ "status": "new",
+ "status_functions": [
+ "is_new"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_assign": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "add_assignee_ids": [
+ "00000000-0000-4000-8000-000000000012"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV und XLSX",
+ "status": "new",
+ "status_functions": [
+ "is_new"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_unassign": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "remove_assignee_ids": [
+ "00000000-0000-4000-8000-000000000012"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV und XLSX",
+ "status": "new",
+ "status_functions": [
+ "is_new"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_assign_and_unassign": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "add_assignee_ids": [
+ "00000000-0000-4000-8000-000000000012"
+ ],
+ "remove_assignee_ids": [
+ "me"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV und XLSX",
+ "status": "new",
+ "status_functions": [
+ "is_new"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_title": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "title": "Export als CSV, XLSX und PDF"
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV, XLSX und PDF",
+ "status": "new",
+ "status_functions": [
+ "is_new"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_beside_stale": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/changes",
+ "params": {
+ "change": {
+ "remove_assignee_ids": [
+ "00000000-0000-4000-8000-000000000012"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000041",
+ "number": 1,
+ "title": "Login bricht ab",
+ "status": "in_progress",
+ "status_functions": [
+ "is_in_progress"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ {
+ "id": "00000000-0000-4000-8000-000000000013",
+ "name": "Carla Conrad"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "created_at": "2026-01-05T09:21:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "invalid_input_mixed": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "title": "x",
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Bitte geben Sie genau eine Änderung an: title, status oder add_assignee_ids und remove_assignee_ids."
+ ]
+ }
+ }
+ },
+ "invalid_input_unknown_key": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "priority": "low"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Eine Änderung kennt nur title, status, add_assignee_ids und remove_assignee_ids."
+ ]
+ }
+ }
+ },
+ "invalid_input_no_change": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {}
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Bitte geben Sie genau eine Änderung an: title, status oder add_assignee_ids und remove_assignee_ids."
+ ]
+ }
+ }
+ },
+ "invalid_input_title": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "title": "zwei\nZeilen"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Der Titel (change[title]) muss eine Zeile ohne Steuerzeichen sein."
+ ]
+ }
+ }
+ },
+ "invalid_input_same_person": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "add_assignee_ids": [
+ "me"
+ ],
+ "remove_assignee_ids": [
+ "00000000-0000-4000-8000-000000000011"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "add_assignee_ids und remove_assignee_ids nennen dieselbe Person."
+ ]
+ }
+ }
+ },
+ "refused_status": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "erledigt"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "value_not_allowed",
+ "code": "refused",
+ "reason": "value_not_allowed",
+ "errors": [
+ "Das ist kein Status dieses Projekts; bitte einen Schlüssel aus meta.available_statuses verwenden."
+ ]
+ }
+ }
+ },
+ "refused_person": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "add_assignee_ids": [
+ "00000000-0000-4000-8000-000000000999"
+ ]
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "value_not_allowed",
+ "code": "refused",
+ "reason": "value_not_allowed",
+ "errors": [
+ "Eine Person in dieser Änderung kann in diesem Projekt nicht zugewiesen werden."
+ ]
+ }
+ }
+ },
+ "refused_no_status_field": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000045/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "no_status_field",
+ "code": "refused",
+ "reason": "no_status_field",
+ "errors": [
+ "Dieses Projekt hat kein Statusfeld."
+ ]
+ }
+ }
+ },
+ "not_found": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000999/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 404,
+ "body": {
+ "error": "not_found",
+ "code": "not_found"
+ }
+ }
+ },
+ "hidden": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000043/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 404,
+ "body": {
+ "error": "not_found",
+ "code": "not_found"
+ }
+ }
+ },
+ "forbidden": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000044/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 403,
+ "body": {
+ "error": "forbidden",
+ "code": "forbidden"
+ }
+ }
+ },
+ "read_only": {
+ "token": "read",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ }
+ },
+ "response": {
+ "status": 403,
+ "body": {
+ "error": "forbidden",
+ "code": "read_only"
+ }
+ }
+ },
+ "idempotency_first": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "backlog"
+ }
+ },
+ "idempotency_key": "contract-rest-change-1"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV, XLSX und PDF",
+ "status": "backlog",
+ "status_functions": [
+ "is_backlog"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "idempotency_replay": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "backlog"
+ }
+ },
+ "idempotency_key": "contract-rest-change-1"
+ },
+ "response": {
+ "status": 200,
+ "body": {
+ "data": {
+ "id": "00000000-0000-4000-8000-000000000042",
+ "number": 2,
+ "title": "Export als CSV, XLSX und PDF",
+ "status": "backlog",
+ "status_functions": [
+ "is_backlog"
+ ],
+ "ticket_type": "support",
+ "parent_id": null,
+ "assignees": [
+ {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ }
+ ],
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000012",
+ "name": "Ben Berger"
+ },
+ "created_at": "2026-01-05T09:22:00Z",
+ "updated_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "idempotency_mismatch": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/changes",
+ "params": {
+ "change": {
+ "status": "new"
+ }
+ },
+ "idempotency_key": "contract-rest-change-1"
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "idempotency_key_reused",
+ "code": "invalid_input",
+ "message": "idempotency_key already used with different parameters"
+ }
+ }
+ }
}
}
}
diff --git a/spec/locales/token_rule_refusal_texts_spec.rb b/spec/locales/token_rule_refusal_texts_spec.rb
index c183a74..a472dff 100644
--- a/spec/locales/token_rule_refusal_texts_spec.rb
+++ b/spec/locales/token_rule_refusal_texts_spec.rb
@@ -3,10 +3,10 @@
require 'rails_helper'
# Guard: every refusal of a token write rule is worded on both surfaces, in
-# both locales. Since REST R6 and R3a a rule names its refusals once
-# (TimeSessions::Booking::REFUSALS, Posts::Comment::REFUSALS) and each hull
-# words them: the MCP tool in its REFUSAL_TEXT, the HTTP API under a
-# `services.*` scope in de and en.
+# both locales. Since REST R6, R3a and R3b a rule names its refusals once
+# (TimeSessions::Booking::REFUSALS, Posts::Comment::REFUSALS,
+# Tickets::Change::REFUSALS and ::FAILURES) and each hull words them: the MCP
+# tool in its REFUSAL_TEXT, the HTTP API under a `services.*` scope in de and en.
#
# Why this exists (the drift it prevents): the three lists are kept by hand.
# A refusal added to a rule without its MCP text raises KeyError in the tool;
@@ -20,8 +20,14 @@ require 'rails_helper'
RSpec.describe 'Token write rule refusal texts' do
# A new rule with refusals of its own adds a line here.
rules = [
- { rule: Posts::Comment, tool: Lalabase::Tools::PostComment, scope: %i[services post_comment] },
- { rule: TimeSessions::Booking, tool: Lalabase::Tools::CreateTimeSession, scope: %i[services time_session_booking] }
+ { rule: 'Posts::Comment', refusals: Posts::Comment::REFUSALS, texts: Lalabase::Tools::PostComment::REFUSAL_TEXT,
+ scope: %i[services post_comment] },
+ { rule: 'TimeSessions::Booking', refusals: TimeSessions::Booking::REFUSALS, texts: Lalabase::Tools::CreateTimeSession::REFUSAL_TEXT,
+ scope: %i[services time_session_booking] },
+ { rule: 'Tickets::Change', refusals: Tickets::Change::REFUSALS, texts: Lalabase::Tools::UpdateTicket::REFUSAL_TEXT,
+ scope: %i[services ticket_change] },
+ { rule: 'Tickets::Change (failures)', refusals: Tickets::Change::FAILURES, texts: Lalabase::Tools::UpdateTicket::FAILURE_TEXT,
+ scope: %i[services ticket_change_failure] }
].freeze
# nil when absent, never the fallback value of another locale.
@@ -32,18 +38,22 @@ RSpec.describe 'Token write rule refusal texts' do
before { I18n.backend.send(:init_translations) unless I18n.backend.initialized? }
rules.each do |entry|
- refusals = entry[:rule]::REFUSALS
-
- it "words every refusal of #{entry[:rule]} in #{entry[:tool]}, and no other" do
- expect(entry[:tool]::REFUSAL_TEXT.keys).to match_array(refusals)
+ it "words every refusal of #{entry[:rule]} for MCP, and no other" do
+ expect(entry[:texts].keys).to match_array(entry[:refusals])
end
%i[de en].each do |locale|
it "has a #{locale} text for every refusal of #{entry[:rule]}, and no other" do
texts = stored(locale, *entry[:scope]) || {}
- expect(texts.keys).to match_array(refusals)
+ expect(texts.keys).to match_array(entry[:refusals])
expect(texts.values).to all(be_present)
end
end
+
+ # A placeholder only one language has would raise in the other.
+ it "names the same placeholders in both languages for #{entry[:rule]}" do
+ placeholders = ->(locale) { (stored(locale, *entry[:scope]) || {}).transform_values { |text| text.scan(/%\{(\w+)\}/).flatten.sort } }
+ expect(placeholders.call(:de)).to eq(placeholders.call(:en))
+ end
end
end
diff --git a/spec/requests/api/v1/capabilities_spec.rb b/spec/requests/api/v1/capabilities_spec.rb
index a3c207f..8a6427c 100644
--- a/spec/requests/api/v1/capabilities_spec.rb
+++ b/spec/requests/api/v1/capabilities_spec.rb
@@ -33,7 +33,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
it 'names the API version and the capabilities beside the existing fields' do
data = me(token(read_only: false))
- expect(data['api_version']).to eq('1.6.0')
+ expect(data['api_version']).to eq('1.7.0')
expect(data['capabilities']).to eq(Api::V1::Capabilities.names)
expect(data.keys).to include('user', 'token', 'scoped_organisations')
end
@@ -47,7 +47,8 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
'me.show', 'organisations.list', 'projects.list', 'tickets.list', 'tickets.create', 'tickets.show',
'tickets.update', 'tickets.attachments', 'posts.create', 'time_sessions.create',
'notifications.list', 'notifications.mark_as_read', 'people.list', 'people.show', 'idempotency', 'error_codes',
- 'tickets.by_number', 'posts.show', 'tickets.paging', 'time_sessions.book', 'posts.plain', 'knowledge.search'
+ 'tickets.by_number', 'posts.show', 'tickets.paging', 'time_sessions.book', 'posts.plain', 'knowledge.search',
+ 'tickets.changes'
)
end
diff --git a/spec/requests/api/v1/ticket_changes_side_effects_spec.rb b/spec/requests/api/v1/ticket_changes_side_effects_spec.rb
new file mode 100644
index 0000000..3a195d8
--- /dev/null
+++ b/spec/requests/api/v1/ticket_changes_side_effects_spec.rb
@@ -0,0 +1,166 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: the side effects of POST /api/v1/tickets/:id/changes against the MCP tool
+# update_ticket (REST R3b).
+# Type: request spec, both writes over HTTP, the jobs drained as a worker runs them.
+# Why: one rule, two hulls: what follows a write must not depend on the surface.
+# Two tickets that differ only in their number take the same change, one through
+# REST, one through MCP, and their activities, bulk runs, outbox events,
+# notifications (by recipient and channel) and subscriptions must match. The
+# tool's own spec holds the tool to the web write, so this one holds REST to
+# both. Exactly one activity each: a second actor call or a second save would
+# add one.
+RSpec.describe 'REST ticket changes: side effects equal the MCP write', :ci_guard, type: :request do
+ let(:organisation) { create(:organisation) }
+ let(:writer) { create(:user, first_name: 'Willi', last_name: 'Writer') }
+ let(:follower) { create(:user, first_name: 'Fritz', last_name: 'Follower') }
+ let(:colleague) { create(:user, first_name: 'Anna', last_name: 'Berg') }
+ let(:project) { create(:project, organisation: organisation) }
+
+ before do
+ bulk_project_setup
+ bulk_member(follower)
+ bulk_member(colleague)
+ ActsAsTenant.current_tenant = nil
+ end
+
+ let(:write_pat) do
+ token = build(:personal_access_token, user: writer, organisations: [organisation], read_only: false)
+ token.token_hash = nil
+ token.token_prefix = nil
+ token.generate_token!
+ token
+ end
+
+ # Two tickets that differ only in their number. The follower created them, so
+ # the creator subscription makes them a follower of both; the colleague is
+ # assigned to both.
+ def twins
+ ActsAsTenant.with_tenant(organisation) do
+ Array.new(2) do
+ create(:ticket, project: project, organisation: organisation, creator: follower, title: 'Login bricht ab',
+ assignees: [colleague], custom_attributes: { 'status' => 'open', 'priority' => 'high' })
+ end
+ end
+ end
+
+ def over_rest(ticket, fields)
+ post "/api/v1/tickets/#{ticket.id}/changes", params: { change: fields }.to_json,
+ headers: { 'Authorization' => "Bearer #{write_pat.token}", 'Content-Type' => 'application/json' }
+ expect(response).to have_http_status(:ok)
+ end
+
+ def over_mcp(ticket, fields)
+ body = { jsonrpc: '2.0', id: 1, method: 'tools/call',
+ params: { name: 'update_ticket', arguments: { project_id: project.id, ticket_id: ticket.id }.merge(fields) } }.to_json
+ post '/api/mcp', params: body,
+ headers: { 'Authorization' => "Bearer #{write_pat.token}", 'CONTENT_TYPE' => 'application/json' }
+ expect(response).to have_http_status(:ok)
+ expect(JSON.parse(response.body).fetch('result')['_meta']).to eq('lalabase/kind' => 'ok')
+ end
+
+ # Each job looks up its tenant once when it is deserialized; run back to
+ # back here, Prosopite would read those lookups as an N+1.
+ def drain
+ Prosopite.pause
+ drain_enqueued_jobs
+ ensure
+ Prosopite.resume
+ end
+
+ def baseline
+ ActsAsTenant.without_tenant { { activities: Activity.ids, notifications: Notification.ids } }
+ end
+
+ # What a write left behind for one ticket. Parameters are compared by their
+ # keys: values like the run id and the ticket number differ by construction.
+ def effects(ticket, since)
+ ActsAsTenant.without_tenant do
+ activities = Activity.where(trackable: ticket).where.not(id: since[:activities]).order(:created_at).to_a
+ {
+ activities: activities.map { |activity| [activity.key, activity.actor_id, activity.parameters.keys.sort] },
+ outbox: OutboxEvent.where(activity_id: activities.map(&:id)).count,
+ runs: TicketBulkRun.where('jsonb_exists(results, ?)', ticket.id).pluck(:user_id, :change_list, :changed_count, :failed_count),
+ notifications: Notification.where(notifiable: ticket).where.not(id: since[:notifications])
+ .pluck(:recipient_id, :channel, :event_type).sort,
+ subscriptions: NotificationSubscription.where(subscribable: ticket).pluck(:user_id, :mode, :source).sort
+ }
+ end
+ end
+
+ # Both writes in one queue, then the jobs of both, so neither side runs with a
+ # warmer world than the other. `prepare` runs on each twin before the baseline.
+ def compare(fields, prepare: nil)
+ rest_ticket, mcp_ticket = twins
+ with_test_queue_adapter do
+ Prosopite.pause { [rest_ticket, mcp_ticket].each { |ticket| prepare.call(ticket) } } if prepare
+ drain
+ since = baseline
+ over_rest(rest_ticket, fields)
+ over_mcp(mcp_ticket, fields)
+ drain
+ # Reading the same things for two tickets is the spec's loop, not the app's.
+ Prosopite.pause { [effects(rest_ticket, since), effects(mcp_ticket, since), rest_ticket, mcp_ticket] }
+ end
+ end
+
+ def reloaded(tickets, &)
+ Prosopite.pause { ActsAsTenant.without_tenant { tickets.map { |ticket| yield ticket.reload } } }
+ end
+
+ it 'changes the status with the same trail, once' do
+ rest, mcp, rest_ticket, mcp_ticket = compare({ status: 'wip' })
+
+ expect(rest).to eq(mcp)
+ expect(rest[:activities].map(&:first)).to eq(['ticket.status_changed'])
+ expect(rest[:activities].dig(0, 1)).to eq(writer.id)
+ expect(rest[:activities].dig(0, 2)).to include('bulk_run_id')
+ expect(rest[:runs].size).to eq(1)
+ expect(rest[:outbox]).to eq(1)
+ expect(rest[:notifications]).not_to be_empty
+ expect(rest[:notifications].map(&:first)).not_to include(writer.id)
+ expect(reloaded([rest_ticket, mcp_ticket], &:custom_attributes)).to all(eq('status' => 'wip', 'priority' => 'high'))
+ end
+
+ it 'assigns with the same trail, once' do
+ rest, mcp, rest_ticket, mcp_ticket = compare({ add_assignee_ids: ['me'] })
+
+ expect(rest).to eq(mcp)
+ expect(rest[:activities].map(&:first)).to eq(['ticket.assigned'])
+ expect(rest[:runs].size).to eq(1)
+ expect(rest[:notifications]).not_to be_empty
+ expect(reloaded([rest_ticket, mcp_ticket]) { |ticket| ticket.assignees.map(&:id).sort })
+ .to all(eq([colleague.id, writer.id].sort))
+ end
+
+ # The assignment of the colleague is made the way the board makes it, so it
+ # carries its subscription; taking it away must take both, and say so once.
+ it 'unassigns with the same trail, once' do
+ assign_colleague = lambda do |ticket|
+ ActsAsTenant.with_tenant(organisation) do
+ ticket.ticket_assignments.delete_all
+ TicketAssignmentSync.call(ticket: ticket, assignee_ids: [colleague.id], is_new_ticket: false)
+ end
+ end
+
+ rest, mcp, rest_ticket, mcp_ticket = compare({ remove_assignee_ids: [colleague.id] }, prepare: assign_colleague)
+
+ expect(rest).to eq(mcp)
+ expect(rest[:activities].map(&:first)).to eq(['ticket.unassigned'])
+ expect(rest[:subscriptions].map(&:first)).not_to include(colleague.id)
+ expect(reloaded([rest_ticket, mcp_ticket]) { |ticket| ticket.assignees.to_a }).to all(be_empty)
+ end
+
+ it 'renames with the same trail, once, and without a run' do
+ rest, mcp, rest_ticket, mcp_ticket = compare({ title: 'Login bricht in Safari ab' })
+
+ expect(rest).to eq(mcp)
+ expect(rest[:activities].map(&:first)).to eq(['ticket.title_changed'])
+ expect(rest[:activities].dig(0, 1)).to eq(writer.id)
+ expect(rest[:runs]).to be_empty
+ expect(rest[:notifications]).not_to be_empty
+ expect(reloaded([rest_ticket, mcp_ticket], &:title)).to all(eq('Login bricht in Safari ab'))
+ end
+end
diff --git a/spec/requests/api/v1/ticket_changes_spec.rb b/spec/requests/api/v1/ticket_changes_spec.rb
new file mode 100644
index 0000000..2c57d30
--- /dev/null
+++ b/spec/requests/api/v1/ticket_changes_spec.rb
@@ -0,0 +1,745 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: POST /api/v1/tickets/:id/changes changes one thing on a ticket, by the rule
+# the MCP tool update_ticket changes it by (Tickets::Change, cli_rest_plan
+# D3): the title, the status, or the assignees added and removed against
+# the current list.
+# Type: request spec.
+# Why: PATCH /tickets/:id REPLACES the assignee list and knows no title, so the
+# terminal client gets its own endpoint. Pinned here: a person removed who
+# was not named, a person who may not be assigned passed over silently, a
+# status outside the project's catalogue written or another JSONB key
+# touched, a ticket that moved or was deleted changed or built anew, an
+# unreadable ticket telling itself apart from a missing one, a read-only
+# ticket or token writing, a replay writing twice, an exception text
+# reaching the client.
+RSpec.describe 'API V1 ticket changes', :ci_guard, type: :request do
+ let(:organisation) { create(:organisation) }
+ let(:user) { create(:user, language_preference: 'en') }
+ let(:colleague) { create(:user) }
+ let(:role) { create(:role, organisation: organisation) }
+ let(:project) { with_statuses(ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) }) }
+ let(:ticket) do
+ ActsAsTenant.with_tenant(organisation) do
+ create(:ticket, project: project, organisation: organisation, creator: user, title: 'Login bricht ab',
+ custom_attributes: { 'status' => statuses.first, 'priority' => 'high' })
+ end
+ end
+ let(:statuses) { in_org { TicketAttributeDefinition.ordered_value_keys_for(project, 'status') } }
+ let(:pat) { build_pat(user) }
+
+ before do
+ Prosopite.pause do
+ in_org do
+ create(:membership, user: user, organisation: organisation, role: role, active: true)
+ create(:membership, user: colleague, organisation: organisation, role: role, active: true)
+ create(:project_permission, user: user, project: project, tickets_access: :read_write)
+ create(:project_permission, user: colleague, project: project, tickets_access: :read_write)
+ end
+ ticket
+ end
+ end
+
+ after { ActsAsTenant.current_tenant = nil }
+
+ def in_org(&) = ActsAsTenant.with_tenant(organisation, &)
+
+ # The status field the board uses: a single select named "status".
+ def with_statuses(target, values = %w[open wip])
+ ActsAsTenant.with_tenant(target.organisation) do
+ create(:ticket_attribute_definition,
+ project: target, name: 'status', field_type: 'select', position: 1,
+ labels: { 'de' => 'Status', 'en' => 'Status' },
+ options: { 'allowed_values' => values.map { |value| { 'value' => value, 'labels' => { 'de' => "Label #{value}" } } } })
+ end
+ target
+ end
+
+ def build_pat(owner, read_only: false, project_scopes: {})
+ build(:personal_access_token, user: owner, organisations: [organisation], read_only: read_only,
+ project_scopes: project_scopes).tap do |token|
+ token.token_hash = nil
+ token.token_prefix = nil
+ token.generate_token!
+ end
+ end
+
+ def headers(token: pat, key: nil, json: true)
+ { 'Authorization' => "Bearer #{token.token}" }.tap do |h|
+ h['Idempotency-Key'] = key if key
+ h['Content-Type'] = 'application/json' if json
+ end
+ end
+
+ # JSON, for values a form cannot carry (numbers, null, lists).
+ def send_change(fields, ticket_id: ticket.id, token: pat, key: nil)
+ post "/api/v1/tickets/#{ticket_id}/changes", params: { change: fields }.to_json, headers: headers(token: token, key: key)
+ end
+
+ def change_raw(body, ticket_id: ticket.id)
+ post "/api/v1/tickets/#{ticket_id}/changes", params: body, headers: headers
+ end
+
+ def change_form(params, ticket_id: ticket.id)
+ post "/api/v1/tickets/#{ticket_id}/changes", params: params, headers: headers(json: false)
+ end
+
+ # Multipart, where a text part may name a charset of its own (Rack tags the
+ # string with it); JSON and forms always arrive as UTF-8.
+ def change_multipart(name, type, bytes)
+ boundary = 'r3b-boundary'
+ raw = "--#{boundary}\r\nContent-Disposition: form-data; name=\"change[#{name}]\"\r\nContent-Type: #{type}\r\n\r\n".b
+ raw << bytes.b << "\r\n--#{boundary}--\r\n".b
+ post "/api/v1/tickets/#{ticket.id}/changes", params: raw,
+ headers: headers(json: false).merge('Content-Type' => "multipart/form-data; boundary=#{boundary}")
+ end
+
+ def body = response.parsed_body
+
+ def reloaded = ActsAsTenant.without_tenant { Ticket.find(ticket.id) }
+
+ def assignee_ids
+ ActsAsTenant.without_tenant { TicketAssignment.where(ticket_id: ticket.id).pluck(:user_id) }
+ end
+
+ # Everything a write could leave behind, organisation-wide.
+ def written
+ Prosopite.pause do
+ ActsAsTenant.without_tenant do
+ [TicketBulkRun.count, Activity.count, TicketAssignment.count, Ticket.order(:id).pluck(:title, :custom_attributes)]
+ end
+ end
+ end
+
+ def assign(*people)
+ Prosopite.pause { in_org { people.each { |person| ticket.ticket_assignments.create!(user: person) } } }
+ end
+
+ # Written out, not read through I18n.t as the controller reads them: a missing
+ # or misspelt key would be compared with itself, and an English key that is
+ # missing falls back to the German text on both sides.
+ def invalid_input(text)
+ { 'error' => 'validation_failed', 'code' => 'invalid_input', 'errors' => [text] }
+ end
+
+ def refused(reason, *texts)
+ { 'error' => reason, 'code' => 'refused', 'reason' => reason, 'errors' => texts }
+ end
+
+ def expect_invalid_input(text)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq(invalid_input(text))
+ end
+
+ def expect_refused(reason, *texts)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq(refused(reason, *texts))
+ end
+
+ def one_kind = 'Give exactly one change: title, status, or add_assignee_ids and remove_assignee_ids.'
+
+ def unknown_keys = 'A change takes only title, status, add_assignee_ids and remove_assignee_ids.'
+
+ describe 'a status' do
+ it 'sets a key from the project catalogue and answers the summary, as PATCH does' do
+ expect { send_change({ status: statuses.last }) }.to change { TicketBulkRun.unscoped.count }.by(1)
+
+ expect(response).to have_http_status(:ok)
+ fresh = reloaded
+ summary = Prosopite.pause { in_org { Tickets::Serializer.new(current_user: user).summary(fresh) } }
+ expect(response.body).to eq({ data: summary }.to_json)
+ expect(body.dig('data', 'status')).to eq(statuses.last)
+ end
+
+ it 'leaves every other key of the JSONB as it was' do
+ send_change({ status: statuses.last })
+ expect(reloaded.custom_attributes).to eq('status' => statuses.last, 'priority' => 'high')
+ end
+
+ it 'takes a key with spaces around it' do
+ send_change({ status: " #{statuses.last} " })
+ expect(response).to have_http_status(:ok)
+ expect(reloaded.custom_attributes['status']).to eq(statuses.last)
+ end
+
+ # Display labels, other spellings, the keys of other projects: only the keys.
+ ['Label wip', 'WIP', 'erledigt'].each do |value|
+ it "refuses #{value.inspect} as no status of this project, writing nothing" do
+ before = written
+ send_change({ status: value })
+
+ expect_refused('value_not_allowed', 'This is no status of this project; use a key from meta.available_statuses.')
+ expect(written).to eq(before)
+ end
+ end
+
+ it 'never repeats the value it refused' do
+ value = "x#{27.chr}[31mROT\nzwei"
+ send_change({ status: value })
+ expect(response.body).not_to include('ROT')
+ end
+
+ it 'answers in the language of the token owner' do
+ Prosopite.pause { user.update!(language_preference: 'de') }
+ send_change({ status: 'erledigt' })
+
+ expect_refused('value_not_allowed',
+ 'Das ist kein Status dieses Projekts; bitte einen Schlüssel aus meta.available_statuses verwenden.')
+ end
+
+ context 'in a project without a status field' do
+ let(:project) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ let(:statuses) { ['frei'] }
+
+ it 'refuses, writing nothing' do
+ before = written
+ send_change({ status: 'wip' })
+
+ expect_refused('no_status_field', 'This project has no status field.')
+ expect(written).to eq(before)
+ end
+
+ # The board writes any active field of that name.
+ it 'refuses when "status" is a checkbox' do
+ Prosopite.pause do
+ in_org do
+ create(:ticket_attribute_definition, project: project, name: 'status', field_type: 'checkbox', position: 1,
+ labels: { 'de' => 'Status', 'en' => 'Status' }, options: {})
+ end
+ end
+ before = written
+ send_change({ status: 'true' })
+
+ expect_refused('no_status_field', 'This project has no status field.')
+ expect(written).to eq(before)
+ end
+ end
+ end
+
+ describe 'assignees' do
+ it 'adds a person and keeps who is on the ticket' do
+ assign(colleague)
+ send_change({ add_assignee_ids: [user.id] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to contain_exactly(user.id, colleague.id)
+ expect(body.dig('data', 'assignees').pluck('id')).to contain_exactly(user.id, colleague.id)
+ end
+
+ it 'removes only the person it names' do
+ assign(colleague, user)
+ send_change({ remove_assignee_ids: [colleague.id] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to eq([user.id])
+ end
+
+ it 'reads "me" as the token owner' do
+ assign(colleague)
+ send_change({ add_assignee_ids: ['me'] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to contain_exactly(user.id, colleague.id)
+ end
+
+ it 'removes the token owner with "me"' do
+ assign(colleague, user)
+ send_change({ remove_assignee_ids: ['me'] })
+
+ expect(assignee_ids).to eq([colleague.id])
+ end
+
+ it 'adds and removes in one change' do
+ assign(colleague)
+ send_change({ add_assignee_ids: ['me'], remove_assignee_ids: [colleague.id] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to eq([user.id])
+ end
+
+ it 'takes the lists from a form too' do
+ assign(colleague)
+ change_form({ change: { add_assignee_ids: ['me'] } })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to contain_exactly(user.id, colleague.id)
+ end
+
+ it 'refuses the same person in both lists, also as "me"' do
+ before = written
+ send_change({ add_assignee_ids: ['me'], remove_assignee_ids: [user.id] })
+
+ expect_invalid_input('add_assignee_ids and remove_assignee_ids name the same user.')
+ expect(written).to eq(before)
+ end
+
+ it 'takes 50 ids in a list and refuses 51' do
+ at_limit = Array.new(Tickets::Change::MAX_ASSIGNEE_IDS) { SecureRandom.uuid }
+
+ send_change({ add_assignee_ids: at_limit + [SecureRandom.uuid] })
+ expect_invalid_input('Name at most 50 users per list.')
+
+ # At the limit the shape passes; these random people are then refused by the project.
+ send_change({ add_assignee_ids: at_limit })
+ expect(body['reason']).to eq('value_not_allowed')
+ end
+
+ {
+ 'a list that is no list' => [{ add_assignee_ids: 'me' }, 'Give add_assignee_ids as a list of user ids or "me".'],
+ 'a number in the list' => [{ remove_assignee_ids: [5] }, 'Give remove_assignee_ids as a list of user ids or "me".'],
+ 'null as the list' => [{ add_assignee_ids: nil }, 'Give add_assignee_ids as a list of user ids or "me".'],
+ 'an entry that is no id' => [{ add_assignee_ids: ['oops'] }, 'add_assignee_ids holds a value that is no user id and not "me".'],
+ 'empty lists' => [{ add_assignee_ids: [], remove_assignee_ids: [] }, 'Name at least one user in add_assignee_ids or remove_assignee_ids.']
+ }.each do |label, (fields, text)|
+ it "refuses #{label}, writing nothing" do
+ assign(colleague)
+ before = written
+ send_change(fields)
+
+ expect_invalid_input(text)
+ expect(written).to eq(before)
+ end
+ end
+
+ it 'refuses a person the project does not offer loudly, and takes nobody off' do
+ assign(colleague)
+ before = written
+ send_change({ add_assignee_ids: [SecureRandom.uuid], remove_assignee_ids: [colleague.id] })
+
+ expect_refused('value_not_allowed', 'A user in this change cannot be assigned in this project.')
+ expect(written).to eq(before)
+ end
+
+ it 'refuses a member without access to the project, in the same words' do
+ outsider = Prosopite.pause do
+ create(:user).tap { |person| in_org { create(:membership, user: person, organisation: organisation, role: role, active: true) } }
+ end
+ before = written
+ send_change({ add_assignee_ids: [outsider.id] })
+
+ expect_refused('value_not_allowed', 'A user in this change cannot be assigned in this project.')
+ expect(written).to eq(before)
+ end
+
+ it 'refuses a person who lost access meanwhile, and takes nobody off' do
+ assign(colleague)
+ allow_any_instance_of(Ticket).to receive(:assignable_user_ids).and_return([])
+ before = written
+ send_change({ add_assignee_ids: ['me'], remove_assignee_ids: [colleague.id] })
+
+ expect_refused('user_not_assignable', 'Nothing was changed: a person in this change no longer has access to this project.')
+ expect(written).to eq(before)
+ end
+
+ context 'with a stale assignee, who lost access since' do
+ let(:stale) do
+ Prosopite.pause do
+ create(:user).tap { |person| in_org { create(:membership, user: person, organisation: organisation, role: role, active: false) } }
+ end
+ end
+
+ it 'keeps them when they are not named' do
+ assign(stale)
+ send_change({ add_assignee_ids: ['me'] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to contain_exactly(stale.id, user.id)
+ end
+
+ it 'takes them off when they are named' do
+ assign(stale)
+ send_change({ add_assignee_ids: ['me'], remove_assignee_ids: [stale.id] })
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to eq([user.id])
+ end
+ end
+ end
+
+ describe 'a title' do
+ it 'renames the ticket and leaves everyone on it' do
+ assign(colleague)
+ send_change({ title: ' Login bricht in Safari ab ' })
+
+ expect(response).to have_http_status(:ok)
+ expect(body.dig('data', 'title')).to eq('Login bricht in Safari ab')
+ expect(reloaded.title).to eq('Login bricht in Safari ab')
+ expect(reloaded.custom_attributes).to eq('status' => statuses.first, 'priority' => 'high')
+ expect(assignee_ids).to eq([colleague.id])
+ end
+
+ it 'runs no bulk run' do
+ expect { send_change({ title: 'Neu' }) }.not_to(change { TicketBulkRun.unscoped.count })
+ end
+
+ it 'takes 255 characters' do
+ send_change({ title: 'ä' * Ticket::TITLE_MAX_LENGTH })
+
+ expect(response).to have_http_status(:ok)
+ expect(reloaded.title).to eq('ä' * Ticket::TITLE_MAX_LENGTH)
+ end
+
+ {
+ 'nothing' => ['', 'The title (change[title]) has no visible text.'],
+ 'spaces alone' => [' ', 'The title (change[title]) has no visible text.'],
+ '256 characters' => ['a' * 256, 'The title (change[title]) is longer than 255 characters.'],
+ 'a line break' => ["a\nb", 'The title (change[title]) must be one line without control characters.'],
+ 'a control character' => ["a#{7.chr}b", 'The title (change[title]) must be one line without control characters.'],
+ 'a NUL byte' => ["a#{0.chr}b", 'The title (change[title]) must be one line without control characters.'],
+ 'a zero-width space' => ["x#{0x200B.chr(Encoding::UTF_8)}y", 'The title (change[title]) must be one line without control characters.'],
+ 'a number' => [5, 'Give the title (change[title]) as text.'],
+ 'null' => [nil, 'Give the title (change[title]) as text.'],
+ 'a list' => [['Neu'], 'Give the title (change[title]) as text.']
+ }.each do |label, (value, text)|
+ it "refuses #{label}, writing nothing" do
+ before = written
+ send_change({ title: value })
+
+ expect_invalid_input(text)
+ expect(written).to eq(before)
+ end
+ end
+
+ # A real model refusal: a ticket that lost its number cannot be saved.
+ it 'answers a title the model refuses with the messages of the model' do
+ Prosopite.pause { in_org { ticket.update_column(:number, nil) } }
+ send_change({ title: 'Neu' })
+
+ expect_refused('validation_failed', 'The title could not be saved.', "Number can't be blank")
+ expect(reloaded.title).to eq('Login bricht ab')
+ end
+ end
+
+ describe 'what a change is' do
+ {
+ 'title and status' => { title: 'x', status: 'wip' },
+ 'status and a list' => { status: 'wip', add_assignee_ids: ['me'] },
+ 'an empty title next to a status' => { title: '', status: 'wip' },
+ 'a null title next to a status' => { title: nil, status: 'wip' },
+ 'an empty list next to a title' => { title: 'x', remove_assignee_ids: [] },
+ 'an empty object' => {}
+ }.each do |label, fields|
+ it "refuses #{label}, by the keys present, writing nothing" do
+ before = written
+ send_change(fields)
+
+ expect_invalid_input(one_kind)
+ expect(written).to eq(before)
+ end
+ end
+
+ { 'no body' => '{}', 'a string' => '{"change":"status"}', 'a number' => '{"change":5}', 'null' => '{"change":null}',
+ 'a list' => '{"change":[{"status":"open"}]}', 'the change on top' => '{"status":"open"}' }.each do |label, raw|
+ it "refuses #{label} in place of a change" do
+ before = written
+ change_raw(raw)
+
+ expect_invalid_input(one_kind)
+ expect(written).to eq(before)
+ end
+ end
+
+ it 'refuses a key it does not know instead of ignoring it, and repeats nothing of it' do
+ before = written
+ send_change({ status: 'wip', priority: 'low', "x#{27.chr}[2J" => 1 })
+
+ expect_invalid_input(unknown_keys)
+ expect(response.body).not_to include('priority')
+ expect(written).to eq(before)
+ end
+
+ # The list PATCH takes REPLACES; a guess at it must not read as done.
+ it 'refuses assignee_ids' do
+ before = written
+ send_change({ assignee_ids: [user.id] })
+
+ expect_invalid_input(unknown_keys)
+ expect(written).to eq(before)
+ end
+
+ # Never reaches the rule: Rails refuses raw bytes in a form as a 400.
+ it 'writes nothing for a key of raw bytes in a form' do
+ before = written
+ post "/api/v1/tickets/#{ticket.id}/changes", params: 'change[x%FF]=1&change[status]=wip',
+ headers: headers(json: false).merge('Content-Type' => 'application/x-www-form-urlencoded')
+
+ expect(response).to have_http_status(:bad_request)
+ expect(written).to eq(before)
+ end
+
+ # The patterns of the title rule raise on these; a part named UTF-16 never
+ # gets here, Rack's own parser raises on it.
+ { 'Latin-1' => ['text/plain; charset=iso-8859-1', "M\xFCller"], 'binary' => ['text/plain; charset=binary', "M\xC3\xBCller"] }.each do |label, (type, bytes)|
+ it "refuses a #{label} part instead of crashing on it" do
+ before = written
+ change_multipart('title', type, bytes)
+
+ expect_invalid_input('The change cannot be read as UTF-8.')
+ expect(written).to eq(before)
+ end
+ end
+
+ it 'takes a multipart part in UTF-8' do
+ change_multipart('title', 'text/plain; charset=utf-8', 'Müller')
+
+ expect(response).to have_http_status(:ok)
+ expect(reloaded.title).to eq('Müller')
+ end
+ end
+
+ describe 'rights and existence' do
+ let(:not_found_body) { '{"error":"not_found","code":"not_found"}' }
+
+ # Input of every class: fine, unusable, unknown, none.
+ inputs = {
+ 'a usable change' => '{"change":{"title":"Gekapert"}}',
+ 'a mixed change' => '{"change":{"title":"x","status":"y"}}',
+ 'an unknown key' => '{"change":{"priority":"low"}}',
+ 'a title it refuses' => '{"change":{"title":""}}',
+ 'no change' => '{}'
+ }
+
+ inputs.each do |label, raw|
+ describe "with #{label}" do
+ it 'answers a missing ticket 404' do
+ before = written
+ change_raw(raw, ticket_id: SecureRandom.uuid)
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ expect(written).to eq(before)
+ end
+
+ it 'answers a ticket the owner may not read with the same 404' do
+ hidden = Prosopite.pause do
+ in_org do
+ notes_only = create(:project, organisation: organisation)
+ create(:project_permission, user: user, project: notes_only, notes_access: :read_only)
+ create(:ticket, project: notes_only, organisation: organisation, creator: colleague, title: 'Vertraulich')
+ end
+ end
+ before = written
+ change_raw(raw, ticket_id: hidden.id)
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ expect(written).to eq(before)
+ end
+
+ it 'answers a ticket of a foreign organisation with the same 404' do
+ foreign = Prosopite.pause do
+ other = create(:organisation)
+ ActsAsTenant.with_tenant(other) do
+ create(:ticket, organisation: other, project: create(:project, organisation: other), creator: create(:user), title: 'Fremd')
+ end
+ end
+ before = written
+ change_raw(raw, ticket_id: foreign.id)
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ expect(written).to eq(before)
+ end
+
+ it 'answers a ticket that may be read and not written 403, before the input' do
+ Prosopite.pause { in_org { ProjectPermission.find_by!(user: user, project: project).update!(tickets_access: :read_only) } }
+ before = written
+ change_raw(raw)
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.body).to eq('{"error":"forbidden","code":"forbidden"}')
+ expect(written).to eq(before)
+ end
+
+ it 'answers a read-only token 403 read_only, before anything' do
+ read_only = Prosopite.pause { build_pat(user, read_only: true) }
+ before = written
+ expect(Ticket).not_to receive(:where)
+ post "/api/v1/tickets/#{ticket.id}/changes", params: raw, headers: headers(token: read_only)
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.body).to eq('{"error":"forbidden","code":"read_only"}')
+ expect(written).to eq(before)
+ end
+ end
+ end
+
+ it 'answers a malformed id with the same 404' do
+ change_raw('{"change":{"title":"x"}}', ticket_id: 'oops')
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ end
+
+ it 'answers a ticket outside the token with the same 404' do
+ elsewhere = Prosopite.pause { in_org { create(:project, organisation: organisation) } }
+ narrow = Prosopite.pause { build_pat(user, project_scopes: { organisation => [elsewhere] }) }
+ before = written
+ send_change({ title: 'Gekapert' }, token: narrow)
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ expect(written).to eq(before)
+ end
+
+ it 'answers a token of a deactivated member with the same 404' do
+ Prosopite.pause { in_org { Membership.find_by!(user: user, organisation: organisation).update!(active: false) } }
+ before = written
+ send_change({ title: 'Gekapert' })
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq(not_found_body)
+ expect(written).to eq(before)
+ end
+
+ it 'lets an account admin without a project permission change the ticket' do
+ admin = Prosopite.pause do
+ create(:user).tap do |person|
+ in_org { create(:membership, user: person, organisation: organisation, role: create(:admin_role, organisation: organisation)) }
+ end
+ end
+ send_change({ status: statuses.last }, token: Prosopite.pause { build_pat(admin) })
+
+ expect(response).to have_http_status(:ok)
+ expect(reloaded.custom_attributes['status']).to eq(statuses.last)
+ end
+
+ it 'asks the write right of the ticket itself' do
+ expect_any_instance_of(TicketPolicy).to receive(:update?).and_call_original
+ send_change({ title: 'Neu' })
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ # The ticket changes after the rights check. SaveTicket finds a ticket
+ # organisation-wide and builds a new one for an id it does not find.
+ describe 'a ticket that leaves after the rights check' do
+ def after_the_rights_check(&block)
+ allow_any_instance_of(Tickets::Change).to receive(:write).and_wrap_original do |original, **kwargs|
+ block.call
+ original.call(**kwargs)
+ end
+ end
+
+ { 'title' => { title: 'Gekapert' }, 'status' => { status: 'wip' }, 'assignees' => { add_assignee_ids: ['me'] } }.each do |kind, fields|
+ it "answers a #{kind} change on a moved ticket like a missing one and leaves it alone" do
+ elsewhere = Prosopite.pause { in_org { create(:project, organisation: organisation) } }
+ after_the_rights_check { ActsAsTenant.without_tenant { Ticket.where(id: ticket.id).update_all(project_id: elsewhere.id) } }
+ send_change(fields)
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq('{"error":"not_found","code":"not_found"}')
+ expect(reloaded).to have_attributes(title: 'Login bricht ab', custom_attributes: { 'status' => statuses.first, 'priority' => 'high' })
+ expect(assignee_ids).to be_empty
+ end
+ end
+
+ it 'builds no ticket for a deleted one' do
+ after_the_rights_check { ActsAsTenant.without_tenant { Ticket.where(id: ticket.id).delete_all } }
+ send_change({ title: 'Phantom' })
+
+ expect(response).to have_http_status(:not_found)
+ expect(response.body).to eq('{"error":"not_found","code":"not_found"}')
+ expect(ActsAsTenant.without_tenant { Ticket.where(title: 'Phantom') }).not_to exist
+ end
+ end
+
+ describe 'a failure the rule does not name' do
+ let(:secret) { 'PG::Error: secret detail' }
+
+ def failing(code)
+ Actors::BaseActor::Result.new(success: false, errors: [secret], code: code)
+ end
+
+ it 'answers an unexpected actor failure 500, without its message' do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(failing(:internal_error))
+ send_change({ status: statuses.last })
+
+ expect(response).to have_http_status(:internal_server_error)
+ expect(body).to eq('error' => 'internal_error', 'code' => 'refused', 'reason' => 'internal_error')
+ expect(response.body).not_to include(secret)
+ end
+
+ it 'does the same for a title' do
+ allow(Actors::SaveTicket).to receive(:call).and_return(failing(:internal_error))
+ send_change({ title: 'Neu' })
+
+ expect(response).to have_http_status(:internal_server_error)
+ expect(response.body).not_to include(secret)
+ end
+
+ it 'never repeats the text of any other code' do
+ allow(Actors::ApplyTicketChanges).to receive(:call).and_return(failing(:stale_object))
+ send_change({ status: statuses.last })
+
+ expect(response).to have_http_status(:internal_server_error)
+ expect(response.body).not_to include(secret)
+ end
+ end
+
+ describe 'idempotency' do
+ let(:key) { 'r3b-term-1' }
+
+ it 'answers a repeated key with the first answer and writes once' do
+ send_change({ status: statuses.last }, key: key)
+ first = [response.status, response.body]
+ before = written
+
+ send_change({ status: statuses.last }, key: key)
+
+ expect([response.status, response.body]).to eq(first)
+ expect(written).to eq(before)
+ end
+
+ it 'keeps one run and one activity across the replay' do
+ expect do
+ send_change({ add_assignee_ids: ['me'] }, key: key)
+ send_change({ add_assignee_ids: ['me'] }, key: key)
+ end.to change { ActsAsTenant.without_tenant { [TicketBulkRun.count, Activity.where(trackable_id: ticket.id).count] } }.by([1, 1])
+ end
+
+ it 'refuses the key with another body' do
+ send_change({ status: statuses.last }, key: key)
+ before = written
+
+ send_change({ status: statuses.first }, key: key)
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body['error']).to eq('idempotency_key_reused')
+ expect(body['code']).to eq('invalid_input')
+ expect(written).to eq(before)
+ end
+
+ # A refused write is not pinned to its key: once the project offers the
+ # status, the same request with the same key writes.
+ it 'does not store a refused change' do
+ send_change({ status: 'review' }, key: key)
+ expect(body['reason']).to eq('value_not_allowed')
+
+ Prosopite.pause do
+ in_org do
+ definition = project.ticket_attribute_definitions.find_by!(name: 'status')
+ definition.update!(options: { 'allowed_values' => definition.options['allowed_values'] +
+ [{ 'value' => 'review', 'labels' => { 'de' => 'review' } }] })
+ end
+ end
+ send_change({ status: 'review' }, key: key)
+
+ expect(response).to have_http_status(:ok)
+ expect(reloaded.custom_attributes['status']).to eq('review')
+ end
+ end
+
+ describe 'PATCH beside it' do
+ it 'still replaces the list, and takes no title' do
+ assign(colleague)
+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { assignee_ids: [user.id], title: 'Neu' } }.to_json, headers: headers
+
+ expect(response).to have_http_status(:ok)
+ expect(assignee_ids).to eq([user.id])
+ expect(reloaded.title).to eq('Login bricht ab')
+ end
+ end
+end
diff --git a/spec/requests/api/v1/ticket_existence_spec.rb b/spec/requests/api/v1/ticket_existence_spec.rb
index fa0feda..d7bb1ad 100644
--- a/spec/requests/api/v1/ticket_existence_spec.rb
+++ b/spec/requests/api/v1/ticket_existence_spec.rb
@@ -2,7 +2,7 @@
require 'rails_helper'
-# Missing and unreadable UUIDs have the same HTTP contract on all seven ticket
+# Missing and unreadable UUIDs have the same HTTP contract on all eight ticket
# member routes. Query counts deliberately differ: tenant discovery reads only
# the two routing IDs before the scoped lookup. Each example sends one request.
RSpec.describe 'REST ticket existence', :ci_guard, type: :request do
@@ -74,7 +74,8 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request do
[:get, '/attachments', {}],
[:get, '/time_sessions', {}],
[:post, '/time_sessions', { time_session: { duration_minutes: 30 } }],
- [:post, '/posts', { post: { body: 'A public comment' } }]
+ [:post, '/posts', { post: { body: 'A public comment' } }],
+ [:post, '/changes', { change: { title: 'Renamed by an admin' } }]
]
routes.each do |verb, suffix, payload|
@@ -112,10 +113,12 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request do
expect_any_instance_of(TicketPolicy).to receive(:show?).and_call_original
before = domain_state
request_ticket(verb, suffix, payload)
- expect(response).to have_http_status(verb == :post ? :created : :ok)
+ expect(response).to have_http_status(verb == :post && suffix != '/changes' ? :created : :ok)
after = domain_state
if verb == :patch
expect(after.first.fetch('custom_attributes').fetch('status')).to eq('closed')
+ elsif suffix == '/changes'
+ expect(after.first.fetch('title')).to eq('Renamed by an admin')
elsif verb == :post
key = suffix == '/posts' ? 1 : 2
expect(after[key]).to eq(before[key] + 1)
diff --git a/spec/requests/api/v1/write_endpoints_spec.rb b/spec/requests/api/v1/write_endpoints_spec.rb
index 4f741ba..5d3810e 100644
--- a/spec/requests/api/v1/write_endpoints_spec.rb
+++ b/spec/requests/api/v1/write_endpoints_spec.rb
@@ -626,7 +626,7 @@ RSpec.describe 'API V1 Write Endpoints', :ci_guard, type: :request do
def request_write(verb, path_spec, controller)
record_id = controller == 'api/v1/notifications' ? notification.id : ticket.id
path = path_spec.gsub(':project_id', project.id).gsub(':ticket_id', ticket.id).gsub(':id', record_id)
- params = { ticket: { title: 'Written anyway' }, post: { body: 'Written anyway' },
+ params = { ticket: { title: 'Written anyway' }, post: { body: 'Written anyway' }, change: { title: 'Written anyway' },
time_session: { occurred_on: '2026-05-20T10:00:00Z', duration_minutes: 30 } }
process verb.downcase.to_sym, path, params: params, headers: auth_headers
end