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
Give /api/v1 an error code, Idempotency-Key and capabilities for programs
Guido Boyke7b30dc1f18b2
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex b61e579..11738ee 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -288,6 +288,9 @@ jobs:spec/requests/api/v1/ticket_existence_spec.rbspec/requests/api/v1/time_sessions_open_access_spec.rbspec/requests/api/v1/write_endpoints_spec.rb+ spec/requests/api/v1/error_codes_spec.rb+ spec/requests/api/v1/idempotency_spec.rb+ spec/requests/api/v1/capabilities_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/CLAUDE.md b/CLAUDE.mdindex e7b1081..5893cf6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -777,14 +777,32 @@ Drei Namensräume unter `/api`, und sie unterscheiden sich darin, **wer** ruft:For the seven REST ticket member routes, `Api::V1::ReadableTicket` resolves ticketsthrough the token's effective organisation/project reach and `TicketPolicy::Scope`:-missing and unreadable tickets return 404 with `{"error":"not_found"}`. Denied actions-on readable tickets remain 403; read-only tokens reject writes with 403 before any-ticket lookup, including missing IDs. Status and body are equal for missing and+missing and unreadable tickets return 404 with `{"error":"not_found","code":"not_found"}`.+Denied actions on readable tickets remain 403; read-only tokens reject writes with 403+(`"code":"read_only"`) before any ticket lookup, including missing IDs. Status and body are equal for missing andunreadable tickets, but queries are not: discovering the unknown tenant reads only`organisation_id` and `project_id` first. Ticket IDs are random UUIDs, not sequentialnumbers; this deliberately accepts query asymmetry instead of searching everyorganisation the token reaches. It makes no constant-time guarantee.+**`/api/v1` for programs** (REST R0, 2026-10-28; the terminal client moves from MCP to REST+feature by feature):++* **Error bodies** keep `error` and the HTTP status as they always were and add `code`, the+ 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,+ `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.+* **`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.+`GET /api/v1/time_sessions/open` lists the person's own open hours within the token'sreach, organisations AND projects, and only the rows the web time list shows them(`TimeSessions::ViewingScope`). A booking on a ticket they cannot read keeps its row anddiff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rbindex e994f19..cbf1610 100644--- a/app/controllers/api/v1/base_controller.rb+++ b/app/controllers/api/v1/base_controller.rb@@ -15,6 +15,8 @@ module Api# endpoint is the one that calls it, and its only test used to cover the EMPTY# list, so a 500 on every ticket that actually had a file stayed invisible.include ActiveStorage::SetCurrent+ # Idempotency-Key on writes (D7); each controller names its writes with `idempotent`.+ include Api::V1::Idempotent# A read-only token (the default) may not write through any endpoint. Enforced# here, once, like Mcp::ToolCall#write_blocked? on the MCP seam, so a new write@@ -44,19 +46,32 @@ module Apiprivatedef refuse_write_with_read_only_token- forbidden if current_token.read_only? && !(request.get? || request.head?)+ return unless current_token.read_only? && !(request.get? || request.head?)++ render_error(error: 'forbidden', code: 'read_only', status: :forbidden)enddef forbidden- render json: { error: 'forbidden' }, status: :forbidden+ render_error(error: 'forbidden', status: :forbidden)enddef not_found- render json: { error: 'not_found' }, status: :not_found+ render_error(error: 'not_found', status: :not_found)enddef bad_request(exception)- render json: { error: 'bad_request', message: exception.message }, status: :bad_request+ render_error(error: 'bad_request', message: exception.message, status: :bad_request)+ end++ # Every error body of /api/v1 goes through here (Api::V1::ErrorBody, D6).+ def render_error(error:, status:, code: nil, **extra)+ render json: Api::V1::ErrorBody.build(error: error, code: code, **extra), status: status+ end++ # Api::TokenAuthenticatable's 401 hook: the same body plus `code`. /api/mcp+ # shares the concern and keeps its own body.+ def render_unauthorized+ render_error(error: 'unauthorized', status: :unauthorized)enddef reset_current_attributesdiff --git a/app/controllers/api/v1/me_controller.rb b/app/controllers/api/v1/me_controller.rbindex 6143fcb..6509029 100644--- a/app/controllers/api/v1/me_controller.rb+++ b/app/controllers/api/v1/me_controller.rb@@ -15,7 +15,12 @@ module Apidata: {user: serialize_user(current_user),token: serialize_token(current_token),- scoped_organisations: serialize_scoped_organisations(current_token)+ scoped_organisations: serialize_scoped_organisations(current_token),+ # What this server offers, so a client enables a feature only where it+ # exists (cli_rest_plan D4). The same list for every token: whether a+ # write is refused is token.read_only.+ api_version: Api::V1::Capabilities::API_VERSION,+ capabilities: Api::V1::Capabilities.names}}enddiff --git a/app/controllers/api/v1/notifications_controller.rb b/app/controllers/api/v1/notifications_controller.rbindex b1f4df4..6a460ca 100644--- a/app/controllers/api/v1/notifications_controller.rb+++ b/app/controllers/api/v1/notifications_controller.rb@@ -15,6 +15,8 @@ module Apiskip_after_action :verify_authorizedskip_after_action :verify_policy_scoped+ idempotent :mark_as_read, :archive, :mark_all_as_read+rescue_from Notifications::InboxQuery::InvalidArgument, with: :bad_request# Declared after InvalidArgument (its parent) so it wins: a project or an# organisation outside the reach is a 404 here, like every other out-of-scope project.diff --git a/app/controllers/api/v1/posts_controller.rb b/app/controllers/api/v1/posts_controller.rbindex 492ea96..2a51bba 100644--- a/app/controllers/api/v1/posts_controller.rb+++ b/app/controllers/api/v1/posts_controller.rb@@ -5,6 +5,8 @@ module Apiclass PostsController < BaseControllerinclude Api::V1::ReadableTicket+ idempotent :create+# POST /api/v1/tickets/:ticket_id/posts## The web form's write (Actors::SavePost), so an API comment carries the same@@ -19,8 +21,7 @@ module Apiif result.success?render json: { data: serialize(actor.record) }, status: :createdelse- render json: { error: 'validation_failed', errors: result.errors },- status: :unprocessable_entity+ render_error(error: 'validation_failed', errors: result.errors, status: :unprocessable_entity)endendenddiff --git a/app/controllers/api/v1/tickets_controller.rb b/app/controllers/api/v1/tickets_controller.rbindex 1075668..8fd108d 100644--- a/app/controllers/api/v1/tickets_controller.rb+++ b/app/controllers/api/v1/tickets_controller.rb@@ -5,6 +5,8 @@ module Apiclass TicketsController < BaseControllerinclude Api::V1::ReadableTicket+ idempotent :create, :update+MAX_PER_PAGE = 100DEFAULT_PER_PAGE = 25@@ -118,10 +120,11 @@ module Api# Renders an actor failure Result. The machine-readable code becomes both# the `error` field and (via ACTOR_ERROR_STATUS) the HTTP status, so a- # client can distinguish validation (422) from a conflict (409) etc.+ # client can distinguish validation (422) from a conflict (409) etc.;+ # Api::V1::ErrorBody adds the class (`code`) and, for a refusal, `reason`.def render_actor_failure(result)- render json: { error: result.code, errors: result.errors },- status: ACTOR_ERROR_STATUS.fetch(result.code, :unprocessable_entity)+ render_error(error: result.code, errors: result.errors,+ status: ACTOR_ERROR_STATUS.fetch(result.code, :unprocessable_entity))end# --- Create helpers --------------------------------------------------diff --git a/app/controllers/api/v1/time_sessions_controller.rb b/app/controllers/api/v1/time_sessions_controller.rbindex 46257b7..e13ff0b 100644--- a/app/controllers/api/v1/time_sessions_controller.rb+++ b/app/controllers/api/v1/time_sessions_controller.rb@@ -5,6 +5,8 @@ module Apiclass TimeSessionsController < BaseControllerinclude Api::V1::ReadableTicket+ idempotent :create+# Deliberate opt-out for #open: it reads across organisations without a# tenant, so there is no single record to authorize. What it shows is# decided in TimeSessions::OpenHours: own bookings (creator_id), the@@ -63,8 +65,7 @@ module Apiif session.saverender json: { data: TimeSessions::Serializer.row(session) }, status: :createdelse- render json: { error: 'validation_failed', errors: session.errors.full_messages },- status: :unprocessable_entity+ render_error(error: 'validation_failed', errors: session.errors.full_messages, status: :unprocessable_entity)endendenddiff --git a/app/controllers/concerns/api/token_authenticatable.rb b/app/controllers/concerns/api/token_authenticatable.rbindex 65f0682..f871508 100644--- a/app/controllers/concerns/api/token_authenticatable.rb+++ b/app/controllers/concerns/api/token_authenticatable.rb@@ -49,7 +49,7 @@ module Api# unconfirmed past the grace period, system account): Devise's own# sign-in rule, so a token never reaches further than a password would.if pat.nil? || !pat.user&.active_for_authentication?- render json: { error: 'unauthorized' }, status: :unauthorized+ render_unauthorizedreturnend@@ -66,6 +66,12 @@ module Apipat.update_column(:last_used_at, Time.current)end+ # The 401 body. Api::V1::BaseController overrides it to add the error code;+ # /api/mcp keeps this one.+ def render_unauthorized+ render json: { error: 'unauthorized' }, status: :unauthorized+ end+def current_token@current_tokenenddiff --git a/app/controllers/concerns/api/v1/error_body.rb b/app/controllers/concerns/api/v1/error_body.rbnew file mode 100644index 0000000..a20f550--- /dev/null+++ b/app/controllers/concerns/api/v1/error_body.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++module Api+ module V1+ # The ONE builder of every /api/v1 error body (cli_rest_plan D6). Guarded by+ # spec/architecture/api_v1_error_body_guard_spec.rb: no controller renders+ # its own error JSON.+ #+ # `error` keeps the value it always had (token clients read it) and the HTTP+ # status stays the caller's. New beside it: `code`, the MCP error vocabulary+ # (Lalabase::Tools::Result::ERROR_CODES), so a program branches on the same+ # five classes on both surfaces, plus `unauthorized`, which MCP never answers+ # as a tool result. Actor codes nobody mapped are `refused` and carry the old+ # value as `reason`, as an MCP refusal carries its sub-code.+ module ErrorBody+ CODE_FOR_ERROR = {+ 'unauthorized' => 'unauthorized',+ 'forbidden' => 'forbidden',+ 'not_member' => 'forbidden',+ 'not_found' => 'not_found',+ 'bad_request' => 'invalid_input',+ 'validation_failed' => 'invalid_input'+ }.freeze++ REFUSED = 'refused'++ # @param error [String, Symbol] the legacy `error` value, unchanged on the wire+ # @param code [String, nil] overrides the derived code (read_only)+ # @param extra [Hash] fields the endpoint always sent beside `error` (errors, message)+ def self.build(error:, code: nil, **extra)+ error = error.to_s+ derived = CODE_FOR_ERROR[error]+ body = { error: error, code: (code || derived || REFUSED).to_s }+ body[:reason] = error if code.nil? && derived.nil?+ body.merge(extra)+ end+ end+ end+enddiff --git a/app/controllers/concerns/api/v1/idempotent.rb b/app/controllers/concerns/api/v1/idempotent.rbnew file mode 100644index 0000000..b726481--- /dev/null+++ b/app/controllers/concerns/api/v1/idempotent.rb@@ -0,0 +1,69 @@+# frozen_string_literal: true++module Api+ module V1+ # Idempotency-Key on /api/v1 writes (cli_rest_plan D7): a client retrying a+ # write after a timeout sends the same key and gets the first answer back,+ # status and body, instead of a second comment or a second booking.+ #+ # Same table and store as the MCP writes (Mcp::IdempotencyStore), so keys+ # are per token. The fingerprint is method + path + parameters, never only+ # the parameters: an MCP call stores its tool arguments, so a key reused+ # across the two surfaces is a mismatch on either side and never replays the+ # other surface's answer.+ #+ # Runs as an around_action declared by the controller (`idempotent :create`),+ # so it sits INSIDE authentication and the read-only gate of+ # 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.+ module Idempotent+ extend ActiveSupport::Concern++ HEADER = 'Idempotency-Key'+ MISMATCH = 'idempotency_key_reused'++ class_methods do+ def idempotent(*actions)+ around_action :with_idempotency_key, only: actions+ end+ end++ private++ def with_idempotency_key+ key = request.headers[HEADER].to_s.strip.presence+ return yield unless key++ store = Mcp::IdempotencyStore.new(token: current_token, tool_name: "rest:#{controller_path}##{action_name}",+ key: key, args: idempotency_fingerprint_args)+ stored = store.lookup+ return render_idempotency_mismatch if stored == :mismatch+ return replay_idempotent_answer(stored) if stored++ yield+ store.remember({ status: response.status, body: response.body }.to_json) if response.successful?+ end++ def idempotency_fingerprint_args+ { 'method' => request.request_method, 'path' => request.path,+ 'params' => request.query_parameters.merge(request.request_parameters) }+ end++ # The stored body is the JSON string the first answer sent; rendered as is.+ # Nothing was authorized for this request, by design: the write it answers+ # for was, when it ran.+ def replay_idempotent_answer(record)+ answer = JSON.parse(record.response_content)+ skip_authorization+ render json: answer.fetch('body'), status: answer.fetch('status')+ end++ def render_idempotency_mismatch+ skip_authorization+ render_error(error: MISMATCH, code: 'invalid_input', message: Mcp::IdempotencyStore::MISMATCH_ERROR,+ status: :unprocessable_entity)+ end+ end+ end+enddiff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rbnew file mode 100644index 0000000..40289f7--- /dev/null+++ b/app/services/api/v1/capabilities.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++module Api+ module V1+ # What this server's REST API offers, for a client that decides from it which+ # features to show (cli_rest_plan D4), the way the terminal client reads MCP+ # tools/list today. GET /api/v1/me hands it out with API_VERSION.+ #+ # ONE list. spec/requests/api/v1/capabilities_spec.rb pins it against the+ # routes both ways: every endpoint capability has its route, every /api/v1+ # route is named here. A new endpoint therefore adds its line here or turns+ # that spec red.+ module Capabilities+ # Minor for an additive change (a new endpoint, field or capability), major+ # never: an existing name, field or meaning does not change.+ API_VERSION = '1.1.0'++ # name => [verb, path as the router spells it]+ ENDPOINTS = {+ 'me.show' => ['GET', '/api/v1/me'],+ 'organisations.list' => ['GET', '/api/v1/organisations'],+ 'projects.list' => ['GET', '/api/v1/projects'],+ 'projects.ticket_attribute_definitions' => ['GET', '/api/v1/projects/:id/ticket_attribute_definitions'],+ 'tickets.list' => ['GET', '/api/v1/projects/:project_id/tickets'],+ 'tickets.create' => ['POST', '/api/v1/projects/:project_id/tickets'],+ 'tickets.show' => ['GET', '/api/v1/tickets/:id'],+ 'tickets.update' => ['PATCH', '/api/v1/tickets/:id'],+ 'tickets.activities' => ['GET', '/api/v1/tickets/:id/activities'],+ 'tickets.attachments' => ['GET', '/api/v1/tickets/:id/attachments'],+ 'posts.create' => ['POST', '/api/v1/tickets/:ticket_id/posts'],+ 'time_sessions.list' => ['GET', '/api/v1/tickets/:ticket_id/time_sessions'],+ 'time_sessions.create' => ['POST', '/api/v1/tickets/:ticket_id/time_sessions'],+ 'time_sessions.open' => ['GET', '/api/v1/time_sessions/open'],+ 'notifications.list' => ['GET', '/api/v1/notifications'],+ 'notifications.mark_as_read' => ['POST', '/api/v1/notifications/:id/mark_as_read'],+ 'notifications.archive' => ['POST', '/api/v1/notifications/:id/archive'],+ 'notifications.mark_all_as_read' => ['POST', '/api/v1/notifications/mark_all_as_read']+ }.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++ def self.names+ (ENDPOINTS.keys + FEATURES).sort+ end+ end+ end+enddiff --git a/app/services/mcp/idempotency_store.rb b/app/services/mcp/idempotency_store.rbindex e2777a8..2b3df8c 100644--- a/app/services/mcp/idempotency_store.rb+++ b/app/services/mcp/idempotency_store.rb@@ -2,7 +2,9 @@module Mcp# Durable idempotency for MCP write tools (D9), backed by the- # mcp_idempotency_keys table. Extracted from Mcp::ToolCall so the ToolCall stays+ # mcp_idempotency_keys table. The /api/v1 writes share it (Api::V1::Idempotent,+ # cli_rest_plan D7): one key space per token, so a key used on one surface+ # can never replay an answer on the other (their fingerprints differ). Extracted from Mcp::ToolCall so the ToolCall stays# focused on "run one tool call safely" and this concern can be unit-tested on# its own (no HTTP/dispatcher needed).#@@ -53,11 +55,22 @@ module Mcp# stored response, or a mismatch error), or nil when the key is unseen and# the caller should execute the write.def replay+ record = lookup+ return nil if record.nil?+ return mismatch_result if record == :mismatch++ Lalabase::Tools::Result.new(content: record.response_content)+ end++ # The stored row for this key, :mismatch when the key was used with another+ # request, or nil when it is unseen. The REST surface (Api::V1::Idempotent)+ # replays from here with its own answer shape; #replay is the MCP one.+ def lookuprecord = findreturn nil unless record- return mismatch_result unless record.request_fingerprint == @fingerprint+ return :mismatch unless record.request_fingerprint == @fingerprint- Lalabase::Tools::Result.new(content: record.response_content)+ recordend# Records a successful write's response so a later retry replays it.diff --git a/spec/architecture/api_v1_error_body_guard_spec.rb b/spec/architecture/api_v1_error_body_guard_spec.rbnew file mode 100644index 0000000..4e4cc93--- /dev/null+++ b/spec/architecture/api_v1_error_body_guard_spec.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++require 'rails_helper'++# What: no /api/v1 controller or concern builds an error body by hand; every one+# goes through Api::V1::BaseController#render_error (Api::V1::ErrorBody).+# Why: the error code (`code`, cli_rest_plan D6) is only as reliable as its+# coverage. A controller that renders `{ error: ... }` itself answers without+# `code`, and a client that branches on it misreads the answer. The rule has to+# hold for the next endpoint as well, so the hand-built body is what this guard+# refuses.+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++ def self.offences+ GLOBS.flat_map { |glob| Rails.root.glob(glob) }.filter_map do |path|+ relative = path.relative_path_from(Rails.root).to_s+ next if relative == OWNER++ relative if path.read.match?(HAND_BUILT)+ end+ end+end++RSpec.describe 'API V1 error body guard', :ci_guard do+ it 'finds the files it is meant to scan' do+ files = ApiV1ErrorBodyGuard::GLOBS.flat_map { |glob| Rails.root.glob(glob) }+ expect(files.map { |f| f.basename.to_s }).to include('base_controller.rb', 'tickets_controller.rb', 'error_body.rb')+ end++ it 'recognises a hand-built error body, wrapped or not' 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: { data: rows }').not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)+ expect("render_error(error: 'forbidden', status: :forbidden)").not_to match(ApiV1ErrorBodyGuard::HAND_BUILT)+ end++ it 'leaves every error body to render_error' do+ expect(ApiV1ErrorBodyGuard.offences).to be_empty+ end+enddiff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rbindex 8b9794e..b1a0474 100644--- a/spec/contracts/mcp_contract_recorder.rb+++ b/spec/contracts/mcp_contract_recorder.rb@@ -462,7 +462,41 @@ module McpContract},# Terminal client S5, appended last: its files are made right before it,# so every answer above stays as it was.- 'GET /api/v1/tickets/:id/attachments' => attachment_calls+ 'GET /api/v1/tickets/:id/attachments' => attachment_calls,+ # REST R0 (cli_rest_plan D6, D7), appended last for the same reason: one+ # answer per error code, then a write with an Idempotency-Key, its replay+ # and the key reused with another body. `refused` has no case: no+ # endpoint reaches an actor refusal deterministically (pinned with a+ # stubbed actor in spec/requests/api/v1/error_codes_spec.rb).+ 'errors' => rest_error_calls,+ 'idempotency' => rest_idempotency_calls+ }+ end++ def rest_error_calls+ login_posts = "/api/v1/tickets/#{id(:login_ticket)}/posts"+ {+ 'read_only' => rest_send(:post, :read, login_posts, params: { post: { body: 'Hallo' } }),+ # Anna may read the archive's tickets, not write them.+ 'forbidden' => rest_send(:post, :write, "/api/v1/tickets/#{id(:archived_ticket)}/posts",+ params: { post: { body: 'Hallo' } }),+ 'not_found' => rest_get(:read, "/api/v1/tickets/#{id(:missing)}"),+ 'invalid_input' => rest_send(:post, :write, login_posts, params: {}),+ 'invalid_input_validation' => rest_send(:post, :write, "/api/v1/projects/#{id(:website)}/tickets",+ params: { ticket: { title: '' } })+ }+ end++ def rest_idempotency_calls+ # Spelled out, not a loop: each request from its own line, as everywhere+ # here (Prosopite reads one call site asked three times as an N+1).+ path = "/api/v1/tickets/#{id(:login_ticket)}/posts"+ once = { post: { body: 'Per REST, einmal.' } }+ key = 'contract-rest-1'+ {+ 'first' => rest_send(:post, :write, path, params: once, key: key),+ 'replay' => rest_send(:post, :write, path, params: once, key: key),+ 'mismatch' => rest_send(:post, :write, path, params: { post: { body: 'Anderer Text' } }, key: key)}end@@ -519,6 +553,14 @@ module McpContractanswerend+ def rest_send(verb, token_name, path, params:, key: nil)+ extra = key ? { 'Idempotency-Key' => key } : {}+ session.public_send(verb, path, params: params, headers: headers(token_for(token_name)).merge(extra))+ request = { 'method' => verb.to_s.upcase, 'path' => path, 'params' => params }+ request['idempotency_key'] = key if key+ { 'token' => token_name.to_s, 'request' => request, 'response' => response }+ end+def rest_get(token_name, path)token = token_name ? token_for(token_name) : 'lalab_pat_invalid'session.get path, headers: headers(token)diff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.jsonindex b29b6f5..da00613 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": "fd599cb693f019c491228e081a54e59380d50b7d",+ "core_commit": "de411024f1483e7c7601855a7c9b46954dc9b7ec","core_dirty": true,- "contract_sha256": "5bcc5e85d196623f5d95be207275d2f8493062b988703534cfc0e0633d84d8bc"+ "contract_sha256": "605a4d53ca32608b71308f622a65f119e1ddbdaa8029849c802fa6a11754e39f"},"contract": {"mcp": {@@ -2991,6 +2991,29 @@"name": "Nordlicht GmbH","all_projects": true}+ ],+ "api_version": "1.1.0",+ "capabilities": [+ "error_codes",+ "idempotency",+ "me.show",+ "notifications.archive",+ "notifications.list",+ "notifications.mark_all_as_read",+ "notifications.mark_as_read",+ "organisations.list",+ "posts.create",+ "projects.list",+ "projects.ticket_attribute_definitions",+ "tickets.activities",+ "tickets.attachments",+ "tickets.create",+ "tickets.list",+ "tickets.show",+ "tickets.update",+ "time_sessions.create",+ "time_sessions.list",+ "time_sessions.open"]}}@@ -3025,6 +3048,29 @@"name": "Nordlicht GmbH","all_projects": true}+ ],+ "api_version": "1.1.0",+ "capabilities": [+ "error_codes",+ "idempotency",+ "me.show",+ "notifications.archive",+ "notifications.list",+ "notifications.mark_all_as_read",+ "notifications.mark_as_read",+ "organisations.list",+ "posts.create",+ "projects.list",+ "projects.ticket_attribute_definitions",+ "tickets.activities",+ "tickets.attachments",+ "tickets.create",+ "tickets.list",+ "tickets.show",+ "tickets.update",+ "time_sessions.create",+ "time_sessions.list",+ "time_sessions.open"]}}@@ -3038,7 +3084,8 @@"response": {"status": 401,"body": {- "error": "unauthorized"+ "error": "unauthorized",+ "code": "unauthorized"}}}@@ -3083,7 +3130,8 @@"response": {"status": 401,"body": {- "error": "unauthorized"+ "error": "unauthorized",+ "code": "unauthorized"}}}@@ -3231,7 +3279,8 @@"response": {"status": 401,"body": {- "error": "unauthorized"+ "error": "unauthorized",+ "code": "unauthorized"}}}@@ -3323,7 +3372,8 @@"response": {"status": 404,"body": {- "error": "not_found"+ "error": "not_found",+ "code": "not_found"}}},@@ -3335,7 +3385,186 @@"response": {"status": 404,"body": {- "error": "not_found"+ "error": "not_found",+ "code": "not_found"+ }+ }+ }+ },+ "errors": {+ "read_only": {+ "token": "read",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "body": "Hallo"+ }+ }+ },+ "response": {+ "status": 403,+ "body": {+ "error": "forbidden",+ "code": "read_only"+ }+ }+ },+ "forbidden": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000044/posts",+ "params": {+ "post": {+ "body": "Hallo"+ }+ }+ },+ "response": {+ "status": 403,+ "body": {+ "error": "forbidden",+ "code": "forbidden"+ }+ }+ },+ "not_found": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000999"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found",+ "code": "not_found"+ }+ }+ },+ "invalid_input": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {}+ },+ "response": {+ "status": 400,+ "body": {+ "error": "bad_request",+ "code": "invalid_input",+ "message": "param is missing or the value is empty or invalid: post"+ }+ }+ },+ "invalid_input_validation": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/tickets",+ "params": {+ "ticket": {+ "title": ""+ }+ }+ },+ "response": {+ "status": 422,+ "body": {+ "error": "validation_failed",+ "code": "invalid_input",+ "errors": [+ "Titel darf nicht leer sein"+ ]+ }+ }+ }+ },+ "idempotency": {+ "first": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "body": "Per REST, einmal."+ }+ },+ "idempotency_key": "contract-rest-1"+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-7>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "Per REST, einmal.",+ "body_text": "Per REST, einmal.",+ "is_private": false,+ "visible_to_user_id": null,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "replay": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "body": "Per REST, einmal."+ }+ },+ "idempotency_key": "contract-rest-1"+ },+ "response": {+ "status": 201,+ "body": {+ "data": {+ "id": "<generated-id-7>",+ "ticket_id": "00000000-0000-4000-8000-000000000041",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "Per REST, einmal.",+ "body_text": "Per REST, einmal.",+ "is_private": false,+ "visible_to_user_id": null,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "mismatch": {+ "token": "write",+ "request": {+ "method": "POST",+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts",+ "params": {+ "post": {+ "body": "Anderer Text"+ }+ },+ "idempotency_key": "contract-rest-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.rbnew file mode 100644index 0000000..6526449--- /dev/null+++ b/spec/requests/api/v1/capabilities_spec.rb@@ -0,0 +1,77 @@+# frozen_string_literal: true++require 'rails_helper'++# What: GET /api/v1/me names the API version and the abilities of this server+# (cli_rest_plan D4), from ONE list, Api::V1::Capabilities.+# Why: a REST client decides from this list which features it offers, as the+# terminal client decides from MCP tools/list today. A capability without a+# route makes it offer a feature that answers 404; a route without a+# capability stays invisible to it. Both directions are pinned here.+RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do+ let(:organisation) { create(:organisation) }+ let(:user) { create(:user) }++ def token(read_only:)+ build(:personal_access_token, user: user, organisations: [organisation], read_only: read_only).tap do |pat|+ pat.token_hash = nil+ pat.token_prefix = nil+ pat.generate_token!+ end+ end++ before do+ ActsAsTenant.with_tenant(organisation) do+ create(:membership, user: user, organisation: organisation, role: create(:role, organisation: organisation))+ end+ end++ def me(pat)+ get '/api/v1/me', headers: { 'Authorization' => "Bearer #{pat.token}" }+ response.parsed_body['data']+ end++ it 'names the API version and the capabilities beside the existing fields' do+ data = me(token(read_only: false))+ expect(data['api_version']).to eq('1.1.0')+ expect(data['capabilities']).to eq(Api::V1::Capabilities.names)+ expect(data.keys).to include('user', 'token', 'scoped_organisations')+ end++ it 'gives a read-only token the same list (the write right is token.read_only)' do+ expect(me(token(read_only: true))['capabilities']).to eq(me(token(read_only: false))['capabilities'])+ end++ it 'names the abilities that exist today, idempotency included' do+ expect(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', 'idempotency', 'error_codes'+ )+ end++ describe 'every capability and every route, both ways' do+ let(:v1_routes) do+ Rails.application.routes.routes.filter_map do |route|+ path = route.path.spec.to_s.delete_suffix('(.:format)')+ # Rails routes an update as PATCH and PUT; the capability names PATCH.+ "#{route.verb.sub(/\APUT\z/, 'PATCH')} #{path}" if path.start_with?('/api/v1/') && route.verb.present?+ end.uniq+ end++ it 'points every endpoint capability at a route that exists' do+ Api::V1::Capabilities::ENDPOINTS.each do |name, (verb, path)|+ expect(v1_routes).to include("#{verb} #{path}"), "#{name}: no route #{verb} #{path}"+ end+ end++ it 'names every /api/v1 route as a capability' do+ named = Api::V1::Capabilities::ENDPOINTS.values.map { |verb, path| "#{verb} #{path}" }+ expect(v1_routes - named).to be_empty+ end++ it 'keeps feature capabilities apart from endpoints' do+ expect(Api::V1::Capabilities::FEATURES & Api::V1::Capabilities::ENDPOINTS.keys).to be_empty+ end+ end+enddiff --git a/spec/requests/api/v1/error_codes_spec.rb b/spec/requests/api/v1/error_codes_spec.rbnew file mode 100644index 0000000..aa76702--- /dev/null+++ b/spec/requests/api/v1/error_codes_spec.rb@@ -0,0 +1,144 @@+# frozen_string_literal: true++require 'rails_helper'++# What: every /api/v1 error body carries `code`, the MCP error vocabulary+# (invalid_input, read_only, forbidden, not_found, refused, plus unauthorized),+# next to its unchanged `error` value and HTTP status (cli_rest_plan D6).+# Why: a program branches on a fixed code. `error` stays exactly as it was,+# because existing token clients read it; "missing" and "not visible to you"+# stay one answer, so the code leaks no existence either.+RSpec.describe 'API V1 error codes', :ci_guard, type: :request do+ let(:organisation) { create(:organisation) }+ let(:other_organisation) { create(:organisation) }+ let(:user) { create(:user) }+ let(:role) { create(:role, organisation: organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:ticket) { create(:ticket, project: project, organisation: organisation, creator: user) }+ let(:foreign_ticket) do+ ActsAsTenant.with_tenant(other_organisation) do+ foreign_project = create(:project, organisation: other_organisation)+ create(:ticket, project: foreign_project, organisation: other_organisation, creator: create(:user))+ end+ end++ def build_pat(read_only:)+ build(:personal_access_token, user: user, organisations: [organisation], read_only: read_only).tap do |pat|+ pat.token_hash = nil+ pat.token_prefix = nil+ pat.generate_token!+ end+ end++ let(:pat) { build_pat(read_only: false) }+ let(:read_pat) { build_pat(read_only: true) }++ def headers(token = pat)+ { 'Authorization' => "Bearer #{token.token}" }+ end++ def body = response.parsed_body++ before do+ ActsAsTenant.current_tenant = organisation+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end++ after { ActsAsTenant.current_tenant = nil }++ it 'answers a missing token with unauthorized, error unchanged' do+ get '/api/v1/me'+ expect(response).to have_http_status(:unauthorized)+ expect(body).to eq('error' => 'unauthorized', 'code' => 'unauthorized')+ end++ # The 401 lives in a concern /api/mcp shares; MCP answers as before.+ it 'leaves the 401 of /api/mcp as it was' do+ post '/api/mcp', params: { jsonrpc: '2.0', id: 1, method: 'tools/list' }.to_json,+ headers: { 'CONTENT_TYPE' => 'application/json' }+ expect(response).to have_http_status(:unauthorized)+ expect(body).to eq('error' => 'unauthorized')+ end++ it 'answers a write with a read-only token as read_only, error unchanged' do+ post "/api/v1/tickets/#{ticket.id}/posts", params: { post: { body: 'x' } }, headers: headers(read_pat)+ expect(response).to have_http_status(:forbidden)+ expect(body).to eq('error' => 'forbidden', 'code' => 'read_only')+ end++ it 'answers a Pundit refusal as forbidden' do+ ProjectPermission.find_by!(user: user, project: project).update!(tickets_access: :read_only)+ post "/api/v1/tickets/#{ticket.id}/posts", params: { post: { body: 'x' } }, headers: headers+ expect(response).to have_http_status(:forbidden)+ expect(body).to eq('error' => 'forbidden', 'code' => 'forbidden')+ end++ it 'answers a missing and a foreign ticket with one and the same not_found' do+ get "/api/v1/tickets/#{SecureRandom.uuid}", headers: headers+ missing = [response.status, body]+ get "/api/v1/tickets/#{foreign_ticket.id}", headers: headers+ expect([response.status, body]).to eq(missing)+ expect(missing).to eq([404, { 'error' => 'not_found', 'code' => 'not_found' }])+ end++ it 'answers a missing parameter as invalid_input, keeping error and message' do+ post "/api/v1/tickets/#{ticket.id}/posts", params: {}, headers: headers+ expect(response).to have_http_status(:bad_request)+ expect(body).to include('error' => 'bad_request', 'code' => 'invalid_input')+ expect(body['message']).to be_present+ end++ it 'answers a validation failure as invalid_input, keeping error and errors' do+ post "/api/v1/projects/#{project.id}/tickets", params: { ticket: { title: '' } }, headers: headers+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to include('error' => 'validation_failed', 'code' => 'invalid_input')+ expect(body['errors']).to be_present+ end++ it 'answers an unusable inbox filter as invalid_input' do+ get '/api/v1/notifications', params: { status: 'bogus' }, headers: headers+ expect(response).to have_http_status(:bad_request)+ expect(body).to include('error' => 'bad_request', 'code' => 'invalid_input')+ end++ it 'answers a time session without duration as invalid_input' do+ create(:time_session_permission, user: user, project: project)+ post "/api/v1/tickets/#{ticket.id}/time_sessions", params: { time_session: { description: 'x' } }, headers: headers+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to include('error' => 'validation_failed', 'code' => 'invalid_input')+ end++ describe 'actor failures on a ticket write' do+ def fail_with(code)+ allow(Actors::SaveTicket).to receive(:call)+ .and_return(Actors::BaseActor::Result.new(success: false, errors: ['nope'], code: code))+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'new' } }, headers: headers+ end++ it 'answers stale_object as refused with the old error as reason, status unchanged' do+ fail_with(:stale_object)+ expect(response).to have_http_status(:conflict)+ expect(body).to eq('error' => 'stale_object', 'code' => 'refused', 'reason' => 'stale_object', 'errors' => ['nope'])+ end++ it 'answers conflict as refused' do+ fail_with(:conflict)+ expect(response).to have_http_status(:conflict)+ expect(body).to include('error' => 'conflict', 'code' => 'refused', 'reason' => 'conflict')+ end++ it 'answers not_member as forbidden' do+ fail_with(:not_member)+ expect(response).to have_http_status(:forbidden)+ expect(body).to include('error' => 'not_member', 'code' => 'forbidden')+ expect(body).not_to have_key('reason')+ end++ it 'answers an unknown actor code as refused, status 422 as before' do+ fail_with(:error)+ expect(response).to have_http_status(:unprocessable_content)+ expect(body).to include('error' => 'error', 'code' => 'refused', 'reason' => 'error')+ end+ end+enddiff --git a/spec/requests/api/v1/idempotency_spec.rb b/spec/requests/api/v1/idempotency_spec.rbnew file mode 100644index 0000000..81d7f35--- /dev/null+++ b/spec/requests/api/v1/idempotency_spec.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++require 'rails_helper'++# What: an Idempotency-Key header on a /api/v1 write replays the first answer+# (status and body) instead of writing again (cli_rest_plan D7). Same table as+# the MCP idempotency keys, keyed per token.+# Why: a client retries a write after a timeout without knowing whether it+# landed. Without the key that retry is a second comment or a second booking.+# The threats pinned here: a replay reaching another token or a read-only one,+# a reused key with other arguments still writing, a failed write blocking its+# correction, and a key crossing between MCP and REST to hand out a foreign answer.+RSpec.describe 'API V1 idempotency', :ci_guard, type: :request do+ include ActiveSupport::Testing::TimeHelpers++ let(:organisation) { create(:organisation) }+ let(:user) { create(:user) }+ let(:role) { create(:role, organisation: organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:ticket) { create(:ticket, project: project, organisation: organisation, creator: user) }++ def build_pat(read_only: false, owner: user)+ build(:personal_access_token, user: owner, organisations: [organisation], read_only: read_only).tap do |pat|+ pat.token_hash = nil+ pat.token_prefix = nil+ pat.generate_token!+ end+ end++ let(:pat) { build_pat }++ def headers(key = nil, token: pat)+ h = { 'Authorization' => "Bearer #{token.token}" }+ h['Idempotency-Key'] = key if key+ h+ end++ def snapshot = [response.status, response.body]++ def posts_count = Post.where(ticket: ticket).count++ before do+ ActsAsTenant.current_tenant = organisation+ create(:membership, user: user, organisation: organisation, role: role, active: true)+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end++ after { ActsAsTenant.current_tenant = nil }++ def comment(body, key:, token: pat)+ post "/api/v1/tickets/#{ticket.id}/posts", params: { post: { body: body } }, headers: headers(key, token: token)+ end++ describe 'POST /api/v1/tickets/:ticket_id/posts' do+ it 'replays the first answer for a repeated key and writes once' do+ expect { comment('Hallo', key: 'k-1') }.to change { posts_count }.by(1)+ first = snapshot+ expect(first.first).to eq(201)++ expect { comment('Hallo', key: 'k-1') }.not_to(change { posts_count })+ expect(snapshot).to eq(first)+ end++ it 'writes twice without a key, as before' do+ expect { 2.times { comment('Hallo', key: nil) } }.to change { posts_count }.by(2)+ end++ it 'treats a blank key as no key' do+ expect { 2.times { comment('Hallo', key: ' ') } }.to change { posts_count }.by(2)+ end++ it 'refuses the key with other arguments as invalid_input and writes nothing' do+ comment('Hallo', key: 'k-2')+ expect { comment('Anders', key: 'k-2') }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(response.parsed_body).to include('code' => 'invalid_input', 'error' => 'idempotency_key_reused')+ end++ it 'does not remember a failed write, so the corrected retry writes' do+ post "/api/v1/tickets/#{ticket.id}/posts", params: { post: { body: '' } }, headers: headers('k-3')+ expect(response).to have_http_status(:unprocessable_content)+ expect { comment('Jetzt richtig', key: 'k-3') }.to change { posts_count }.by(1)+ expect(response).to have_http_status(:created)+ end++ it "keeps one token's key away from another token" do+ comment('Hallo', key: 'k-4')+ expect { comment('Hallo', key: 'k-4', token: build_pat) }.to change { posts_count }.by(1)+ end++ it 'refuses a read-only token before any replay' do+ comment('Hallo', key: 'k-5')+ read_only = build_pat(read_only: true)+ McpIdempotencyKey.find_by!(idempotency_key: 'k-5').update!(personal_access_token_id: read_only.id)+ comment('Hallo', key: 'k-5', token: read_only)+ expect(response).to have_http_status(:forbidden)+ expect(response.parsed_body).to eq('error' => 'forbidden', 'code' => 'read_only')+ end++ # The stored fingerprint is what this very request's parameters would give+ # without method and path: only those two keep the surfaces apart.+ it 'never replays an answer stored by an MCP call under the same key' do+ bare = Mcp::IdempotencyStore.fingerprint('params' => { 'post' => { 'body' => 'Hallo' } })+ McpIdempotencyKey.create!(personal_access_token: pat, idempotency_key: 'k-6', tool_name: 'post_comment',+ request_fingerprint: bare, response_content: 'MCP-ANSWER')+ expect { comment('Hallo', key: 'k-6') }.not_to(change { posts_count })+ expect(response).to have_http_status(:unprocessable_content)+ expect(response.body).not_to include('MCP-ANSWER')+ end++ it 'never lets MCP replay an answer stored by REST under the same key' do+ comment('Hallo', key: 'k-7')+ rest_body = response.body+ post '/api/mcp', params: { jsonrpc: '2.0', id: 1, method: 'tools/call',+ params: { name: 'post_comment',+ arguments: { project_id: project.id, ticket_id: ticket.id, body: 'Hallo',+ idempotency_key: 'k-7' } } }.to_json,+ headers: headers.merge('CONTENT_TYPE' => 'application/json')+ result = response.parsed_body['result']+ expect(result['isError']).to be(true)+ expect(result['_meta']).to eq('lalabase/code' => 'invalid_input')+ expect(response.body).not_to include(JSON.parse(rest_body).dig('data', 'id'))+ end+ end++ describe 'the other writes' do+ before do+ create(:time_session_permission, user: user, project: project)+ end++ it 'replays a ticket creation' do+ create_ticket = lambda do+ post "/api/v1/projects/#{project.id}/tickets", params: { ticket: { title: 'Neu' } }, headers: headers('t-1')+ end+ expect { 2.times { create_ticket.call } }.to change { Ticket.where(project: project).count }.by(1)+ expect(response).to have_http_status(:created)+ end++ it 'replays a ticket update without writing again' do+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'new' } }, headers: headers('u-1')+ first = snapshot+ expect(Actors::SaveTicket).not_to receive(:call)+ patch "/api/v1/tickets/#{ticket.id}", params: { ticket: { status: 'new' } }, headers: headers('u-1')+ expect(snapshot).to eq(first)+ end++ it 'replays a time booking' do+ book = lambda do+ post "/api/v1/tickets/#{ticket.id}/time_sessions", params: { time_session: { duration_minutes: 30 } },+ headers: headers('b-1')+ end+ expect { 2.times { book.call } }.to change { TimeSession.where(ticket: ticket).count }.by(1)+ expect(response).to have_http_status(:created)+ end++ describe 'notifications' do+ def notification(state: 'queued')+ create(:notification, recipient: user, actor: create(:user), organisation: organisation, notifiable: ticket,+ state: state, event_type: Notifications::Constants::EVENT_TYPE_TICKET_COMMENTED,+ payload: { 'action' => 'commented' })+ end++ it 'replays mark_as_read with the first read_at' do+ row = notification+ post "/api/v1/notifications/#{row.id}/mark_as_read", headers: headers('n-1')+ first = snapshot+ travel 1.hour do+ post "/api/v1/notifications/#{row.id}/mark_as_read", headers: headers('n-1')+ end+ expect(snapshot).to eq(first)+ end++ it 'replays archive' do+ row = notification+ post "/api/v1/notifications/#{row.id}/archive", headers: headers('n-2')+ first = snapshot+ expect_any_instance_of(Notification).not_to receive(:archive!)+ post "/api/v1/notifications/#{row.id}/archive", headers: headers('n-2')+ expect(snapshot).to eq(first)+ end++ it 'replays mark_all_as_read without touching a row that arrived in between' do+ notification+ post '/api/v1/notifications/mark_all_as_read', headers: headers('n-3')+ first = snapshot+ later = notification+ post '/api/v1/notifications/mark_all_as_read', headers: headers('n-3')+ expect(snapshot).to eq(first)+ expect(later.reload.state).to eq('queued')+ end+ end+ end+enddiff --git a/spec/requests/api/v1/ticket_existence_spec.rb b/spec/requests/api/v1/ticket_existence_spec.rbindex d6da7c1..fa0feda 100644--- a/spec/requests/api/v1/ticket_existence_spec.rb+++ b/spec/requests/api/v1/ticket_existence_spec.rb@@ -52,12 +52,12 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request doendend- def expect_refusal(verb, suffix, payload, id:, status: :not_found, error: 'not_found')+ def expect_refusal(verb, suffix, payload, id:, status: :not_found, error: 'not_found', code: 'not_found')before = domain_staterequest_ticket(verb, suffix, payload, id: id)expect(domain_state).to eq(before)expect(response).to have_http_status(status)- expect(response.body).to eq({ error: error }.to_json)+ expect(response.body).to eq({ error: error, code: code }.to_json)enddef member_of(org, admin: false)@@ -185,13 +185,13 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request doelseexpect(Ticket).not_to receive(:where)expect(Ticket).not_to receive(:includes)- expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden')+ expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden', code: 'read_only')endendit 'returns the same answer for a missing UUID' do- status, error = verb == :get ? [:not_found, 'not_found'] : [:forbidden, 'forbidden']- expect_refusal(verb, suffix, payload, id: SecureRandom.uuid, status: status, error: error)+ status, error, code = verb == :get ? [:not_found, 'not_found', 'not_found'] : [:forbidden, 'forbidden', 'read_only']+ expect_refusal(verb, suffix, payload, id: SecureRandom.uuid, status: status, error: error, code: code)endcontext 'with a readable and writable ticket' do@@ -202,7 +202,8 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request dorequest_ticket(verb, suffix, payload)expect(response).to have_http_status(:ok)else- expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden')+ expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden',+ code: 'read_only')endendend@@ -250,7 +251,7 @@ RSpec.describe 'REST ticket existence', :ci_guard, type: :request doroutes.reject { |verb,| verb == :get }.each do |verb, suffix, payload|it "keeps action refusal at 403 for #{verb.upcase} #{suffix.presence || 'ticket'}" do- expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden')+ expect_refusal(verb, suffix, payload, id: ticket.id, status: :forbidden, error: 'forbidden', code: 'forbidden')endenddiff --git a/spec/requests/api/v1/write_endpoints_spec.rb b/spec/requests/api/v1/write_endpoints_spec.rbindex 60816d1..4fff37f 100644--- a/spec/requests/api/v1/write_endpoints_spec.rb+++ b/spec/requests/api/v1/write_endpoints_spec.rb@@ -667,7 +667,8 @@ RSpec.describe 'API V1 Write Endpoints', :ci_guard, type: :request doend)expect(response).to have_http_status(:forbidden)- expect(response.parsed_body).to eq('error' => 'forbidden')+ # `error` as it always was, `code` naming the token as the reason (D6).+ expect(response.parsed_body).to eq('error' => 'forbidden', 'code' => 'read_only')expect(ticket.reload.attributes).to eq(ticket_state)expect(notification.reload).to have_attributes(read_at: nil, archived_at: nil)end