From b198dba4ad953746d1e10050f66325d8d3846d88 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 11:25:45 -0500 Subject: [PATCH 1/9] feat: add patches with per-patch roles, app links and a patches claim --- .../admin/oauth_applications_controller.rb | 2 +- app/controllers/admin/patches_controller.rb | 69 +++++++++++ app/helpers/admin_nav_helper.rb | 1 + .../concerns/oauth_application_patch_link.rb | 19 +++ app/models/patch.rb | 73 ++++++++++++ app/serializers/directory_user_serializer.rb | 10 +- app/services/patch_roles.rb | 37 ++++++ app/services/role_registry.rb | 6 +- .../oauth_applications/_patch_field.html.erb | 9 ++ .../admin/oauth_applications/edit.html.erb | 4 +- .../admin/oauth_applications/new.html.erb | 5 +- .../admin/oauth_applications/show.html.erb | 8 ++ app/views/admin/patches/_form.html.erb | 34 ++++++ app/views/admin/patches/edit.html.erb | 12 ++ app/views/admin/patches/index.html.erb | 45 +++++++ app/views/admin/patches/new.html.erb | 7 ++ app/views/admin/patches/show.html.erb | 110 ++++++++++++++++++ app/views/admin/users/_roles.html.erb | 5 +- app/views/identity/governance/show.html.erb | 4 +- config/initializers/doorkeeper.rb | 11 +- .../initializers/doorkeeper_openid_connect.rb | 8 ++ .../oauth_application_public_id.rb | 2 + config/roles.yml | 20 ++++ config/routes.rb | 4 + db/migrate/20261112120000_create_patches.rb | 62 ++++++++++ ...2120100_add_patch_to_oauth_applications.rb | 14 +++ db/schema.rb | 37 +++++- db/seeds.rb | 3 + docs/KYC.md | 6 +- docs/OAUTH.md | 44 ++++++- lib/tasks/patches.rake | 14 +++ spec/factories/patches.rb | 8 ++ spec/models/patch_spec.rb | 63 ++++++++++ spec/requests/admin_nav_spec.rb | 4 +- .../admin_oauth_application_patch_spec.rb | 58 +++++++++ spec/requests/admin_patches_spec.rb | 89 ++++++++++++++ spec/requests/api/directory_spec.rb | 10 ++ spec/requests/oauth/introspection_spec.rb | 23 ++++ spec/requests/oauth/openid_connect_spec.rb | 46 +++++++- spec/requests/roles_spec.rb | 36 +++++- spec/services/patch_roles_spec.rb | 59 ++++++++++ spec/services/role_registry_spec.rb | 26 ++++- 42 files changed, 1084 insertions(+), 23 deletions(-) create mode 100644 app/controllers/admin/patches_controller.rb create mode 100644 app/models/concerns/oauth_application_patch_link.rb create mode 100644 app/models/patch.rb create mode 100644 app/services/patch_roles.rb create mode 100644 app/views/admin/oauth_applications/_patch_field.html.erb create mode 100644 app/views/admin/patches/_form.html.erb create mode 100644 app/views/admin/patches/edit.html.erb create mode 100644 app/views/admin/patches/index.html.erb create mode 100644 app/views/admin/patches/new.html.erb create mode 100644 app/views/admin/patches/show.html.erb create mode 100644 db/migrate/20261112120000_create_patches.rb create mode 100644 db/migrate/20261112120100_add_patch_to_oauth_applications.rb create mode 100644 lib/tasks/patches.rake create mode 100644 spec/factories/patches.rb create mode 100644 spec/models/patch_spec.rb create mode 100644 spec/requests/admin_oauth_application_patch_spec.rb create mode 100644 spec/requests/admin_patches_spec.rb create mode 100644 spec/services/patch_roles_spec.rb diff --git a/app/controllers/admin/oauth_applications_controller.rb b/app/controllers/admin/oauth_applications_controller.rb index d2aabc01..cc725bc3 100644 --- a/app/controllers/admin/oauth_applications_controller.rb +++ b/app/controllers/admin/oauth_applications_controller.rb @@ -203,7 +203,7 @@ def set_application end def application_params - params.require(:doorkeeper_application).permit(:name, :redirect_uri, :scopes, :confidential, + params.require(:doorkeeper_application).permit(:name, :redirect_uri, :scopes, :confidential, :patch_id, :show_in_launcher, :launch_url, :launcher_icon_url, :launcher_description) end diff --git a/app/controllers/admin/patches_controller.rb b/app/controllers/admin/patches_controller.rb new file mode 100644 index 00000000..7c9fd253 --- /dev/null +++ b/app/controllers/admin/patches_controller.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +# Patches in the admin panel (see Patch). +# +# Any admin may look at patches. Only a superadmin may create a patch or +# change its name and description, like groups. The slug never changes, and +# there is no delete: role assignments, Quilt and app tokens name the slug. +# +# The show page lists the apps linked to the patch and the people with a patch +# role. Grant and revoke a patch role on the user's admin page (see +# Admin::RoleAssignmentsController). +class Admin::PatchesController < Admin::BaseController + before_action :set_patch, only: [:show, :edit, :update] + before_action :require_superadmin, except: [:index, :show] + + def index + @patches = Patch.order(:name) + @application_counts = Doorkeeper::Application.where.not(patch_id: nil).group(:patch_id).count + end + + def show + @applications = @patch.applications.order(:name) + @assignments = PatchRoles::NAMES.keys.index_with do |key| + RoleGrants.assignments(key).where(scope: @patch.slug).includes(:granted_by).to_a + end + end + + def new + @patch = Patch.new + end + + def create + @patch = Patch.new(patch_params.merge(created_by: current_user)) + + if @patch.save + redirect_to admin_patch_path(@patch), notice: "The patch was created." + else + render :new, status: :unprocessable_content + end + end + + def edit + end + + def update + if @patch.update(patch_params.except(:slug)) + redirect_to admin_patch_path(@patch), notice: "The patch was updated." + else + render :edit, status: :unprocessable_content + end + end + + private + + def set_patch + @patch = Patch.find_by!(slug: params[:id]) + end + + def patch_params + params.require(:patch).permit(:name, :slug, :description) + end + + def require_superadmin + return if current_user.superadmin? + + redirect_to admin_patches_path, alert: "Only a superadmin can change patches." + end + +end diff --git a/app/helpers/admin_nav_helper.rb b/app/helpers/admin_nav_helper.rb index 661538a7..66200a11 100644 --- a/app/helpers/admin_nav_helper.rb +++ b/app/helpers/admin_nav_helper.rb @@ -56,6 +56,7 @@ def admin_nav_groups(user = current_user) %w[role_assignments], :admin) end), (admin_nav_entry("Groups", admin_groups_path, :users_round, "admin teams", %w[groups group_memberships], :admin) if admin), + (admin_nav_entry("Patches", admin_patches_path, :rocket, "admin grant programs ganymede quilt", %w[patches], :admin) if admin), (if admin admin_nav_entry("Consents", admin_guardian_consents_path, :shield_check, "admin guardian minors review queue", %w[guardian_consents], :admin) diff --git a/app/models/concerns/oauth_application_patch_link.rb b/app/models/concerns/oauth_application_patch_link.rb new file mode 100644 index 00000000..a28a483b --- /dev/null +++ b/app/models/concerns/oauth_application_patch_link.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +# The patch an OAuth app belongs to, if any (see Patch). Included into +# Doorkeeper::Application by config/initializers/oauth_application_public_id.rb. +# +# Introspection of the app's client_credentials tokens names the patch slug as +# `patch` (see config/initializers/doorkeeper.rb), so a resource server such as +# Quilt can tell which patch the calling app belongs to. +module OauthApplicationPatchLink + extend ActiveSupport::Concern + + included do + belongs_to :patch, optional: true, inverse_of: :applications + + # A patch_id that names no patch is a form error, not a foreign key error. + validates :patch, presence: { message: "must be a patch that exists" }, if: :patch_id? + end + +end diff --git a/app/models/patch.rb b/app/models/patch.rb new file mode 100644 index 00000000..d99411ab --- /dev/null +++ b/app/models/patch.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +# One patch: a grant program of Patchwork Labs, for example Project Ganymede. +# +# The slug is the stable name that apps see. It is the program key in +# config/kyc/knot.yml and the patch slug in Quilt, so it never changes after +# the patch is created: the model refuses the change, and a database trigger +# refuses it too. Renaming a patch changes only its display name. +# +# A patch has per-patch roles (patch_lead, patch_viewer in config/roles.yml), +# scoped by the slug, and OAuth apps linked to it (oauth_applications.patch_id). +# The `patches` claim sends a person's patch roles to apps (see PatchRoles). +# +# There is no delete: role assignments, Quilt and app tokens name the slug. +# == Schema Information +# +# Table name: patches +# Database name: primary +# +# id :bigint not null, primary key +# description :text +# name :string not null +# slug :string not null +# created_at :datetime not null +# updated_at :datetime not null +# created_by_id :bigint +# +# Indexes +# +# index_patches_on_created_by_id (created_by_id) +# index_patches_on_slug (slug) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# +class Patch < ApplicationRecord + include EncodedIds::HashidIdentifiable + set_public_id_prefix :ptch + + has_paper_trail + + SLUG_FORMAT = /\A[a-z0-9]+(-[a-z0-9]+)*\z/ + + belongs_to :created_by, class_name: "User", optional: true + has_many :applications, class_name: "Doorkeeper::Application", inverse_of: :patch, dependent: :restrict_with_exception + + validates :name, presence: true, length: { maximum: 100 } + validates :description, length: { maximum: 2000 } + validates :slug, presence: true, length: { maximum: 64 }, format: { with: SLUG_FORMAT }, uniqueness: true + validate :slug_unchanged, on: :update + + def to_param = slug + + # Creates a patch for each program in config/kyc/knot.yml, named as the + # program. Idempotent. Never renames or removes a patch. + # + # model: the ActiveRecord class of the patches table (a migration passes + # its own). + def self.sync_programs!(model: self) + KnotSettings.programs.each do |program| + model.find_or_create_by!(slug: program.key) { |patch| patch.name = program.name } + end + model.where(slug: KnotSettings.program_keys).order(:slug).to_a + end + + private + + def slug_unchanged + errors.add(:slug, "can't be changed after the patch is created") if slug_changed? + end + +end diff --git a/app/serializers/directory_user_serializer.rb b/app/serializers/directory_user_serializer.rb index e481e849..24b19330 100644 --- a/app/serializers/directory_user_serializer.rb +++ b/app/serializers/directory_user_serializer.rb @@ -45,7 +45,7 @@ def as_json(*) # The member saved demographics answers. Never the answers themselves. # Krater asks for it before a member's first grant application. demographics_answered: DemographicsVault.answered?(@user) - }.merge(age_fields) + }.merge(age_fields).merge(patch_fields) end private @@ -58,4 +58,12 @@ def age_fields { age_band: @user.age_band }.compact end + # Only for an app allowed the patches scope, like the patches claim. Quilt + # checks a person's patch roles again before an action (see PatchRoles). + def patch_fields + return {} unless @application.scopes.exists?("patches") + + { patches: PatchRoles.for(@user) } + end + end diff --git a/app/services/patch_roles.rb b/app/services/patch_roles.rb new file mode 100644 index 00000000..3b297449 --- /dev/null +++ b/app/services/patch_roles.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +# A person's roles for each patch, as apps see them in the `patches` claim and +# in the directory API (see docs/OAUTH.md "Patch claims"). +# +# This is the contract with Quilt and the other patch apps. Keep the shape: +# a JSON object that maps a patch slug to the sorted list of short role names +# the person actively holds for that patch, for example +# +# {"ganymede": ["lead"], "europa": ["viewer"]} +# +# - The keys are patch slugs, sorted. Only patches that exist are listed. +# - A revoked role is left out. +# - An empty object ({}) when the person holds no patch role. +module PatchRoles + # The role key in config/roles.yml => its short name in the claim. Add a + # new per-patch role here, or apps never see it. + NAMES = { + "patch_lead" => "lead", + "patch_viewer" => "viewer" + }.freeze + + # The claim value for one user. + def self.for(user) + return {} if user.nil? + + held = user.active_user_roles.select { |assignment| NAMES.key?(assignment.role.key) && assignment.scope.present? } + return {} if held.empty? + + existing = Patch.where(slug: held.map(&:scope).uniq).pluck(:slug).to_set + held.select { |assignment| existing.include?(assignment.scope) } + .group_by(&:scope) + .sort_by(&:first) + .to_h { |slug, assignments| [slug, assignments.map { |assignment| NAMES.fetch(assignment.role.key) }.uniq.sort] } + end + +end diff --git a/app/services/role_registry.rb b/app/services/role_registry.rb index 8a491e3a..e2c170f1 100644 --- a/app/services/role_registry.rb +++ b/app/services/role_registry.rb @@ -19,10 +19,10 @@ class ConfigError < StandardError; end RULES = (PROPOSAL_RULES + IMMEDIATE_RULES).freeze PRECONDITIONS = %w[verified_by_another verified_or_bootstrap adult].freeze - SCOPE_SOURCES = %w[knot_programs].freeze + SCOPE_SOURCES = %w[knot_programs patches].freeze # Code reads these roles by key, so the config must define each of them. - REQUIRED_KEYS = %w[verifier identity_lead key_holder board staff contractor patch_lead].freeze + REQUIRED_KEYS = %w[verifier identity_lead key_holder board staff contractor patch_lead patch_viewer].freeze ROLE_KEYS = %w[name description scopable scope_source requires grant revoke].freeze RULE_KEYS = %w[rule preconditions_at_proposal preconditions_at_approval].freeze @@ -60,6 +60,8 @@ def scopes_for(key) case definition.scope_source when "knot_programs" then KnotSettings.program_keys + # Read from the database each time: an admin can add a patch. + when "patches" then Patch.order(:slug).pluck(:slug) else [] end end diff --git a/app/views/admin/oauth_applications/_patch_field.html.erb b/app/views/admin/oauth_applications/_patch_field.html.erb new file mode 100644 index 00000000..b58ce5a9 --- /dev/null +++ b/app/views/admin/oauth_applications/_patch_field.html.erb @@ -0,0 +1,9 @@ +<%# The patch the app belongs to (see OauthApplicationPatchLink). %> +
+ <%= form.label :patch_id, class: "field-label" do %>Patch (optional)<% end %> + <%= form.select :patch_id, Patch.order(:name).map { |patch| ["#{patch.name} (#{patch.slug})", patch.id] }, + { include_blank: "No patch" }, class: "field", aria: { describedby: "application-patch-hint" } %> +

+ The patch this app belongs to. Introspection of the app's own tokens names it as patch, so Quilt knows the patch of the calling app. +

+
diff --git a/app/views/admin/oauth_applications/edit.html.erb b/app/views/admin/oauth_applications/edit.html.erb index 2909a5ed..a0240d81 100644 --- a/app/views/admin/oauth_applications/edit.html.erb +++ b/app/views/admin/oauth_applications/edit.html.erb @@ -31,7 +31,7 @@ <%= form.label :scopes, class: "field-label" %> <%= form.text_field :scopes, class: "field", placeholder: "profile email" %>

- Space-separated list of scopes. Available: profile, email, admin, slack, groups, roles, social. + Space-separated list of scopes. Available: profile, email, admin, slack, groups, roles, social, patches. App tokens only: directory, fulfillment, quilt, stash, introspect (superadmin only). Leave empty to use defaults.

@@ -48,6 +48,8 @@ + <%= render "patch_field", form: form %> + <%= render "launcher_fields", form: form %>
diff --git a/app/views/admin/oauth_applications/new.html.erb b/app/views/admin/oauth_applications/new.html.erb index 9bf8325e..a175ac40 100644 --- a/app/views/admin/oauth_applications/new.html.erb +++ b/app/views/admin/oauth_applications/new.html.erb @@ -34,7 +34,8 @@ slack (Slack membership and Slack ID), groups (the user's groups that are linked to this app), roles (the user's roles in this app), - social (the accounts the user linked, for example GitHub). + social (the accounts the user linked, for example GitHub), + patches (the user's roles for each patch). App tokens only (client_credentials): directory (the directory API), fulfillment (read a shipping address to print a label), @@ -56,6 +57,8 @@ + <%= render "patch_field", form: form %> + <%= render "launcher_fields", form: form %>
diff --git a/app/views/admin/oauth_applications/show.html.erb b/app/views/admin/oauth_applications/show.html.erb index 85ad6df1..242d770c 100644 --- a/app/views/admin/oauth_applications/show.html.erb +++ b/app/views/admin/oauth_applications/show.html.erb @@ -52,6 +52,14 @@ Using default scopes: profile <% end %> <% end %> + <%= dl_row("Patch") do %> + <% if @application.patch %> + <%= link_to @application.patch.name, admin_patch_path(@application.patch), class: "link" %> + (<%= @application.patch.slug %>) + <% else %> + None + <% end %> + <% end %> <%= dl_row("Launcher") do %> <% if @application.show_in_launcher && @application.launch_url.present? %> <%= badge "Shown", tone: :success %> diff --git a/app/views/admin/patches/_form.html.erb b/app/views/admin/patches/_form.html.erb new file mode 100644 index 00000000..66b0df71 --- /dev/null +++ b/app/views/admin/patches/_form.html.erb @@ -0,0 +1,34 @@ +<%= form_with model: [:admin, patch], local: true, class: "card" do |form| %> +
+ <%= form_errors(patch) %> + +
+ <%= form.label :name, class: "field-label" %> + <%= form.text_field :name, class: "field", placeholder: "Project Ganymede" %> +
+ +
+ <%= form.label :slug, class: "field-label" %> + <% if patch.persisted? %> + <%= patch.slug %> +

The slug can't be changed after the patch is created.

+ <% else %> + <%= form.text_field :slug, class: "field", placeholder: "ganymede", aria: { describedby: "patch-slug-hint" } %> +

+ Lowercase letters, numbers and dashes. Apps and Quilt see this name. Use the same slug as in Quilt. + You can't change it later. +

+ <% end %> +
+ +
+ <%= form.label :description, class: "field-label" do %>Description (optional)<% end %> + <%= form.text_area :description, rows: 3, class: "field" %> +
+ +
+ <%= link_to "Cancel", patch.persisted? ? admin_patch_path(patch) : admin_patches_path, class: "btn btn-secondary" %> + <%= form.submit patch.persisted? ? "Save patch" : "Create patch", class: "btn btn-primary" %> +
+
+<% end %> diff --git a/app/views/admin/patches/edit.html.erb b/app/views/admin/patches/edit.html.erb new file mode 100644 index 00000000..633b19f5 --- /dev/null +++ b/app/views/admin/patches/edit.html.erb @@ -0,0 +1,12 @@ +<% content_for :title, "Edit #{@patch.name}" %> + +
+ + + <%= render "form", patch: @patch %> +
diff --git a/app/views/admin/patches/index.html.erb b/app/views/admin/patches/index.html.erb new file mode 100644 index 00000000..f6d7f901 --- /dev/null +++ b/app/views/admin/patches/index.html.erb @@ -0,0 +1,45 @@ +<% content_for :title, "Patches" %> + +<%= page_header("Patches", lede: "The grant programs. Each patch has its own leads and viewers, and the apps that belong to it.") do %> + <% if current_user.superadmin? %> + <%= link_to new_admin_patch_path, class: "btn btn-primary" do %><%= icon(:plus) %>New patch<% end %> + <% end %> +<% end %> + +
+
+

All patches

+
+ + <% if @patches.any? %> +
+ + + + + + + + + + + <% @patches.each do |patch| %> + + + + + + + <% end %> + +
NameSlugAppsCreated
+ <%= link_to patch.name, admin_patch_path(patch), class: "link-quiet font-medium" %> + <% if patch.description.present? %> + <%= patch.description %> + <% end %> + <%= patch.slug %><%= @application_counts.fetch(patch.id, 0) %><%= time_label(patch.created_at, :relative) %>
+
+ <% else %> + <%= empty_state("No patches yet", body: "Run bin/rails patches:sync to create the patches of config/kyc/knot.yml, or create one here.", icon: :rocket) %> + <% end %> +
diff --git a/app/views/admin/patches/new.html.erb b/app/views/admin/patches/new.html.erb new file mode 100644 index 00000000..a2980a91 --- /dev/null +++ b/app/views/admin/patches/new.html.erb @@ -0,0 +1,7 @@ +<% content_for :title, "New patch" %> + +
+ <%= page_header("New patch", lede: "A grant program, such as Project Ganymede. Apps and people get roles for each patch.") %> + + <%= render "form", patch: @patch %> +
diff --git a/app/views/admin/patches/show.html.erb b/app/views/admin/patches/show.html.erb new file mode 100644 index 00000000..a4670bda --- /dev/null +++ b/app/views/admin/patches/show.html.erb @@ -0,0 +1,110 @@ +<% content_for :title, @patch.name %> + + + +
+
+
+

Details

+
+
+
+ <%= dl_row("Slug") { tag.span(@patch.slug, class: "mono") } %> + <% if @patch.description.present? %> + <%= dl_row "Description", @patch.description %> + <% end %> + <%= dl_row("Created") do %> + <%= time_label(@patch.created_at) %> + <% if @patch.created_by %>by <%= @patch.created_by.full_name %><% end %> + <% end %> +
+

+ Apps that ask for the patches scope get each person's roles for this patch. +

+
+
+ +
+
+
+
+
+

People

+ <%= badge(@assignments.values.sum(&:size).to_s) %> +
+

Grant or revoke a patch role in the roles section of the user's admin page.

+
+
+ <% if @assignments.values.any?(&:any?) %> +
+
    + <% @assignments.each do |key, assignments| %> + <% definition = RoleRegistry.fetch(key) %> + <% assignments.each do |assignment| %> + <% user = assignment.user %> +
  • +
    +

    + <% if user %> + <%= link_to user.full_name, admin_user_path(user, anchor: "roles"), class: "link-quiet" %> + (<%= user.p_id %>) + <% else %> + A deleted user + <% end %> +

    +

    + Since <%= time_label(assignment.granted_at) %>. + Granted by <%= assignment.granted_by&.full_name || "Weave" %>. +

    +
    + <%= badge(definition.name, tone: key == "patch_lead" ? :info : :neutral) %> +
  • + <% end %> + <% end %> +
+
+ <% else %> + <%= empty_state("Nobody has a role for this patch.", icon: :user_round) %> + <% end %> +
+ +
+
+
+
+

Apps

+ <%= badge(@applications.size.to_s) %> +
+

OAuth apps that belong to this patch. Set the patch on the app's edit page.

+
+
+ <% if @applications.any? %> +
+
    + <% @applications.each do |application| %> +
  • +
    +

    <%= link_to application.name, admin_oauth_application_path(application), class: "link-quiet" %>

    +

    <%= application.uid %>

    +
    +
  • + <% end %> +
+
+ <% else %> + <%= empty_state("No app belongs to this patch.", icon: :app_window) %> + <% end %> +
+
+
diff --git a/app/views/admin/users/_roles.html.erb b/app/views/admin/users/_roles.html.erb index 35d24dd9..5218bc92 100644 --- a/app/views/admin/users/_roles.html.erb +++ b/app/views/admin/users/_roles.html.erb @@ -46,14 +46,15 @@ <% end %> <% end %> - <% if !held || definition.scopable? %> + <% open_scopes = definition.scopable? ? RoleRegistry.scopes_for(definition.key) - scopes : [] %> + <% if definition.scopable? ? open_scopes.any? : !held %> <% if RoleGrants.allowed_now?(current_user, user, definition.key, :grant) %> <%= form_with url: admin_role_assignments_path, method: :post, class: "flex flex-col sm:flex-row gap-2" do |form| %> <%= form.hidden_field :user_id, value: user.p_id %> <%= form.hidden_field :role, value: definition.key %> <%= form.hidden_field :return_to, value: "user" %> <% if definition.scopable? %> - <%= form.select :scope, RoleRegistry.scopes_for(definition.key) - scopes, {}, class: "field field-sm sm:w-48", + <%= form.select :scope, open_scopes, {}, class: "field field-sm sm:w-48", aria: { label: "Scope of #{definition.name}" } %> <% end %> <%= form.text_field :reason, placeholder: "Reason (optional)", diff --git a/app/views/identity/governance/show.html.erb b/app/views/identity/governance/show.html.erb index cf536d4d..52f03550 100644 --- a/app/views/identity/governance/show.html.erb +++ b/app/views/identity/governance/show.html.erb @@ -59,7 +59,7 @@

Each role, who has it, and its grant rule. Staff and contractor change on the <%= link_to "staff and contractors page", admin_role_assignments_path, class: "link" %>, - and board member and the removal of a patch lead on the roles section of a user's admin page. + and board member, patch viewer and the removal of a patch lead on the roles section of a user's admin page.

@@ -69,7 +69,7 @@ <% assignments = @role_assignments.fetch(definition.key, []) %>
  • - <%= definition.name %><%= " (scoped by program)" if definition.scopable? %> + <%= definition.name %><%= " (scoped by patch)" if definition.scopable? %> Grant: <%= RoleGrants.rule_text(definition.key, :grant) %> Revoke: <%= RoleGrants.rule_text(definition.key, :revoke) %>

    diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb index e11b0689..355edd4f 100644 --- a/config/initializers/doorkeeper.rb +++ b/config/initializers/doorkeeper.rb @@ -299,7 +299,7 @@ # - `introspect`: introspect the `client_credentials` tokens of other apps # (see `allow_token_introspection` below). Only a superadmin may allow it # on an app (see Admin::OauthApplicationsController). - user_scopes = %i[profile openid email phone admin slack groups roles verification residency age social] + user_scopes = %i[profile openid email phone admin slack groups roles verification residency age social patches] app_scopes = %i[directory fulfillment quilt stash introspect] default_scopes :profile @@ -405,6 +405,15 @@ # or # # custom_introspection_response CustomIntrospectionResponder + # + # Weave adds `patch`: the slug of the patch the token's app belongs to (see + # OauthApplicationPatchLink), for an app token (client_credentials, no + # user) of an app linked to a patch. A resource server such as Quilt reads + # it to tell which patch the calling app belongs to. Left out otherwise. + custom_introspection_response do |token, _context| + slug = token.resource_owner_id.nil? ? token.application&.patch&.slug : nil + slug ? { patch: slug } : {} + end # Specify what grant flows are enabled in array of Strings. The valid # strings and the flows they enable are: diff --git a/config/initializers/doorkeeper_openid_connect.rb b/config/initializers/doorkeeper_openid_connect.rb index bd28c6fb..3c4b45ab 100644 --- a/config/initializers/doorkeeper_openid_connect.rb +++ b/config/initializers/doorkeeper_openid_connect.rb @@ -239,5 +239,13 @@ def test_key normal_claim :social_profiles, scope: :social, response: [:id_token, :user_info] do |user| user.social_profiles.order(:provider).map { |profile| { provider: profile.provider, id: profile.uid, username: profile.username } } end + + # The user's roles for each patch (see PatchRoles): a JSON object that + # maps a patch slug to the sorted short role names, for example + # {"ganymede": ["lead"]}. An empty object when none. Quilt depends on this + # shape: keep it. + normal_claim :patches, scope: :patches, response: [:id_token, :user_info] do |user| + PatchRoles.for(user) + end end end diff --git a/config/initializers/oauth_application_public_id.rb b/config/initializers/oauth_application_public_id.rb index 200380a3..a88b71c0 100644 --- a/config/initializers/oauth_application_public_id.rb +++ b/config/initializers/oauth_application_public_id.rb @@ -9,4 +9,6 @@ Doorkeeper::Application.set_public_id_prefix :app # The app launcher and access requests (see OauthApplicationLauncher). Doorkeeper::Application.include OauthApplicationLauncher + # The patch the app belongs to (see OauthApplicationPatchLink). + Doorkeeper::Application.include OauthApplicationPatchLink end diff --git a/config/roles.yml b/config/roles.yml index 4f6f28b3..2c4fc622 100644 --- a/config/roles.yml +++ b/config/roles.yml @@ -16,6 +16,10 @@ # program key). false: the role is global. # scope_source For a scopable role: where the valid scopes come from. # knot_programs = the program keys in config/kyc/knot.yml. +# patches = the slugs of the patches table (see Patch). +# Each knot.yml program has a patch with the same slug +# (Patch.sync_programs!), so both sources name the same +# program the same way. # requires Roles the person must hold first. Revoking a required # role revokes this role too. # grant, revoke The rule for each direction: @@ -105,10 +109,14 @@ roles: revoke: rule: admin + # The patch roles go to apps in the `patches` claim (see PatchRoles). patch_lead: name: Patch lead description: Leads a grant program. Records grants and asks for a grant over the cap. scopable: true + # knot_programs, not patches: the Knot records grants by program key, and + # a program key is valid without a patches row. Each program key also has + # a patch (Patch.sync_programs!). scope_source: knot_programs # LOCKED (2026-10-20): a patch lead must be ID-verified, like a key holder. grant: @@ -117,3 +125,15 @@ roles: preconditions_at_approval: [verified_by_another] revoke: rule: owner + + # Added 2026-11-12 by Jasper: a read-only role for one patch. Quilt shows + # the patch's finances to a patch viewer. + patch_viewer: + name: Patch viewer + description: Sees one patch's finances in apps such as Quilt. Read only. + scopable: true + scope_source: patches + grant: + rule: admin + revoke: + rule: admin diff --git a/config/routes.rb b/config/routes.rb index dc150e10..cdbdc1e0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -818,6 +818,10 @@ end end + # Patches: the grant programs (see Patch). No destroy: the slug is + # named by role assignments, Quilt and app tokens. + resources :patches, only: [:index, :show, :new, :create, :edit, :update] + resources :groups do resources :memberships, controller: "group_memberships", only: [:create, :destroy] do patch :role, on: :member diff --git a/db/migrate/20261112120000_create_patches.rb b/db/migrate/20261112120000_create_patches.rb new file mode 100644 index 00000000..e95dd0df --- /dev/null +++ b/db/migrate/20261112120000_create_patches.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +# Patches: the grant programs of Patchwork Labs, for example Project Ganymede +# (see Patch and docs/OAUTH.md "Patch claims"). +# +# - The slug is the stable name that apps see. It matches the program key in +# config/kyc/knot.yml and the patch slug in Quilt. A check constraint holds +# the format, and a trigger refuses a change to it after the insert. +# - The migration creates one patch for each program in config/kyc/knot.yml +# (Patch.sync_programs!). Seeds and `bin/rails patches:sync` do the same. +# +# db/schema.rb holds the function and the trigger through the fx gem. +class CreatePatches < ActiveRecord::Migration[8.1] + # The migration's own model, so a later change to Patch can't break it. + class MigrationPatch < ActiveRecord::Base + self.table_name = "patches" + end + + def up + create_table :patches do |t| + t.string :slug, null: false + t.string :name, null: false + t.text :description + t.references :created_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.timestamps + end + add_index :patches, :slug, unique: true + add_check_constraint :patches, "slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'", name: "patches_slug_format" + + safety_assured do + execute <<~SQL + CREATE FUNCTION refuse_patch_slug_change() RETURNS trigger + LANGUAGE plpgsql SET search_path = pg_catalog AS $$ + BEGIN + IF NEW.slug IS DISTINCT FROM OLD.slug THEN + RAISE EXCEPTION 'patches: the slug of a patch never changes'; + END IF; + RETURN NEW; + END; + $$; + SQL + + execute <<~SQL + CREATE TRIGGER patches_slug_fixed + BEFORE UPDATE OF slug ON patches + FOR EACH ROW EXECUTE FUNCTION refuse_patch_slug_change(); + SQL + end + + MigrationPatch.reset_column_information + Patch.sync_programs!(model: MigrationPatch) + end + + def down + safety_assured do + execute "DROP TRIGGER IF EXISTS patches_slug_fixed ON patches" + execute "DROP FUNCTION IF EXISTS refuse_patch_slug_change()" + end + drop_table :patches + end + +end diff --git a/db/migrate/20261112120100_add_patch_to_oauth_applications.rb b/db/migrate/20261112120100_add_patch_to_oauth_applications.rb new file mode 100644 index 00000000..38618ea5 --- /dev/null +++ b/db/migrate/20261112120100_add_patch_to_oauth_applications.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# An OAuth app can belong to one patch (see Patch). Introspection names the +# patch of an app token (see config/initializers/doorkeeper.rb). +class AddPatchToOauthApplications < ActiveRecord::Migration[8.1] + def change + # oauth_applications holds a few dozen rows, so the index and the foreign + # key take no time and block nothing. + safety_assured do + add_reference :oauth_applications, :patch, foreign_key: true, index: true + end + end + +end diff --git a/db/schema.rb b/db/schema.rb index fef23a83..e4a7069e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_10_120000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_12_120100) do # These are extensions that must be enabled in order to support this database enable_extension "fuzzystrmatch" enable_extension "pg_catalog.plpgsql" @@ -885,7 +885,9 @@ t.string "launcher_icon_url" t.text "launcher_description" t.bigint "access_request_group_id" + t.bigint "patch_id" t.index ["access_request_group_id"], name: "index_oauth_applications_on_access_request_group_id" + t.index ["patch_id"], name: "index_oauth_applications_on_patch_id" t.index ["uid"], name: "index_oauth_applications_on_uid", unique: true end @@ -895,6 +897,18 @@ t.index ["access_grant_id"], name: "index_oauth_openid_requests_on_access_grant_id" end + create_table "patches", force: :cascade do |t| + t.string "slug", null: false + t.string "name", null: false + t.text "description" + t.bigint "created_by_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["created_by_id"], name: "index_patches_on_created_by_id" + t.index ["slug"], name: "index_patches_on_slug", unique: true + t.check_constraint "slug::text ~ '^[a-z0-9]+(-[a-z0-9]+)*$'::text", name: "patches_slug_format" + end + create_table "pg_search_documents", force: :cascade do |t| t.text "content" t.string "searchable_type" @@ -1477,7 +1491,9 @@ add_foreign_key "oauth_access_tokens", "oauth_applications", column: "application_id" add_foreign_key "oauth_access_tokens", "users", column: "resource_owner_id" add_foreign_key "oauth_applications", "groups", column: "access_request_group_id", on_delete: :nullify + add_foreign_key "oauth_applications", "patches" add_foreign_key "oauth_openid_requests", "oauth_access_grants", column: "access_grant_id", on_delete: :cascade + add_foreign_key "patches", "users", column: "created_by_id", on_delete: :nullify add_foreign_key "program_grants", "knots" add_foreign_key "program_participations", "users", on_delete: :nullify add_foreign_key "residency_checks", "users", column: "decided_by_id", on_delete: :nullify @@ -1662,6 +1678,21 @@ $function$ SQL + create_function :refuse_patch_slug_change, sql_definition: <<-'SQL' + CREATE OR REPLACE FUNCTION public.refuse_patch_slug_change() + RETURNS trigger + LANGUAGE plpgsql + SET search_path TO 'pg_catalog' + AS $function$ + BEGIN + IF NEW.slug IS DISTINCT FROM OLD.slug THEN + RAISE EXCEPTION 'patches: the slug of a patch never changes'; + END IF; + RETURN NEW; + END; + $function$ + SQL + create_trigger :log_privileged_attribute_changes, sql_definition: <<-SQL CREATE TRIGGER log_privileged_attribute_changes AFTER INSERT OR UPDATE OF role ON public.users FOR EACH ROW EXECUTE FUNCTION log_privileged_attribute_changes() SQL @@ -1685,4 +1716,8 @@ create_trigger :user_roles_no_truncate, sql_definition: <<-SQL CREATE TRIGGER user_roles_no_truncate BEFORE TRUNCATE ON public.user_roles FOR EACH STATEMENT EXECUTE FUNCTION refuse_user_role_edits() SQL + + create_trigger :patches_slug_fixed, sql_definition: <<-SQL + CREATE TRIGGER patches_slug_fixed BEFORE UPDATE OF slug ON public.patches FOR EACH ROW EXECUTE FUNCTION refuse_patch_slug_change() + SQL end diff --git a/db/seeds.rb b/db/seeds.rb index fa82eff1..478c0f71 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -15,4 +15,7 @@ # To create an owner user, run: rails user:create_owner +# A patch for each program in config/kyc/knot.yml (see Patch). +Patch.sync_programs! + puts "Seed data successfully created!" diff --git a/docs/KYC.md b/docs/KYC.md index e5eb9ead..37d18d64 100644 --- a/docs/KYC.md +++ b/docs/KYC.md @@ -414,7 +414,9 @@ Jasper locked this design on 2026-10-20. Staff and identity roles are rows in a | Staff | `staff` | none | any admin, at once | any admin, at once | | Contractor | `contractor` | none | any admin, at once | any admin, at once | | Patch lead | `patch_lead` | a program key from `config/kyc/knot.yml` | an owner proposes, a different board member approves. Verified by another verifier | one owner, at once | +| Patch viewer | `patch_viewer` | a patch slug (the `patches` table) | any admin, at once | any admin, at once | +- Patches and their roles: Jasper added the patch viewer role and the `patches` scope source on 2026-11-12. A patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead keeps the `knot_programs` scope source, because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch roles in the `patches` claim (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). - The identity lead and the key holder need the verifier role first (`requires`). A revoke of the verifier role also revokes them. - The rules `owner` and `admin` also need the actor to manage the person in the admin panel (`UserAdminPermissions#manage?`): an admin changes only people below them, or themselves. The board role uses `any_owner` instead (locked 2026-10-20): any owner changes the board role of any person, other owners too. - A new identity lead, key holder or patch lead must be ID-verified by another verifier. Weave checks this at the proposal and again at the approval (`preconditions_at_proposal` and `preconditions_at_approval`). @@ -427,7 +429,7 @@ flowchart TD R -->|rule of each role| G[RoleGrants] P[Proposal rule: verifier, lead, key holder, new patch lead] --> IG[IdentityGovernance: propose, approve] IG -->|grant! or revoke!| G - I[Immediate rule: board, staff, contractor, patch lead removal, verifier removal] -->|RoleGrants.grant or .revoke| G + I[Immediate rule: board, staff, contractor, patch viewer, patch lead removal, verifier removal] -->|RoleGrants.grant or .revoke| G G -->|insert or set revoked_at| UR[(user_roles)] UR -->|trigger log_user_role_changes| L[(privileged_attribute_changes)] UR -->|after commit| SG[SystemGroups: staff, board, contractors, identity-team] @@ -438,7 +440,7 @@ flowchart TD - A proposal role (verifier, identity lead, key holder, a new patch lead) changes on `/identity/governance`. A patch lead proposal (`add_patch_lead`) names the program. - Staff and contractor change on `/admin/role_assignments` (the staff and contractors page), or in the roles section of the admin user page (`/admin/users/:id`). -- Board member and the removal of a patch lead change in the roles section of `/admin/users/:id`. Only an owner sees the forms. The roles section is on the user page, not the edit page, because an owner can open the page of another owner but not edit it. +- Board member and the removal of a patch lead change in the roles section of `/admin/users/:id`. Only an owner sees the forms. Any admin grants and revokes a patch viewer there, for a person they can manage. The patch page (`/admin/patches/:slug`) lists the leads and the viewers of the patch. The roles section is on the user page, not the edit page, because an owner can open the page of another owner but not edit it. - A verifier is removed with the removal form on `/identity/governance`. `RoleGrants.revoke` sends a verifier removal to `IdentityGovernance.remove_member`. - The governance page lists each role, its holders (with the scope) and its rules. diff --git a/docs/OAUTH.md b/docs/OAUTH.md index bbae17cd..d9319bb4 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -77,6 +77,7 @@ The OAuth provider supports the following scopes: - `roles`: the user's roles in this app (`roles`) - `age`: the user's age group, not the birthday (`age_band`, see "Age band claim") - `social`: the accounts the user linked on other sites (`social_profiles`, see "Social profile claims") +- `patches`: the user's roles for each patch (`patches`, see "Patch claims") - `directory`: the directory API, for `client_credentials` tokens only (see "Directory API") - `fulfillment`: read a user's shipping address, for `client_credentials` tokens only (see "Shipping address API") - `quilt`: the Quilt patch API, for `client_credentials` tokens only (see "Resource servers") @@ -360,6 +361,46 @@ link a group to an app that is open to everyone, to send the claim without limiting access. The list is empty when no linked group matches. Slugs never change after a group is created, so clients can compare them safely. +### Patch claims + +A patch is a grant program of Patchwork Labs, for example Project Ganymede. +Weave keeps the patches in `/admin/patches`. Each patch has a slug, such as +`ganymede`, that never changes. It is the same slug as in Quilt. A person can +hold a role for a patch: + +| Role | Short name | Who grants it | +|---|---|---| +| Patch lead (`patch_lead`) | `lead` | an owner proposes, a board member approves (see `docs/KYC.md` "Roles") | +| Patch viewer (`patch_viewer`) | `viewer` | any admin, on the user's admin page | + +Request the `patches` scope to get a `patches` claim in the ID token and the +userinfo response. The value is a JSON object. Each key is a patch slug, and +each value is the sorted list of the short names of the roles that the user +holds for that patch: + +```json +"patches": {"europa": ["viewer"], "ganymede": ["lead"]} +``` + +Rules: + +- The object is empty (`{}`) when the user holds no patch role. +- Only active roles count. A revoked role is left out at once, at the next token or userinfo call. +- Only patches that exist in Weave are listed. +- The keys are sorted. A slug never changes, so clients can compare it safely. +- `PatchRoles` (`app/services/patch_roles.rb`) builds the value. Quilt depends on this shape. Do not change it without a change in Quilt. + +The directory API sends the same object as `patches` when the app's scopes +list `patches` (see "Directory API"). + +```mermaid +flowchart LR + P[(patches: ganymede)] --> UR[user_roles: patch_lead, scope ganymede] + UR --> PR[PatchRoles] + PR --> C["patches claim: {ganymede: [lead]}"] + PR --> D[Directory API: patches] +``` + ### App roles An app can define its own roles, for example `member`, `reviewer` and `admin`. @@ -438,6 +479,7 @@ Rules: - `minor` is `true` when the user is under 18, from their birthday. It is `false` when Weave does not know the birthday yet. Weave asks for a missing birthday at the next sign-in. Only the directory sends this field. It is not a claim. - `guardian_verified` is `true` for a minor whose guardian was checked beyond the email link: a Weave admin recorded a signed form and a call or video check, or the minor passed identity verification with the guardian on the call (a pass needs a granted consent). The email consent alone does not set it. A revoked consent or a pass that no longer stands ends it. Ask for it before your app gives a minor money or other risk. It is `false` for adults. - `age_band` is in the response only when the app's scopes list `age` and Weave knows the birthday (see "Age band claim"). +- `patches` is in the response only when the app's scopes list `patches` (see "Patch claims"). - `demographics_answered` is `true` when the user saved answers to the demographics form. Weave never sends the answers. Ask for it before a user's first grant application. To send the user to the form, link to `/profile/demographics?return_to=`. After a save, Weave sends the user back to `return_to` when its origin matches a redirect URI of a registered app. Weave ignores any other `return_to`. - `?group=` works only for a group linked to the app. `?role=` works only for a role of the app. Other values give `404`. - Pass exactly one of `role` and `group`, or the API answers `400`. @@ -558,7 +600,7 @@ Rules for the resource server: - Refuse the request unless `active` is `true`. An inactive, revoked, expired, unknown or hidden token gives only `{"active": false}`. - Refuse the request unless `scope` (a space-separated list) includes the resource server's own scope (`quilt` for Quilt, `stash` for Stash). -- Use `client_id` to find the calling app, for example the patch it belongs to. Keep this mapping in the resource server. +- Use `client_id` to find the calling app. When an admin linked the calling app to a patch (the Patch field on the app's edit page), the response also has `patch`: the patch slug, for example `"patch": "ganymede"`. Weave sends `patch` only for a token with no user. It is not in the response when the app has no patch. - Keep a result for up to 60 seconds, keyed by a hash of the token, and never past `exp`. A revoked token can then work for up to 60 seconds. - Authenticate with HTTP Basic. A bearer token can introspect only tokens of its own app. diff --git a/lib/tasks/patches.rake b/lib/tasks/patches.rake new file mode 100644 index 00000000..47bf2151 --- /dev/null +++ b/lib/tasks/patches.rake @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +namespace :patches do + desc "Create a patch for each program in config/kyc/knot.yml. Safe to run more than once." + task sync: :environment do + PaperTrail.request(whodunnit: "patches:sync") do + Patch.sync_programs! + end + + Patch.order(:slug).each do |patch| + puts "#{patch.slug}: #{patch.name}" + end + end +end diff --git a/spec/factories/patches.rb b/spec/factories/patches.rb new file mode 100644 index 00000000..9fa12295 --- /dev/null +++ b/spec/factories/patches.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +FactoryBot.define do + factory :patch do + sequence(:slug) { |n| "patch-#{n}" } + sequence(:name) { |n| "Patch #{n}" } + end +end diff --git a/spec/models/patch_spec.rb b/spec/models/patch_spec.rb new file mode 100644 index 00000000..a8b30bb6 --- /dev/null +++ b/spec/models/patch_spec.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require "rails_helper" + +# A patch is a grant program. Apps, Quilt and role scopes name its slug, so the +# slug never changes. +RSpec.describe Patch do + it "needs a name and a slug in the slug format" do + expect(build(:patch, name: "")).not_to be_valid + expect(build(:patch, slug: "")).not_to be_valid + %w[Ganymede gany_mede -ganymede ganymede- gany--mede].each do |slug| + expect(build(:patch, slug:)).not_to be_valid, "expected #{slug.inspect} to be refused" + end + expect(build(:patch, slug: "project-ganymede-2")).to be_valid + end + + it "keeps the slug unique" do + create(:patch, slug: "ganymede") + + expect(build(:patch, slug: "ganymede")).not_to be_valid + end + + it "refuses a slug change, in the model and in the database" do + patch = create(:patch, slug: "ganymede") + + expect(patch.update(slug: "europa")).to be(false) + expect(patch.errors[:slug]).to include("can't be changed after the patch is created") + expect { patch.update_column(:slug, "europa") }.to raise_error(ActiveRecord::StatementInvalid, /slug of a patch never changes/) # rubocop:disable Rails/SkipsModelValidations + end + + it "refuses a bad slug in the database too" do + sql = "INSERT INTO patches (slug, name, created_at, updated_at) VALUES ('Bad Slug', 'Bad', now(), now())" + + expect { ActiveRecord::Base.connection.execute(sql) }.to raise_error(ActiveRecord::StatementInvalid, /patches_slug_format/) + end + + it "uses the slug in URLs" do + expect(build(:patch, slug: "ganymede").to_param).to eq("ganymede") + end + + it "keeps a version of each change" do + patch = create(:patch, name: "Ganymede") + patch.update!(name: "Project Ganymede") + + expect(patch.versions.map(&:event)).to eq(%w[create update]) + end + + describe ".sync_programs!" do + it "creates a patch for each program in config/kyc/knot.yml, named as the program" do + expect { described_class.sync_programs! }.to change(described_class, :count).by(KnotSettings.program_keys.size) + + expect(described_class.find_by!(slug: "ganymede").name).to eq("Project Ganymede") + expect(described_class.pluck(:slug)).to match_array(KnotSettings.program_keys) + end + + it "is idempotent and never renames a patch" do + create(:patch, slug: "ganymede", name: "Ganymede (renamed)") + + expect { 2.times { described_class.sync_programs! } }.not_to change(described_class, :count) + expect(described_class.find_by!(slug: "ganymede").name).to eq("Ganymede (renamed)") + end + end +end diff --git a/spec/requests/admin_nav_spec.rb b/spec/requests/admin_nav_spec.rb index ec5a9b47..5eec19d3 100644 --- a/spec/requests/admin_nav_spec.rb +++ b/spec/requests/admin_nav_spec.rb @@ -30,7 +30,7 @@ def current_link = Nokogiri::HTML(response.body).at_css('aside[aria-label="Admin get admin_root_path expect(sidebar).to eq( - "People" => ["Users", "Staff and contractors", "Groups", "Consents"], + "People" => ["Users", "Staff and contractors", "Groups", "Patches", "Consents"], "Data" => ["Demographics", "Funder reports"], "System" => ["Dashboard", "OAuth apps", "Services", "Jobs", "Feature flags", "Blazer", "Console audits", "Console sign-in"] ) @@ -44,7 +44,7 @@ def current_link = Nokogiri::HTML(response.body).at_css('aside[aria-label="Admin expect(sidebar).to eq( "Identity" => ["Verification", "US residency", "Key custody", "Knot"], - "People" => ["Users", "Staff and contractors", "Groups", "Consents"], + "People" => ["Users", "Staff and contractors", "Groups", "Patches", "Consents"], "Data" => ["Deletion", "Demographics", "Funder reports"], "System" => ["Dashboard", "OAuth apps", "Services", "Jobs", "Feature flags", "Blazer", "Console audits", "Console sign-in"] ) diff --git a/spec/requests/admin_oauth_application_patch_spec.rb b/spec/requests/admin_oauth_application_patch_spec.rb new file mode 100644 index 00000000..e965e49d --- /dev/null +++ b/spec/requests/admin_oauth_application_patch_spec.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require "rails_helper" + +# An OAuth app can belong to one patch. Any admin who can edit apps sets it. +RSpec.describe "Admin OAuth application patch", type: :request do + let(:admin) { create(:user, :admin, :verified) } + let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let(:application) { Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb") } + + before { sign_in_via_magic_link(admin) } + + it "links an app to a patch, and shows the patch on the app page and the app on the patch page" do + get edit_admin_oauth_application_path(application) + expect(response.body).to include("Project Ganymede (ganymede)") + + patch admin_oauth_application_path(application), params: { doorkeeper_application: { patch_id: ganymede.id } } + + expect(application.reload.patch).to eq(ganymede) + get admin_oauth_application_path(application) + expect(response.body).to include("Project Ganymede", admin_patch_path(ganymede)) + get admin_patch_path(ganymede) + expect(response.body).to include("Krater") + end + + it "removes the link" do + application.update!(patch: ganymede) + + patch admin_oauth_application_path(application), params: { doorkeeper_application: { patch_id: "" } } + + expect(application.reload.patch).to be_nil + end + + it "refuses a patch that does not exist" do + patch admin_oauth_application_path(application), params: { doorkeeper_application: { patch_id: ganymede.id + 1000 } } + + expect(response).to have_http_status(:unprocessable_content) + expect(application.reload.patch).to be_nil + end + + it "sets the patch when an app is created" do + post admin_oauth_applications_path, params: { + doorkeeper_application: { name: "Orbit", redirect_uri: "https://orbit.example.com/cb", scopes: "openid patches", patch_id: ganymede.id } + } + + expect(Doorkeeper::Application.find_by!(name: "Orbit").patch).to eq(ganymede) + end + + it "is not open to a member" do + sign_in_via_magic_link(create(:user, :verified)) + + patch admin_oauth_application_path(application), params: { doorkeeper_application: { patch_id: ganymede.id } } + + # The admin routes do not exist for a member (AdminConstraint). + expect(response).to have_http_status(:not_found) + expect(application.reload.patch).to be_nil + end +end diff --git a/spec/requests/admin_patches_spec.rb b/spec/requests/admin_patches_spec.rb new file mode 100644 index 00000000..d6918ff4 --- /dev/null +++ b/spec/requests/admin_patches_spec.rb @@ -0,0 +1,89 @@ +# frozen_string_literal: true + +require "rails_helper" + +# Patches in the admin panel. Any admin may look; only a superadmin may create +# a patch or change it. The slug never changes, and there is no delete. +RSpec.describe "Admin patches", type: :request do + let(:admin) { create(:user, :admin, :verified) } + let(:superadmin) { create(:user, :superadmin, :verified) } + let(:owner) { create(:user, :owner, :verified) } + let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede", description: "Space grants.") } + + it "is only for admins" do + sign_in_via_magic_link(create(:user, :verified)) + + get admin_patches_path + expect(response).to redirect_to(login_path) + + get admin_patch_path(ganymede) + expect(response).to redirect_to(login_path) + end + + context "when signed in as a plain admin" do + before { sign_in_via_magic_link(admin) } + + it "lists and shows patches, with the linked apps and the people with a patch role, with no N+1" do + krater = Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb", patch: ganymede) + Doorkeeper::Application.create!(name: "Stash", redirect_uri: "https://stash.example.com/cb") + create_list(:user, 2, :verified, :patch_lead) + viewers = create_list(:user, 2, :verified) + viewers.each { |viewer| RoleGrants.grant!(viewer, "patch_viewer", scope: "ganymede", by: owner, reason: "spec") } + + get admin_patches_path + expect(response).to have_http_status(:ok) + expect(response.body).to include("Project Ganymede", "ganymede", "Space grants.") + expect(response.body).not_to include("New patch") + + get admin_patch_path(ganymede) + expect(response).to have_http_status(:ok) + expect(response.body).to include("Project Ganymede", krater.name, "Patch lead", "Patch viewer", viewers.first.full_name) + expect(response.body).not_to include("Stash", edit_admin_patch_path(ganymede)) + end + + it "can't create or edit a patch" do + get new_admin_patch_path + expect(response).to redirect_to(admin_patches_path) + + post admin_patches_path, params: { patch: { name: "Europa", slug: "europa" } } + expect(response).to redirect_to(admin_patches_path) + expect(Patch.exists?(slug: "europa")).to be(false) + + patch admin_patch_path(ganymede), params: { patch: { name: "Renamed" } } + expect(ganymede.reload.name).to eq("Project Ganymede") + end + end + + context "when signed in as a superadmin" do + before { sign_in_via_magic_link(superadmin) } + + it "creates a patch" do + get new_admin_patch_path + expect(response).to have_http_status(:ok) + + post admin_patches_path, params: { patch: { name: "Europa", slug: "europa", description: "Ocean grants." } } + + europa = Patch.find_by!(slug: "europa") + expect(europa).to have_attributes(name: "Europa", description: "Ocean grants.", created_by: superadmin) + expect(response).to redirect_to(admin_patch_path(europa)) + expect(europa.versions.last.whodunnit).to eq(superadmin.id.to_s) + end + + it "shows the form again when the input is not valid" do + post admin_patches_path, params: { patch: { name: "Europa", slug: "Not A Slug" } } + + expect(response).to have_http_status(:unprocessable_content) + expect(Patch.exists?(name: "Europa")).to be(false) + end + + it "changes the name and the description, never the slug" do + get edit_admin_patch_path(ganymede) + expect(response).to have_http_status(:ok) + + patch admin_patch_path(ganymede), params: { patch: { name: "Ganymede", description: "", slug: "europa" } } + + expect(ganymede.reload).to have_attributes(name: "Ganymede", description: "", slug: "ganymede") + expect(response).to redirect_to(admin_patch_path(ganymede)) + end + end +end diff --git a/spec/requests/api/directory_spec.rb b/spec/requests/api/directory_spec.rb index 6a3c1c74..84cd12be 100644 --- a/spec/requests/api/directory_spec.rb +++ b/spec/requests/api/directory_spec.rb @@ -42,6 +42,16 @@ def directory_get(path, token: app_token, params: {}) ) end + it "gives the patch roles only to an app allowed the patches scope" do + create(:patch, slug: "ganymede", name: "Project Ganymede") + RoleGrants.grant!(reviewer, "patch_viewer", scope: "ganymede", reason: "spec") + + expect(directory_get(api_v1_directory_user_path(reviewer.p_id))).not_to have_key("patches") + + application.update!(scopes: "openid profile groups roles directory patches") + expect(directory_get(api_v1_directory_user_path(reviewer.p_id))).to include("patches" => { "ganymede" => ["viewer"] }) + end + it "says when a sponsored project's group waives Slack and the code of conduct" do sponsored = create(:group, waives_code_of_conduct: true, waives_slack: true) create(:group_membership, group: sponsored, user: reviewer) diff --git a/spec/requests/oauth/introspection_spec.rb b/spec/requests/oauth/introspection_spec.rb index 4e64ded5..02a21bcb 100644 --- a/spec/requests/oauth/introspection_spec.rb +++ b/spec/requests/oauth/introspection_spec.rb @@ -54,6 +54,29 @@ def introspect(token, as:) end end + it "sees the patch of the calling app, for an app linked to a patch" do + krater.update!(patch: create(:patch, slug: "ganymede", name: "Project Ganymede")) + token = client_credentials_token(krater, scope: "quilt") + + expect(introspect(token, as: quilt)).to include("active" => true, "client_id" => krater.uid, "patch" => "ganymede") + end + + it "gets no patch field for an app with no patch" do + token = client_credentials_token(krater, scope: "quilt") + + expect(introspect(token, as: quilt)).not_to have_key("patch") + end + + it "gets no patch field for a user's token" do + krater.update!(patch: create(:patch, slug: "ganymede", name: "Project Ganymede")) + token = Doorkeeper::AccessToken.create!(application: krater, resource_owner_id: user.id, scopes: "openid profile") + + body = introspect(token.plaintext_token, as: krater) + + expect(body).to include("active" => true) + expect(body).not_to have_key("patch") + end + it "does not see a user's token of another app" do token = Doorkeeper::AccessToken.create!(application: krater, resource_owner_id: user.id, scopes: "openid profile") diff --git a/spec/requests/oauth/openid_connect_spec.rb b/spec/requests/oauth/openid_connect_spec.rb index cf69db22..fe9bfb49 100644 --- a/spec/requests/oauth/openid_connect_spec.rb +++ b/spec/requests/oauth/openid_connect_spec.rb @@ -16,7 +16,7 @@ Doorkeeper::Application.create!( name: "Test Client", redirect_uri: redirect_uri, - scopes: "openid profile email phone admin slack groups roles verification residency age social", + scopes: "openid profile email phone admin slack groups roles verification residency age social patches", confidential: false ) end @@ -160,7 +160,15 @@ def header = decoded.last "email_verified" => true ) expect(claims).not_to include("phone_number", "phone_number_verified", "admin", "slack_member", "slack_id", "groups", "roles") - expect(claims).not_to include("age_band") + expect(claims).not_to include("age_band", "patches") + end + + it "carries the patch roles when the patches scope is granted" do + create(:patch, slug: "ganymede", name: "Project Ganymede") + RoleGrants.grant!(user, "patch_lead", scope: "ganymede", reason: "spec") + patch_claims = verify_id_token(obtain_tokens(scope: "openid patches")["id_token"]).first + + expect(patch_claims).to include("patches" => { "ganymede" => ["lead"] }) end it "carries the Slack membership claims when the slack scope is granted" do @@ -348,6 +356,40 @@ def userinfo(scope:) expect(userinfo(scope: "openid profile")).not_to include("social_profiles") end + describe "the patches claim" do + let(:owner) { create(:user, :owner, :verified) } + + before do + create(:patch, slug: "ganymede", name: "Project Ganymede") + create(:patch, slug: "europa", name: "Europa") + end + + it "maps each patch slug to the user's sorted short role names" do + RoleGrants.grant!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") + RoleGrants.grant!(user, "patch_viewer", scope: "ganymede", by: owner, reason: "spec") + RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + + expect(userinfo(scope: "openid patches")).to include("patches" => { "europa" => ["viewer"], "ganymede" => %w[lead viewer] }) + end + + it "is an empty object when the user has no patch role" do + expect(userinfo(scope: "openid patches")).to include("patches" => {}) + end + + it "leaves out a revoked role" do + RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + RoleGrants.revoke!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + + expect(userinfo(scope: "openid patches")).to include("patches" => {}) + end + + it "is not sent without the patches scope" do + RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + + expect(userinfo(scope: "openid profile")).not_to have_key("patches") + end + end + describe "the groups claim" do before do %w[engineering design payroll].each do |slug| diff --git a/spec/requests/roles_spec.rb b/spec/requests/roles_spec.rb index e1c33967..b634e362 100644 --- a/spec/requests/roles_spec.rb +++ b/spec/requests/roles_spec.rb @@ -20,7 +20,7 @@ get identity_governance_path expect(response).to have_http_status(:ok) - expect(response.body).to include("Roles", "Patch lead (scoped by program)", "Adam Doe (ganymede)", + expect(response.body).to include("Roles", "Patch lead (scoped by patch)", "Adam Doe (ganymede)", "Grant: An owner proposes. Every board member approves.", "Grant: Any admin, at once.", "Revoke: One owner or identity lead, at once.", "· key holder", "· lead") @@ -66,5 +66,39 @@ expect(response.body).to include("Revoke staff", "Revoke patch lead (ganymede)", "Grant board member", "Grant contractor", "To grant it, an owner proposes the change on the identity governance page.") end + + it "lets an admin grant and revoke a patch viewer role for a patch that exists" do + admin = create(:user, :admin, :verified) + user = create(:user, :verified) + create(:patch, slug: "ganymede", name: "Project Ganymede") + sign_in_via_magic_link(admin) + + get admin_user_path(user) + expect(response.body).to include("Grant patch viewer") + + post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", return_to: "user" } + expect(response).to redirect_to(admin_user_path(user, anchor: "roles")) + expect(user.reload_roles!.role_scopes("patch_viewer")).to eq(["ganymede"]) + + post revoke_admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", reason: "Done." } + expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) + end + + it "refuses a patch viewer role for a patch that does not exist, and to a member" do + user = create(:user, :verified) + sign_in_via_magic_link(create(:user, :admin, :verified)) + + get admin_user_path(user) + expect(response.body).not_to include("Grant patch viewer") + + post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "europa" } + expect(flash[:alert]).to include("Not granted") + + create(:patch, slug: "europa") + sign_in_via_magic_link(create(:user, :verified)) + post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "europa" } + expect(response).to have_http_status(:not_found) + expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) + end end end diff --git a/spec/services/patch_roles_spec.rb b/spec/services/patch_roles_spec.rb new file mode 100644 index 00000000..0d77b22a --- /dev/null +++ b/spec/services/patch_roles_spec.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require "rails_helper" + +# The `patches` claim and the directory field: the contract with Quilt. +RSpec.describe PatchRoles do + let(:owner) { create(:user, :owner, :verified) } + let(:user) { create(:user, :verified) } + + before do + create(:patch, slug: "ganymede", name: "Project Ganymede") + create(:patch, slug: "europa", name: "Europa") + end + + def grant(key, scope) = RoleGrants.grant!(user, key, scope:, by: owner, reason: "spec") + + it "maps each patch slug to the sorted short role names, with the slugs sorted" do + grant("patch_viewer", "europa") + grant("patch_viewer", "ganymede") + grant("patch_lead", "ganymede") + + result = described_class.for(user.reload_roles!) + + expect(result).to eq("europa" => ["viewer"], "ganymede" => %w[lead viewer]) + expect(result.keys).to eq(%w[europa ganymede]) + expect(result.to_json).to eq('{"europa":["viewer"],"ganymede":["lead","viewer"]}') + end + + it "is an empty object for a person with no patch role" do + user.update!(is_staff: true) + + expect(described_class.for(user.reload_roles!)).to eq({}) + expect(described_class.for(nil)).to eq({}) + end + + it "leaves out a revoked role" do + grant("patch_viewer", "europa") + grant("patch_lead", "ganymede") + RoleGrants.revoke!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + + expect(described_class.for(user.reload_roles!)).to eq("ganymede" => ["lead"]) + end + + it "leaves out a patch that does not exist" do + # A patch lead is scoped by a knot.yml program key, which is valid with no + # patches row. + Patch.find_by!(slug: "ganymede").then { |patch| ActiveRecord::Base.connection.execute("DELETE FROM patches WHERE id = #{patch.id}") } + grant("patch_lead", "ganymede") + grant("patch_viewer", "europa") + + expect(described_class.for(user.reload_roles!)).to eq("europa" => ["viewer"]) + end + + it "names only scopable roles of config/roles.yml" do + described_class::NAMES.each_key do |key| + expect(RoleRegistry.fetch(key)).to be_scopable + end + end +end diff --git a/spec/services/role_registry_spec.rb b/spec/services/role_registry_spec.rb index d4079629..59bbbd46 100644 --- a/spec/services/role_registry_spec.rb +++ b/spec/services/role_registry_spec.rb @@ -16,12 +16,13 @@ def changed(&block) delegate :parse, to: :described_class it "loads every role of the locked set from config/roles.yml" do - expect(described_class.keys).to eq(%w[verifier identity_lead key_holder board staff contractor patch_lead]) + expect(described_class.keys).to eq(%w[verifier identity_lead key_holder board staff contractor patch_lead patch_viewer]) expect(described_class.fetch("patch_lead")).to have_attributes(scopable: true, scope_source: "knot_programs") + expect(described_class.fetch("patch_viewer")).to have_attributes(scopable: true, scope_source: "patches") expect(described_class.fetch("key_holder").requires).to eq(["verifier"]) end - it "holds the locked grant rules" do + it "holds the locked grant rules" do # rubocop:disable RSpec/ExampleLength rules = described_class.definitions.transform_values { |definition| [definition.grant.rule, definition.revoke.rule] } expect(rules).to eq( @@ -31,7 +32,8 @@ def changed(&block) "board" => %w[any_owner any_owner], "staff" => %w[admin admin], "contractor" => %w[admin admin], - "patch_lead" => %w[owner_proposes_board_approves owner] + "patch_lead" => %w[owner_proposes_board_approves owner], + "patch_viewer" => %w[admin admin] ) expect(described_class.fetch("verifier").grant.preconditions_at_approval).to eq(%w[verified_by_another adult]) expect(described_class.fetch("verifier").grant.preconditions_at_proposal).to eq([]) @@ -126,6 +128,24 @@ def changed(&block) expect(described_class.valid_scope?("staff", nil)).to be(true) expect(described_class.valid_scope?("staff", "ganymede")).to be(false) end + + it "takes the patch viewer scopes from the patches table" do + expect(described_class.scopes_for("patch_viewer")).to eq([]) + + create(:patch, slug: "europa") + create(:patch, slug: "ganymede") + + expect(described_class.scopes_for("patch_viewer")).to eq(%w[europa ganymede]) + expect(described_class.valid_scope?("patch_viewer", "europa")).to be(true) + expect(described_class.valid_scope?("patch_viewer", "callisto")).to be(false) + expect(described_class.valid_scope?("patch_viewer", nil)).to be(false) + end + + it "gives every Knot program a patch with the same slug, so both scope sources agree" do + Patch.sync_programs! + + expect(described_class.scopes_for("patch_viewer")).to include(*described_class.scopes_for("patch_lead")) + end end describe ".sync!" do From 85027945c5aed6a0cf5da2ed68eccd5e3333a44e Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 11:33:44 -0500 Subject: [PATCH 2/9] fix: let only a superadmin link an app to a patch --- .../admin/oauth_applications_controller.rb | 8 ++++++-- .../oauth_applications/_patch_field.html.erb | 2 +- app/views/admin/oauth_applications/edit.html.erb | 4 +++- app/views/admin/oauth_applications/new.html.erb | 4 +++- docs/OAUTH.md | 2 +- .../admin_oauth_application_patch_spec.rb | 15 +++++++++++++-- 6 files changed, 27 insertions(+), 8 deletions(-) diff --git a/app/controllers/admin/oauth_applications_controller.rb b/app/controllers/admin/oauth_applications_controller.rb index cc725bc3..a5bdda15 100644 --- a/app/controllers/admin/oauth_applications_controller.rb +++ b/app/controllers/admin/oauth_applications_controller.rb @@ -202,9 +202,13 @@ def set_application @application = Doorkeeper::Application.find_by_public_param!(params[:id]) end + # Only a superadmin links an app to a patch: introspection names the patch, + # and a resource server such as Quilt may trust it to tell which patch calls. def application_params - params.require(:doorkeeper_application).permit(:name, :redirect_uri, :scopes, :confidential, :patch_id, - :show_in_launcher, :launch_url, :launcher_icon_url, :launcher_description) + permitted = [:name, :redirect_uri, :scopes, :confidential, + :show_in_launcher, :launch_url, :launcher_icon_url, :launcher_description] + permitted << :patch_id if current_user.superadmin? + params.require(:doorkeeper_application).permit(*permitted) end end diff --git a/app/views/admin/oauth_applications/_patch_field.html.erb b/app/views/admin/oauth_applications/_patch_field.html.erb index b58ce5a9..df76dde4 100644 --- a/app/views/admin/oauth_applications/_patch_field.html.erb +++ b/app/views/admin/oauth_applications/_patch_field.html.erb @@ -1,4 +1,4 @@ -<%# The patch the app belongs to (see OauthApplicationPatchLink). %> +<%# The patch the app belongs to (see OauthApplicationPatchLink). Superadmin only. %>

    <%= form.label :patch_id, class: "field-label" do %>Patch (optional)<% end %> <%= form.select :patch_id, Patch.order(:name).map { |patch| ["#{patch.name} (#{patch.slug})", patch.id] }, diff --git a/app/views/admin/oauth_applications/edit.html.erb b/app/views/admin/oauth_applications/edit.html.erb index a0240d81..57b2650d 100644 --- a/app/views/admin/oauth_applications/edit.html.erb +++ b/app/views/admin/oauth_applications/edit.html.erb @@ -48,7 +48,9 @@ - <%= render "patch_field", form: form %> + <% if current_user.superadmin? %> + <%= render "patch_field", form: form %> + <% end %> <%= render "launcher_fields", form: form %> diff --git a/app/views/admin/oauth_applications/new.html.erb b/app/views/admin/oauth_applications/new.html.erb index a175ac40..3bb4eb67 100644 --- a/app/views/admin/oauth_applications/new.html.erb +++ b/app/views/admin/oauth_applications/new.html.erb @@ -57,7 +57,9 @@ - <%= render "patch_field", form: form %> + <% if current_user.superadmin? %> + <%= render "patch_field", form: form %> + <% end %> <%= render "launcher_fields", form: form %> diff --git a/docs/OAUTH.md b/docs/OAUTH.md index d9319bb4..3437618e 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -600,7 +600,7 @@ Rules for the resource server: - Refuse the request unless `active` is `true`. An inactive, revoked, expired, unknown or hidden token gives only `{"active": false}`. - Refuse the request unless `scope` (a space-separated list) includes the resource server's own scope (`quilt` for Quilt, `stash` for Stash). -- Use `client_id` to find the calling app. When an admin linked the calling app to a patch (the Patch field on the app's edit page), the response also has `patch`: the patch slug, for example `"patch": "ganymede"`. Weave sends `patch` only for a token with no user. It is not in the response when the app has no patch. +- Use `client_id` to find the calling app. When a superadmin linked the calling app to a patch (the Patch field on the app's edit page), the response also has `patch`: the patch slug, for example `"patch": "ganymede"`. Weave sends `patch` only for a token with no user. It is not in the response when the app has no patch. - Keep a result for up to 60 seconds, keyed by a hash of the token, and never past `exp`. A revoked token can then work for up to 60 seconds. - Authenticate with HTTP Basic. A bearer token can introspect only tokens of its own app. diff --git a/spec/requests/admin_oauth_application_patch_spec.rb b/spec/requests/admin_oauth_application_patch_spec.rb index e965e49d..430db9ba 100644 --- a/spec/requests/admin_oauth_application_patch_spec.rb +++ b/spec/requests/admin_oauth_application_patch_spec.rb @@ -2,9 +2,9 @@ require "rails_helper" -# An OAuth app can belong to one patch. Any admin who can edit apps sets it. +# An OAuth app can belong to one patch. Only a superadmin sets it. RSpec.describe "Admin OAuth application patch", type: :request do - let(:admin) { create(:user, :admin, :verified) } + let(:admin) { create(:user, :superadmin, :verified) } let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } let(:application) { Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb") } @@ -46,6 +46,17 @@ expect(Doorkeeper::Application.find_by!(name: "Orbit").patch).to eq(ganymede) end + it "ignores the patch from an admin who is not a superadmin, and hides the field" do + sign_in_via_magic_link(create(:user, :admin, :verified)) + + get edit_admin_oauth_application_path(application) + expect(response.body).not_to include("Project Ganymede (ganymede)") + + patch admin_oauth_application_path(application), params: { doorkeeper_application: { patch_id: ganymede.id } } + + expect(application.reload.patch).to be_nil + end + it "is not open to a member" do sign_in_via_magic_link(create(:user, :verified)) From 851d77535f6f4047db62e6a427299086c4cf920d Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 11:38:34 -0500 Subject: [PATCH 3/9] fix: let only an owner grant a patch viewer, and send patch roles only to apps that list patches --- app/services/knot_settings.rb | 4 +++ .../initializers/doorkeeper_openid_connect.rb | 7 ++-- config/roles.yml | 6 ++-- docs/KYC.md | 2 +- docs/OAUTH.md | 5 ++- spec/requests/oauth/openid_connect_spec.rb | 7 ++++ spec/requests/roles_spec.rb | 32 ++++++++++++++++--- spec/services/knot_settings_spec.rb | 7 ++++ spec/services/role_registry_spec.rb | 2 +- 9 files changed, 61 insertions(+), 11 deletions(-) diff --git a/app/services/knot_settings.rb b/app/services/knot_settings.rb index 21b817f4..806ea0f7 100644 --- a/app/services/knot_settings.rb +++ b/app/services/knot_settings.rb @@ -18,6 +18,10 @@ def programs raise ArgumentError, "#{PATH}: programs.#{key}.patch_lead_p_ids is gone. A patch lead is a patch_lead role scoped to the program (see config/roles.yml)." end + unless Patch::SLUG_FORMAT.match?(key.to_s) + raise ArgumentError, "#{PATH}: programs.#{key}: a program key is a patch slug (lowercase letters, digits and single dashes)." + end + Program.new(key: key.to_s, name: values.fetch(:name), grant_cap: values[:grant_cap]) end end diff --git a/config/initializers/doorkeeper_openid_connect.rb b/config/initializers/doorkeeper_openid_connect.rb index 3c4b45ab..b5de5ccd 100644 --- a/config/initializers/doorkeeper_openid_connect.rb +++ b/config/initializers/doorkeeper_openid_connect.rb @@ -244,8 +244,11 @@ def test_key # maps a patch slug to the sorted short role names, for example # {"ganymede": ["lead"]}. An empty object when none. Quilt depends on this # shape: keep it. - normal_claim :patches, scope: :patches, response: [:id_token, :user_info] do |user| - PatchRoles.for(user) + # Only an app whose scopes field lists `patches` gets it. Doorkeeper lets + # an app with an empty scopes field ask for any user scope, and the patch + # roster must not reach such an app. + normal_claim :patches, scope: :patches, response: [:id_token, :user_info] do |user, _scopes, access_token| + access_token.application&.scopes&.exists?("patches") ? PatchRoles.for(user) : {} end end end diff --git a/config/roles.yml b/config/roles.yml index 2c4fc622..a84204a6 100644 --- a/config/roles.yml +++ b/config/roles.yml @@ -127,13 +127,15 @@ roles: rule: owner # Added 2026-11-12 by Jasper: a read-only role for one patch. Quilt shows - # the patch's finances to a patch viewer. + # the patch's finances to a patch viewer. An owner grants it, because it + # opens finance data in Quilt, like a Quilt app role (superadmin only). Any + # admin can revoke it, so access is quick to take away. patch_viewer: name: Patch viewer description: Sees one patch's finances in apps such as Quilt. Read only. scopable: true scope_source: patches grant: - rule: admin + rule: owner revoke: rule: admin diff --git a/docs/KYC.md b/docs/KYC.md index 37d18d64..fc7af4a9 100644 --- a/docs/KYC.md +++ b/docs/KYC.md @@ -414,7 +414,7 @@ Jasper locked this design on 2026-10-20. Staff and identity roles are rows in a | Staff | `staff` | none | any admin, at once | any admin, at once | | Contractor | `contractor` | none | any admin, at once | any admin, at once | | Patch lead | `patch_lead` | a program key from `config/kyc/knot.yml` | an owner proposes, a different board member approves. Verified by another verifier | one owner, at once | -| Patch viewer | `patch_viewer` | a patch slug (the `patches` table) | any admin, at once | any admin, at once | +| Patch viewer | `patch_viewer` | a patch slug (the `patches` table) | one owner, at once | any admin, at once | - Patches and their roles: Jasper added the patch viewer role and the `patches` scope source on 2026-11-12. A patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead keeps the `knot_programs` scope source, because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch roles in the `patches` claim (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). - The identity lead and the key holder need the verifier role first (`requires`). A revoke of the verifier role also revokes them. diff --git a/docs/OAUTH.md b/docs/OAUTH.md index 3437618e..6b7840f5 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -371,7 +371,7 @@ hold a role for a patch: | Role | Short name | Who grants it | |---|---|---| | Patch lead (`patch_lead`) | `lead` | an owner proposes, a board member approves (see `docs/KYC.md` "Roles") | -| Patch viewer (`patch_viewer`) | `viewer` | any admin, on the user's admin page | +| Patch viewer (`patch_viewer`) | `viewer` | an owner grants it and any admin revokes it, on the user's admin page | Request the `patches` scope to get a `patches` claim in the ID token and the userinfo response. The value is a JSON object. Each key is a patch slug, and @@ -388,6 +388,9 @@ Rules: - Only active roles count. A revoked role is left out at once, at the next token or userinfo call. - Only patches that exist in Weave are listed. - The keys are sorted. A slug never changes, so clients can compare it safely. +- The app's scopes field must list `patches`. An app with an empty scopes field gets `{}`. +- A patch role does not open an app whose access policy is restricted. Give the person an access grant too, or keep the app open to everyone and let it refuse people with no role. +- An app reads the claim at sign-in. A revoked role stays in the app's session until the person signs in again. - `PatchRoles` (`app/services/patch_roles.rb`) builds the value. Quilt depends on this shape. Do not change it without a change in Quilt. The directory API sends the same object as `patches` when the app's scopes diff --git a/spec/requests/oauth/openid_connect_spec.rb b/spec/requests/oauth/openid_connect_spec.rb index fe9bfb49..ac10a921 100644 --- a/spec/requests/oauth/openid_connect_spec.rb +++ b/spec/requests/oauth/openid_connect_spec.rb @@ -383,6 +383,13 @@ def userinfo(scope:) expect(userinfo(scope: "openid patches")).to include("patches" => {}) end + it "is an empty object for an app whose scopes field does not list patches" do + application.update!(scopes: "") + RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + + expect(userinfo(scope: "openid patches")).to include("patches" => {}) + end + it "is not sent without the patches scope" do RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") diff --git a/spec/requests/roles_spec.rb b/spec/requests/roles_spec.rb index b634e362..5e1606a9 100644 --- a/spec/requests/roles_spec.rb +++ b/spec/requests/roles_spec.rb @@ -67,11 +67,10 @@ "To grant it, an owner proposes the change on the identity governance page.") end - it "lets an admin grant and revoke a patch viewer role for a patch that exists" do - admin = create(:user, :admin, :verified) + it "lets an owner grant and revoke a patch viewer role for a patch that exists" do user = create(:user, :verified) create(:patch, slug: "ganymede", name: "Project Ganymede") - sign_in_via_magic_link(admin) + sign_in_via_magic_link(owner) get admin_user_path(user) expect(response.body).to include("Grant patch viewer") @@ -84,10 +83,35 @@ expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) end - it "refuses a patch viewer role for a patch that does not exist, and to a member" do + it "does not let an admin who is not an owner grant a patch viewer role, to anyone or to themselves" do + admin = create(:user, :admin, :verified) user = create(:user, :verified) + create(:patch, slug: "ganymede", name: "Project Ganymede") + sign_in_via_magic_link(admin) + + get admin_user_path(user) + expect(response.body).not_to include("Grant patch viewer") + + [user, admin].each do |target| + post admin_role_assignments_path, params: { user_id: target.p_id, role: "patch_viewer", scope: "ganymede" } + expect(target.reload_roles!.role_scopes("patch_viewer")).to eq([]) + end + end + + it "lets an admin revoke a patch viewer role" do + user = create(:user, :verified) + create(:patch, slug: "ganymede", name: "Project Ganymede") + RoleGrants.grant(user, "patch_viewer", by: owner, scope: "ganymede", reason: "Ganymede finances.") sign_in_via_magic_link(create(:user, :admin, :verified)) + post revoke_admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", reason: "Done." } + expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) + end + + it "refuses a patch viewer role for a patch that does not exist, and to a member" do + user = create(:user, :verified) + sign_in_via_magic_link(owner) + get admin_user_path(user) expect(response.body).not_to include("Grant patch viewer") diff --git a/spec/services/knot_settings_spec.rb b/spec/services/knot_settings_spec.rb index f19dfab2..6c7e4a79 100644 --- a/spec/services/knot_settings_spec.rb +++ b/spec/services/knot_settings_spec.rb @@ -27,4 +27,11 @@ def values_for(environment) expect { described_class.programs }.to raise_error(ArgumentError, /patch_lead_p_ids is gone/) end + + it "refuses a program key that is not a patch slug" do + allow(described_class).to receive(:config) + .and_return({ programs: { project_x: { name: "Project X", grant_cap: nil } } }) + + expect { described_class.programs }.to raise_error(ArgumentError, /a program key is a patch slug/) + end end diff --git a/spec/services/role_registry_spec.rb b/spec/services/role_registry_spec.rb index 59bbbd46..65549f3d 100644 --- a/spec/services/role_registry_spec.rb +++ b/spec/services/role_registry_spec.rb @@ -33,7 +33,7 @@ def changed(&block) "staff" => %w[admin admin], "contractor" => %w[admin admin], "patch_lead" => %w[owner_proposes_board_approves owner], - "patch_viewer" => %w[admin admin] + "patch_viewer" => %w[owner admin] ) expect(described_class.fetch("verifier").grant.preconditions_at_approval).to eq(%w[verified_by_another adult]) expect(described_class.fetch("verifier").grant.preconditions_at_proposal).to eq([]) From 4bad5e16a704dab89bf9474dc6a7e7ff90706652 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:40:40 +0000 Subject: [PATCH 4/9] chore: autofix annotations and lint --- config/routes.rb | 7 +++++++ spec/factories/patches.rb | 22 ++++++++++++++++++++++ spec/models/patch_spec.rb | 22 ++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/config/routes.rb b/config/routes.rb index cdbdc1e0..ecad1edd 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -203,6 +203,13 @@ # admin_break_glass_report GET /admin/break_glass_report(.:format) admin/break_glass_reports#show # review_admin_guardian_consent PATCH /admin/guardian_consents/:id/review(.:format) admin/guardian_consents#review # admin_guardian_consents GET /admin/guardian_consents(.:format) admin/guardian_consents#index +# admin_patches GET /admin/patches(.:format) admin/patches#index +# POST /admin/patches(.:format) admin/patches#create +# new_admin_patch GET /admin/patches/new(.:format) admin/patches#new +# edit_admin_patch GET /admin/patches/:id/edit(.:format) admin/patches#edit +# admin_patch GET /admin/patches/:id(.:format) admin/patches#show +# PATCH /admin/patches/:id(.:format) admin/patches#update +# PUT /admin/patches/:id(.:format) admin/patches#update # role_admin_group_membership PATCH /admin/groups/:group_id/memberships/:id/role(.:format) admin/group_memberships#role # admin_group_memberships POST /admin/groups/:group_id/memberships(.:format) admin/group_memberships#create # admin_group_membership DELETE /admin/groups/:group_id/memberships/:id(.:format) admin/group_memberships#destroy diff --git a/spec/factories/patches.rb b/spec/factories/patches.rb index 9fa12295..50e176f9 100644 --- a/spec/factories/patches.rb +++ b/spec/factories/patches.rb @@ -1,5 +1,27 @@ # frozen_string_literal: true +# == Schema Information +# +# Table name: patches +# Database name: primary +# +# id :bigint not null, primary key +# description :text +# name :string not null +# slug :string not null +# created_at :datetime not null +# updated_at :datetime not null +# created_by_id :bigint +# +# Indexes +# +# index_patches_on_created_by_id (created_by_id) +# index_patches_on_slug (slug) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# FactoryBot.define do factory :patch do sequence(:slug) { |n| "patch-#{n}" } diff --git a/spec/models/patch_spec.rb b/spec/models/patch_spec.rb index a8b30bb6..3da1ef3a 100644 --- a/spec/models/patch_spec.rb +++ b/spec/models/patch_spec.rb @@ -4,6 +4,28 @@ # A patch is a grant program. Apps, Quilt and role scopes name its slug, so the # slug never changes. +# == Schema Information +# +# Table name: patches +# Database name: primary +# +# id :bigint not null, primary key +# description :text +# name :string not null +# slug :string not null +# created_at :datetime not null +# updated_at :datetime not null +# created_by_id :bigint +# +# Indexes +# +# index_patches_on_created_by_id (created_by_id) +# index_patches_on_slug (slug) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# RSpec.describe Patch do it "needs a name and a slug in the slug format" do expect(build(:patch, name: "")).not_to be_valid From ef257eaa0b09c3c4c4ce00592ecebd649504c56c Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 12:05:27 -0500 Subject: [PATCH 5/9] feat: replace the patch viewer role with roles that each patch defines --- .../patch_role_assignments_controller.rb | 65 ++++++ .../admin/patch_roles_controller.rb | 59 ++++++ app/controllers/admin/patches_controller.rb | 14 +- app/helpers/admin_nav_helper.rb | 2 +- app/models/group.rb | 1 + app/models/patch.rb | 6 +- app/models/patch_role.rb | 72 +++++++ app/models/patch_role_assignment.rb | 44 ++++ app/models/user.rb | 1 + app/services/data_categories.rb | 2 +- app/services/deletion_pipeline.rb | 4 +- app/services/patch_roles.rb | 35 ++-- app/services/role_registry.rb | 6 +- app/views/admin/patches/show.html.erb | 190 +++++++++++++++--- app/views/identity/governance/show.html.erb | 4 +- .../initializers/doorkeeper_openid_connect.rb | 7 +- config/roles.yml | 27 +-- config/routes.rb | 7 +- .../20261112130000_create_patch_roles.rb | 33 +++ db/schema.rb | 30 ++- docs/KYC.md | 7 +- docs/OAUTH.md | 33 ++- spec/models/patch_role_spec.rb | 57 ++++++ spec/requests/admin_patch_roles_spec.rb | 108 ++++++++++ spec/requests/admin_patches_spec.rb | 15 +- spec/requests/api/directory_spec.rb | 4 +- spec/requests/oauth/openid_connect_spec.rb | 25 +-- spec/requests/roles_spec.rb | 60 +----- spec/services/patch_roles_spec.rb | 79 +++++--- spec/services/role_registry_spec.rb | 26 +-- 30 files changed, 787 insertions(+), 236 deletions(-) create mode 100644 app/controllers/admin/patch_role_assignments_controller.rb create mode 100644 app/controllers/admin/patch_roles_controller.rb create mode 100644 app/models/patch_role.rb create mode 100644 app/models/patch_role_assignment.rb create mode 100644 db/migrate/20261112130000_create_patch_roles.rb create mode 100644 spec/models/patch_role_spec.rb create mode 100644 spec/requests/admin_patch_roles_spec.rb diff --git a/app/controllers/admin/patch_role_assignments_controller.rb b/app/controllers/admin/patch_role_assignments_controller.rb new file mode 100644 index 00000000..84fca424 --- /dev/null +++ b/app/controllers/admin/patch_role_assignments_controller.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +# Gives a role of a patch to a user or a group, or takes it away (see +# PatchRoleAssignment). Superadmin only, like the roles themselves. +class Admin::PatchRoleAssignmentsController < Admin::BaseController + before_action :set_role + before_action :require_superadmin + + def create + assignee = find_assignee + return redirect_back_to_roles(alert: assignee_not_found_message) unless assignee + + assignment = @role.assignments.new(assignee: assignee, created_by: current_user) + + if assignment.save + redirect_back_to_roles(notice: "#{assignee_label(assignee)} has the #{@role.name} role now.") + else + redirect_back_to_roles(alert: assignment.errors.full_messages.to_sentence) + end + end + + def destroy + assignment = @role.assignments.find_by_public_param!(params[:id]) + assignment.destroy! + redirect_back_to_roles(notice: "#{assignee_label(assignment.assignee)} no longer has the #{@role.name} role.") + end + + private + + def set_role + @patch = Patch.find_by!(slug: params[:patch_id]) + @role = @patch.roles.find_by_public_param!(params[:role_id]) + end + + def require_superadmin + return if current_user.superadmin? + + redirect_to admin_patch_path(@patch), alert: "Only a superadmin can change the roles of a patch." + end + + def assignment_params + params.require(:assignment).permit(:group_id, :email) + end + + def find_assignee + if assignment_params[:group_id].present? + Group.find_by_public_id(assignment_params[:group_id].to_s) + elsif assignment_params[:email].present? + User.find_for_any_email(assignment_params[:email]) + end + end + + def assignee_not_found_message + assignment_params[:group_id].present? ? "That group doesn't exist." : "No user has that email address." + end + + def assignee_label(assignee) + assignee.is_a?(Group) ? "The #{assignee.name} group" : assignee.full_name + end + + def redirect_back_to_roles(**flash) + redirect_to admin_patch_path(@patch, anchor: "roles"), **flash + end + +end diff --git a/app/controllers/admin/patch_roles_controller.rb b/app/controllers/admin/patch_roles_controller.rb new file mode 100644 index 00000000..e9875bf5 --- /dev/null +++ b/app/controllers/admin/patch_roles_controller.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +# Adds a role to a patch, renames it or deletes it (see PatchRole). +# Superadmin only: apps such as Quilt read the role from the `patches` claim, +# so a role can open a patch's finance data. +class Admin::PatchRolesController < Admin::BaseController + before_action :set_patch + before_action :require_superadmin + before_action :set_role, only: [:update, :destroy] + + def create + role = @patch.roles.new(role_params.merge(created_by: current_user)) + + if role.save + redirect_back_to_roles(notice: "The #{role.name} role was added.") + else + redirect_back_to_roles(alert: role.errors.full_messages.to_sentence) + end + end + + # Changes the name and the description. The key never changes. + def update + if @role.update(role_params.except(:key)) + redirect_back_to_roles(notice: "The #{@role.name} role was updated.") + else + redirect_back_to_roles(alert: @role.errors.full_messages.to_sentence) + end + end + + def destroy + @role.destroy! + redirect_back_to_roles(notice: "The #{@role.name} role was deleted.") + end + + private + + def set_patch + @patch = Patch.find_by!(slug: params[:patch_id]) + end + + def set_role + @role = @patch.roles.find_by_public_param!(params[:id]) + end + + def require_superadmin + return if current_user.superadmin? + + redirect_to admin_patch_path(@patch), alert: "Only a superadmin can change the roles of a patch." + end + + def role_params + params.require(:role).permit(:key, :name, :description) + end + + def redirect_back_to_roles(**flash) + redirect_to admin_patch_path(@patch, anchor: "roles"), **flash + end + +end diff --git a/app/controllers/admin/patches_controller.rb b/app/controllers/admin/patches_controller.rb index 7c9fd253..2a209eb7 100644 --- a/app/controllers/admin/patches_controller.rb +++ b/app/controllers/admin/patches_controller.rb @@ -6,9 +6,11 @@ # change its name and description, like groups. The slug never changes, and # there is no delete: role assignments, Quilt and app tokens name the slug. # -# The show page lists the apps linked to the patch and the people with a patch -# role. Grant and revoke a patch role on the user's admin page (see -# Admin::RoleAssignmentsController). +# The show page lists the patch leads, the patch's own roles with who holds +# them, and the apps linked to the patch. A patch lead changes through +# identity governance. The patch's own roles change through +# Admin::PatchRolesController and Admin::PatchRoleAssignmentsController +# (superadmin only). class Admin::PatchesController < Admin::BaseController before_action :set_patch, only: [:show, :edit, :update] before_action :require_superadmin, except: [:index, :show] @@ -20,9 +22,9 @@ def index def show @applications = @patch.applications.order(:name) - @assignments = PatchRoles::NAMES.keys.index_with do |key| - RoleGrants.assignments(key).where(scope: @patch.slug).includes(:granted_by).to_a - end + @leads = RoleGrants.assignments("patch_lead").where(scope: @patch.slug).includes(:granted_by).to_a + @roles = @patch.roles.includes(assignments: :assignee).order(:key) + @groups = Group.order(:name) if current_user.superadmin? end def new diff --git a/app/helpers/admin_nav_helper.rb b/app/helpers/admin_nav_helper.rb index 66200a11..89d52962 100644 --- a/app/helpers/admin_nav_helper.rb +++ b/app/helpers/admin_nav_helper.rb @@ -56,7 +56,7 @@ def admin_nav_groups(user = current_user) %w[role_assignments], :admin) end), (admin_nav_entry("Groups", admin_groups_path, :users_round, "admin teams", %w[groups group_memberships], :admin) if admin), - (admin_nav_entry("Patches", admin_patches_path, :rocket, "admin grant programs ganymede quilt", %w[patches], :admin) if admin), + (admin_nav_entry("Patches", admin_patches_path, :rocket, "admin grant programs ganymede quilt", %w[patches patch_roles patch_role_assignments], :admin) if admin), (if admin admin_nav_entry("Consents", admin_guardian_consents_path, :shield_check, "admin guardian minors review queue", %w[guardian_consents], :admin) diff --git a/app/models/group.rb b/app/models/group.rb index 3278853b..958ef182 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -66,6 +66,7 @@ class Group < ApplicationRecord has_many :access_requests, dependent: nil has_many :application_access_grants, as: :grantee, dependent: :destroy has_many :application_role_assignments, as: :assignee, dependent: :destroy + has_many :patch_role_assignments, as: :assignee, dependent: :destroy before_validation :generate_slug, on: :create diff --git a/app/models/patch.rb b/app/models/patch.rb index d99411ab..30db20a5 100644 --- a/app/models/patch.rb +++ b/app/models/patch.rb @@ -7,8 +7,9 @@ # the patch is created: the model refuses the change, and a database trigger # refuses it too. Renaming a patch changes only its display name. # -# A patch has per-patch roles (patch_lead, patch_viewer in config/roles.yml), -# scoped by the slug, and OAuth apps linked to it (oauth_applications.patch_id). +# A patch has roles: the patch_lead governance role (config/roles.yml), +# scoped by the slug, and the roles a superadmin defines for the patch +# (PatchRole). It also has OAuth apps linked to it (oauth_applications.patch_id). # The `patches` claim sends a person's patch roles to apps (see PatchRoles). # # There is no delete: role assignments, Quilt and app tokens name the slug. @@ -44,6 +45,7 @@ class Patch < ApplicationRecord belongs_to :created_by, class_name: "User", optional: true has_many :applications, class_name: "Doorkeeper::Application", inverse_of: :patch, dependent: :restrict_with_exception + has_many :roles, class_name: "PatchRole", inverse_of: :patch, dependent: :destroy validates :name, presence: true, length: { maximum: 100 } validates :description, length: { maximum: 2000 } diff --git a/app/models/patch_role.rb b/app/models/patch_role.rb new file mode 100644 index 00000000..cd47aff6 --- /dev/null +++ b/app/models/patch_role.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +# A role that a superadmin defines for one patch, such as "viewer". Users get +# it directly or through a group (PatchRoleAssignment). Apps read the keys in +# the `patches` claim (see PatchRoles), so a role can open a patch's data in +# an app such as Quilt. +# +# The key is the stable name that apps see, so it never changes after the +# role is created. Renaming a role changes only its display name. The key +# "lead" is reserved: the claim sends it for the patch_lead role, which +# identity governance grants (config/roles.yml). +# == Schema Information +# +# Table name: patch_roles +# Database name: primary +# +# id :bigint not null, primary key +# description :text +# key :string not null +# name :string not null +# created_at :datetime not null +# updated_at :datetime not null +# created_by_id :bigint +# patch_id :bigint not null +# +# Indexes +# +# index_patch_roles_on_created_by_id (created_by_id) +# index_patch_roles_on_patch_id_and_key (patch_id,key) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# fk_rails_... (patch_id => patches.id) ON DELETE => cascade +# +class PatchRole < ApplicationRecord + include EncodedIds::HashidIdentifiable + set_public_id_prefix :prole + + has_paper_trail + + KEY_FORMAT = ApplicationRole::KEY_FORMAT + # Keys that PatchRoles sends for a governance role (see PatchRoles::LEAD). + RESERVED_KEYS = %w[lead].freeze + + belongs_to :patch + belongs_to :created_by, class_name: "User", optional: true + has_many :assignments, class_name: "PatchRoleAssignment", foreign_key: :role_id, + inverse_of: :role, dependent: :destroy + + validates :name, presence: true, length: { maximum: 100 } + validates :description, length: { maximum: 2000 } + validates :key, presence: true, length: { maximum: 64 }, format: { with: KEY_FORMAT }, + exclusion: { in: RESERVED_KEYS, message: "is reserved for the patch lead" }, + uniqueness: { scope: :patch_id } + validate :key_unchanged, on: :update + + # Roles held by a user, directly or through an unexpired group membership + # (the same rule as ApplicationRole.held_by). + scope :held_by, lambda { |user| + direct = PatchRoleAssignment.where(assignee: user) + via_group = PatchRoleAssignment.where(assignee_type: "Group", assignee_id: user.active_group_memberships.select(:group_id)) + where(id: direct.or(via_group).select(:role_id)) + } + + private + + def key_unchanged + errors.add(:key, "can't be changed after the role is created") if key_changed? + end + +end diff --git a/app/models/patch_role_assignment.rb b/app/models/patch_role_assignment.rb new file mode 100644 index 00000000..ff58be37 --- /dev/null +++ b/app/models/patch_role_assignment.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +# Gives a user, or every active member of a group, one role of one patch (see +# PatchRole). Only a superadmin makes or removes one. +# == Schema Information +# +# Table name: patch_role_assignments +# Database name: primary +# +# id :bigint not null, primary key +# assignee_type :string not null +# created_at :datetime not null +# updated_at :datetime not null +# assignee_id :bigint not null +# created_by_id :bigint +# role_id :bigint not null +# +# Indexes +# +# index_patch_role_assignments_on_assignee (assignee_type,assignee_id) +# index_patch_role_assignments_on_created_by_id (created_by_id) +# index_patch_role_assignments_uniqueness (role_id,assignee_type,assignee_id) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# fk_rails_... (role_id => patch_roles.id) ON DELETE => cascade +# +class PatchRoleAssignment < ApplicationRecord + include EncodedIds::HashidIdentifiable + set_public_id_prefix :pras + + has_paper_trail + + ASSIGNEE_TYPES = %w[User Group].freeze + + belongs_to :role, class_name: "PatchRole", inverse_of: :assignments + belongs_to :assignee, polymorphic: true + belongs_to :created_by, class_name: "User", optional: true + + validates :assignee_type, inclusion: { in: ASSIGNEE_TYPES } + validates :assignee_id, uniqueness: { scope: [:role_id, :assignee_type], message: "already has this role" } + +end diff --git a/app/models/user.rb b/app/models/user.rb index e9b2b8e5..aaaf7cba 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -250,6 +250,7 @@ def self.generate_secure_password has_many :application_access_grants, as: :grantee, dependent: :destroy # OAuth app roles given to this user directly (see ApplicationRole). has_many :application_role_assignments, as: :assignee, dependent: :destroy + has_many :patch_role_assignments, as: :assignee, dependent: :destroy # Records this user created. Nullify on delete so the records survive. has_many :created_services, class_name: "Service", diff --git a/app/services/data_categories.rb b/app/services/data_categories.rb index 2056ab34..786339e2 100644 --- a/app/services/data_categories.rb +++ b/app/services/data_categories.rb @@ -48,7 +48,7 @@ def window_values source_models: %w[Verification#id_document]), Category.new(key: "account_profile", outcome: "deleted", exportable: true, source_models: %w[User EmailAddress UserAddress User::Session User::MagicLink User::Passkey Ahoy::Visit - Ahoy::Message Group::Membership ApplicationAccessGrant ApplicationRoleAssignment AccessRequest + Ahoy::Message Group::Membership ApplicationAccessGrant ApplicationRoleAssignment PatchRoleAssignment AccessRequest Doorkeeper::AccessGrant Doorkeeper::AccessToken TakeoutRequest DormancyWarning ThreadCount::Entry FunderConsent PaperTrail::Version]), Category.new(key: "guardian_contact", outcome: "deleted", exportable: true, diff --git a/app/services/deletion_pipeline.rb b/app/services/deletion_pipeline.rb index b4c87afe..8126a6c9 100644 --- a/app/services/deletion_pipeline.rb +++ b/app/services/deletion_pipeline.rb @@ -40,7 +40,8 @@ class NotRunnable < StandardError; end "GuardianConsent" => { "user_id" => :id }, "AccessRequest" => { "user_id" => :id }, "ApplicationAccessGrant" => { "grantee_type" => "User", "grantee_id" => :id }, - "ApplicationRoleAssignment" => { "assignee_type" => "User", "assignee_id" => :id } + "ApplicationRoleAssignment" => { "assignee_type" => "User", "assignee_id" => :id }, + "PatchRoleAssignment" => { "assignee_type" => "User", "assignee_id" => :id } }.freeze Result = Data.define(:run, :error) do @@ -214,6 +215,7 @@ def version_items(user) "SocialProfile" => user.social_profiles.ids, "ApplicationAccessGrant" => user.application_access_grants.ids, "ApplicationRoleAssignment" => user.application_role_assignments.ids, + "PatchRoleAssignment" => user.patch_role_assignments.ids, "AccessRequest" => user.access_requests.ids, "GuardianConsent" => GuardianConsent.where(user_id: user.id).ids } diff --git a/app/services/patch_roles.rb b/app/services/patch_roles.rb index 3b297449..bee2f1a3 100644 --- a/app/services/patch_roles.rb +++ b/app/services/patch_roles.rb @@ -4,34 +4,35 @@ # in the directory API (see docs/OAUTH.md "Patch claims"). # # This is the contract with Quilt and the other patch apps. Keep the shape: -# a JSON object that maps a patch slug to the sorted list of short role names -# the person actively holds for that patch, for example +# a JSON object that maps a patch slug to the sorted, unique role keys the +# person holds for that patch, for example # -# {"ganymede": ["lead"], "europa": ["viewer"]} +# {"europa": ["viewer"], "ganymede": ["lead", "reviewer"]} # +# - "lead" comes from an active patch_lead role (config/roles.yml, granted +# through identity governance) scoped to the slug. +# - Every other key is a PatchRole that a superadmin defined for the patch, +# held directly or through an active group membership (the same rule as +# AppAccess.role_keys). # - The keys are patch slugs, sorted. Only patches that exist are listed. -# - A revoked role is left out. # - An empty object ({}) when the person holds no patch role. module PatchRoles - # The role key in config/roles.yml => its short name in the claim. Add a - # new per-patch role here, or apps never see it. - NAMES = { - "patch_lead" => "lead", - "patch_viewer" => "viewer" - }.freeze + # The claim key of the patch_lead governance role. PatchRole refuses it as + # a key (PatchRole::RESERVED_KEYS). + LEAD = "lead" # The claim value for one user. def self.for(user) return {} if user.nil? - held = user.active_user_roles.select { |assignment| NAMES.key?(assignment.role.key) && assignment.scope.present? } - return {} if held.empty? + keys = Hash.new { |hash, slug| hash[slug] = [] } - existing = Patch.where(slug: held.map(&:scope).uniq).pluck(:slug).to_set - held.select { |assignment| existing.include?(assignment.scope) } - .group_by(&:scope) - .sort_by(&:first) - .to_h { |slug, assignments| [slug, assignments.map { |assignment| NAMES.fetch(assignment.role.key) }.uniq.sort] } + lead_slugs = user.role_scopes("patch_lead") + Patch.where(slug: lead_slugs).pluck(:slug).each { |slug| keys[slug] << LEAD } if lead_slugs.any? + + PatchRole.held_by(user).joins(:patch).pluck("patches.slug", "patch_roles.key").each { |slug, key| keys[slug] << key } + + keys.sort.to_h { |slug, role_keys| [slug, role_keys.uniq.sort] } end end diff --git a/app/services/role_registry.rb b/app/services/role_registry.rb index e2c170f1..8a491e3a 100644 --- a/app/services/role_registry.rb +++ b/app/services/role_registry.rb @@ -19,10 +19,10 @@ class ConfigError < StandardError; end RULES = (PROPOSAL_RULES + IMMEDIATE_RULES).freeze PRECONDITIONS = %w[verified_by_another verified_or_bootstrap adult].freeze - SCOPE_SOURCES = %w[knot_programs patches].freeze + SCOPE_SOURCES = %w[knot_programs].freeze # Code reads these roles by key, so the config must define each of them. - REQUIRED_KEYS = %w[verifier identity_lead key_holder board staff contractor patch_lead patch_viewer].freeze + REQUIRED_KEYS = %w[verifier identity_lead key_holder board staff contractor patch_lead].freeze ROLE_KEYS = %w[name description scopable scope_source requires grant revoke].freeze RULE_KEYS = %w[rule preconditions_at_proposal preconditions_at_approval].freeze @@ -60,8 +60,6 @@ def scopes_for(key) case definition.scope_source when "knot_programs" then KnotSettings.program_keys - # Read from the database each time: an admin can add a patch. - when "patches" then Patch.order(:slug).pluck(:slug) else [] end end diff --git a/app/views/admin/patches/show.html.erb b/app/views/admin/patches/show.html.erb index a4670bda..3e8bfcac 100644 --- a/app/views/admin/patches/show.html.erb +++ b/app/views/admin/patches/show.html.erb @@ -36,49 +36,183 @@
    -
    +
    -

    People

    - <%= badge(@assignments.values.sum(&:size).to_s) %> +

    Patch leads

    + <%= badge(@leads.size.to_s) %>
    -

    Grant or revoke a patch role in the roles section of the user's admin page.

    +

    + Apps get the key lead for them. A patch lead changes through the + <%= link_to "identity governance page", identity_governance_path, class: "link" %>. +

    - <% if @assignments.values.any?(&:any?) %> + <% if @leads.any? %>
      - <% @assignments.each do |key, assignments| %> - <% definition = RoleRegistry.fetch(key) %> - <% assignments.each do |assignment| %> - <% user = assignment.user %> -
    • -
      -

      - <% if user %> - <%= link_to user.full_name, admin_user_path(user, anchor: "roles"), class: "link-quiet" %> - (<%= user.p_id %>) - <% else %> - A deleted user - <% end %> -

      -

      - Since <%= time_label(assignment.granted_at) %>. - Granted by <%= assignment.granted_by&.full_name || "Weave" %>. -

      -
      - <%= badge(definition.name, tone: key == "patch_lead" ? :info : :neutral) %> -
    • - <% end %> + <% @leads.each do |assignment| %> + <% user = assignment.user %> +
    • +
      +

      + <% if user %> + <%= link_to user.full_name, admin_user_path(user, anchor: "roles"), class: "link-quiet" %> + (<%= user.p_id %>) + <% else %> + A deleted user + <% end %> +

      +

      + Since <%= time_label(assignment.granted_at) %>. + Granted by <%= assignment.granted_by&.full_name || "Weave" %>. +

      +
      +
    • <% end %>
    <% else %> - <%= empty_state("Nobody has a role for this patch.", icon: :user_round) %> + <%= empty_state("This patch has no lead.", icon: :user_round) %> <% end %>
    +
    +
    +
    +

    Roles

    +

    + Roles this patch defines. Apps read the keys from the patches claim, + and a role can open the patch's finances in Quilt. +

    +
    +
    + +
    + <% if @roles.any? %> + <% @roles.each do |role| %> +
    +
    +
    +

    + <%= role.name %> + <%= role.key %> +

    + <% if role.description.present? %> +

    <%= role.description %>

    + <% end %> +
    + <% if current_user.superadmin? %> + <%= button_to "Delete role", admin_patch_role_path(@patch, role), method: :delete, + class: "btn btn-danger btn-sm", + data: { turbo_confirm: "Delete the #{role.name} role? Everyone loses it." } %> + <% end %> +
    + + <% if role.assignments.any? %> +
    + <% role.assignments.sort_by { |assignment| [assignment.assignee_type, assignment.created_at] }.each do |assignment| %> +
    +
    + <% if assignment.assignee.is_a?(Group) %> + <%= badge "Group", tone: :teal %> + <%= link_to assignment.assignee.name, admin_group_path(assignment.assignee), class: "record-title link-quiet" %> + <% else %> + <%= badge "User", tone: :sky %> + <%= link_to assignment.assignee.full_name, admin_user_path(assignment.assignee), class: "record-title link-quiet" %> + <%= assignment.assignee.email %> + <% end %> +
    + <% if current_user.superadmin? %> +
    + <%= button_to "Remove", admin_patch_role_assignment_path(@patch, role, assignment), method: :delete, + class: "btn btn-danger btn-sm", + data: { turbo_confirm: "Remove this role assignment?" } %> +
    + <% end %> +
    + <% end %> +
    + <% else %> +

    Nobody has this role.

    + <% end %> + + <% if current_user.superadmin? %> +
    + <%= form_with scope: :assignment, url: admin_patch_role_assignments_path(@patch, role), local: true, + class: "flex items-end gap-2" do |form| %> +
    + <%= form.label :group_id, "Give to a group", class: "field-label", for: "patch_role_#{role.id}_group_id" %> + <%= form.select :group_id, @groups.map { |group| [group.name, group.public_id] }, + { include_blank: "Choose a group" }, required: true, id: "patch_role_#{role.id}_group_id", class: "field field-sm" %> +
    + <%= form.submit "Add", class: "btn btn-secondary btn-sm" %> + <% end %> + <%= form_with scope: :assignment, url: admin_patch_role_assignments_path(@patch, role), local: true, + class: "flex items-end gap-2" do |form| %> +
    + <%= form.label :email, "Give to a user", class: "field-label", for: "patch_role_#{role.id}_email" %> + <%= form.email_field :email, required: true, placeholder: "person@example.com", id: "patch_role_#{role.id}_email", class: "field field-sm" %> +
    + <%= form.submit "Add", class: "btn btn-secondary btn-sm" %> + <% end %> +
    + +
    + Rename <%= role.name %> + <%= form_with scope: :role, url: admin_patch_role_path(@patch, role), method: :patch, local: true, + class: "mt-3 flex flex-col md:flex-row md:items-end gap-3" do |form| %> +
    +
    + <%= form.label :name, "Name", class: "field-label", for: "patch_role_#{role.id}_name" %> + <%= form.text_field :name, value: role.name, required: true, id: "patch_role_#{role.id}_name", class: "field field-sm" %> +
    +
    + <%= form.label :description, class: "field-label", for: "patch_role_#{role.id}_description" do %>Description (optional)<% end %> + <%= form.text_field :description, value: role.description, id: "patch_role_#{role.id}_description", class: "field field-sm" %> +
    +
    + <%= form.submit "Save role", class: "btn btn-secondary btn-sm" %> + <% end %> +
    + <% end %> +
    + <% end %> + <% else %> +

    This patch has no roles.

    + <% end %> + + <% if current_user.superadmin? %> +
    + <%= form_with scope: :role, url: admin_patch_roles_path(@patch), local: true, + class: "flex flex-col md:flex-row md:items-end gap-3" do |form| %> +
    +
    + <%= form.label :key, "Key", class: "field-label", for: "new_patch_role_key" %> + <%= form.text_field :key, required: true, placeholder: "viewer", id: "new_patch_role_key", class: "field" %> +
    +
    + <%= form.label :name, "Name", class: "field-label", for: "new_patch_role_name" %> + <%= form.text_field :name, required: true, placeholder: "Viewer", id: "new_patch_role_name", class: "field" %> +
    +
    + <%= form.label :description, class: "field-label", for: "new_patch_role_description" do %>Description (optional)<% end %> + <%= form.text_field :description, id: "new_patch_role_description", class: "field" %> +
    +
    + <%= form.submit "Add role", class: "btn btn-secondary" %> + <% end %> +

    + The key can't change after the role is created. Use lowercase letters, digits, -, + _ or :. The key lead is + reserved for the patch lead. +

    +
    + <% end %> +
    +
    +
    diff --git a/app/views/identity/governance/show.html.erb b/app/views/identity/governance/show.html.erb index 52f03550..cf536d4d 100644 --- a/app/views/identity/governance/show.html.erb +++ b/app/views/identity/governance/show.html.erb @@ -59,7 +59,7 @@

    Each role, who has it, and its grant rule. Staff and contractor change on the <%= link_to "staff and contractors page", admin_role_assignments_path, class: "link" %>, - and board member, patch viewer and the removal of a patch lead on the roles section of a user's admin page. + and board member and the removal of a patch lead on the roles section of a user's admin page.

    @@ -69,7 +69,7 @@ <% assignments = @role_assignments.fetch(definition.key, []) %>
  • - <%= definition.name %><%= " (scoped by patch)" if definition.scopable? %> + <%= definition.name %><%= " (scoped by program)" if definition.scopable? %> Grant: <%= RoleGrants.rule_text(definition.key, :grant) %> Revoke: <%= RoleGrants.rule_text(definition.key, :revoke) %>

    diff --git a/config/initializers/doorkeeper_openid_connect.rb b/config/initializers/doorkeeper_openid_connect.rb index b5de5ccd..b3b41fc8 100644 --- a/config/initializers/doorkeeper_openid_connect.rb +++ b/config/initializers/doorkeeper_openid_connect.rb @@ -241,9 +241,10 @@ def test_key end # The user's roles for each patch (see PatchRoles): a JSON object that - # maps a patch slug to the sorted short role names, for example - # {"ganymede": ["lead"]}. An empty object when none. Quilt depends on this - # shape: keep it. + # maps a patch slug to the sorted role keys, for example + # {"ganymede": ["lead", "viewer"]}: "lead" for a patch lead, and the keys of + # the roles the patch defines (PatchRole). An empty object when none. Quilt + # depends on this shape: keep it. # Only an app whose scopes field lists `patches` gets it. Doorkeeper lets # an app with an empty scopes field ask for any user scope, and the patch # roster must not reach such an app. diff --git a/config/roles.yml b/config/roles.yml index a84204a6..810c8381 100644 --- a/config/roles.yml +++ b/config/roles.yml @@ -16,10 +16,6 @@ # program key). false: the role is global. # scope_source For a scopable role: where the valid scopes come from. # knot_programs = the program keys in config/kyc/knot.yml. -# patches = the slugs of the patches table (see Patch). -# Each knot.yml program has a patch with the same slug -# (Patch.sync_programs!), so both sources name the same -# program the same way. # requires Roles the person must hold first. Revoking a required # role revokes this role too. # grant, revoke The rule for each direction: @@ -109,14 +105,15 @@ roles: revoke: rule: admin - # The patch roles go to apps in the `patches` claim (see PatchRoles). + # A patch lead goes to apps as "lead" in the `patches` claim (see + # PatchRoles). Other patch roles are not here: a superadmin defines them for + # each patch (PatchRole). patch_lead: name: Patch lead description: Leads a grant program. Records grants and asks for a grant over the cap. scopable: true - # knot_programs, not patches: the Knot records grants by program key, and - # a program key is valid without a patches row. Each program key also has - # a patch (Patch.sync_programs!). + # The Knot records grants by program key. Each program key also has a + # patch with the same slug (Patch.sync_programs!). scope_source: knot_programs # LOCKED (2026-10-20): a patch lead must be ID-verified, like a key holder. grant: @@ -125,17 +122,3 @@ roles: preconditions_at_approval: [verified_by_another] revoke: rule: owner - - # Added 2026-11-12 by Jasper: a read-only role for one patch. Quilt shows - # the patch's finances to a patch viewer. An owner grants it, because it - # opens finance data in Quilt, like a Quilt app role (superadmin only). Any - # admin can revoke it, so access is quick to take away. - patch_viewer: - name: Patch viewer - description: Sees one patch's finances in apps such as Quilt. Read only. - scopable: true - scope_source: patches - grant: - rule: owner - revoke: - rule: admin diff --git a/config/routes.rb b/config/routes.rb index ecad1edd..714d297b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -827,7 +827,12 @@ # Patches: the grant programs (see Patch). No destroy: the slug is # named by role assignments, Quilt and app tokens. - resources :patches, only: [:index, :show, :new, :create, :edit, :update] + resources :patches, only: [:index, :show, :new, :create, :edit, :update] do + # The roles a superadmin defines for the patch (see PatchRole). + resources :roles, controller: "patch_roles", only: [:create, :update, :destroy] do + resources :assignments, controller: "patch_role_assignments", only: [:create, :destroy] + end + end resources :groups do resources :memberships, controller: "group_memberships", only: [:create, :destroy] do diff --git a/db/migrate/20261112130000_create_patch_roles.rb b/db/migrate/20261112130000_create_patch_roles.rb new file mode 100644 index 00000000..58e1546a --- /dev/null +++ b/db/migrate/20261112130000_create_patch_roles.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +# Roles that a superadmin defines for one patch, such as "viewer" or +# "reviewer", and who holds them: a user, or every active member of a group +# (see PatchRole, PatchRoleAssignment and PatchRoles). The same design as +# application_roles and application_role_assignments. +class CreatePatchRoles < ActiveRecord::Migration[8.1] + def change + create_table :patch_roles do |t| + t.references :patch, null: false, index: false, foreign_key: { on_delete: :cascade } + t.string :key, null: false + t.string :name, null: false + t.text :description + t.references :created_by, foreign_key: { to_table: :users, on_delete: :nullify } + + t.timestamps + end + + add_index :patch_roles, [:patch_id, :key], unique: true + + create_table :patch_role_assignments do |t| + t.references :role, null: false, index: false, foreign_key: { to_table: :patch_roles, on_delete: :cascade } + t.references :assignee, null: false, polymorphic: true + t.references :created_by, foreign_key: { to_table: :users, on_delete: :nullify } + + t.timestamps + end + + add_index :patch_role_assignments, [:role_id, :assignee_type, :assignee_id], unique: true, + name: "index_patch_role_assignments_uniqueness" + end + +end diff --git a/db/schema.rb b/db/schema.rb index e4a7069e..82deb4bf 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_12_120100) do +ActiveRecord::Schema[8.1].define(version: 2026_11_12_130000) do # These are extensions that must be enabled in order to support this database enable_extension "fuzzystrmatch" enable_extension "pg_catalog.plpgsql" @@ -897,6 +897,30 @@ t.index ["access_grant_id"], name: "index_oauth_openid_requests_on_access_grant_id" end + create_table "patch_role_assignments", force: :cascade do |t| + t.bigint "role_id", null: false + t.string "assignee_type", null: false + t.bigint "assignee_id", null: false + t.bigint "created_by_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["assignee_type", "assignee_id"], name: "index_patch_role_assignments_on_assignee" + t.index ["created_by_id"], name: "index_patch_role_assignments_on_created_by_id" + t.index ["role_id", "assignee_type", "assignee_id"], name: "index_patch_role_assignments_uniqueness", unique: true + end + + create_table "patch_roles", force: :cascade do |t| + t.bigint "patch_id", null: false + t.string "key", null: false + t.string "name", null: false + t.text "description" + t.bigint "created_by_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["created_by_id"], name: "index_patch_roles_on_created_by_id" + t.index ["patch_id", "key"], name: "index_patch_roles_on_patch_id_and_key", unique: true + end + create_table "patches", force: :cascade do |t| t.string "slug", null: false t.string "name", null: false @@ -1493,6 +1517,10 @@ add_foreign_key "oauth_applications", "groups", column: "access_request_group_id", on_delete: :nullify add_foreign_key "oauth_applications", "patches" add_foreign_key "oauth_openid_requests", "oauth_access_grants", column: "access_grant_id", on_delete: :cascade + add_foreign_key "patch_role_assignments", "patch_roles", column: "role_id", on_delete: :cascade + add_foreign_key "patch_role_assignments", "users", column: "created_by_id", on_delete: :nullify + add_foreign_key "patch_roles", "patches", on_delete: :cascade + add_foreign_key "patch_roles", "users", column: "created_by_id", on_delete: :nullify add_foreign_key "patches", "users", column: "created_by_id", on_delete: :nullify add_foreign_key "program_grants", "knots" add_foreign_key "program_participations", "users", on_delete: :nullify diff --git a/docs/KYC.md b/docs/KYC.md index fc7af4a9..4663c7ee 100644 --- a/docs/KYC.md +++ b/docs/KYC.md @@ -414,9 +414,8 @@ Jasper locked this design on 2026-10-20. Staff and identity roles are rows in a | Staff | `staff` | none | any admin, at once | any admin, at once | | Contractor | `contractor` | none | any admin, at once | any admin, at once | | Patch lead | `patch_lead` | a program key from `config/kyc/knot.yml` | an owner proposes, a different board member approves. Verified by another verifier | one owner, at once | -| Patch viewer | `patch_viewer` | a patch slug (the `patches` table) | one owner, at once | any admin, at once | -- Patches and their roles: Jasper added the patch viewer role and the `patches` scope source on 2026-11-12. A patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead keeps the `knot_programs` scope source, because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch roles in the `patches` claim (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). +- Patches and their roles (added 2026-11-12): a patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead is scoped by program key (`knot_programs`), because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch lead as the key `lead` in the `patches` claim. The other patch roles are not in `config/roles.yml`: a superadmin defines them for each patch on the patch page (`PatchRole`, `PatchRoleAssignment`), and gives them to users or groups (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). - The identity lead and the key holder need the verifier role first (`requires`). A revoke of the verifier role also revokes them. - The rules `owner` and `admin` also need the actor to manage the person in the admin panel (`UserAdminPermissions#manage?`): an admin changes only people below them, or themselves. The board role uses `any_owner` instead (locked 2026-10-20): any owner changes the board role of any person, other owners too. - A new identity lead, key holder or patch lead must be ID-verified by another verifier. Weave checks this at the proposal and again at the approval (`preconditions_at_proposal` and `preconditions_at_approval`). @@ -429,7 +428,7 @@ flowchart TD R -->|rule of each role| G[RoleGrants] P[Proposal rule: verifier, lead, key holder, new patch lead] --> IG[IdentityGovernance: propose, approve] IG -->|grant! or revoke!| G - I[Immediate rule: board, staff, contractor, patch viewer, patch lead removal, verifier removal] -->|RoleGrants.grant or .revoke| G + I[Immediate rule: board, staff, contractor, patch lead removal, verifier removal] -->|RoleGrants.grant or .revoke| G G -->|insert or set revoked_at| UR[(user_roles)] UR -->|trigger log_user_role_changes| L[(privileged_attribute_changes)] UR -->|after commit| SG[SystemGroups: staff, board, contractors, identity-team] @@ -440,7 +439,7 @@ flowchart TD - A proposal role (verifier, identity lead, key holder, a new patch lead) changes on `/identity/governance`. A patch lead proposal (`add_patch_lead`) names the program. - Staff and contractor change on `/admin/role_assignments` (the staff and contractors page), or in the roles section of the admin user page (`/admin/users/:id`). -- Board member and the removal of a patch lead change in the roles section of `/admin/users/:id`. Only an owner sees the forms. Any admin grants and revokes a patch viewer there, for a person they can manage. The patch page (`/admin/patches/:slug`) lists the leads and the viewers of the patch. The roles section is on the user page, not the edit page, because an owner can open the page of another owner but not edit it. +- Board member and the removal of a patch lead change in the roles section of `/admin/users/:id`. Only an owner sees the forms. The patch page (`/admin/patches/:slug`) lists the leads of the patch. The roles section is on the user page, not the edit page, because an owner can open the page of another owner but not edit it. - A verifier is removed with the removal form on `/identity/governance`. `RoleGrants.revoke` sends a verifier removal to `IdentityGovernance.remove_member`. - The governance page lists each role, its holders (with the scope) and its rules. diff --git a/docs/OAUTH.md b/docs/OAUTH.md index 6b7840f5..929c5d5d 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -366,31 +366,37 @@ change after a group is created, so clients can compare them safely. A patch is a grant program of Patchwork Labs, for example Project Ganymede. Weave keeps the patches in `/admin/patches`. Each patch has a slug, such as `ganymede`, that never changes. It is the same slug as in Quilt. A person can -hold a role for a patch: +hold roles for a patch: -| Role | Short name | Who grants it | +| Key | Where it comes from | Who gives it | |---|---|---| -| Patch lead (`patch_lead`) | `lead` | an owner proposes, a board member approves (see `docs/KYC.md` "Roles") | -| Patch viewer (`patch_viewer`) | `viewer` | an owner grants it and any admin revokes it, on the user's admin page | +| `lead` | the `patch_lead` governance role, scoped to the patch slug | an owner proposes, a board member approves (see `docs/KYC.md` "Roles") | +| any other key, for example `viewer` | a role that the patch defines (`PatchRole`) | a superadmin, in the "Roles" panel on the patch page (`/admin/patches/:slug`), to a user or a group | + +A superadmin defines the roles of each patch, the same way as app roles (see +"App roles"). A role key never changes after the role is created, and the key +`lead` is reserved. A person holds a patch role directly or through an +unexpired group membership. An app reads the keys it knows and ignores the +rest, so a new role on a patch never breaks an app. Request the `patches` scope to get a `patches` claim in the ID token and the userinfo response. The value is a JSON object. Each key is a patch slug, and -each value is the sorted list of the short names of the roles that the user -holds for that patch: +each value is the sorted list of the role keys that the user holds for that +patch, each key once: ```json -"patches": {"europa": ["viewer"], "ganymede": ["lead"]} +"patches": {"europa": ["viewer"], "ganymede": ["lead", "reviewer"]} ``` Rules: - The object is empty (`{}`) when the user holds no patch role. -- Only active roles count. A revoked role is left out at once, at the next token or userinfo call. +- Only active roles count. A revoked lead, a removed assignment, a deleted role and an expired group membership are left out at once, at the next token or userinfo call. - Only patches that exist in Weave are listed. - The keys are sorted. A slug never changes, so clients can compare it safely. - The app's scopes field must list `patches`. An app with an empty scopes field gets `{}`. - A patch role does not open an app whose access policy is restricted. Give the person an access grant too, or keep the app open to everyone and let it refuse people with no role. -- An app reads the claim at sign-in. A revoked role stays in the app's session until the person signs in again. +- An app reads the claim at sign-in. A removed role stays in the app's session until the person signs in again. Check the directory API again before an action that matters. - `PatchRoles` (`app/services/patch_roles.rb`) builds the value. Quilt depends on this shape. Do not change it without a change in Quilt. The directory API sends the same object as `patches` when the app's scopes @@ -399,8 +405,13 @@ list `patches` (see "Directory API"). ```mermaid flowchart LR P[(patches: ganymede)] --> UR[user_roles: patch_lead, scope ganymede] - UR --> PR[PatchRoles] - PR --> C["patches claim: {ganymede: [lead]}"] + P --> R[patch_roles: viewer] + U[User] -->|direct| A[patch_role_assignments] + U -->|member| G[Group] -->|assignee| A + A --> R + UR -->|lead| PR[PatchRoles] + R -->|viewer| PR + PR --> C["patches claim: {ganymede: [lead, viewer]}"] PR --> D[Directory API: patches] ``` diff --git a/spec/models/patch_role_spec.rb b/spec/models/patch_role_spec.rb new file mode 100644 index 00000000..5b27bfb4 --- /dev/null +++ b/spec/models/patch_role_spec.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +require "rails_helper" + +# A role that a superadmin defines for one patch. Apps see the key, so it never +# changes, and "lead" belongs to the patch_lead governance role. +RSpec.describe PatchRole do + let(:patch) { create(:patch, slug: "ganymede") } + + it "needs a name and a key in the key format" do + expect(patch.roles.build(key: "viewer", name: "")).not_to be_valid + %w[Viewer view\ er -viewer viewer-].each do |key| + expect(patch.roles.build(key:, name: "Viewer")).not_to be_valid, "expected #{key.inspect} to be refused" + end + expect(patch.roles.build(key: "finance:read", name: "Finance")).to be_valid + end + + it "refuses the reserved key lead" do + role = patch.roles.build(key: "lead", name: "Lead") + + expect(role).not_to be_valid + expect(role.errors[:key]).to include("is reserved for the patch lead") + end + + it "keeps the key unique in a patch, and lets another patch use it" do + patch.roles.create!(key: "viewer", name: "Viewer") + + expect(patch.roles.build(key: "viewer", name: "Viewer 2")).not_to be_valid + expect(create(:patch, slug: "europa").roles.build(key: "viewer", name: "Viewer")).to be_valid + end + + it "never changes the key, and keeps a version of each change" do + role = patch.roles.create!(key: "viewer", name: "Viewer") + + expect(role.update(key: "reader")).to be(false) + expect(role.errors[:key]).to include("can't be changed after the role is created") + role.reload.update!(name: "Finance viewer") + expect(role.versions.map(&:event)).to eq(%w[create update]) + end + + it "gives one assignment for each assignee, and goes with its assignments" do + role = patch.roles.create!(key: "viewer", name: "Viewer") + user = create(:user, :verified) + PatchRoleAssignment.create!(role:, assignee: user) + + expect(PatchRoleAssignment.new(role:, assignee: user)).not_to be_valid + expect { role.destroy! }.to change(PatchRoleAssignment, :count).by(-1) + end + + it "goes when the user or the group goes" do + role = patch.roles.create!(key: "viewer", name: "Viewer") + group = create(:group) + PatchRoleAssignment.create!(role:, assignee: group) + + expect { group.destroy }.to change(PatchRoleAssignment, :count).by(-1) + end +end diff --git a/spec/requests/admin_patch_roles_spec.rb b/spec/requests/admin_patch_roles_spec.rb new file mode 100644 index 00000000..4c02fbb9 --- /dev/null +++ b/spec/requests/admin_patch_roles_spec.rb @@ -0,0 +1,108 @@ +# frozen_string_literal: true + +require "rails_helper" + +# The roles a patch defines, and who holds them. A role can open a patch's +# finances in Quilt, so only a superadmin changes them. Any admin can look. +RSpec.describe "Admin patch roles", type: :request do + let(:admin) { create(:user, :admin, :verified) } + let(:superadmin) { create(:user, :superadmin, :verified) } + let(:member) { create(:user, :verified, email: "member@example.com") } + let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let(:group) { create(:group, name: "Finance") } + + def role(key = "viewer") = ganymede.roles.find_or_create_by!(key:) { |record| record.name = key.titleize } + + context "when signed in as a superadmin" do + before { sign_in_via_magic_link(superadmin) } + + it "adds a role, renames it and deletes it" do + get admin_patch_path(ganymede) + expect(response.body).to include("Add role") + + post admin_patch_roles_path(ganymede), params: { role: { key: "viewer", name: "Viewer", description: "Reads finances." } } + added = ganymede.roles.find_by!(key: "viewer") + expect(added).to have_attributes(name: "Viewer", description: "Reads finances.", created_by: superadmin) + expect(response).to redirect_to(admin_patch_path(ganymede, anchor: "roles")) + + patch admin_patch_role_path(ganymede, added), params: { role: { name: "Finance viewer", description: "", key: "reader" } } + expect(added.reload).to have_attributes(name: "Finance viewer", description: "", key: "viewer") + + delete admin_patch_role_path(ganymede, added) + expect(ganymede.roles.reload).to be_empty + end + + it "refuses the reserved key lead and a bad key" do + post admin_patch_roles_path(ganymede), params: { role: { key: "lead", name: "Lead" } } + expect(flash[:alert]).to include("reserved for the patch lead") + + post admin_patch_roles_path(ganymede), params: { role: { key: "Bad Key", name: "Bad" } } + expect(ganymede.roles.reload).to be_empty + end + + it "gives a role to a user and a group, and takes it away" do + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: member.email } } + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { group_id: group.public_id } } + + expect(role.assignments.map(&:assignee)).to contain_exactly(member, group) + expect(PatchRoles.for(member)).to eq("ganymede" => ["viewer"]) + + assignment = role.assignments.find_by!(assignee: member) + delete admin_patch_role_assignment_path(ganymede, role, assignment) + expect(role.assignments.reload.map(&:assignee)).to eq([group]) + expect(PatchRoles.for(member)).to eq({}) + end + + it "says when the user or the group does not exist" do + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: "nobody@example.com" } } + expect(flash[:alert]).to eq("No user has that email address.") + + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { group_id: "grp_nothing" } } + expect(flash[:alert]).to eq("That group doesn't exist.") + expect(role.assignments).to be_empty + end + + it "finds a role only in its own patch" do + other = create(:patch, slug: "europa").roles.create!(key: "viewer", name: "Viewer") + + delete admin_patch_role_path(ganymede, other) + + expect(response).to have_http_status(:not_found) + expect(PatchRole.exists?(other.id)).to be(true) + end + end + + context "when signed in as a plain admin" do + before { sign_in_via_magic_link(admin) } + + it "sees the roles and refuses every change" do + assignment = PatchRoleAssignment.create!(role:, assignee: member) + + get admin_patch_path(ganymede) + expect(response.body).to include("Viewer", member.full_name) + expect(response.body).not_to include("Add role", "Delete role", "Give to a user") + + post admin_patch_roles_path(ganymede), params: { role: { key: "reviewer", name: "Reviewer" } } + expect(response).to redirect_to(admin_patch_path(ganymede)) + patch admin_patch_role_path(ganymede, role), params: { role: { name: "Renamed" } } + delete admin_patch_role_path(ganymede, role) + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: admin.email } } + delete admin_patch_role_assignment_path(ganymede, role, assignment) + + expect(ganymede.roles.reload.map(&:key)).to eq(["viewer"]) + expect(role.reload.name).to eq("Viewer") + expect(role.assignments.map(&:assignee)).to eq([member]) + end + end + + it "does not exist for a member" do + sign_in_via_magic_link(member) + + post admin_patch_roles_path(ganymede), params: { role: { key: "reviewer", name: "Reviewer" } } + expect(response).to have_http_status(:not_found) + + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: member.email } } + expect(response).to have_http_status(:not_found) + expect(role.assignments).to be_empty + end +end diff --git a/spec/requests/admin_patches_spec.rb b/spec/requests/admin_patches_spec.rb index d6918ff4..2cba9611 100644 --- a/spec/requests/admin_patches_spec.rb +++ b/spec/requests/admin_patches_spec.rb @@ -23,12 +23,16 @@ context "when signed in as a plain admin" do before { sign_in_via_magic_link(admin) } - it "lists and shows patches, with the linked apps and the people with a patch role, with no N+1" do + it "lists and shows patches, with the leads, the roles and their holders, and the linked apps, with no N+1" do # rubocop:disable RSpec/ExampleLength krater = Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb", patch: ganymede) Doorkeeper::Application.create!(name: "Stash", redirect_uri: "https://stash.example.com/cb") - create_list(:user, 2, :verified, :patch_lead) + leads = create_list(:user, 2, :verified, :patch_lead) viewers = create_list(:user, 2, :verified) - viewers.each { |viewer| RoleGrants.grant!(viewer, "patch_viewer", scope: "ganymede", by: owner, reason: "spec") } + %w[viewer reviewer].each do |key| + role = ganymede.roles.create!(key:, name: key.titleize) + viewers.each { |viewer| PatchRoleAssignment.create!(role:, assignee: viewer) } + PatchRoleAssignment.create!(role:, assignee: create(:group, name: "#{key.titleize} group")) + end get admin_patches_path expect(response).to have_http_status(:ok) @@ -37,8 +41,9 @@ get admin_patch_path(ganymede) expect(response).to have_http_status(:ok) - expect(response.body).to include("Project Ganymede", krater.name, "Patch lead", "Patch viewer", viewers.first.full_name) - expect(response.body).not_to include("Stash", edit_admin_patch_path(ganymede)) + expect(response.body).to include("Project Ganymede", krater.name, "Patch leads", leads.first.full_name, "Reviewer", + "viewer", viewers.first.full_name, "Viewer group") + expect(response.body).not_to include("Stash", edit_admin_patch_path(ganymede), "Add role", "Delete role") end it "can't create or edit a patch" do diff --git a/spec/requests/api/directory_spec.rb b/spec/requests/api/directory_spec.rb index 84cd12be..8540f2e9 100644 --- a/spec/requests/api/directory_spec.rb +++ b/spec/requests/api/directory_spec.rb @@ -43,8 +43,8 @@ def directory_get(path, token: app_token, params: {}) end it "gives the patch roles only to an app allowed the patches scope" do - create(:patch, slug: "ganymede", name: "Project Ganymede") - RoleGrants.grant!(reviewer, "patch_viewer", scope: "ganymede", reason: "spec") + ganymede = create(:patch, slug: "ganymede", name: "Project Ganymede") + PatchRoleAssignment.create!(role: ganymede.roles.create!(key: "viewer", name: "Viewer"), assignee: reviewer) expect(directory_get(api_v1_directory_user_path(reviewer.p_id))).not_to have_key("patches") diff --git a/spec/requests/oauth/openid_connect_spec.rb b/spec/requests/oauth/openid_connect_spec.rb index ac10a921..10fdbf5c 100644 --- a/spec/requests/oauth/openid_connect_spec.rb +++ b/spec/requests/oauth/openid_connect_spec.rb @@ -357,17 +357,15 @@ def userinfo(scope:) end describe "the patches claim" do - let(:owner) { create(:user, :owner, :verified) } + let(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let(:europa) { create(:patch, slug: "europa", name: "Europa") } - before do - create(:patch, slug: "ganymede", name: "Project Ganymede") - create(:patch, slug: "europa", name: "Europa") - end + def give(patch, key, to: user) = PatchRoleAssignment.create!(role: patch.roles.find_or_create_by!(key:) { |role| role.name = key.titleize }, assignee: to) - it "maps each patch slug to the user's sorted short role names" do - RoleGrants.grant!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") - RoleGrants.grant!(user, "patch_viewer", scope: "ganymede", by: owner, reason: "spec") - RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + it "maps each patch slug to the lead key and the patch's own role keys, sorted" do + RoleGrants.grant!(user, "patch_lead", scope: ganymede.slug, reason: "spec") + give(ganymede, "viewer") + give(europa, "viewer") expect(userinfo(scope: "openid patches")).to include("patches" => { "europa" => ["viewer"], "ganymede" => %w[lead viewer] }) end @@ -376,22 +374,21 @@ def userinfo(scope:) expect(userinfo(scope: "openid patches")).to include("patches" => {}) end - it "leaves out a revoked role" do - RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") - RoleGrants.revoke!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + it "leaves out a removed role" do + give(europa, "viewer").destroy! expect(userinfo(scope: "openid patches")).to include("patches" => {}) end it "is an empty object for an app whose scopes field does not list patches" do application.update!(scopes: "") - RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + give(europa, "viewer") expect(userinfo(scope: "openid patches")).to include("patches" => {}) end it "is not sent without the patches scope" do - RoleGrants.grant!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + give(europa, "viewer") expect(userinfo(scope: "openid profile")).not_to have_key("patches") end diff --git a/spec/requests/roles_spec.rb b/spec/requests/roles_spec.rb index 5e1606a9..e1c33967 100644 --- a/spec/requests/roles_spec.rb +++ b/spec/requests/roles_spec.rb @@ -20,7 +20,7 @@ get identity_governance_path expect(response).to have_http_status(:ok) - expect(response.body).to include("Roles", "Patch lead (scoped by patch)", "Adam Doe (ganymede)", + expect(response.body).to include("Roles", "Patch lead (scoped by program)", "Adam Doe (ganymede)", "Grant: An owner proposes. Every board member approves.", "Grant: Any admin, at once.", "Revoke: One owner or identity lead, at once.", "· key holder", "· lead") @@ -66,63 +66,5 @@ expect(response.body).to include("Revoke staff", "Revoke patch lead (ganymede)", "Grant board member", "Grant contractor", "To grant it, an owner proposes the change on the identity governance page.") end - - it "lets an owner grant and revoke a patch viewer role for a patch that exists" do - user = create(:user, :verified) - create(:patch, slug: "ganymede", name: "Project Ganymede") - sign_in_via_magic_link(owner) - - get admin_user_path(user) - expect(response.body).to include("Grant patch viewer") - - post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", return_to: "user" } - expect(response).to redirect_to(admin_user_path(user, anchor: "roles")) - expect(user.reload_roles!.role_scopes("patch_viewer")).to eq(["ganymede"]) - - post revoke_admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", reason: "Done." } - expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) - end - - it "does not let an admin who is not an owner grant a patch viewer role, to anyone or to themselves" do - admin = create(:user, :admin, :verified) - user = create(:user, :verified) - create(:patch, slug: "ganymede", name: "Project Ganymede") - sign_in_via_magic_link(admin) - - get admin_user_path(user) - expect(response.body).not_to include("Grant patch viewer") - - [user, admin].each do |target| - post admin_role_assignments_path, params: { user_id: target.p_id, role: "patch_viewer", scope: "ganymede" } - expect(target.reload_roles!.role_scopes("patch_viewer")).to eq([]) - end - end - - it "lets an admin revoke a patch viewer role" do - user = create(:user, :verified) - create(:patch, slug: "ganymede", name: "Project Ganymede") - RoleGrants.grant(user, "patch_viewer", by: owner, scope: "ganymede", reason: "Ganymede finances.") - sign_in_via_magic_link(create(:user, :admin, :verified)) - - post revoke_admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "ganymede", reason: "Done." } - expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) - end - - it "refuses a patch viewer role for a patch that does not exist, and to a member" do - user = create(:user, :verified) - sign_in_via_magic_link(owner) - - get admin_user_path(user) - expect(response.body).not_to include("Grant patch viewer") - - post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "europa" } - expect(flash[:alert]).to include("Not granted") - - create(:patch, slug: "europa") - sign_in_via_magic_link(create(:user, :verified)) - post admin_role_assignments_path, params: { user_id: user.p_id, role: "patch_viewer", scope: "europa" } - expect(response).to have_http_status(:not_found) - expect(user.reload_roles!.role_scopes("patch_viewer")).to eq([]) - end end end diff --git a/spec/services/patch_roles_spec.rb b/spec/services/patch_roles_spec.rb index 0d77b22a..5fb2fa26 100644 --- a/spec/services/patch_roles_spec.rb +++ b/spec/services/patch_roles_spec.rb @@ -6,54 +6,75 @@ RSpec.describe PatchRoles do let(:owner) { create(:user, :owner, :verified) } let(:user) { create(:user, :verified) } + let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let!(:europa) { create(:patch, slug: "europa", name: "Europa") } - before do - create(:patch, slug: "ganymede", name: "Project Ganymede") - create(:patch, slug: "europa", name: "Europa") + def role(patch, key) = patch.roles.find_or_create_by!(key:) { |record| record.name = key.titleize } + + def give(patch, key, to: user) = PatchRoleAssignment.create!(role: role(patch, key), assignee: to) + + def claim = described_class.for(user.reload_roles!) + + it "gives a role held directly" do + give(europa, "viewer") + + expect(claim).to eq("europa" => ["viewer"]) end - def grant(key, scope) = RoleGrants.grant!(user, key, scope:, by: owner, reason: "spec") + it "gives a role held through an active group membership, and not through an expired one" do + finance = create(:group, name: "Finance") + create(:group_membership, group: finance, user:) + give(ganymede, "finance", to: finance) + alumni = create(:group, name: "Alumni") + create(:group_membership, group: alumni, user:, expires_at: 1.day.from_now) + give(europa, "viewer", to: alumni) - it "maps each patch slug to the sorted short role names, with the slugs sorted" do - grant("patch_viewer", "europa") - grant("patch_viewer", "ganymede") - grant("patch_lead", "ganymede") + travel 2.days do + expect(claim).to eq("ganymede" => ["finance"]) + end + end - result = described_class.for(user.reload_roles!) + it "merges the lead key with the patch's own roles, sorted and unique, with the slugs sorted" do + RoleGrants.grant!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") + give(ganymede, "viewer") + give(ganymede, "reviewer") + group = create(:group, name: "Reviewers") + create(:group_membership, group:, user:) + give(ganymede, "reviewer", to: group) + give(europa, "viewer") - expect(result).to eq("europa" => ["viewer"], "ganymede" => %w[lead viewer]) - expect(result.keys).to eq(%w[europa ganymede]) - expect(result.to_json).to eq('{"europa":["viewer"],"ganymede":["lead","viewer"]}') + expect(claim.to_json).to eq('{"europa":["viewer"],"ganymede":["lead","reviewer","viewer"]}') end it "is an empty object for a person with no patch role" do user.update!(is_staff: true) - expect(described_class.for(user.reload_roles!)).to eq({}) + expect(claim).to eq({}) expect(described_class.for(nil)).to eq({}) end - it "leaves out a revoked role" do - grant("patch_viewer", "europa") - grant("patch_lead", "ganymede") - RoleGrants.revoke!(user, "patch_viewer", scope: "europa", by: owner, reason: "spec") + it "leaves out a removed assignment and a deleted role" do + give(europa, "viewer").destroy! + give(ganymede, "reviewer") + role(ganymede, "reviewer").destroy! - expect(described_class.for(user.reload_roles!)).to eq("ganymede" => ["lead"]) + expect(claim).to eq({}) end - it "leaves out a patch that does not exist" do - # A patch lead is scoped by a knot.yml program key, which is valid with no - # patches row. - Patch.find_by!(slug: "ganymede").then { |patch| ActiveRecord::Base.connection.execute("DELETE FROM patches WHERE id = #{patch.id}") } - grant("patch_lead", "ganymede") - grant("patch_viewer", "europa") + it "does not leak a role of another patch or another person" do + give(europa, "viewer", to: create(:user, :verified)) + give(ganymede, "viewer") - expect(described_class.for(user.reload_roles!)).to eq("europa" => ["viewer"]) + expect(claim).to eq("ganymede" => ["viewer"]) end - it "names only scopable roles of config/roles.yml" do - described_class::NAMES.each_key do |key| - expect(RoleRegistry.fetch(key)).to be_scopable - end + it "leaves out a revoked lead, and a lead of a program with no patch" do + RoleGrants.grant!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") + RoleGrants.revoke!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") + expect(claim).to eq({}) + + ActiveRecord::Base.connection.execute("DELETE FROM patches WHERE id = #{ganymede.id}") + RoleGrants.grant!(user, "patch_lead", scope: "ganymede", by: owner, reason: "spec") + expect(claim).to eq({}) end end diff --git a/spec/services/role_registry_spec.rb b/spec/services/role_registry_spec.rb index 65549f3d..d4079629 100644 --- a/spec/services/role_registry_spec.rb +++ b/spec/services/role_registry_spec.rb @@ -16,13 +16,12 @@ def changed(&block) delegate :parse, to: :described_class it "loads every role of the locked set from config/roles.yml" do - expect(described_class.keys).to eq(%w[verifier identity_lead key_holder board staff contractor patch_lead patch_viewer]) + expect(described_class.keys).to eq(%w[verifier identity_lead key_holder board staff contractor patch_lead]) expect(described_class.fetch("patch_lead")).to have_attributes(scopable: true, scope_source: "knot_programs") - expect(described_class.fetch("patch_viewer")).to have_attributes(scopable: true, scope_source: "patches") expect(described_class.fetch("key_holder").requires).to eq(["verifier"]) end - it "holds the locked grant rules" do # rubocop:disable RSpec/ExampleLength + it "holds the locked grant rules" do rules = described_class.definitions.transform_values { |definition| [definition.grant.rule, definition.revoke.rule] } expect(rules).to eq( @@ -32,8 +31,7 @@ def changed(&block) "board" => %w[any_owner any_owner], "staff" => %w[admin admin], "contractor" => %w[admin admin], - "patch_lead" => %w[owner_proposes_board_approves owner], - "patch_viewer" => %w[owner admin] + "patch_lead" => %w[owner_proposes_board_approves owner] ) expect(described_class.fetch("verifier").grant.preconditions_at_approval).to eq(%w[verified_by_another adult]) expect(described_class.fetch("verifier").grant.preconditions_at_proposal).to eq([]) @@ -128,24 +126,6 @@ def changed(&block) expect(described_class.valid_scope?("staff", nil)).to be(true) expect(described_class.valid_scope?("staff", "ganymede")).to be(false) end - - it "takes the patch viewer scopes from the patches table" do - expect(described_class.scopes_for("patch_viewer")).to eq([]) - - create(:patch, slug: "europa") - create(:patch, slug: "ganymede") - - expect(described_class.scopes_for("patch_viewer")).to eq(%w[europa ganymede]) - expect(described_class.valid_scope?("patch_viewer", "europa")).to be(true) - expect(described_class.valid_scope?("patch_viewer", "callisto")).to be(false) - expect(described_class.valid_scope?("patch_viewer", nil)).to be(false) - end - - it "gives every Knot program a patch with the same slug, so both scope sources agree" do - Patch.sync_programs! - - expect(described_class.scopes_for("patch_viewer")).to include(*described_class.scopes_for("patch_lead")) - end end describe ".sync!" do From be1477e3b791a707deafcb9955144fdc865ae3a3 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 12:18:38 -0500 Subject: [PATCH 6/9] fix: keep patch roles off system groups, and let only a superadmin add members to a group that holds one --- .../patch_role_assignments_controller.rb | 5 +- app/controllers/admin/patches_controller.rb | 3 +- app/models/group.rb | 5 + app/models/group/membership.rb | 17 ++++ app/models/patch_role_assignment.rb | 17 +++- app/policies/group_policy.rb | 5 +- app/services/access_requests.rb | 6 ++ app/services/patch_roles.rb | 2 +- app/views/admin/groups/show.html.erb | 3 + app/views/admin/patches/show.html.erb | 20 ++-- app/views/groups/show.html.erb | 6 +- .../initializers/doorkeeper_openid_connect.rb | 2 +- docs/KYC.md | 2 +- docs/OAUTH.md | 21 ++++- spec/models/patch_role_spec.rb | 10 ++ spec/requests/admin_patch_roles_spec.rb | 31 ++++++- spec/requests/patch_role_groups_spec.rb | 93 +++++++++++++++++++ spec/services/patch_roles_spec.rb | 7 ++ 18 files changed, 226 insertions(+), 29 deletions(-) create mode 100644 spec/requests/patch_role_groups_spec.rb diff --git a/app/controllers/admin/patch_role_assignments_controller.rb b/app/controllers/admin/patch_role_assignments_controller.rb index 84fca424..8cee2f03 100644 --- a/app/controllers/admin/patch_role_assignments_controller.rb +++ b/app/controllers/admin/patch_role_assignments_controller.rb @@ -1,10 +1,11 @@ # frozen_string_literal: true # Gives a role of a patch to a user or a group, or takes it away (see -# PatchRoleAssignment). Superadmin only, like the roles themselves. +# PatchRoleAssignment). Only a superadmin gives a role, like the roles +# themselves. Any admin takes one away, so access is quick to remove. class Admin::PatchRoleAssignmentsController < Admin::BaseController before_action :set_role - before_action :require_superadmin + before_action :require_superadmin, only: [:create] def create assignee = find_assignee diff --git a/app/controllers/admin/patches_controller.rb b/app/controllers/admin/patches_controller.rb index 2a209eb7..1d2303aa 100644 --- a/app/controllers/admin/patches_controller.rb +++ b/app/controllers/admin/patches_controller.rb @@ -24,7 +24,8 @@ def show @applications = @patch.applications.order(:name) @leads = RoleGrants.assignments("patch_lead").where(scope: @patch.slug).includes(:granted_by).to_a @roles = @patch.roles.includes(assignments: :assignee).order(:key) - @groups = Group.order(:name) if current_user.superadmin? + # Only a manual group can hold a patch role (see PatchRoleAssignment). + @groups = Group.manual.order(:name) if current_user.superadmin? end def new diff --git a/app/models/group.rb b/app/models/group.rb index 958ef182..d107025f 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -91,6 +91,11 @@ def editable? = manual? def managed_by?(user) = user.present? && manual? && manager_memberships.exists?(user_id: user.id) + # A group that holds a patch role gives that role to every member, and a + # patch role can open finance data in Quilt. So only a superadmin adds a + # member to it (see Group::Membership and GroupPolicy#add_member?). + def holds_patch_roles? = patch_role_assignments.exists? + private def generate_slug diff --git a/app/models/group/membership.rb b/app/models/group/membership.rb index 6c1cf4c3..181b8f32 100644 --- a/app/models/group/membership.rb +++ b/app/models/group/membership.rb @@ -71,6 +71,7 @@ class Group::Membership < ApplicationRecord validates :user_id, uniqueness: { scope: :group_id, message: "is already in this group" } validate :expires_in_the_future, if: -> { expires_at.present? && will_save_change_to_expires_at? } validate :manager_is_manual, if: :role_manager? + validate :patch_role_group_added_by_superadmin, if: :joins_group? def expired? = expires_at.present? && expires_at <= Time.current @@ -102,6 +103,22 @@ def expires_in_the_future errors.add(:expires_at, "must be in the future") if expires_at <= Time.current end + # A new row, or an expired row that starts again. + def joins_group? + return true if new_record? + + will_save_change_to_expires_at? && expires_at_in_database.present? && expires_at_in_database <= Time.current + end + + # Every path that adds a member (a group manager, an approved access + # request, the admin panel, a rake task) passes here. + def patch_role_group_added_by_superadmin + return unless group&.holds_patch_roles? + return if added_by&.superadmin? + + errors.add(:base, "Only a superadmin can add a member to #{group.name}, because the group holds patch roles") + end + def manager_is_manual errors.add(:role, "can be manager only in a manual group") unless manual? && group&.manual? end diff --git a/app/models/patch_role_assignment.rb b/app/models/patch_role_assignment.rb index ff58be37..fa1e7838 100644 --- a/app/models/patch_role_assignment.rb +++ b/app/models/patch_role_assignment.rb @@ -1,7 +1,13 @@ # frozen_string_literal: true # Gives a user, or every active member of a group, one role of one patch (see -# PatchRole). Only a superadmin makes or removes one. +# PatchRole). Only a superadmin makes one. Any admin removes one, so access is +# quick to take away. +# +# The group must be a manual group. A system group follows user attributes +# (everyone, staff, admins), so a patch role on it would open the patch to +# anyone who gets the attribute. A superadmin adds the members of a group that +# holds a patch role (see Group#holds_patch_roles?). # == Schema Information # # Table name: patch_role_assignments @@ -40,5 +46,14 @@ class PatchRoleAssignment < ApplicationRecord validates :assignee_type, inclusion: { in: ASSIGNEE_TYPES } validates :assignee_id, uniqueness: { scope: [:role_id, :assignee_type], message: "already has this role" } + validate :group_is_manual + + private + + def group_is_manual + return unless assignee.is_a?(Group) && !assignee.manual? + + errors.add(:assignee, "must be a manual group: a system group follows user attributes") + end end diff --git a/app/policies/group_policy.rb b/app/policies/group_policy.rb index f674f821..b9648b5a 100644 --- a/app/policies/group_policy.rb +++ b/app/policies/group_policy.rb @@ -16,11 +16,12 @@ def manage? end # A sponsored project group waives the code of conduct or the Slack for its - # members, so only a superadmin adds people to it (see Group). + # members, and a group that holds a patch role gives that role to every + # member. So only a superadmin adds people to either (see Group). def add_member? return false unless manage? - user.superadmin? || !(record.waives_code_of_conduct || record.waives_slack) + user.superadmin? || !(record.waives_code_of_conduct || record.waives_slack || record.holds_patch_roles?) end # The groups listed on /groups: the ones the user manages. diff --git a/app/services/access_requests.rb b/app/services/access_requests.rb index f4c6cd52..20209530 100644 --- a/app/services/access_requests.rb +++ b/app/services/access_requests.rb @@ -74,6 +74,12 @@ def approve!(request, by:) raise Error, "#{request.application.name} no longer takes requests through #{request.group.name}." end + # A group that holds a patch role takes new members only from a + # superadmin (see Group#holds_patch_roles?). + if request.group.holds_patch_roles? && !by&.superadmin? + raise Error, "Only a superadmin can approve this request: #{request.group.name} holds patch roles." + end + membership = request.group.memberships.find_or_initialize_by(user: request.user) if membership.new_record? || membership.expired? # A renewed row starts again as a plain member: only a superadmin diff --git a/app/services/patch_roles.rb b/app/services/patch_roles.rb index bee2f1a3..6af28e37 100644 --- a/app/services/patch_roles.rb +++ b/app/services/patch_roles.rb @@ -7,7 +7,7 @@ # a JSON object that maps a patch slug to the sorted, unique role keys the # person holds for that patch, for example # -# {"europa": ["viewer"], "ganymede": ["lead", "reviewer"]} +# {"europa": ["reviewer"], "ganymede": ["lead", "quilt:viewer", "reviewer"]} # # - "lead" comes from an active patch_lead role (config/roles.yml, granted # through identity governance) scoped to the slug. diff --git a/app/views/admin/groups/show.html.erb b/app/views/admin/groups/show.html.erb index 16f533e4..6e07d31c 100644 --- a/app/views/admin/groups/show.html.erb +++ b/app/views/admin/groups/show.html.erb @@ -38,6 +38,9 @@ <% if @group.created_by %>by <%= @group.created_by.full_name %><% end %> <% end %> + <% if @group.holds_patch_roles? %> +

    This group holds patch roles, so only a superadmin adds members. A manager or an access request can't.

    + <% end %> <% if @group.system? %>

    Weave keeps this group in sync from user attributes. You can't change it by hand.

    <% elsif current_user.superadmin? %> diff --git a/app/views/admin/patches/show.html.erb b/app/views/admin/patches/show.html.erb index 3e8bfcac..82f9b763 100644 --- a/app/views/admin/patches/show.html.erb +++ b/app/views/admin/patches/show.html.erb @@ -86,6 +86,7 @@ Roles this patch defines. Apps read the keys from the patches claim, and a role can open the patch's finances in Quilt.

    +

    Quilt reads quilt:viewer. Use an app prefix for a role meant for one app.

  • @@ -124,13 +125,12 @@ <%= assignment.assignee.email %> <% end %> - <% if current_user.superadmin? %> -
    - <%= button_to "Remove", admin_patch_role_assignment_path(@patch, role, assignment), method: :delete, - class: "btn btn-danger btn-sm", - data: { turbo_confirm: "Remove this role assignment?" } %> -
    - <% end %> + <%# Any admin removes an assignment, so access is quick to take away. %> +
    + <%= button_to "Remove", admin_patch_role_assignment_path(@patch, role, assignment), method: :delete, + class: "btn btn-danger btn-sm", + data: { turbo_confirm: "Remove this role assignment?" } %> +
    <% end %> @@ -143,7 +143,7 @@ <%= form_with scope: :assignment, url: admin_patch_role_assignments_path(@patch, role), local: true, class: "flex items-end gap-2" do |form| %>
    - <%= form.label :group_id, "Give to a group", class: "field-label", for: "patch_role_#{role.id}_group_id" %> + <%= form.label :group_id, "Give to a manual group", class: "field-label", for: "patch_role_#{role.id}_group_id" %> <%= form.select :group_id, @groups.map { |group| [group.name, group.public_id] }, { include_blank: "Choose a group" }, required: true, id: "patch_role_#{role.id}_group_id", class: "field field-sm" %>
    @@ -190,7 +190,7 @@
    <%= form.label :key, "Key", class: "field-label", for: "new_patch_role_key" %> - <%= form.text_field :key, required: true, placeholder: "viewer", id: "new_patch_role_key", class: "field" %> + <%= form.text_field :key, required: true, placeholder: "quilt:viewer", id: "new_patch_role_key", class: "field" %>
    <%= form.label :name, "Name", class: "field-label", for: "new_patch_role_name" %> @@ -206,7 +206,7 @@

    The key can't change after the role is created. Use lowercase letters, digits, -, _ or :. The key lead is - reserved for the patch lead. + reserved for the patch lead. Quilt reads quilt:viewer. Use an app prefix for a role meant for one app.

    <% end %> diff --git a/app/views/groups/show.html.erb b/app/views/groups/show.html.erb index 3b27ee22..a5237e95 100644 --- a/app/views/groups/show.html.erb +++ b/app/views/groups/show.html.erb @@ -81,7 +81,11 @@ <% end %>
    <% else %> -

    This group is a sponsored project that waives onboarding steps, so only a superadmin adds members.

    + <% if @group.holds_patch_roles? %> +

    This group holds patch roles, so only a superadmin adds members.

    + <% else %> +

    This group is a sponsored project that waives onboarding steps, so only a superadmin adds members.

    + <% end %> <% end %> <% if @memberships.any? %> diff --git a/config/initializers/doorkeeper_openid_connect.rb b/config/initializers/doorkeeper_openid_connect.rb index b3b41fc8..9527d13b 100644 --- a/config/initializers/doorkeeper_openid_connect.rb +++ b/config/initializers/doorkeeper_openid_connect.rb @@ -242,7 +242,7 @@ def test_key # The user's roles for each patch (see PatchRoles): a JSON object that # maps a patch slug to the sorted role keys, for example - # {"ganymede": ["lead", "viewer"]}: "lead" for a patch lead, and the keys of + # {"ganymede": ["lead", "quilt:viewer"]}: "lead" for a patch lead, and the keys of # the roles the patch defines (PatchRole). An empty object when none. Quilt # depends on this shape: keep it. # Only an app whose scopes field lists `patches` gets it. Doorkeeper lets diff --git a/docs/KYC.md b/docs/KYC.md index 4663c7ee..45c60393 100644 --- a/docs/KYC.md +++ b/docs/KYC.md @@ -415,7 +415,7 @@ Jasper locked this design on 2026-10-20. Staff and identity roles are rows in a | Contractor | `contractor` | none | any admin, at once | any admin, at once | | Patch lead | `patch_lead` | a program key from `config/kyc/knot.yml` | an owner proposes, a different board member approves. Verified by another verifier | one owner, at once | -- Patches and their roles (added 2026-11-12): a patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead is scoped by program key (`knot_programs`), because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch lead as the key `lead` in the `patches` claim. The other patch roles are not in `config/roles.yml`: a superadmin defines them for each patch on the patch page (`PatchRole`, `PatchRoleAssignment`), and gives them to users or groups (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). +- Patches and their roles (added 2026-11-12): a patch (`Patch`, `/admin/patches`) is a grant program. Its slug is the program key in `config/kyc/knot.yml` and the patch slug in Quilt, and it never changes. `Patch.sync_programs!` makes a patch for each program key: the migration `CreatePatches`, `db/seeds.rb` and `bin/rails patches:sync` run it. The patch lead is scoped by program key (`knot_programs`), because the Knot records grants by program key and a program key is valid with no `patches` row. Apps get the patch lead as the key `lead` in the `patches` claim. The other patch roles are not in `config/roles.yml`: a superadmin defines them for each patch on the patch page (`PatchRole`, `PatchRoleAssignment`), and gives them to users or manual groups (see `docs/OAUTH.md` "Patch claims" and `PatchRoles`). - The identity lead and the key holder need the verifier role first (`requires`). A revoke of the verifier role also revokes them. - The rules `owner` and `admin` also need the actor to manage the person in the admin panel (`UserAdminPermissions#manage?`): an admin changes only people below them, or themselves. The board role uses `any_owner` instead (locked 2026-10-20): any owner changes the board role of any person, other owners too. - A new identity lead, key holder or patch lead must be ID-verified by another verifier. Weave checks this at the proposal and again at the approval (`preconditions_at_proposal` and `preconditions_at_approval`). diff --git a/docs/OAUTH.md b/docs/OAUTH.md index 929c5d5d..77afd917 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -371,7 +371,7 @@ hold roles for a patch: | Key | Where it comes from | Who gives it | |---|---|---| | `lead` | the `patch_lead` governance role, scoped to the patch slug | an owner proposes, a board member approves (see `docs/KYC.md` "Roles") | -| any other key, for example `viewer` | a role that the patch defines (`PatchRole`) | a superadmin, in the "Roles" panel on the patch page (`/admin/patches/:slug`), to a user or a group | +| any other key, for example `quilt:viewer` or `reviewer` | a role that the patch defines (`PatchRole`) | a superadmin, in the "Roles" panel on the patch page (`/admin/patches/:slug`), to a user or a manual group | A superadmin defines the roles of each patch, the same way as app roles (see "App roles"). A role key never changes after the role is created, and the key @@ -379,13 +379,24 @@ A superadmin defines the roles of each patch, the same way as app roles (see unexpired group membership. An app reads the keys it knows and ignores the rest, so a new role on a patch never breaks an app. +Give a role that is meant for one app that app's prefix, so another app never +reads it by mistake. Quilt reads only `lead` and `quilt:viewer`: a bare +`viewer` that a patch app uses does not open the patch's finances in Quilt. + +Who changes what: + +- Only a superadmin creates, renames and deletes a patch role, and gives one to a user or a group. +- Any admin removes an assignment, so access is quick to take away. +- Only a manual group can hold a patch role. A system group (`everyone`, `staff`, `admins` and the others) follows user attributes, so Weave refuses it. +- When a group holds a patch role, only a superadmin adds a member to it. A group manager and an approved access request can't. + Request the `patches` scope to get a `patches` claim in the ID token and the userinfo response. The value is a JSON object. Each key is a patch slug, and each value is the sorted list of the role keys that the user holds for that patch, each key once: ```json -"patches": {"europa": ["viewer"], "ganymede": ["lead", "reviewer"]} +"patches": {"europa": ["reviewer"], "ganymede": ["lead", "quilt:viewer", "reviewer"]} ``` Rules: @@ -405,13 +416,13 @@ list `patches` (see "Directory API"). ```mermaid flowchart LR P[(patches: ganymede)] --> UR[user_roles: patch_lead, scope ganymede] - P --> R[patch_roles: viewer] + P --> R[patch_roles: quilt:viewer] U[User] -->|direct| A[patch_role_assignments] U -->|member| G[Group] -->|assignee| A A --> R UR -->|lead| PR[PatchRoles] - R -->|viewer| PR - PR --> C["patches claim: {ganymede: [lead, viewer]}"] + R -->|quilt:viewer| PR + PR --> C["patches claim: {ganymede: [lead, quilt:viewer]}"] PR --> D[Directory API: patches] ``` diff --git a/spec/models/patch_role_spec.rb b/spec/models/patch_role_spec.rb index 5b27bfb4..06b4aac5 100644 --- a/spec/models/patch_role_spec.rb +++ b/spec/models/patch_role_spec.rb @@ -13,6 +13,7 @@ expect(patch.roles.build(key:, name: "Viewer")).not_to be_valid, "expected #{key.inspect} to be refused" end expect(patch.roles.build(key: "finance:read", name: "Finance")).to be_valid + expect(patch.roles.build(key: "quilt:viewer", name: "Quilt viewer")).to be_valid end it "refuses the reserved key lead" do @@ -47,6 +48,15 @@ expect { role.destroy! }.to change(PatchRoleAssignment, :count).by(-1) end + it "refuses a system group, and takes a manual group" do + role = patch.roles.create!(key: "quilt:viewer", name: "Quilt viewer") + assignment = PatchRoleAssignment.new(role:, assignee: create(:group, :system, name: "Everyone", slug: "everyone-test")) + + expect(assignment).not_to be_valid + expect(assignment.errors[:assignee]).to include("must be a manual group: a system group follows user attributes") + expect(PatchRoleAssignment.new(role:, assignee: create(:group))).to be_valid + end + it "goes when the user or the group goes" do role = patch.roles.create!(key: "viewer", name: "Viewer") group = create(:group) diff --git a/spec/requests/admin_patch_roles_spec.rb b/spec/requests/admin_patch_roles_spec.rb index 4c02fbb9..b9bb3501 100644 --- a/spec/requests/admin_patch_roles_spec.rb +++ b/spec/requests/admin_patch_roles_spec.rb @@ -53,6 +53,20 @@ def role(key = "viewer") = ganymede.roles.find_or_create_by!(key:) { |record| re expect(PatchRoles.for(member)).to eq({}) end + it "lists only manual groups, refuses a system group, and shows the Quilt key hint" do + system = create(:group, :system, name: "Everyone else", slug: "everyone-else") + create(:group, name: "Finance team") + role + + get admin_patch_path(ganymede) + expect(response.body).to include("Finance team", "Quilt reads", "quilt:viewer") + expect(response.body).not_to include("Everyone else") + + post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { group_id: system.public_id } } + expect(flash[:alert]).to include("must be a manual group") + expect(role.assignments).to be_empty + end + it "says when the user or the group does not exist" do post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: "nobody@example.com" } } expect(flash[:alert]).to eq("No user has that email address.") @@ -75,11 +89,11 @@ def role(key = "viewer") = ganymede.roles.find_or_create_by!(key:) { |record| re context "when signed in as a plain admin" do before { sign_in_via_magic_link(admin) } - it "sees the roles and refuses every change" do - assignment = PatchRoleAssignment.create!(role:, assignee: member) + it "sees the roles, and is refused every change but a removal" do + PatchRoleAssignment.create!(role:, assignee: member) get admin_patch_path(ganymede) - expect(response.body).to include("Viewer", member.full_name) + expect(response.body).to include("Viewer", member.full_name, "Remove") expect(response.body).not_to include("Add role", "Delete role", "Give to a user") post admin_patch_roles_path(ganymede), params: { role: { key: "reviewer", name: "Reviewer" } } @@ -87,12 +101,21 @@ def role(key = "viewer") = ganymede.roles.find_or_create_by!(key:) { |record| re patch admin_patch_role_path(ganymede, role), params: { role: { name: "Renamed" } } delete admin_patch_role_path(ganymede, role) post admin_patch_role_assignments_path(ganymede, role), params: { assignment: { email: admin.email } } - delete admin_patch_role_assignment_path(ganymede, role, assignment) expect(ganymede.roles.reload.map(&:key)).to eq(["viewer"]) expect(role.reload.name).to eq("Viewer") expect(role.assignments.map(&:assignee)).to eq([member]) end + + it "removes an assignment, so access is quick to take away" do + assignment = PatchRoleAssignment.create!(role:, assignee: member) + + delete admin_patch_role_assignment_path(ganymede, role, assignment) + + expect(response).to redirect_to(admin_patch_path(ganymede, anchor: "roles")) + expect(role.assignments.reload).to be_empty + expect(PatchRoles.for(member)).to eq({}) + end end it "does not exist for a member" do diff --git a/spec/requests/patch_role_groups_spec.rb b/spec/requests/patch_role_groups_spec.rb new file mode 100644 index 00000000..66b21701 --- /dev/null +++ b/spec/requests/patch_role_groups_spec.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require "rails_helper" + +# A group that holds a patch role gives that role to every member, and a patch +# role can open a patch's finances in Quilt. So only a superadmin adds a member +# to such a group, through every path. Removing a member stays as before. +RSpec.describe "Groups that hold patch roles", type: :request do + include ActiveJob::TestHelper + + let(:manager) { create(:user, :verified, :accepted_code_of_conduct) } + let(:member) { create(:user, :verified, :accepted_code_of_conduct) } + let(:superadmin) { create(:user, :superadmin, :verified) } + let(:group) { create(:group, name: "Finance", slug: "finance") } + + before do + create(:group_membership, group:, user: manager, role: "manager") + ganymede = create(:patch, slug: "ganymede", name: "Project Ganymede") + PatchRoleAssignment.create!(role: ganymede.roles.create!(key: "quilt:viewer", name: "Quilt viewer"), assignee: group) + end + + it "refuses a member that a group manager adds, and says why on the group page" do + sign_in_via_magic_link(manager) + + get group_path(group) + expect(response.body).to include("This group holds patch roles, so only a superadmin adds members.") + expect(response.body).not_to include("Add a member by email") + + post group_members_path(group), params: { group_membership: { email: member.email } } + + expect(group.users).not_to include(member) + expect(PatchRoles.for(member)).to eq({}) + end + + it "lets a manager still remove a member" do + membership = create(:group_membership, group:, user: member, added_by: superadmin) + sign_in_via_magic_link(manager) + + delete group_member_path(group, membership) + + expect(Group::Membership.exists?(membership.id)).to be(false) + end + + describe "an access request for an app whose request group holds a patch role" do + let(:request_record) do + application = Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb", + scopes: "openid profile", access_policy: "restricted") + ApplicationAccessGrant.create!(application:, grantee: group) + application.update!(access_request_group: group) + AccessRequest.create!(user: member, application:, group:, reason: "Please") + end + + it "is not approved by a manager, and adds nobody" do + sign_in_via_magic_link(manager) + + patch approve_access_request_path(request_record) + + expect(flash[:alert]).to include("Only a superadmin can approve this request") + expect(request_record.reload).to be_pending + expect(group.users).not_to include(member) + expect(PatchRoles.for(member)).to eq({}) + end + + it "is approved by a superadmin" do + AccessRequests.approve!(request_record, by: superadmin) + + expect(group.users).to include(member) + expect(PatchRoles.for(member)).to eq("ganymede" => ["quilt:viewer"]) + end + end + + it "lets a superadmin add a member in the admin panel" do + sign_in_via_magic_link(superadmin) + + get admin_group_path(group) + expect(response.body).to include("This group holds patch roles, so only a superadmin adds members.") + + post admin_group_memberships_path(group), params: { group_membership: { email: member.email } } + + expect(group.users).to include(member) + expect(PatchRoles.for(member)).to eq("ganymede" => ["quilt:viewer"]) + end + + it "refuses a new member that no superadmin added, at the model, and an expired member who starts again" do + expect(group.memberships.build(user: member).save).to be(false) + expect(group.memberships.build(user: member, added_by: manager).save).to be(false) + + expired = create(:group_membership, group:, user: create(:user, :verified), added_by: superadmin) + expired.update_column(:expires_at, 1.day.ago) # rubocop:disable Rails/SkipsModelValidations + expect(expired.update(expires_at: nil, added_by: manager)).to be(false) + expect(expired.update(expires_at: nil, added_by: superadmin)).to be(true) + end +end diff --git a/spec/services/patch_roles_spec.rb b/spec/services/patch_roles_spec.rb index 5fb2fa26..08271949 100644 --- a/spec/services/patch_roles_spec.rb +++ b/spec/services/patch_roles_spec.rb @@ -46,6 +46,13 @@ def claim = described_class.for(user.reload_roles!) expect(claim.to_json).to eq('{"europa":["viewer"],"ganymede":["lead","reviewer","viewer"]}') end + it "sends an app-prefixed key such as quilt:viewer as it is" do + give(ganymede, "quilt:viewer") + give(ganymede, "viewer") + + expect(claim).to eq("ganymede" => %w[quilt:viewer viewer]) + end + it "is an empty object for a person with no patch role" do user.update!(is_staff: true) From 5843d397f4b902a03e509f9e45b8ecf95475bb87 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:21:35 +0000 Subject: [PATCH 7/9] chore: autofix annotations and lint --- config/routes.rb | 6 ++++++ spec/models/patch_role_spec.rb | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/config/routes.rb b/config/routes.rb index 714d297b..73a8bb15 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -203,6 +203,12 @@ # admin_break_glass_report GET /admin/break_glass_report(.:format) admin/break_glass_reports#show # review_admin_guardian_consent PATCH /admin/guardian_consents/:id/review(.:format) admin/guardian_consents#review # admin_guardian_consents GET /admin/guardian_consents(.:format) admin/guardian_consents#index +# admin_patch_role_assignments POST /admin/patches/:patch_id/roles/:role_id/assignments(.:format) admin/patch_role_assignments#create +# admin_patch_role_assignment DELETE /admin/patches/:patch_id/roles/:role_id/assignments/:id(.:format) admin/patch_role_assignments#destroy +# admin_patch_roles POST /admin/patches/:patch_id/roles(.:format) admin/patch_roles#create +# admin_patch_role PATCH /admin/patches/:patch_id/roles/:id(.:format) admin/patch_roles#update +# PUT /admin/patches/:patch_id/roles/:id(.:format) admin/patch_roles#update +# DELETE /admin/patches/:patch_id/roles/:id(.:format) admin/patch_roles#destroy # admin_patches GET /admin/patches(.:format) admin/patches#index # POST /admin/patches(.:format) admin/patches#create # new_admin_patch GET /admin/patches/new(.:format) admin/patches#new diff --git a/spec/models/patch_role_spec.rb b/spec/models/patch_role_spec.rb index 06b4aac5..ebdc3ddd 100644 --- a/spec/models/patch_role_spec.rb +++ b/spec/models/patch_role_spec.rb @@ -4,6 +4,30 @@ # A role that a superadmin defines for one patch. Apps see the key, so it never # changes, and "lead" belongs to the patch_lead governance role. +# == Schema Information +# +# Table name: patch_roles +# Database name: primary +# +# id :bigint not null, primary key +# description :text +# key :string not null +# name :string not null +# created_at :datetime not null +# updated_at :datetime not null +# created_by_id :bigint +# patch_id :bigint not null +# +# Indexes +# +# index_patch_roles_on_created_by_id (created_by_id) +# index_patch_roles_on_patch_id_and_key (patch_id,key) UNIQUE +# +# Foreign Keys +# +# fk_rails_... (created_by_id => users.id) ON DELETE => nullify +# fk_rails_... (patch_id => patches.id) ON DELETE => cascade +# RSpec.describe PatchRole do let(:patch) { create(:patch, slug: "ganymede") } From 6afd7e0e401d1c0d1c9f41e7f5b90b905ad4cb39 Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 13:13:08 -0500 Subject: [PATCH 8/9] feat: add a task that moves an app's roles to patch roles --- app/services/patch_role_import.rb | 134 ++++++++++++++++++++++++ docs/OAUTH.md | 27 +++++ lib/tasks/patches.rake | 26 +++++ spec/lib/patches_rake_spec.rb | 48 +++++++++ spec/services/patch_role_import_spec.rb | 128 ++++++++++++++++++++++ 5 files changed, 363 insertions(+) create mode 100644 app/services/patch_role_import.rb create mode 100644 spec/lib/patches_rake_spec.rb create mode 100644 spec/services/patch_role_import_spec.rb diff --git a/app/services/patch_role_import.rb b/app/services/patch_role_import.rb new file mode 100644 index 00000000..d96f0c00 --- /dev/null +++ b/app/services/patch_role_import.rb @@ -0,0 +1,134 @@ +# frozen_string_literal: true + +# Copies the roles of one OAuth app into a patch, as patch roles with an app +# prefix (see PatchRole and docs/OAUTH.md "Moving app roles to a patch"). +# For example, Krater's app roles `reviewer` and `admin` become the Ganymede +# patch roles `krater:reviewer` and `krater:admin`. +# +# - Each app role becomes the patch role ":", with the same name +# and description. An existing patch role with that key is kept as it is. +# - Each assignment of the app role becomes a patch role assignment: a user, +# or a manual group. A system group is skipped: it can't hold a patch role +# (see PatchRoleAssignment). +# - group_map gives the patch role of an app role key to a group too, even +# with no app role assignment for it. Manual groups only, the same rule. +# - The app roles and their assignments are never changed: the app reads them +# until it reads the `patches` claim. +# +# A dry run (the default) writes nothing and returns the plan. apply: true +# writes the plan in one transaction, with the actor as created_by and as the +# PaperTrail whodunnit. A second run creates nothing: each item is reported +# as already present. Only a superadmin can be the actor. +module PatchRoleImport + class Error < StandardError; end + + PREFIX_FORMAT = /\A[a-z0-9]+(?:[-_][a-z0-9]+)*\z/ + + # status: :create, :present or :skip. + Step = Data.define(:status, :text) + + Result = Data.define(:steps, :groups, :applied) do + def created = steps.count { |step| step.status == :create } + + def lines + header = applied ? "Applied. Weave wrote the items marked create." : "Dry run. Nothing was written. Run again with APPLY=1 to write it." + list = steps.map { |step| "#{step.status.to_s.ljust(7)} #{step.text}" } + warning = if groups.any? + ["Warning: these groups hold a patch role. Only a superadmin can add members to them now: " \ + "#{groups.map(&:slug).sort.join(', ')}."] + else + [] + end + [header, *list, *warning] + end + end + + class << self + def call(application:, patch:, prefix:, actor:, group_map: {}, apply: false) + check!(application:, patch:, prefix:, actor:) + app_roles = ApplicationRole.for_application(application).includes(assignments: :assignee).order(:key).to_a + extra = map_groups(group_map, app_roles) + + plan = Plan.new(patch:, prefix:, actor:, apply:) + work = -> { app_roles.each { |app_role| plan.add_role(app_role, extra.fetch(app_role.key, [])) } } + if apply + PaperTrail.request(whodunnit: actor.id.to_s) { ApplicationRecord.transaction { work.call } } + else + work.call + end + Result.new(steps: plan.steps, groups: plan.groups.uniq, applied: apply) + end + + private + + def check!(application:, patch:, prefix:, actor:) + raise Error, "Unknown app." if application.nil? + raise Error, "Unknown patch." if patch.nil? + raise Error, "The prefix must be lowercase letters and digits, for example krater." unless prefix.to_s.match?(PREFIX_FORMAT) + raise Error, "The actor must be a superadmin." unless actor&.superadmin? + end + + # { "reviewer" => [group, ...] } from { "krater-reviewers" => "reviewer" }. + def map_groups(group_map, app_roles) + keys = app_roles.map(&:key) + group_map.each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |(slug, key), result| + group = Group.find_by(slug:) + raise Error, "Unknown group #{slug}." if group.nil? + raise Error, "The app has no role #{key} (GROUP_MAP #{slug}:#{key})." unless keys.include?(key) + + result[key] << group + end + end + + end + + # Builds the steps, and writes them when apply is true. + class Plan + attr_reader :steps, :groups + + def initialize(patch:, prefix:, actor:, apply:) + @patch = patch + @prefix = prefix + @actor = actor + @apply = apply + @steps = [] + @groups = [] + end + + def add_role(app_role, extra_groups) + key = "#{@prefix}:#{app_role.key}" + role = @patch.roles.find_by(key:) + if role + @steps << Step.new(status: :present, text: "role #{key} on #{@patch.slug}") + else + @steps << Step.new(status: :create, text: "role #{key} on #{@patch.slug} (#{app_role.name})") + if @apply + role = @patch.roles.create!(key:, name: app_role.name, description: app_role.description, created_by: @actor) + end + end + + assignees = (app_role.assignments.map(&:assignee).compact + extra_groups).uniq + assignees.each { |assignee| add_assignment(role, key, assignee) } + end + + private + + def add_assignment(role, key, assignee) + label = assignee.is_a?(Group) ? "group #{assignee.slug}" : "user #{assignee.email}" + if assignee.is_a?(Group) && !assignee.manual? + @steps << Step.new(status: :skip, text: "#{key} for #{label}: a system group can't hold a patch role") + return + end + + @groups << assignee if assignee.is_a?(Group) + if role&.persisted? && role.assignments.exists?(assignee:) + @steps << Step.new(status: :present, text: "#{key} for #{label}") + else + @steps << Step.new(status: :create, text: "#{key} for #{label}") + PatchRoleAssignment.create!(role:, assignee:, created_by: @actor) if @apply + end + end + + end + +end diff --git a/docs/OAUTH.md b/docs/OAUTH.md index 77afd917..e6d9a65d 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -426,6 +426,33 @@ flowchart LR PR --> D[Directory API: patches] ``` +### Moving app roles to a patch + +An app that kept its patch roles as app roles (see "App roles") can move them +to a patch. For example, Krater's app roles `reviewer` and `admin` become the +Ganymede patch roles `krater:reviewer` and `krater:admin`. `PatchRoleImport` +does the work, and a rake task runs it: + +```bash +bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater \ + ACTOR= GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin +``` + +- Each app role becomes the patch role `:`, with the same name and description. +- Each user who holds the app role gets the patch role. A manual group that holds it gets the patch role too. A system group is skipped and reported: it can't hold a patch role. +- `GROUP_MAP` gives the patch role of an app role key to a manual group, also when no app role assignment exists for it. +- `ACTOR` must be a superadmin. Weave records them as the creator and in the change history. +- The task never changes the app roles or their assignments. +- It prints a warning with each group that holds a patch role. After the move, only a superadmin can add members to those groups. +- Without `APPLY=1` it is a dry run: it prints the plan and writes nothing. With `APPLY=1` it writes the plan in one transaction. A second run creates nothing and reports each item as already present. + +The switch order: + +1. Run the task without `APPLY=1`, and read the plan. +2. Run it again with `APPLY=1`. +3. Add `patches` to the app's scopes, and switch the app to read the `patches` claim (or the directory field). +4. When no running copy of the app reads its app roles, remove the app roles in the app's "Roles" panel. + ### App roles An app can define its own roles, for example `member`, `reviewer` and `admin`. diff --git a/lib/tasks/patches.rake b/lib/tasks/patches.rake index 47bf2151..fb50d418 100644 --- a/lib/tasks/patches.rake +++ b/lib/tasks/patches.rake @@ -11,4 +11,30 @@ namespace :patches do puts "#{patch.slug}: #{patch.name}" end end + + desc "Copy the roles of an OAuth app into a patch (see PatchRoleImport). " \ + "APP= PATCH= PREFIX= ACTOR= " \ + "[GROUP_MAP=slug:role_key,...] [APPLY=1]. A dry run unless APPLY=1." + task import_app_roles: :environment do + app_param = ENV["APP"].to_s + application = Doorkeeper::Application.find_by_public_param(app_param) if app_param.present? + application ||= Doorkeeper::Application.find_by(uid: app_param) if app_param.present? + group_map = ENV["GROUP_MAP"].to_s.split(",").map(&:strip).compact_blank.to_h do |pair| + slug, key = pair.split(":", 2) + abort "GROUP_MAP takes slug:role_key pairs, not #{pair.inspect}." if slug.blank? || key.blank? + [slug, key] + end + + result = PatchRoleImport.call( + application:, + patch: Patch.find_by(slug: ENV["PATCH"].to_s), + prefix: ENV["PREFIX"].to_s, + actor: User.find_for_any_email(ENV["ACTOR"].to_s), + group_map:, + apply: ENV["APPLY"] == "1" + ) + puts result.lines + rescue PatchRoleImport::Error => error + abort error.message + end end diff --git a/spec/lib/patches_rake_spec.rb b/spec/lib/patches_rake_spec.rb new file mode 100644 index 00000000..11381892 --- /dev/null +++ b/spec/lib/patches_rake_spec.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +require "rails_helper" +require "rake" + +# The patch tasks (lib/tasks/patches.rake). +RSpec.describe "patches rake tasks", type: :task do + before(:all) do # rubocop:disable RSpec/BeforeAfterAll + Rails.application.load_tasks unless Rake::Task.task_defined?("patches:import_app_roles") + end + + let(:superadmin) { create(:user, :superadmin, :verified) } + let(:krater) { Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb") } + + before do + create(:patch, slug: "ganymede", name: "Project Ganymede") + role = ApplicationRole.create!(application: krater, key: "reviewer", name: "Reviewer") + ApplicationRoleAssignment.create!(role:, assignee: create(:group, name: "Krater Admins", slug: "krater-admins")) + end + + def run(env) + env.each { |key, value| ENV[key] = value } + Rake::Task["patches:import_app_roles"].reenable + Rake::Task["patches:import_app_roles"].invoke + ensure + env.each_key { |key| ENV.delete(key) } + end + + def env(**extra) = { "APP" => krater.public_id, "PATCH" => "ganymede", "PREFIX" => "krater", "ACTOR" => superadmin.email, **extra } + + it "prints the plan and writes nothing without APPLY=1" do + expect { run(env) }.to output(/Dry run.*create role krater:reviewer.*Warning.*krater-admins/m).to_stdout + expect(PatchRole.count).to eq(0) + end + + it "writes with APPLY=1, and finds the app by its client id too" do + expect { run(env("APP" => krater.uid, "APPLY" => "1")) }.to output(/Applied/).to_stdout + expect(PatchRole.pluck(:key)).to eq(["krater:reviewer"]) + end + + it "stops with a message for an actor who is not a superadmin, and for a bad GROUP_MAP" do + admin = create(:user, :admin, :verified) + + expect { run(env("ACTOR" => admin.email, "APPLY" => "1")) }.to raise_error(SystemExit).and output(/superadmin/).to_stderr + expect { run(env("GROUP_MAP" => "krater-admins")) }.to raise_error(SystemExit).and output(/slug:role_key/).to_stderr + expect(PatchRole.count).to eq(0) + end +end diff --git a/spec/services/patch_role_import_spec.rb b/spec/services/patch_role_import_spec.rb new file mode 100644 index 00000000..d92610cd --- /dev/null +++ b/spec/services/patch_role_import_spec.rb @@ -0,0 +1,128 @@ +# frozen_string_literal: true + +require "rails_helper" + +# Moving an app's roles to a patch: Krater's reviewer and admin become the +# Ganymede patch roles krater:reviewer and krater:admin. +RSpec.describe PatchRoleImport do + let(:superadmin) { create(:user, :superadmin, :verified) } + let(:krater) { Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb") } + let(:reviewer) { create(:user, :verified) } + let(:reviewers) { create(:group, name: "Krater Reviewers", slug: "krater-reviewers") } + let!(:admins) { create(:group, name: "Krater Admins", slug: "krater-admins") } + + before do + create(:patch, slug: "ganymede", name: "Project Ganymede") + review = ApplicationRole.create!(application: krater, key: "reviewer", name: "Reviewer", description: "Reviews proposals.") + ApplicationRole.create!(application: krater, key: "admin", name: "Admin") + ApplicationRoleAssignment.create!(role: review, assignee: reviewer) + ApplicationRoleAssignment.create!(role: review, assignee: reviewers) + end + + def ganymede = Patch.find_by!(slug: "ganymede") + + def import(apply: false, **options) + described_class.call(application: krater, patch: ganymede, prefix: "krater", actor: superadmin, + group_map: { "krater-admins" => "admin" }, apply:, **options) + end + + def app_role_rows = ApplicationRole.order(:id).map(&:attributes) + ApplicationRoleAssignment.order(:id).map(&:attributes) + + it "plans the roles and the assignments in a dry run, and writes nothing" do + result = import + + expect(result.lines.first).to start_with("Dry run") + expect(result.steps.map { |step| [step.status, step.text] }).to eq( + [ + [:create, "role krater:admin on ganymede (Admin)"], + [:create, "krater:admin for group krater-admins"], + [:create, "role krater:reviewer on ganymede (Reviewer)"], + [:create, "krater:reviewer for user #{reviewer.email}"], + [:create, "krater:reviewer for group krater-reviewers"] + ] + ) + expect(result.lines.last).to include("Only a superadmin can add members", "krater-admins, krater-reviewers") + expect(PatchRole.count).to eq(0) + expect(PatchRoleAssignment.count).to eq(0) + end + + it "writes the roles and the assignments, and the claim has them" do # rubocop:disable RSpec/MultipleExpectations + create(:group_membership, group: admins, user: create(:user, :verified, email: "admin@example.com"), added_by: superadmin) + + result = import(apply: true) + + expect(result.created).to eq(5) + roles = ganymede.roles.order(:key) + expect(roles.map { |role| [role.key, role.name, role.description, role.created_by] }).to eq( + [["krater:admin", "Admin", nil, superadmin], ["krater:reviewer", "Reviewer", "Reviews proposals.", superadmin]] + ) + expect(PatchRoleAssignment.all.map { |assignment| [assignment.role.key, assignment.assignee] }) + .to contain_exactly(["krater:admin", admins], ["krater:reviewer", reviewer], ["krater:reviewer", reviewers]) + expect(PatchRoleAssignment.distinct.pluck(:created_by_id)).to eq([superadmin.id]) + expect(PatchRole.first.versions.last.whodunnit).to eq(superadmin.id.to_s) + expect(PatchRoles.for(reviewer)).to eq("ganymede" => ["krater:reviewer"]) + expect(PatchRoles.for(User.find_by!(email: "admin@example.com"))).to eq("ganymede" => ["krater:admin"]) + end + + it "creates nothing on a second run, and reports each item as already present" do + import(apply: true) + + result = import(apply: true) + + expect(result.created).to eq(0) + expect(result.steps.map(&:status)).to all(eq(:present)) + expect(PatchRole.count).to eq(2) + expect(PatchRoleAssignment.count).to eq(3) + end + + it "never changes the app roles or their assignments" do + before = app_role_rows + + import(apply: true) + + expect(app_role_rows).to eq(before) + end + + it "skips a system group, and reports it" do + staff = create(:group, :system, name: "Staff (system)", slug: "staff-system") + ApplicationRoleAssignment.create!(role: ApplicationRole.find_by!(key: "admin"), assignee: staff) + + result = import(apply: true, group_map: {}) + + expect(result.steps).to include(PatchRoleImport::Step.new(status: :skip, + text: "krater:admin for group staff-system: a system group can't hold a patch role")) + expect(PatchRoleAssignment.where(assignee: staff)).to be_empty + expect(result.groups).to eq([reviewers]) + end + + it "refuses a system group in GROUP_MAP the same way" do + create(:group, :system, name: "Everyone (system)", slug: "everyone-system") + + result = import(apply: true, group_map: { "everyone-system" => "admin" }) + + expect(result.steps.map(&:status)).to include(:skip) + expect(PatchRoleAssignment.where(assignee_type: "Group").map(&:assignee)).to eq([reviewers]) + end + + it "refuses an actor who is not a superadmin, an unknown app or patch, a bad prefix and a bad GROUP_MAP" do # rubocop:disable RSpec/MultipleExpectations + admin = create(:user, :admin, :verified) + base = { application: krater, patch: ganymede, prefix: "krater", actor: superadmin } + + expect { described_class.call(**base, actor: admin) }.to raise_error(described_class::Error, /superadmin/) + expect { described_class.call(**base, actor: nil) }.to raise_error(described_class::Error, /superadmin/) + expect { described_class.call(**base, application: nil) }.to raise_error(described_class::Error, /Unknown app/) + expect { described_class.call(**base, patch: nil) }.to raise_error(described_class::Error, /Unknown patch/) + expect { described_class.call(**base, prefix: "Krater:") }.to raise_error(described_class::Error, /prefix/) + expect { described_class.call(**base, group_map: { "nope" => "admin" }) }.to raise_error(described_class::Error, /Unknown group nope/) + expect { described_class.call(**base, group_map: { "krater-reviewers" => "owner" }) } + .to raise_error(described_class::Error, /no role owner/) + expect(PatchRole.count).to eq(0) + end + + it "writes nothing when one item fails" do + allow(PatchRoleAssignment).to receive(:create!).and_raise(ActiveRecord::RecordInvalid) + + expect { import(apply: true) }.to raise_error(ActiveRecord::RecordInvalid) + expect(PatchRole.count).to eq(0) + end +end From e299b0c6749415dd206898f6e067d58bd3f202ca Mon Sep 17 00:00:00 2001 From: Jasper Mayone Date: Thu, 12 Nov 2026 13:34:54 -0500 Subject: [PATCH 9/9] fix: check the app's patch, conflicts and removed assignments in the role import, and add a patch role directory filter --- .../api/v1/directory/users_controller.rb | 47 +++++- app/services/patch_role_import.rb | 151 +++++++++++++----- docs/OAUTH.md | 38 ++++- lib/tasks/patches.rake | 6 +- spec/lib/patches_rake_spec.rb | 4 +- spec/requests/api/directory_spec.rb | 89 +++++++++++ spec/services/patch_role_import_spec.rb | 65 +++++++- 7 files changed, 340 insertions(+), 60 deletions(-) diff --git a/app/controllers/api/v1/directory/users_controller.rb b/app/controllers/api/v1/directory/users_controller.rb index f2342bf4..74c390eb 100644 --- a/app/controllers/api/v1/directory/users_controller.rb +++ b/app/controllers/api/v1/directory/users_controller.rb @@ -2,6 +2,9 @@ # GET /api/v1/directory/users/:sub # GET /api/v1/directory/users?role= or ?group= +# GET /api/v1/directory/users?patch=&patch_role= (key "lead" for +# the patch leads). Only for an app whose scopes list `patches`, and only +# for the patch the app belongs to (see PatchRoles). # # A user the calling app may not serve is reported as not found, the same as # an unknown user, so the app can't learn who else has a Weave account. @@ -14,6 +17,10 @@ def index return if performed? users = users.select { |user| AppAccess.permitted?(user, current_application) } + # The patches field reads each user's roles (see PatchRoles). + if current_application.scopes.exists?("patches") + ActiveRecord::Associations::Preloader.new(records: users, associations: :active_user_roles).call + end render json: { users: users.sort_by(&:p_id).map { |user| serialize(user) } } end @@ -27,12 +34,16 @@ def show private def filtered_users - if params[:role].present? == params[:group].present? - render json: { error: "invalid_request", error_description: "Pass exactly one of role or group" }, status: :bad_request + filters = [params[:role], params[:group], params[:patch]].count(&:present?) + if filters != 1 || params[:patch].present? != params[:patch_role].present? + render json: { error: "invalid_request", error_description: "Pass exactly one of role, group or patch (with patch_role)" }, + status: :bad_request elsif params[:role].present? users_with_role - else + elsif params[:group].present? users_in_group + else + users_with_patch_role end end @@ -54,6 +65,36 @@ def users_in_group group.users.to_a end + # The holders of one patch role, directly or through an active group + # membership (PatchRole.held_by), or the patch leads for "lead". + # Needs the patches scope on the app, like the claim. A patch other + # than the app's own, and an unknown role key, are not found. + def users_with_patch_role + unless current_application.scopes.exists?("patches") + return render json: { error: "insufficient_scope", error_description: "Use an app allowed the patches scope" }, + status: :forbidden + end + + patch = current_application.patch + return render_not_found unless patch && patch.slug == params[:patch] + + patch_role_holders(patch, params[:patch_role].to_s) + end + + def patch_role_holders(patch, key) + if key == PatchRoles::LEAD + return User.where(id: UserRole.active.for_role("patch_lead").where(scope: patch.slug).select(:user_id)).to_a + end + + role = patch.roles.find_by(key:) + return render_not_found unless role + + assignments = role.assignments.to_a + direct = User.where(id: assignments.select { |a| a.assignee_type == "User" }.map(&:assignee_id)) + via_group = User.where(id: Group::Membership.active.where(group_id: assignments.select { |a| a.assignee_type == "Group" }.map(&:assignee_id)).select(:user_id)) + direct.or(via_group).to_a + end + def serialize(user) = DirectoryUserSerializer.new(user, current_application).as_json end diff --git a/app/services/patch_role_import.rb b/app/services/patch_role_import.rb index d96f0c00..da695fe1 100644 --- a/app/services/patch_role_import.rb +++ b/app/services/patch_role_import.rb @@ -5,58 +5,75 @@ # For example, Krater's app roles `reviewer` and `admin` become the Ganymede # patch roles `krater:reviewer` and `krater:admin`. # +# - The app must belong to the patch (a superadmin links it first). # - Each app role becomes the patch role ":", with the same name -# and description. An existing patch role with that key is kept as it is. +# and description. A patch role with that key that has another name or +# description is a conflict: APPLY refuses unless merge is true, and then +# keeps the patch role as it is. # - Each assignment of the app role becomes a patch role assignment: a user, # or a manual group. A system group is skipped: it can't hold a patch role # (see PatchRoleAssignment). # - group_map gives the patch role of an app role key to a group too, even -# with no app role assignment for it. Manual groups only, the same rule. +# with no app role assignment for it ("grant", with the group's active +# member count). Manual groups only, the same rule. +# - An assignment that an admin removed before (a PaperTrail destroy version) +# is skipped as "previously removed", unless restore is true. # - The app roles and their assignments are never changed: the app reads them # until it reads the `patches` claim. # -# A dry run (the default) writes nothing and returns the plan. apply: true -# writes the plan in one transaction, with the actor as created_by and as the -# PaperTrail whodunnit. A second run creates nothing: each item is reported -# as already present. Only a superadmin can be the actor. +# A dry run (the default) builds every record and checks it, and writes +# nothing. apply: true refuses when an item is invalid or a conflict (without +# merge), and otherwise writes the plan in one transaction, with the actor as +# created_by and as the PaperTrail whodunnit. A second run creates nothing. +# Only a superadmin can be the actor. module PatchRoleImport class Error < StandardError; end PREFIX_FORMAT = /\A[a-z0-9]+(?:[-_][a-z0-9]+)*\z/ - # status: :create, :present or :skip. - Step = Data.define(:status, :text) + # status: :create, :grant, :present, :conflict, :skip, :removed or :invalid. + # record: the unsaved record that APPLY saves, for :create and :grant. + Step = Data.define(:status, :text, :record) do + def initialize(status:, text:, record: nil) = super - Result = Data.define(:steps, :groups, :applied) do - def created = steps.count { |step| step.status == :create } + def label = status == :removed ? "previously removed" : status.to_s + end + + WRITES = %i[create grant].freeze + + Result = Data.define(:steps, :groups, :applied, :header) do + def created = steps.count { |step| WRITES.include?(step.status) } def lines - header = applied ? "Applied. Weave wrote the items marked create." : "Dry run. Nothing was written. Run again with APPLY=1 to write it." - list = steps.map { |step| "#{step.status.to_s.ljust(7)} #{step.text}" } + mode = applied ? "Applied. Weave wrote the items marked create and grant." : "Dry run. Nothing was written. Run again with APPLY=1 to write it." + list = steps.map { |step| "#{step.label.ljust(8)} #{step.text}" } warning = if groups.any? ["Warning: these groups hold a patch role. Only a superadmin can add members to them now: " \ "#{groups.map(&:slug).sort.join(', ')}."] else [] end - [header, *list, *warning] + [header, mode, *list, *warning] end end class << self - def call(application:, patch:, prefix:, actor:, group_map: {}, apply: false) + def call(application:, patch:, prefix:, actor:, group_map: {}, apply: false, merge: false, restore: false) check!(application:, patch:, prefix:, actor:) app_roles = ApplicationRole.for_application(application).includes(assignments: :assignee).order(:key).to_a extra = map_groups(group_map, app_roles) - plan = Plan.new(patch:, prefix:, actor:, apply:) - work = -> { app_roles.each { |app_role| plan.add_role(app_role, extra.fetch(app_role.key, [])) } } - if apply - PaperTrail.request(whodunnit: actor.id.to_s) { ApplicationRecord.transaction { work.call } } - else - work.call + plan = Plan.new(patch:, prefix:, actor:, restore:) + app_roles.each { |app_role| plan.add_role(app_role, extra.fetch(app_role.key, [])) } + header = "App: #{application.name} (client id #{application.uid}). Patch: #{patch.name} (#{patch.slug})." + result = Result.new(steps: plan.steps, groups: plan.groups.uniq, applied: apply, header:) + return result unless apply + + refuse_apply!(result.steps, merge:) + PaperTrail.request(whodunnit: actor.id.to_s) do + ApplicationRecord.transaction { result.steps.each { |step| step.record&.save! } } end - Result.new(steps: plan.steps, groups: plan.groups.uniq, applied: apply) + result end private @@ -66,6 +83,20 @@ def check!(application:, patch:, prefix:, actor:) raise Error, "Unknown patch." if patch.nil? raise Error, "The prefix must be lowercase letters and digits, for example krater." unless prefix.to_s.match?(PREFIX_FORMAT) raise Error, "The actor must be a superadmin." unless actor&.superadmin? + return if application.patch_id == patch.id + + raise Error, "#{application.name} does not belong to #{patch.slug}. A superadmin links the app to the patch first (the Patch field on the app's edit page)." + end + + def refuse_apply!(steps, merge:) + invalid = steps.select { |step| step.status == :invalid } + raise Error, "Nothing was written. Fix the invalid items first: #{invalid.map(&:text).join('; ')}" if invalid.any? + + conflicts = steps.select { |step| step.status == :conflict } + return if conflicts.empty? || merge + + raise Error, "Nothing was written. A patch role with the same key differs: #{conflicts.map(&:text).join('; ')}. " \ + "Run with MERGE=1 to keep the patch roles as they are and add the assignments." end # { "reviewer" => [group, ...] } from { "krater-reviewers" => "reviewer" }. @@ -82,51 +113,83 @@ def map_groups(group_map, app_roles) end - # Builds the steps, and writes them when apply is true. + # Builds the steps and the unsaved records. Writes nothing. class Plan attr_reader :steps, :groups - def initialize(patch:, prefix:, actor:, apply:) + def initialize(patch:, prefix:, actor:, restore:) @patch = patch @prefix = prefix @actor = actor - @apply = apply + @restore = restore @steps = [] @groups = [] end def add_role(app_role, extra_groups) key = "#{@prefix}:#{app_role.key}" - role = @patch.roles.find_by(key:) - if role - @steps << Step.new(status: :present, text: "role #{key} on #{@patch.slug}") - else - @steps << Step.new(status: :create, text: "role #{key} on #{@patch.slug} (#{app_role.name})") - if @apply - role = @patch.roles.create!(key:, name: app_role.name, description: app_role.description, created_by: @actor) - end - end + role = role_step(app_role, key) + return if role.nil? - assignees = (app_role.assignments.map(&:assignee).compact + extra_groups).uniq - assignees.each { |assignee| add_assignment(role, key, assignee) } + assigned = app_role.assignments.map(&:assignee).compact.uniq + assigned.each { |assignee| add_assignment(role, key, assignee, granted: false) } + (extra_groups.uniq - assigned).each { |group| add_assignment(role, key, group, granted: true) } end private - def add_assignment(role, key, assignee) + # The patch role (saved or unsaved), or nil when it is invalid. + def role_step(app_role, key) + role = @patch.roles.find_by(key:) + if role.nil? + role = PatchRole.new(patch: @patch, key:, name: app_role.name, description: app_role.description, created_by: @actor) + return invalid("role #{key}", role) unless role.valid? + + @steps << Step.new(status: :create, text: "role #{key} on #{@patch.slug} (#{app_role.name})", record: role) + elsif role.name != app_role.name || role.description.presence != app_role.description.presence + @steps << Step.new(status: :conflict, + text: "role #{key} on #{@patch.slug} is named #{role.name.inspect} with description " \ + "#{role.description.inspect}, the app role #{app_role.name.inspect} with #{app_role.description.inspect}") + else + @steps << Step.new(status: :present, text: "role #{key} on #{@patch.slug}") + end + role + end + + def add_assignment(role, key, assignee, granted:) label = assignee.is_a?(Group) ? "group #{assignee.slug}" : "user #{assignee.email}" + text = "#{key} for #{label}" + text += " (#{assignee.active_memberships.count} active members)" if granted + if assignee.is_a?(Group) && !assignee.manual? - @steps << Step.new(status: :skip, text: "#{key} for #{label}: a system group can't hold a patch role") - return + @steps << Step.new(status: :skip, text: "#{text}: a system group can't hold a patch role") + elsif role.persisted? && role.assignments.exists?(assignee:) + @groups << assignee if assignee.is_a?(Group) + @steps << Step.new(status: :present, text:) + elsif role.persisted? && removed_before?(role, assignee) && !@restore + @steps << Step.new(status: :removed, text: "#{text}: an admin removed it, run with RESTORE=1 to give it back") + else + add_new_assignment(role, assignee, text, granted:) end + end + + def add_new_assignment(role, assignee, text, granted:) + assignment = PatchRoleAssignment.new(role:, assignee:, created_by: @actor) + return invalid(text, assignment) unless assignment.valid? @groups << assignee if assignee.is_a?(Group) - if role&.persisted? && role.assignments.exists?(assignee:) - @steps << Step.new(status: :present, text: "#{key} for #{label}") - else - @steps << Step.new(status: :create, text: "#{key} for #{label}") - PatchRoleAssignment.create!(role:, assignee:, created_by: @actor) if @apply - end + @steps << Step.new(status: granted ? :grant : :create, text:, record: assignment) + end + + def removed_before?(role, assignee) + PaperTrail::Version.where(item_type: "PatchRoleAssignment", event: "destroy") + .where_object(role_id: role.id, assignee_type: assignee.class.name, assignee_id: assignee.id) + .exists? + end + + def invalid(text, record) + @steps << Step.new(status: :invalid, text: "#{text}: #{record.errors.full_messages.to_sentence}") + nil end end diff --git a/docs/OAUTH.md b/docs/OAUTH.md index e6d9a65d..d6a22b83 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -435,23 +435,48 @@ does the work, and a rake task runs it: ```bash bin/rails patches:import_app_roles APP= PATCH=ganymede PREFIX=krater \ - ACTOR= GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin + ACTOR= ``` +- The app must belong to the patch. A superadmin sets the Patch field on the app's edit page first. The plan starts with the app name, its client id and the patch. - Each app role becomes the patch role `:`, with the same name and description. - Each user who holds the app role gets the patch role. A manual group that holds it gets the patch role too. A system group is skipped and reported: it can't hold a patch role. -- `GROUP_MAP` gives the patch role of an app role key to a manual group, also when no app role assignment exists for it. - `ACTOR` must be a superadmin. Weave records them as the creator and in the change history. - The task never changes the app roles or their assignments. - It prints a warning with each group that holds a patch role. After the move, only a superadmin can add members to those groups. -- Without `APPLY=1` it is a dry run: it prints the plan and writes nothing. With `APPLY=1` it writes the plan in one transaction. A second run creates nothing and reports each item as already present. +- Without `APPLY=1` it is a dry run: it builds and checks every record, prints the plan and writes nothing. With `APPLY=1` it writes the plan in one transaction. + +Each line of the plan has a status: + +| Status | Meaning | +|---|---| +| `create` | Weave creates the role or the assignment. | +| `grant` | A `GROUP_MAP` group gets the role with no app role assignment for it. The line gives the group's active member count. | +| `present` | The role or the assignment already exists. | +| `conflict` | A patch role with the same key has another name or description. `APPLY=1` refuses. With `MERGE=1`, Weave keeps the patch role as it is and adds the assignments. | +| `previously removed` | An admin removed this assignment before. Weave skips it. With `RESTORE=1`, Weave gives it back. | +| `skip` | A system group. It can't hold a patch role. | +| `invalid` | The record does not pass its checks. `APPLY=1` refuses. | + +A second run creates nothing: each item is `present`, or `previously removed` +when an admin took it away after the first run. + +Use `GROUP_MAP=:,...` only when the app gives a role to the +members of a group by itself, outside Weave's app roles (a group fallback +that the app reads from the `groups` claim). Then each pair gives that +group the patch role of that app role key. Krater does this for +`krater-reviewers` and `krater-admins`: add +`GROUP_MAP=krater-reviewers:reviewer,krater-admins:admin` only if Krater +still reads those groups for the role. The switch order: 1. Run the task without `APPLY=1`, and read the plan. 2. Run it again with `APPLY=1`. 3. Add `patches` to the app's scopes, and switch the app to read the `patches` claim (or the directory field). -4. When no running copy of the app reads its app roles, remove the app roles in the app's "Roles" panel. +4. Switch every list of people by role to the patch role filter of the directory API (`?patch=&patch_role=`, see "Directory API"). The old `?role=` filter gives `404` once the app role is gone. +5. If the app is restricted, give the holders an access grant (a user or a group). A patch role does not open a restricted app. +6. When no running copy of the app reads its app roles, remove the app roles in the app's "Roles" panel. ### App roles @@ -495,6 +520,7 @@ curl -u "$CLIENT_ID:$CLIENT_SECRET" -d grant_type=client_credentials -d scope=di |---|---| | `GET /api/v1/directory/users/:sub` | One user | | `GET /api/v1/directory/users?role=` | `{"users": [...]}`: users who hold this app role | +| `GET /api/v1/directory/users?patch=&patch_role=` | `{"users": [...]}`: users who hold this role of the app's patch. `patch_role=lead` lists the patch leads | | `GET /api/v1/directory/users?group=` | `{"users": [...]}`: members of a group linked to this app | Each user has the same fields as the claims: @@ -534,7 +560,9 @@ Rules: - `patches` is in the response only when the app's scopes list `patches` (see "Patch claims"). - `demographics_answered` is `true` when the user saved answers to the demographics form. Weave never sends the answers. Ask for it before a user's first grant application. To send the user to the form, link to `/profile/demographics?return_to=`. After a save, Weave sends the user back to `return_to` when its origin matches a redirect URI of a registered app. Weave ignores any other `return_to`. - `?group=` works only for a group linked to the app. `?role=` works only for a role of the app. Other values give `404`. -- Pass exactly one of `role` and `group`, or the API answers `400`. +- Pass exactly one of `role`, `group` and `patch`, or the API answers `400`. `patch` needs `patch_role`, and `patch_role` needs `patch`. +- `?patch=&patch_role=` needs `patches` in the app's scopes, or the API answers `403` with `insufficient_scope`. It works only for the patch the app belongs to (the Patch field on the app's edit page). Another patch, an app with no patch and an unknown role key give `404`, like `?role=`. +- `?patch=&patch_role=` lists the users who hold the patch role directly or through an unexpired group membership. `patch_role=lead` lists the users with an active patch lead role for the patch. Like the other lists, it leaves out users the app may not serve, and each user has the `patches` field. - A token with a user, a token without the `directory` scope, or a token of an app whose scopes do not list `directory` gives `403`. ### Shipping address API diff --git a/lib/tasks/patches.rake b/lib/tasks/patches.rake index fb50d418..48ed9031 100644 --- a/lib/tasks/patches.rake +++ b/lib/tasks/patches.rake @@ -14,7 +14,7 @@ namespace :patches do desc "Copy the roles of an OAuth app into a patch (see PatchRoleImport). " \ "APP= PATCH= PREFIX= ACTOR= " \ - "[GROUP_MAP=slug:role_key,...] [APPLY=1]. A dry run unless APPLY=1." + "[GROUP_MAP=slug:role_key,...] [MERGE=1] [RESTORE=1] [APPLY=1]. A dry run unless APPLY=1." task import_app_roles: :environment do app_param = ENV["APP"].to_s application = Doorkeeper::Application.find_by_public_param(app_param) if app_param.present? @@ -31,7 +31,9 @@ namespace :patches do prefix: ENV["PREFIX"].to_s, actor: User.find_for_any_email(ENV["ACTOR"].to_s), group_map:, - apply: ENV["APPLY"] == "1" + apply: ENV["APPLY"] == "1", + merge: ENV["MERGE"] == "1", + restore: ENV["RESTORE"] == "1" ) puts result.lines rescue PatchRoleImport::Error => error diff --git a/spec/lib/patches_rake_spec.rb b/spec/lib/patches_rake_spec.rb index 11381892..1b1a396f 100644 --- a/spec/lib/patches_rake_spec.rb +++ b/spec/lib/patches_rake_spec.rb @@ -13,7 +13,7 @@ let(:krater) { Doorkeeper::Application.create!(name: "Krater", redirect_uri: "https://krater.example.com/cb") } before do - create(:patch, slug: "ganymede", name: "Project Ganymede") + krater.update!(patch: create(:patch, slug: "ganymede", name: "Project Ganymede")) role = ApplicationRole.create!(application: krater, key: "reviewer", name: "Reviewer") ApplicationRoleAssignment.create!(role:, assignee: create(:group, name: "Krater Admins", slug: "krater-admins")) end @@ -29,7 +29,7 @@ def run(env) def env(**extra) = { "APP" => krater.public_id, "PATCH" => "ganymede", "PREFIX" => "krater", "ACTOR" => superadmin.email, **extra } it "prints the plan and writes nothing without APPLY=1" do - expect { run(env) }.to output(/Dry run.*create role krater:reviewer.*Warning.*krater-admins/m).to_stdout + expect { run(env) }.to output(/App: Krater.*Dry run.*create +role krater:reviewer.*Warning.*krater-admins/m).to_stdout expect(PatchRole.count).to eq(0) end diff --git a/spec/requests/api/directory_spec.rb b/spec/requests/api/directory_spec.rb index 8540f2e9..ca23728e 100644 --- a/spec/requests/api/directory_spec.rb +++ b/spec/requests/api/directory_spec.rb @@ -208,6 +208,95 @@ def directory_get(path, token: app_token, params: {}) end end + describe "GET /api/v1/directory/users?patch=&patch_role=" do + let(:viewer_role) { Patch.find_by!(slug: "ganymede").roles.create!(key: "krater:reviewer", name: "Reviewer") } + + # A user the restricted app may serve (an access grant). + def servable_user + create(:user, :verified, :accepted_code_of_conduct).tap { |user| ApplicationAccessGrant.create!(application:, grantee: user) } + end + + def patch_get(patch: "ganymede", key: "krater:reviewer", token: app_token) + directory_get(api_v1_directory_users_path, token:, params: { patch:, patch_role: key }) + end + + before do + application.update!(scopes: "openid profile groups roles directory patches", + patch: create(:patch, slug: "ganymede", name: "Project Ganymede")) + end + + it "lists users who hold the patch role directly or through an active group membership" do + direct = servable_user + PatchRoleAssignment.create!(role: viewer_role, assignee: direct) + finance = create(:group, name: "Finance") + member = servable_user + create(:group_membership, group: finance, user: member) + expired = servable_user + create(:group_membership, group: finance, user: expired, expires_at: 1.hour.from_now) + PatchRoleAssignment.create!(role: viewer_role, assignee: finance) + servable_user + + travel 2.hours do + body = patch_get + + expect(response).to have_http_status(:ok) + expect(body["users"].pluck("sub")).to contain_exactly(direct.p_id, member.p_id) + expect(body["users"].first.keys).to include("sub", "patches") + end + end + + it "lists the patch leads for the key lead" do + lead = servable_user + RoleGrants.grant!(lead, "patch_lead", scope: "ganymede", reason: "spec") + revoked = servable_user + RoleGrants.grant!(revoked, "patch_lead", scope: "ganymede", reason: "spec") + RoleGrants.revoke!(revoked, "patch_lead", scope: "ganymede", reason: "spec") + + expect(patch_get(key: "lead")["users"].pluck("sub")).to eq([lead.p_id]) + end + + it "leaves out a holder the app may not serve" do + PatchRoleAssignment.create!(role: viewer_role, assignee: create(:user, :verified, :accepted_code_of_conduct)) + + expect(patch_get["users"]).to eq([]) + end + + it "is forbidden for an app whose scopes do not list patches" do + application.update!(scopes: "openid profile groups roles directory") + + patch_get + + expect(response).to have_http_status(:forbidden) + expect(response.parsed_body["error"]).to eq("insufficient_scope") + end + + it "is not found for another patch, for an app with no patch, and for an unknown role key" do + create(:patch, slug: "europa").roles.create!(key: "krater:reviewer", name: "Reviewer") + viewer_role + + patch_get(patch: "europa") + expect(response).to have_http_status(:not_found) + + patch_get(key: "krater:nobody") + expect(response).to have_http_status(:not_found) + + application.update!(patch: nil) + patch_get + expect(response).to have_http_status(:not_found) + end + + it "needs patch_role with patch, and no other filter" do + directory_get(api_v1_directory_users_path, params: { patch: "ganymede" }) + expect(response).to have_http_status(:bad_request) + + directory_get(api_v1_directory_users_path, params: { patch_role: "lead" }) + expect(response).to have_http_status(:bad_request) + + directory_get(api_v1_directory_users_path, params: { patch: "ganymede", patch_role: "lead", role: "reviewer" }) + expect(response).to have_http_status(:bad_request) + end + end + describe "authentication" do let(:path) { api_v1_directory_user_path(reviewer.p_id) } diff --git a/spec/services/patch_role_import_spec.rb b/spec/services/patch_role_import_spec.rb index d92610cd..db713e84 100644 --- a/spec/services/patch_role_import_spec.rb +++ b/spec/services/patch_role_import_spec.rb @@ -12,7 +12,7 @@ let!(:admins) { create(:group, name: "Krater Admins", slug: "krater-admins") } before do - create(:patch, slug: "ganymede", name: "Project Ganymede") + krater.update!(patch: create(:patch, slug: "ganymede", name: "Project Ganymede")) review = ApplicationRole.create!(application: krater, key: "reviewer", name: "Reviewer", description: "Reviews proposals.") ApplicationRole.create!(application: krater, key: "admin", name: "Admin") ApplicationRoleAssignment.create!(role: review, assignee: reviewer) @@ -31,11 +31,12 @@ def app_role_rows = ApplicationRole.order(:id).map(&:attributes) + ApplicationRo it "plans the roles and the assignments in a dry run, and writes nothing" do result = import - expect(result.lines.first).to start_with("Dry run") + expect(result.lines.first(2)).to eq(["App: Krater (client id #{krater.uid}). Patch: Project Ganymede (ganymede).", + "Dry run. Nothing was written. Run again with APPLY=1 to write it."]) expect(result.steps.map { |step| [step.status, step.text] }).to eq( [ [:create, "role krater:admin on ganymede (Admin)"], - [:create, "krater:admin for group krater-admins"], + [:grant, "krater:admin for group krater-admins (0 active members)"], [:create, "role krater:reviewer on ganymede (Reviewer)"], [:create, "krater:reviewer for user #{reviewer.email}"], [:create, "krater:reviewer for group krater-reviewers"] @@ -120,9 +121,65 @@ def app_role_rows = ApplicationRole.order(:id).map(&:attributes) + ApplicationRo end it "writes nothing when one item fails" do - allow(PatchRoleAssignment).to receive(:create!).and_raise(ActiveRecord::RecordInvalid) + allow_any_instance_of(PatchRoleAssignment).to receive(:save!).and_raise(ActiveRecord::RecordInvalid) # rubocop:disable RSpec/AnyInstance expect { import(apply: true) }.to raise_error(ActiveRecord::RecordInvalid) expect(PatchRole.count).to eq(0) end + + it "refuses an app that does not belong to the patch" do + krater.update!(patch: nil) + + expect { import }.to raise_error(described_class::Error, /Krater does not belong to ganymede/) + krater.update!(patch: create(:patch, slug: "europa")) + expect { import(apply: true) }.to raise_error(described_class::Error, /does not belong/) + expect(PatchRole.count).to eq(0) + end + + it "reports a patch role with the same key and another name as a conflict, and refuses APPLY without MERGE" do + ganymede.roles.create!(key: "krater:reviewer", name: "Reviewer (old)", description: "Reviews proposals.") + + expect(import.steps.map(&:status)).to include(:conflict) + expect { import(apply: true) }.to raise_error(described_class::Error, /MERGE=1/) + expect(PatchRoleAssignment.count).to eq(0) + + import(apply: true, merge: true) + expect(ganymede.roles.find_by!(key: "krater:reviewer").name).to eq("Reviewer (old)") + expect(PatchRoles.for(reviewer)).to eq("ganymede" => ["krater:reviewer"]) + end + + it "gives a GROUP_MAP group with no app role assignment the status grant, with its active member count" do + create(:group_membership, group: admins, user: create(:user, :verified), added_by: superadmin) + create(:group_membership, group: reviewers, user: create(:user, :verified), added_by: superadmin) + + steps = import(group_map: { "krater-admins" => "admin", "krater-reviewers" => "reviewer" }).steps + + expect(steps.select { |step| step.status == :grant }.map(&:text)).to eq(["krater:admin for group krater-admins (1 active members)"]) + expect(steps.map(&:text)).to include("krater:reviewer for group krater-reviewers") + end + + it "skips an assignment that an admin removed before, unless RESTORE" do + import(apply: true) + PaperTrail.request(whodunnit: superadmin.id.to_s) { PatchRoleAssignment.find_by!(assignee: reviewer).destroy! } + + result = import(apply: true) + + expect(result.steps.map(&:label)).to include("previously removed") + expect(PatchRoles.for(reviewer)).to eq({}) + + import(apply: true, restore: true) + expect(PatchRoles.for(reviewer)).to eq("ganymede" => ["krater:reviewer"]) + end + + it "checks each record in a dry run, and APPLY refuses an invalid item" do + stub_const("PatchRoleImport::PREFIX_FORMAT", /.*/) + + result = described_class.call(application: krater, patch: ganymede, prefix: "Bad Prefix", actor: superadmin) + + expect(result.steps.map(&:status)).to all(eq(:invalid)) + expect(result.steps.first.text).to include("Key is invalid") + expect { described_class.call(application: krater, patch: ganymede, prefix: "Bad Prefix", actor: superadmin, apply: true) } + .to raise_error(described_class::Error, /invalid items/) + expect(PatchRole.count).to eq(0) + end end