OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
[#62107] Update a few SCIM related things.
Pavel Balashou5fe52f3a64b0
diff --git a/app/controllers/scim_v2/groups_controller.rb b/app/controllers/scim_v2/groups_controller.rbindex 94dec422b3a..a48d765c141 100644--- a/app/controllers/scim_v2/groups_controller.rb+++ b/app/controllers/scim_v2/groups_controller.rb@@ -38,10 +38,11 @@ module ScimV2group = storage_class.newgroup.from_scim!(scim_hash: scim_resource.as_json)call = Groups::CreateService- .new(user: User.system)+ .new(user: User.system, model: group).call(group.attributes).on_failure { |result| raise result.message }group = call.result+Groups::AddUsersService.new(group, current_user: User.system).call(ids: scim_resource.members.map(&:value), send_notifications: false)@@ -61,6 +62,21 @@ module ScimV2.new(user: User.system, model: group).call(user_ids: scim_resource.members.map(&:value)).on_failure { |call| raise call.message }+ group.reload+ group.to_scim(location: url_for(action: :show, id: group.id))+ end+ end+ end++ def update+ super do |group_id, patch_hash|+ storage_class.transaction do+ group = storage_scope.find(group_id)+ group.from_scim_patch!(patch_hash: patch_hash)+ Groups::UpdateService+ .new(user: User.system, model: group)+ .call+ .on_failure { |call| raise call.message }group.to_scim(location: url_for(action: :show, id: group.id))endend@@ -83,7 +99,7 @@ module ScimV2enddef storage_scope- Group.all+ Group.left_joins(:users, :user_auth_provider_links).includes(:users, :user_auth_provider_links).not_builtinendendenddiff --git a/app/controllers/scim_v2/users_controller.rb b/app/controllers/scim_v2/users_controller.rbindex 5d8fad44c89..7da11df0565 100644--- a/app/controllers/scim_v2/users_controller.rb+++ b/app/controllers/scim_v2/users_controller.rb@@ -37,10 +37,23 @@ module ScimV2storage_class.transaction douser = storage_class.newuser.from_scim!(scim_hash: scim_resource.as_json)+ user.firstname = "123" if user.firstname.blank?+ user.lastname = "456" if user.lastname.blank?call = Users::CreateService- .new(user: User.system)+ .new(user: User.system, model: user).call(user.attributes)- .on_failure { |result| raise result.message }+ .on_failure do |result|+ uniqueness_error = result.errors.find { |e| e.type == :taken }+ if uniqueness_error.present?+ raise Scimitar::ErrorResponse.new(+ status: 409,+ scimType: "uniqueness",+ detail: "Operation failed due to a uniqueness constraint: #{result.message}"+ )+ else+ raise result.message+ end+ enduser = call.resultuser.to_scim(location: url_for(action: :show, id: user.id))@@ -62,6 +75,20 @@ module ScimV2endend+ def update+ super do |user_id, patch_hash|+ storage_class.transaction do+ user = storage_scope.find(user_id)+ user.from_scim_patch!(patch_hash: patch_hash)+ Users::UpdateService+ .new(user: User.system, model: user)+ .call+ .on_failure { |call| raise call.message }+ user.to_scim(location: url_for(action: :show, id: user.id))+ end+ end+ end+def destroysuper do |user_id|user = storage_scope.find(user_id)@@ -79,7 +106,7 @@ module ScimV2enddef storage_scope- User.not_builtin+ User.left_joins(:groups, :user_auth_provider_links).includes(:groups, :user_auth_provider_links).not_builtinendendenddiff --git a/app/models/group.rb b/app/models/group.rbindex dfaa753d9eb..083b6c6b483 100644--- a/app/models/group.rb+++ b/app/models/group.rb@@ -70,16 +70,17 @@ class Group < Principalenddef scim_external_id- return nil if identity_url.blank?-- identity_url.split(":", 2).second+ active_user_auth_provider_link&.external_idenddef scim_external_id=(external_id)oidc_provider = OpenIDConnect::Provider.firstraise "There should at least one OIDC Provider for SCIM to work with" unless oidc_provider- self.identity_url = "#{oidc_provider.slug}:#{external_id}"+ ::Groups::SetAttributesService+ .new(user: User.system, model: self, contract_class: EmptyContract)+ .call(identity_url: "#{oidc_provider.slug}:#{external_id}")+ .on_failure { |result| raise result.to_s }external_idend@@ -133,7 +134,8 @@ class Group < Principaldef self.scim_queryable_attributes{- displayName: { column: :lastname }+ displayName: { column: :lastname },+ externalId: { column: UserAuthProviderLink.arel_table[:external_id] }}enddiff --git a/app/models/principal.rb b/app/models/principal.rbindex c031896c8cb..2b0e16c495f 100644--- a/app/models/principal.rb+++ b/app/models/principal.rb@@ -65,6 +65,8 @@ class Principal < ApplicationRecordforeign_key: "user_id"has_many :projects, through: :membershipshas_many :categories, foreign_key: "assigned_to_id", dependent: :nullify, inverse_of: :assigned_to+ has_many :user_auth_provider_links, dependent: :destroy, foreign_key: :user_id+ has_many :auth_providers, through: :user_auth_provider_linkshas_paper_trail@@ -157,6 +159,20 @@ class Principal < ApplicationRecord.or(me)end+ def active_user_auth_provider_link+ # note: order("updated_at") is not used, because it returns nil if relation is not persisted+ user_auth_provider_links.max_by(&:updated_at)+ end++ def identity_url+ link = active_user_auth_provider_link+ "#{link.auth_provider.slug}:#{link.external_id}" if link.present?+ end++ def authentication_provider+ active_user_auth_provider_link&.auth_provider+ end+# Helper method to identify internal usersdef builtin?falsediff --git a/app/models/user.rb b/app/models/user.rbindex 06ccd821388..0d4eb649c83 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -98,8 +98,6 @@ class User < Principalhas_many :emoji_reactions, dependent: :destroyhas_many :reminders, foreign_key: "creator_id", dependent: :destroy, inverse_of: :creatorhas_many :remote_identities, dependent: :destroy- has_many :user_auth_provider_links, dependent: :destroy- has_many :auth_providers, through: :user_auth_provider_links# Users blocked via brute force prevention# use lambda here, so time is evaluated on each query@@ -312,20 +310,6 @@ class User < Principalendend- def active_user_auth_provider_link- # note: order("updated_at") is not used, because it returns nil if relation is not persisted- user_auth_provider_links.max_by(&:updated_at)- end-- def identity_url- link = active_user_auth_provider_link- "#{link.auth_provider.slug}:#{link.external_id}" if link.present?- end-- def authentication_provider- active_user_auth_provider_link&.auth_provider- end-# Return user's authentication provider for displaydef human_authentication_providerauthentication_provider&.display_name@@ -573,16 +557,17 @@ class User < Principalenddef scim_external_id- return nil if identity_url.blank?-- identity_url.split(":", 2).second+ active_user_auth_provider_link&.external_idenddef scim_external_id=(external_id)oidc_provider = OpenIDConnect::Provider.firstraise "There should at least one OIDC Provider for SCIM to work with" unless oidc_provider- self.identity_url = "#{oidc_provider.slug}:#{external_id}"+ ::Users::SetAttributesService+ .new(user: User.system, model: self, contract_class: EmptyContract)+ .call(identity_url: "#{oidc_provider.slug}:#{external_id}")+ .on_failure { |result| raise result.to_s }external_idend@@ -600,6 +585,15 @@ class User < Principalactive?end+ Email = Struct.new("Email", :value, :primary, :type)+ def scim_emails+ [Email.new(mail, true, "work")]+ end++ def scim_emails=(emails)+ self.mail = emails.first.value+ end+def self.scim_resource_typeScimitar::Resources::Userend@@ -615,21 +609,23 @@ class User < Principal},emails: [{- match: "type",- with: "work",+ list: :scim_emails,+ class: User,using: {- value: :mail,- primary: true- }+ value: :value,+ primary: :primary,+ type: :type+ },+ find_with: Proc.new do |qwe|+ Email.new(qwe["value"], !!qwe["primary"], qwe["type"])+ end}],-groups: [{list: :groups,using: {- value: :id,- # TODO $ref seems to be mandadory accroding to the spec.+ value: :id}}],@@ -644,6 +640,8 @@ class User < Principaldef self.scim_queryable_attributes{+ externalId: { column: UserAuthProviderLink.arel_table[:external_id] },+ username: { column: :login },givenName: { column: :firstname },familyName: { column: :lastname },emails: { column: :mail },diff --git a/app/models/user_auth_provider_link.rb b/app/models/user_auth_provider_link.rbindex 5d13653b217..de7925b22d7 100644--- a/app/models/user_auth_provider_link.rb+++ b/app/models/user_auth_provider_link.rb@@ -29,7 +29,7 @@#++class UserAuthProviderLink < ApplicationRecord- belongs_to :user+ belongs_to :principal, foreign_key: :user_idbelongs_to :auth_providerscope :with_identity_url, ->(identity_url) dodiff --git a/app/services/base_services/create.rb b/app/services/base_services/create.rbindex eaf18c7157a..ae3b76efaf3 100644--- a/app/services/base_services/create.rb+++ b/app/services/base_services/create.rb@@ -1,3 +1,5 @@+# frozen_string_literal: true+#-- copyright# OpenProject is an open source project management software.# Copyright (C) the OpenProject GmbH@@ -28,6 +30,11 @@module BaseServicesclass Create < Write+ def initialize(user:, model: nil, contract_class: nil, contract_options: {})+ self.model = model+ super(user:, contract_class:, contract_options:)+ end+protecteddef service_context(send_notifications:, &)@@ -35,7 +42,7 @@ module BaseServicesenddef instance(_params)- instance_class.new+ model || instance_class.newenddef default_contract_classdiff --git a/app/services/groups/set_attributes_service.rb b/app/services/groups/set_attributes_service.rbindex b6440352c8b..9393d4fa896 100644--- a/app/services/groups/set_attributes_service.rb+++ b/app/services/groups/set_attributes_service.rb@@ -1,3 +1,5 @@+# frozen_string_literal: true+#-- copyright# OpenProject is an open source project management software.# Copyright (C) the OpenProject GmbH@@ -32,6 +34,7 @@ module Groupsdef set_attributes(params)set_users(params) if params.key?(:user_ids)+ set_user_auth_provider_links(params.delete(:identity_url))superend@@ -48,6 +51,27 @@ module Groupsmark_outdated_users existing_user_ids - user_idsend+ def set_user_auth_provider_links(identity_url)+ if identity_url.present?+ slug, external_id = identity_url.split(":", 2)+ if slug.present? && external_id.present?+ auth_provider_id = AuthProvider.where(slug:).pick(:id)+ if auth_provider_id.present?+ link = model.user_auth_provider_links+ .find_or_initialize_by(auth_provider_id:)+ link.assign_attributes(external_id:, principal: model)+ if link.changed? && link.persisted?+ link.save!+ model.user_auth_provider_links.reload+ model.user_auth_provider_links.find { |l| l.id == link.id }.external_id_will_change!+ end+ else+ raise ActiveRecord::RecordNotFound, "AuthProvider with slug: \"#{slug}\" has been not found"+ end+ end+ end+ end+def build_new_users(new_user_ids)new_user_ids.each do |id|model.group_users.build(user_id: id)diff --git a/app/services/users/set_attributes_service.rb b/app/services/users/set_attributes_service.rbindex 99aeb5e0fd7..79409a0573a 100644--- a/app/services/users/set_attributes_service.rb+++ b/app/services/users/set_attributes_service.rb@@ -69,10 +69,14 @@ module Usersif slug.present? && external_id.present?auth_provider_id = AuthProvider.where(slug:).pick(:id)if auth_provider_id.present?- model- .user_auth_provider_links- .find_or_initialize_by(auth_provider_id:)- .assign_attributes(external_id:)+ link = model.user_auth_provider_links+ .find_or_initialize_by(auth_provider_id:)+ link.assign_attributes(external_id:, principal: model)+ if link.changed? && link.persisted?+ link.save!+ model.user_auth_provider_links.reload+ model.user_auth_provider_links.find { |l| l.id == link.id }.external_id_will_change!+ endelseraise ActiveRecord::RecordNotFound, "AuthProvider with slug: \"#{slug}\" has been not found"enddiff --git a/config/initializers/scimitar.rb b/config/initializers/scimitar.rbindex b5fcb6807f0..6069bb87a87 100644--- a/config/initializers/scimitar.rb+++ b/config/initializers/scimitar.rb@@ -29,12 +29,26 @@#++Rails.application.config.to_prepare do- Scimitar.service_provider_configuration = Scimitar::ServiceProviderConfiguration.new({- patch: Scimitar::Supportable.unsupported- })+ Scimitar.service_provider_configuration = Scimitar::ServiceProviderConfiguration.new(+ patch: Scimitar::Supportable.supported+ )Scimitar.engine_configuration = Scimitar::EngineConfiguration.new(token_authenticator: Proc.new do |_token, _options|OpenProject::FeatureDecisions.scim_api_active?end)++ module ScimitarSchemaExtension+ def scim_attributes+ super + [Scimitar::Schema::Attribute.new(name: "externalId", type: "string")]+ end+ end++ Scimitar::Schema::User.singleton_class.class_eval do+ prepend ScimitarSchemaExtension+ end++ Scimitar::Schema::Group.singleton_class.class_eval do+ prepend ScimitarSchemaExtension+ endenddiff --git a/config/routes.rb b/config/routes.rbindex 1f326aa1803..dd6a75be777 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -900,12 +900,14 @@ Rails.application.routes.draw doget "Users/:id", to: "users#show"post "Users", to: "users#create"put "Users/:id", to: "users#replace"+ patch "Users/:id", to: "users#update"delete "Users/:id", to: "users#destroy"get "Groups", to: "groups#index"get "Groups/:id", to: "groups#show"post "Groups", to: "groups#create"put "Groups/:id", to: "groups#replace"+ patch "Groups/:id", to: "groups#update"delete "Groups/:id", to: "groups#destroy"enddiff --git a/spec/factories/principal_factory.rb b/spec/factories/principal_factory.rbindex 315f6a660d8..b397119d195 100644--- a/spec/factories/principal_factory.rb+++ b/spec/factories/principal_factory.rb@@ -47,6 +47,7 @@ FactoryBot.define doglobal_roles { [] }global_permissions { [] }+ identity_url { nil }endcallback(:after_build) do |_principal, evaluator|@@ -73,6 +74,13 @@ FactoryBot.define doendcallback(:after_create) do |principal, evaluator|+ if evaluator.identity_url.present?+ slug, external_id = evaluator.identity_url.split(":", 2)+ raise "slug or external_id is blank" if slug.blank? || external_id.blank?++ auth_provider = AuthProvider.find_by(slug:) || create(:oidc_provider, slug:)+ principal.user_auth_provider_links.create!(auth_provider:, external_id:)+ endevaluator.member_with_permissions.each do |object, permissions|if object.is_a?(Project)role = create(:project_role, permissions:)diff --git a/spec/factories/user_factory.rb b/spec/factories/user_factory.rbindex cab39ac30b1..81273041bab 100644--- a/spec/factories/user_factory.rb+++ b/spec/factories/user_factory.rb@@ -41,7 +41,6 @@ FactoryBot.define dopreferences { {} }authentication_provider { nil }external_id { SecureRandom.uuid }- identity_url { nil }endlanguage { "en" }@@ -68,13 +67,6 @@ FactoryBot.define douser.user_auth_provider_links.create!(auth_provider: factory.authentication_provider,external_id: factory.external_id)end- if factory.identity_url.present?- slug, external_id = factory.identity_url.split(":", 2)- raise "slug or external_id is blank" if slug.blank? || external_id.blank?-- auth_provider = AuthProvider.find_by(slug:) || create(:oidc_provider, slug:)- user.user_auth_provider_links.create!(auth_provider:, external_id:)- endendcallback(:after_stub) do |user, evaluator|diff --git a/spec/requests/scim_v2/groups_spec.rb b/spec/requests/scim_v2/groups_spec.rbindex c087c0da55c..885f6f37e04 100644--- a/spec/requests/scim_v2/groups_spec.rb+++ b/spec/requests/scim_v2/groups_spec.rb@@ -63,7 +63,7 @@ RSpec.describe "SCIM API Groups" doendit "filters results" do- filter = ERB::Util.url_encode('displayName Eq "' + group.name + '"')+ filter = ERB::Util.url_encode("displayName Eq \"#{group.name}\"")get "/scim_v2/Groups?filter=#{filter}", {}, headersresponse_body = JSON.parse(last_response.body)@@ -85,11 +85,11 @@ RSpec.describe "SCIM API Groups" doget "/scim_v2/Groups?filter=#{filter}", {}, headersresponse_body = JSON.parse(last_response.body)- expect(response_body).to eq({"Resources" => [],- "itemsPerPage" => 100,- "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],- "startIndex" => 1,- "totalResults" => 0})+ expect(response_body).to eq({ "Resources" => [],+ "itemsPerPage" => 100,+ "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ "startIndex" => 1,+ "totalResults" => 0 })endend@@ -237,7 +237,7 @@ RSpec.describe "SCIM API Groups" do"displayName" => group.name,"members" => [{ "value" => user.id.to_s },- { "value" => admin.id.to_s },+ { "value" => admin.id.to_s }],"schemas" => ["urn:ietf:params:scim:schemas:core:2.0:Group"]}@@ -250,8 +250,8 @@ RSpec.describe "SCIM API Groups" do"externalId" => new_external_group_id,"id" => group.id.to_s,"members" => [- { "value" => admin.id.to_s },{ "value" => user.id.to_s },+ { "value" => admin.id.to_s }],"meta" => { "location" => "http://test.host/scim_v2/Groups/#{group.id}","created" => group.created_at.iso8601,@@ -273,4 +273,47 @@ RSpec.describe "SCIM API Groups" doendendend++ describe "PATCH /scim_v2/Groups/:id" do+ context "with the feature flag enabled", with_flag: { scim_api: true } do+ it "changes external_id" do+ group+ new_external_group_id = "new_idp_user_id_123asdqwe12345"+ request_body = {+ "schemas" =>+ ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations" => [{+ "op" => "replace",+ "path" => "externalId",+ "value" => new_external_group_id+ }]+ }+ patch "/scim_v2/Groups/#{group.id}", request_body.to_json, headers++ response_body = JSON.parse(last_response.body)+ group.reload+ expect(response_body).to eq({ "displayName" => group.name,+ "externalId" => new_external_group_id,+ "id" => group.id.to_s,+ "members" => [{ "value" => user.id.to_s }],+ "meta" => { "location" => "http://test.host/scim_v2/Groups/#{group.id}",+ "created" => group.created_at.iso8601,+ "lastModified" => group.updated_at.iso8601,+ "resourceType" => "Group" },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:Group"] })+ end+ end++ context "with the feature flag disabled", with_flag: { scim_api: false } do+ it do+ patch "/scim_v2/Groups/123", "", headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq(+ { "detail" => "Requires authentication", "schemas" => ["urn:ietf:params:scim:api:messages:2.0:Error"],+ "status" => "401" }+ )+ end+ end+ endenddiff --git a/spec/requests/scim_v2/service_provider_config_spec.rb b/spec/requests/scim_v2/service_provider_config_spec.rbnew file mode 100644index 00000000000..446dcc5b4d0--- /dev/null+++ b/spec/requests/scim_v2/service_provider_config_spec.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#++++require "spec_helper"++RSpec.describe "SCIM API ServiceProviderConfig" do+ let(:external_user_id) { "idp_user_id_123asdqwe12345" }+ let(:external_group_id) { "idp_group_id_123asdqwe12345" }+ let(:admin) { create(:admin) }+ let(:oidc_provider) { create(:oidc_provider, slug: "keycloak", creator: admin) }+ let(:user) { create(:user, identity_url: "#{oidc_provider.slug}:#{external_user_id}") }+ let(:group) { create(:group, identity_url: "#{oidc_provider.slug}:#{external_group_id}", members: [user]) }+ let(:headers) { { "CONTENT_TYPE" => "application/scim+json", "HTTP_AUTHORIZATION" => "Bearer access_token" } }++ describe "GET /scim_v2/ServiceProviderConfig" do+ context "with the feature flag enabled", with_flag: { scim_api: true } do+ before { group }++ it do+ get "/scim_v2/ServiceProviderConfig", {}, headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to include({ "authenticationSchemes" => [{ "description" => "Authentication scheme using the HTTP Basic Standard",+ "name" => "HTTP Basic",+ "type" => "httpbasic" },+ { "description" => "Authentication scheme using the OAuth Bearer Token Standard",+ "name" => "OAuth Bearer Token",+ "type" => "oauthbearertoken" }],+ "bulk" => { "supported" => false },+ "changePassword" => { "supported" => false },+ "etag" => { "supported" => false },+ "filter" => { "maxResults" => 100,+ "supported" => true },+ "patch" => { "supported" => true },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"],+ "sort" => { "supported" => false } })+ end+ end++ context "with the feature flag disabled", with_flag: { scim_api: false } do+ it do+ get "/scim_v2/ServiceProviderConfig", {}, headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq(+ { "detail" => "Requires authentication", "schemas" => ["urn:ietf:params:scim:api:messages:2.0:Error"],+ "status" => "401" }+ )+ end+ end+ end+enddiff --git a/spec/requests/scim_v2/users_spec.rb b/spec/requests/scim_v2/users_spec.rbindex 825ca2c0ed2..c94def7034c 100644--- a/spec/requests/scim_v2/users_spec.rb+++ b/spec/requests/scim_v2/users_spec.rb@@ -77,16 +77,15 @@ RSpec.describe "SCIM API Users" do"name" => { "familyName" => user.lastname,"givenName" => user.firstname },"schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],- "userName" => user.login },- ],+ "userName" => user.login }],"itemsPerPage" => 100,"schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex" => 1,"totalResults" => 2)end- it "filters results" do- filter_with_existing_rows = ERB::Util.url_encode('familyName Eq "' + user.lastname + '"')+ it "filters results by familyName" do+ filter_with_existing_rows = ERB::Util.url_encode("familyName Eq \"#{user.lastname}\"")get "/scim_v2/Users?filter=#{filter_with_existing_rows}", {}, headersresponse_body = JSON.parse(last_response.body)@@ -114,13 +113,48 @@ RSpec.describe "SCIM API Users" doget "/scim_v2/Users?filter=#{filter_with_nonexisting_rows}", {}, headersresponse_body = JSON.parse(last_response.body)- expect(response_body).to eq({"Resources" => [],- "itemsPerPage" => 100,- "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],- "startIndex" => 1,- "totalResults" => 0})+ expect(response_body).to eq({ "Resources" => [],+ "itemsPerPage" => 100,+ "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ "startIndex" => 1,+ "totalResults" => 0 })end+ it "filters results by externalId" do+ filter_with_existing_rows = ERB::Util.url_encode("externalId Eq \"#{external_user_id}\"")+ get "/scim_v2/Users?filter=#{filter_with_existing_rows}", {}, headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq("Resources" => [{ "active" => true,+ "emails" => [{ "primary" => true,+ "type" => "work",+ "value" => user.mail }],+ "externalId" => external_user_id,+ "groups" => [{ "value" => group.id.to_s }],+ "id" => user.id.to_s,+ "meta" => { "created" => user.created_at.iso8601,+ "lastModified" => user.updated_at.iso8601,+ "location" => "http://test.host/scim_v2/Users/#{user.id}",+ "resourceType" => "User" },+ "name" => { "familyName" => user.lastname,+ "givenName" => user.firstname },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName" => user.login }],+ "itemsPerPage" => 100,+ "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ "startIndex" => 1,+ "totalResults" => 1)++ filter_with_nonexisting_rows = ERB::Util.url_encode('externalId Eq "NONEXISTENT EXTERNAL ID"')+ get "/scim_v2/Users?filter=#{filter_with_nonexisting_rows}", {}, headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq({ "Resources" => [],+ "itemsPerPage" => 100,+ "schemas" => ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ "startIndex" => 1,+ "totalResults" => 0 })+ endendcontext "with the feature flag disabled", with_flag: { scim_api: false } do@@ -178,6 +212,37 @@ RSpec.describe "SCIM API Users" dobefore { oidc_provider }context "with the feature flag enabled", with_flag: { scim_api: true } do+ context "when user with userName has already exists" do+ it do+ group+ request_body = {+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "externalId" => external_user_id,+ "userName" => user.login,+ "name" => {+ "givenName" => "John",+ "familyName" => "Doe"+ },+ "active" => true,+ "emails" => [{+ "value" => "[email protected]",+ "type" => "work",+ "primary" => true+ }]+ }++ post "/scim_v2/Users/", request_body.to_json, headers+++ expect(last_response.status).to eq(409)+ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq({ "schemas" => ["urn:ietf:params:scim:api:messages:2.0:Error"],+ "detail" => "Operation failed due to a uniqueness constraint: Username has already been taken.",+ "status" => "409",+ "scimType" => "uniqueness" })+ end+ end+it dorequest_body = {"schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],@@ -198,6 +263,45 @@ RSpec.describe "SCIM API Users" do}post "/scim_v2/Users/", request_body.to_json, headers+ response_body = JSON.parse(last_response.body)+ created_user = User.find_by(login: "jdoe")+ expect(created_user).to be_present+ expect(response_body).to eq({ "active" => true,+ "emails" => [{ "primary" => true,+ "type" => "work",+ "value" => "[email protected]" }],+ "externalId" => external_user_id,+ "groups" => [],+ "id" => created_user.id.to_s,+ "meta" => { "created" => created_user.created_at.iso8601,+ "lastModified" => created_user.updated_at.iso8601,+ "location" => "http://test.host/scim_v2/Users/#{created_user.id}",+ "resourceType" => "User" },+ "name" => { "familyName" => "Doe",+ "givenName" => "John" },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName" => "jdoe" })+ end++ it "microsoft style" do+ request_body = {+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "externalId" => external_user_id,+ "userName" => "jdoe",+ "name" => {+ "givenName" => "John",+ "familyName" => "Doe"+ },+ "active" => true,+ "emails" => [+ {+ "value" => "[email protected]",+ "type" => "untyped"+ }+ ]+ }+ post "/scim_v2/Users/", request_body.to_json, headers+response_body = JSON.parse(last_response.body)created_user = User.find_by(login: "jdoe")expect(response_body).to eq({ "active" => true,@@ -347,4 +451,92 @@ RSpec.describe "SCIM API Users" doendendend++ describe "PATCH /scim_v2/Users/:id" do+ let(:new_external_user_id) { "new_idp_user_id_123asdqwe12345" }++ before { group }++ context "with the feature flag enabled", with_flag: { scim_api: true } do+ it "changes external_id" do+ request_body = {+ "schemas" =>+ ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations" => [{+ "op" => "replace",+ "path" => "externalId",+ "value" => new_external_user_id+ }]+ }+ patch "/scim_v2/Users/#{user.id}", request_body.to_json, headers++ response_body = JSON.parse(last_response.body)+ user.reload+ expect(response_body).to eq({ "active" => true,+ "emails" => [{ "primary" => true,+ "type" => "work",+ "value" => user.mail }],+ "externalId" => new_external_user_id,+ "groups" => [{ "value" => group.id.to_s }],+ "id" => user.id.to_s,+ "meta" => { "created" => user.created_at.iso8601,+ "lastModified" => user.updated_at.iso8601,+ "location" => "http://test.host/scim_v2/Users/#{user.id}",+ "resourceType" => "User" },+ "name" => { "familyName" => user.lastname,+ "givenName" => user.firstname },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName" => user.login })+ end++ it "changes email value" do+ new_email_value = "[email protected]"+ request_body = {+ "schemas" =>+ ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations" => [{+ "op" => "replace",+ "path" => "emails[type eq \"work\"]",+ "value" =>+ {+ "type" => "work",+ "value" => new_email_value,+ "primary" => true+ }+ }]+ }+ patch "/scim_v2/Users/#{user.id}", request_body.to_json, headers++ response_body = JSON.parse(last_response.body)+ user.reload+ expect(response_body).to eq({ "active" => true,+ "emails" => [{ "primary" => true,+ "type" => "work",+ "value" => new_email_value }],+ "externalId" => user.scim_external_id,+ "groups" => [{ "value" => group.id.to_s }],+ "id" => user.id.to_s,+ "meta" => { "created" => user.created_at.iso8601,+ "lastModified" => user.updated_at.iso8601,+ "location" => "http://test.host/scim_v2/Users/#{user.id}",+ "resourceType" => "User" },+ "name" => { "familyName" => user.lastname,+ "givenName" => user.firstname },+ "schemas" => ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName" => user.login })+ end+ end++ context "with the feature flag disabled", with_flag: { scim_api: false } do+ it do+ patch "/scim_v2/Users/123", "", headers++ response_body = JSON.parse(last_response.body)+ expect(response_body).to eq(+ { "detail" => "Requires authentication", "schemas" => ["urn:ietf:params:scim:api:messages:2.0:Error"],+ "status" => "401" }+ )+ end+ end+ endend