-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.go
363 lines (303 loc) · 9.3 KB
/
api.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
package api
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen --package=api -generate=types -o ./openapi.gen.go ../../config/openapi.yml
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"net/url"
"strings"
"github.com/anchordotdev/cli"
"github.com/anchordotdev/cli/keyring"
"golang.org/x/exp/slices"
)
var (
ErrSignedOut = errors.New("sign in required")
)
// NB: can't call this Client since the name is already taken by an openapi
// generated type. It's more like a session anyways, since it caches some
// current user info.
type Session struct {
*http.Client
cfg *cli.Config
userInfo *Root
}
// TODO: rename to NewSession
func NewClient(cfg *cli.Config) (*Session, error) {
anc := &Session{
Client: &http.Client{
Transport: urlRewriter{
RoundTripper: responseChecker{
RoundTripper: new(http.Transport),
},
URL: cfg.API.URL,
},
},
cfg: cfg,
}
apiToken := cfg.API.Token
if apiToken == "" {
var (
kr = keyring.Keyring{Config: cfg}
err error
)
if apiToken, err = kr.Get(keyring.APIToken); err == keyring.ErrNotFound {
return anc, ErrSignedOut
} else if err != nil {
return nil, fmt.Errorf("reading PAT token from keyring failed: %w", err)
}
if !strings.HasPrefix(apiToken, "ap0_") || len(apiToken) != 64 {
return nil, fmt.Errorf("read invalid PAT token from keyring")
}
}
anc.Client.Transport = basicAuther{
RoundTripper: anc.Client.Transport,
PAT: apiToken,
}
return anc, nil
}
func attachServicePath(orgSlug, serviceSlug string) string {
return "/orgs/" + url.QueryEscape(orgSlug) + "/services/" + url.QueryEscape(serviceSlug) + "/actions/attach"
}
func (s *Session) AttachService(ctx context.Context, chainSlug string, domains []string, orgSlug, realmSlug, serviceSlug string) (*ServicesXtach200, error) {
attachInput := AttachOrgServiceJSONRequestBody{
Domains: domains,
}
attachInput.Relationships.Chain.Slug = chainSlug
attachInput.Relationships.Realm.Slug = realmSlug
var attachOutput ServicesXtach200
if err := s.post(ctx, attachServicePath(orgSlug, serviceSlug), attachInput, &attachOutput); err != nil {
return nil, err
}
return &attachOutput, nil
}
func (s *Session) CreatePATToken(ctx context.Context, deviceCode string) (string, error) {
reqBody := CreateCliTokenJSONRequestBody{
DeviceCode: deviceCode,
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(reqBody); err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, "POST", "/cli/pat-tokens", &buf)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
res, err := s.Do(req)
if err != nil {
return "", err
}
switch res.StatusCode {
case http.StatusOK:
var patTokens *AuthCliPatTokensResponse
if err = json.NewDecoder(res.Body).Decode(&patTokens); err != nil {
return "", err
}
return patTokens.PatToken, nil
case http.StatusBadRequest:
var errorsRes *Error
if err = json.NewDecoder(res.Body).Decode(&errorsRes); err != nil {
return "", err
}
switch errorsRes.Type {
case "urn:anchordev:api:cli-auth:authorization-pending":
return "", nil
case "urn:anchordev:api:cli-auth:expired-device-code":
return "", fmt.Errorf("Your authorization request has expired, please try again.")
case "urn:anchordev:api:cli-auth:incorrect-device-code":
return "", fmt.Errorf("Your authorization request was not found, please try again.")
default:
return "", fmt.Errorf("unexpected error: %s", errorsRes.Detail)
}
default:
return "", fmt.Errorf("unexpected response code: %d", res.StatusCode)
}
}
func (s *Session) CreateEAB(ctx context.Context, chainSlug, orgSlug, realmSlug, serviceSlug, subCASlug string) (*Eab, error) {
var eabInput CreateEabTokenJSONRequestBody
eabInput.Relationships.Chain.Slug = chainSlug
eabInput.Relationships.Organization.Slug = orgSlug
eabInput.Relationships.Realm.Slug = realmSlug
eabInput.Relationships.Service.Slug = &serviceSlug
eabInput.Relationships.SubCa.Slug = subCASlug
var eabOutput Eab
if err := s.post(ctx, "/acme/eab-tokens", eabInput, &eabOutput); err != nil {
return nil, err
}
return &eabOutput, nil
}
func (s *Session) CreateService(ctx context.Context, orgSlug, serviceSlug, serverType string, localhostPort *int) (*Service, error) {
serviceInput := CreateServiceJSONRequestBody{
Name: serviceSlug,
ServerType: serverType,
LocalhostPort: localhostPort,
}
serviceInput.Relationships.Organization.Slug = orgSlug
var serviceOutput Service
if err := s.post(ctx, "/services", serviceInput, &serviceOutput); err != nil {
return nil, err
}
return &serviceOutput, nil
}
func fetchCredentialsPath(orgSlug, realmSlug string) string {
return "/orgs/" + url.QueryEscape(orgSlug) + "/realms/" + url.QueryEscape(realmSlug) + "/x509/credentials"
}
func (s *Session) FetchCredentials(ctx context.Context, orgSlug, realmSlug string) ([]Credential, error) {
var creds struct {
Items []Credential `json:"items,omitempty"`
}
if err := s.get(ctx, fetchCredentialsPath(orgSlug, realmSlug), &creds); err != nil {
return nil, err
}
return creds.Items, nil
}
func (s *Session) UserInfo(ctx context.Context) (*Root, error) {
if s.userInfo != nil {
return s.userInfo, nil
}
if err := s.get(ctx, "", &s.userInfo); err != nil {
return nil, err
}
return s.userInfo, nil
}
func (s *Session) GenerateUserFlowCodes(ctx context.Context, source string) (*AuthCliCodesResponse, error) {
var codes AuthCliCodesResponse
if err := s.post(ctx, "/cli/codes", nil, &codes); err != nil {
return nil, err
}
// TODO: should the request POST the signup source instead?
if source != "" {
codes.VerificationUri += "?signup_src=" + source
}
return &codes, nil
}
func getOrgServicesPath(orgSlug string) string {
return "/orgs/" + url.QueryEscape(orgSlug) + "/services"
}
func (s *Session) GetOrgServices(ctx context.Context, orgSlug string) ([]Service, error) {
var svc Services
if err := s.get(ctx, getOrgServicesPath(orgSlug), &svc); err != nil {
return nil, err
}
return svc.Items, nil
}
func getServicePath(orgSlug, serviceSlug string) string {
return "/orgs/" + url.QueryEscape(orgSlug) + "/services/" + url.QueryEscape(serviceSlug)
}
func (s *Session) GetService(ctx context.Context, orgSlug, serviceSlug string) (*Service, error) {
var svc Service
if err := s.get(ctx, getServicePath(orgSlug, serviceSlug), &svc); err != nil {
if errors.Is(err, NotFoundErr) {
return nil, nil
}
return nil, err
}
return &svc, nil
}
func (s *Session) get(ctx context.Context, path string, out any) error {
req, err := http.NewRequestWithContext(ctx, "GET", path, nil)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := s.Do(req)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
var errorsRes *Error
if err = json.NewDecoder(res.Body).Decode(&errorsRes); err != nil {
return err
}
return fmt.Errorf("%w: %s", StatusCodeError(res.StatusCode), errorsRes.Title)
}
return json.NewDecoder(res.Body).Decode(out)
}
func (s *Session) post(ctx context.Context, path string, in, out any) error {
var buf bytes.Buffer
if in != nil {
if err := json.NewEncoder(&buf).Encode(in); err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, "POST", path, &buf)
if err != nil {
return err
}
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
res, err := s.Do(req)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
var errorsRes *Error
if err = json.NewDecoder(res.Body).Decode(&errorsRes); err != nil {
return err
}
return fmt.Errorf("%w: %s", StatusCodeError(res.StatusCode), errorsRes.Title)
}
return json.NewDecoder(res.Body).Decode(out)
}
type basicAuther struct {
http.RoundTripper
PAT string
}
func (r basicAuther) RoundTrip(req *http.Request) (*http.Response, error) {
if r.PAT != "" {
req.SetBasicAuth(r.PAT, "")
}
return r.RoundTripper.RoundTrip(req)
}
type responseChecker struct {
http.RoundTripper
}
var jsonMediaTypes = mediaTypes{
"application/json",
"application/problem+json",
}
func (r responseChecker) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := r.RoundTripper.RoundTrip(req)
if err != nil {
return nil, fmt.Errorf("request error %s %s: %w", req.Method, req.URL.Path, err)
}
switch res.StatusCode {
case http.StatusForbidden:
return nil, ErrSignedOut
case http.StatusInternalServerError:
return nil, fmt.Errorf("request failed: %w", err)
}
if contentType := res.Header.Get("Content-Type"); !jsonMediaTypes.Matches(contentType) {
return nil, fmt.Errorf("non-json response received: %q: %w", contentType, err)
}
return res, nil
}
type urlRewriter struct {
http.RoundTripper
URL string
}
func (r urlRewriter) RoundTrip(req *http.Request) (*http.Response, error) {
u, err := url.Parse(r.URL)
if err != nil {
return nil, err
}
req.URL = u.JoinPath(req.URL.Path)
return r.RoundTripper.RoundTrip(req)
}
type mediaTypes []string
func (s mediaTypes) Matches(val string) bool {
media, _, err := mime.ParseMediaType(val)
if err != nil {
return false
}
return slices.Contains(s, media)
}
type StatusCodeError int
const NotFoundErr = StatusCodeError(http.StatusNotFound)
func (err StatusCodeError) StatusCode() int { return int(err) }
func (err StatusCodeError) Error() string { return fmt.Sprintf("unexpected %d status response", err) }