powerhome-scimitar 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (116) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +708 -0
  4. data/Rakefile +16 -0
  5. data/app/controllers/scimitar/active_record_backed_resources_controller.rb +257 -0
  6. data/app/controllers/scimitar/application_controller.rb +157 -0
  7. data/app/controllers/scimitar/resource_types_controller.rb +28 -0
  8. data/app/controllers/scimitar/resources_controller.rb +203 -0
  9. data/app/controllers/scimitar/schemas_controller.rb +21 -0
  10. data/app/controllers/scimitar/service_provider_configurations_controller.rb +8 -0
  11. data/app/models/scimitar/authentication_error.rb +9 -0
  12. data/app/models/scimitar/authentication_scheme.rb +18 -0
  13. data/app/models/scimitar/bulk.rb +8 -0
  14. data/app/models/scimitar/complex_types/address.rb +12 -0
  15. data/app/models/scimitar/complex_types/base.rb +83 -0
  16. data/app/models/scimitar/complex_types/email.rb +12 -0
  17. data/app/models/scimitar/complex_types/entitlement.rb +12 -0
  18. data/app/models/scimitar/complex_types/ims.rb +12 -0
  19. data/app/models/scimitar/complex_types/name.rb +12 -0
  20. data/app/models/scimitar/complex_types/phone_number.rb +12 -0
  21. data/app/models/scimitar/complex_types/photo.rb +12 -0
  22. data/app/models/scimitar/complex_types/reference_group.rb +12 -0
  23. data/app/models/scimitar/complex_types/reference_member.rb +12 -0
  24. data/app/models/scimitar/complex_types/role.rb +12 -0
  25. data/app/models/scimitar/complex_types/x509_certificate.rb +12 -0
  26. data/app/models/scimitar/engine_configuration.rb +32 -0
  27. data/app/models/scimitar/error_response.rb +32 -0
  28. data/app/models/scimitar/errors.rb +14 -0
  29. data/app/models/scimitar/filter.rb +11 -0
  30. data/app/models/scimitar/filter_error.rb +22 -0
  31. data/app/models/scimitar/invalid_syntax_error.rb +9 -0
  32. data/app/models/scimitar/lists/count.rb +64 -0
  33. data/app/models/scimitar/lists/query_parser.rb +745 -0
  34. data/app/models/scimitar/meta.rb +7 -0
  35. data/app/models/scimitar/not_found_error.rb +10 -0
  36. data/app/models/scimitar/resource_invalid_error.rb +9 -0
  37. data/app/models/scimitar/resource_type.rb +29 -0
  38. data/app/models/scimitar/resources/base.rb +190 -0
  39. data/app/models/scimitar/resources/group.rb +13 -0
  40. data/app/models/scimitar/resources/mixin.rb +1524 -0
  41. data/app/models/scimitar/resources/user.rb +13 -0
  42. data/app/models/scimitar/schema/address.rb +25 -0
  43. data/app/models/scimitar/schema/attribute.rb +132 -0
  44. data/app/models/scimitar/schema/base.rb +90 -0
  45. data/app/models/scimitar/schema/derived_attributes.rb +24 -0
  46. data/app/models/scimitar/schema/email.rb +10 -0
  47. data/app/models/scimitar/schema/entitlement.rb +10 -0
  48. data/app/models/scimitar/schema/group.rb +27 -0
  49. data/app/models/scimitar/schema/ims.rb +10 -0
  50. data/app/models/scimitar/schema/name.rb +20 -0
  51. data/app/models/scimitar/schema/phone_number.rb +10 -0
  52. data/app/models/scimitar/schema/photo.rb +10 -0
  53. data/app/models/scimitar/schema/reference_group.rb +23 -0
  54. data/app/models/scimitar/schema/reference_member.rb +21 -0
  55. data/app/models/scimitar/schema/role.rb +10 -0
  56. data/app/models/scimitar/schema/user.rb +52 -0
  57. data/app/models/scimitar/schema/vdtp.rb +18 -0
  58. data/app/models/scimitar/schema/x509_certificate.rb +22 -0
  59. data/app/models/scimitar/service_provider_configuration.rb +60 -0
  60. data/app/models/scimitar/supportable.rb +14 -0
  61. data/app/views/layouts/scimitar/application.html.erb +14 -0
  62. data/config/initializers/scimitar.rb +111 -0
  63. data/config/routes.rb +6 -0
  64. data/lib/scimitar/engine.rb +63 -0
  65. data/lib/scimitar/support/hash_with_indifferent_case_insensitive_access.rb +216 -0
  66. data/lib/scimitar/support/utilities.rb +51 -0
  67. data/lib/scimitar/version.rb +13 -0
  68. data/lib/scimitar.rb +29 -0
  69. data/spec/apps/dummy/app/controllers/custom_create_mock_users_controller.rb +25 -0
  70. data/spec/apps/dummy/app/controllers/custom_destroy_mock_users_controller.rb +24 -0
  71. data/spec/apps/dummy/app/controllers/custom_replace_mock_users_controller.rb +25 -0
  72. data/spec/apps/dummy/app/controllers/custom_request_verifiers_controller.rb +30 -0
  73. data/spec/apps/dummy/app/controllers/custom_save_mock_users_controller.rb +24 -0
  74. data/spec/apps/dummy/app/controllers/custom_update_mock_users_controller.rb +25 -0
  75. data/spec/apps/dummy/app/controllers/mock_groups_controller.rb +13 -0
  76. data/spec/apps/dummy/app/controllers/mock_users_controller.rb +13 -0
  77. data/spec/apps/dummy/app/models/mock_group.rb +83 -0
  78. data/spec/apps/dummy/app/models/mock_user.rb +132 -0
  79. data/spec/apps/dummy/config/application.rb +18 -0
  80. data/spec/apps/dummy/config/boot.rb +2 -0
  81. data/spec/apps/dummy/config/environment.rb +2 -0
  82. data/spec/apps/dummy/config/environments/test.rb +38 -0
  83. data/spec/apps/dummy/config/initializers/cookies_serializer.rb +3 -0
  84. data/spec/apps/dummy/config/initializers/scimitar.rb +61 -0
  85. data/spec/apps/dummy/config/initializers/session_store.rb +3 -0
  86. data/spec/apps/dummy/config/routes.rb +45 -0
  87. data/spec/apps/dummy/db/migrate/20210304014602_create_mock_users.rb +24 -0
  88. data/spec/apps/dummy/db/migrate/20210308020313_create_mock_groups.rb +10 -0
  89. data/spec/apps/dummy/db/migrate/20210308044214_create_join_table_mock_groups_mock_users.rb +13 -0
  90. data/spec/apps/dummy/db/schema.rb +48 -0
  91. data/spec/controllers/scimitar/application_controller_spec.rb +296 -0
  92. data/spec/controllers/scimitar/resource_types_controller_spec.rb +94 -0
  93. data/spec/controllers/scimitar/resources_controller_spec.rb +247 -0
  94. data/spec/controllers/scimitar/schemas_controller_spec.rb +83 -0
  95. data/spec/controllers/scimitar/service_provider_configurations_controller_spec.rb +22 -0
  96. data/spec/models/scimitar/complex_types/address_spec.rb +18 -0
  97. data/spec/models/scimitar/complex_types/email_spec.rb +21 -0
  98. data/spec/models/scimitar/lists/count_spec.rb +147 -0
  99. data/spec/models/scimitar/lists/query_parser_spec.rb +830 -0
  100. data/spec/models/scimitar/resource_type_spec.rb +21 -0
  101. data/spec/models/scimitar/resources/base_spec.rb +485 -0
  102. data/spec/models/scimitar/resources/base_validation_spec.rb +86 -0
  103. data/spec/models/scimitar/resources/mixin_spec.rb +3562 -0
  104. data/spec/models/scimitar/resources/user_spec.rb +68 -0
  105. data/spec/models/scimitar/schema/attribute_spec.rb +99 -0
  106. data/spec/models/scimitar/schema/base_spec.rb +64 -0
  107. data/spec/models/scimitar/schema/group_spec.rb +87 -0
  108. data/spec/models/scimitar/schema/user_spec.rb +720 -0
  109. data/spec/requests/active_record_backed_resources_controller_spec.rb +1354 -0
  110. data/spec/requests/application_controller_spec.rb +61 -0
  111. data/spec/requests/controller_configuration_spec.rb +17 -0
  112. data/spec/requests/engine_spec.rb +45 -0
  113. data/spec/spec_helper.rb +101 -0
  114. data/spec/spec_helper_spec.rb +30 -0
  115. data/spec/support/hash_with_indifferent_case_insensitive_access_spec.rb +169 -0
  116. metadata +321 -0
