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.

Bound the Idempotency-Key and guard that every /api/v1 write honours it

Guido Boyke49ab9c13d53a
diff --git a/CLAUDE.md b/CLAUDE.md
index 5893cf6..df725ed 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -792,13 +792,18 @@ feature by feature):
MCP vocabulary (`invalid_input`, `read_only`, `forbidden`, `not_found`, `refused`, plus
`unauthorized`); an unmapped actor code is `refused` with the old value as `reason`. Every
body comes from `Api::V1::ErrorBody` through `BaseController#render_error`; guard
- `spec/architecture/api_v1_error_body_guard_spec.rb`. The 401 of `/api/mcp` (same concern,
+ `spec/architecture/api_v1_error_body_guard_spec.rb`. Answers outside the controllers carry
+ no `code`: the Rack::Attack 429 (plain text) and a 500 from the exceptions app. The 401 of `/api/mcp` (same concern,
`render_unauthorized`) keeps its old body.
* **`Idempotency-Key`** on every write (`idempotent :create` in the controller,
`Api::V1::Idempotent`): the same key and request replays the first 2xx answer (status and
body), another request answers 422 `idempotency_key_reused`. Same table and store as MCP
(`Mcp::IdempotencyStore`); the REST fingerprint includes method and path, so a key never
- crosses surfaces. Runs inside authentication and the read-only gate.
+ crosses surfaces. Runs inside authentication and the read-only gate. A key is at most 255
+ bytes (longer: 422 `invalid_idempotency_key`, nothing written). 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`
+ (`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 new
endpoint adds its line there. Additive changes bump the minor.
diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb
index cbf1610..b51da87 100644
--- a/app/controllers/api/v1/base_controller.rb
+++ b/app/controllers/api/v1/base_controller.rb
@@ -27,6 +27,9 @@ module Api
rescue_from Pundit::NotAuthorizedError, with: :forbidden
rescue_from ActiveRecord::RecordNotFound, with: :not_found
rescue_from ActionController::ParameterMissing, with: :bad_request
+ # A body that is not the JSON it claims to be. Without a key Rails parses it
+ # lazily and some actions never ask; with one the fingerprint reads it first.
+ rescue_from ActionDispatch::Http::Parameters::ParseError, with: :bad_request
# Pundit tripwire (pattern: Organisations::BaseController): Every action must
# authorize explicitly — authorize or policy_scope in index. A new
diff --git a/app/controllers/concerns/api/v1/idempotent.rb b/app/controllers/concerns/api/v1/idempotent.rb
index b726481..637357e 100644
--- a/app/controllers/concerns/api/v1/idempotent.rb
+++ b/app/controllers/concerns/api/v1/idempotent.rb
@@ -17,14 +17,33 @@ module Api
# Api::V1::BaseController: a read-only token is refused before any replay,
# and a replay goes to the token that stored it. Only a 2xx answer is
# remembered; a refused write leaves the key free for the corrected retry.
+ #
+ # A replay checks no rights, deliberately: it hands the token the answer that
+ # same token already received, nothing it has not seen; a new key goes
+ # through every check. Keys do not expire. A retry must send the same bytes:
+ # the fingerprint sorts only the top-level keys, so another encoding of the
+ # same request is a mismatch (safe: it writes nothing).
module Idempotent
extend ActiveSupport::Concern
HEADER = 'Idempotency-Key'
MISMATCH = 'idempotency_key_reused'
+ INVALID_KEY = 'invalid_idempotency_key'
+ # Bytes. The unique index on (token, key) holds about 2.7 KB, and the key is
+ # stored only AFTER the write: a longer key wrote, failed to be stored with
+ # a 500, and wrote again on every retry. Refused before anything runs.
+ MAX_KEY_LENGTH = 255
+
+ included do
+ # The actions this controller declared, read by
+ # spec/architecture/api_v1_writes_idempotent_guard_spec.rb: every write
+ # route must be here, as /api/v1/me promises.
+ class_attribute :idempotent_actions, instance_writer: false, default: [].freeze
+ end
class_methods do
def idempotent(*actions)
+ self.idempotent_actions = (idempotent_actions + actions).uniq.freeze
around_action :with_idempotency_key, only: actions
end
end
@@ -34,6 +53,7 @@ module Api
def with_idempotency_key
key = request.headers[HEADER].to_s.strip.presence
return yield unless key
+ return render_invalid_idempotency_key if key.bytesize > MAX_KEY_LENGTH
store = Mcp::IdempotencyStore.new(token: current_token, tool_name: "rest:#{controller_path}##{action_name}",
key: key, args: idempotency_fingerprint_args)
@@ -59,6 +79,12 @@ module Api
render json: answer.fetch('body'), status: answer.fetch('status')
end
+ def render_invalid_idempotency_key
+ skip_authorization
+ render_error(error: INVALID_KEY, code: 'invalid_input',
+ message: "#{HEADER} is longer than #{MAX_KEY_LENGTH} bytes", status: :unprocessable_entity)
+ end
+
def render_idempotency_mismatch
skip_authorization
render_error(error: MISMATCH, code: 'invalid_input', message: Mcp::IdempotencyStore::MISMATCH_ERROR,
diff --git a/spec/architecture/api_v1_error_body_guard_spec.rb b/spec/architecture/api_v1_error_body_guard_spec.rb
index 4e4cc93..e546fe4 100644
--- a/spec/architecture/api_v1_error_body_guard_spec.rb
+++ b/spec/architecture/api_v1_error_body_guard_spec.rb
@@ -13,8 +13,18 @@ module ApiV1ErrorBodyGuard
GLOBS = %w[app/controllers/api/v1/**/*.rb app/controllers/concerns/api/v1/**/*.rb].freeze
OWNER = 'app/controllers/concerns/api/v1/error_body.rb'
- # A render with an `error` key or an `errors` key, on one line or wrapped.
- HAND_BUILT = /render\s*\(?\s*json:\s*\{[^}]*\berrors?:/m
+ ERROR_STATUS = 'bad_request|unauthorized|forbidden|not_found|unprocessable_entity|unprocessable_content|' \
+ 'conflict|internal_server_error|[45]\\d\\d'
+
+ # Any of: a render with an `error`/`errors` key (one line or wrapped), a
+ # string `"error" =>` key, a bodyless `head` with an error status, or a plain
+ # `render` (not `render_error`) that sets an error status on its own line.
+ HAND_BUILT = Regexp.union(
+ /render\s*\(?\s*json:\s*\{[^}]*\berrors?:/m,
+ /["']errors?["']\s*=>/,
+ /\bhead\s*\(?\s*:?(?:#{ERROR_STATUS})\b/,
+ /\brender(?!_)\b[^\n]*\bstatus:\s*:?(?:#{ERROR_STATUS})\b/
+ )
def self.offences
GLOBS.flat_map { |glob| Rails.root.glob(glob) }.filter_map do |path|
@@ -36,7 +46,13 @@ RSpec.describe 'API V1 error body guard', :ci_guard do
expect("render json: { error: 'forbidden' }, status: :forbidden").to match(ApiV1ErrorBodyGuard::HAND_BUILT)
expect("render json: { data: x, errors: e },\n status: :ok").to match(ApiV1ErrorBodyGuard::HAND_BUILT)
expect("render json: {\n error: result.code\n}").to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect("render json: { 'error' => 'x' }").to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect('render status: :not_found, json: body').to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect('render json: body, status: 422').to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect('head :forbidden').to match(ApiV1ErrorBodyGuard::HAND_BUILT)
expect('render json: { data: rows }').not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect('render json: { data: row }, status: :created').not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)
+ expect('head :ok').not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)
expect("render_error(error: 'forbidden', status: :forbidden)").not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)
end
diff --git a/spec/architecture/api_v1_writes_idempotent_guard_spec.rb b/spec/architecture/api_v1_writes_idempotent_guard_spec.rb
new file mode 100644
index 0000000..00061d2
--- /dev/null
+++ b/spec/architecture/api_v1_writes_idempotent_guard_spec.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: every write route of /api/v1 honours the Idempotency-Key header
+# (`idempotent :action` in its controller, Api::V1::Idempotent).
+# Why: /api/v1/me promises the `idempotency` capability for every write. A new
+# POST or PATCH that forgets `idempotent` would ignore the header silently, and
+# a client that trusts the promise would write twice on a retry. A promise a
+# new endpoint has to remember is not kept, so this guard keeps it.
+RSpec.describe 'API V1 writes are idempotent', :ci_guard do
+ let(:write_routes) do
+ Rails.application.routes.routes.filter_map do |route|
+ controller = route.defaults[:controller].to_s
+ next unless controller.start_with?('api/v1/')
+ next if route.verb.blank? || %w[GET HEAD].include?(route.verb)
+
+ [controller, route.defaults[:action].to_s, "#{route.verb} #{route.path.spec}"]
+ end
+ end
+
+ it 'finds the write routes it is meant to cover' do
+ expect(write_routes.map(&:first).uniq).to include('api/v1/tickets', 'api/v1/posts', 'api/v1/notifications')
+ end
+
+ it 'declares every write action idempotent' do
+ missing = write_routes.reject do |controller, action, _|
+ "#{controller.camelize}Controller".constantize.idempotent_actions.include?(action.to_sym)
+ end
+ expect(missing.map(&:last)).to be_empty
+ end
+end
diff --git a/spec/requests/api/v1/idempotency_spec.rb b/spec/requests/api/v1/idempotency_spec.rb
index 81d7f35..3b1e9d4 100644
--- a/spec/requests/api/v1/idempotency_spec.rb
+++ b/spec/requests/api/v1/idempotency_spec.rb
@@ -123,6 +123,67 @@ RSpec.describe 'API V1 idempotency', :ci_guard, type: :request do
end
end
+ describe 'the request the key belongs to' do
+ let(:other_ticket) { create(:ticket, project: project, organisation: organisation, creator: user) }
+
+ # 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' do
+ comment('Hallo', key: 'p-1')
+ expect do
+ post "/api/v1/tickets/#{other_ticket.id}/posts", params: { post: { body: 'Hallo' } }, headers: headers('p-1')
+ end.not_to(change { Post.where(ticket: other_ticket).count })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.parsed_body).to include('error' => 'idempotency_key_reused', 'code' => 'invalid_input')
+ end
+
+ it 'refuses the key on another method to the same path' do
+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'new' } }, headers: headers('p-2')
+ put "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'new' } }, headers: headers('p-2')
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.parsed_body).to include('error' => 'idempotency_key_reused')
+ end
+ end
+
+ # Deliberate: a replay checks no rights. It hands the token the answer that
+ # very token already received, nothing new; a fresh key gets the rights check.
+ it 'replays to the same token after its project rights are gone, while a new key is refused' do
+ comment('Hallo', key: 'r-1')
+ first = snapshot
+ ProjectPermission.find_by!(user: user, project: project).destroy!
+ comment('Hallo', key: 'r-1')
+ expect(snapshot).to eq(first)
+ expect { comment('Hallo', key: 'r-2') }.not_to(change { posts_count })
+ expect(response).to have_http_status(:not_found)
+ end
+
+ describe 'a key the store cannot hold' do
+ # The unique index on (token, key) holds about 2.7 KB; a longer key used to
+ # write, fail to be stored with a 500, and write again on every retry.
+ it 'refuses a key longer than the limit before writing' do
+ long = 'k' * (Api::V1::Idempotent::MAX_KEY_LENGTH + 1)
+ expect { comment('Hallo', key: long) }.not_to(change { posts_count })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.parsed_body).to include('error' => 'invalid_idempotency_key', 'code' => 'invalid_input')
+ end
+
+ it 'accepts a key of exactly the limit' do
+ key = 'k' * Api::V1::Idempotent::MAX_KEY_LENGTH
+ expect { 2.times { comment('Hallo', key: key) } }.to change { posts_count }.by(1)
+ end
+ end
+
+ # A malformed JSON body answers like any bad request, with a code, whether
+ # or not the request carries a key.
+ it 'answers an unreadable JSON body with a key as invalid_input, writing nothing' do
+ expect do
+ post "/api/v1/tickets/#{ticket.id}/posts", params: '{bad',
+ headers: headers('j-1').merge('CONTENT_TYPE' => 'application/json')
+ end.not_to(change { posts_count })
+ expect(response).to have_http_status(:bad_request)
+ expect(response.parsed_body).to include('error' => 'bad_request', 'code' => 'invalid_input')
+ end
+
describe 'the other writes' do
before do
create(:time_session_permission, user: user, project: project)