diff --git a/internal/document.go b/internal/document.go new file mode 100644 index 0000000..6043de8 --- /dev/null +++ b/internal/document.go @@ -0,0 +1,143 @@ +package internal + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" +) + +// Transitions of an effect (wire-interface.md, "The effect document"). +const ( + TransitionActivated = "activated" + TransitionUpdated = "updated" + TransitionRepeated = "repeated" + TransitionFinished = "finished" + TransitionRedelivered = "redelivered" + TransitionCleared = "cleared" + TransitionDisabled = "disabled" + TransitionRemoved = "removed" + TransitionOccurred = "occurred" +) + +// States of an effect. +const ( + StateActive = "active" + StateFinished = "finished" + StateInactive = "inactive" +) + +// Effect is the part of the effect document (EffectRequest.effect_document) the plugin +// reads: the target, the transition, and the subjects that explain why it is active. +type Effect struct { + ID string `json:"id"` + Generation uint64 `json:"generation"` + Transition string `json:"transition"` + State string `json:"state"` + Rule Rule `json:"rule"` + Action Action `json:"action"` + Target Target `json:"target"` + Trigger Trigger `json:"trigger"` + Applied *Applied `json:"applied,omitempty"` +} + +// Rule is the rule that produced the effect. +type Rule struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` +} + +// Action is the rule action and the effector action it runs. +type Action struct { + RuleActionID string `json:"rule-action-id"` + EffectorAction string `json:"effector-action"` + Effect string `json:"effect"` +} + +// Target is the effect's target identity, split into scheme and value. +type Target struct { + Identity string `json:"identity"` + Scheme string `json:"scheme"` + Value string `json:"value"` +} + +// Trigger is what caused the effect. +type Trigger struct { + Source string `json:"source"` + Subjects []Subject `json:"subjects"` +} + +// Subject is one subject (an evidence stream) in the effect. +type Subject struct { + ID string `json:"id"` + Title string `json:"title"` + URL string `json:"url,omitempty"` +} + +// Applied is what the agent last reported for the effect. +type Applied struct { + Generation uint64 `json:"generation"` + Status string `json:"status"` + Refs map[string]any `json:"refs,omitempty"` +} + +// ParseEffect decodes an effect document. It accepts the effect object itself and, for +// robustness, a whole webhook body ({"type": ..., "effect": {...}}). +func ParseEffect(raw []byte) (*Effect, error) { + if len(raw) == 0 { + return nil, errors.New("empty effect document") + } + var wrapper struct { + Effect json.RawMessage `json:"effect"` + } + if err := json.Unmarshal(raw, &wrapper); err == nil && len(wrapper.Effect) > 0 && wrapper.Effect[0] == '{' { + raw = wrapper.Effect + } + var eff Effect + if err := json.Unmarshal(raw, &eff); err != nil { + return nil, fmt.Errorf("decode effect document: %w", err) + } + if eff.ID == "" { + return nil, errors.New("effect document has no id") + } + return &eff, nil +} + +// Target scheme of a repository. +const ( + SchemeRepo = "github-repo" + repoValuePattern = `^github\.com/[A-Za-z0-9-]+/[A-Za-z0-9._-]+$` + repoExample = "github-repo:github.com/acme/repo-1" + repoSchemeSummary = "A GitHub repository, as github.com//" +) + +var repoValueRE = regexp.MustCompile(repoValuePattern) + +// Repo is a repository named by a target. +type Repo struct { + Owner, Name string +} + +// FullName is owner/name. +func (r Repo) FullName() string { return r.Owner + "/" + r.Name } + +// ParseTarget returns the repository a github-repo target names. +func ParseTarget(t Target) (Repo, error) { + scheme, value := t.Scheme, t.Value + if scheme == "" || value == "" { + scheme, value, _ = strings.Cut(t.Identity, ":") + } + if scheme != SchemeRepo { + return Repo{}, fmt.Errorf("unsupported target scheme %q (only %s)", scheme, SchemeRepo) + } + if !repoValueRE.MatchString(value) { + return Repo{}, fmt.Errorf("target %s:%s doesn't match %s", scheme, value, repoValuePattern) + } + parts := strings.SplitN(value, "/", 3) + if parts[2] == "." || parts[2] == ".." { + return Repo{}, fmt.Errorf("target %s:%s isn't a repository name", scheme, value) + } + return Repo{Owner: parts[1], Name: parts[2]}, nil +} diff --git a/internal/document_test.go b/internal/document_test.go new file mode 100644 index 0000000..2b33698 --- /dev/null +++ b/internal/document_test.go @@ -0,0 +1,74 @@ +package internal + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const effectDoc = `{ + "id": "eff_7f3c", "generation": 3, "transition": "repeated", "state": "active", + "rule": {"id": "rul_19a2", "name": "No direct collaborators", "kind": "state"}, + "action": {"rule-action-id": "act_55d1", "effector-action": "fix-github-repo", "effect": "remediate-apply"}, + "target": {"identity": "github-repo:github.com/acme/repo-1", "scheme": "github-repo", "value": "github.com/acme/repo-1"}, + "trigger": {"source": "evidence", "subjects": [{"id": "sub_1", "title": "repository_team_access"}]}, + "applied": {"generation": 2, "status": "applied", "refs": {"last_applied": "2026-12-01T10:00:00Z"}} +}` + +func TestParseEffect(t *testing.T) { + for name, raw := range map[string]string{ + "effect": effectDoc, + "webhook body": `{"type": "effect.repeated", "effect": ` + effectDoc + `}`, + } { + eff, err := ParseEffect([]byte(raw)) + require.NoError(t, err, name) + assert.Equal(t, "eff_7f3c", eff.ID, name) + assert.Equal(t, uint64(3), eff.Generation, name) + assert.Equal(t, TransitionRepeated, eff.Transition, name) + assert.Equal(t, StateActive, eff.State, name) + assert.Equal(t, "fix-github-repo", eff.Action.EffectorAction, name) + assert.Equal(t, "github.com/acme/repo-1", eff.Target.Value, name) + require.Len(t, eff.Trigger.Subjects, 1, name) + require.NotNil(t, eff.Applied, name) + assert.Equal(t, "2026-12-01T10:00:00Z", eff.Applied.Refs["last_applied"], name) + } + + for name, raw := range map[string]string{ + "empty": ``, + "invalid": `{`, + "no id": `{"transition": "activated"}`, + } { + _, err := ParseEffect([]byte(raw)) + assert.Error(t, err, name) + } +} + +func TestParseTarget(t *testing.T) { + for name, tc := range map[string]struct { + target Target + want Repo + }{ + "split": {Target{Scheme: SchemeRepo, Value: "github.com/acme/repo-1"}, Repo{"acme", "repo-1"}}, + "identity only": {Target{Identity: "github-repo:github.com/Acme-2/my.repo_x"}, Repo{"Acme-2", "my.repo_x"}}, + } { + got, err := ParseTarget(tc.target) + require.NoError(t, err, name) + assert.Equal(t, tc.want, got, name) + } + assert.Equal(t, "acme/repo-1", Repo{"acme", "repo-1"}.FullName()) + + for identity, want := range map[string]string{ + "slack-channel:#alerts": `unsupported target scheme "slack-channel"`, + "github-repo:gitlab.com/acme/x": "doesn't match", + "github-repo:github.com/acme": "doesn't match", + "github-repo:github.com/a/b/c": "doesn't match", + "github-repo:github.com/acme/..": "isn't a repository name", + "github-repo:github.com/acme/.": "isn't a repository name", + "no-scheme": "unsupported target scheme", + } { + _, err := ParseTarget(Target{Identity: identity}) + require.Error(t, err, identity) + assert.Contains(t, err.Error(), want, identity) + } +} diff --git a/internal/fakegithub_test.go b/internal/fakegithub_test.go new file mode 100644 index 0000000..7706387 --- /dev/null +++ b/internal/fakegithub_test.go @@ -0,0 +1,252 @@ +package internal + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" +) + +const testToken = "ghs_test-token-not-real" + +// fakeGitHub is a GitHub REST API on httptest: repositories with direct collaborators, +// pending invitations and the web commit signoff setting. It records every call and can fail +// chosen calls. +type fakeGitHub struct { + t *testing.T + server *httptest.Server + + mu sync.Mutex + repos map[string]*fakeRepo // "owner/name" + calls []string // "METHOD /path?query" + fail map[string]fakeError // "METHOD /path" -> error response + pageSize int // items per page served (GitHub's is per_page, up to 100) + // keepSignoff makes PATCH ignore web_commit_signoff_required (an org policy enforcing it). + keepSignoff bool + // nextHost, when set, is the host put in Link next URLs (to test off-host links). + nextHost string + // moved redirects a renamed or transferred repository ("owner/name") to its new full name, + // as GitHub does: 301 for GET, 307 for other methods. + moved map[string]string +} + +type fakeError struct { + status int + message string +} + +type fakeRepo struct { + owner string + fullName string // full_name answered, when not the name it is served under + signoff bool + collaborators []string + invitations []fakeInvitation +} + +type fakeInvitation struct { + id int64 + login string // "" for an email invitation + email string +} + +func newFakeGitHub(t *testing.T) *fakeGitHub { + t.Helper() + f := &fakeGitHub{t: t, repos: map[string]*fakeRepo{}, fail: map[string]fakeError{}, pageSize: 100, moved: map[string]string{}} + f.server = httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(f.server.Close) + return f +} + +func (f *fakeGitHub) url() string { return f.server.URL } + +func (f *fakeGitHub) addRepo(fullName string, r *fakeRepo) *fakeRepo { + f.mu.Lock() + defer f.mu.Unlock() + if r.owner == "" { + r.owner, _, _ = strings.Cut(fullName, "/") + } + f.repos[fullName] = r + return r +} + +func (f *fakeGitHub) failOn(call string, status int, message string) { + f.mu.Lock() + defer f.mu.Unlock() + f.fail[call] = fakeError{status, message} +} + +func (f *fakeGitHub) repo(fullName string) fakeRepo { + f.mu.Lock() + defer f.mu.Unlock() + r := *f.repos[fullName] + r.collaborators = append([]string(nil), r.collaborators...) + r.invitations = append([]fakeInvitation(nil), r.invitations...) + return r +} + +// recorded returns the calls made, without query strings. +func (f *fakeGitHub) recorded() []string { + f.mu.Lock() + defer f.mu.Unlock() + out := make([]string, len(f.calls)) + for i, c := range f.calls { + out[i], _, _ = strings.Cut(c, "?") + } + return out +} + +// writes returns the PATCH and DELETE calls made. +func (f *fakeGitHub) writes() []string { + var out []string + for _, c := range f.recorded() { + if !strings.HasPrefix(c, http.MethodGet+" ") { + out = append(out, c) + } + } + return out +} + +func (f *fakeGitHub) serve(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + call := r.Method + " " + r.URL.Path + f.calls = append(f.calls, call+"?"+r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + if r.Header.Get("Authorization") != "Bearer "+testToken { + f.write(w, http.StatusUnauthorized, map[string]any{"message": "Bad credentials"}) + return + } + if r.Header.Get("Accept") != "application/vnd.github+json" || r.Header.Get("X-GitHub-Api-Version") != "2022-11-28" { + f.write(w, http.StatusBadRequest, map[string]any{"message": "missing GitHub headers"}) + return + } + if e, ok := f.fail[call]; ok { + f.write(w, e.status, map[string]any{"message": e.message, "documentation_url": "https://docs.github.com/rest"}) + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") + if len(parts) < 3 || parts[0] != "repos" { + f.write(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) + return + } + if to, ok := f.moved[parts[1]+"/"+parts[2]]; ok { + status := http.StatusTemporaryRedirect + if r.Method == http.MethodGet { + status = http.StatusMovedPermanently + } + w.Header().Set("Location", "http://"+r.Host+"/"+strings.Join(append([]string{"repos", to}, parts[3:]...), "/")) + f.write(w, status, map[string]any{"message": "Moved Permanently"}) + return + } + repo, ok := f.repos[parts[1]+"/"+parts[2]] + if !ok { + f.write(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) + return + } + full := parts[1] + "/" + parts[2] + rest := parts[3:] + switch { + case len(rest) == 0 && r.Method == http.MethodGet: + f.write(w, http.StatusOK, f.repoJSON(full, repo)) + case len(rest) == 0 && r.Method == http.MethodPatch: + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + f.write(w, http.StatusBadRequest, map[string]any{"message": "Problems parsing JSON"}) + return + } + if v, ok := body["web_commit_signoff_required"].(bool); ok && !f.keepSignoff { + repo.signoff = v + } + f.write(w, http.StatusOK, f.repoJSON(full, repo)) + case len(rest) == 1 && rest[0] == "collaborators" && r.Method == http.MethodGet: + if r.URL.Query().Get("affiliation") != "direct" { + f.write(w, http.StatusBadRequest, map[string]any{"message": "expected affiliation=direct"}) + return + } + items := make([]any, 0, len(repo.collaborators)) + for _, c := range repo.collaborators { + items = append(items, map[string]any{"login": c, "type": "User"}) + } + f.page(w, r, items) + case len(rest) == 2 && rest[0] == "collaborators" && r.Method == http.MethodDelete: + for i, c := range repo.collaborators { + if c == rest[1] { + repo.collaborators = append(repo.collaborators[:i], repo.collaborators[i+1:]...) + w.WriteHeader(http.StatusNoContent) + return + } + } + w.WriteHeader(http.StatusNoContent) // GitHub answers 204 for a non-collaborator too + case len(rest) == 1 && rest[0] == "invitations" && r.Method == http.MethodGet: + items := make([]any, 0, len(repo.invitations)) + for _, inv := range repo.invitations { + m := map[string]any{"id": inv.id, "permissions": "write"} + if inv.login != "" { + m["invitee"] = map[string]any{"login": inv.login} + } else { + m["invitee"] = nil + m["email"] = inv.email + } + items = append(items, m) + } + f.page(w, r, items) + case len(rest) == 2 && rest[0] == "invitations" && r.Method == http.MethodDelete: + id, _ := strconv.ParseInt(rest[1], 10, 64) + for i, inv := range repo.invitations { + if inv.id == id { + repo.invitations = append(repo.invitations[:i], repo.invitations[i+1:]...) + w.WriteHeader(http.StatusNoContent) + return + } + } + f.write(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) + default: + f.write(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) + } +} + +func (f *fakeGitHub) repoJSON(full string, r *fakeRepo) map[string]any { + if r.fullName != "" { + full = r.fullName + } + return map[string]any{ + "full_name": full, + "html_url": "https://github.com/" + full, + "web_commit_signoff_required": r.signoff, + "owner": map[string]any{"login": r.owner}, + } +} + +// page serves items with GitHub's pagination: page and per_page, and a Link header. +func (f *fakeGitHub) page(w http.ResponseWriter, r *http.Request, items []any) { + q := r.URL.Query() + size, _ := strconv.Atoi(q.Get("per_page")) + if size <= 0 || size > f.pageSize { + size = f.pageSize + } + page, _ := strconv.Atoi(q.Get("page")) + if page < 1 { + page = 1 + } + start := min((page-1)*size, len(items)) + end := min(start+size, len(items)) + if end < len(items) { + q.Set("page", strconv.Itoa(page+1)) + host := r.Host + if f.nextHost != "" { + host = f.nextHost + } + next := fmt.Sprintf("http://%s%s?%s", host, r.URL.Path, q.Encode()) + w.Header().Set("Link", fmt.Sprintf(`<%s>; rel="next", ; rel="last"`, next, host, r.URL.Path)) + } + f.write(w, http.StatusOK, items[start:end]) +} + +func (f *fakeGitHub) write(w http.ResponseWriter, status int, body any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} diff --git a/internal/github.go b/internal/github.go new file mode 100644 index 0000000..fa02694 --- /dev/null +++ b/internal/github.go @@ -0,0 +1,319 @@ +package internal + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + perPage = 100 + maxPages = 100 // 10,000 items: more than any repository's direct collaborators + maxErrorBody = 64 << 10 + maxErrorMessage = 300 + requestTimeout = 30 * time.Second + githubAPIVer = "2022-11-28" + githubMediaType = "application/vnd.github+json" +) + +// githubClient is a small GitHub REST client: the few calls the plugin makes, over net/http. +// The token goes only to the configured API host and is never logged or put in an error. +type githubClient struct { + base *url.URL // ends with "/" + token string + http *http.Client +} + +func newGitHubClient(cfg *PluginConfig) (*githubClient, error) { + base, err := url.Parse(cfg.APIURL) + if err != nil { + return nil, fmt.Errorf("api_url: %w", err) + } + // Redirects are never followed: GitHub redirects a renamed or transferred repository's + // calls (301 GET, 307 PATCH/DELETE) to its new location, which the action's targets + // don't allow. send fails on them instead. + noRedirect := func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &githubClient{base: base, token: cfg.Token, http: &http.Client{Timeout: requestTimeout, CheckRedirect: noRedirect}}, nil +} + +// apiError is a failed GitHub call: the call and GitHub's message. +type apiError struct { + Method, Path string + Status int + Message string +} + +func (e *apiError) Error() string { + if e.Status == 0 { // no response: a transport error, or a check before or after the call + return fmt.Sprintf("%s %s: %s", e.Method, e.Path, e.Message) + } + return fmt.Sprintf("%s %s: %d %s", e.Method, e.Path, e.Status, e.Message) +} + +// repository is the part of GET /repos/{owner}/{repo} the plugin reads. +type repository struct { + FullName string `json:"full_name"` + HTMLURL string `json:"html_url"` + WebCommitSignoffRequired bool `json:"web_commit_signoff_required"` + Owner struct { + Login string `json:"login"` + } `json:"owner"` +} + +type user struct { + Login string `json:"login"` +} + +// invitation is a pending repository invitation. +type invitation struct { + ID int64 `json:"id"` + Invitee *user `json:"invitee"` + Email string `json:"email,omitempty"` +} + +// login is the invitee's login, or "" (an invitation by email). +func (i invitation) login() string { + if i.Invitee == nil { + return "" + } + return i.Invitee.Login +} + +func repoPath(r Repo, rest ...string) string { + parts := append([]string{"repos", r.Owner, r.Name}, rest...) + return "/" + strings.Join(parts, "/") +} + +func (c *githubClient) getRepository(ctx context.Context, r Repo) (*repository, error) { + var out repository + if err := c.do(ctx, http.MethodGet, repoPath(r), nil, nil, &out); err != nil { + return nil, err + } + if err := sameRepository(http.MethodGet, r, &out); err != nil { + return nil, err + } + return &out, nil +} + +func (c *githubClient) setWebCommitSignoff(ctx context.Context, r Repo, required bool) (*repository, error) { + var out repository + body := map[string]bool{"web_commit_signoff_required": required} + if err := c.do(ctx, http.MethodPatch, repoPath(r), nil, body, &out); err != nil { + return nil, err + } + if err := sameRepository(http.MethodPatch, r, &out); err != nil { + return nil, err + } + return &out, nil +} + +// sameRepository fails when GitHub answered for another repository than the target r (its +// full_name differs, ignoring case), so nothing is planned for a repository the action's +// targets don't name. +func sameRepository(method string, r Repo, got *repository) error { + if strings.EqualFold(got.FullName, r.Owner+"/"+r.Name) { + return nil + } + return &apiError{Method: method, Path: repoPath(r), Message: fmt.Sprintf("GitHub answered for repository %q (renamed or transferred?): update the target", got.FullName)} +} + +func (c *githubClient) listDirectCollaborators(ctx context.Context, r Repo) ([]user, error) { + return listAll[user](ctx, c, repoPath(r, "collaborators"), url.Values{"affiliation": {"direct"}}) +} + +func (c *githubClient) removeCollaborator(ctx context.Context, r Repo, login string) error { + return c.do(ctx, http.MethodDelete, repoPath(r, "collaborators", login), nil, nil, nil) +} + +func (c *githubClient) listInvitations(ctx context.Context, r Repo) ([]invitation, error) { + return listAll[invitation](ctx, c, repoPath(r, "invitations"), nil) +} + +func (c *githubClient) deleteInvitation(ctx context.Context, r Repo, id int64) error { + return c.do(ctx, http.MethodDelete, repoPath(r, "invitations", fmt.Sprint(id)), nil, nil, nil) +} + +// listAll pages through a list endpoint (per_page=100), following the Link header's next +// URL as long as it stays on the API host. +func listAll[T any](ctx context.Context, c *githubClient, path string, query url.Values) ([]T, error) { + q := url.Values{} + for k, v := range query { + q[k] = v + } + q.Set("per_page", fmt.Sprint(perPage)) + next := c.resolve(path, q) + var out []T + for page := 0; next != nil; page++ { + if page == maxPages { + return nil, &apiError{Method: http.MethodGet, Path: path, Message: fmt.Sprintf("more than %d pages", maxPages)} + } + var items []T + header, err := c.send(ctx, http.MethodGet, next, path, nil, &items) + if err != nil { + return nil, err + } + out = append(out, items...) + next = nil + if link := nextLink(header.Get("Link")); link != "" { + u, err := sameHostURL(c.base, link) + if err != nil { + return nil, &apiError{Method: http.MethodGet, Path: path, Message: err.Error()} + } + next = u + } + } + return out, nil +} + +// sameHostURL parses a Link next URL and checks it stays on the API's scheme and host, so the +// token is never sent elsewhere. +func sameHostURL(base *url.URL, link string) (*url.URL, error) { + u, err := base.Parse(link) + if err != nil { + return nil, fmt.Errorf("bad Link next URL: %w", err) + } + if u.Scheme != base.Scheme || u.Host != base.Host { + return nil, fmt.Errorf("refusing to follow a Link next URL off the API host (%s)", u.Host) + } + return u, nil +} + +// nextLink returns the rel="next" URL of a Link header, or "". +func nextLink(header string) string { + for _, part := range strings.Split(header, ",") { + segs := strings.Split(part, ";") + if len(segs) < 2 { + continue + } + target := strings.TrimSpace(segs[0]) + if !strings.HasPrefix(target, "<") || !strings.HasSuffix(target, ">") { + continue + } + for _, attr := range segs[1:] { + k, v, ok := strings.Cut(strings.TrimSpace(attr), "=") + if !ok || strings.TrimSpace(k) != "rel" { + continue + } + for _, rel := range strings.Fields(strings.Trim(strings.TrimSpace(v), `"`)) { + if rel == "next" { + return target[1 : len(target)-1] + } + } + } + } + return "" +} + +// resolve builds the URL of an API path (starting with "/") under the base URL. Path +// segments are owners, repository names, logins and IDs, which need no escaping. +func (c *githubClient) resolve(path string, query url.Values) *url.URL { + u := *c.base + u.Path = strings.TrimSuffix(c.base.Path, "/") + path + u.RawPath = "" + u.RawQuery = query.Encode() + return &u +} + +func (c *githubClient) do(ctx context.Context, method, path string, query url.Values, body, out any) error { + _, err := c.send(ctx, method, c.resolve(path, query), path, body, out) + return err +} + +// send makes one call and returns the response headers; it closes the body itself. path is the +// API path shown in errors. +func (c *githubClient) send(ctx context.Context, method string, u *url.URL, path string, body, out any) (http.Header, error) { + var rd io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + return nil, err + } + rd = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, u.String(), rd) + if err != nil { + return nil, &apiError{Method: method, Path: path, Message: err.Error()} + } + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Accept", githubMediaType) + req.Header.Set("X-GitHub-Api-Version", githubAPIVer) + req.Header.Set("User-Agent", "ccf-effector-github-settings/"+Version) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + return nil, &apiError{Method: method, Path: path, Message: transportMessage(err)} + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode >= 300 && resp.StatusCode <= 399 { + msg := fmt.Sprintf("repository moved to %s (renamed or transferred): redirects aren't followed, update the target", resp.Header.Get("Location")) + return nil, &apiError{Method: method, Path: path, Status: resp.StatusCode, Message: truncateMessage(msg)} + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return nil, &apiError{Method: method, Path: path, Status: resp.StatusCode, Message: githubMessage(resp)} + } + if out != nil && resp.StatusCode != http.StatusNoContent { + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + return nil, &apiError{Method: method, Path: path, Status: resp.StatusCode, Message: "decode response: " + err.Error()} + } + } + return resp.Header, nil +} + +// transportMessage describes a transport error without the URL (which holds nothing +// secret, but is noise next to the call). +func transportMessage(err error) string { + var ue *url.Error + if errors.As(err, &ue) { + err = ue.Err + } + if errors.Is(err, context.DeadlineExceeded) { + return "timed out" + } + if errors.Is(err, context.Canceled) { + return "canceled" + } + return err.Error() +} + +// githubMessage is GitHub's error message ({"message": ...}), else the status text, with a +// rate limit's reset time when GitHub sends one. +func githubMessage(resp *http.Response) string { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody)) + var body struct { + Message string `json:"message"` + } + msg := "" + if json.Unmarshal(raw, &body) == nil { + msg = strings.TrimSpace(body.Message) + } + if msg == "" { + msg = http.StatusText(resp.StatusCode) + } + if resp.Header.Get("X-RateLimit-Remaining") == "0" { + if reset := resp.Header.Get("X-RateLimit-Reset"); reset != "" { + var sec int64 + if _, err := fmt.Sscan(reset, &sec); err == nil { + msg += " (rate limit resets at " + time.Unix(sec, 0).UTC().Format(time.RFC3339) + ")" + } + } + } + return truncateMessage(msg) +} + +// truncateMessage collapses whitespace and cuts msg to maxErrorMessage bytes. +func truncateMessage(msg string) string { + msg = strings.Join(strings.Fields(msg), " ") + if len(msg) > maxErrorMessage { + msg = msg[:maxErrorMessage] + "…" + } + return msg +} diff --git a/internal/github_test.go b/internal/github_test.go new file mode 100644 index 0000000..f336f78 --- /dev/null +++ b/internal/github_test.go @@ -0,0 +1,238 @@ +package internal + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var testRepo = Repo{Owner: "acme", Name: "repo-1"} + +func newTestClient(t *testing.T, apiURL, token string) *githubClient { + t.Helper() + cfg, err := ParsePluginConfig(map[string]any{"token": token, "api_url": apiURL}) + require.NoError(t, err) + c, err := newGitHubClient(cfg) + require.NoError(t, err) + return c +} + +func testCtx(t *testing.T) context.Context { + c, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + return c +} + +func TestClientReadsAndWrites(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{ + collaborators: []string{"acme", "alice", "bob"}, + invitations: []fakeInvitation{{id: 7, login: "dave"}, {id: 9, email: "eve@example.com"}}, + }) + c := newTestClient(t, f.url(), testToken) + ctx := testCtx(t) + + repo, err := c.getRepository(ctx, testRepo) + require.NoError(t, err, "the fake answers 400 without GitHub's Accept and API version headers") + assert.Equal(t, "acme/repo-1", repo.FullName) + assert.Equal(t, "acme", repo.Owner.Login) + assert.Equal(t, "https://github.com/acme/repo-1", repo.HTMLURL) + assert.False(t, repo.WebCommitSignoffRequired) + + users, err := c.listDirectCollaborators(ctx, testRepo) + require.NoError(t, err) + assert.Equal(t, []user{{"acme"}, {"alice"}, {"bob"}}, users) + + invs, err := c.listInvitations(ctx, testRepo) + require.NoError(t, err) + require.Len(t, invs, 2) + assert.Equal(t, "dave", invs[0].login()) + assert.Equal(t, "", invs[1].login(), "an email invitation has no invitee") + assert.Equal(t, "eve@example.com", invs[1].Email) + + require.NoError(t, c.removeCollaborator(ctx, testRepo, "bob")) + require.NoError(t, c.deleteInvitation(ctx, testRepo, 7)) + repo, err = c.setWebCommitSignoff(ctx, testRepo, true) + require.NoError(t, err) + assert.True(t, repo.WebCommitSignoffRequired) + + assert.Equal(t, []string{ + "DELETE /repos/acme/repo-1/collaborators/bob", + "DELETE /repos/acme/repo-1/invitations/7", + "PATCH /repos/acme/repo-1", + }, f.writes()) + after := f.repo("acme/repo-1") + assert.Equal(t, []string{"acme", "alice"}, after.collaborators) + assert.Equal(t, []fakeInvitation{{id: 9, email: "eve@example.com"}}, after.invitations) + assert.True(t, after.signoff) +} + +func TestClientPaginates(t *testing.T) { + f := newFakeGitHub(t) + var many []string + for i := range 250 { + many = append(many, fmt.Sprintf("user-%03d", i)) + } + f.addRepo("acme/repo-1", &fakeRepo{collaborators: many}) + c := newTestClient(t, f.url(), testToken) + + users, err := c.listDirectCollaborators(testCtx(t), testRepo) + require.NoError(t, err) + require.Len(t, users, 250) + assert.Equal(t, "user-249", users[249].Login) + + f.mu.Lock() + calls := append([]string(nil), f.calls...) + f.mu.Unlock() + require.Len(t, calls, 3, "100 per page") + for _, call := range calls { + assert.Contains(t, call, "per_page=100") + assert.Contains(t, call, "affiliation=direct") + } +} + +func TestClientPageCap(t *testing.T) { + f := newFakeGitHub(t) + var many []string + for i := range maxPages + 1 { + many = append(many, fmt.Sprintf("user-%d", i)) + } + f.addRepo("acme/repo-1", &fakeRepo{collaborators: many}) + f.pageSize = 1 + c := newTestClient(t, f.url(), testToken) + + _, err := c.listDirectCollaborators(testCtx(t), testRepo) + require.Error(t, err) + assert.Equal(t, fmt.Sprintf("GET /repos/acme/repo-1/collaborators: more than %d pages", maxPages), err.Error()) + assert.Len(t, f.recorded(), maxPages) +} + +func TestClientRefusesOffHostLinks(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{collaborators: []string{"a", "b", "c"}}) + f.pageSize = 2 + f.nextHost = "evil.example" + c := newTestClient(t, f.url(), testToken) + + _, err := c.listDirectCollaborators(testCtx(t), testRepo) + require.Error(t, err) + assert.Contains(t, err.Error(), "refusing to follow a Link next URL off the API host (evil.example)") + assert.Len(t, f.recorded(), 1, "the token never goes to the other host") +} + +// A renamed or transferred repository: GitHub redirects its calls (301 GET, 307 PATCH and +// DELETE) to the new location, outside the action's targets. Nothing follows them. +func TestClientRefusesRedirects(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("other-org/repo-1", &fakeRepo{collaborators: []string{"carol"}}) + f.moved["acme/repo-1"] = "other-org/repo-1" + c := newTestClient(t, f.url(), testToken) + ctx := testCtx(t) + + _, err := c.getRepository(ctx, testRepo) + assert.EqualError(t, err, "GET /repos/acme/repo-1: 301 repository moved to "+f.url()+"/repos/other-org/repo-1 (renamed or transferred): redirects aren't followed, update the target") + err = c.removeCollaborator(ctx, testRepo, "carol") + assert.ErrorContains(t, err, "DELETE /repos/acme/repo-1/collaborators/carol: 307 repository moved to") + _, err = c.setWebCommitSignoff(ctx, testRepo, true) + assert.ErrorContains(t, err, "PATCH /repos/acme/repo-1: 307 repository moved to") + + assert.Equal(t, []string{"GET /repos/acme/repo-1", "DELETE /repos/acme/repo-1/collaborators/carol", "PATCH /repos/acme/repo-1"}, f.recorded(), "nothing reaches the new location") + assert.Equal(t, []string{"carol"}, f.repo("other-org/repo-1").collaborators) + assert.False(t, f.repo("other-org/repo-1").signoff) +} + +// A repository GitHub answers for under another full_name (case aside) is not the target. +func TestClientChecksRepositoryName(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{fullName: "other-org/repo-1"}) + f.addRepo("acme/repo-2", &fakeRepo{fullName: "ACME/Repo-2"}) + c := newTestClient(t, f.url(), testToken) + + _, err := c.getRepository(testCtx(t), testRepo) + assert.EqualError(t, err, `GET /repos/acme/repo-1: GitHub answered for repository "other-org/repo-1" (renamed or transferred?): update the target`) + _, err = c.setWebCommitSignoff(testCtx(t), testRepo, true) + assert.ErrorContains(t, err, `PATCH /repos/acme/repo-1: GitHub answered for repository "other-org/repo-1"`) + _, err = c.getRepository(testCtx(t), Repo{Owner: "acme", Name: "repo-2"}) + assert.NoError(t, err, "full_name is compared ignoring case") +} + +func TestClientErrors(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{collaborators: []string{"carol"}}) + f.failOn("DELETE /repos/acme/repo-1/collaborators/carol", http.StatusForbidden, "Must have admin rights to Repository.") + ctx := testCtx(t) + + err := newTestClient(t, f.url(), testToken).removeCollaborator(ctx, testRepo, "carol") + assert.EqualError(t, err, "DELETE /repos/acme/repo-1/collaborators/carol: 403 Must have admin rights to Repository.") + + _, err = newTestClient(t, f.url(), testToken).getRepository(ctx, Repo{Owner: "acme", Name: "missing"}) + assert.EqualError(t, err, "GET /repos/acme/missing: 404 Not Found") + + _, err = newTestClient(t, f.url(), "ghp_wrong-secret-value").getRepository(ctx, testRepo) + assert.EqualError(t, err, "GET /repos/acme/repo-1: 401 Bad credentials") + assert.NotContains(t, err.Error(), "wrong-secret") +} + +func TestClientErrorMessages(t *testing.T) { + var handler http.HandlerFunc + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(w, r) })) + t.Cleanup(srv.Close) + c := newTestClient(t, srv.URL+"/api/v3", testToken) + ctx := testCtx(t) + + handler = func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/api/v3/repos/acme/repo-1", r.URL.Path, "the base URL's path is kept (GitHub Enterprise Server)") + assert.Equal(t, "ccf-effector-github-settings/"+Version, r.Header.Get("User-Agent")) + w.Header().Set("X-RateLimit-Remaining", "0") + w.Header().Set("X-RateLimit-Reset", "1795000000") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"message": "API rate limit exceeded"}`)) + } + _, err := c.getRepository(ctx, testRepo) + assert.EqualError(t, err, "GET /repos/acme/repo-1: 403 API rate limit exceeded (rate limit resets at 2026-11-18T11:06:40Z)") + + handler = func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadGateway) + _, _ = w.Write([]byte("bad gateway")) + } + _, err = c.getRepository(ctx, testRepo) + assert.EqualError(t, err, "GET /repos/acme/repo-1: 502 Bad Gateway", "a body that isn't GitHub's JSON gives the status text") + + handler = func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusUnprocessableEntity) + _, _ = fmt.Fprintf(w, `{"message": "%s"}`, strings.Repeat("x ", 400)) + } + _, err = c.getRepository(ctx, testRepo) + require.Error(t, err) + assert.True(t, strings.HasSuffix(err.Error(), "…"), "long messages are cut") + assert.Less(t, len(err.Error()), maxErrorMessage+100) + + handler = func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("{")) } + _, err = c.getRepository(ctx, testRepo) + assert.ErrorContains(t, err, "GET /repos/acme/repo-1: 200 decode response:") + + srv.Close() + _, err = c.getRepository(ctx, testRepo) + require.Error(t, err) + assert.NotContains(t, err.Error(), srv.URL, "transport errors leave out the URL") + + canceled, cancel := context.WithCancel(context.Background()) + cancel() + _, err = c.getRepository(canceled, testRepo) + assert.EqualError(t, err, "GET /repos/acme/repo-1: canceled") +} + +func TestNextLink(t *testing.T) { + assert.Equal(t, "https://api.github.com/x?page=2", nextLink(`; rel="next", ; rel="last"`)) + assert.Equal(t, "https://api.github.com/x?page=3", nextLink(`; rel="prev", ; rel="next"`)) + assert.Empty(t, nextLink(`; rel="prev"`)) + assert.Empty(t, nextLink(`https://api.github.com/x?page=2; rel="next"`), "the URL must be in angle brackets") + assert.Empty(t, nextLink("")) +}