-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathhandlers.go
More file actions
676 lines (601 loc) · 17.4 KB
/
handlers.go
File metadata and controls
676 lines (601 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
package scim
import (
"encoding/json"
"net/http"
"github.com/elimity-com/scim/errors"
"github.com/elimity-com/scim/filter"
"github.com/elimity-com/scim/schema"
)
func (s Server) errorHandler(w http.ResponseWriter, scimErr *errors.ScimError) {
raw, err := json.Marshal(scimErr)
if err != nil {
s.log.Error(
"failed marshaling scim error",
"scimError", scimErr,
"error", err,
)
return
}
w.WriteHeader(scimErr.Status)
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// parseSearchRequest reads and parses a search request body, returning a SearchParams.
func (s Server) parseSearchRequest(r *http.Request) (searchRequest, SearchParams, *errors.ScimError) {
data, err := readBody(r)
if err != nil {
return searchRequest{}, SearchParams{}, &errors.ScimErrorInternal
}
var sr searchRequest
if err := json.Unmarshal(data, &sr); err != nil {
scimErr := errors.ScimError{
Status: 400,
Detail: "Invalid search request body.",
}
return searchRequest{}, SearchParams{}, &scimErr
}
if len(sr.Schemas) != 1 || sr.Schemas[0] != "urn:ietf:params:scim:api:messages:2.0:SearchRequest" {
return searchRequest{}, SearchParams{}, &errors.ScimErrorInvalidValue
}
if sr.SortOrder != "" && sr.SortOrder != "ascending" && sr.SortOrder != "descending" {
return searchRequest{}, SearchParams{}, &errors.ScimErrorInvalidValue
}
defaultCount := s.config.getItemsPerPage()
count := defaultCount
if sr.Count != nil {
count = *sr.Count
}
if count > defaultCount {
count = defaultCount
}
if count < 0 {
count = 0
}
startIndex := defaultStartIndex
if sr.StartIndex != nil {
startIndex = *sr.StartIndex
}
if startIndex < 1 {
startIndex = defaultStartIndex
}
return sr, SearchParams{
Attributes: sr.Attributes,
Count: count,
ExcludedAttributes: sr.ExcludedAttributes,
Filter: sr.Filter,
SortBy: sr.SortBy,
SortOrder: sr.SortOrder,
StartIndex: startIndex,
}, nil
}
// resourceDeleteHandler receives an HTTP DELETE request to the resource endpoint, e.g., "/Users/{id}" or "/Groups/{id}",
// where "{id}" is a resource identifier to delete a known resource.
func (s Server) resourceDeleteHandler(w http.ResponseWriter, r *http.Request, id string, resourceType ResourceType) {
deleteErr := resourceType.Handler.Delete(r, id)
if deleteErr != nil {
scimErr := errors.CheckScimError(deleteErr, http.MethodDelete)
s.errorHandler(w, &scimErr)
return
}
w.WriteHeader(http.StatusNoContent)
}
// resourceGetHandler receives an HTTP GET request to the resource endpoint, e.g., "/Users/{id}" or "/Groups/{id}",
// where "{id}" is a resource identifier to retrieve a known resource.
func (s Server) resourceGetHandler(w http.ResponseWriter, r *http.Request, id string, resourceType ResourceType) {
resource, getErr := resourceType.Handler.Get(r, id)
if getErr != nil {
scimErr := errors.CheckScimError(getErr, http.MethodGet)
s.errorHandler(w, &scimErr)
return
}
location := resourceLocation(resourceType, id, s.baseURL)
raw, err := json.Marshal(resource.response(resourceType, location))
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling resource",
"resource", resource,
"error", err,
)
return
}
if resource.Meta.Version != "" {
w.Header().Set("Etag", resource.Meta.Version)
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourcePatchHandler receives an HTTP PATCH to the resource endpoint, e.g., "/Users/{id}" or "/Groups/{id}", where
// "{id}" is a resource identifier to replace a resource's attributes.
func (s Server) resourcePatchHandler(w http.ResponseWriter, r *http.Request, id string, resourceType ResourceType) {
patch, scimErr := resourceType.validatePatch(r)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
resource, patchErr := resourceType.Handler.Patch(r, id, patch)
if patchErr != nil {
scimErr := errors.CheckScimError(patchErr, http.MethodPatch)
s.errorHandler(w, &scimErr)
return
}
if len(resource.Attributes) == 0 {
w.WriteHeader(http.StatusNoContent)
return
}
location := resourceLocation(resourceType, id, s.baseURL)
raw, err := json.Marshal(resource.response(resourceType, location))
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling resource",
"resource", resource,
"error", err,
)
return
}
if resource.Meta.Version != "" {
w.Header().Set("Etag", resource.Meta.Version)
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourcePostHandler receives an HTTP POST request to the resource endpoint, such as "/Users" or "/Groups", as
// defined by the associated resource type endpoint discovery to create new resources.
func (s Server) resourcePostHandler(w http.ResponseWriter, r *http.Request, resourceType ResourceType) {
data, _ := readBody(r)
attributes, scimErr := resourceType.validate(data)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
resource, postErr := resourceType.Handler.Create(r, attributes)
if postErr != nil {
scimErr := errors.CheckScimError(postErr, http.MethodPost)
s.errorHandler(w, &scimErr)
return
}
location := resourceLocation(resourceType, resource.ID, s.baseURL)
raw, err := json.Marshal(resource.response(resourceType, location))
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling resource",
"resource", resource,
"error", err,
)
return
}
w.Header().Set("Location", location)
if resource.Meta.Version != "" {
w.Header().Set("Etag", resource.Meta.Version)
}
w.WriteHeader(http.StatusCreated)
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourcePutHandler receives an HTTP PUT to the resource endpoint, e.g., "/Users/{id}" or "/Groups/{id}", where
// "{id}" is a resource identifier to replace a resource's attributes.
func (s Server) resourcePutHandler(w http.ResponseWriter, r *http.Request, id string, resourceType ResourceType) {
data, _ := readBody(r)
attributes, scimErr := resourceType.validate(data)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
resource, putError := resourceType.Handler.Replace(r, id, attributes)
if putError != nil {
scimErr := errors.CheckScimError(putError, http.MethodPut)
s.errorHandler(w, &scimErr)
return
}
location := resourceLocation(resourceType, id, s.baseURL)
raw, err := json.Marshal(resource.response(resourceType, location))
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling resource",
"resource", resource,
"error", err,
)
return
}
if resource.Meta.Version != "" {
w.Header().Set("Etag", resource.Meta.Version)
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourceSearchHandler receives an HTTP POST request to a resource endpoint's /.search
// (e.g. /Users/.search) to query resources of that type.
func (s Server) resourceSearchHandler(w http.ResponseWriter, r *http.Request, resourceType ResourceType) {
searcher, ok := resourceType.Handler.(ResourceSearcher)
if !ok {
s.errorHandler(w, &errors.ScimError{
Status: 501,
Detail: "Search is not supported for this resource type.",
})
return
}
_, params, scimErr := s.parseSearchRequest(r)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
if params.Filter != "" {
validator, err := filter.NewValidator(params.Filter, resourceType.Schema, resourceType.getSchemaExtensions()...)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInvalidFilter)
return
}
if err := validator.Validate(); err != nil {
s.errorHandler(w, &errors.ScimErrorInvalidFilter)
return
}
params.FilterValidator = &validator
}
page, searchErr := searcher.Search(r, params)
if searchErr != nil {
scimErr := errors.CheckScimError(searchErr, http.MethodPost)
s.errorHandler(w, &scimErr)
return
}
lr := listResponse{
TotalResults: page.TotalResults,
Resources: page.resources(resourceType, s.baseURL),
StartIndex: params.StartIndex,
ItemsPerPage: params.Count,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourceTypeHandler receives an HTTP GET to retrieve individual resource types which can be returned by appending the
// resource types name to the /ResourceTypes endpoint. For example: "/ResourceTypes/User".
func (s Server) resourceTypeHandler(w http.ResponseWriter, r *http.Request, name string) {
var resourceType ResourceType
for _, r := range s.resourceTypes {
if r.Name == name {
resourceType = r
break
}
}
if resourceType.Name != name {
scimErr := errors.ScimErrorResourceNotFound(name)
s.errorHandler(w, &scimErr)
return
}
raw, err := json.Marshal(resourceType.getRaw())
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling resource type",
"resourceType", resourceType,
"error", err,
)
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourceTypesHandler receives an HTTP GET to this endpoint, "/ResourceTypes", which is used to discover the types of
// resources available on a SCIM service provider (e.g., Users and Groups). Each resource type defines the endpoints,
// the core schema URI that defines the resource, and any supported schema extensions.
func (s Server) resourceTypesHandler(w http.ResponseWriter, r *http.Request) {
params, paramsErr := s.parseRequestParams(r, schema.ResourceTypeSchema())
if paramsErr != nil {
s.errorHandler(w, paramsErr)
return
}
start, end := clamp(params.StartIndex-1, params.Count, len(s.resourceTypes))
var resources []interface{}
for _, v := range s.resourceTypes[start:end] {
resources = append(resources, v.getRaw())
}
lr := listResponse{
TotalResults: len(s.resourceTypes),
ItemsPerPage: params.Count,
StartIndex: params.StartIndex,
Resources: resources,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// resourcesGetHandler receives an HTTP GET request to the resource endpoint, e.g., "/Users" or "/Groups", to retrieve
// all known resources.
func (s Server) resourcesGetHandler(w http.ResponseWriter, r *http.Request, resourceType ResourceType) {
params, paramsErr := s.parseRequestParams(r, resourceType.Schema, resourceType.getSchemaExtensions()...)
if paramsErr != nil {
s.errorHandler(w, paramsErr)
return
}
page, getError := resourceType.Handler.GetAll(r, params)
if getError != nil {
scimErr := errors.CheckScimError(getError, http.MethodGet)
s.errorHandler(w, &scimErr)
return
}
lr := listResponse{
TotalResults: page.TotalResults,
Resources: page.resources(resourceType, s.baseURL),
StartIndex: params.StartIndex,
ItemsPerPage: params.Count,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// rootResourcesGetHandler receives an HTTP GET request to the server root endpoint to query across all resource types.
func (s Server) rootResourcesGetHandler(w http.ResponseWriter, r *http.Request) {
count, startIndex, scimErr := s.parsePaginationParams(r)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
params := ListRequestParams{
Count: count,
StartIndex: startIndex,
}
page, getError := s.rootQueryHandler.GetAll(r, params)
if getError != nil {
scimErr := errors.CheckScimError(getError, http.MethodGet)
s.errorHandler(w, &scimErr)
return
}
lr := listResponse{
TotalResults: page.TotalResults,
Resources: page.rawResources(),
StartIndex: params.StartIndex,
ItemsPerPage: params.Count,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// rootSearchHandler receives an HTTP POST request to /.search to query across all resource types.
// Per RFC 7644 Section 3.4.3, this is an alternative to GET / with query parameters.
// If the RootQueryHandler also implements ResourceSearcher, the Search method is called
// with full SearchParams. Otherwise, GetAll is called with only Count and StartIndex.
func (s Server) rootSearchHandler(w http.ResponseWriter, r *http.Request) {
_, params, scimErr := s.parseSearchRequest(r)
if scimErr != nil {
s.errorHandler(w, scimErr)
return
}
var (
page Page
getError error
)
if searcher, ok := s.rootQueryHandler.(ResourceSearcher); ok {
page, getError = searcher.Search(r, params)
} else {
page, getError = s.rootQueryHandler.GetAll(r, ListRequestParams{
Count: params.Count,
StartIndex: params.StartIndex,
})
}
if getError != nil {
scimErr := errors.CheckScimError(getError, http.MethodPost)
s.errorHandler(w, &scimErr)
return
}
lr := listResponse{
TotalResults: page.TotalResults,
Resources: page.rawResources(),
StartIndex: params.StartIndex,
ItemsPerPage: params.Count,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// schemaHandler receives an HTTP GET to retrieve individual schema definitions which can be returned by appending the
// schema URI to the /Schemas endpoint. For example: "/Schemas/urn:ietf:params:scim:schemas:core:2.0:User".
func (s Server) schemaHandler(w http.ResponseWriter, r *http.Request, id string) {
getSchema := s.getSchema(id)
if getSchema.ID != id {
scimErr := errors.ScimErrorResourceNotFound(id)
s.errorHandler(w, &scimErr)
return
}
raw, err := json.Marshal(getSchema)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling schema",
"schema", getSchema,
"error", err,
)
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// schemasHandler receives an HTTP GET to retrieve information about resource schemas supported by a SCIM service
// provider. An HTTP GET to the endpoint "/Schemas" returns all supported schemas in ListResponse format.
func (s Server) schemasHandler(w http.ResponseWriter, r *http.Request) {
params, paramsErr := s.parseRequestParams(r, schema.Definition())
if paramsErr != nil {
s.errorHandler(w, paramsErr)
return
}
var (
start, end = clamp(params.StartIndex-1, params.Count, len(s.getSchemas()))
resources []interface{}
)
if validator := params.FilterValidator; validator != nil {
if err := validator.Validate(); err != nil {
s.errorHandler(w, &errors.ScimErrorInvalidFilter)
return
}
}
for _, v := range s.getSchemas()[start:end] {
resource := v.ToMap()
if validator := params.FilterValidator; validator != nil {
if err := validator.PassesFilter(resource); err != nil {
continue
}
}
resources = append(resources, resource)
}
lr := listResponse{
TotalResults: len(s.getSchemas()),
ItemsPerPage: params.Count,
StartIndex: params.StartIndex,
Resources: resources,
}
raw, err := json.Marshal(lr)
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling list response",
"listResponse", lr,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// serviceProviderConfigHandler receives an HTTP GET to this endpoint will return a JSON structure that describes the
// SCIM specification features available on a service provider.
func (s Server) serviceProviderConfigHandler(w http.ResponseWriter, r *http.Request) {
raw, err := json.Marshal(s.config.getRaw())
if err != nil {
s.errorHandler(w, &errors.ScimErrorInternal)
s.log.Error(
"failed marshaling service provider config",
"serviceProviderConfig", s.config,
"error", err,
)
return
}
_, err = w.Write(raw)
if err != nil {
s.log.Error(
"failed writing response",
"error", err,
)
}
}
// searchRequest represents the JSON body of a POST /.search request per RFC 7644 Section 3.4.3.
type searchRequest struct {
Schemas []string `json:"schemas"`
Attributes []string `json:"attributes"`
ExcludedAttributes []string `json:"excludedAttributes"`
Filter string `json:"filter"`
SortBy string `json:"sortBy"`
SortOrder string `json:"sortOrder"`
StartIndex *int `json:"startIndex"`
Count *int `json:"count"`
}