generated from SAP/repository-template
/
client.go
348 lines (272 loc) · 10.8 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
package btpcli
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"strconv"
uuid "github.com/hashicorp/go-uuid"
)
const DefaultServerURL string = "https://cli.btp.cloud.sap"
func NewV2Client(serverURL *url.URL) *v2Client {
return NewV2ClientWithHttpClient(http.DefaultClient, serverURL)
}
func NewV2ClientWithHttpClient(client *http.Client, serverURL *url.URL) *v2Client {
return &v2Client{
httpClient: injectBTPCLITransport(client),
serverURL: serverURL,
newCorrelationID: func() string {
val, err := uuid.GenerateUUID()
if err != nil {
panic(fmt.Sprintf("crypto/rand returned fatal error: %s", err.Error()))
}
return val
},
}
}
const (
HeaderCorrelationID string = "X-Correlationid"
HeaderIDToken string = "X-Id-Token"
HeaderCLIFormat string = "X-Cpcli-Format"
HeaderCLISessionId string = "X-Cpcli-Sessionid"
HeaderCLISubdomain string = "X-Cpcli-Subdomain"
HeaderCLICustomIDP string = "X-Cpcli-Customidp"
HeaderCLIBackendStatus string = "X-Cpcli-Backend-Status"
HeaderCLIBackendMessage string = "X-Cpcli-Backend-Message"
HeaderCLIBackendMediaType string = "X-Cpcli-Backend-Mediatype"
HeaderCLIClientUpdate string = "X-Cpcli-Client-Update"
HeaderCLIServerMessage string = "X-Cpcli-Server-Message"
)
const cliTargetProtocolVersion string = "v2.49.0"
type v2ContextKey string
type v2Client struct {
httpClient *http.Client
serverURL *url.URL
newCorrelationID func() string
session *Session
UserAgent string
}
func (v2 *v2Client) initTrace(ctx context.Context) context.Context {
return context.WithValue(ctx, v2ContextKey(HeaderCorrelationID), v2.newCorrelationID())
}
func (v2 *v2Client) doRequest(ctx context.Context, method string, endpoint string, body any) (*http.Response, error) {
endpointURL, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
var bodyContent bytes.Buffer
if body != nil {
encoder := json.NewEncoder(&bodyContent)
encoder.SetEscapeHTML(false) // no need for HTML safe json encoding
if err = encoder.Encode(body); err != nil {
return nil, err
}
}
fullQualifiedEndpointURL := v2.serverURL.ResolveReference(endpointURL)
req, err := http.NewRequestWithContext(ctx, method, fullQualifiedEndpointURL.String(), &bodyContent)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", v2.UserAgent)
req.Header.Set("Content-Type", "application/json")
req.Header.Set(HeaderCLIFormat, "json")
if v2.session != nil {
v2.session.Lock()
defer v2.session.Unlock()
req.Header.Set(HeaderCLISessionId, v2.session.SessionId)
req.Header.Set(HeaderCLISubdomain, v2.session.GlobalAccountSubdomain)
req.Header.Set(HeaderCLICustomIDP, v2.session.IdentityProvider)
}
if correlationID := ctx.Value(v2ContextKey(HeaderCorrelationID)); correlationID != nil {
req.Header.Set(HeaderCorrelationID, correlationID.(string))
}
res, err := v2.httpClient.Do(req)
return res, err
}
func (v2 *v2Client) doPostRequest(ctx context.Context, endpoint string, body any) (*http.Response, error) {
return v2.doRequest(ctx, http.MethodPost, endpoint, body)
}
func (v2 *v2Client) parseResponse(ctx context.Context, res *http.Response, targetObj any, goodState int, knownErrorStates map[int]string) error {
if err := v2.checkResponseForErrors(ctx, res, goodState, knownErrorStates); err != nil {
return err
}
if targetObj == nil {
return nil
}
return json.NewDecoder(res.Body).Decode(targetObj)
}
func (v2 *v2Client) checkResponseForErrors(ctx context.Context, res *http.Response, goodState int, knownErrorStates map[int]string) error {
if res.StatusCode == goodState {
return nil
}
var err error
if errorMsg, known := knownErrorStates[res.StatusCode]; known {
err = fmt.Errorf("%s", errorMsg)
} else {
err = v2.parseResponseError(ctx, res)
}
return fmt.Errorf("%w [Status: %d; Correlation ID: %s]", err, res.StatusCode, ctx.Value(v2ContextKey(HeaderCorrelationID)))
}
func (v2 *v2Client) parseResponseError(ctx context.Context, res *http.Response) error {
return fmt.Errorf("received response with unexpected status")
}
// Login authenticates a user using username + password
func (v2 *v2Client) Login(ctx context.Context, loginReq *LoginRequest) (*LoginResponse, error) {
ctx = v2.initTrace(ctx)
// TODO: After the switch to client protocol v2.49.0 the terraform provider is still providing
// the globalaccount subdomain during login. However, this relies on a special handling
// for older clients that might be removed from the server in the future.
res, err := v2.doPostRequest(ctx, path.Join("login", cliTargetProtocolVersion), loginReq)
if err != nil {
return nil, err
}
var loginResponse LoginResponse
err = v2.parseResponse(ctx, res, &loginResponse, http.StatusOK, map[int]string{
http.StatusUnauthorized: "Login failed. Check your credentials.",
http.StatusForbidden: fmt.Sprintf("You cannot access global account '%s'. Make sure you have at least read access to the global account, a directory, or a subaccount.", loginReq.GlobalAccountSubdomain),
http.StatusNotFound: fmt.Sprintf("Global account '%s' not found. Try again and make sure to provide the global account's subdomain.", loginReq.GlobalAccountSubdomain),
http.StatusPreconditionFailed: "Login failed due to outdated provider version. Update to the latest version of the provider.",
http.StatusGatewayTimeout: "Login timed out. Please try again later.",
})
if err != nil {
return nil, err
}
v2.session = &Session{
GlobalAccountSubdomain: loginReq.GlobalAccountSubdomain,
IdentityProvider: loginReq.IdentityProvider,
LoggedInUser: &v2LoggedInUser{
Username: loginResponse.Username,
Email: loginResponse.Email,
Issuer: loginResponse.Issuer,
},
SessionId: res.Header.Get(HeaderCLISessionId),
}
return &loginResponse, nil
}
// IdTokenLogin authenticates a user by providing an id token
func (v2 *v2Client) IdTokenLogin(ctx context.Context, loginReq *IdTokenLoginRequest) (*LoginResponse, error) {
ctx = v2.initTrace(ctx)
res, err := v2.doPostRequest(ctx, path.Join("login", cliTargetProtocolVersion, "idtoken"), loginReq)
if err != nil {
return nil, err
}
var loginResponse LoginResponse
err = v2.parseResponse(ctx, res, &loginResponse, http.StatusOK, map[int]string{
http.StatusBadRequest: "Login failed. Invalid provider configuration.",
http.StatusUnauthorized: "Login failed. Please check ID Token validity.",
http.StatusNotFound: fmt.Sprintf("Global account '%s' not found. Try again and make sure to provide the global account's subdomain.", loginReq.GlobalAccountSubdomain),
http.StatusPreconditionFailed: "Login failed due to outdated provider version. Update to the latest version of the provider.",
http.StatusGatewayTimeout: "Login timed out. Please try again later.",
})
if err != nil && err.Error() != "EOF" { // TODO: stop ignoring EOF when btp CLI server returning non-empty body has reached productive landscapes
return nil, err
}
v2.session = &Session{
GlobalAccountSubdomain: loginReq.GlobalAccountSubdomain,
IdentityProvider: loginResponse.Issuer,
LoggedInUser: &v2LoggedInUser{
Username: loginResponse.Username,
Email: loginResponse.Email,
Issuer: loginResponse.Issuer,
},
SessionId: res.Header.Get(HeaderCLISessionId),
}
return &loginResponse, nil
}
// PasscodeLogin authenticates with a pem encoded x509 key-pair
func (v2 *v2Client) PasscodeLogin(ctx context.Context, loginReq *PasscodeLoginRequest) (*LoginResponse, error) {
ctx = v2.initTrace(ctx)
clientCert, err := tls.X509KeyPair([]byte(loginReq.PEMEncodedCertificate), []byte(loginReq.PEMEncodedPrivateKey))
if err != nil {
return nil, err
}
caCertPool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
if len(loginReq.PEMEncodedCACerts) > 0 {
caCertPool.AppendCertsFromPEM([]byte(loginReq.PEMEncodedCACerts))
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{clientCert},
RootCAs: caCertPool,
}
tlsTransport := (http.DefaultTransport.(*http.Transport)).Clone()
tlsTransport.TLSClientConfig = tlsConfig
idpClient := &http.Client{Transport: tlsTransport}
res, err := idpClient.Get(fmt.Sprintf("%s/service/users/passcode", loginReq.IdentityProviderURL)) // TODO use URL
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("IDP responded with unexpected response code: %d", res.StatusCode)
}
var passcodeResponse struct {
Passcode string `json:"passcode"`
}
if err := json.NewDecoder(res.Body).Decode(&passcodeResponse); err != nil {
return nil, err
}
return v2.Login(ctx, &LoginRequest{
IdentityProvider: loginReq.IdentityProvider,
GlobalAccountSubdomain: loginReq.GlobalAccountSubdomain,
Username: loginReq.Username,
Password: passcodeResponse.Passcode,
})
}
// Execute executes a command
func (v2 *v2Client) Execute(ctx context.Context, cmdReq *CommandRequest, options ...CommandOptions) (cmdRes CommandResponse, err error) {
ctx = v2.initTrace(ctx)
wrappedArgs := struct {
ParamValues any `json:"paramValues"`
}{
ParamValues: cmdReq.Args,
}
res, err := v2.doPostRequest(ctx, fmt.Sprintf("%s?%s", path.Join("command", cliTargetProtocolVersion, cmdReq.Command), cmdReq.Action), wrappedArgs)
if err != nil {
return
}
opts := firstElementOrDefault(options, CommandOptions{GoodState: http.StatusOK, KnownErrorStates: map[int]string{}})
opts.KnownErrorStates[http.StatusGatewayTimeout] = "Command timed out. Please try again later."
opts.KnownErrorStates[http.StatusForbidden] = "Access forbidden due to insufficient authorization. Make sure to have sufficient access rights."
if err = v2.checkResponseForErrors(ctx, res, opts.GoodState, opts.KnownErrorStates); err != nil {
return
}
if cmdRes.StatusCode, err = strconv.Atoi(res.Header.Get(HeaderCLIBackendStatus)); err != nil {
err = fmt.Errorf("unable to convert reported backend status code: %w", err)
return
}
if cmdRes.StatusCode >= 400 {
var backendError struct {
Message string `json:"error"`
}
if err = json.NewDecoder(res.Body).Decode(&backendError); err == nil {
err = fmt.Errorf(backendError.Message)
} else if res.Header.Get(HeaderCLIServerMessage) != "" {
err = fmt.Errorf("the backend responded with an error: %s", res.Header.Get(HeaderCLIServerMessage))
} else {
err = fmt.Errorf("the backend responded with an unknown error: %d", cmdRes.StatusCode)
}
return
}
cmdRes.Body = res.Body
cmdRes.ContentType = res.Header.Get(HeaderCLIBackendMediaType)
return
}
func (v2 *v2Client) GetGlobalAccountSubdomain() string {
if v2.session == nil {
return ""
}
return v2.session.GlobalAccountSubdomain
}
func (v2 *v2Client) GetLoggedInUser() *v2LoggedInUser {
if v2.session == nil {
return nil
}
return v2.session.LoggedInUser
}