package forge import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" ) // ErrCIRead means the hub's CI answer could not be read: a refused or // failed request, a redirect, an oversized or unreadable body. Callers // treat it as "not known", never as a verdict. var ErrCIRead = errors.New("forge: the hub's CI answer could not be read") // CI status logs modes the hub knows: none for a poll, failed for the // logs of the units that failed. const ( CILogsNone = "none" CILogsFailed = "failed" ) // CIStatus is the hub's verdict on a branch's tip, as GET /api/v1/repos/ // {ns}/{repo}/ci/status?branch= reports it (amadan discussion #8): the tip // it judged, the run's state, when the hub recorded it, its one-line // summary of what failed, and the workflow's steps and shards. type CIStatus struct { NS string `json:"ns"` Repo string `json:"repo"` Branch string `json:"branch"` SHA string `json:"sha"` State string `json:"state"` Summary string `json:"summary"` UpdatedAt int64 `json:"updated_at"` Log string `json:"log"` Steps []CIStep `json:"steps"` } // CIStep is one step of a run, with its shards when it is sharded. type CIStep struct { Name string `json:"name"` State string `json:"state"` Log string `json:"log"` Shards []CIShard `json:"shards"` } // CIShard is one shard of a sharded step. type CIShard struct { Name string `json:"name"` State string `json:"state"` Log string `json:"log"` } // Read caps: the hosted answer is a handful of fields; a status with the // failing units' logs is bounded by the hub's own log budget. const ( maxCIHostedBody = 64 << 10 maxCIStatusBody = 4 << 20 ) // HubCIHosted asks the hub whether it runs repo's CI on its own machines // (GET /api/v1/repos/{ns}/{repo}/ci/hosted, any member). func HubCIHosted(ctx context.Context, client *http.Client, hub string, cred Credential, repo string) (bool, error) { var out struct { On *bool `json:"on"` } if err := ciGet(ctx, client, hub, cred, repo, "/ci/hosted", nil, maxCIHostedBody, &out); err != nil { return false, err } if out.On == nil { return false, ErrCIRead } return *out.On, nil } // HubCIStatus reads the hub's CI verdict on branch's tip, with logs // (CILogsNone or CILogsFailed). func HubCIStatus(ctx context.Context, client *http.Client, hub string, cred Credential, repo, branch, logs string) (CIStatus, error) { if !validRef(branch) || logs != CILogsNone && logs != CILogsFailed { return CIStatus{}, ErrCIRead } var out CIStatus if err := ciGet(ctx, client, hub, cred, repo, "/ci/status", url.Values{"branch": {branch}, "logs": {logs}}, maxCIStatusBody, &out); err != nil { return CIStatus{}, err } // The answer must be about exactly what was asked. parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") if out.NS != parts[0] || out.Repo != parts[1] || out.Branch != branch || out.State == "" || out.SHA != "" && !object.MatchString(out.SHA) { return CIStatus{}, ErrCIRead } return out, nil } func ciGet(ctx context.Context, client *http.Client, hub string, cred Credential, repo, suffix string, q url.Values, limit int64, out any) error { if !validRepository(repo) || cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { return ErrCIRead } parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") endpoint := strings.TrimRight(hub, "/") + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + suffix if len(q) > 0 { endpoint += "?" + q.Encode() } req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return ErrCIRead } req.Header.Set("Authorization", "Bearer "+cred.Bearer) req.Header.Set("Accept", "application/json") // The bearer goes to the hub only: a redirect is refused, not followed. c := *client c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } res, err := c.Do(req) if err != nil { return fmt.Errorf("%w: %v", ErrCIRead, err) } defer res.Body.Close() if res.StatusCode != http.StatusOK { return fmt.Errorf("%w: status %d", ErrCIRead, res.StatusCode) } raw, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) if err != nil || int64(len(raw)) > limit || json.Unmarshal(raw, out) != nil { return ErrCIRead } return nil }