-
Notifications
You must be signed in to change notification settings - Fork 52
/
iam.go
376 lines (323 loc) · 12 KB
/
iam.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
package iam
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strconv"
"time"
"github.com/IBM-Cloud/ibm-cloud-cli-sdk/bluemix/authentication"
"github.com/IBM-Cloud/ibm-cloud-cli-sdk/common/rest"
"github.com/IBM-Cloud/ibm-cloud-cli-sdk/common/types"
)
const (
defaultClientID = "bx"
defaultClientSecret = "bx"
crTokenParam = "cr_token"
profileIDParam = "profile_id"
profileNameParam = "profile_name"
profileCRNParam = "profile_crn"
)
// Grant types
const (
GrantTypePassword authentication.GrantType = "password" // #nosec G101 - this the API request grant type. Not a credential
GrantTypeAPIKey authentication.GrantType = "urn:ibm:params:oauth:grant-type:apikey" // #nosec G101 - this the API request grant type. Not a credential
GrantTypeOnetimePasscode authentication.GrantType = "urn:ibm:params:oauth:grant-type:passcode" // #nosec G101 - this the API request grant type. Not a credential
GrantTypeAuthorizationCode authentication.GrantType = "authorization_code"
GrantTypeRefreshToken authentication.GrantType = "refresh_token"
GrantTypeDelegatedRefreshToken authentication.GrantType = "urn:ibm:params:oauth:grant-type:delegated-refresh-token" // #nosec G101 - this the API request grant type. Not a credential
GrantTypeIdentityCookie authentication.GrantType = "urn:ibm:params:oauth:grant-type:identity-cookie"
GrantTypeDerive authentication.GrantType = "urn:ibm:params:oauth:grant-type:derive"
GrantTypeCRToken authentication.GrantType = "urn:ibm:params:oauth:grant-type:cr-token" // #nosec G101 - this the API request grant type. Not a credential
)
// Response types
const (
ResponseTypeIAM authentication.ResponseType = "cloud_iam"
ResponseTypeIMS authentication.ResponseType = "ims_portal"
ResponseTypeDelegatedRefreshToken authentication.ResponseType = "delegated_refresh_token" // #nosec G101 - this the API response grant type. Not a credential
)
const (
InvalidTokenErrorCode = "BXNIM0407E" // #nosec G101 - this an API error response code. Not a credential
RefreshTokenExpiryErrorCode = "BXNIM0408E" // #nosec G101 - this an API error response code. Not a credential
ExternalAuthenticationErrorCode = "BXNIM0400E"
SessionInactiveErrorCode = "BXNIM0439E"
)
type MFAVendor string
func (m MFAVendor) String() string {
return string(m)
}
// MFA vendors
const (
MFAVendorVerisign MFAVendor = "VERISIGN"
MFAVendorTOTP MFAVendor = "TOTP"
MFAVendorPhoneFactor MFAVendor = "PHONE_FACTOR"
)
func PasswordTokenRequest(username, password string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypePassword)
r.SetTokenParam("username", username)
r.SetTokenParam("password", password)
for _, o := range opts {
r.WithOption(o)
}
return r
}
func OnetimePasscodeTokenRequest(passcode string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypeOnetimePasscode)
r.SetTokenParam("passcode", passcode)
for _, o := range opts {
r.WithOption(o)
}
return r
}
func APIKeyTokenRequest(apikey string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypeAPIKey)
r.SetTokenParam("apikey", apikey)
for _, o := range opts {
r.WithOption(o)
}
return r
}
// CRTokenRequest builds a 'TokenRequest' struct from the user input. The value of 'crToken' is set as the value of the 'cr_token' form
// parameter of the request. 'profileID' and 'profileName' are optional parameters used to set the 'profile_id' and 'profile_name' form parameters
// in the request, respectively.
func CRTokenRequest(crToken string, profileID string, profileName string, opts ...authentication.TokenOption) *authentication.TokenRequest {
return CRTokenRequestWithCRN(crToken, profileID, profileName, "", opts...)
}
// CRTokenRequestWithCRN builds a 'TokenRequest' struct from the user input. The value of 'crToken' is set as the value of the 'cr_token' form
// parameter of the request. 'profileID', 'profileName', and 'profileCRN' are optional parameters used to set the 'profile_id', 'profile_name',
// and 'profile_crn' form parameters in the request, respectively.
func CRTokenRequestWithCRN(crToken string, profileID string, profileName string, profileCRN string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypeCRToken)
r.SetTokenParam(crTokenParam, crToken)
if profileID != "" {
r.SetTokenParam(profileIDParam, profileID)
}
if profileName != "" {
r.SetTokenParam(profileNameParam, profileName)
}
if profileCRN != "" {
r.SetTokenParam(profileCRNParam, profileCRN)
}
for _, o := range opts {
r.WithOption(o)
}
return r
}
func RefreshTokenRequest(refreshToken string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypeRefreshToken)
r.SetTokenParam("refresh_token", refreshToken)
for _, o := range opts {
r.WithOption(o)
}
return r
}
func AuthorizationTokenRequest(code string, redirectURI string, opts ...authentication.TokenOption) *authentication.TokenRequest {
r := authentication.NewTokenRequest(GrantTypeAuthorizationCode)
r.SetTokenParam("code", code)
r.SetTokenParam("redirect_uri", redirectURI)
for _, o := range opts {
r.WithOption(o)
}
return r
}
func SetAccount(accountID string) authentication.TokenOption {
return func(r *authentication.TokenRequest) {
r.SetTokenParam("account", accountID)
}
}
func SetIMSAccount(imsAccountID string) authentication.TokenOption {
return func(r *authentication.TokenRequest) {
r.SetTokenParam("ims_account", imsAccountID)
}
}
func SetSecurityQuestion(questionID int, answer string) authentication.TokenOption {
return func(r *authentication.TokenRequest) {
r.SetTokenParam("security_question_id", strconv.Itoa(questionID))
r.SetTokenParam("security_question_answer", answer)
}
}
func SetVeriSignCode(code string) authentication.TokenOption {
return SetSecurityCode(code, MFAVendorVerisign)
}
func SetTOTPCode(code string) authentication.TokenOption {
return SetSecurityCode(code, MFAVendorTOTP)
}
func SetSecurityCode(code string, vendor MFAVendor) authentication.TokenOption {
return func(r *authentication.TokenRequest) {
r.SetTokenParam("security_code", code)
r.SetTokenParam("vendor", vendor.String())
}
}
func SetPhoneAuthToken(token string) authentication.TokenOption {
return func(r *authentication.TokenRequest) {
r.SetTokenParam("authentication_token", token)
r.SetTokenParam("vendor", MFAVendorPhoneFactor.String())
}
}
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
SessionID string `json:"session_id"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Expiry time.Time `json:"expiration"`
// Fields present when ResponseTypeIMS is set
IMSUserID int64 `json:"ims_user_id"`
IMSToken string `json:"ims_token"`
}
type APIError struct {
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
ErrorDetails string `json:"errorDetails"`
Requirements Requirement `json:"requirements"`
}
type Requirement struct {
ErrorCode string `json:"code"`
ErrorMessage string `json:"error"`
}
func (e APIError) errorMessage() string {
if e.ErrorDetails != "" {
return e.ErrorDetails
}
return e.ErrorMessage
}
type Endpoint struct {
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
PasscodeURL string `json:"passcode_endpoint"`
}
type Interface interface {
GetEndpoint() (*Endpoint, error)
RefreshSession(sessionId string) error
GetToken(req *authentication.TokenRequest) (*Token, error)
InitiateIMSPhoneFactor(req *authentication.TokenRequest) (authToken string, err error)
}
type Config struct {
IAMEndpoint string
TokenEndpoint string // Optional. Default value is <IAMEndpoint>/identity/token
SessionEndpoint string // Optional. Default value is <IAMEndpoint>/v1/sessions
ClientID string
ClientSecret string
UAAClientID string
UAAClientSecret string
}
func (c Config) tokenEndpoint() string {
if c.TokenEndpoint != "" {
return c.TokenEndpoint
}
return c.IAMEndpoint + "/identity/token"
}
func (c Config) sessionEndpoint() string {
if c.SessionEndpoint != "" {
return c.SessionEndpoint
}
return c.IAMEndpoint + "/v1/sessions"
}
func DefaultConfig(iamEndpoint string) Config {
return Config{
IAMEndpoint: iamEndpoint,
TokenEndpoint: iamEndpoint + "/identity/token",
SessionEndpoint: iamEndpoint + "/v1/sessions",
ClientID: defaultClientID,
ClientSecret: defaultClientSecret,
}
}
type client struct {
config Config
client *rest.Client
}
func NewClient(config Config, restClient *rest.Client) Interface {
return &client{
config: config,
client: restClient,
}
}
func (c *client) GetToken(tokenReq *authentication.TokenRequest) (*Token, error) {
v := make(url.Values)
tokenReq.SetValue(v)
responseTypes := tokenReq.ResponseTypes()
if len(responseTypes) == 0 {
v.Set("response_type", ResponseTypeIAM.String())
}
r := rest.PostRequest(c.config.tokenEndpoint()).
Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.config.ClientID, c.config.ClientSecret))))
for k, ss := range v {
for _, s := range ss {
r.Field(k, s)
}
}
var tokenResponse struct {
Token
Expiry types.UnixTime `json:"expiration"`
}
if err := c.doRequest(r, &tokenResponse); err != nil {
return nil, err
}
ret := tokenResponse.Token
ret.Expiry = time.Time(tokenResponse.Expiry)
return &ret, nil
}
// RefreshSession maintains the session state. Useful for async workloads
// @param sessionID string - the session ID
func (c *client) RefreshSession(sessionID string) error {
// If no session ID is provided there is no need to refresh
if sessionID == "" {
return nil
}
url := fmt.Sprintf("%s/%s/state", c.config.sessionEndpoint(), sessionID)
r := rest.PatchRequest(url).
Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.config.ClientID, c.config.ClientSecret))))
if err := c.doRequest(r, nil); err != nil {
return err
}
return nil
}
func (c *client) InitiateIMSPhoneFactor(tokenReq *authentication.TokenRequest) (authToken string, err error) {
v := make(url.Values)
tokenReq.SetValue(v)
r := rest.PostRequest(c.config.IAMEndpoint+"/identity/initiate_ims_2fa").
Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.config.ClientID, c.config.ClientSecret))))
for k, ss := range v {
for _, s := range ss {
r.Field(k, s)
}
}
var resp struct {
AuthenticationToken string `json:"authenticationToken"`
}
if err := c.doRequest(r, &resp); err != nil {
return "", err
}
return resp.AuthenticationToken, nil
}
func (c *client) GetEndpoint() (*Endpoint, error) {
var e Endpoint
err := c.doRequest(rest.GetRequest(c.config.IAMEndpoint+"/identity/.well-known/openid-configuration"), &e)
if err != nil {
return nil, err
}
return &e, nil
}
func (c *client) doRequest(r *rest.Request, respV interface{}) error {
_, err := c.client.Do(r, respV, nil)
switch err := err.(type) {
case *rest.ErrorResponse:
var apiErr APIError
if jsonErr := json.Unmarshal([]byte(err.Message), &apiErr); jsonErr == nil {
switch apiErr.ErrorCode {
case "":
case InvalidTokenErrorCode:
return authentication.NewInvalidTokenError(apiErr.errorMessage())
case RefreshTokenExpiryErrorCode:
return authentication.NewRefreshTokenExpiryError(apiErr.errorMessage())
case ExternalAuthenticationErrorCode:
return &authentication.ExternalAuthenticationError{ErrorCode: apiErr.Requirements.ErrorCode, ErrorMessage: apiErr.Requirements.ErrorMessage}
case SessionInactiveErrorCode:
return authentication.NewSessionInactiveError(apiErr.errorMessage())
default:
return authentication.NewServerError(err.StatusCode, apiErr.ErrorCode, apiErr.errorMessage())
}
}
}
return err
}