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.
Ruby agplai-assistantdockerdsgvogdprhotwireissue-trackerjira-alternativeknowledge-basellmmcp-servermeeting-notesopen-sourceproject-managementredmine-alternativeruby-on-railsself-hostedticketingtime-tracking
Let POST /api/v1/tickets/:ticket_id/posts take format plain by the MCP rule
Guido Boyke0e9c0d627730
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 782054e..93d47ba 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -268,6 +268,8 @@ jobs:spec/requests/api/mcp_people_spec.rbspec/services/posts/plain_text_body_spec.rbspec/services/lalabase/tools/post_comment_spec.rb+ spec/services/lalabase/tools/post_comment_failure_spec.rb+ spec/services/posts/comment_spec.rbspec/requests/api/inbox_organisation_filter_spec.rbspec/services/lalabase/tools/get_ticket_paging_spec.rbspec/services/lalabase/tools/get_ticket_assistant_limits_spec.rb@@ -294,6 +296,7 @@ jobs:spec/requests/api/v1/capabilities_spec.rbspec/requests/api/v1/people_spec.rbspec/requests/api/people_parity_spec.rb+ spec/requests/api/v1/post_comment_format_spec.rbspec/models/codebase_import_mapping_spec.rbspec/services/codebase_import/time_session_importer_spec.rbspec/services/codebase_import/duplicate_prevention_spec.rbdiff --git a/app/controllers/api/v1/posts_controller.rb b/app/controllers/api/v1/posts_controller.rbindex 2a51bba..b993bb1 100644--- a/app/controllers/api/v1/posts_controller.rb+++ b/app/controllers/api/v1/posts_controller.rb@@ -9,34 +9,68 @@ module Api# POST /api/v1/tickets/:ticket_id/posts#- # The web form's write (Actors::SavePost), so an API comment carries the same- # side effects: the post_added activity, the notifications, the author's marks- # read, the embedding. The record exists before #call for the policy.+ # Writes by the rule the MCP tool post_comment writes by (Posts::Comment,+ # REST R3a): post[format] html, the default, stores the body as sent;+ # plain stores literal text, escaped. The write is the web form's+ # (Actors::SavePost), so an API comment carries the same side effects: the+ # post_added activity, the notifications, the author's marks read, the+ # embedding. The input is checked inside the read gate, so a refusal of it+ # only ever answers for a ticket the token can read.def createwith_readable_ticket(params[:ticket_id]) do |ticket|- actor = Actors::SavePost.new(ticket: ticket, current_user: current_user, params: post_attributes)- authorize actor.record, :create?+ comment = Posts::Comment.parse(**comment_input)+ next render_comment_refusal(comment.refusal) if refused_here?(comment)- result = actor.call+ post = comment.build(ticket: ticket, current_user: current_user)+ authorize post, :create?++ result = comment.saveif result.success?- render json: { data: serialize(actor.record) }, status: :created+ render json: { data: serialize(post) }, status: :createdelse- render_error(error: 'validation_failed', errors: result.errors, status: :unprocessable_entity)+ render_comment_failure(result)endendendprivate- def post_attributes- attributes = { is_private: [true, 'true'].include?(post_params[:is_private]),- visible_to_user_id: post_params[:visible_to_user_id] }- attributes[:content] = post_params[:body] if post_params[:body].present?- attributes+ # Without format (and with html) an empty body stays the model's refusal,+ # answered after the write check with every message the model has: the+ # answer this endpoint gave before R3a, which existing callers read. A+ # plain body that converts to nothing is the rule's refusal.+ def refused_here?(comment)+ comment.refused? && (comment.plain? || comment.refusal != :body_empty)+ end++ def render_comment_refusal(refusal)+ render_error(error: 'validation_failed', errors: [I18n.t("services.post_comment.#{refusal}")],+ status: :unprocessable_entity)end- def post_params- params.require(:post).permit(:body, :is_private, :visible_to_user_id)+ # A failure the actor did not expect (BaseActor answers :internal_error+ # where it does not re-raise) is no refusal of the input: a 500 without the+ # exception's text, which may name the database. Every other failure+ # answers as it always did.+ def render_comment_failure(result)+ return render_error(error: 'internal_error', status: :internal_server_error) if result.code == :internal_error++ render_error(error: 'validation_failed', errors: result.errors, status: :unprocessable_entity)+ end++ # The format is read raw, not through permit: strong parameters drop a+ # list or an object, which would have written the comment as html. Given,+ # it goes to the rule as it came (null included); absent, it is html.+ def comment_input+ input = params.require(:post)+ # A post that is no object (post=text) answers like a missing one.+ raise ActionController::ParameterMissing, :post unless input.is_a?(ActionController::Parameters)++ permitted = input.permit(:body, :is_private, :visible_to_user_id)+ fields = { body: permitted[:body], is_private: permitted[:is_private],+ visible_to_user_id: permitted[:visible_to_user_id] }+ fields[:format] = input[:format] if input.key?(:format)+ fieldsenddef serialize(post)diff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rbindex 3d0da2d..02b3d05 100644--- a/app/services/api/v1/capabilities.rb+++ b/app/services/api/v1/capabilities.rb@@ -15,8 +15,8 @@ module Apimodule Capabilities# Minor for an additive change (a new endpoint, field or capability), major# never: an existing name, field or meaning does not change. 1.2.0: people.list and- # people.show (People S3b).- API_VERSION = '1.2.0'+ # people.show (People S3b). 1.3.0: posts.plain (REST R3a).+ API_VERSION = '1.3.0'# name => [verb, path as the router spells it]ENDPOINTS = {@@ -43,8 +43,10 @@ module Api}.freeze# Abilities that are not one endpoint: `idempotency` (the Idempotency-Key- # header on every write, D7) and `error_codes` (`code` on every error body, D6).- FEATURES = %w[idempotency error_codes].freeze+ # header on every write, D7), `error_codes` (`code` on every error body, D6)+ # and `posts.plain` (posts.create takes post[format] html or plain, by the+ # rule the MCP tool post_comment writes by, Posts::Comment; R3a).+ FEATURES = %w[idempotency error_codes posts.plain].freezedef self.names(ENDPOINTS.keys + FEATURES).sortdiff --git a/config/locales/services.de.yml b/config/locales/services.de.ymlindex 0254f2d..1c35399 100644--- a/config/locales/services.de.yml+++ b/config/locales/services.de.yml@@ -161,6 +161,15 @@ de:request_refused_own_access: "Der KI-Anbieter hat die Anfrage abgelehnt. Diese Organisation nutzt einen eigenen Zugang: Ein Administrator kann in den KI-Einstellungen prüfen, ob das Modell verfügbar ist und Guthaben besteht."post_update:unexpected_error: "Unerwarteter Fehler: %{error}"+ # The refusals of a comment written through a token (Posts::Comment), as+ # the HTTP API answers them; the MCP tool post_comment keeps its own+ # English texts.+ post_comment:+ format_not_string: "Bitte geben Sie das Format (post[format]) als Text an: html oder plain."+ format_unknown: "Das Format (post[format]) muss html oder plain sein."+ body_invalid_utf8: "Der Kommentar (post[body]) ist kein gültiges UTF-8."+ body_nul: "Ein Kommentar im Format plain (post[body]) darf keine NUL-Bytes enthalten."+ body_empty: "Bitte geben Sie einen Kommentartext (post[body]) an."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.ymlindex 8f9f1ce..fc03ad8 100644--- a/config/locales/services.en.yml+++ b/config/locales/services.en.yml@@ -161,6 +161,15 @@ en:request_refused_own_access: "The AI provider refused the request. This organisation uses its own access: an administrator can check in the AI settings that the model is available and that there is credit."post_update:unexpected_error: "Unexpected error: %{error}"+ # The refusals of a comment written through a token (Posts::Comment), as+ # the HTTP API answers them; the MCP tool post_comment keeps its own+ # English texts.+ post_comment:+ format_not_string: "Give the format (post[format]) as text: html or plain."+ format_unknown: "The format (post[format]) must be html or plain."+ body_invalid_utf8: "The comment (post[body]) is not valid UTF-8."+ body_nul: "A plain comment (post[body]) must not contain NUL bytes."+ body_empty: "The comment (post[body]) has no text."default_smart_folder:my_tasks: "My Tasks"high_priority: "High Priority"diff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rbindex 9cbb676..48dfef3 100644--- a/spec/contracts/mcp_contract_recorder.rb+++ b/spec/contracts/mcp_contract_recorder.rb@@ -586,12 +586,34 @@ module McpContract# (and with `format: html`) were recorded before R3a and must stay as# they were: existing callers send no format.def rest_comment_calls- login = "/api/v1/tickets/#{id(:login_ticket)}/posts"+ path = ->(ticket) { "/api/v1/tickets/#{id(ticket)}/posts" }+ login = path.call(:login_ticket)+ plain = { format: 'plain', body: "Zeile 1\nZeile 2\n\nAbsatz <b>&" }+ once = { post: { format: 'plain', body: 'Per REST, einmal, als Text.' } }+ key = 'contract-rest-comment-1'{'html' => rest_send(:post, :write, login, params: { post: { body: '<p>Ein <b>fetter</b> Satz & mehr</p>' } }),'html_named' => rest_send(:post, :write, login, params: { post: { format: 'html', body: '<p>Noch ein <i>Satz</i></p>' } }),# The model refuses an empty body, with its own message.- 'html_empty' => rest_send(:post, :write, login, params: { post: { body: '' } })+ 'html_empty' => rest_send(:post, :write, login, params: { post: { body: '' } }),+ # R3a: literal text, escaped, in paragraphs and line breaks.+ 'plain' => rest_send(:post, :write, login, params: { post: plain }),+ 'plain_private' => rest_send(:post, :write, login, params: { post: { format: 'plain', is_private: true, body: '<privat>' } }),+ 'invalid_input_format' => rest_send(:post, :write, login, params: { post: { format: 'markdown', body: 'x' } }),+ 'invalid_input_empty' => rest_send(:post, :write, login, params: { post: { format: 'plain', body: '' } }),+ # Unicode whitespace alone is no text, although String#strip keeps it.+ 'invalid_input_whitespace' => rest_send(:post, :write, login,+ params: { post: { format: 'plain', body: " \n#{0xA0.chr(Encoding::UTF_8)}" } }),+ 'invalid_input_nul' => rest_send(:post, :write, login, params: { post: { format: 'plain', body: "a#{0.chr}b" } }),+ 'not_found' => rest_send(:post, :write, path.call(:missing), params: { post: plain }),+ # No read access to the ticket: answered like a missing one.+ 'hidden' => rest_send(:post, :write, path.call(:hidden_ticket), params: { post: plain }),+ # Anna reads the archive's tickets, she may not write them.+ 'forbidden' => rest_send(:post, :write, path.call(:archived_ticket), params: { post: plain }),+ 'read_only' => rest_send(:post, :read, login, params: { post: plain }),+ 'idempotency_first' => rest_send(:post, :write, login, params: once, key: key),+ 'idempotency_replay' => rest_send(:post, :write, login, params: once, key: key),+ 'idempotency_mismatch' => rest_send(:post, :write, login, params: { post: { format: 'plain', body: 'Anderer Text' } }, key: key)}enddiff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.jsonindex 894def5..04ce9a0 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": "f21d59e33e5dbbe4f15365c6b7d6b429f11184f7",+ "core_commit": "fa34b08abd15cca2628402543c953cd075a26c77","core_dirty": true,- "contract_sha256": "ef502440d07806d550dca180a6bc947ab361a9f85a8155c19e26843f3875b230"+ "contract_sha256": "a4c77ae287c11f6984df3d0451d379150f5af5e1c7322fff9b0e55213b2ad865"},"contract": {"mcp": {@@ -3654,7 +3654,7 @@"all_projects": true}],- "api_version": "1.2.0",+ "api_version": "1.3.0","capabilities": ["error_codes","idempotency",@@ -3667,6 +3667,7 @@"people.list","people.show","posts.create",+ "posts.plain","projects.list","projects.ticket_attribute_definitions","tickets.activities",@@ -3713,7 +3714,7 @@"all_projects": true}],- "api_version": "1.2.0",+ "api_version": "1.3.0","capabilities": ["error_codes","idempotency",@@ -3726,6 +3727,7 @@"people.list","people.show","posts.create",+ "posts.plain","projects.list","projects.ticket_attribute_definitions","tickets.activities",@@ -4680,6 +4682,331 @@]}}+ },+ "plain": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Zeile 1\nZeile 2\n\nAbsatz <b>&"+ }+ }+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-10>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p>Zeile 1<br>Zeile 2</p><p>Absatz <b>&</p>",+ "body_text": "Zeile 1\nZeile 2\n\nAbsatz <b>&",+ "is_private": false,+ "visible_to_user_id": null,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "plain_private": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "is_private": true,+ "body": "<privat>"+ }+ }+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-11>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p><privat></p>",+ "body_text": "<privat>",+ "is_private": true,+ "visible_to_user_id": "00000000-0000-4000-8000-000000000011",+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "invalid_input_format": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "markdown",+ "body": "x"+ }+ }+ },+ "response": {+ "status": 422,+ "body": {+ "error": "validation_failed",+ "code": "invalid_input",+ "errors": [+ "Das Format (post[format]) muss html oder plain sein."+ ]+ }+ }+ },+ "invalid_input_empty": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": ""+ }+ }+ },+ "response": {+ "status": 422,+ "body": {+ "error": "validation_failed",+ "code": "invalid_input",+ "errors": [+ "Bitte geben Sie einen Kommentartext (post[body]) an."+ ]+ }+ }+ },+ "invalid_input_whitespace": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": " \n "+ }+ }+ },+ "response": {+ "status": 422,+ "body": {+ "error": "validation_failed",+ "code": "invalid_input",+ "errors": [+ "Bitte geben Sie einen Kommentartext (post[body]) an."+ ]+ }+ }+ },+ "invalid_input_nul": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "a\u0000b"+ }+ }+ },+ "response": {+ "status": 422,+ "body": {+ "error": "validation_failed",+ "code": "invalid_input",+ "errors": [+ "Ein Kommentar im Format plain (post[body]) darf keine NUL-Bytes enthalten."+ ]+ }+ }+ },+ "not_found": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000999/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Zeile 1\nZeile 2\n\nAbsatz <b>&"+ }+ }+ },+ "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/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Zeile 1\nZeile 2\n\nAbsatz <b>&"+ }+ }+ },+ "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/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Zeile 1\nZeile 2\n\nAbsatz <b>&"+ }+ }+ },+ "response": {+ "status": 403,+ "body": {+ "error": "forbidden",+ "code": "forbidden"+ }+ }+ },+ "read_only": {+ "token": "read",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Zeile 1\nZeile 2\n\nAbsatz <b>&"+ }+ }+ },+ "response": {+ "status": 403,+ "body": {+ "error": "forbidden",+ "code": "read_only"+ }+ }+ },+ "idempotency_first": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Per REST, einmal, als Text."+ }+ },+ "idempotency_key": "contract-rest-comment-1"+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-12>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p>Per REST, einmal, als Text.</p>",+ "body_text": "Per REST, einmal, als Text.",+ "is_private": false,+ "visible_to_user_id": null,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "idempotency_replay": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Per REST, einmal, als Text."+ }+ },+ "idempotency_key": "contract-rest-comment-1"+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-12>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p>Per REST, einmal, als Text.</p>",+ "body_text": "Per REST, einmal, als Text.",+ "is_private": false,+ "visible_to_user_id": null,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "idempotency_mismatch": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "format": "plain",+ "body": "Anderer Text"+ }+ },+ "idempotency_key": "contract-rest-comment-1"+ },+ "response": {+ "status": 422,+ "body": {+ "error": "idempotency_key_reused",+ "code": "invalid_input",+ "message": "idempotency_key already used with different parameters"+ }+ }}}}diff --git a/spec/requests/api/v1/capabilities_spec.rb b/spec/requests/api/v1/capabilities_spec.rbindex 8348aa0..2b3e9ed 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 doit 'names the API version and the capabilities beside the existing fields' dodata = me(token(read_only: false))- expect(data['api_version']).to eq('1.2.0')+ expect(data['api_version']).to eq('1.3.0')expect(data['capabilities']).to eq(Api::V1::Capabilities.names)expect(data.keys).to include('user', 'token', 'scoped_organisations')end@@ -46,7 +46,8 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request doexpect(Api::V1::Capabilities.names).to include('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'+ 'notifications.list', 'notifications.mark_as_read', 'people.list', 'people.show', 'idempotency', 'error_codes',+ 'posts.plain')enddiff --git a/spec/requests/api/v1/post_comment_format_spec.rb b/spec/requests/api/v1/post_comment_format_spec.rbnew file mode 100644index 0000000..e6614ec--- /dev/null+++ b/spec/requests/api/v1/post_comment_format_spec.rb@@ -0,0 +1,439 @@+# frozen_string_literal: true++require 'rails_helper'++# What: POST /api/v1/tickets/:ticket_id/posts writes by the rule the MCP tool+# post_comment writes by (Posts::Comment, cli_rest_plan R3 a): post[format]+# html (the default, the body stored as sent) or plain (literal text).+# Type: Request spec.+# Why: The terminal client comments over REST and sends literal text, never+# HTML it built itself. Before R3a REST took every body as HTML and checked+# neither its encoding nor NUL bytes. Pinned here: plain letting markup+# through, a NUL reaching the database, an input refusal telling a hidden+# ticket from a missing one, a private comment reaching people it is not+# for, the side effects of the web form missing, a replay writing twice,+# the answer without format changing, an exception text reaching the client.+RSpec.describe 'API V1 comment format', :ci_guard, type: :request do+ let(:organisation) { create(:organisation) }+ let(:user) { create(:user, language_preference: 'en') }+ let(:role) { create(:role, organisation: organisation) }+ let(:project) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }+ let(:ticket) do+ ActsAsTenant.with_tenant(organisation) { create(:ticket, project: project, organisation: organisation, creator: user) }+ end+ let(:read_only) { false }+ let(:pat) do+ build(:personal_access_token, user: user, organisations: [organisation], read_only: read_only).tap do |token|+ token.token_hash = nil+ token.token_prefix = nil+ token.generate_token!+ end+ end+ let!(:permission) do+ ActsAsTenant.with_tenant(organisation) do+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end+ end++ def headers(key: nil, json: false)+ { 'Authorization' => "Bearer #{pat.token}" }.tap do |h|+ h['Idempotency-Key'] = key if key+ h['Content-Type'] = 'application/json' if json+ end+ end++ # Form-encoded, as most callers send it.+ def comment(ticket_id: ticket.id, key: nil, **fields)+ post "/api/v1/tickets/#{ticket_id}/posts", params: { post: fields }, headers: headers(key: key)+ end++ # JSON, for values a form cannot carry (numbers, booleans, null, lists).+ def comment_json(fields, ticket_id: ticket.id)+ post "/api/v1/tickets/#{ticket_id}/posts", params: { post: fields }.to_json, headers: headers(json: true)+ end++ def body = response.parsed_body++ def posts_count = ActsAsTenant.without_tenant { Post.count }++ def saved = ActsAsTenant.without_tenant { Post.find(body.dig('data', 'id')) }++ def refusal(key, locale: :en)+ { 'error' => 'validation_failed', 'code' => 'invalid_input', 'errors' => [I18n.t("services.post_comment.#{key}", locale: locale)] }+ end++ def nbsp = 0xA0.chr(Encoding::UTF_8)++ describe 'format plain' do+ let(:text) { "Zeile 1\nZeile 2\n\nAbsatz <b>&" }++ it 'stores literal text: paragraphs, line breaks and escaped markup' do+ expect { comment(format: 'plain', body: text) }.to change { posts_count }.by(1)+ expect(response).to have_http_status(:created)+ expect(body.dig('data', 'body_text')).to eq(text)+ expect(body.dig('data', 'body_html')).to eq('<p>Zeile 1<br>Zeile 2</p><p>Absatz <b>&</p>')+ expect(saved.plain_text_version).to eq(text)+ end++ it 'takes CRLF as LF and drops blank lines at the edges' do+ comment(format: 'plain', body: "\r\n \r\nZeile 1\r\nZeile 2\r\n\r\n")+ expect(body.dig('data', 'body_text')).to eq("Zeile 1\nZeile 2")+ expect(body.dig('data', 'body_html')).to eq('<p>Zeile 1<br>Zeile 2</p>')+ end++ {+ 'a script' => '<script>alert(1)</script>',+ 'an image with a handler' => '<img src=x onerror=alert(1)>',+ 'entities' => '<tag> & <b>',+ 'operators' => 'a < b && c > d'+ }.each do |label, text|+ it "lands #{label} as text, never as markup" do+ comment(format: 'plain', body: text)+ expect(response).to have_http_status(:created)+ expect(body.dig('data', 'body_text')).to eq(text)+ fragment = Nokogiri::HTML.fragment(body.dig('data', 'body_html'))+ expect(fragment.css('*').map(&:name).uniq).to eq(['p'])+ expect(fragment.text).to eq(text)+ end+ end++ it 'answers the fields the endpoint always answered' do+ comment(format: 'plain', body: 'x')+ expect(body['data'].keys).to eq(%w[id ticket_id author body_html body_text is_private visible_to_user_id created_at updated_at])+ end+ end++ # Existing callers (gboyke/lalabase-mcp among them) send no format. Their+ # answer stays byte for byte, refusals and their order included; the contract+ # recorded it before R3a (rest > POST /api/v1/tickets/:ticket_id/posts).+ describe 'without format, as before R3a' do+ it 'stores the body as sent and answers in the old shape, byte for byte' do+ html = '<p><b>fett</b> & mehr</p>'+ comment(body: html)+ expect(response).to have_http_status(:created)+ post_record = saved+ expected = { data: { id: post_record.id, ticket_id: ticket.id, author: { id: user.id, name: user.display_name },+ body_html: html, body_text: 'fett & mehr', is_private: false, visible_to_user_id: nil,+ created_at: post_record.created_at.iso8601, updated_at: post_record.updated_at.iso8601 } }+ expect(response.body).to eq(expected.to_json)+ end++ it 'answers format html exactly like no format' do+ comment(body: '<p>Gleich</p>')+ without = body['data'].except('id', 'created_at', 'updated_at')+ comment(format: 'html', body: '<p>Gleich</p>')+ expect(body['data'].except('id', 'created_at', 'updated_at')).to eq(without)+ end++ it 'keeps a NUL byte in an html body as before: the HTML parser drops it' do+ comment(body: "a#{0.chr}b")+ expect(response).to have_http_status(:created)+ expect(body.dig('data', 'body_text')).to eq('ab')+ end++ it 'takes a body that is no string as its text, as before' do+ comment_json({ body: true })+ expect(response).to have_http_status(:created)+ expect(body.dig('data', 'body_html')).to eq('true')+ end++ it 'leaves an empty body to the model, which refuses it with its own message' do+ expect { comment(body: '') }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(response.body).to eq('{"error":"validation_failed","code":"invalid_input","errors":["Content can\'t be blank"]}')+ end++ it 'checks the write right before the empty body, as before' do+ ActsAsTenant.with_tenant(organisation) { ProjectPermission.find_by!(user: user).update!(tickets_access: :read_only) }+ comment(body: ' ')+ expect(response).to have_http_status(:forbidden)+ expect(body).to eq('error' => 'forbidden', 'code' => 'forbidden')+ end++ it 'answers an empty body with a foreign addressee with every model message, as before' do+ expect { comment(body: '', is_private: true, visible_to_user_id: SecureRandom.uuid) }.not_to(change { posts_count })+ expect(response.body).to eq({ error: 'validation_failed', code: 'invalid_input',+ errors: ["Content can't be blank", 'Visible to user must be set for private posts',+ 'Visible to user must be a member of the organisation'] }.to_json)+ end+ end++ describe 'refusals: 422 invalid_input, nothing written' do+ {+ 'an unknown format' => [{ format: 'markdown', body: 'x' }, :format_unknown],+ 'a format in capitals' => [{ format: 'PLAIN', body: 'x' }, :format_unknown],+ 'an empty format' => [{ format: '', body: 'x' }, :format_unknown],+ 'an empty plain body' => [{ format: 'plain', body: '' }, :body_empty],+ 'a plain body of blank lines' => [{ format: 'plain', body: " \n\t\r\n " }, :body_empty],+ 'a plain body of a no-break space' => [{ format: 'plain', body: -> { nbsp } }, :body_empty],+ 'a plain body of an em space' => [{ format: 'plain', body: -> { 0x2003.chr(Encoding::UTF_8) } }, :body_empty],+ 'a NUL byte in a plain body' => [{ format: 'plain', body: "a#{0.chr}b" }, :body_nul]+ }.each do |label, (fields, key)|+ it "refuses #{label}" do+ fields = fields.transform_values { |value| value.is_a?(Proc) ? instance_exec(&value) : value }+ expect { comment(**fields) }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to eq(refusal(key))+ end+ end++ # Strong parameters let numbers and booleans through, and drop lists and+ # objects: without reading the raw value, a list as format would have+ # written the comment as html.+ { 'a number' => 1, 'a boolean' => true, 'null' => nil, 'a list' => ['plain'], 'an object' => { 'name' => 'plain' } }+ .each do |label, format|+ it "refuses #{label} as format over JSON, never a crash" do+ expect { comment_json({ format: format, body: 'x' }) }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to eq(refusal(:format_not_string))+ end+ end++ it 'refuses a NUL byte in a plain body sent as JSON' do+ expect { comment_json({ format: 'plain', body: "a#{0.chr}b" }) }.not_to(change { posts_count })+ expect(body).to eq(refusal(:body_nul))+ end++ it 'refuses a plain body that is a list or an object as empty' do+ expect { comment_json({ format: 'plain', body: ['x'] }) }.not_to(change { posts_count })+ expect(body).to eq(refusal(:body_empty))+ end++ it 'answers the refusal in the token owner language' do+ user.update!(language_preference: 'de')+ comment(format: 'markdown', body: 'x')+ expect(body).to eq(refusal(:format_unknown, locale: :de))+ end++ # Rails refuses a parameter that is no valid UTF-8 while it parses the+ # request, before any of this endpoint's code runs: the rule's+ # body_invalid_utf8 is reached over MCP only.+ it 'never lets invalid UTF-8 reach the rule: Rails answers 400 first' do+ expect do+ post "/api/v1/tickets/#{ticket.id}/posts", params: 'post[format]=plain&post[body]=a%FFb',+ headers: headers.merge('Content-Type' => 'application/x-www-form-urlencoded')+ end.not_to(change { posts_count })+ expect(response).to have_http_status(:bad_request)+ end++ it 'answers a post that is no object like a missing one, never a crash' do+ post "/api/v1/tickets/#{ticket.id}/posts", params: {}, headers: headers+ missing = [response.status, response.body]+ expect { comment_json('abc') }.not_to(change { posts_count })+ expect([response.status, response.body]).to eq(missing)+ expect(missing.first).to eq(400)+ end+ end++ describe 'who may comment' do+ def hide_ticket+ ActsAsTenant.with_tenant(organisation) do+ ProjectPermission.find_by!(user: user).update!(tickets_access: :no_access, notes_access: :read_only)+ end+ end++ it 'answers a missing and a hidden ticket the same, writing nothing' do+ comment(ticket_id: SecureRandom.uuid, format: 'plain', body: 'x')+ missing = [response.status, response.body]+ hide_ticket+ expect { comment(format: 'plain', body: 'x') }.not_to(change { posts_count })+ expect([response.status, response.body]).to eq(missing)+ expect(missing).to eq([404, { error: 'not_found', code: 'not_found' }.to_json])+ end++ # The input is checked inside the read gate: a refusal of it only ever+ # answers for a ticket the token can read, so it tells nothing the 404 does not.+ it 'answers a hidden ticket with an unusable comment like a missing one' do+ comment(ticket_id: SecureRandom.uuid, format: 'markdown', body: '')+ missing = [response.status, response.body]+ hide_ticket+ comment(format: 'markdown', body: '')+ expect([response.status, response.body]).to eq(missing)+ expect(missing.first).to eq(404)+ end++ it 'answers a ticket of another organisation like a missing one' do+ other = create(:organisation)+ foreign = ActsAsTenant.with_tenant(other) do+ create(:ticket, project: create(:project, organisation: other), organisation: other, creator: create(:user))+ end+ comment(ticket_id: SecureRandom.uuid, format: 'plain', body: 'x')+ missing = [response.status, response.body]+ expect { comment(ticket_id: foreign.id, format: 'plain', body: 'x') }.not_to(change { posts_count })+ expect([response.status, response.body]).to eq(missing)+ end++ it 'refuses a plain comment without the write right in the project, writing nothing' do+ ActsAsTenant.with_tenant(organisation) { ProjectPermission.find_by!(user: user).update!(tickets_access: :read_only) }+ expect { comment(format: 'plain', body: 'x') }.not_to(change { posts_count })+ expect(response).to have_http_status(:forbidden)+ expect(body).to eq('error' => 'forbidden', 'code' => 'forbidden')+ end++ context 'with a read-only token' do+ let(:read_only) { true }++ it 'refuses before anything else, writing nothing' do+ expect { comment(format: 'plain', body: 'x') }.not_to(change { posts_count })+ expect(response).to have_http_status(:forbidden)+ expect(body).to eq('error' => 'forbidden', 'code' => 'read_only')+ end++ it 'refuses an unusable comment the same way' do+ comment(format: 'markdown', body: "a#{0.chr}")+ expect(body).to eq('error' => 'forbidden', 'code' => 'read_only')+ end+ end+ end++ # The web comment is Actors::SavePost. A bare Post#save beside it produced no+ # activity, no notification and no embedding until 2026-10-10.+ describe 'side effects of the web form (Actors::SavePost)' do+ let(:subscriber) { create(:user) }++ before do+ ActsAsTenant.with_tenant(organisation) do+ create(:membership, user: subscriber, organisation: organisation, role: role, active: true)+ create(:project_permission, user: subscriber, project: project, tickets_access: :read_write)+ NotificationSubscription.create!(user: subscriber, subscribable: ticket, mode: :follow)+ end+ end++ def activity_for(post_record)+ ActsAsTenant.without_tenant { Activity.find_by!(action: 'post_added', secondary: post_record) }+ end++ def fan_out(post_record)+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ Notifications::FanoutService.new(OutboxEvent.find_by!(activity: activity_for(post_record))).call+ end+ end+ end++ def notified?(recipient)+ ActsAsTenant.without_tenant do+ Notification.where(recipient: recipient, notifiable: ticket, event_type: 'ticket_commented').exists?+ end+ end++ it 'writes through Actors::SavePost' do+ expect(Actors::SavePost).to receive(:new).and_call_original+ comment(format: 'plain', body: 'Hallo')+ expect(response).to have_http_status(:created)+ end++ it 'records a post_added activity with the excerpt of the text' do+ comment(format: 'plain', body: "Hallo <b>\nWelt")+ activity = activity_for(saved)+ ActsAsTenant.with_tenant(organisation) do+ expect(activity.trackable).to eq(ticket)+ expect(activity.actor).to eq(user)+ end+ expect(activity.parameters['post_excerpt']).to eq("Hallo <b>\nWelt")+ end++ it 'reaches a subscriber as ticket_commented through the outbox' do+ comment(format: 'plain', body: 'Hallo')+ fan_out(saved)+ expect(notified?(subscriber)).to be(true)+ end++ it "marks the author's own unread notifications about the ticket as read" do+ own = ActsAsTenant.with_tenant(organisation) do+ create(:notification, :ticket_commented, organisation: organisation, recipient: user, actor: subscriber,+ notifiable: ticket, project: project)+ end+ comment(format: 'plain', body: 'Hallo')+ expect(ActsAsTenant.without_tenant { own.reload.state }).to eq('read')+ end++ describe 'a private plain comment' do+ it 'carries no excerpt and notifies no subscriber it is not addressed to' do+ comment(format: 'plain', body: 'Nur an mich', is_private: true)+ expect(body.dig('data', 'is_private')).to be(true)+ expect(body.dig('data', 'visible_to_user_id')).to eq(user.id)+ expect(activity_for(saved).parameters).not_to have_key('post_excerpt')+ fan_out(saved)+ expect(notified?(subscriber)).to be(false)+ end++ it 'notifies its addressee' do+ comment(format: 'plain', body: 'An dich', is_private: 'true', visible_to_user_id: subscriber.id)+ expect(body.dig('data', 'visible_to_user_id')).to eq(subscriber.id)+ fan_out(saved)+ expect(notified?(subscriber)).to be(true)+ end+ end+ end++ # The same input writes the same post on both surfaces: one rule, two hulls.+ it 'writes the post the MCP tool writes for the same input' do+ text = "Zeile 1\r\nZeile 2\n\n<b>&</b>"+ comment(format: 'plain', body: text, is_private: true)+ rest = saved++ context = Lalabase::Tools::Context.new(actor: user, organisation: organisation, project: project,+ authorization: Lalabase::Tools::AuthorizationRecorder.new)+ result = ActsAsTenant.with_tenant(organisation) do+ Lalabase::Tools::PostComment.execute(args: { ticket_id: ticket.id, format: 'plain', body: text, is_private: true },+ context: context)+ end+ mcp = ActsAsTenant.without_tenant { Post.find(JSON.parse(result.content).fetch('id')) }++ # Read outside the requests: one rich text per post, asked twice from one line.+ fields = ->(record) { [record.content.body.to_html, record.plain_text_version, record.is_private, record.user_id, record.visible_to_user_id, record.ticket_id] }+ Prosopite.pause do+ ActsAsTenant.without_tenant { expect(fields.call(mcp)).to eq(fields.call(rest)) }+ end+ end++ describe 'a failed save' do+ def failing_save(code, errors)+ allow_any_instance_of(Actors::SavePost).to receive(:call)+ .and_return(Actors::BaseActor::Result.new(success: false, errors: errors, code: code))+ end++ # BaseActor answers an exception it did not expect as :internal_error with+ # the exception's text where it does not re-raise (production).+ it 'answers an unexpected failure as a server error without its text' do+ failing_save(:internal_error, ['PG::ConnectionBad: could not connect to server at 192.168.0.1'])+ comment(format: 'plain', body: 'x')+ expect(response).to have_http_status(:internal_server_error)+ expect(response.body).not_to include('PG::', '192.168.0.1')+ expect(body).to eq('error' => 'internal_error', 'code' => 'refused', 'reason' => 'internal_error')+ end++ it 'answers every other failure as it always did' do+ failing_save(:validation_failed, ['Visible to user must be a member of the organisation'])+ comment(body: 'x')+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to eq('error' => 'validation_failed', 'code' => 'invalid_input',+ 'errors' => ['Visible to user must be a member of the organisation'])+ end+ end++ describe 'Idempotency-Key' do+ it 'replays the first answer for the same key and request, writing once' do+ expect { comment(key: 'r3a-1', format: 'plain', body: "a\nb") }.to change { posts_count }.by(1)+ first = [response.status, response.body]+ expect { comment(key: 'r3a-1', format: 'plain', body: "a\nb") }.not_to(change { posts_count })+ expect([response.status, response.body]).to eq(first)+ end++ it 'refuses the key with another body' do+ comment(key: 'r3a-2', format: 'plain', body: 'a')+ expect { comment(key: 'r3a-2', format: 'plain', body: 'b') }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to include('error' => 'idempotency_key_reused', 'code' => 'invalid_input')+ end++ it 'refuses the key with another format' do+ comment(key: 'r3a-3', format: 'plain', body: 'a')+ expect { comment(key: 'r3a-3', format: 'html', body: 'a') }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to include('error' => 'idempotency_key_reused', 'code' => 'invalid_input')+ end+ end+enddiff --git a/spec/services/lalabase/tools/post_comment_failure_spec.rb b/spec/services/lalabase/tools/post_comment_failure_spec.rbindex 1fc4db9..14c88de 100644--- a/spec/services/lalabase/tools/post_comment_failure_spec.rb+++ b/spec/services/lalabase/tools/post_comment_failure_spec.rb@@ -8,7 +8,7 @@ require 'rails_helper'# Why: BaseActor answers an unexpected exception as :internal_error with the# exception's text where it does not re-raise (production). That text may# name the database and reached the client through "comment failed: ...".-RSpec.describe Lalabase::Tools::PostComment do+RSpec.describe Lalabase::Tools::PostComment, :ci_guard dolet(:organisation) { create(:organisation) }let(:user) { create(:user) }let(:project) { create(:project, organisation: organisation) }diff --git a/spec/services/posts/comment_spec.rb b/spec/services/posts/comment_spec.rbindex f476ba5..f4e77cb 100644--- a/spec/services/posts/comment_spec.rb+++ b/spec/services/posts/comment_spec.rb@@ -8,7 +8,7 @@ require 'rails_helper'# body as HTML without checking its encoding or NUL bytes. The surfaces word# a refusal each their own way; what is refused, and what is stored, is# decided here once.-RSpec.describe Posts::Comment do+RSpec.describe Posts::Comment, :ci_guard dolet(:organisation) { create(:organisation) }let(:user) { create(:user) }let(:project) { create(:project, organisation: organisation) }