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
fix(api): fingerprint binary multipart input before validation
Guido Boyke02536b7acb11
diff --git a/CLAUDE.md b/CLAUDE.mdindex d022a04..073a053 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -817,7 +817,9 @@ feature by feature):`spec/requests/api/mcp_idempotency_key_bound_spec.rb`; it used to write, fail to rememberthe key with -32603 and write again on every retry). A replay checks no rights(it repeats what the same token already got; keys do not expire), and a retry must send- the same bytes. Every write route must be `idempotent`+ the same bytes. Multipart bytes Rack accepts but JSON cannot encode are fingerprinted+ without decoding, so the action still applies its permissions and input validation.+ Existing JSON fingerprints stay unchanged. Every write route must be `idempotent`(`spec/architecture/api_v1_writes_idempotent_guard_spec.rb`).* **`GET /api/v1/me`** names `api_version` and `capabilities` from `Api::V1::Capabilities`,pinned against the routes both ways (`spec/requests/api/v1/capabilities_spec.rb`): a newdiff --git a/app/services/mcp/idempotency_store.rb b/app/services/mcp/idempotency_store.rbindex 1c5ec6f..d8eb57c 100644--- a/app/services/mcp/idempotency_store.rb+++ b/app/services/mcp/idempotency_store.rb@@ -96,7 +96,14 @@ module Mcp# (sort.to_h) — sufficient because a retrying client resends the same structure;# we are detecting accidental reuse of a key, not defending against an adversary.def self.fingerprint(args)- Digest::SHA256.hexdigest(args.sort.to_h.to_json)+ ordered = args.sort.to_h+ Digest::SHA256.hexdigest(ordered.to_json)+ rescue JSON::GeneratorError+ # Rack can accept binary multipart strings that JSON cannot encode. Keep+ # their bytes and types so authorization and input validation can run.+ # The NUL prefix separates this dump (never loaded) from legacy JSON;+ # every request JSON can encode keeps its existing stored fingerprint.+ Digest::SHA256.hexdigest("\0binary-params-v1\0".b + Marshal.dump(ordered.as_json))end# @return [Lalabase::Tools::Result, nil] a Result to return verbatim (thediff --git a/spec/requests/api/v1/idempotency_spec.rb b/spec/requests/api/v1/idempotency_spec.rbindex eee6441..44eb8ab 100644--- a/spec/requests/api/v1/idempotency_spec.rb+++ b/spec/requests/api/v1/idempotency_spec.rb@@ -51,6 +51,15 @@ RSpec.describe 'API V1 idempotency', :ci_guard, type: :request dopost "/api/v1/tickets/#{ticket.id}/posts", params: { post: { body: body } }, headers: headers(key, token: token)end+ def comment_with_binary_parameter(bytes)+ boundary = 'binary-parameter'+ raw = "--#{boundary}\r\nContent-Disposition: form-data; name=\"post[body]\"\r\n\r\nHallo\r\n".b+ raw << "--#{boundary}\r\nContent-Disposition: form-data; name=\"ignored\"\r\nContent-Type: text/plain; charset=binary\r\n\r\n".b+ raw << bytes.b << "\r\n--#{boundary}--\r\n".b+ post "/api/v1/tickets/#{ticket.id}/posts", params: raw,+ headers: headers('binary-parameter').merge('CONTENT_TYPE' => "multipart/form-data; boundary=#{boundary}")+ end+describe 'POST /api/v1/tickets/:ticket_id/posts' doit 'replays the first answer for a repeated key and writes once' doexpect { comment('Hallo', key: 'k-1') }.to change { posts_count }.by(1)@@ -126,6 +135,19 @@ RSpec.describe 'API V1 idempotency', :ci_guard, type: :request dodescribe 'the request the key belongs to' dolet(:other_ticket) { create(:ticket, project: project, organisation: organisation, creator: user) }+ it 'replays a successful write with ignored binary input, but refuses different bytes' do+ expect { comment_with_binary_parameter("x\xFF") }.to change { posts_count }.by(1)+ first = snapshot+ expect(first.first).to eq(201)++ expect { comment_with_binary_parameter("x\xFF") }.not_to(change { posts_count })+ expect(snapshot).to eq(first)++ expect { comment_with_binary_parameter("x\xFE") }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(response.parsed_body).to include('error' => 'idempotency_key_reused')+ end+# The ticket is in the path only: without the path in the fingerprint the# comment on the second ticket would get the first ticket's answer and never land.it 'refuses the key on another ticket with the same body, writing nothing there' dodiff --git a/spec/requests/api/v1/ticket_changes_spec.rb b/spec/requests/api/v1/ticket_changes_spec.rbindex 7867eee..a170c8d 100644--- a/spec/requests/api/v1/ticket_changes_spec.rb+++ b/spec/requests/api/v1/ticket_changes_spec.rb@@ -88,12 +88,12 @@ RSpec.describe 'API V1 ticket changes', :ci_guard, type: :request do# 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)+ def change_multipart(name, type, bytes, key: nil, ticket_id: ticket.id)boundary = 'r3b-boundary'raw = "--#{boundary}\r\nContent-Disposition: form-data; name=\"change[#{name}]\"\r\nContent-Type: #{type}\r\n\r\n".braw << 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}")+ post "/api/v1/tickets/#{ticket_id}/changes", params: raw,+ headers: headers(json: false, key: key).merge('Content-Type' => "multipart/form-data; boundary=#{boundary}")enddef body = response.parsed_body@@ -530,6 +530,33 @@ RSpec.describe 'API V1 ticket changes', :ci_guard, type: :request doexpect(response).to have_http_status(:ok)expect(reloaded.title).to eq('Müller')end++ it 'refuses binary bytes with an idempotency key and leaves the key free for a corrected retry' do+ before = written+ change_multipart('title', 'text/plain; charset=binary', "M\xFFller", key: 'binary-title')++ expect_invalid_input('The change cannot be read as UTF-8.')+ expect(written).to eq(before)++ send_change({ title: 'Müller' }, key: 'binary-title')+ expect(response).to have_http_status(:ok)+ expect(reloaded.title).to eq('Müller')+ end++ it 'keeps the read gate ahead of keyed binary bytes' do+ change_multipart('title', 'text/plain; charset=binary', "M\xFFller", key: 'binary-title', ticket_id: SecureRandom.uuid)++ expect(response).to have_http_status(:not_found)+ expect(response.body).to eq('{"error":"not_found","code":"not_found"}')+ end++ it 'keeps the write permission ahead of keyed binary bytes' do+ Prosopite.pause { in_org { ProjectPermission.find_by!(user: user, project: project).update!(tickets_access: :read_only) } }+ change_multipart('title', 'text/plain; charset=binary', "M\xFFller", key: 'binary-title')++ expect(response).to have_http_status(:forbidden)+ expect(response.body).to eq('{"error":"forbidden","code":"forbidden"}')+ endenddescribe 'rights and existence' dodiff --git a/spec/services/mcp/idempotency_store_spec.rb b/spec/services/mcp/idempotency_store_spec.rbindex b0d2861..55fe964 100644--- a/spec/services/mcp/idempotency_store_spec.rb+++ b/spec/services/mcp/idempotency_store_spec.rb@@ -21,6 +21,34 @@ RSpec.describe Mcp::IdempotencyStore, :ci_guard doenddescribe '#replay' do+ it 'keeps fingerprints stored before binary parameter support' do+ McpIdempotencyKey.create!(personal_access_token: token, idempotency_key: 'old', tool_name: 'create_ticket',+ request_fingerprint: Digest::SHA256.hexdigest('{"a":1,"b":{"title":"Old"}}'),+ response_content: 'original answer')++ expect(store(key: 'old', args: { b: { title: 'Old' }, a: 1 }).replay.content).to eq('original answer')+ end++ it 'replays nested binary parameters and distinguishes different bytes' do+ store(key: 'binary', args: { change: { title: 'New' }, extra: ["x\xFF".b] }).remember('first')++ expect(store(key: 'binary', args: { extra: ["x\xFF".b], change: { title: 'New' } }).replay.content).to eq('first')+ expect(store(key: 'binary', args: { extra: ["x\xFE".b], change: { title: 'New' } }).replay.error).to match(/different parameters/)+ expect(store(key: 'binary', args: { extra: ["x\uFFFD"], change: { title: 'New' } }).replay.error).to match(/different parameters/)+ end++ {+ 'a marker-shaped object' => { encoding: 'ASCII-8BIT', bytes: 'fe' },+ 'a marker-shaped list' => %w[ASCII-8BIT fe],+ 'the same bytes in another encoding' => "\xFE".dup.force_encoding('UTF-8')+ }.each do |label, value|+ it "keeps binary strings distinct from #{label}" do+ store(key: 'binary', args: { extra: "\xFF".b, value: "\xFE".b }).remember('first')++ expect(store(key: 'binary', args: { extra: "\xFF".b, value: value }).replay.error).to match(/different parameters/)+ end+ end+it 'returns nil when the key has not been seen (caller should execute)' doexpect(store(key: 'k', args: { a: 1 }).replay).to be_nilend