Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

fix: review round 2 of #81, respect a multipart part's own charset

Guido Boyke1a16f823f40c
diff --git a/CLAUDE.md b/CLAUDE.md
index 1466775..1bb9754 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -840,8 +840,11 @@ back to html), NUL in a plain body and a plain body that converts to nothing ans
`validation_failed`/`invalid_input` with a text from `services.post_comment.*`, checked inside
the read gate. Without `format` the answer stays byte for byte: an empty body is the model's
refusal, after the write check, with every model message (the contract case `html_empty` was
-recorded before R3a), and a JSON `false` as body counts as none, as before. Invalid UTF-8 never reaches the rule over REST (the 400 above); MCP
-refuses it. An unexpected actor failure (`internal_error`) answers 500 without the exception's
+recorded before R3a), and a JSON `false` as body counts as none, as before. Raw invalid bytes
+in a form or JSON body never reach the rule (the 400 above); MCP refuses them. Only a multipart
+part can name a charset of its own (`text/plain; charset=...`): `html` hands it to ActionText as
+it came, as before (a Latin-1 comment keeps its letters), `plain` transcodes it to UTF-8, and a
+`plain` part declared binary must hold UTF-8. An unexpected actor failure (`internal_error`) answers 500 without the exception's
text, every other failure 422 `validation_failed` as before; MCP answers `comment failed:
unexpected error`. Capability `posts.plain`. Guards:
`spec/requests/api/v1/post_comment_format_spec.rb`, `spec/services/posts/comment_spec.rb`,
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index bf1a45b..ce0be1e 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -201,6 +201,8 @@ Verzeichnis-Übersicht (Auswahl):
answered differently on purpose: MCP refuses it before the ticket lookup (`body is
required`, as always), REST leaves it to the model after the write check (its answer
without `format` stays byte for byte). Not a second rule: do not align them in one hull.
+ Encodings: JSON and forms always give UTF-8; a multipart part may name its own charset,
+ which an html body keeps (ActionText reads it, as before) and a plain body transcodes.
* `lalabase/` — AI/RAG-Domäne (eigene Karte im Ordner)
* `access_check/` — Projekt-Zugriffslogik, 5 Objekte mit überlappenden Prädikaten —
**vor Neubau erst hier prüfen**. `project_access_service.rb` ist der EINE Besitzer der
diff --git a/app/services/posts/comment.rb b/app/services/posts/comment.rb
index 038b44e..62dbff7 100644
--- a/app/services/posts/comment.rb
+++ b/app/services/posts/comment.rb
@@ -82,8 +82,8 @@ module Posts
# 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?
+ body = readable(body)
+ 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
@@ -95,5 +95,21 @@ module Posts
@content = plain? ? Posts::PlainTextBody.call(body: body) : body
:body_empty if @content.strip.empty?
end
+
+ # The body in the encoding the rule reads it in, nil when it has none.
+ # JSON and forms give UTF-8 on both surfaces. Only a multipart part (REST)
+ # can name a charset of its own: html, stored as sent, keeps it, and
+ # ActionText reads it as it always did (a Latin-1 comment keeps its
+ # letters); plain transcodes it. A binary part names no charset, so plain
+ # reads its bytes as UTF-8.
+ def readable(body)
+ return body.dup.force_encoding(Encoding::UTF_8) if body.encoding == Encoding::UTF_8
+ return body unless plain?
+ return body.dup.force_encoding(Encoding::UTF_8) if body.encoding == Encoding::BINARY
+
+ body.encode(Encoding::UTF_8)
+ rescue EncodingError
+ nil
+ end
end
end
diff --git a/spec/requests/api/v1/post_comment_format_spec.rb b/spec/requests/api/v1/post_comment_format_spec.rb
index 21c89c4..ac82be3 100644
--- a/spec/requests/api/v1/post_comment_format_spec.rb
+++ b/spec/requests/api/v1/post_comment_format_spec.rb
@@ -53,6 +53,21 @@ RSpec.describe 'API V1 comment format', :ci_guard, type: :request do
post "/api/v1/tickets/#{ticket_id}/posts", params: { post: fields }.to_json, headers: headers(json: true)
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 comment_multipart(parts)
+ boundary = 'r3a-boundary'
+ raw = ''.b
+ parts.each do |name, (type, bytes)|
+ raw << "--#{boundary}\r\nContent-Disposition: form-data; name=\"post[#{name}]\"\r\n".b
+ raw << "Content-Type: #{type}\r\n".b if type
+ raw << "\r\n".b << bytes.b << "\r\n".b
+ end
+ raw << "--#{boundary}--\r\n".b
+ post "/api/v1/tickets/#{ticket.id}/posts", params: raw,
+ headers: headers.merge('Content-Type' => "multipart/form-data; boundary=#{boundary}")
+ end
+
def body = response.parsed_body
def posts_count = ActsAsTenant.without_tenant { Post.count }
@@ -231,8 +246,9 @@ RSpec.describe 'API V1 comment format', :ci_guard, type: :request do
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.
+ # request, before any of this endpoint's code runs: over REST the rule's
+ # body_invalid_utf8 is reached only by a plain multipart part declared
+ # binary (below); MCP reaches it with invalid bytes in a JSON string.
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',
@@ -267,6 +283,38 @@ RSpec.describe 'API V1 comment format', :ci_guard, type: :request do
end
end
+ # Only a multipart part can carry another encoding (text/plain; charset=...).
+ describe 'a multipart part in an encoding of its own' do
+ def latin1 = "a#{0xE4.chr}b"
+ def a_umlaut_b = "a#{0xE4.chr(Encoding::UTF_8)}b"
+
+ it 'keeps an html part as it came, as before: a Latin-1 comment keeps its letters' do
+ comment_multipart('body' => ['text/plain; charset=iso-8859-1', latin1])
+ expect(response).to have_http_status(:created)
+ expect(body.dig('data', 'body_text')).to eq(a_umlaut_b)
+ end
+
+ it 'keeps an html part declared binary as it came, as before (ActionText reads it)' do
+ comment_multipart('body' => ['text/plain; charset=binary', "a#{0xFF.chr}b"])
+ expect(response).to have_http_status(:created)
+ expect(body.dig('data', 'body_text')).to eq("a#{0xFF.chr(Encoding::UTF_8)}b")
+ end
+
+ it 'transcodes a plain part to UTF-8' do
+ comment_multipart('format' => [nil, 'plain'], 'body' => ['text/plain; charset=iso-8859-1', "#{latin1}\n<b>"])
+ expect(response).to have_http_status(:created)
+ expect(body.dig('data', 'body_text')).to eq("#{a_umlaut_b}\n<b>")
+ expect(body.dig('data', 'body_html')).to eq("<p>#{a_umlaut_b}<br>&lt;b&gt;</p>")
+ end
+
+ it 'refuses a plain part declared binary that holds no UTF-8, writing nothing' do
+ expect { comment_multipart('format' => [nil, 'plain'], 'body' => ['text/plain; charset=binary', "a#{0xFF.chr}b"]) }
+ .not_to(change { posts_count })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq(refusal(:body_invalid_utf8))
+ end
+ end
+
describe 'who may comment' do
def hide_ticket
ActsAsTenant.with_tenant(organisation) do
diff --git a/spec/services/posts/comment_spec.rb b/spec/services/posts/comment_spec.rb
index 2481821..966cfcc 100644
--- a/spec/services/posts/comment_spec.rb
+++ b/spec/services/posts/comment_spec.rb
@@ -50,8 +50,10 @@ RSpec.describe Posts::Comment, :ci_guard do
'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 binary string is always valid_encoding?: the rule reads it as UTF-8.
+ # A binary string is always valid_encoding?: plain reads it as UTF-8.
'invalid bytes in a binary body' => [{ format: 'plain', body: -> { "a#{255.chr}b".b } }, :body_invalid_utf8],
+ 'a plain body that does not transcode' => [{ format: 'plain', body: -> { "a#{0x82.chr}".force_encoding(Encoding::SHIFT_JIS) } },
+ :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],
@@ -88,6 +90,14 @@ RSpec.describe Posts::Comment, :ci_guard do
expect(described_class.parse(body: "a#{0.chr}b")).not_to be_refused
end
+ # A multipart part (REST) may name a charset of its own; JSON and forms
+ # always give UTF-8.
+ it 'keeps an html body in an encoding of its own as it came, for ActionText to read as before' do
+ latin1 = "a#{0xE4.chr}b".force_encoding(Encoding::ISO_8859_1)
+ expect(described_class.parse(body: latin1)).not_to be_refused
+ expect(described_class.parse(body: "a#{0xFF.chr}b".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
@@ -121,6 +131,21 @@ RSpec.describe Posts::Comment, :ci_guard do
.to eq('<p>Zeile 1<br>Zeile 2</p><p>Absatz &lt;b&gt;&amp;</p>')
end
+ it 'transcodes a plain body in an encoding of its own to UTF-8' do
+ latin1 = "a#{0xE4.chr}<b".force_encoding(Encoding::ISO_8859_1)
+ expect(build(body: latin1, format: 'plain').content.body.to_html).to eq("<p>a#{0xE4.chr(Encoding::UTF_8)}&lt;b</p>")
+ end
+
+ it 'reads a plain body in binary as UTF-8' do
+ binary = "a#{0xC3.chr}#{0xA4.chr}b".b
+ expect(build(body: binary, format: 'plain').content.body.to_html).to eq("<p>a#{0xE4.chr(Encoding::UTF_8)}b</p>")
+ end
+
+ it 'hands an html body in an encoding of its own to ActionText as it came' do
+ latin1 = "<p>a#{0xE4.chr}b</p>".force_encoding(Encoding::ISO_8859_1)
+ expect(build(body: latin1).content.body.to_html).to eq("<p>a#{0xE4.chr(Encoding::UTF_8)}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)>&amp;', format: 'plain')
html = post.content.body.to_html