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
Record the ticket attachments endpoint in the contract, guard private files
Guido Boyke38c4d2ad6e9f
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex 20f312d..9830cdf 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -274,6 +274,7 @@ jobs:spec/requests/api/v1/pundit_tripwire_spec.rbspec/requests/api/v1/read_endpoints_spec.rbspec/requests/api/v1/token_organisation_scopes_spec.rb+ spec/requests/api/v1/ticket_attachments_privacy_spec.rbspec/requests/api/v1/ticket_existence_spec.rbspec/requests/api/v1/time_sessions_open_access_spec.rbspec/requests/api/v1/write_endpoints_spec.rbdiff --git a/app/controllers/api/v1/tickets_controller.rb b/app/controllers/api/v1/tickets_controller.rbindex 3a05e68..e204514 100644--- a/app/controllers/api/v1/tickets_controller.rb+++ b/app/controllers/api/v1/tickets_controller.rb@@ -272,9 +272,11 @@ module Api# counts as attachments_count. This used to read post.attachments, the# has_many_attached NOTHING in the app writes, so the list answered "none" for# every comment that had a file while #show reported a real count — one API,- # two answers to the same question.- ticket.posts.readable_by(current_user, ticket.organisation).each do |post|- post.post_documents.includes(post_document_file_attachment: :blob).find_each do |pd|+ # two answers to the same question. Preloaded, because one read per+ # readable comment was an N+1; sorted by id as find_each used to order them.+ ticket.posts.readable_by(current_user, ticket.organisation)+ .includes(post_documents: { post_document_file_attachment: :blob }).find_each do |post|+ post.post_documents.sort_by(&:id).each do |pd|blob = pd.post_document_file&.blobnext unless blobdiff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rbindex f3f1905..c2a6408 100644--- a/spec/contracts/mcp_contract_recorder.rb+++ b/spec/contracts/mcp_contract_recorder.rb@@ -420,10 +420,63 @@ module McpContract'ok_one_organisation' => rest_get(:read, "/api/v1/projects?organisation_id=#{id(:organisation)}"),'empty' => rest_get(:read, "/api/v1/projects?organisation_id=#{id(:other_organisation)}"),'unauthorized' => rest_get(nil, '/api/v1/projects')- }+ },+ # 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+ }+ end++ # One file on the login ticket, one on Ben's public comment there, both from+ # fixed fixture files so name, type and size are the same on every run.+ # Without `record`: no tick, no clock moved for anything recorded later.+ ATTACHMENT_FIXTURES = {+ ticket: ['test_document.pdf', 'application/pdf'],+ post: ['test_file.txt', 'text/plain']+ }.freeze++ def attachment_calls+ in_org do+ attach_fixture(TicketDocument.new(ticket: @login, organisation: @organisation, create_embeddings: false),+ :ticket_document_file, :ticket)+ attach_fixture(PostDocument.new(post: Post.find(id(:first_post)), organisation: @organisation, create_embeddings: false),+ :post_document_file, :post)+ end+ path = ->(ticket) { "/api/v1/tickets/#{id(ticket)}/attachments" }+ {+ 'ok' => signed_urls_replaced(rest_get(:write, path.call(:login_ticket))),+ # A read-only token reads files like any other reader.+ 'ok_read_only' => signed_urls_replaced(rest_get(:read, path.call(:login_ticket))),+ 'empty' => rest_get(:read, path.call(:export_ticket)),+ 'not_found' => rest_get(:read, path.call(:missing)),+ # No read access to the ticket: answered like a missing one.+ 'hidden' => rest_get(:read, path.call(:hidden_ticket))}end+ def attach_fixture(document, attachment, kind)+ filename, content_type = ATTACHMENT_FIXTURES.fetch(kind)+ document.public_send(attachment).attach(io: Rails.root.join('spec/fixtures/files', filename).open('rb'),+ filename: filename, content_type: content_type, identify: false)+ document.save!+ end++ SIGNED_PART = '<signed-key>'++ # The URL is signed for five minutes and differs on every run: the request's+ # host, Active Storage's Disk route, a signed segment, the file name. Only the+ # signed segment becomes a placeholder; a URL of any other form stops the+ # recording instead of being written down in a form the server does not send.+ # The real URL's form is pinned in spec/requests/api/v1/read_endpoints_spec.rb.+ def signed_urls_replaced(answer)+ form = %r{\A(?<before>http://#{Regexp.escape(session.host)}/rails/active_storage/disk/)[^/?#]+(?<after>/[^/?#]+)\z}+ answer.dig('response', 'body', 'data').each do |file|+ match = form.match(file['url']) or raise "attachment URL of an unexpected form: #{file['url'].inspect}"+ file['url'] = "#{match[:before]}#{SIGNED_PART}#{match[:after]}"+ end+ answer+ 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 21b6bd0..1aee2d8 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": "d4d6322615bd67d285773b26ae356562147881b3",+ "core_commit": "c8f6e4acf5deca9444ea3b87c75251c9246e8ec4","core_dirty": true,- "contract_sha256": "617ccb4d3671ee6fb82dfd0cc4857c0001450b2886b3eb6db6b8354c9961abc8"+ "contract_sha256": "0d74f7549e9cf134b87e79ee66e48495a1698088d5828795030b98255036fd79"},"contract": {"mcp": {@@ -2957,6 +2957,110 @@}}}+ },+ "GET /api/v1/tickets/:id/attachments": {+ "ok": {+ "token": "write",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/attachments"+ },+ "response": {+ "status": 200,+ "body": {+ "data": [+ {+ "id": "<generated-id-5>",+ "filename": "test_document.pdf",+ "content_type": "application/pdf",+ "byte_size": 452,+ "attached_to": "ticket",+ "parent_id": null,+ "url": "http://www.example.com/rails/active_storage/disk/<signed-key>/test_document.pdf",+ "created_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-6>",+ "filename": "test_file.txt",+ "content_type": "text/plain",+ "byte_size": 500,+ "attached_to": "post",+ "parent_id": "00000000-0000-4000-8000-000000000051",+ "url": "http://www.example.com/rails/active_storage/disk/<signed-key>/test_file.txt",+ "created_at": "2026-01-05T09:36:00Z"+ }+ ]+ }+ }+ },+ "ok_read_only": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/attachments"+ },+ "response": {+ "status": 200,+ "body": {+ "data": [+ {+ "id": "<generated-id-5>",+ "filename": "test_document.pdf",+ "content_type": "application/pdf",+ "byte_size": 452,+ "attached_to": "ticket",+ "parent_id": null,+ "url": "http://www.example.com/rails/active_storage/disk/<signed-key>/test_document.pdf",+ "created_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-6>",+ "filename": "test_file.txt",+ "content_type": "text/plain",+ "byte_size": 500,+ "attached_to": "post",+ "parent_id": "00000000-0000-4000-8000-000000000051",+ "url": "http://www.example.com/rails/active_storage/disk/<signed-key>/test_file.txt",+ "created_at": "2026-01-05T09:36:00Z"+ }+ ]+ }+ }+ },+ "empty": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000042/attachments"+ },+ "response": {+ "status": 200,+ "body": {+ "data": []+ }+ }+ },+ "not_found": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000999/attachments"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found"+ }+ }+ },+ "hidden": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000043/attachments"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found"+ }+ }+ }}}}diff --git a/spec/requests/api/v1/read_endpoints_spec.rb b/spec/requests/api/v1/read_endpoints_spec.rbindex 63781a4..20e75ff 100644--- a/spec/requests/api/v1/read_endpoints_spec.rb+++ b/spec/requests/api/v1/read_endpoints_spec.rb@@ -471,5 +471,43 @@ RSpec.describe 'API V1 Read Endpoints', type: :request doexpect(listed.first).to include('parent_id' => post_record.id, 'filename' => 'test_document.pdf')expect(listed.first['url']).to be_presentend++ # The URL is all a client needs to fetch the file: signed, no session. The+ # contract file records it with the signed segment replaced by a placeholder+ # (spec/contracts/mcp_contract_recorder.rb), so the real form is held here:+ # this instance's own host, Active Storage's Disk route (production runs the+ # Disk service), the file name last, nothing else.+ describe 'the signed URL' do+ include ActiveSupport::Testing::TimeHelpers++ let(:url) do+ ActsAsTenant.with_tenant(organisation) do+ create(:ticket_document, :with_pdf, ticket: ticket, organisation: organisation)+ end+ get "/api/v1/tickets/#{ticket.id}/attachments", headers: auth_headers+ URI.parse(JSON.parse(response.body)['data'].first['url'])+ end++ it 'points at the requesting host under the Disk route, the file name last' do+ expect([url.scheme, url.host, url.port, url.userinfo, url.query, url.fragment])+ .to eq(['http', 'www.example.com', 80, nil, nil, nil])+ expect(url.path).to match(%r{\A/rails/active_storage/disk/[^/]+/test_document\.pdf\z})+ end++ it 'serves the file to a request without any credential' do+ get url.path++ expect(response).to have_http_status(:ok)+ expect(response.body).to eq('%PDF-1.4 fake pdf content')+ end++ it 'stops serving it after five minutes' do+ path = url.path++ travel(5.minutes + 1.second) { get path }++ expect(response).to have_http_status(:not_found)+ end+ endendenddiff --git a/spec/requests/api/v1/ticket_attachments_privacy_spec.rb b/spec/requests/api/v1/ticket_attachments_privacy_spec.rbnew file mode 100644index 0000000..38d12cd--- /dev/null+++ b/spec/requests/api/v1/ticket_attachments_privacy_spec.rb@@ -0,0 +1,57 @@+# frozen_string_literal: true++require 'rails_helper'++# What: GET /api/v1/tickets/:id/attachments lists the file of a private comment+# only for the people Post.readable_by lets read that comment: its addressee,+# its author and an account admin. Another member of the same project gets the+# ticket's own file and a public comment's file from the same answer, so the+# missing entry is the filter at work, not an empty or failed list.+# Why: the rule is applied in Api::V1::TicketsController#collect_attachments,+# not in a serializer the service-level readers spec+# (spec/services/post_readers_follow_readable_by_spec.rb) can call. Each answer+# carries a signed download URL that needs no session, so a file listed here is+# a file handed out.+RSpec.describe 'API ticket attachments of private comments', :ci_guard, type: :request do+ let(:organisation) { create(:organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:author) { create(:user) }+ let(:addressee) { create(:user) }+ let(:stranger) { create(:user) }+ let(:admin) { create(:user) }+ let(:ticket) { create(:ticket, project: project, organisation: organisation, creator: author) }+ let(:public_comment) { create(:post, ticket: ticket, user: author, is_private: false) }+ let(:private_comment) { create(:post, ticket: ticket, user: author, is_private: true, visible_to_user: addressee) }++ before do+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ [author, addressee, stranger].each do |user|+ create(:membership, user: user, organisation: organisation)+ create(:project_permission, user: user, project: project, tickets_access: :read_write)+ end+ create(:membership, user: admin, organisation: organisation,+ role: Role.find_or_create_account_admin(organisation))+ create(:ticket_document, ticket: ticket, organisation: organisation)+ create(:post_document, post: public_comment, organisation: organisation)+ create(:post_document, post: private_comment, organisation: organisation)+ end+ end+ end++ def listed_for(user)+ token = Prosopite.pause { create(:personal_access_token, user: user, organisations: [organisation], read_only: true) }+ get "/api/v1/tickets/#{ticket.id}/attachments", headers: { 'Authorization' => "Bearer #{token.token}" }+ expect(response).to have_http_status(:ok)+ JSON.parse(response.body)['data'].map { |file| [file['attached_to'], file['parent_id']] }+ end++ { author: true, addressee: true, admin: true, stranger: false }.each do |reader, sees|+ it "#{sees ? 'lists' : 'leaves out'} the private comment's file for the #{reader}" do+ expected = [['ticket', nil], ['post', public_comment.id]]+ expected << ['post', private_comment.id] if sees++ expect(listed_for(public_send(reader))).to match_array(expected)+ end+ end+enddiff --git a/spec/services/post_readers_follow_readable_by_spec.rb b/spec/services/post_readers_follow_readable_by_spec.rbindex 01b2008..94ea179 100644--- a/spec/services/post_readers_follow_readable_by_spec.rb+++ b/spec/services/post_readers_follow_readable_by_spec.rb@@ -5,7 +5,9 @@ require 'rails_helper'# What: the readers that already filtered private comments (API ticket show and# attachments, MCP get_ticket through Tickets::Serializer, the assistant search# through CombinedSearchService) follow the same rule as the timeline:-# Post.readable_by.+# Post.readable_by. The attachments list applies the rule in its controller,+# so its examples are request specs:+# spec/requests/api/v1/ticket_attachments_privacy_spec.rb.# Why: they used Post.visible_to, which knows only the addressee. An author who# addressed a comment to someone else through the API lost it, and an account# admin saw private comments in the timeline but not in the API. One rule, one