forked from cxpsemea/Cx1ClientGo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
clients.go
332 lines (269 loc) · 9.13 KB
/
clients.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
package Cx1ClientGo
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// Clients
func (c Cx1Client) GetClients() ([]OIDCClient, error) {
c.logger.Debug("Getting OIDC Clients")
var json_clients []map[string]interface{}
var clients []OIDCClient
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", "/clients?briefRepresentation=true", nil, nil)
if err != nil {
return clients, err
}
err = json.Unmarshal(response, &json_clients)
if err != nil {
return clients, err
}
clients = make([]OIDCClient, len(json_clients))
for id, client := range json_clients {
clients[id], err = clientFromMap(client)
if err != nil {
return clients, err
}
}
c.logger.Tracef("Got %d clients", len(clients))
return clients, err
}
func (c Cx1Client) GetClientByID(id string) (OIDCClient, error) {
c.logger.Debugf("Getting OIDC client with ID %v", id)
var client OIDCClient
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", fmt.Sprintf("/clients/%v", id), nil, nil)
if err != nil {
return client, err
}
var json_client map[string]interface{}
err = json.Unmarshal(response, &json_client)
if err != nil {
return client, err
}
return clientFromMap(json_client)
}
func (c Cx1Client) GetClientByName(clientName string) (OIDCClient, error) {
c.logger.Debugf("Getting OIDC client with name %v", clientName)
var client OIDCClient
clients, err := c.GetClients()
if err != nil {
return client, err
}
for _, c := range clients {
if c.ClientID == clientName {
client = c
return client, nil
}
}
return client, fmt.Errorf("no such client %v found", clientName)
}
func (c Cx1Client) GetClientSecret(client *OIDCClient) (string, error) {
c.logger.Debugf("Getting OIDC client secret for %v", client.String())
var responseBody struct {
Type string
Value string
}
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", fmt.Sprintf("/clients/%v/client-secret", client.ID), nil, nil)
if err != nil {
return "", err
}
err = json.Unmarshal(response, &responseBody)
if err == nil {
client.ClientSecret = responseBody.Value
}
return responseBody.Value, err
}
func (c Cx1Client) CreateClient(name string, notificationEmails []string, secretExpiration int) (OIDCClient, error) {
c.logger.Debugf("Creating OIDC client with name %v", name)
notificationEmailsStr := "[\"" + strings.Join(notificationEmails, "\",\"") + "\"]"
c.logger.Infof("Setting emails: %v", notificationEmailsStr)
body := map[string]interface{}{
"enabled": true,
"attributes": map[string]interface{}{
"lastUpdate": time.Now().UnixMilli(),
"client.secret.creation.time": time.Now().Unix(),
"client.secret.expiration.time": time.Now().AddDate(0, 0, secretExpiration).Unix(),
"notificationEmail": notificationEmailsStr,
"secretExpiration": fmt.Sprintf("%d", secretExpiration),
},
"redirectUris": []string{},
"clientId": name,
"protocol": "openid-connect",
"frontchannelLogout": true,
"publicClient": false,
"serviceAccountsEnabled": true,
"standardFlowEnabled": false,
}
jsonBody, _ := json.Marshal(body)
_, err := c.sendRequestIAM(http.MethodPost, "/auth/admin", "/clients", bytes.NewReader(jsonBody), nil)
if err != nil {
return OIDCClient{}, err
}
newClient, err := c.GetClientByName(name)
if err != nil {
return newClient, err
}
groupScope, err := c.GetClientScopeByName("groups")
if err != nil {
return newClient, fmt.Errorf("failed to get 'groups' client scope to add to new client: %s", err)
}
err = c.AddClientScopeByID(newClient.ID, groupScope.ID)
if err != nil {
return newClient, fmt.Errorf("failed to add 'groups' client scope to new client: %s", err)
}
err = c.SaveClient(newClient)
return newClient, err
}
func clientFromMap(data map[string]interface{}) (OIDCClient, error) {
var client OIDCClient
jsonData, err := json.Marshal(data)
if err != nil {
return client, fmt.Errorf("failed to marshal unmarshaled json: %s", err)
}
err = json.Unmarshal(jsonData, &client)
if err != nil {
return client, fmt.Errorf("failed to re-unmarshal json: %s", err)
}
client.OIDCClientRaw = data
if client.OIDCClientRaw["attributes"] != nil {
if client.OIDCClientRaw["attributes"].(map[string]interface{})["client.secret.expiration.time"] != nil {
timestamp := client.OIDCClientRaw["attributes"].(map[string]interface{})["client.secret.expiration.time"].(string)
client.ClientSecretExpiry, _ = strconv.ParseUint(timestamp, 10, 64)
}
if client.OIDCClientRaw["attributes"].(map[string]interface{})["creator"] != nil {
client.Creator = client.OIDCClientRaw["attributes"].(map[string]interface{})["creator"].(string)
}
}
return client, nil
}
/*
The SaveClient function should be used sparingly - it will use the contents of the OIDCClient.OIDCClientRaw variable of type map[string]interface{} in the PUT request.
As a result, changes to the member variables in the OIDCClient object itself (creator & clientsecretexpiry) will not be saved using this method unless they are also updated in OIDCClientRaw.
*/
func (c Cx1Client) SaveClient(client OIDCClient) error {
c.logger.Debugf("Updating OIDC client with name %v", client.ClientID)
jsonBody, _ := json.Marshal(client.OIDCClientRaw)
_, err := c.sendRequestIAM(http.MethodPut, "/auth/admin", fmt.Sprintf("/clients/%v", client.ID), bytes.NewReader(jsonBody), nil)
if err != nil {
return err
}
return nil
}
func (c Cx1Client) AddClientScopeByID(oidcId, clientScopeId string) error {
c.logger.Debugf("Adding client scope %v to OIDC Client %v", clientScopeId, oidcId)
_, err := c.sendRequestIAM(http.MethodPut, "/auth/admin", fmt.Sprintf("/clients/%v/default-client-scopes/%v", oidcId, clientScopeId), nil, nil)
return err
}
func (c Cx1Client) DeleteClientByID(id string) error {
c.logger.Debugf("Deleting OIDC client with ID %v", id)
if strings.EqualFold(id, c.GetASTAppID()) {
return fmt.Errorf("attempt to delete the ast-app client (ID: %v) prevented - this will break your tenant", id)
}
_, err := c.sendRequestIAM(http.MethodDelete, "/auth/admin", fmt.Sprintf("/clients/%v", id), nil, nil)
return err
}
func (c Cx1Client) GetServiceAccountByID(oidcId string) (User, error) {
c.logger.Debugf("Getting service account user behind OIDC client with ID %v", oidcId)
var user User
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", fmt.Sprintf("/clients/%v/service-account-user", oidcId), nil, nil)
if err != nil {
return user, err
}
err = json.Unmarshal(response, &user)
return user, err
}
func (c Cx1Client) GetTenantID() string {
if tenantID != "" {
return tenantID
}
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", "", nil, nil)
if err != nil {
c.logger.Warnf("Failed to retrieve tenant ID: %s", err)
return tenantID
}
var realms struct {
ID string `json:"id"`
Realm string `json:"realm"`
} // Sometimes this returns an array of one element? Is it possible to return multiple?
err = json.Unmarshal(response, &realms)
if err != nil {
c.logger.Warnf("Failed to parse tenant ID: %s", err)
c.logger.Tracef("Response was: %v", string(response))
return tenantID
}
//for _, r := range realms {
if realms.Realm == c.tenant {
tenantID = realms.ID
}
//}
if tenantID == "" {
c.logger.Warnf("Failed to retrieve tenant ID: no tenant found matching %v", c.tenant)
}
return tenantID
}
func (c Cx1Client) GetTenantName() string {
return c.tenant
}
func (c Cx1Client) GetClientScopes() ([]OIDCClientScope, error) {
c.logger.Debug("Getting OIDC Client Scopes")
var clientscopes []OIDCClientScope
response, err := c.sendRequestIAM(http.MethodGet, "/auth/admin", "/client-scopes", nil, nil)
if err != nil {
return clientscopes, err
}
err = json.Unmarshal(response, &clientscopes)
c.logger.Tracef("Got %d client scopes", len(clientscopes))
return clientscopes, err
}
func (c Cx1Client) GetClientScopeByName(name string) (OIDCClientScope, error) {
clientScopes, err := c.GetClientScopes()
if err != nil {
return OIDCClientScope{}, err
}
for _, cs := range clientScopes {
if cs.Name == name {
return cs, nil
}
}
return OIDCClientScope{}, fmt.Errorf("client-scope %v not found", name)
}
// convenience function
func (c Cx1Client) GetASTAppID() string {
if astAppID == "" {
client, err := c.GetClientByName("ast-app")
if err != nil {
c.logger.Warnf("Error finding AST App ID: %s", err)
return ""
}
astAppID = client.ID
}
return astAppID
}
func (c Cx1Client) RegenerateClientSecret(client OIDCClient) (string, error) {
clientId := client.ID
body := map[string]interface{}{
"realm": c.tenant,
"client": clientId,
}
type RespBody struct {
Type string
Value string
}
var secretResponse RespBody
jsonBody, _ := json.Marshal(body)
response, err := c.sendRequestIAM(http.MethodPost, "/auth/admin", fmt.Sprintf("/clients/%s/client-secret", clientId), bytes.NewReader(jsonBody), nil)
if err != nil {
return "", err
}
err = json.Unmarshal(response, &secretResponse)
if err != nil {
return "", err
}
return secretResponse.Value, nil
}
func (client OIDCClient) String() string {
return fmt.Sprintf("[%v] %v", ShortenGUID(client.ID), client.ClientID)
}