data/README.md ADDED
@@ -0,0 +1,708 @@
1
+ # Scimitar
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/powerhome-scimitar.svg)](https://badge.fury.io/rb/powerhome-scimitar)
4
+ [![Build Status](https://app.travis-ci.com/powerhome/scimitar.svg?branch=main)](https://app.travis-ci.com/powerhome/scimitar)
5
+ [![License](https://img.shields.io/badge/license-mit-blue.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A SCIM v2 API endpoint implementation for Ruby On Rails.
8
+
9
+ For a list of changes and information on major version upgrades, please see `CHANGELOG.md`.
10
+
11
+
12
+
13
+ ## Overview
14
+
15
+ System for Cross-domain Identity Management (SCIM) is a protocol that helps systems synchronise user data between different business systems. A _service provider_ hosts a SCIM API endpoint implementation and the Scimitar gem is used to help quickly build this implementation. One or more _enterprise subscribers_ use these APIs to let that service know about changes in the enterprise's user (employee) list.
16
+
17
+ In the context of the names used by the SCIM standard, the service that is provided is some kind of software-as-a-service solution that the enterprise subscriber uses to assist with their day to day business. The enterprise maintains its user (employee) list via whatever means it wants, but includes SCIM support so that any third party services it uses can be kept up to date with adds, removals or changes to employee data.
18
+
19
+ * [Overview](https://en.wikipedia.org/wiki/System_for_Cross-domain_Identity_Management) at Wikipedia
20
+ * [More detailed introduction](http://www.simplecloud.info) at SimpleCloud
21
+ * SCIM v2 RFC [7642](https://tools.ietf.org/html/rfc7642): Concepts
22
+ * SCIM v2 RFC [7643](https://tools.ietf.org/html/rfc7643): Core schema
23
+ * SCIM v2 RFC [7644](https://tools.ietf.org/html/rfc7644): Protocol
24
+
25
+
26
+
27
+ ## Installation
28
+
29
+ Install using:
30
+
31
+ ```shell
32
+ gem install powerhome-scimitar
33
+ ```
34
+
35
+ In your Gemfile:
36
+
37
+ ```ruby
38
+ gem 'powerhome-scimitar', '~> 2.0'
39
+ ```
40
+
41
+ Scimitar uses [semantic versioning](https://semver.org) so you can be confident that patch and minor version updates for features, bug fixes and/or security patches will not break your application.
42
+
43
+
44
+
45
+ ## Heritage
46
+
47
+ Scimitar borrows heavily - to the point of cut-and-paste - from:
48
+
49
+ * [ScimEngine](https://github.com/Cisco-AMP/scim_engine) for the Rails controllers and resource-agnostic subclassing approach that makes supporting User and/or Group, along with custom resource types if you need them, quite easy.
50
+ * [ScimRails](https://github.com/lessonly/scim_rails) for the bearer token support, 'index' actions and filter support.
51
+ * [SCIM Query Filter Parser](https://github.com/ingydotnet/scim-query-filter-parser-rb) for advanced filter handling.
52
+
53
+ All three are provided under the MIT license. Scimitar is too.
54
+
55
+
56
+
57
+ ## Usage
58
+
59
+ Scimitar is best used with Rails and ActiveRecord, but it can be used with other persistence back-ends too - you just have to do more of the work in controllers using Scimitar's lower level controller subclasses, rather than relying on Scimitar's higher level ActiveRecord abstractions.
60
+
61
+ ### Authentication
62
+
63
+ Noting the _Security_ section later - to set up an authentication method, create a `config/initializers/scimitar.rb` in your Rails application and define a token-based authenticator and/or a username-password authenticator in the [engine configuration section documented in the sample file](https://github.com/powerhome/scimitar/blob/main/config/initializers/scimitar.rb). For example:
64
+
65
+ ```ruby
66
+ Scimitar.engine_configuration = Scimitar::EngineConfiguration.new({
67
+ token_authenticator: Proc.new do | token, options |
68
+
69
+ # This is where you'd write the code to validate `token` - the means by
70
+ # which your application issues tokens to SCIM clients, or validates them,
71
+ # is outside the scope of the gem; the required mechanisms vary by client.
72
+ # More on this can be found in the 'Security' section later.
73
+ #
74
+ SomeLibraryModule.validate_access_token(token)
75
+
76
+ end
77
+ })
78
+ ```
79
+
80
+ When it comes to token access, Scimitar neither enforces nor presumes any kind of encoding for bearer tokens. You can use anything you like, including encoding/encrypting JWTs if you so wish - https://rubygems.org/gems/jwt may be useful. The way in which a client might integrate with your SCIM service varies by client and you will have to check documentation to see how a token gets conveyed to that client in the first place (e.g. a full OAuth flow with your application, or just a static token generated in some UI which an administrator copies and pastes into their client's SCIM configuration UI).
81
+
82
+ **Important:** Under Rails 7 or later, you may need to wrap any Scimitar configuration with `Rails.application.config.to_prepare do...` to avoid `NameError: uninitialized constant...` exceptions arising due to autoloader problems:
83
+
84
+ ```ruby
85
+ Rails.application.config.to_prepare do
86
+ Scimitar.engine_configuration = Scimitar::EngineConfiguration.new({
87
+ # ...
88
+ end
89
+ end
90
+ ```
91
+
92
+ ### Routes
93
+
94
+ For each resource you support, add these lines to your `routes.rb`:
95
+
96
+ ```ruby
97
+ namespace :scim_v2 do
98
+ mount Scimitar::Engine, at: '/'
99
+
100
+ get 'Users', to: 'users#index'
101
+ get 'Users/:id', to: 'users#show'
102
+ post 'Users', to: 'users#create'
103
+ put 'Users/:id', to: 'users#replace'
104
+ patch 'Users/:id', to: 'users#update'
105
+ delete 'Users/:id', to: 'users#destroy'
106
+ end
107
+ ```
108
+
109
+ All routes then will be available at `https://.../scim_v2/...` via controllers you write in `app/controllers/scim_v2/...`, e.g. `app/controllers/scim_v2/users_controller.rb`. More on controllers later.
110
+
111
+ #### URL helpers
112
+
113
+ Internally Scimitar always invokes URL helpers in the controller layer. I.e. any variable path parameters will be resolved by Rails automatically. If you need more control over the way URLs are generated you can override any URL helper by redefining it in the application controller mixin. See the [`application_controller_mixin` engine configuration option](https://github.com/powerhome/scimitar/blob/main/config/initializers/scimitar.rb).
114
+
115
+ ### Data models
116
+
117
+ Scimitar assumes that each SCIM resource maps to a single corresponding class in your system. This might be an abstraction over more complex underpinings, but either way, a 1:1 relationship is expected. For example, a SCIM User might map to a User ActiveRecord model in your Rails application, while a SCIM Group might map to some custom class called Team which operates on a more complex set of data "under the hood".
118
+
119
+ Before writing any controllers, it's a good idea to examine the SCIM specification and figure out how you intend to map SCIM attributes in any resources of interest, to your local data. A [mixin is provided](https://github.com/powerhome/scimitar/blob/main/app/models/scimitar/resources/mixin.rb) which you can include in any plain old Ruby class (including, but not limited to ActiveRecord model classes) - a more readable form of the comments in this file [is in the RDoc output](https://www.rubydoc.info/gems/scimitar/Scimitar/Resources/Mixin).
120
+
121
+ The functionality exposed by the mixin is relatively complicated because the range of operations that the SCIM API supports is quite extensive. Rather than duplicate all the information here, please see the extensive comments in the mixin linked above for more information. There are examples in the [test suite's Rails models](https://github.com/powerhome/scimitar/tree/main/spec/apps/dummy/app/models), or for another example:
122
+
123
+ ```ruby
124
+ class User < ActiveRecord::Base
125
+
126
+ # The attributes in the SCIM section below include a reference to this
127
+ # hypothesised 'groups' HABTM relationship. All of the other "leaf node"
128
+ # Symbols - e.g. ":first_name", ":last_name" - are expected to be defined as
129
+ # accessors e.g. via ActiveRecord and your related database table columns,
130
+ # "attr_accessor" declarations, or bespoke "def foo"/"def foo=(value)". If a
131
+ # write accessor is not present, the attribute will not be writable via SCIM.
132
+ #
133
+ has_and_belongs_to_many :groups
134
+
135
+ # ===========================================================================
136
+ # SCIM MIXIN AND REQUIRED METHODS
137
+ # ===========================================================================
138
+ #
139
+ # All class methods shown below are mandatory unless otherwise commented.
140
+
141
+ def self.scim_resource_type
142
+ return Scimitar::Resources::User
143
+ end
144
+
145
+ def self.scim_attributes_map
146
+ return {
147
+ id: :id,
148
+ externalId: :scim_uid,
149
+ userName: :username,
150
+ name: {
151
+ givenName: :first_name,
152
+ familyName: :last_name
153
+ },
154
+ emails: [
155
+ {
156
+ match: 'type',
157
+ with: 'work',
158
+ using: {
159
+ value: :work_email_address,
160
+ primary: true
161
+ }
162
+ },
163
+ {
164
+ match: 'type',
165
+ with: 'home',
166
+ using: {
167
+ value: :home_email_address,
168
+ primary: false
169
+ }
170
+ },
171
+ ],
172
+ phoneNumbers: [
173
+ {
174
+ match: 'type',
175
+ with: 'work',
176
+ using: {
177
+ value: :work_phone_number,
178
+ primary: false
179
+ }
180
+ },
181
+ ],
182
+
183
+ # NB The 'groups' collection in a SCIM User resource is read-only, so
184
+ # we provide no ":find_with" key for looking up records for writing
185
+ # updates to the associated collection.
186
+ #
187
+ groups: [
188
+ {
189
+ list: :groups,
190
+ using: {
191
+ value: :id,
192
+ display: :display_name
193
+ }
194
+ }
195
+ ],
196
+ active: :is_active
197
+ }
198
+ end
199
+
200
+ def self.scim_mutable_attributes
201
+ return nil
202
+ end
203
+
204
+ # The attributes in this example include a reference to the same hypothesised
205
+ # 'Group' model as in the HABTM relationship above. In this case, in order to
206
+ # filter by "groups" or "groups.value", the 'column' entry must reference the
207
+ # Group model's ID column as an AREL attribute as shown below, and the SCIM
208
+ # controller's #storage_scope implementation must also introduce a #join with
209
+ # ':groups' - see the "Queries & Optimisations" section below.
210
+ #
211
+ def self.scim_queryable_attributes
212
+ return {
213
+ givenName: { column: :first_name },
214
+ familyName: { column: :last_name },
215
+ emails: { column: :work_email_address },
216
+ groups: { column: Group.arel_table[:id] },
217
+ "groups.value" => { column: Group.arel_table[:id] },
218
+ }
219
+ end
220
+
221
+ # Optional but recommended.
222
+ #
223
+ def self.scim_timestamps_map
224
+ {
225
+ created: :created_at,
226
+ lastModified: :updated_at
227
+ }
228
+ end
229
+
230
+ # If you omit any mandatory declarations, you'll get an exception raised by
231
+ # this inclusion which tells you which method(s) need(s) to be added.
232
+ #
233
+ include Scimitar::Resources::Mixin
234
+ end
235
+ ```
236
+
237
+ ### Controllers
238
+
239
+ #### ActiveRecord
240
+
241
+ If you use ActiveRecord, your controllers can potentially be extremely simple by subclassing [`Scimitar::ActiveRecordBackedResourcesController`](https://www.rubydoc.info/gems/scimitar/Scimitar/ActiveRecordBackedResourcesController) - at a minimum:
242
+
243
+ ```ruby
244
+ module Scim
245
+ class UsersController < Scimitar::ActiveRecordBackedResourcesController
246
+
247
+ protected
248
+
249
+ def storage_class
250
+ User
251
+ end
252
+
253
+ def storage_scope
254
+ User.all # Or e.g. "User.where(is_deleted: false)" - whatever base scope you require
255
+ end
256
+
257
+ end
258
+ end
259
+ ```
260
+
261
+ All data-layer actions are taken via `#find` or `#save!`, with exceptions such as `ActiveRecord::RecordNotFound`, `ActiveRecord::RecordInvalid` or generalised SCIM exceptions handled by various superclasses. For a real Rails example of this, see the [test suite's controllers](https://github.com/powerhome/scimitar/tree/main/spec/apps/dummy/app/controllers) which are invoked via its [routing declarations](https://github.com/powerhome/scimitar/blob/main/spec/apps/dummy/config/routes.rb).
262
+
263
+ ##### Overriding controller methods
264
+
265
+ You can overwrite write-based controller methods `#create`, `#update`, `#replace` and `#destroy` in your controller subclass, should you wish, wherein a call to `super` is passed a block. The block is invoked with the instance of a new unsaved record for `#create`, the updated record that needs to have its changes saved for `#update` and `#replace` and the record that should be destroyed for `#destroy`. This allows you to do things like applying business logic, default values, extra request-derived data and so-forth before then calling `record.save!`, or using some different method other than `record.destroy!` to discard a record (e.g. you might be using soft-delete, or want to skip all callbacks for some reason via `record.delete`).
266
+
267
+ * The `#destroy` method just calls `record.destroy!` unless a block is given, with nothing much else to say about it.
268
+
269
+ * The other methods all establish a database transaction and call through to the _controller's_ protected `#save!` method, passing it the record; it is _this_ method which then either calls `record.save!` or invokes a block. Using the exception-throwing versions of persistence methods is recommended, as there is exception handling within the controller's implementation which rescues things like `ActiveRecord::RecordInvalid` and builds an appropriate SCIM error response when they occur. You can change the list of exceptions handled in this way by overriding protected method `#scimitar_rescuable_exceptions'.
270
+
271
+ * If you want to override saving behaviour for both new and modified records, overriding `#save!` in your controller subclass, rather than overriding all of `#create`, `#update` and `#replace`, is likely to be the better choice.
272
+
273
+ * For more information, see the [RDoc output for `Scimitar::ActiveRecordBackedResourcesController`](https://www.rubydoc.info/github/powerhome/scimitar/main/Scimitar/ActiveRecordBackedResourcesController).
274
+
275
+ Example:
276
+
277
+ ```ruby
278
+ module Scim
279
+ class UsersController < Scimitar::ActiveRecordBackedResourcesController
280
+
281
+ # Create all new records with some special internal field set to a value
282
+ # determined by a bespoke-to-your-application mechanism.
283
+ #
284
+ def create
285
+ super do | user |
286
+ user.some_special_on_creation_field = method_that_calculates_value()
287
+ user.save!
288
+ end
289
+ end
290
+
291
+ # Use #discard! rather than #destroy! as an example of soft-delete via the
292
+ # 'discard' gem - https://rubygems.org/gems/discard.
293
+ #
294
+ def destroy
295
+ super do | user |
296
+ user.discard!
297
+ end
298
+ end
299
+ end
300
+ ```
301
+
302
+ #### Queries & Optimisations
303
+
304
+ The scope can be optimised to eager load the data exposed by the SCIM interface, i.e.:
305
+
306
+ ```ruby
307
+ def storage_scope
308
+ User.eager_load(:groups)
309
+ end
310
+ ```
311
+
312
+ In cases where you have references to related columns in your `scim_queryable_attributes`, your `storage_scope` must join the relation:
313
+
314
+ ```ruby
315
+ def storage_scope
316
+ User.left_join(:groups)
317
+ end
318
+ ```
319
+
320
+ #### Other source types
321
+
322
+ If you do _not_ use ActiveRecord to store data, or if you have very esoteric read-write requirements, you can subclass [`Scimigar::ResourcesController`](https://www.rubydoc.info/gems/scimitar/Scimitar/ResourcesController) in a manner similar to this:
323
+
324
+ ```ruby
325
+ class UsersController < Scimitar::ResourcesController
326
+
327
+ # SCIM clients don't use Rails CSRF tokens.
328
+ #
329
+ skip_before_action :verify_authenticity_token
330
+
331
+ # If you have any filters you need to run BEFORE authentication done in
332
+ # the superclass (typically set up in config/initializers/scimitar.rb),
333
+ # then use "prepend_before_filter to declare these - else Scimitar's
334
+ # own authorisation before-action filter would always run first.
335
+
336
+ def index
337
+ # There's a degree of heavy lifting for arbitrary storage engines.
338
+ query = if params[:filter].present?
339
+ attribute_map = User.new.scim_queryable_attributes() # Note use of *instance* method
340
+ parser = Scimitar::Lists::QueryParser.new(attribute_map)
341
+
342
+ parser.parse(params[:filter])
343
+ # Then use 'parser' to read e.g. #tree or #rpn and turn this into a
344
+ # query object for your storage engine. With ActiveRecord, you could
345
+ # just do: parser.to_activerecord_query(base_scope)
346
+ else
347
+ # Return a query object for 'all results' (e.g. User.all).
348
+ end
349
+
350
+ # Assuming the 'query' object above had ActiveRecord-like semantics,
351
+ # you'd create a Scimitar::Lists::Count object with total count filled in
352
+ # via #scim_pagination_info and obtain a page of results with something
353
+ # like the code shown below.
354
+ pagination_info = scim_pagination_info(query.count())
355
+ page_of_results = query.offset(pagination_info.offset).limit(pagination_info.limit).to_a
356
+
357
+ super(pagination_info, page_of_results) do | record |
358
+ # Return each instance as a SCIM object, e.g. via Scimitar::Resources::Mixin#to_scim
359
+ record.to_scim(location: url_for(action: :show, id: record.id))
360
+ end
361
+ end
362
+
363
+ def show
364
+ super do |user_id|
365
+ user = find_user(user_id)
366
+ # Evaluate to the record as a SCIM object, e.g. via Scimitar::Resources::Mixin#to_scim
367
+ user.to_scim(location: url_for(action: :show, id: user_id))
368
+ end
369
+ end
370
+
371
+ def create
372
+ super do |scim_resource|
373
+ # Create an instance based on the Scimitar::Resources::User in
374
+ # "scim_resource" (or whatever your ::storage_class() defines via its
375
+ # ::scim_resource_type class method).
376
+ record = self.storage_class().new
377
+ record.from_scim!(scim_hash: scim_resource.as_json())
378
+ self.save!(record)
379
+ # Evaluate to the record as a SCIM object (or do that via "self.save!")
380
+ user.to_scim(location: url_for(action: :show, id: record.id))
381
+ end
382
+ end
383
+
384
+ def replace
385
+ super do |record_id, scim_resource|
386
+ # Fully update an instance based on the Scimitar::Resources::User in
387
+ # "scim_resource" (or whatever your ::storage_class() defines via its
388
+ # ::scim_resource_type class method). For example:
389
+ record = self.find_record(record_id)
390
+ record.from_scim!(scim_hash: scim_resource.as_json())
391
+ self.save!(record)
392
+ # Evaluate to the record as a SCIM object (or do that via "self.save!")
393
+ user.to_scim(location: url_for(action: :show, id: record_id))
394
+ end
395
+ end
396
+
397
+ def update
398
+ super do |record_id, patch_hash|
399
+ # Partially update an instance based on the PATCH payload *Hash* given
400
+ # in "patch_hash" (note that unlike the "scim_resource" parameter given
401
+ # to blocks in #create or #replace, this is *not* a high-level object).
402
+ record = self.find_record(record_id)
403
+ record.from_scim_patch!(patch_hash: patch_hash)
404
+ self.save!(record)
405
+ # Evaluate to the record as a SCIM object (or do that via "self.save!")
406
+ user.to_scim(location: url_for(action: :show, id: record_id))
407
+ end
408
+ end
409
+
410
+ def destroy
411
+ super do |user_id|
412
+ user = find_user(user_id)
413
+ user.delete
414
+ end
415
+ end
416
+
417
+ protected
418
+
419
+ # The class including Scimitar::Resources::Mixin which declares mappings
420
+ # to the entity you return in #resource_type.
421
+ #
422
+ def storage_class
423
+ User
424
+ end
425
+
426
+ # Find your user. The +id+ parameter is one of YOUR identifiers, which
427
+ # are returned in "id" fields in JSON responses via SCIM schema. If the
428
+ # remote caller (client) doesn't want to remember your IDs and hold a
429
+ # mapping to their IDs, then they do an index with filter on their own
430
+ # "externalId" value and retrieve your "id" from that response.
431
+ #
432
+ def find_user(id)
433
+ # Find records by your ID here.
434
+ end
435
+
436
+ # Persist 'user' - for example, if we *were* using ActiveRecord...
437
+ #
438
+ def save!(user)
439
+ user.save!
440
+ rescue ActiveRecord::RecordInvalid => exception
441
+ raise Scimitar::ResourceInvalidError.new(record.errors.full_messages.join('; '))
442
+ end
443
+
444
+ end
445
+
446
+ ```
447
+
448
+ Note that the [`Scimitar::ApplicationController` parent class](https://www.rubydoc.info/gems/scimitar/Scimitar/ApplicationController) of `Scimitar::ResourcesController` has a few methods to help with handling exceptions and rendering them as SCIM responses; for example, if a resource were not found by ID, you might wish to use [`Scimitar::ApplicationController#handle_resource_not_found`](https://github.com/powerhome/scimitar/blob/v1.0.3/app/controllers/scimitar/application_controller.rb#L22).
449
+
450
+ ### Extension schema
451
+
452
+ You can extend schema with custom data by defining an extension class and calling `::extend_schema` on the SCIM resource class to which the extension applies. These extension classes:
453
+
454
+ * Must subclass `Scimitar::Schema::Base`
455
+ * Must call `super` in `def initialize`, providing data as shown in the example below
456
+ * Must define class methods for `::id` and `::scim_attributes`
457
+
458
+ The `::id` class method defines a unique schema ID that is used to namespace payloads or paths in JSON responses describing extended resources, JSON payloads creating them or PATCH paths modifying them. The SCIM RFCs would refer to this as the URN. For example, we might choose to use the [RFC-defined User extension schema](https://tools.ietf.org/html/rfc7643#section-4.3) to define a couple of extra fields our User model happens to support:
459
+
460
+ ```ruby
461
+ class UserEnterpriseExtension < Scimitar::Schema::Base
462
+ def initialize(options = {})
463
+ super(
464
+ name: 'ExtendedUser',
465
+ description: 'Enterprise extension for a User',
466
+ id: self.class.id,
467
+ scim_attributes: self.class.scim_attributes
468
+ )
469
+ end
470
+
471
+ def self.id
472
+ 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User'
473
+ end
474
+
475
+ def self.scim_attributes
476
+ [
477
+ Scimitar::Schema::Attribute.new(name: 'organization', type: 'string'),
478
+ Scimitar::Schema::Attribute.new(name: 'department', type: 'string')
479
+ ]
480
+ end
481
+ end
482
+ ```
483
+
484
+ ...with the `super` call providing your choice of `name` and `description`, but also always providing `id` and `scim_attributes` as shown above. The class name chosen here is just an example and the class can be put inside any level of wrapping namespaces you choose - it's *your* class that can be named however you like. The extension class is then applied to the SCIM User resource _globally in your application_ by calling:
485
+
486
+ ```ruby
487
+ Scimitar::Resources::User.extend_schema(UserEnterpriseExtension)
488
+ ```
489
+
490
+ This is often done in `config/initializers/scimitar.rb` to help make it very clear that extensions are globally available and remove the risk of SCIM resources somehow being referenced before schema extensions have been applied.
491
+
492
+ In `def self.scim_attributes_map` in the underlying data model, add any new fields - `organization` and `department` in this example - to map them to whatever the equivalent data model attributes are, just as you would do with any other resource fields. These are declared without any special nesting - for example:
493
+
494
+ ```ruby
495
+ def self.scim_attributes_map
496
+ return {
497
+ id: :id,
498
+ externalId: :scim_uid,
499
+ userName: :username,
500
+ # ...etc...
501
+ organization: :company,
502
+ department: :team
503
+ }
504
+ end
505
+ ```
506
+
507
+ Whatever you provide in the `::id` method in your extension class will be used as a namespace in JSON data. This means that, for example, a SCIM representation of the above resource would look something like this:
508
+
509
+ ```json
510
+ {
511
+ "schemas": [
512
+ "urn:ietf:params:scim:schemas:core:2.0:User",
513
+ "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
514
+ ],
515
+ "id": "2819c223-7f76-453a-413861904646",
516
+ "externalId": "701984",
517
+ "userName": "bjensen@example.com",
518
+ // ...
519
+
520
+ "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
521
+ "organization": "Corporation Incorporated",
522
+ "department": "Marketing",
523
+ },
524
+ // ...
525
+ }
526
+ ```
527
+
528
+ ...and likewise, creation via `POST` would require the same nesting if a caller wanted to create a resource instance with those extended properties set (and RFC-compliant consumers of your SCIM API should already be doing this). For `PATCH` operations, [the `path` uses a _colon_ to separate the ID/URN part from the path](https://tools.ietf.org/html/rfc7644#section-3.10) rather than just using a dot as you might expect from the JSON nesting above:
529
+
530
+ ```json
531
+ {
532
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
533
+ "Operations": [
534
+ {
535
+ "op": "replace",
536
+ "path": "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:organization",
537
+ "value": "Sales"
538
+ }
539
+ ]
540
+ }
541
+ ```
542
+
543
+ Resource extensions can provide any fields you choose, under any ID/URN you choose, to either RFC-described resources or entirely custom SCIM resources. There are no hard-coded assumptions or other "magic" that might require you to only extend RFC-described resources with RFC-described extensions. Of course, if you use custom resources or custom extensions that are not described by the SCIM RFCs, then the SCIM API you provide may only work with custom-written API callers that are aware of your bespoke resources and/or extensions.
544
+
545
+ Extensions can also contain complex attributes such as groups. For instance, if you want the ability to write to groups from the User resource perspective (since 'groups' collection in a SCIM User resource is read-only), you can add one attribute to your extension like this:
546
+
547
+ ```ruby
548
+ Scimitar::Schema::Attribute.new(name: "userGroups", multiValued: true, complexType: Scimitar::ComplexTypes::ReferenceGroup, mutability: "writeOnly"),
549
+ ```
550
+
551
+ Then map it in your `scim_attributes_map`:
552
+
553
+ ```ruby
554
+ userGroups: [
555
+ {
556
+ list: :groups,
557
+ find_with: ->(value) { Group.find(value["value"]) },
558
+ using: {
559
+ value: :id,
560
+ display: :name
561
+ }
562
+ }
563
+ ]
564
+ ```
565
+
566
+ And write to it like this:
567
+
568
+ ```json
569
+ {
570
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
571
+ "Operations": [
572
+ {
573
+ "op": "replace",
574
+ "path": "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:userGroups",
575
+ "value": [{ "value": "1" }]
576
+ }
577
+ ]
578
+ }
579
+ ```
580
+
581
+ ## Security
582
+
583
+ One vital feature of SCIM is its authorisation and security model. The best resource I've found to describe this in any detail is [section 2 of the protocol RFC, 7644](https://tools.ietf.org/html/rfc7644#section-2).
584
+
585
+ Often, you'll find that bearer tokens are in use by SCIM API consumers, but the way in which this is used by that consumer in practice can vary a great deal. For example, suppose a corporation uses Microsoft Azure Active Directory to maintain a master database of employee details. Azure lets administrators [connect to SCIM endpoints](https://docs.microsoft.com/en-us/azure/active-directory/app-provisioning/how-provisioning-works) for services that this corporation might use. In all cases, bearer tokens are used.
586
+
587
+ * When the third party integration builds an app that it gets hosted in the Azure Marketplace, the token is obtained via full OAuth flow of some kind - the enterprise corporation would sign into your app by some OAuth UI mechanism you provide, which leads to a Bearer token being issued. Thereafter, the Azure system would quote this back to you in API calls via the `Authorization` HTTP header.
588
+
589
+ * If you are providing SCIM services as part of some wider service offering it might not make sense to go to the trouble of adding all the extra features and requirements for Marketplace inclusion. Fortunately, Microsoft support [addition of 'user-defined' enterprise "app" integrations](https://docs.microsoft.com/en-us/azure/active-directory/app-provisioning/use-scim-to-provision-users-and-groups#integrate-your-scim-endpoint-with-the-aad-scim-client) in Azure, so the administrator can set up and 'provision' your SCIM API endpoint. In _this_ case, the bearer token is just some string that you generate which they paste into the Azure AD UI. Clearly, then, this amounts to little more than a glorified password, but you can take steps to make sure that it's long, unguessable and potentially be some encrypted/encoded structure that allows you to make additional security checks on "your side" when you unpack the token as part of API request handling.
590
+
591
+ * HTTPS is obviously a given here and localhost integration during development is difficult; perhaps search around for things like POSTman collections to assist with development testing. Scimitar has a reasonably comprehensive internal test suite but it's only as good as the accuracy and reliability of the subclass code you write to "bridge the gap" between SCIM schema and actions, and your User/Group equivalent records and the operations you perform upon them. Microsoft provide [additional information](https://techcommunity.microsoft.com/t5/identity-standards-blog/provisioning-with-scim-design-build-and-test-your-scim-endpoint/ba-p/1204883) to help guide service provider implementors with best practice.
592
+
593
+
594
+
595
+ ## Limitations
596
+
597
+ ### Specification versus implementation
598
+
599
+ * The `name` complex type of a User has `givenName` and `familyName` fields which [the RFC 7643 core schema](https://tools.ietf.org/html/rfc7643#section-8.7.1) describes as optional. Scimitar marks these as required, in the belief that most user synchronisation scenarios between clients and a Scimitar-based provider would require at least those names for basic user management on the provider side, in conjunction with the in-spec-required `userName` field. That's only if the whole `name` type is given at all - at the top level, this itself remains optional per spec, but if you're going to bother specifying names at all, Scimitar wants at least those two pieces of data.
600
+
601
+ * Several complex types for User contain the same set of `value`, `display`, `type` and `primary` fields, all used in synonymous ways.
602
+
603
+ - The `value` field - which is e.g. an e-mail address or phone number - is described as optional by [the RFC 7643 core schema](https://tools.ietf.org/html/rfc7643#section-8.7.1), also using "SHOULD" rather than "MUST" in field descriptions elsewhere. Scimitar marks this as required by default, since there's not much point being sent (say) an e-mail section which has entries that don't provide the e-mail address. Some services might send `null` values here regardless so, if you need to be able to accept such data, you can set [engine configuration option `optional_value_fields_required`](https://github.com/powerhome/scimitar/blob/main/config/initializers/scimitar.rb) to `false`.
604
+
605
+ - The schema _descriptions_ for `display` declare that the field is something optionally sent by the service provider and state clearly that it is read-only - yet the formal schema declares it `readWrite`. Scimitar marks it as read-only.
606
+
607
+ * The `displayName` of a Group is described in [RFC 7643 section 4.2](https://tools.ietf.org/html/rfc7643#section-4.2) and in the free-text schema `description` field as required, but the schema nonetheless states `"required" : false` in the formal definition. We consider this to be an error and mark the property as `"required" : true`.
608
+
609
+ * In the `members` section of a [`Group` in the RFC 7643 core schema](https://tools.ietf.org/html/rfc7643#page-69), any member's `value` is noted as _not_ required but [the RFC also says](https://tools.ietf.org/html/rfc7643#section-4.2) "Service providers MAY require clients to provide a non-empty value by setting the "required" attribute characteristic of a sub-attribute of the "members" attribute in the "Group" resource schema". Scimitar does this. The `value` field would contain the `id` of a SCIM resource, which is the primary key on "our side" as a service provider. Just as we must store `externalId` values to maintain a mapping on "our side", we in turn _do_ require clients to provide our ID in group member lists via the `value` field.
610
+
611
+ * While the gem attempts to support difficult/complex filter strings via incorporating code and ideas in [SCIM Query Filter Parser](https://github.com/ingydotnet/scim-query-filter-parser-rb), it is possible that ActiveRecord / Rails precedence on some query operations in complex cases might not exactly match the SCIM specification. Please do submit a bug report if you encounter this. You may also wish to view [`query_parser_spec.rb`](https://github.com/powerhome/scimitar/blob/main/spec/models/scimitar/lists/query_parser_spec.rb) to get an idea of the tested examples - more interesting test cases are in the "`context 'with complex cases' do`" section.
612
+
613
+ * Group resource examples show the `members` array including field `display`, but this is not in the [formal schema](https://tools.ietf.org/html/rfc7643#page-69); Scimitar includes it in the Group definition.
614
+
615
+ * `POST` actions with only a subset of attributes specified treat missing attributes "to be cleared" for anything that's mapped for the target model. If you have defaults established at instantiation rather than (say) before-validation, you'll need to override `Scimitar::ActiveRecordBackedResourcesController#create` (if using that controller as a base class) as normally the controller just instantiates a model, applies _all_ attributes (with any mapped attribute values without an inbound value set to `nil`), then saves the record. This might cause default values to be overwritten. For consistency, `PUT` operations apply the same behaviour. The decision on this optional specification aspect is in part constrained by the difficulties of implementing `PATCH`.
616
+
617
+ * [RFC 7644 indicates](https://tools.ietf.org/html/rfc7644#page-35) that a resource might only return its core schema in the `schemas` attribute if it was created without any extension fields used. Only if e.g. a subsequent `PATCH` operation added data provided by extension schema, would that extension also appear in `schemas`. This behaviour is extremely difficult to implement and Scimitar does not try - it will always return a resource's core schema and any/all defined extension schemas in the `schemas` array at all times.
618
+
619
+ If you believe choices made in this section may be incorrect, please [create a GitHub issue](https://github.com/powerhome/scimitar/issues/new) describing the problem.
620
+
621
+ ### Omissions
622
+
623
+ * Bulk operations are not supported.
624
+
625
+ * List ("index") endpoint [filters in SCIM](https://tools.ietf.org/html/rfc7644#section-3.4.2.2) are _extremely_ complicated. There is a syntax for specifying equals, not-equals, precedence through parentheses and things like "and"/"or"/"not" along the lines of "attribute operator value", which Scimitar supports to a reasonably comprehensive degree but with some limitations discussed shortly. That aside, it isn't at all clear what some of the [examples in the RFC](https://tools.ietf.org/html/rfc7644#page-23) are even meant to mean. Consider:
626
+
627
+ - `filter=userType eq "Employee" and (emails co "example.com" or emails.value co "example.org")`
628
+
629
+ It's very strange just specifying `emails co...`, since this is an Array which contains complex types. Is the filter there meant to try and match every attribute of the nested types in all array entries? I.e. if `type` happened to contain `example.com`, is that meant to match? It's strongly implied, because the next part of the filter specifically says `emails.value`. Again, we have to reach a little and assume that `emails.value` means "in _any_ of the objects in the `emails` Array, match all things where `value` contains `example.org`. It seems likely that this is a specification error and both of the specifiers should be `emails.value`.
630
+
631
+ Adding even more complexity - the specification shows filters _which include filters within them_. In the same way that PATCH operations use paths to identify attributes not just by name, but by filter matches within collections - e.g. `emails[type eq "work"]`, for all e-mail objects inside the `emails` array with a `type` attribute that has a value of `work`) - so also can a filter _contain a filter_, which isn't supported. So, this [example from the RFC](https://tools.ietf.org/html/rfc7644#page-23) is not supported by Scimitar:
632
+
633
+ - `filter=userType eq "Employee" and emails[type eq "work" and value co "@example.com"]`
634
+
635
+ Another filter shows a potential workaround:
636
+
637
+ - `filter=userType eq "Employee" and (emails.type eq "work")`
638
+
639
+ ...which is just a match on `emails.type`, so if you have a queryable attribute mapping defined for `emails.type`, that would become queryable. Likewise, you could rewrite the more complex prior example thus:
640
+
641
+ - `filter=userType eq "Employee" and emails.type eq "work" and emails.value co "@example.com"`
642
+
643
+ ...so adding a mapping for `emails.value` would then allow a database query to be constructed.
644
+
645
+ * Currently filtering for lists is always matched case-insensitive regardless of schema declarations that might indicate otherwise, for `eq`, `ne`, `co`, `sw` and `ew` operators; for greater/less-thank style filters, case is maintained with simple `>`, `<` etc. database operations in use. The standard Group and User schema have `caseExact` set to `false` for just about anything readily queryable, so this hopefully would only ever potentially be an issue for custom schema.
646
+
647
+ * As an exception to the above, attributes `id`, `externalId` and `meta.*` are matched case-sensitive. Filters that use `eq` on such attributes will end up a comparison using `=` rather than e.g. `ILIKE` (arising from https://github.com/powerhome/scimitar/issues/36).
648
+
649
+ * The `PATCH` mechanism is supported, but where filters are included, only a single "attribute eq value" is permitted - no other operators or combinations. For example, a work e-mail address's value could be replaced by a PATCH patch of `emails[type eq "work"].value`. For in-path filters such as this, other operators such as `ne` are not supported; combinations with "and"/"or" are not supported; negation with "not" is not supported.
650
+
651
+ If you would like to see something listed in the session implemented, please [create a GitHub issue](https://github.com/powerhome/scimitar/issues/new) asking for it to be implemented, or if possible, implement the feature and send a Pull Request.
652
+
653
+
654
+
655
+ ## Development
656
+
657
+ Install Ruby dependencies first:
658
+
659
+ ```
660
+ bundle install
661
+ ```
662
+
663
+ ### Tests
664
+
665
+ For testing, two main options are available:
666
+
667
+ * The first option is running the project locally. This is also the recommended way, as running the tests on a variety of setups and platforms increases he chance of finding platform-specific or setup-specific bugs.
668
+ * The second option is utilising the existing Docker Compose setup provided in the project. You can use this if getting the project to work locally is hard or not feasible.
669
+
670
+ #### Testing on your machine
671
+
672
+ You will need to have PostgreSQL running. This database is chosen for tests to prove case-insensitive behaviour via detection of ILIKE in generated queries. Using SQLite would have resulted in a more conceptually self-contained test suite, but SQLite is case-insensitive by default and uses "LIKE" either way, making it hard to "see" if the query system is doing the right thing.
673
+
674
+ After `bundle install` and with PostgreSQL up, set up the test database with:
675
+
676
+ ```shell
677
+ pushd spec/apps/dummy
678
+ RAILS_ENV=test bundle exec bin/rails db:drop db:create db:migrate
679
+ popd
680
+ ```
681
+
682
+ ...and thereafter, run tests with:
683
+
684
+ ```
685
+ bundle exec rspec
686
+ ```
687
+
688
+ You can get an idea of arising test coverage by opening `coverage/index.html` in your preferred web browser.
689
+
690
+ #### Testing with Docker (Compose)
691
+
692
+ In order to be able to utilise the Docker Compose setup, you will need to have Docker installed with the Compose plugin. For an easy installation of Docker (with a GUI and the Compose plugin preinstalled) please see [Docker Desktop](https://www.docker.com/products/docker-desktop/).
693
+
694
+ In order to configure the Docker image, run `docker compose build` in a terminal of your choice, in the root of this project. This will download the required image and install the required libraries. After this is complete, running the tests is as easy as running the command `docker compose up test`.
695
+
696
+ As mentioned in the previous section, test coverage may be analysed using `coverage/index.html` after running the project.
697
+
698
+ You can also open a raw terminal in this test container by running `docker run --rm test sh`. For more Compose commands, please refer to [the Docker Compose reference manual](https://docs.docker.com/compose/reference/).
699
+
700
+ ### Internal documentation
701
+
702
+ Locally generated RDoc HTML seems to contain a more comprehensive and inter-linked set of pages than those available from `rubydoc.info`. You can (re)generate the internal [`rdoc` documentation](https://ruby-doc.org/stdlib-2.4.1/libdoc/rdoc/rdoc/RDoc/Markup.html#label-Supported+Formats) with:
703
+
704
+ ```shell
705
+ bundle exec rake rerdoc
706
+ ```
707
+
708
+ ...yes, that's `rerdoc` - Re-R-Doc - then open `docs/rdoc/index.html`.