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
refactor(api): read a token's organisations and projects in one place
Guido Boykefc6a0e63bd97
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex fa8667c..a306672 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -271,6 +271,7 @@ jobs:spec/requests/api/mcp_people_spec.rbspec/requests/api/mcp_idempotency_key_bound_spec.rbspec/services/mcp/idempotency_store_spec.rb+ spec/services/personal_access_tokens/reach_listing_spec.rbspec/services/posts/plain_text_body_spec.rbspec/services/lalabase/tools/post_comment_spec.rbspec/services/lalabase/tools/post_comment_failure_spec.rbdiff --git a/app/controllers/api/v1/organisations_controller.rb b/app/controllers/api/v1/organisations_controller.rbindex aeb9d52..b92c12d 100644--- a/app/controllers/api/v1/organisations_controller.rb+++ b/app/controllers/api/v1/organisations_controller.rb@@ -9,24 +9,10 @@ module Apiskip_after_action :verify_policy_scopeddef index- # The organisations the token reaches right now (PersonalAccessToken#organisation_scopes:- # token scope AND active membership, or every active membership for an all-organisations- # token), in the order of the org switcher (Organisation.by_name).- scopes = current_token.organisation_scopes.index_by(&:organisation_id)- organisations = Organisation.where(id: scopes.keys).by_name-- render json: { data: organisations.map { |org| serialize(org, scopes.fetch(org.id)) } }- end-- private-- def serialize(org, scope)- {- id: org.id,- name: org.name,- subdomain: org.subdomain,- scope: scope.all_projects? ? 'all_projects' : 'selected_projects'- }+ # The organisations the token reaches right now (token scope AND active+ # membership, or every active membership for an all-organisations token), in the+ # order of the org switcher. The reader is shared with the MCP tool list_organisations.+ render json: { data: PersonalAccessTokens::ReachListing.new(reach: current_token.reach).organisations }endendenddiff --git a/app/controllers/api/v1/projects_controller.rb b/app/controllers/api/v1/projects_controller.rbindex 686f3f0..6e69a96 100644--- a/app/controllers/api/v1/projects_controller.rb+++ b/app/controllers/api/v1/projects_controller.rb@@ -4,17 +4,18 @@ module Apimodule V1class ProjectsController < BaseControllerUUID_TYPE = ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Uuid.new- def index- scopes = applicable_scopes- # Empty scope list (e.g. organisation_id outside the token scope):- # there is no org in which policy_scope could run — deliberately mark the- # empty result as scoped instead of a tripwire error.- skip_policy_scope if scopes.empty?+ # Deliberate opt-out from the Pundit tripwire on index: PersonalAccessTokens::ReachListing+ # asks the policy scope per organisation itself, for the MCP tool list_projects as well.+ # The helper this tripwire watches is the one it must not use (it memoises per scope+ # object). Pinned in spec/services/personal_access_tokens/reach_listing_spec.rb.+ skip_after_action :verify_policy_scoped- all_projects = scopes.flat_map { |organisation, scope| projects_in_organisation(organisation, scope) }+ def index+ projects = PersonalAccessTokens::ReachListing.new(reach: current_token.reach)+ .projects(viewer: current_user, organisation_ids: organisation_ids)- render json: { data: all_projects.map { |p| serialize(p) } }+ render json: { data: projects }end# GET /api/v1/projects/:id/ticket_attribute_definitions@@ -33,44 +34,10 @@ module Apiprivate- # One organisation's projects for the token. Its own method so the per-organisation loop- # has a frame of its own in the Prosopite stack (allow-listed there, bounded by the- # organisations the token reaches, like aggregate_org_slice).- def projects_in_organisation(organisation, scope)- ActsAsTenant.with_tenant(organisation) do- # Controller helper instead of Pundit.policy_scope: identical scope class,- # but only the helper sets the tripwire's verify_policy_scoped flag.- # ⚠️ A relation of THIS organisation, never the bare class: the helper- # memoises per scope object, so `policy_scope(Project)` answered every- # organisation after the first with the first one's projects (until 2026-10-02).- scoped = policy_scope(Project.where(organisation_id: organisation.id))- scoped = scoped.where(id: current_token.linked_project_ids(scope.organisation_id)) unless scope.all_projects?- scoped.includes(:organisation).order(:name).to_a- end- end-- # [organisation, scope] pairs the token reaches right now- # (PersonalAccessToken#organisation_scopes), organisations by Organisation.by_name. With ?organisation_id=- # only that one, if reached; the id is normalised like ActiveRecord would (case, hyphens).- def applicable_scopes- scopes = current_token.organisation_scopes.index_by(&:organisation_id)- scopes = scopes.slice(UUID_TYPE.cast(params[:organisation_id].to_s)) if params[:organisation_id].present?- Organisation.where(id: scopes.keys).by_name.map { |org| [org, scopes.fetch(org.id)] }- end-- def serialize(project)- {- id: project.id,- name: project.name,- description: project.description,- archived: project.archived_at.present?,- organisation: {- id: project.organisation_id,- name: project.organisation&.name- },- created_at: project.created_at.iso8601,- updated_at: project.updated_at.iso8601- }+ # nil = every organisation in reach. The id is normalised like ActiveRecord would+ # (case, hyphens); one that cannot be a UUID casts to nil and matches nothing.+ def organisation_ids+ [UUID_TYPE.cast(params[:organisation_id].to_s)].compact if params[:organisation_id].present?enddef serialize_definition(definition)diff --git a/app/services/personal_access_tokens/reach_listing.rb b/app/services/personal_access_tokens/reach_listing.rbnew file mode 100644index 0000000..7dcbc52--- /dev/null+++ b/app/services/personal_access_tokens/reach_listing.rb@@ -0,0 +1,83 @@+# frozen_string_literal: true++# The organisations and projects a token reaches, as the rows an API client reads.+# One reader for both surfaces, so GET /api/v1/organisations, GET /api/v1/projects+# and the MCP tools list_organisations and list_projects cannot drift. What differs+# by surface stays with the surface: the MCP tools pick include_archived, page and+# cap the text; REST answers everything the token and its owner may see.+#+# A project shows up only when the token reaches it AND the policy scope lets its+# owner read it, so a listed id passes the project gate of the API and of MCP.+#+# Tenant-free: it runs before any tenant is set and sets one per organisation, the+# policy scope reads it. Asks Pundit directly, never the controller helper, which+# memoises per scope object and would answer every organisation with the first one's+# projects.+#+# Entry point: organisations, projects+module PersonalAccessTokens+ class ReachListing+ # @param reach [PersonalAccessToken::Reach]+ def initialize(reach:)+ @reach = reach+ end++ # @return [Array<Hash>] one row per organisation in reach, in the order of the+ # org switcher+ def organisations+ Organisation.where(id: @reach.organisation_ids).by_name.map { |organisation| organisation_row(organisation) }+ end++ # @param viewer [User] the token's owner+ # @param organisation_ids [Array<String>, nil] only these organisations; an id+ # outside the reach adds nothing. nil means every organisation in reach.+ # @param include_archived [Boolean] false leaves archived projects out; true shows+ # those the viewer may read, which is an admin's alone+ # @return [Array<Hash>] one row per project, by organisation, then by name+ def projects(viewer:, organisation_ids: nil, include_archived: true)+ ids = organisation_ids ? @reach.organisation_ids & organisation_ids : @reach.organisation_ids+ Organisation.where(id: ids).by_name.flat_map do |organisation|+ projects_in_organisation(organisation, viewer, include_archived).map { |project| project_row(project) }+ end+ end++ private++ # One organisation's projects. Its own method so the per-organisation loop has a+ # frame of its own in the Prosopite stack: spec/support/prosopite.rb allow-lists it+ # by this name, bounded by the organisations the token reaches.+ def projects_in_organisation(organisation, viewer, include_archived)+ ActsAsTenant.with_tenant(organisation) do+ relation = Project.where(organisation_id: organisation.id)+ relation = relation.active unless include_archived+ linked = @reach.project_ids_for(organisation.id)+ relation = relation.where(id: linked) if linked+ Pundit.policy_scope!(viewer, relation).includes(:organisation).order(:name).to_a+ end+ end++ def organisation_row(organisation)+ {+ id: organisation.id,+ name: organisation.name,+ subdomain: organisation.subdomain,+ scope: @reach.project_ids_for(organisation.id).nil? ? 'all_projects' : 'selected_projects'+ }+ end++ def project_row(project)+ {+ id: project.id,+ name: project.name,+ description: project.description,+ archived: project.archived_at.present?,+ organisation: {+ id: project.organisation_id,+ name: project.organisation&.name+ },+ created_at: project.created_at.iso8601,+ updated_at: project.updated_at.iso8601+ }+ end+ end+enddiff --git a/spec/services/personal_access_tokens/reach_listing_spec.rb b/spec/services/personal_access_tokens/reach_listing_spec.rbnew file mode 100644index 0000000..6cfc61b--- /dev/null+++ b/spec/services/personal_access_tokens/reach_listing_spec.rb@@ -0,0 +1,151 @@+# frozen_string_literal: true++require 'rails_helper'++# What: PersonalAccessTokens::ReachListing, the one read of a token's organisations+# and projects behind GET /api/v1/organisations, GET /api/v1/projects and the+# MCP tools list_organisations and list_projects.+# Type: Service spec.+# Why: The reach of a token stood by hand at several doors and went wrong there more+# than once. Three things must hold: the token AND the owner's rights decide; each+# organisation answers with its own projects (the controller helper memoised+# per scope object and answered the first one's for all); archived projects stay+# an admin's, whatever the caller asks for.+RSpec.describe PersonalAccessTokens::ReachListing, :ci_guard do+ let(:user) { create(:user) }+ let(:organisation) { create(:organisation, name: 'Beta') }+ let(:other_organisation) { create(:organisation, name: 'Alpha') }+ let(:outside_organisation) { create(:organisation, name: 'Outside') }++ def project_in(org, **attributes)+ ActsAsTenant.with_tenant(org) { create(:project, organisation: org, **attributes) }+ end++ def admin_in(org)+ ActsAsTenant.with_tenant(org) do+ Membership.find_by!(user: user, organisation: org).update!(role: create(:admin_role, organisation: org))+ end+ user.instance_variable_set(:@role_cache, nil)+ end++ def listing(token) = described_class.new(reach: token.reach)++ describe '#organisations' do+ before do+ make_token_owner_a_member(user, organisation)+ make_token_owner_a_member(user, other_organisation)+ end++ it 'names each organisation in reach, by name, with its scope' do+ project = project_in(organisation)+ token = create(:personal_access_token, user: user, organisations: [organisation, other_organisation],+ project_scopes: { organisation => [project] })++ expect(listing(token).organisations).to eq(+ [{ id: other_organisation.id, name: 'Alpha', subdomain: other_organisation.subdomain, scope: 'all_projects' },+ { id: organisation.id, name: 'Beta', subdomain: organisation.subdomain, scope: 'selected_projects' }]+ )+ end++ it 'leaves out an organisation whose membership was deactivated' do+ token = create(:personal_access_token, user: user, organisations: [organisation, other_organisation])+ Membership.find_by!(user: user, organisation: organisation).update!(active: false)++ expect(listing(token).organisations.pluck(:id)).to eq([other_organisation.id])+ end++ it 'covers every membership for an all-organisations token, which has no link rows' do+ token = create(:personal_access_token, :all_organisations, user: user)++ expect(listing(token).organisations.pluck(:name)).to eq(%w[Alpha Beta])+ end+ end++ describe '#projects' do+ let(:zeta) { project_in(organisation, name: 'Zeta') }+ let(:eta) { project_in(organisation, name: 'Eta') }+ let(:foreign) { project_in(other_organisation, name: 'Foreign') }++ # Paused: the grants repeat their lookups per project, which is the setup and not the read.+ before do+ Prosopite.pause do+ make_token_owner_a_member(user, organisation, projects: [zeta, eta])+ make_token_owner_a_member(user, other_organisation, projects: [foreign])+ end+ end++ it 'answers each organisation with its own projects, by organisation, then by name' do+ token = create(:personal_access_token, user: user, organisations: [organisation, other_organisation])++ expect(listing(token).projects(viewer: user).pluck(:name)).to eq(%w[Foreign Eta Zeta])+ end++ it 'carries the row of the API' do+ token = create(:personal_access_token, user: user, organisations: [other_organisation])++ expect(listing(token).projects(viewer: user)).to eq(+ [{ id: foreign.id, name: 'Foreign', description: foreign.description, archived: false,+ organisation: { id: other_organisation.id, name: 'Alpha' },+ created_at: foreign.created_at.iso8601, updated_at: foreign.updated_at.iso8601 }]+ )+ end++ it 'keeps to the projects a limited token is linked to' do+ token = create(:personal_access_token, user: user, organisations: [organisation],+ project_scopes: { organisation => [eta] })++ expect(listing(token).projects(viewer: user).pluck(:id)).to eq([eta.id])+ end++ it 'keeps to the projects the owner may read, even with an all-projects token' do+ unreadable = project_in(organisation, name: 'Unreadable')+ token = create(:personal_access_token, user: user, organisations: [organisation])++ expect(listing(token).projects(viewer: user).pluck(:id)).not_to include(unreadable.id)+ end++ it 'narrows to the organisations asked for, and an id outside the reach adds nothing' do+ token = create(:personal_access_token, user: user, organisations: [organisation])+ project_in(outside_organisation)++ expect(listing(token).projects(viewer: user, organisation_ids: [organisation.id]).pluck(:name)).to eq(%w[Eta Zeta])+ expect(listing(token).projects(viewer: user, organisation_ids: [outside_organisation.id])).to eq([])+ expect(listing(token).projects(viewer: user, organisation_ids: [])).to eq([])+ end++ it 'answers an empty list to a member without a project' do+ stranger = create(:user)+ make_token_owner_a_member(stranger, organisation)+ token = create(:personal_access_token, user: stranger, organisations: [organisation])++ expect(listing(token).projects(viewer: stranger)).to eq([])+ end++ it 'leaves no tenant behind' do+ token = create(:personal_access_token, user: user, organisations: [organisation])++ listing(token).projects(viewer: user)++ expect(ActsAsTenant.current_tenant).to be_nil+ end++ context 'with an archived project' do+ let!(:archived) { project_in(organisation, name: 'Archived', archived_at: 1.day.ago) }++ it 'shows it to an admin unless it is left out, and marks it' do+ admin_in(organisation)+ token = create(:personal_access_token, user: user, organisations: [organisation])++ rows = listing(token).projects(viewer: user)+ expect(rows.find { |row| row[:id] == archived.id }).to include(archived: true)+ expect(listing(token).projects(viewer: user, include_archived: false).pluck(:id)).not_to include(archived.id)+ end++ it 'never shows it to anybody else, whatever the caller asks for' do+ token = create(:personal_access_token, user: user, organisations: [organisation])++ expect(listing(token).projects(viewer: user, include_archived: true).pluck(:id)).not_to include(archived.id)+ end+ end+ end+enddiff --git a/spec/support/prosopite.rb b/spec/support/prosopite.rbindex b310d19..98ec45f 100644--- a/spec/support/prosopite.rb+++ b/spec/support/prosopite.rb@@ -89,7 +89,7 @@ Prosopite.allow_stack_paths = ['from_attachable_sgid', # ActionText: one Blob.find per <action-text-attachment sgid> when a rich text with images is saved or rendered (GlobalID::Locator.locate_signed, ActionText's own embeds sync in before_save does the same). Bounded by the images in ONE text, inherent to ActionText, not a per-record N+1 of our code; the cost per screenshot is the Paket-2 measurement of doc/inline_bilder_spike_plan.md (E2). RichTextEmbedGuard's own queries stay under watch'db/seeds/demo', # db/seeds/demo.rb: five demo tickets saved one by one through Actors::SaveTicket, each with its own assignment sync, as a real user would create them. Bounded by DemoSeed::TICKETS, run from db:seed in development only, never in a request. Surfaces only in spec/db/seeds_spec.rb'db/seeds/prompt_personas', # db/seeds/prompt_personas.rb: one find_or_initialize_by per seeded persona (bounded by the entries in GLOBAL_PROMPT_PERSONAS, four today), run from db:seed or a rails runner, never in a request. Surfaces only in spec/db/seeds/prompt_personas_spec.rb, which loads the file on purpose- 'projects_in_organisation', # Api::V1::ProjectsController#index: one policy-scoped project read per ORGANISATION the token reaches (PersonalAccessToken#organisation_scopes), bounded by that handful, the per-tenant loop of aggregate_org_slice. Hidden until 2026-10-02 by Pundit memoising policy_scope(Project) per class, which also answered every organisation with the first one's projects+ 'projects_in_organisation', # PersonalAccessTokens::ReachListing#projects: one policy-scoped project read per ORGANISATION the token reaches (PersonalAccessToken#organisation_scopes), bounded by that handful, the per-tenant loop of aggregate_org_slice. Hidden until 2026-10-02 by Pundit memoising policy_scope(Project) per class, which also answered every organisation with the first one's projects'inbox_query_readable_rows', # Notifications::InboxQuery: the AREA resolution behind Notification.readable (one per area the mapping names, plus any area) for ONE organisation of a token's reach. Same bounded per-organisation loop as inbox_query_current_access below: for a role with rights in all projects it is one exclusion read (ProjectAccessService.find_excluded_project_ids_for_area) per area and organisation, bounded by the organisations the TOKEN names. Pinned: area_rights_spec.rb, the token inbox over organisations'open_hours_in_organisation', # TimeSessions::OpenHours (GET /api/v1/time_sessions/open): one ViewingScope resolution per ORGANISATION in a token's reach (active membership, admin check, ONE read of the time permission rows), to narrow that organisation's own bookings the way TimeSessionPolicy::Scope does. ViewingScope answers per organisation by construction, so the loop is mandatory; it is bounded by the organisations the TOKEN names, not by any record count. A frame of its own for the same reason as inbox_query_current_access below'readable_open_hour_tickets', # TimeSessions::OpenHours: one TicketPolicy::Scope resolution plus one pluck per ORGANISATION that has a ticket on the current page (at most the organisations of the token, and at most per_page rows), the tickets the person may read. The policy scope takes one organisation as its tenant, so the loop is mandatory; a check per ROW would be the real N+1 (time_sessions_open_access_spec.rb pins it)