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
Move the comment rule into Posts::Comment and let post_comment use it
Guido Boykefa34b08abd15
diff --git a/app/services/lalabase/tools/post_comment.rb b/app/services/lalabase/tools/post_comment.rbindex 2243bed..9bb9338 100644--- a/app/services/lalabase/tools/post_comment.rb+++ b/app/services/lalabase/tools/post_comment.rb@@ -8,18 +8,23 @@ module Lalabase# marks read, the embedding. Returns the created post as JSON.## The body arrives as ActionText HTML (format html, the default, stored as- # sent) or as literal text (format plain, MCP 0.11): Posts::PlainTextBody- # escapes it and turns line breaks into paragraphs and <br>, so body_text- # comes back as the client sent it. Format, encoding and emptiness of the- # body are checked before the ticket lookup.+ # sent) or as literal text (format plain, MCP 0.11). The rule is+ # Posts::Comment's, shared with POST /api/v1/tickets/:ticket_id/posts (REST+ # R3a); format, encoding and emptiness of the body are checked before the+ # ticket lookup.## Mutating (D3): blocked for a read-only PAT. Record-mode (D7): authorizes the# ticket (:show?) and the post (:create?) before saving, or the tripwire fires.class PostComment < Base- # The body formats a client may name, read by the schema and the check.- FORMATS = %w[html plain].freeze- DEFAULT_FORMAT = 'html'- PLAIN_FORMAT = 'plain'+ # The refusal texts of this surface (Posts::Comment::REFUSALS), unchanged+ # since the tool's first answer.+ REFUSAL_TEXT = {+ format_not_string: 'format must be a string',+ format_unknown: "format must be #{Posts::Comment::FORMATS.join(' or ')}",+ body_invalid_utf8: 'body must be valid UTF-8',+ body_nul: 'body must not contain NUL bytes',+ body_empty: 'body is required'+ }.freeze# Writes on behalf of context.actor. No chat set may ever carry a mutating# tool, so the Runner's bar can never fire here — the declaration is kept@@ -53,7 +58,7 @@ module Lalabaseproperties: {ticket_id: { type: 'string', description: 'UUID of the ticket to comment on.' },body: { type: 'string', description: 'Comment body (required). HTML unless format is plain.' },- format: { type: 'string', enum: FORMATS,+ format: { type: 'string', enum: Posts::Comment::FORMATS,description: 'Body format: html (default) or plain. Plain escapes literal text, turns blank lines ' \'into paragraphs and single line breaks into <br>; line endings are normalized, ' \'blank lines at the edges are dropped, repeated spaces collapse in the web view, ' \@@ -69,30 +74,12 @@ module Lalabaseargs = symbolized(args)ticket_id = args[:ticket_id].to_s.strip- body = args[:body].to_sreturn Result.invalid_input('ticket_id is required') if ticket_id.empty?return Result.invalid_input('invalid ticket_id format') unless ticket_id.match?(UUID_FORMAT)- format = args.fetch(:format, DEFAULT_FORMAT)- return Result.invalid_input('format must be a string') unless format.is_a?(String)- return Result.invalid_input("format must be #{FORMATS.join(' or ')}") unless FORMATS.include?(format)-- # The JSON parser lets invalid UTF-8 through inside a string, and- # String#strip raises on it: refused for both formats before any string- # method runs on the body.- body = body.dup.force_encoding(Encoding::UTF_8)- return Result.invalid_input('body must be valid UTF-8') unless body.valid_encoding?-- plain = format == PLAIN_FORMAT- # plain promises body_text == body, so a byte that cannot round-trip is- # refused rather than cleaned. html keeps its legacy behaviour: the HTML- # parser drops a NUL byte on its own.- return Result.invalid_input('body must not contain NUL bytes') if plain && body.include?("\0")-- # Decided on what would be stored: a plain body of Unicode whitespace- # only converts to nothing (String#strip knows ASCII whitespace only).- content = plain ? Posts::PlainTextBody.call(body: body) : body- return Result.invalid_input('body is required') if content.strip.empty?+ # A format only when given: absent is html, a given null is refused.+ comment = Posts::Comment.parse(body: args[:body], is_private: args[:is_private], **args.slice(:format))+ return Result.invalid_input(REFUSAL_TEXT.fetch(comment.refusal)) if comment.refused?# Inside the read scope: a ticket the caller may not read answers like a# missing one (Base.readable_tickets).@@ -103,19 +90,25 @@ module Lalabase# may see the ticket at all (private-post visibility lives in that policy),# :create? proves write access. Either denial → tripwire-safe 'Not authorized.'.authorize!(context, ticket, :show?)- # The record exists before #call, so the policy sees the post it is asked- # about (PostUpdateService does the same).- actor = Actors::SavePost.new(ticket: ticket, current_user: context.actor,- params: { content: content, is_private: [true, 'true'].include?(args[:is_private]) })- authorize!(context, actor.record, :create?)-- # No code, so refused: a model validation does not prove the input was wrong,- # and create_ticket and create_time_session answer a refused save the same way.- outcome = actor.call- return Result.new(error: "comment failed: #{outcome.errors.join(', ')}") unless outcome.success?-- json_result(serialize(actor.record))+ post = comment.build(ticket: ticket, current_user: context.actor)+ authorize!(context, post, :create?)++ outcome = comment.save+ return Result.new(error: comment_failure(outcome)) unless outcome.success?++ json_result(serialize(post))+ end++ # No code, so refused: a model validation does not prove the input was+ # wrong, and create_ticket and create_time_session answer a refused save+ # the same way. An unexpected failure (BaseActor's :internal_error where it+ # does not re-raise) gets a fixed text: its message may name the database.+ def self.comment_failure(outcome)+ return 'comment failed: unexpected error' if outcome.code == :internal_error++ "comment failed: #{outcome.errors.join(', ')}"end+ private_class_method :comment_failuredef self.serialize(post){diff --git a/app/services/posts/comment.rb b/app/services/posts/comment.rbnew file mode 100644index 0000000..038b44e--- /dev/null+++ b/app/services/posts/comment.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++# The one rule of a comment written through a token: the MCP tool post_comment+# and POST /api/v1/tickets/:ticket_id/posts both write through it, so the two+# surfaces cannot drift apart again (before REST R3a, REST took every body as+# HTML and checked neither its encoding nor NUL bytes).+#+# Entry point: parse+#+# Three steps, because the callers authorize in between (cut like+# TimeSessions::Booking): `parse` checks the format and the body and converts+# a plain body, `build` makes the unsaved post on a ticket the caller has found+# readable, through Actors::SavePost (the web form's write: the post_added+# activity, the notifications, the author's read marks, the embedding), and+# `save` writes it once the caller has authorized the post (:create?). Rights+# stay with the callers; this object holds none.+#+# The body arrives as ActionText HTML (format html, the default, stored as+# sent) or as literal text (format plain): Posts::PlainTextBody escapes it and+# turns line breaks into paragraphs and <br>, so body_text comes back as the+# client sent it. A body that is no string is taken as its text (`to_s`), as+# both surfaces always did.+module Posts+ class Comment+ # The body formats a client may name.+ FORMATS = %w[html plain].freeze+ DEFAULT_FORMAT = 'html'+ PLAIN_FORMAT = 'plain'++ # Why `parse` turns a comment away, in the order it checks. Each caller+ # words it for its surface.+ REFUSALS = %i[format_not_string format_unknown body_invalid_utf8 body_nul body_empty].freeze++ attr_reader :refusal++ # `format` absent is html; given, it must be one of FORMATS as a String.+ def self.parse(body:, format: DEFAULT_FORMAT, is_private: nil, visible_to_user_id: nil)+ new(body: body, format: format, is_private: is_private, visible_to_user_id: visible_to_user_id)+ end++ def initialize(body:, format:, is_private:, visible_to_user_id:)+ @format = format+ @attributes = { is_private: [true, 'true'].include?(is_private), visible_to_user_id: visible_to_user_id }+ @refusal = refusal_for(body.to_s)+ end++ def refused?+ end++ def plain?+ @format == PLAIN_FORMAT+ end++ # The unsaved post on `ticket`, for the caller's :create? check: the actor+ # builds it before it saves, so the policy sees the post it is asked about.+ # An empty body can be built, the model refuses it on save; a body the rule+ # could not read (format, encoding, NUL) cannot.+ def build(ticket:, current_user:)+ raise ArgumentError, "unreadable comment: #{@refusal}" if @content.nil?++ @actor = Actors::SavePost.new(ticket: ticket, current_user: current_user,+ params: { content: @content, **@attributes })+ @actor.record+ end++ # => Actors::BaseActor::Result. A model refusal (an empty content, an+ # addressee outside the organisation) comes back as :validation_failed,+ # nothing written.+ def save+ raise ArgumentError, 'build the comment before saving it' if @actor.nil?++ @actor.call+ end++ private++ def refusal_for(body)+ return :format_not_string unless @format.is_a?(String)+ return :format_unknown unless FORMATS.include?(@format)++ # The JSON parser lets invalid UTF-8 through inside a string, and+ # String#strip raises on it: refused for both formats before any string+ # method runs on the body.+ body = body.dup.force_encoding(Encoding::UTF_8)+ return :body_invalid_utf8 unless body.valid_encoding?++ # plain promises body_text == body, so a byte that cannot round-trip is+ # refused rather than cleaned. html keeps its legacy behaviour: the HTML+ # parser drops a NUL byte on its own.+ return :body_nul if plain? && body.include?("\0")++ # Decided on what would be stored: a plain body of Unicode whitespace+ # only converts to nothing (String#strip knows ASCII whitespace only).+ @content = plain? ? Posts::PlainTextBody.call(body: body) : body+ :body_empty if @content.strip.empty?+ end+ end+enddiff --git a/spec/services/lalabase/tools/post_comment_failure_spec.rb b/spec/services/lalabase/tools/post_comment_failure_spec.rbnew file mode 100644index 0000000..1fc4db9--- /dev/null+++ b/spec/services/lalabase/tools/post_comment_failure_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++require 'rails_helper'++# What: how post_comment words a save that failed (REST R3a). Beside+# post_comment_spec.rb, which stays as it was: every answer it pins is+# the tool's answer before the rule moved into Posts::Comment.+# 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+ let(:organisation) { create(:organisation) }+ let(:user) { create(:user) }+ let(:project) { create(:project, organisation: organisation) }+ let(:ticket) { create(:ticket, organisation: organisation, project: project, creator: user) }+ let(:context) do+ Lalabase::Tools::Context.new(actor: user, organisation: organisation, project: project,+ authorization: Lalabase::Tools::AuthorizationRecorder.new)+ end++ before do+ ActsAsTenant.current_tenant = organisation+ create(:membership, user: user, organisation: organisation, role: create(:role, organisation: organisation))+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end++ after { ActsAsTenant.current_tenant = nil }++ def execute(arguments = {})+ described_class.execute(args: { ticket_id: ticket.id, body: 'Hallo', format: 'plain' }.merge(arguments), context: context)+ end++ 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++ it 'answers an unexpected failure with a fixed text, never the exception text' do+ failing_save(:internal_error, ['PG::ConnectionBad: could not connect to server at 192.168.0.1'])+ result = execute+ expect(result).not_to be_success+ expect(result.error).to eq('comment failed: unexpected error')+ expect(result.error_code).to eq(:refused)+ end++ it 'still names the reason of any other failure, as before' do+ failing_save(:validation_failed, ['Content darf nicht leer sein'])+ result = execute+ expect(result.error).to eq('comment failed: Content darf nicht leer sein')+ expect(result.error_code).to eq(:refused)+ end++ it 'answers a model refusal of the stored body with the model text, as before' do+ result = nil+ expect { result = execute(format: 'html', body: '<p></p>') }.not_to change(Post, :count)+ expect(result.error).to match(/\Acomment failed: Content /)+ end+enddiff --git a/spec/services/posts/comment_spec.rb b/spec/services/posts/comment_spec.rbnew file mode 100644index 0000000..f476ba5--- /dev/null+++ b/spec/services/posts/comment_spec.rb@@ -0,0 +1,190 @@+# frozen_string_literal: true++require 'rails_helper'++# What: Posts::Comment, the one rule of a comment written through a token: the+# MCP tool post_comment and POST /api/v1/tickets/:ticket_id/posts.+# Why: Until REST R3a the rule lived in the MCP tool alone, and REST took every+# 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+ let(:organisation) { create(:organisation) }+ let(:user) { create(:user) }+ let(:project) { create(:project, organisation: organisation) }+ let(:ticket) { create(:ticket, organisation: organisation, project: project, creator: user) }++ before do+ ActsAsTenant.current_tenant = organisation+ create(:membership, user: user, organisation: organisation, role: create(:role, organisation: organisation))+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end++ after { ActsAsTenant.current_tenant = nil }++ def nbsp = 0xA0.chr(Encoding::UTF_8)+ def em_space = 0x2003.chr(Encoding::UTF_8)+ def invalid_utf8 = 255.chr.force_encoding(Encoding::UTF_8)++ describe '.parse' do+ it 'takes html as the default format' do+ comment = described_class.parse(body: '<p>x</p>')+ expect(comment).not_to be_refused+ expect(comment).not_to be_plain+ end++ it 'takes plain when named' do+ comment = described_class.parse(body: 'x', format: 'plain')+ expect(comment).not_to be_refused+ expect(comment).to be_plain+ end++ refusals = {+ 'a null format' => [{ format: nil }, :format_not_string],+ 'a numeric format' => [{ format: 1 }, :format_not_string],+ 'a boolean format' => [{ format: true }, :format_not_string],+ 'a symbol format' => [{ format: :plain }, :format_not_string],+ 'a list as format' => [{ format: ['plain'] }, :format_not_string],+ 'an unknown format' => [{ format: 'markdown' }, :format_unknown],+ 'a format in capitals' => [{ format: 'PLAIN' }, :format_unknown],+ 'an empty format' => [{ format: '' }, :format_unknown],+ 'invalid UTF-8 in an html body' => [{ body: -> { invalid_utf8 } }, :body_invalid_utf8],+ 'invalid UTF-8 in a plain body' => [{ format: 'plain', body: -> { invalid_utf8 } }, :body_invalid_utf8],+ 'a NUL byte in a plain body' => [{ format: 'plain', body: "a#{0.chr}b" }, :body_nul],+ '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 only a no-break space' => [{ format: 'plain', body: -> { nbsp } }, :body_empty],+ 'a plain body of only an em space' => [{ format: 'plain', body: -> { em_space } }, :body_empty],+ 'an empty html body' => [{ body: '' }, :body_empty],+ 'an html body of spaces' => [{ body: " \n " }, :body_empty],+ 'no body' => [{ body: nil }, :body_empty]+ }++ refusals.each do |label, (arguments, refusal)|+ it "refuses #{label} as #{refusal}" do+ arguments = arguments.transform_values { |value| value.is_a?(Proc) ? instance_exec(&value) : value }+ comment = described_class.parse(**{ body: 'Hallo' }.merge(arguments))+ expect(comment).to be_refused+ expect(comment.refusal).to eq(refusal)+ end+ end++ it 'names every refusal it can give in REFUSALS' do+ expect(described_class::REFUSALS).to eq(refusals.values.map(&:last).uniq)+ end++ it 'checks the format before the body' do+ expect(described_class.parse(body: "a#{0.chr}b", format: 'markdown').refusal).to eq(:format_unknown)+ end++ it 'checks the encoding before NUL bytes, so no string method runs on invalid bytes' do+ expect(described_class.parse(body: "#{invalid_utf8}#{0.chr}", format: 'plain').refusal).to eq(:body_invalid_utf8)+ end++ # html keeps what both surfaces always did: the HTML parser drops a NUL byte.+ it 'lets a NUL byte through in an html body' do+ expect(described_class.parse(body: "a#{0.chr}b")).not_to be_refused+ end++ # html takes a no-break space as text, as it always did; the model then+ # decides on the stored plain text.+ it 'leaves an html body of a no-break space to the model' do+ expect(described_class.parse(body: nbsp)).not_to be_refused+ end+ end++ describe '#build' do+ def build(**arguments)+ described_class.parse(**arguments).build(ticket: ticket, current_user: user)+ end++ it 'builds the unsaved post through Actors::SavePost, the web form write' do+ expect(Actors::SavePost).to receive(:new)+ .with(ticket: ticket, current_user: user, params: { content: '<p>x</p>', is_private: false, visible_to_user_id: nil })+ .and_call_original+ post = build(body: '<p>x</p>')+ expect(post).to be_a(Post).and be_new_record+ expect(post.ticket).to eq(ticket)+ end++ it 'stores an html body as sent' do+ body = '<p><b>bold</b> <tag></p>'+ expect(build(body: body).content.body.to_html).to eq(body)+ end++ it 'converts a plain body through Posts::PlainTextBody' do+ body = "Zeile 1\r\nZeile 2\n\nAbsatz <b>&"+ expect(Posts::PlainTextBody).to receive(:call).with(body: body).and_call_original+ expect(build(body: body, format: 'plain').content.body.to_html)+ .to eq('<p>Zeile 1<br>Zeile 2</p><p>Absatz <b>&</p>')+ end++ it 'escapes markup in a plain body, so it lands as text' do+ post = build(body: '<script>alert(1)</script><img src=x onerror=alert(2)>&', format: 'plain')+ html = post.content.body.to_html+ expect(html).not_to include('<script', '<img')+ expect(html).to include('<script>', '<img', '&amp;')+ end++ it 'takes a body that is no string as its text, as both surfaces always did' do+ expect(build(body: true).content.body.to_html).to eq('true')+ expect(build(body: 12, format: 'plain').content.body.to_html).to eq('<p>12</p>')+ end++ { true => true, 'true' => true, false => false, 'false' => false, '1' => false, 1 => false, nil => false }+ .each do |given, stored|+ it "reads is_private #{given.inspect} as #{stored}" do+ expect(build(body: 'x', is_private: given).is_private).to be(stored)+ end+ end++ it 'passes the addressee on to the model, which checks it' do+ expect(build(body: 'x', is_private: true, visible_to_user_id: user.id).visible_to_user_id).to eq(user.id)+ end++ it 'builds an empty body, which the model refuses on save' do+ comment = described_class.parse(body: '')+ expect(comment.build(ticket: ticket, current_user: user).content).to be_blank+ expect { expect(comment.save.code).to eq(:validation_failed) }.not_to change(Post, :count)+ end++ %i[format_not_string format_unknown body_invalid_utf8 body_nul].each do |refusal|+ it "refuses to build a comment it could not read (#{refusal})" do+ arguments = {+ format_not_string: { body: 'x', format: 1 }, format_unknown: { body: 'x', format: 'markdown' },+ body_invalid_utf8: { body: invalid_utf8 }, body_nul: { body: "a#{0.chr}b", format: 'plain' }+ }.fetch(refusal)+ expect { build(**arguments) }.to raise_error(ArgumentError, /#{refusal}/)+ end+ end+ end++ describe '#save' do+ it 'writes the post and its post_added activity through the actor' do+ comment = described_class.parse(body: "Erste Zeile\nzweite", format: 'plain')+ post = comment.build(ticket: ticket, current_user: user)++ result = nil+ expect { result = comment.save }.to change(Post, :count).by(1)+ expect(result).to be_success+ expect(post).to be_persisted+ expect(post.user).to eq(user)+ expect(post.plain_text_version).to eq("Erste Zeile\nzweite")+ expect(Activity.find_by(action: 'post_added', secondary: post)).to be_present+ end++ it 'answers the model refusal of an html body without text, writing nothing' do+ comment = described_class.parse(body: '<p></p>')+ comment.build(ticket: ticket, current_user: user)++ result = nil+ expect { result = comment.save }.not_to change(Post, :count)+ expect(result).not_to be_success+ expect(result.code).to eq(:validation_failed)+ end++ it 'refuses to save a comment that was not built' do+ expect { described_class.parse(body: 'x').save }.to raise_error(ArgumentError)+ end+ end+end