diff --git a/app/controllers/admin/oauth_applications_controller.rb b/app/controllers/admin/oauth_applications_controller.rb index d2aabc0..a5bdda1 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, - :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/controllers/admin/patch_role_assignments_controller.rb b/app/controllers/admin/patch_role_assignments_controller.rb new file mode 100644 index 0000000..8cee2f0 --- /dev/null +++ b/app/controllers/admin/patch_role_assignments_controller.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +# Gives a role of a patch to a user or a group, or takes it away (see +# 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, only: [:create] + + 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 0000000..e9875bf --- /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 new file mode 100644 index 0000000..1d2303a --- /dev/null +++ b/app/controllers/admin/patches_controller.rb @@ -0,0 +1,72 @@ +# 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 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] + + 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) + @leads = RoleGrants.assignments("patch_lead").where(scope: @patch.slug).includes(:granted_by).to_a + @roles = @patch.roles.includes(assignments: :assignee).order(:key) + # Only a manual group can hold a patch role (see PatchRoleAssignment). + @groups = Group.manual.order(:name) if current_user.superadmin? + 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/controllers/api/v1/directory/users_controller.rb b/app/controllers/api/v1/directory/users_controller.rb index f2342bf..74c390e 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/helpers/admin_nav_helper.rb b/app/helpers/admin_nav_helper.rb index 661538a..89d5296 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 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/concerns/oauth_application_patch_link.rb b/app/models/concerns/oauth_application_patch_link.rb new file mode 100644 index 0000000..a28a483 --- /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/group.rb b/app/models/group.rb index 3278853..d107025 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 @@ -90,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 6c1cf4c..181b8f3 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.rb b/app/models/patch.rb new file mode 100644 index 0000000..30db20a --- /dev/null +++ b/app/models/patch.rb @@ -0,0 +1,75 @@ +# 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 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. +# == 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 + has_many :roles, class_name: "PatchRole", inverse_of: :patch, dependent: :destroy + + 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/models/patch_role.rb b/app/models/patch_role.rb new file mode 100644 index 0000000..cd47aff --- /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 0000000..fa1e783 --- /dev/null +++ b/app/models/patch_role_assignment.rb @@ -0,0 +1,59 @@ +# 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 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 +# 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" } + 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/models/user.rb b/app/models/user.rb index e9b2b8e..aaaf7cb 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/policies/group_policy.rb b/app/policies/group_policy.rb index f674f82..b9648b5 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/serializers/directory_user_serializer.rb b/app/serializers/directory_user_serializer.rb index e481e84..24b1933 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/access_requests.rb b/app/services/access_requests.rb index f4c6cd5..2020953 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/data_categories.rb b/app/services/data_categories.rb index 2056ab3..786339e 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 b4c87af..8126a6c 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/knot_settings.rb b/app/services/knot_settings.rb index 21b817f..806ea0f 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/app/services/patch_role_import.rb b/app/services/patch_role_import.rb new file mode 100644 index 0000000..da695fe --- /dev/null +++ b/app/services/patch_role_import.rb @@ -0,0 +1,197 @@ +# 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`. +# +# - 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. 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 ("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) 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, :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 + + 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 + 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, mode, *list, *warning] + end + end + + class << self + 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:, 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 + 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? + 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" }. + 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 the unsaved records. Writes nothing. + class Plan + attr_reader :steps, :groups + + def initialize(patch:, prefix:, actor:, restore:) + @patch = patch + @prefix = prefix + @actor = actor + @restore = restore + @steps = [] + @groups = [] + end + + def add_role(app_role, extra_groups) + key = "#{@prefix}:#{app_role.key}" + role = role_step(app_role, key) + return if role.nil? + + 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 + + # 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: "#{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) + @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 + +end diff --git a/app/services/patch_roles.rb b/app/services/patch_roles.rb new file mode 100644 index 0000000..6af28e3 --- /dev/null +++ b/app/services/patch_roles.rb @@ -0,0 +1,38 @@ +# 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, unique role keys the +# person holds for that patch, for example +# +# {"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. +# - 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. +# - An empty object ({}) when the person holds no patch role. +module PatchRoles + # 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? + + keys = Hash.new { |hash, slug| hash[slug] = [] } + + 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/views/admin/groups/show.html.erb b/app/views/admin/groups/show.html.erb index 16f533e..6e07d31 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/oauth_applications/_patch_field.html.erb b/app/views/admin/oauth_applications/_patch_field.html.erb new file mode 100644 index 0000000..df76dde --- /dev/null +++ b/app/views/admin/oauth_applications/_patch_field.html.erb @@ -0,0 +1,9 @@ +<%# 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] }, + { 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 2909a5e..57b2650 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,10 @@ + <% 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 9bf8325..3bb4eb6 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,10 @@ + <% if current_user.superadmin? %> + <%= render "patch_field", form: form %> + <% end %> + <%= 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 85ad6df..242d770 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 0000000..66b0df7 --- /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 0000000..633b19f --- /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 0000000..f6d7f90 --- /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 0000000..a2980a9 --- /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 0000000..82f9b76 --- /dev/null +++ b/app/views/admin/patches/show.html.erb @@ -0,0 +1,244 @@ +<% 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. +

