-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
427 lines (402 loc) · 13.6 KB
/
Copy pathapi.go
File metadata and controls
427 lines (402 loc) · 13.6 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
internalapi "atomgit.com/hust-open-atom-club/atomgit-cli/internal/api"
"atomgit.com/hust-open-atom-club/atomgit-cli/internal/commandschema"
"atomgit.com/hust-open-atom-club/atomgit-cli/pkg/cmdutil"
"github.com/spf13/cobra"
)
type options struct {
method string
fields []string
input string
accept string
paginate bool
}
type preparedRequest struct {
method string
path string
body []byte
contentType string
accept string
pagination *paginationState
}
type paginationState struct {
page int
perPage int
totalPages int
visited map[string]bool
}
type redactedError struct {
message string
cause error
}
func (e *redactedError) Error() string { return e.message }
func (e *redactedError) Unwrap() error { return e.cause }
func NewCmdAPI(f *cmdutil.Factory) *cobra.Command {
opts := options{}
cmd := &cobra.Command{
Use: "api <endpoint>",
Short: "Make an authenticated AtomGit API request",
SilenceUsage: true,
Long: `Make an authenticated request to a relative AtomGit API v5 endpoint.
GET is the default. Supported methods are GET, POST, PATCH, PUT, and DELETE.
Explicit non-GET requests may change remote resources; ag does not infer or
confirm the endpoint's effects. Redirects only retain credentials on the exact
AtomGit API origin. Paginated output is one compact JSON page per line.
Response bytes use terminal-safe output unless --raw-output is specified.`,
Example: ` ag api /user
ag api /repos/owner/repo/issues --field state=open
ag api /repos/owner/repo/issues --method POST --field title='New issue'
ag api /repos/owner/repo/issues/42 --method PATCH --input update.json
ag api /repos/owner/repo/issues --paginate`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
prepared, err := prepare(args[0], opts, cmd.InOrStdin())
if err != nil {
return err
}
return execute(cmd, f, prepared)
},
}
cmd.Flags().StringVarP(&opts.method, "method", "X", http.MethodGet, "HTTP method: GET, POST, PATCH, PUT, or DELETE")
cmd.Flags().StringArrayVarP(&opts.fields, "field", "f", nil, "Add a string field as key=value")
cmd.Flags().StringVar(&opts.input, "input", "", "Read the raw request body from a file or - for stdin")
cmd.Flags().StringVarP(&opts.accept, "accept", "H", "application/json", "Set the Accept request header")
cmd.Flags().BoolVar(&opts.paginate, "paginate", false, "Request all pages and emit compact JSON pages as NDJSON")
commandschema.Annotate(cmd, commandschema.Metadata{
Positionals: &commandschema.Positionals{MinCount: 1, MaxCount: 1, Description: "One relative AtomGit API v5 endpoint; absolute URLs and path escapes are rejected."},
Output: "raw", Effects: "conditional",
Notes: []string{"Output is the response body; pagination emits JSON pages as NDJSON. Response shape and required permissions depend on the endpoint.", "Non-GET methods may modify remote resources. Field/input combinations and pagination have additional runtime validation."},
})
return cmd
}
func prepare(endpoint string, opts options, stdin io.Reader) (preparedRequest, error) {
method := strings.ToUpper(strings.TrimSpace(opts.method))
switch method {
case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodPut, http.MethodDelete:
default:
return preparedRequest{}, fmt.Errorf("unsupported HTTP method %q", opts.method)
}
path, values, err := parseEndpoint(endpoint)
if err != nil {
return preparedRequest{}, err
}
if !validHeaderValue(opts.accept) {
return preparedRequest{}, fmt.Errorf("invalid Accept value")
}
if opts.input != "" && len(opts.fields) > 0 {
return preparedRequest{}, fmt.Errorf("--input and --field cannot be used together")
}
if opts.paginate && method != http.MethodGet {
return preparedRequest{}, fmt.Errorf("--paginate requires GET")
}
if opts.paginate && opts.input != "" {
return preparedRequest{}, fmt.Errorf("--paginate cannot be used with --input")
}
fields, err := parseFields(opts.fields)
if err != nil {
return preparedRequest{}, err
}
request := preparedRequest{method: method, accept: opts.accept}
if method == http.MethodGet {
for _, field := range fields {
values.Add(field[0], field[1])
}
} else if len(fields) > 0 {
object := make(map[string]string, len(fields))
for _, field := range fields {
object[field[0]] = field[1]
}
request.body, err = json.Marshal(object)
if err != nil {
return preparedRequest{}, fmt.Errorf("encode fields: %w", err)
}
request.contentType = "application/json"
}
if opts.input != "" {
if opts.input == "-" {
request.body, err = io.ReadAll(stdin)
} else {
request.body, err = os.ReadFile(opts.input)
}
if err != nil {
return preparedRequest{}, fmt.Errorf("read input %q: %w", opts.input, err)
}
}
if opts.paginate {
request.pagination, err = preparePagination(values)
if err != nil {
return preparedRequest{}, err
}
}
request.path = path
if encoded := values.Encode(); encoded != "" {
request.path += "?" + encoded
}
return request, nil
}
func parseEndpoint(value string) (string, url.Values, error) {
if value == "" || strings.HasPrefix(value, "//") {
return "", nil, fmt.Errorf("endpoint must be a relative API v5 path")
}
parsed, err := url.Parse(value)
if err != nil {
return "", nil, fmt.Errorf("invalid endpoint: %w", err)
}
if parsed.IsAbs() || parsed.Host != "" || parsed.User != nil || parsed.Fragment != "" || parsed.Path == "" {
return "", nil, fmt.Errorf("endpoint must be a relative API v5 path without a fragment")
}
unescapedPath, err := url.PathUnescape(parsed.EscapedPath())
if err != nil {
return "", nil, fmt.Errorf("invalid endpoint path escape: %w", err)
}
for segment := range strings.SplitSeq(unescapedPath, "/") {
if segment == "." || segment == ".." {
return "", nil, fmt.Errorf("endpoint must remain within the API v5 base path")
}
}
query, err := url.ParseQuery(parsed.RawQuery)
if err != nil {
return "", nil, fmt.Errorf("invalid endpoint query: %w", err)
}
return "/" + strings.TrimLeft(parsed.EscapedPath(), "/"), query, nil
}
func parseFields(values []string) ([][2]string, error) {
fields := make([][2]string, 0, len(values))
for _, value := range values {
key, fieldValue, ok := strings.Cut(value, "=")
if !ok || key == "" {
return nil, fmt.Errorf("invalid field %q: expected non-empty key=value", value)
}
fields = append(fields, [2]string{key, fieldValue})
}
return fields, nil
}
func validHeaderValue(value string) bool {
if strings.TrimSpace(value) == "" {
return false
}
for _, r := range value {
if r == '\r' || r == '\n' || r == 0 || (r < 0x20 && r != '\t') || r == 0x7f {
return false
}
}
return true
}
func preparePagination(values url.Values) (*paginationState, error) {
state := &paginationState{page: 1, perPage: 100, visited: map[string]bool{}}
for key, target := range map[string]*int{"page": &state.page, "per_page": &state.perPage} {
entries := values[key]
if len(entries) > 1 {
return nil, fmt.Errorf("pagination query %q must occur once", key)
}
if len(entries) == 1 {
parsed, err := strconv.Atoi(entries[0])
if err != nil || parsed <= 0 {
return nil, fmt.Errorf("pagination query %q must be a positive integer", key)
}
*target = parsed
}
}
values.Set("page", strconv.Itoa(state.page))
values.Set("per_page", strconv.Itoa(state.perPage))
return state, nil
}
func execute(cmd *cobra.Command, f *cmdutil.Factory, request preparedRequest) error {
if f == nil || f.Config == nil {
return fmt.Errorf("configuration is unavailable")
}
token, err := f.Config.GetToken()
if err != nil {
return redact(cmdutil.AuthenticationError(err), token)
}
httpClient, err := requestHTTPClient(f)
if err != nil {
return redact(err, token)
}
client := internalapi.NewClientWithHTTPClient(token, cloneRedirectSafeClient(httpClient)).WithContext(cmd.Context())
if request.pagination != nil {
return executePagination(cmd.OutOrStdout(), client, request, token)
}
resp, err := client.DoRequestRawWithBody(request.method, request.path, request.body, request.contentType, request.accept)
if err != nil {
return redact(fmt.Errorf("request %s %s: %w", request.method, request.path, err), token)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return responseError(request.method+" "+request.path, resp, token)
}
if _, err := io.Copy(cmd.OutOrStdout(), resp.Body); err != nil {
return redact(fmt.Errorf("read response: %w", err), token)
}
return nil
}
func requestHTTPClient(f *cmdutil.Factory) (*http.Client, error) {
if f.HttpClient == nil {
return &http.Client{Timeout: 30 * time.Second}, nil
}
client, err := f.HttpClient()
if err != nil {
return nil, fmt.Errorf("create HTTP client: %w", err)
}
if client == nil {
return nil, fmt.Errorf("create HTTP client: returned nil client")
}
return client, nil
}
func cloneRedirectSafeClient(source *http.Client) *http.Client {
clone := *source
previous := source.CheckRedirect
clone.CheckRedirect = func(req *http.Request, via []*http.Request) error {
stripRedirectAuthorization(req, via)
if previous != nil {
if err := previous(req, via); err != nil {
return err
}
} else if len(via) >= 10 {
return fmt.Errorf("stopped after 10 redirects")
}
stripRedirectAuthorization(req, via)
return nil
}
return &clone
}
func stripRedirectAuthorization(req *http.Request, via []*http.Request) {
for _, prior := range via {
if !sameOrigin(prior.URL, req.URL) || prior.Header.Get("Authorization") == "" {
req.Header.Del("Authorization")
return
}
}
}
func sameOrigin(a, b *url.URL) bool {
return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Hostname(), b.Hostname()) && effectivePort(a) == effectivePort(b)
}
func effectivePort(value *url.URL) string {
if value.Port() != "" {
return value.Port()
}
if strings.EqualFold(value.Scheme, "https") {
return "443"
}
if strings.EqualFold(value.Scheme, "http") {
return "80"
}
return ""
}
func responseError(operation string, resp *http.Response, token string) error {
details := internalapi.ReadErrorResponse(resp)
result := fmt.Errorf("%s: API request failed (%s)", internalapi.SanitizeErrorText(operation), details.Status)
if details.Message != "" {
result = fmt.Errorf("%w: %s", result, details.Message)
}
if details.RetryAfter != "" {
result = fmt.Errorf("%w (retry after %s)", result, details.RetryAfter)
}
if details.ReadError != nil {
safeReadError := &redactedError{
message: internalapi.SanitizeErrorText(details.ReadError.Error()),
cause: details.ReadError,
}
result = fmt.Errorf("%w: read error response: %w", result, safeReadError)
}
return redact(result, token)
}
// redact replaces an access token in an error message with a placeholder.
// Redaction is unconditional for every accepted non-empty token so that even
// short tokens cannot be exposed verbatim; if short tokens should be invalid,
// that is enforced at the credential boundary, not here.
func redact(err error, token string) error {
if err == nil || token == "" || !strings.Contains(err.Error(), token) {
return err
}
return &redactedError{message: strings.ReplaceAll(err.Error(), token, "[REDACTED]"), cause: err}
}
func executePagination(out io.Writer, client *internalapi.Client, request preparedRequest, token string) error {
state := request.pagination
base, err := url.Parse(request.path)
if err != nil {
return err
}
for {
query := base.Query()
query.Set("page", strconv.Itoa(state.page))
query.Set("per_page", strconv.Itoa(state.perPage))
base.RawQuery = query.Encode()
path := base.RequestURI()
if state.visited[path] {
return fmt.Errorf("pagination repeated request %q", path)
}
state.visited[path] = true
resp, err := client.DoRequestRawWithBody(http.MethodGet, path, nil, "", request.accept)
if err != nil {
return redact(fmt.Errorf("request page %d: %w", state.page, err), token)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
err := responseError(fmt.Sprintf("request page %d", state.page), resp, token)
resp.Body.Close()
return err
}
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return redact(fmt.Errorf("read page %d: %w", state.page, readErr), token)
}
var value json.RawMessage
if json.Unmarshal(body, &value) != nil {
return fmt.Errorf("page %d is not valid JSON", state.page)
}
compact := bytes.Buffer{}
if err := json.Compact(&compact, body); err != nil {
return fmt.Errorf("compact page %d: %w", state.page, err)
}
total, err := parseTotalPages(resp.Header.Get("total_page"))
if err != nil {
return fmt.Errorf("page %d: %w", state.page, err)
}
if total > 0 {
if state.totalPages != 0 && total != state.totalPages {
return fmt.Errorf("page %d returned inconsistent total_page", state.page)
}
state.totalPages = total
}
stop := state.totalPages > 0 && state.page >= state.totalPages
if state.totalPages == 0 {
var array []json.RawMessage
if err := json.Unmarshal(body, &array); err != nil {
return fmt.Errorf("page %d has no total_page and is not an array", state.page)
}
stop = len(array) < state.perPage
}
if _, err := compact.WriteTo(out); err != nil {
return fmt.Errorf("write page %d: %w", state.page, err)
}
if _, err := io.WriteString(out, "\n"); err != nil {
return fmt.Errorf("write page %d: %w", state.page, err)
}
if stop {
return nil
}
state.page++
}
}
func parseTotalPages(value string) (int, error) {
if value == "" {
return 0, nil
}
total, err := strconv.Atoi(value)
if err != nil || total <= 0 {
return 0, fmt.Errorf("invalid total_page header")
}
return total, nil
}