-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
607 lines (490 loc) · 13.7 KB
/
client.go
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
// Copyright (c) 2020, Amazon.com, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scim
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
log "github.com/sirupsen/logrus"
)
var (
ErrUserNotFound = errors.New("user not found")
ErrGroupNotFound = errors.New("group not found")
ErrNoGroupsFound = errors.New("no groups found")
ErrUserNotSpecified = errors.New("user not specified")
ErrGroupNotSpecified = errors.New("group not specified")
)
// OperationType handle patch operations for add/remove groupe members
type OperationType string
const (
// OperationAdd is the add operation for a patch
OperationAdd OperationType = "add"
// OperationRemove is the remove operation for a patch
OperationRemove OperationType = "remove"
// OperationRemove is the replace operation for a patch
OperationReplace OperationType = "replace"
)
// Client represents an interface of methods used
// to communicate with AWS SSO
type Client interface {
AddUserToGroup(*User, *Group) error
CreateGroup(*Group) (*Group, error)
UpdateGroup(*Group) error
CreateUser(*User) (*User, error)
DeleteGroup(*Group) error
DeleteUser(*User) error
FindGroupByDisplayName(string) (*Group, error)
FindUserByEmail(string) (*User, error)
FindUserByID(string) (*User, error)
GetUsers() ([]*User, error)
GetGroupMembers(*Group) ([]*User, error)
IsUserInGroup(*User, *Group) (bool, error)
GetGroups() ([]*Group, error)
UpdateUser(*User) (*User, error)
RemoveUserFromGroup(*User, *Group) error
}
type client struct {
httpClient HttpClient
endpointURL *url.URL
bearerToken string
}
// NewClient creates a new client to talk with AWS SSO's SCIM endpoint. It
// requires a http.Client{} as well as the URL and bearer token from the
// console. If the URL is not parsable, an error will be thrown.
func NewClient(c HttpClient, config *Config) (Client, error) {
u, err := url.Parse(config.Endpoint)
if err != nil {
return nil, err
}
return &client{
httpClient: c,
endpointURL: u,
bearerToken: config.Token,
}, nil
}
// sendRequestWithBody will send the body given to the url/method combination
// with the right Bearer token as well as the correct content type for SCIM.
func (c *client) sendRequestWithBody(method string, url string, body interface{}) (response []byte, err error) {
// Convert the body to JSON
d, err := json.Marshal(body)
if err != nil {
return
}
// Create a request with our body of JSON
r, err := http.NewRequest(method, url, bytes.NewBuffer(d))
if err != nil {
return
}
log.WithFields(log.Fields{"url": url, "method": method})
// Set the content-type and authorization headers
r.Header.Set("Content-Type", "application/scim+json")
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
// Call the URL
resp, err := c.httpClient.Do(r)
if err != nil {
return
}
defer resp.Body.Close()
// Read the body back from the response
response, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// If we get a non-2xx status code, raise that via an error
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent {
err = fmt.Errorf("status of http response was %d", resp.StatusCode)
}
return
}
func (c *client) sendRequest(method string, url string) (response []byte, err error) {
r, err := http.NewRequest(method, url, nil)
if err != nil {
return
}
log.WithFields(log.Fields{"url": url, "method": method})
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
resp, err := c.httpClient.Do(r)
if err != nil {
return
}
defer resp.Body.Close()
response, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent {
err = fmt.Errorf("status of http response was %d", resp.StatusCode)
}
return
}
// IsUserInGroup will determine if user (u) is in group (g)
func (c *client) IsUserInGroup(u *User, g *Group) (bool, error) {
if g == nil {
return false, ErrGroupNotSpecified
}
if u == nil {
return false, ErrUserNotSpecified
}
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return false, err
}
filter := fmt.Sprintf("id eq \"%s\" and members eq \"%s\"", g.ID, u.ID)
startURL.Path = path.Join(startURL.Path, "/Groups")
q := startURL.Query()
q.Add("filter", filter)
startURL.RawQuery = q.Encode()
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return false, err
}
var r GroupFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return false, err
}
return r.TotalResults > 0, nil
}
func (c *client) groupChangeOperation(op OperationType, u *User, g *Group) error {
if g == nil {
return ErrGroupNotSpecified
}
if u == nil {
return ErrUserNotSpecified
}
log.WithFields(log.Fields{"operations": op, "user": u.Username, "group": g.DisplayName}).Debug("Group Change")
gc := &GroupMemberChange{
Schemas: []string{"urn:ietf:params:scim:api:messages:2.0:PatchOp"},
Operations: []GroupMemberChangeOperation{
{
Operation: string(op),
Path: "members",
Members: []GroupMemberChangeMember{
{Value: u.ID},
},
},
},
}
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return err
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Groups/%s", g.ID))
_, err = c.sendRequestWithBody(http.MethodPatch, startURL.String(), *gc)
if err != nil {
return err
}
return nil
}
// AddUserToGroup will add the user specified to the group specified
func (c *client) AddUserToGroup(u *User, g *Group) error {
return c.groupChangeOperation(OperationAdd, u, g)
}
// RemoveUserFromGroup will remove the user specified from the group specified
func (c *client) RemoveUserFromGroup(u *User, g *Group) error {
return c.groupChangeOperation(OperationRemove, u, g)
}
// FindUserByEmail will find the user by the email address specified
func (c *client) FindUserByEmail(email string) (*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
filter := fmt.Sprintf("userName eq \"%s\"", email)
startURL.Path = path.Join(startURL.Path, "/Users")
q := startURL.Query()
q.Add("filter", filter)
startURL.RawQuery = q.Encode()
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r UserFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
if r.TotalResults != 1 {
return nil, ErrUserNotFound
}
return &r.Resources[0], nil
}
// FindUserByID will find the user by the email address specified
func (c *client) FindUserByID(id string) (*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Users/%s", id))
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r UserFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
if r.TotalResults != 1 {
return nil, ErrUserNotFound
}
return &r.Resources[0], nil
}
// FindGroupByDisplayName will find the group by its displayname.
func (c *client) FindGroupByDisplayName(name string) (*Group, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
filter := fmt.Sprintf("displayName eq \"%s\"", name)
startURL.Path = path.Join(startURL.Path, "/Groups")
q := startURL.Query()
q.Add("filter", filter)
startURL.RawQuery = q.Encode()
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r GroupFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
if r.TotalResults != 1 {
return nil, ErrGroupNotFound
}
return &r.Resources[0], nil
}
// CreateUser will create the user specified
func (c *client) CreateUser(u *User) (*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
if u == nil {
err = ErrUserNotSpecified
return nil, err
}
startURL.Path = path.Join(startURL.Path, "/Users")
resp, err := c.sendRequestWithBody(http.MethodPost, startURL.String(), *u)
if err != nil {
return nil, err
}
var newUser User
err = json.Unmarshal(resp, &newUser)
if err != nil {
return nil, err
}
if newUser.ID == "" {
return c.FindUserByEmail(u.Username)
}
return &newUser, nil
}
// UpdateUser will update/replace the user specified
func (c *client) UpdateUser(u *User) (*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
if u == nil {
err = ErrUserNotFound
return nil, err
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Users/%s", u.ID))
resp, err := c.sendRequestWithBody(http.MethodPut, startURL.String(), *u)
if err != nil {
return nil, err
}
var newUser User
err = json.Unmarshal(resp, &newUser)
if err != nil {
return nil, err
}
if newUser.ID == "" {
return c.FindUserByEmail(u.Username)
}
return &newUser, nil
}
// DeleteUser will remove the current user from the directory
func (c *client) DeleteUser(u *User) error {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return err
}
if u == nil {
return ErrUserNotSpecified
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Users/%s", u.ID))
_, err = c.sendRequest(http.MethodDelete, startURL.String())
if err != nil {
return err
}
return nil
}
// CreateGroup will create a group given
func (c *client) CreateGroup(g *Group) (*Group, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
if g == nil {
err = ErrGroupNotSpecified
return nil, err
}
startURL.Path = path.Join(startURL.Path, "/Groups")
resp, err := c.sendRequestWithBody(http.MethodPost, startURL.String(), *g)
if err != nil {
return nil, err
}
var newGroup Group
err = json.Unmarshal(resp, &newGroup)
if err != nil {
return nil, err
}
return &newGroup, nil
}
// UpdateGroup update the displayName property of a group
func (c *client) UpdateGroup(g *Group) error {
if g == nil {
return ErrGroupNotSpecified
}
gc := &GroupReplace{
Schemas: []string{"urn:ietf:params:scim:api:messages:2.0:PatchOp"},
Operations: []GroupReplaceOperation{
{
Operation: string(OperationReplace),
Group: GroupReplaceValue{
GroupId: g.ID,
DisplayName: g.DisplayName,
},
},
},
}
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return err
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Groups/%s", g.ID))
_, err = c.sendRequestWithBody(http.MethodPatch, startURL.String(), *gc)
if err != nil {
return err
}
return nil
}
// DeleteGroup will delete the group specified
func (c *client) DeleteGroup(g *Group) error {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return err
}
if g == nil {
return ErrGroupNotSpecified
}
startURL.Path = path.Join(startURL.Path, fmt.Sprintf("/Groups/%s", g.ID))
_, err = c.sendRequest(http.MethodDelete, startURL.String())
if err != nil {
return err
}
return nil
}
// GetGroups will return existing groups
func (c *client) GetGroups() ([]*Group, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
startURL.Path = path.Join(startURL.Path, "/Groups")
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r GroupFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
// if r.TotalResults != 1 {
// return nil, ErrNoGroupsFound
// }
gps := make([]*Group, len(r.Resources))
for i := range r.Resources {
gps[i] = &r.Resources[i]
}
return gps, nil
}
// GetGroupMembers will return existing groups
func (c *client) GetGroupMembers(g *Group) ([]*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
if g == nil {
return nil, ErrGroupNotSpecified
}
filter := fmt.Sprintf("displayName eq \"%s\"", g.DisplayName)
startURL.Path = path.Join(startURL.Path, "/Groups")
q := startURL.Query()
q.Add("filter", filter)
startURL.RawQuery = q.Encode()
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r GroupFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
var users = make([]*User, 0)
for _, res := range r.Resources {
for _, uID := range res.Members { // NOTE: Not Implemented Yet https://docs.aws.amazon.com/singlesignon/latest/developerguide/listgroups.html
user, err := c.FindUserByID(uID)
if err != nil {
return nil, err
}
users = append(users, user)
}
}
return users, nil
}
// GetUsers will return existing users
func (c *client) GetUsers() ([]*User, error) {
startURL, err := url.Parse(c.endpointURL.String())
if err != nil {
return nil, err
}
startURL.Path = path.Join(startURL.Path, "/Users")
resp, err := c.sendRequest(http.MethodGet, startURL.String())
if err != nil {
return nil, err
}
var r UserFilterResults
err = json.Unmarshal(resp, &r)
if err != nil {
return nil, err
}
// if r.TotalResults != 1 {
// return nil, ErrUserNotFound
// }
usrs := make([]*User, len(r.Resources))
for i := range r.Resources {
usrs[i] = &r.Resources[i]
}
return usrs, nil
}