-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
272 lines (245 loc) · 9.5 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
package saviyntapigoclient
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/saviynt/saviynt-api-go-client/connections"
"github.com/saviynt/saviynt-api-go-client/delegatedadministration"
"github.com/saviynt/saviynt-api-go-client/email"
"github.com/saviynt/saviynt-api-go-client/filedirectory"
"github.com/saviynt/saviynt-api-go-client/jobcontrol"
"github.com/saviynt/saviynt-api-go-client/mtlsauthentication"
"github.com/saviynt/saviynt-api-go-client/savroles"
"github.com/saviynt/saviynt-api-go-client/tasks"
"github.com/saviynt/saviynt-api-go-client/transport"
"github.com/saviynt/saviynt-api-go-client/users"
"golang.org/x/oauth2"
)
const (
apiLoginPath = "/ECM/api/login"
headerAuthorization = "Authorization"
tokenTypeBasic = "Basic"
paramOAuth2ExpiresIn = "expires_in"
)
type Client struct {
serverURL string
token *oauth2.Token
httpClient *http.Client
Connections *connections.ConnectionsAPIService
connectionsClient *connections.APIClient
DelegatedAdministration *delegatedadministration.DelegatedAdministrationAPIService
delegatedAdministrationClient *delegatedadministration.APIClient
Email *email.EmailAPIService
emailClient *email.APIClient
FileDirectory *filedirectory.FileDirectoryAPIService
fileDirectoryClient *filedirectory.APIClient
JobControl *jobcontrol.JobControlAPIService
jobControlClient *jobcontrol.APIClient
MTLSAuthentication *mtlsauthentication.MTLSAuthenticationAPIService
mtlsAuthenticationClient *mtlsauthentication.APIClient
SAVRoles *savroles.SAVRolesAPIService
savRolesClient *savroles.APIClient
Tasks *tasks.TasksAPIService
tasksClient *tasks.APIClient
Transport *transport.TransportAPIService
transportClient *transport.APIClient
Users *users.UsersAPIService
usersClient *users.APIClient
}
func NewClient(ctx context.Context, serverURL string, httpClient *http.Client) *Client {
c := &Client{
serverURL: serverURL,
httpClient: httpClient}
c.connectionsClient = newClientConnections(c.APIBaseURL(), c.httpClient)
c.Connections = c.connectionsClient.ConnectionsAPI
c.delegatedAdministrationClient = newClientDelegatedAdministration(c.APIBaseURL(), c.httpClient)
c.DelegatedAdministration = c.delegatedAdministrationClient.DelegatedAdministrationAPI
c.emailClient = newClientEmail(c.APIBaseURL(), c.httpClient)
c.Email = c.emailClient.EmailAPI
c.fileDirectoryClient = newClientFileDirectory(c.APIBaseURL(), c.httpClient)
c.FileDirectory = c.fileDirectoryClient.FileDirectoryAPI
c.jobControlClient = newClientJobControl(c.APIBaseURL(), c.httpClient)
c.JobControl = c.jobControlClient.JobControlAPI
c.mtlsAuthenticationClient = newClientMTLSAuthentication(c.APIBaseURL(), c.httpClient)
c.MTLSAuthentication = c.mtlsAuthenticationClient.MTLSAuthenticationAPI
c.savRolesClient = newClientSAVRoles(c.APIBaseURL(), c.httpClient)
c.SAVRoles = c.savRolesClient.SAVRolesAPI
c.tasksClient = newClientTasks(c.APIBaseURL(), c.httpClient)
c.Tasks = c.tasksClient.TasksAPI
c.transportClient = newClientTransport(c.APIBaseURL(), c.httpClient)
c.Transport = c.transportClient.TransportAPI
c.usersClient = newClientUsers(c.APIBaseURL(), c.httpClient)
c.Users = c.usersClient.UsersAPI
return c
}
type Credentials struct {
ServerURL string `json:"serverURL"`
Username string `json:"username"`
Password string `json:"password"`
}
func NewClientPassword(ctx context.Context, creds Credentials) (*Client, error) {
if tok, err := newOAuth2TokenBasicAuth(loginURL(creds.ServerURL), creds.Username, creds.Password); err != nil {
return nil, err
} else {
c := NewClientToken(ctx, creds.ServerURL, tok)
c.token = tok
return c, nil
}
}
func NewClientPasswordEnv(ctx context.Context, envvar string) (*Client, Credentials, error) {
v := os.Getenv(envvar)
if v == "" {
return nil, Credentials{}, errors.New("env var cannot be empty")
} else if strings.Index(strings.TrimSpace(v), "{") != 0 {
return nil, Credentials{}, errors.New("env var must be a json object")
}
creds := Credentials{}
if err := json.Unmarshal([]byte(v), &creds); err != nil {
return nil, creds, err
}
clt, err := NewClientPassword(ctx, creds)
return clt, creds, err
}
func NewClientToken(ctx context.Context, serverURL string, token *oauth2.Token) *Client {
c := NewClient(ctx, serverURL, newClientToken(ctx, token))
c.token = token
return c
}
func (c *Client) APIBaseURL() string {
return strings.TrimRight(strings.TrimSpace(c.serverURL), "/")
}
func (c *Client) Token() *oauth2.Token {
return c.token
}
func newClientConnections(apiBaseURL string, httpClient *http.Client) *connections.APIClient {
cfg := connections.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = connections.ServerConfigurations{{URL: apiBaseURL}}
return connections.NewAPIClient(cfg)
}
func newClientDelegatedAdministration(apiBaseURL string, httpClient *http.Client) *delegatedadministration.APIClient {
cfg := delegatedadministration.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = delegatedadministration.ServerConfigurations{{URL: apiBaseURL}}
return delegatedadministration.NewAPIClient(cfg)
}
func newClientEmail(apiBaseURL string, httpClient *http.Client) *email.APIClient {
cfg := email.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = email.ServerConfigurations{{URL: apiBaseURL}}
return email.NewAPIClient(cfg)
}
func newClientFileDirectory(apiBaseURL string, httpClient *http.Client) *filedirectory.APIClient {
cfg := filedirectory.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = filedirectory.ServerConfigurations{{URL: apiBaseURL}}
return filedirectory.NewAPIClient(cfg)
}
func newClientJobControl(apiBaseURL string, httpClient *http.Client) *jobcontrol.APIClient {
cfg := jobcontrol.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = jobcontrol.ServerConfigurations{{URL: apiBaseURL}}
return jobcontrol.NewAPIClient(cfg)
}
func newClientMTLSAuthentication(apiBaseURL string, httpClient *http.Client) *mtlsauthentication.APIClient {
cfg := mtlsauthentication.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = mtlsauthentication.ServerConfigurations{{URL: apiBaseURL}}
return mtlsauthentication.NewAPIClient(cfg)
}
func newClientSAVRoles(apiBaseURL string, httpClient *http.Client) *savroles.APIClient {
cfg := savroles.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = savroles.ServerConfigurations{{URL: apiBaseURL}}
return savroles.NewAPIClient(cfg)
}
func newClientTasks(apiBaseURL string, httpClient *http.Client) *tasks.APIClient {
cfg := tasks.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = tasks.ServerConfigurations{{URL: apiBaseURL}}
return tasks.NewAPIClient(cfg)
}
func newClientTransport(apiBaseURL string, httpClient *http.Client) *transport.APIClient {
cfg := transport.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = transport.ServerConfigurations{{URL: apiBaseURL}}
return transport.NewAPIClient(cfg)
}
func newClientUsers(apiBaseURL string, httpClient *http.Client) *users.APIClient {
cfg := users.NewConfiguration()
cfg.HTTPClient = httpClient
cfg.Servers = users.ServerConfigurations{{URL: apiBaseURL}}
return users.NewAPIClient(cfg)
}
func newOAuth2TokenBasicAuth(tokenURL, username, password string) (*oauth2.Token, error) {
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, tokenURL, nil)
if err != nil {
return nil, err
}
header := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
req.Header.Add(headerAuthorization, tokenTypeBasic+" "+header)
resp, err := client.Do(req)
if err != nil {
return nil, err
} else if resp.StatusCode >= 300 {
return nil, fmt.Errorf("saviynt token response status (%s)", strconv.Itoa(resp.StatusCode))
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
} else if len(b) == 0 {
return nil, errors.New("saviynt token body is empty")
}
return parseToken(b)
}
func loginURL(serverURL string) string {
return strings.TrimSuffix(strings.TrimSpace(serverURL), "/") + apiLoginPath
}
func parseToken(rawToken []byte) (*oauth2.Token, error) {
tok := &oauth2.Token{}
err := json.Unmarshal(rawToken, tok)
if err != nil {
return tok, wrapError(err, fmt.Sprintf("parse OAuth 2.0 token: (%s)", string(rawToken)))
}
msi := map[string]any{}
err = json.Unmarshal(rawToken, &msi)
if err != nil {
return tok, wrapError(err, "parse OAuth 2.0 token as msi")
}
tok = tok.WithExtra(msi)
// convert `expires_in` to `Expiry` with 1 minute leeway.
if tok.Expiry.IsZero() {
expiresIn := tok.Extra(paramOAuth2ExpiresIn)
if expiresIn != nil {
if expiresInFloat, ok := expiresIn.(float64); ok {
if expiresInFloat > 60 { // subtract 1 minute for defensive handling
expiresInFloat -= 60
}
if expiresInFloat > 0 {
tok.Expiry = time.Now().UTC().Add(time.Duration(expiresInFloat) * time.Second)
}
}
}
}
return tok, nil
}
func newClientToken(ctx context.Context, tok *oauth2.Token) *http.Client {
oAuthConfig := &oauth2.Config{}
return oAuthConfig.Client(ctx, tok)
}
func Pointer[E any](e E) *E { return &e }
func wrapError(err error, wrapPrefix string) error {
if err == nil || wrapPrefix == "" {
return err
}
return fmt.Errorf("%s: [%w]", wrapPrefix, err)
}