-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.go
More file actions
325 lines (282 loc) · 8.72 KB
/
client.go
File metadata and controls
325 lines (282 loc) · 8.72 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
package deploymentrecord
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"math/rand/v2"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/github/deployment-tracker/pkg/dtmetrics"
"golang.org/x/time/rate"
)
// ClientOption is a function that configures the Client.
type ClientOption func(*Client)
// validOrgPattern validates organization names (alphanumeric, hyphens,
// underscores).
var validOrgPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
// Client is an API client for posting deployment records.
type Client struct {
baseURL string
org string
httpClient *http.Client
retries int
apiToken string
transport *ghinstallation.Transport
rateLimiter *rate.Limiter
}
// NewClient creates a new API client with the given base URL and
// organization. Returns an error if the base URL is not HTTPS for
// non-local hosts.
func NewClient(baseURL, org string, opts ...ClientOption) (*Client, error) {
// Check if URL is local (allowed to use HTTP)
isLocal := strings.HasPrefix(baseURL, "http://localhost") ||
strings.HasPrefix(baseURL, "http://127.0.0.1") ||
strings.Contains(baseURL, ".svc.cluster.local")
// Reject non-HTTPS URLs for non-local hosts
if strings.HasPrefix(baseURL, "http://") && !isLocal {
return nil, fmt.Errorf("insecure URL not allowed: %s (use HTTPS for non-local hosts)", baseURL)
}
// Add https:// prefix if no scheme is provided
if !strings.HasPrefix(baseURL, "https://") && !strings.HasPrefix(baseURL, "http://") {
baseURL = "https://" + baseURL
}
// Validate organization name to prevent URL injection
if !validOrgPattern.MatchString(org) {
return nil, fmt.Errorf("invalid organization name: %s (must be alphanumeric, hyphens, or underscores)", org)
}
c := &Client{
baseURL: baseURL,
org: org,
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
retries: 3,
// 20 req/sec with burst of 50
rateLimiter: rate.NewLimiter(rate.Limit(20), 50),
}
for _, opt := range opts {
opt(c)
}
return c, nil
}
// WithTimeout sets the HTTP client timeout in seconds.
func WithTimeout(seconds int) ClientOption {
return func(c *Client) {
c.httpClient.Timeout = time.Duration(seconds) * time.Second
}
}
// WithRetries sets the number of retries for failed requests.
func WithRetries(retries int) ClientOption {
return func(c *Client) {
c.retries = retries
}
}
// WithAPIToken sets the API token for Bearer authentication.
func WithAPIToken(token string) ClientOption {
return func(c *Client) {
c.apiToken = token
}
}
// WithGHApp configures a GitHub app to use for authentication.
// If provided values are invalid, this will panic.
// If an API token is also set, the GitHub App will take precedence.
func WithGHApp(id, installID string, pkBytes []byte, pkPath string) ClientOption {
return func(c *Client) {
if len(pkBytes) > 0 && pkPath != "" {
panic("both GitHub App private key and private key path are set")
}
pid, err := strconv.Atoi(id)
if err != nil {
panic(err)
}
piid, err := strconv.Atoi(installID)
if err != nil {
panic(err)
}
if len(pkBytes) > 0 {
c.transport, err = ghinstallation.New(
http.DefaultTransport,
int64(pid),
int64(piid),
pkBytes)
} else {
c.transport, err = ghinstallation.NewKeyFromFile(
http.DefaultTransport,
int64(pid),
int64(piid),
pkPath)
}
if err != nil {
panic(err)
}
}
}
// WithRateLimiter sets a custom rate limiter for API calls.
func WithRateLimiter(rps float64, burst int) ClientOption {
return func(c *Client) {
c.rateLimiter = rate.NewLimiter(rate.Limit(rps), burst)
}
}
// ClientError represents a client error that can not be retried.
type ClientError struct {
err error
}
func (c *ClientError) Error() string {
return fmt.Sprintf("client_error: %s", c.err.Error())
}
func (c *ClientError) Unwrap() error {
return c.err
}
// NoArtifactError represents a 404 client response whose body indicates "no artifacts found".
type NoArtifactError struct {
err error
}
func (n *NoArtifactError) Error() string {
return fmt.Sprintf("no artifact found: %s", n.err.Error())
}
func (n *NoArtifactError) Unwrap() error {
return n.err
}
// PostOne posts a single deployment record to the GitHub deployment
// records API.
func (c *Client) PostOne(ctx context.Context, record *DeploymentRecord) error {
if record == nil {
return errors.New("record cannot be nil")
}
// Wait for rate limiter
if err := c.rateLimiter.Wait(ctx); err != nil {
return fmt.Errorf("rate limiter wait failed: %w", err)
}
url := fmt.Sprintf("%s/orgs/%s/artifacts/metadata/deployment-record", c.baseURL, c.org)
body, err := json.Marshal(record)
if err != nil {
return fmt.Errorf("failed to marshal record: %w", err)
}
bodyReader := bytes.NewReader(body)
var lastErr error
// The first attempt is not a retry!
for attempt := range c.retries + 1 {
if attempt > 0 {
backoff := time.Duration(math.Pow(2,
float64(attempt))) * 100 * time.Millisecond
//nolint:gosec
jitter := time.Duration(rand.Int64N(50)) * time.Millisecond
delay := backoff + jitter
if delay > 5*time.Second {
delay = 5 * time.Second
}
// Wait with context cancellation support
select {
case <-time.After(delay):
case <-ctx.Done():
return fmt.Errorf("context cancelled during retry backoff: %w", ctx.Err())
}
}
// Reset reader position for retries
bodyReader.Reset(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bodyReader)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.transport != nil {
// Token is thread safe, so no need for external
// locking
tok, err := c.transport.Token(ctx)
if err != nil {
return fmt.Errorf("failed to get access token: %w", err)
}
req.Header.Set("Authorization", "Bearer "+tok)
} else if c.apiToken != "" {
req.Header.Set("Authorization", "Bearer "+c.apiToken)
}
start := time.Now()
// nolint: gosec
resp, err := c.httpClient.Do(req)
dur := time.Since(start)
dtmetrics.PostDeploymentRecordTimer.Observe(dur.Seconds())
if err != nil {
lastErr = fmt.Errorf("post request failed: %w", err)
slog.Warn("recoverable error, re-trying",
"attempt", attempt,
"retries", c.retries,
"error", lastErr)
dtmetrics.PostDeploymentRecordSoftFail.Inc()
continue
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
// Drain and close response body to enable connection reuse
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
dtmetrics.PostDeploymentRecordOk.Inc()
return nil
}
// Drain and close response body to enable connection reuse by reading body for error logging
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
switch {
case resp.StatusCode == 404:
// No artifact found
dtmetrics.PostDeploymentRecordNoAttestation.Inc()
slog.Debug("no artifact attestation found, no record created",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
"digest", record.Digest,
)
return &NoArtifactError{err: fmt.Errorf("no attestation found for %s", record.Digest)}
case resp.StatusCode >= 400 && resp.StatusCode < 500:
if resp.Header.Get("retry-after") != "" || resp.Header.Get("x-ratelimit-remaining") == "0" {
// Rate limited — retry with backoff
// Could be 403 or 429
dtmetrics.PostDeploymentRecordRateLimited.Inc()
slog.Warn("rate limited, retrying",
"attempt", attempt,
"status_code", resp.StatusCode,
"retry_after", resp.Header.Get("Retry-After"),
"container_name", record.Name,
"resp_msg", string(respBody),
)
lastErr = fmt.Errorf("rate limited, attempt %d", attempt)
continue
}
// Don't retry non rate limiting client errors
dtmetrics.PostDeploymentRecordClientError.Inc()
slog.Warn("client error, aborting",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
)
return &ClientError{err: fmt.Errorf("unexpected client err with status code %d", resp.StatusCode)}
default:
// Retry with backoff
dtmetrics.PostDeploymentRecordSoftFail.Inc()
slog.Debug("retriable error",
"attempt", attempt,
"status_code", resp.StatusCode,
"container_name", record.Name,
"resp_msg", string(respBody),
)
lastErr = fmt.Errorf("server error, attempt %d", attempt)
}
}
dtmetrics.PostDeploymentRecordHardFail.Inc()
slog.Error("all retries exhausted",
"count", c.retries,
"error", lastErr,
"container_name", record.Name,
)
return fmt.Errorf("all retries exhausted: %w", lastErr)
}