+
+
+ +
+
+
+
+
+

Patch leads

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

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

+
+
+ <% if @leads.any? %> +
+
    + <% @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("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. +

+

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

+
+
+ +
+ <% 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 %> +
+ <%# 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 %> +
+ <% 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 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" %> +
+ <%= 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: "quilt: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. Quilt reads quilt:viewer. Use an app prefix for a role meant for one app. +

+
+ <% 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 35d24dd..5218bc9 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/groups/show.html.erb b/app/views/groups/show.html.erb index 3b27ee2..a5237e9 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.rb b/config/initializers/doorkeeper.rb index e11b068..355edd4 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 bd28c6f..9527d13 100644 --- a/config/initializers/doorkeeper_openid_connect.rb +++ b/config/initializers/doorkeeper_openid_connect.rb @@ -239,5 +239,17 @@ 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 role keys, for example + # {"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 + # 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/initializers/oauth_application_public_id.rb b/config/initializers/oauth_application_public_id.rb index 200380a..a88b71c 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 4f6f28b..810c838 100644 --- a/config/roles.yml +++ b/config/roles.yml @@ -105,10 +105,15 @@ roles: revoke: rule: admin + # 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 + # 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: diff --git a/config/routes.rb b/config/routes.rb index dc150e1..73a8bb1 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -203,6 +203,19 @@ # 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 +# 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 @@ -818,6 +831,15 @@ 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] 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 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 0000000..e95dd0d --- /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 0000000..38618ea --- /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/migrate/20261112130000_create_patch_roles.rb b/db/migrate/20261112130000_create_patch_roles.rb new file mode 100644 index 0000000..58e1546 --- /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 fef23a8..82deb4b 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_130000) 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,42 @@ 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 + 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 +1515,13 @@ 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 "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 add_foreign_key "residency_checks", "users", column: "decided_by_id", on_delete: :nullify @@ -1662,6 +1706,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 +1744,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 fa82eff..478c0f7 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 e5eb9ea..45c6039 100644 --- a/docs/KYC.md +++ b/docs/KYC.md @@ -415,6 +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 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`). @@ -438,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. 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 bbae17c..d6a22b8 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,123 @@ 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 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 `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 +`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. + +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": ["reviewer"], "ganymede": ["lead", "quilt:viewer", "reviewer"]} +``` + +Rules: + +- The object is empty (`{}`) when the user holds no patch role. +- 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 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 +list `patches` (see "Directory API"). + +```mermaid +flowchart LR + P[(patches: ganymede)] --> UR[user_roles: patch_lead, scope ganymede] + 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 -->|quilt:viewer| PR + PR --> C["patches claim: {ganymede: [lead, quilt:viewer]}"] + 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= +``` + +- 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. +- `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 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. 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 An app can define its own roles, for example `member`, `reviewer` and `admin`. @@ -402,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: @@ -438,9 +557,12 @@ 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`. +- 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 @@ -558,7 +680,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 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/lib/tasks/patches.rake b/lib/tasks/patches.rake new file mode 100644 index 0000000..48ed903 --- /dev/null +++ b/lib/tasks/patches.rake @@ -0,0 +1,42 @@ +# 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 + + desc "Copy the roles of an OAuth app into a patch (see PatchRoleImport). " \ + "APP= PATCH= PREFIX= ACTOR= " \ + "[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? + 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", + merge: ENV["MERGE"] == "1", + restore: ENV["RESTORE"] == "1" + ) + puts result.lines + rescue PatchRoleImport::Error => error + abort error.message + end +end diff --git a/spec/factories/patches.rb b/spec/factories/patches.rb new file mode 100644 index 0000000..50e176f --- /dev/null +++ b/spec/factories/patches.rb @@ -0,0 +1,30 @@ +# 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}" } + sequence(:name) { |n| "Patch #{n}" } + end +end diff --git a/spec/lib/patches_rake_spec.rb b/spec/lib/patches_rake_spec.rb new file mode 100644 index 0000000..1b1a396 --- /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 + 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 + + 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(/App: Krater.*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/models/patch_role_spec.rb b/spec/models/patch_role_spec.rb new file mode 100644 index 0000000..ebdc3dd --- /dev/null +++ b/spec/models/patch_role_spec.rb @@ -0,0 +1,91 @@ +# 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. +# == 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") } + + 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 + expect(patch.roles.build(key: "quilt:viewer", name: "Quilt viewer")).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 "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) + PatchRoleAssignment.create!(role:, assignee: group) + + expect { group.destroy }.to change(PatchRoleAssignment, :count).by(-1) + end +end diff --git a/spec/models/patch_spec.rb b/spec/models/patch_spec.rb new file mode 100644 index 0000000..3da1ef3 --- /dev/null +++ b/spec/models/patch_spec.rb @@ -0,0 +1,85 @@ +# 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. +# == 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 + 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 ec5a9b4..5eec19d 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 0000000..430db9b --- /dev/null +++ b/spec/requests/admin_oauth_application_patch_spec.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require "rails_helper" + +# 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, :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") } + + 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 "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)) + + 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_patch_roles_spec.rb b/spec/requests/admin_patch_roles_spec.rb new file mode 100644 index 0000000..b9bb350 --- /dev/null +++ b/spec/requests/admin_patch_roles_spec.rb @@ -0,0 +1,131 @@ +# 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 "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.") + + 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 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, "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" } } + 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 } } + + 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 + 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 new file mode 100644 index 0000000..2cba961 --- /dev/null +++ b/spec/requests/admin_patches_spec.rb @@ -0,0 +1,94 @@ +# 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 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") + leads = create_list(:user, 2, :verified, :patch_lead) + viewers = create_list(:user, 2, :verified) + %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) + 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 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 + 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 6a3c1c7..ca23728 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 + 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") + + 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) @@ -198,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/requests/oauth/introspection_spec.rb b/spec/requests/oauth/introspection_spec.rb index 4e64ded..02a21bc 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 cf69db2..10fdbf5 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,44 @@ def userinfo(scope:) expect(userinfo(scope: "openid profile")).not_to include("social_profiles") end + describe "the patches claim" do + let(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let(:europa) { create(:patch, slug: "europa", name: "Europa") } + + 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 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 + + 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 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: "") + give(europa, "viewer") + + expect(userinfo(scope: "openid patches")).to include("patches" => {}) + end + + it "is not sent without the patches scope" do + give(europa, "viewer") + + 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/patch_role_groups_spec.rb b/spec/requests/patch_role_groups_spec.rb new file mode 100644 index 0000000..66b2170 --- /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/knot_settings_spec.rb b/spec/services/knot_settings_spec.rb index f19dfab..6c7e4a7 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/patch_role_import_spec.rb b/spec/services/patch_role_import_spec.rb new file mode 100644 index 0000000..db713e8 --- /dev/null +++ b/spec/services/patch_role_import_spec.rb @@ -0,0 +1,185 @@ +# 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 + 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) + 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(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)"], + [: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"] + ] + ) + 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_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 diff --git a/spec/services/patch_roles_spec.rb b/spec/services/patch_roles_spec.rb new file mode 100644 index 0000000..0827194 --- /dev/null +++ b/spec/services/patch_roles_spec.rb @@ -0,0 +1,87 @@ +# 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) } + let!(:ganymede) { create(:patch, slug: "ganymede", name: "Project Ganymede") } + let!(:europa) { 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 + + 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) + + travel 2.days do + expect(claim).to eq("ganymede" => ["finance"]) + end + end + + 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(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) + + expect(claim).to eq({}) + expect(described_class.for(nil)).to eq({}) + end + + it "leaves out a removed assignment and a deleted role" do + give(europa, "viewer").destroy! + give(ganymede, "reviewer") + role(ganymede, "reviewer").destroy! + + expect(claim).to eq({}) + end + + it "does not leak a role of another patch or another person" do + give(europa, "viewer", to: create(:user, :verified)) + give(ganymede, "viewer") + + expect(claim).to eq("ganymede" => ["viewer"]) + 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