| 1 | // Package github is the instance's GitHub App client and forge connection lifecycle. |
| 2 | package github |
| 3 | |
| 4 | import ( |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto" |
| 8 | "crypto/rand" |
| 9 | "crypto/rsa" |
| 10 | "crypto/sha256" |
| 11 | "crypto/x509" |
| 12 | "encoding/base64" |
| 13 | "encoding/json" |
| 14 | "encoding/pem" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | "io" |
| 18 | "maps" |
| 19 | "net/http" |
| 20 | "net/url" |
| 21 | "regexp" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | "sync" |
| 25 | "time" |
| 26 | ) |
| 27 | |
| 28 | var ( |
| 29 | ErrUnavailable = errors.New("github: unavailable") |
| 30 | ErrAccess = errors.New("github: access refused") |
| 31 | ErrRateLimit = errors.New("github: rate limited") |
| 32 | ErrTooMany = errors.New("github: repository limit") |
| 33 | ErrBusy = errors.New("github: busy") |
| 34 | ) |
| 35 | |
| 36 | // Retryable reports a busy or concurrent claim or a transient failure, not a |
| 37 | // setup failure. |
| 38 | func Retryable(err error) bool { |
| 39 | for _, kind := range []error{ErrBusy, ErrUnavailable, ErrRateLimit, context.DeadlineExceeded, context.Canceled} { |
| 40 | if errors.Is(err, kind) { |
| 41 | return true |
| 42 | } |
| 43 | } |
| 44 | return false |
| 45 | } |
| 46 | |
| 47 | const MaxRepositories = 1000 |
| 48 | const maxAnswer = 2 << 20 |
| 49 | |
| 50 | var component = regexp.MustCompile(`^[A-Za-z0-9_-]{1,256}$`) |
| 51 | var codePattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,256}$`) |
| 52 | |
| 53 | // ValidCode bounds a manifest code to one URL-safe path segment. |
| 54 | func ValidCode(code string) bool { return codePattern.MatchString(code) && code != "." && code != ".." } |
| 55 | |
| 56 | var loginPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$`) |
| 57 | |
| 58 | func ValidAccount(login, kind string) bool { |
| 59 | return loginPattern.MatchString(login) && (kind == "Organization" || kind == "User") |
| 60 | } |
| 61 | func permissions() map[string]string { |
| 62 | return map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} |
| 63 | } |
| 64 | |
| 65 | type Account struct { |
| 66 | ID int64 `json:"id"` |
| 67 | Login string `json:"login"` |
| 68 | Type string `json:"type"` |
| 69 | } |
| 70 | type App struct { |
| 71 | ID int64 `json:"id"` |
| 72 | Slug string `json:"slug"` |
| 73 | Owner Account `json:"owner"` |
| 74 | Permissions map[string]string `json:"permissions"` |
| 75 | Events []string `json:"events"` |
| 76 | pem string |
| 77 | generation int64 |
| 78 | } |
| 79 | |
| 80 | func (a App) String() string { return fmt.Sprintf("github.App(%d)", a.ID) } |
| 81 | func (a App) GoString() string { return a.String() } |
| 82 | |
| 83 | type Installation struct { |
| 84 | ID int64 `json:"id"` |
| 85 | AppID int64 `json:"app_id"` |
| 86 | Account Account `json:"account"` |
| 87 | Permissions map[string]string `json:"permissions"` |
| 88 | Events []string `json:"events"` |
| 89 | Selection string `json:"repository_selection"` |
| 90 | Suspended *time.Time `json:"suspended_at"` |
| 91 | } |
| 92 | type Repository struct { |
| 93 | ID int64 `json:"id"` |
| 94 | Name string `json:"full_name"` |
| 95 | Owner Account `json:"owner"` |
| 96 | } |
| 97 | type Inventory struct { |
| 98 | Repositories []Repository |
| 99 | Count int |
| 100 | } |
| 101 | type APIError struct { |
| 102 | Status int |
| 103 | Kind error |
| 104 | } |
| 105 | |
| 106 | func (e *APIError) Error() string { return e.Kind.Error() } |
| 107 | func (e *APIError) Unwrap() error { return e.Kind } |
| 108 | |
| 109 | // metadataCredential never leaves the instance or becomes a project grant. |
| 110 | type metadataCredential struct { |
| 111 | value string |
| 112 | expires time.Time |
| 113 | installation int64 |
| 114 | selection string |
| 115 | pages map[int]inventoryPage |
| 116 | generation int64 |
| 117 | } |
| 118 | type API struct { |
| 119 | client *http.Client |
| 120 | now func() time.Time |
| 121 | mu sync.Mutex |
| 122 | tokens map[int64]metadataCredential |
| 123 | // epochs advance on Forget, so a token minted across it is revoked, not kept. |
| 124 | epochs map[int64]uint64 |
| 125 | } |
| 126 | |
| 127 | func NewAPI(transport http.RoundTripper, now func() time.Time) *API { |
| 128 | if transport == nil { |
| 129 | transport = http.DefaultTransport |
| 130 | if base, ok := transport.(*http.Transport); ok { |
| 131 | owned := base.Clone() |
| 132 | owned.MaxResponseHeaderBytes = 32 << 10 |
| 133 | transport = owned |
| 134 | } |
| 135 | } |
| 136 | if now == nil { |
| 137 | now = time.Now |
| 138 | } |
| 139 | return &API{client: &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, now: now, tokens: map[int64]metadataCredential{}, epochs: map[int64]uint64{}} |
| 140 | } |
| 141 | func (a *API) request(ctx context.Context, method, path, credential string, body, out any, conditional ...string) (http.Header, error) { |
| 142 | var payload []byte |
| 143 | var err error |
| 144 | if body != nil { |
| 145 | payload, err = json.Marshal(body) |
| 146 | if err != nil { |
| 147 | return nil, ErrUnavailable |
| 148 | } |
| 149 | } |
| 150 | req, err := http.NewRequestWithContext(ctx, method, "https://api.github.com"+path, bytes.NewReader(payload)) |
| 151 | if err != nil { |
| 152 | return nil, ErrUnavailable |
| 153 | } |
| 154 | req.Header.Set("Accept", "application/vnd.github+json") |
| 155 | req.Header.Set("X-GitHub-Api-Version", "2022-11-28") |
| 156 | req.Header.Set("User-Agent", "Equipo") |
| 157 | if body != nil { |
| 158 | req.Header.Set("Content-Type", "application/json") |
| 159 | } |
| 160 | if credential != "" { |
| 161 | req.Header.Set("Authorization", "Bearer "+credential) |
| 162 | } |
| 163 | if len(conditional) == 1 && conditional[0] != "" { |
| 164 | req.Header.Set("If-None-Match", conditional[0]) |
| 165 | } |
| 166 | response, err := a.client.Do(req) |
| 167 | if err != nil { |
| 168 | return nil, ErrUnavailable |
| 169 | } |
| 170 | defer response.Body.Close() |
| 171 | if response.StatusCode == http.StatusNotModified { |
| 172 | return response.Header, errNotModified |
| 173 | } |
| 174 | if response.StatusCode < 200 || response.StatusCode >= 300 { |
| 175 | kind := ErrUnavailable |
| 176 | if response.StatusCode == 401 || response.StatusCode == 403 || response.StatusCode == 404 || response.StatusCode == 422 { |
| 177 | kind = ErrAccess |
| 178 | } |
| 179 | if response.StatusCode == 429 || (response.StatusCode == 403 && (response.Header.Get("X-RateLimit-Remaining") == "0" || response.Header.Get("Retry-After") != "")) { |
| 180 | kind = ErrRateLimit |
| 181 | } |
| 182 | return nil, &APIError{response.StatusCode, kind} |
| 183 | } |
| 184 | if out == nil { |
| 185 | return response.Header, nil |
| 186 | } |
| 187 | raw, err := io.ReadAll(io.LimitReader(response.Body, maxAnswer+1)) |
| 188 | if err != nil || len(raw) > maxAnswer { |
| 189 | return nil, ErrUnavailable |
| 190 | } |
| 191 | if json.Unmarshal(raw, out) != nil { |
| 192 | return nil, ErrUnavailable |
| 193 | } |
| 194 | return response.Header, nil |
| 195 | } |
| 196 | func parseKey(raw string) (*rsa.PrivateKey, error) { |
| 197 | block, rest := pem.Decode([]byte(raw)) |
| 198 | if block == nil || len(bytes.TrimSpace(rest)) != 0 { |
| 199 | return nil, ErrUnavailable |
| 200 | } |
| 201 | var key *rsa.PrivateKey |
| 202 | if block.Type == "RSA PRIVATE KEY" { |
| 203 | key, _ = x509.ParsePKCS1PrivateKey(block.Bytes) |
| 204 | } else if block.Type == "PRIVATE KEY" { |
| 205 | value, _ := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 206 | key, _ = value.(*rsa.PrivateKey) |
| 207 | } |
| 208 | if key == nil || key.N.BitLen() < 2048 || key.Validate() != nil { |
| 209 | return nil, ErrUnavailable |
| 210 | } |
| 211 | return key, nil |
| 212 | } |
| 213 | func (a *API) jwt(app App) (string, error) { |
| 214 | key, err := parseKey(app.pem) |
| 215 | if err != nil || app.ID <= 0 { |
| 216 | return "", ErrUnavailable |
| 217 | } |
| 218 | raw, _ := json.Marshal(map[string]any{"iss": strconv.FormatInt(app.ID, 10), "iat": a.now().Add(-time.Minute).Unix(), "exp": a.now().Add(5 * time.Minute).Unix()}) |
| 219 | message := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) + "." + base64.RawURLEncoding.EncodeToString(raw) |
| 220 | digest := sha256.Sum256([]byte(message)) |
| 221 | sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:]) |
| 222 | if err != nil { |
| 223 | return "", ErrUnavailable |
| 224 | } |
| 225 | return message + "." + base64.RawURLEncoding.EncodeToString(sig), nil |
| 226 | } |
| 227 | func validApp(app App) bool { |
| 228 | return app.ID > 0 && component.MatchString(app.Slug) && app.Owner.ID > 0 && ValidAccount(app.Owner.Login, app.Owner.Type) && maps.Equal(app.Permissions, permissions()) && app.Events != nil && len(app.Events) == 0 |
| 229 | } |
| 230 | func (a *API) Convert(ctx context.Context, code string) (App, error) { |
| 231 | if !ValidCode(code) { |
| 232 | return App{}, ErrAccess |
| 233 | } |
| 234 | var reply struct { |
| 235 | App |
| 236 | PEM string `json:"pem"` |
| 237 | } |
| 238 | _, err := a.request(ctx, "POST", "/app-manifests/"+code+"/conversions", "", nil, &reply) |
| 239 | if err != nil { |
| 240 | return App{}, err |
| 241 | } |
| 242 | if !validApp(reply.App) { |
| 243 | return App{}, ErrAccess |
| 244 | } |
| 245 | if _, err = parseKey(reply.PEM); err != nil { |
| 246 | return App{}, err |
| 247 | } |
| 248 | reply.App.pem = reply.PEM |
| 249 | return reply.App, nil |
| 250 | } |
| 251 | func (a *API) Verify(ctx context.Context, app App) (App, error) { |
| 252 | jwt, err := a.jwt(app) |
| 253 | if err != nil { |
| 254 | return App{}, err |
| 255 | } |
| 256 | var reply App |
| 257 | _, err = a.request(ctx, "GET", "/app", jwt, nil, &reply) |
| 258 | if err != nil { |
| 259 | return App{}, err |
| 260 | } |
| 261 | if !validApp(reply) || reply.ID != app.ID || reply.Owner.ID != app.Owner.ID || reply.Owner.Type != app.Owner.Type { |
| 262 | return App{}, ErrAccess |
| 263 | } |
| 264 | reply.pem, reply.generation = app.pem, app.generation |
| 265 | return reply, nil |
| 266 | } |
| 267 | func (a *API) Installations(ctx context.Context, app App) ([]Installation, error) { |
| 268 | jwt, err := a.jwt(app) |
| 269 | if err != nil { |
| 270 | return nil, err |
| 271 | } |
| 272 | var all []Installation |
| 273 | for page := 1; page <= 10; page++ { |
| 274 | var rows []Installation |
| 275 | headers, err := a.request(ctx, "GET", fmt.Sprintf("/app/installations?per_page=100&page=%d", page), jwt, nil, &rows) |
| 276 | if err != nil { |
| 277 | return nil, err |
| 278 | } |
| 279 | if len(rows) > 100 { |
| 280 | return nil, ErrUnavailable |
| 281 | } |
| 282 | all = append(all, rows...) |
| 283 | more, err := nextPage(headers, "/app/installations", page) |
| 284 | if err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | if !more { |
| 288 | return all, nil |
| 289 | } |
| 290 | } |
| 291 | return nil, ErrUnavailable |
| 292 | } |
| 293 | func (a *API) Installation(ctx context.Context, app App, id int64) (Installation, error) { |
| 294 | if id <= 0 { |
| 295 | return Installation{}, ErrAccess |
| 296 | } |
| 297 | jwt, err := a.jwt(app) |
| 298 | if err != nil { |
| 299 | return Installation{}, err |
| 300 | } |
| 301 | var reply Installation |
| 302 | _, err = a.request(ctx, "GET", fmt.Sprintf("/app/installations/%d", id), jwt, nil, &reply) |
| 303 | if err != nil { |
| 304 | return Installation{}, err |
| 305 | } |
| 306 | if reply.ID != id || reply.AppID != app.ID || reply.Account.ID != app.Owner.ID || !ValidAccount(reply.Account.Login, reply.Account.Type) || reply.Account.Type != app.Owner.Type || !maps.Equal(reply.Permissions, permissions()) || reply.Events == nil || len(reply.Events) != 0 || (reply.Selection != "selected" && reply.Selection != "all") { |
| 307 | return Installation{}, ErrAccess |
| 308 | } |
| 309 | return reply, nil |
| 310 | } |
| 311 | func nextPage(headers http.Header, path string, page int) (bool, error) { |
| 312 | more := false |
| 313 | for _, part := range strings.Split(headers.Get("Link"), ",") { |
| 314 | part = strings.TrimSpace(part) |
| 315 | if part == "" { |
| 316 | continue |
| 317 | } |
| 318 | fields := strings.SplitN(part, ";", 2) |
| 319 | if len(fields) != 2 { |
| 320 | return false, ErrUnavailable |
| 321 | } |
| 322 | u, err := url.Parse(strings.Trim(fields[0], "<> ")) |
| 323 | if err != nil || u.Scheme != "https" || u.Host != "api.github.com" || u.User != nil || u.Path != path || u.Fragment != "" { |
| 324 | return false, ErrUnavailable |
| 325 | } |
| 326 | if strings.Contains(fields[1], `rel="next"`) { |
| 327 | if more || u.Query().Get("page") != strconv.Itoa(page+1) || u.Query().Get("per_page") != "100" { |
| 328 | return false, ErrUnavailable |
| 329 | } |
| 330 | more = true |
| 331 | } |
| 332 | } |
| 333 | return more, nil |
| 334 | } |
| 335 | func (a *API) metadata(ctx context.Context, app App, inst Installation) (string, error) { |
| 336 | // The mutex guards only the cache; no network call runs while it is held. |
| 337 | a.mu.Lock() |
| 338 | old := a.tokens[app.ID] |
| 339 | if old.value != "" && old.installation == inst.ID && old.selection == inst.Selection && a.now().Add(30*time.Second).Before(old.expires) { |
| 340 | a.mu.Unlock() |
| 341 | return old.value, nil |
| 342 | } |
| 343 | delete(a.tokens, app.ID) |
| 344 | epoch := a.epochs[app.ID] |
| 345 | a.mu.Unlock() |
| 346 | if old.value != "" { |
| 347 | _, _ = a.request(ctx, "DELETE", "/installation/token", old.value, nil, nil) |
| 348 | } |
| 349 | jwt, err := a.jwt(app) |
| 350 | if err != nil { |
| 351 | return "", err |
| 352 | } |
| 353 | var reply struct { |
| 354 | Token string `json:"token"` |
| 355 | Expires time.Time `json:"expires_at"` |
| 356 | Permissions map[string]string `json:"permissions"` |
| 357 | Selection string `json:"repository_selection"` |
| 358 | } |
| 359 | _, err = a.request(ctx, "POST", fmt.Sprintf("/app/installations/%d/access_tokens", inst.ID), jwt, map[string]any{"permissions": map[string]string{"metadata": "read"}}, &reply) |
| 360 | if err != nil { |
| 361 | return "", err |
| 362 | } |
| 363 | if reply.Token == "" || strings.ContainsAny(reply.Token, "\r\n\x00 ") || !maps.Equal(reply.Permissions, map[string]string{"metadata": "read"}) || !a.now().Add(30*time.Second).Before(reply.Expires) || reply.Expires.After(a.now().Add(time.Hour)) || reply.Selection != inst.Selection { |
| 364 | if reply.Token != "" && !strings.ContainsAny(reply.Token, "\r\n\x00 ") { |
| 365 | _, _ = a.request(ctx, "DELETE", "/installation/token", reply.Token, nil, nil) |
| 366 | } |
| 367 | return "", ErrAccess |
| 368 | } |
| 369 | a.mu.Lock() |
| 370 | if a.epochs[app.ID] != epoch { |
| 371 | a.mu.Unlock() |
| 372 | _, _ = a.request(ctx, "DELETE", "/installation/token", reply.Token, nil, nil) |
| 373 | return "", ErrAccess |
| 374 | } |
| 375 | displaced := a.tokens[app.ID] |
| 376 | a.tokens[app.ID] = metadataCredential{value: reply.Token, expires: reply.Expires, installation: inst.ID, selection: inst.Selection, pages: map[int]inventoryPage{}, generation: app.generation} |
| 377 | a.mu.Unlock() |
| 378 | if displaced.value != "" && displaced.value != reply.Token { |
| 379 | _, _ = a.request(ctx, "DELETE", "/installation/token", displaced.value, nil, nil) |
| 380 | } |
| 381 | return reply.Token, nil |
| 382 | } |
| 383 | func (a *API) Inventory(ctx context.Context, app App, inst Installation) (Inventory, error) { |
| 384 | if inst.ID <= 0 || inst.AppID != app.ID || inst.Account.ID != app.Owner.ID || inst.Suspended != nil { |
| 385 | return Inventory{}, ErrAccess |
| 386 | } |
| 387 | token, err := a.metadata(ctx, app, inst) |
| 388 | if err != nil { |
| 389 | return Inventory{}, err |
| 390 | } |
| 391 | all := []Repository{} |
| 392 | seen := map[int64]bool{} |
| 393 | total := -1 |
| 394 | for page := 1; page <= 11; page++ { |
| 395 | var reply inventoryReply |
| 396 | cached := a.cachedPage(app, token, page) |
| 397 | headers, err := a.request(ctx, "GET", fmt.Sprintf("/installation/repositories?per_page=100&page=%d", page), token, nil, &reply, cached.etag) |
| 398 | if errors.Is(err, errNotModified) { |
| 399 | if cached.etag == "" { |
| 400 | return Inventory{}, ErrUnavailable |
| 401 | } |
| 402 | reply = cached.reply |
| 403 | headers = cached.headers |
| 404 | err = nil |
| 405 | } |
| 406 | if err != nil { |
| 407 | return Inventory{}, err |
| 408 | } |
| 409 | if reply.Total == nil || reply.Rows == nil { |
| 410 | return Inventory{}, ErrUnavailable |
| 411 | } |
| 412 | if *reply.Total > MaxRepositories || len(all)+len(reply.Rows) > MaxRepositories { |
| 413 | return Inventory{}, ErrTooMany |
| 414 | } |
| 415 | if *reply.Total < 0 || len(reply.Rows) > 100 || (total >= 0 && *reply.Total != total) { |
| 416 | return Inventory{}, ErrUnavailable |
| 417 | } |
| 418 | total = *reply.Total |
| 419 | for _, r := range reply.Rows { |
| 420 | parts := strings.Split(r.Name, "/") |
| 421 | if r.ID <= 0 || seen[r.ID] || r.Owner.ID != app.Owner.ID || len(parts) != 2 || !strings.EqualFold(parts[0], r.Owner.Login) || parts[1] == "" || strings.ContainsAny(r.Name, "\r\n\x00 ?#") { |
| 422 | return Inventory{}, ErrAccess |
| 423 | } |
| 424 | seen[r.ID] = true |
| 425 | all = append(all, r) |
| 426 | } |
| 427 | a.cachePage(app, token, page, inventoryPage{headers.Get("ETag"), reply, headers.Clone()}) |
| 428 | more, err := nextPage(headers, "/installation/repositories", page) |
| 429 | if err != nil { |
| 430 | return Inventory{}, err |
| 431 | } |
| 432 | if !more { |
| 433 | if len(all) != total { |
| 434 | return Inventory{}, ErrUnavailable |
| 435 | } |
| 436 | return Inventory{all, total}, nil |
| 437 | } |
| 438 | } |
| 439 | return Inventory{}, ErrTooMany |
| 440 | } |
| 441 | func (a *API) Forget(ctx context.Context, id int64) { |
| 442 | a.mu.Lock() |
| 443 | entry := a.tokens[id] |
| 444 | delete(a.tokens, id) |
| 445 | a.epochs[id]++ |
| 446 | a.mu.Unlock() |
| 447 | if entry.value != "" { |
| 448 | _, _ = a.request(ctx, "DELETE", "/installation/token", entry.value, nil, nil) |
| 449 | } |
| 450 | } |
| 451 | |