diff --git a/README.md b/README.md index 4a43e70..ac4ddfa 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,8 @@ sudo sh install.sh --binary ./runplane-linux- --token rp_srv_... --primary 8. Push the change. +runplane can also make the change for you. On the **First job** page or on the **GitHub** tab of **Settings**, select a repository, then select **Open pull request**. The pull request sets `runs-on` to the label for each job on `ubuntu-latest` or `ubuntu-24.04`. If the GitHub App is from an earlier release, add read and write access to Contents, Pull requests, and Workflows in the app settings on GitHub first. + The job shows on the **Jobs** page of the dashboard. If you lose the setup code, run `sudo runplane setup-code` on the server. ## The two modes diff --git a/internal/api/api.go b/internal/api/api.go index be03eda..3ccada2 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -135,6 +135,11 @@ type GitHub interface { Sync(ctx context.Context) error // Disconnect stops the listeners, deletes the scale sets, and removes the app. Disconnect(ctx context.Context) error + // OpenPullRequest opens a pull request in the repository (owner/name) + // that sets runs-on to label in each job on a GitHub-hosted Ubuntu + // runner. While the pull request of an earlier call is open, it returns + // that one. + OpenPullRequest(ctx context.Context, base, repository, label string) (number int, url string, err error) } type Servers interface { @@ -273,6 +278,8 @@ func (h *Handler) routes() { handle(h, public, "GET /api/github/callback", "github-callback", "Finish the manifest flow (browser redirect from GitHub)", h.githubCallback, redirectResponse) handle(h, public, "GET /api/github/setup", "github-setup", "Record an installation (browser redirect from GitHub)", h.githubSetup, redirectResponse) handle(h, auth.ActionAdmin, "POST /api/github/sync", "sync-github", "Sync the installations now", h.syncGitHub) + handle(h, auth.ActionAdmin, "POST /api/github/pull-requests", "create-github-pull-request", "Open a pull request that moves jobs to a runplane label", h.createPullRequest, + describe("The pull request sets runs-on to the label for each job on ubuntu-latest or ubuntu-24.04. While an earlier pull request of runplane is open in the repository, the response gives that one.")) handle(h, auth.ActionAdmin, "DELETE /api/github", "disconnect-github", "Disconnect GitHub", h.disconnectGitHub) handle(h, auth.ActionRead, "GET /api/pools", "list-pools", "List the pools with live sandbox counts", h.listPools) diff --git a/internal/api/github.go b/internal/api/github.go index 73c5c5c..f1a6b32 100644 --- a/internal/api/github.go +++ b/internal/api/github.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "net/url" + "slices" "strconv" "time" @@ -319,6 +320,40 @@ func (h *Handler) syncGitHub(ctx context.Context, _ *struct{}) (*body[GitHubStat return reply(h.gitHubStatus(ctx)) } +type CreatePullRequestRequest struct { + Repository string `json:"repository" maxLength:"140" doc:"owner/name of a repository that the GitHub App can access."` + Label string `json:"label" pattern:"^[a-z0-9][a-z0-9-]{0,62}$" patternDescription:"lowercase letters, digits, and dashes" doc:"The label of an enabled pool."` +} + +type PullRequest struct { + Number int `json:"number"` + HTMLURL string `json:"html_url" doc:"Page of the pull request on GitHub."` +} + +func (h *Handler) createPullRequest(ctx context.Context, in *body[CreatePullRequestRequest]) (*body[PullRequest], error) { + b := in.Body + if h.d.GitHub == nil { + return nil, unavailable("The GitHub connection") + } + pools, err := h.d.Store.ListPools(ctx) + if err != nil { + return nil, err + } + if !slices.ContainsFunc(pools, func(p store.Pool) bool { return p.Enabled && p.Label == b.Label }) { + return nil, invalid("body.label", "No enabled pool has this label.", b.Label) + } + base, err := h.baseURL(ctx) + if err != nil { + return nil, err + } + number, htmlURL, err := h.d.GitHub.OpenPullRequest(ctx, base, b.Repository, b.Label) + if err != nil { + return nil, h.serviceErr(err) + } + h.audit(ctx, "github.pull_request.create", b.Repository, map[string]any{"label": b.Label, "number": number}) + return &body[PullRequest]{PullRequest{Number: number, HTMLURL: htmlURL}}, nil +} + func (h *Handler) disconnectGitHub(ctx context.Context, _ *struct{}) (*empty, error) { if h.d.GitHub == nil { return nil, unavailable("The GitHub connection") diff --git a/internal/api/github_test.go b/internal/api/github_test.go index c2688ed..1991881 100644 --- a/internal/api/github_test.go +++ b/internal/api/github_test.go @@ -3,6 +3,7 @@ package api import ( "context" "encoding/json" + "slices" "testing" "time" @@ -43,6 +44,43 @@ func TestGitHubLinksFollowTheAppHost(t *testing.T) { } } +// fakeGitHub opens pull requests. The tests use no other GitHub method. +type fakeGitHub struct { + GitHub + opened []string // "repository label" of each call +} + +func (f *fakeGitHub) OpenPullRequest(_ context.Context, _, repository, label string) (int, string, error) { + f.opened = append(f.opened, repository+" "+label) + return 12, "https://github.com/" + repository + "/pull/12", nil +} + +// A pull request must move jobs to a label that an enabled pool serves, or +// the jobs never start. Only an admin can write to repositories. +func TestCreatePullRequest(t *testing.T) { + gh := &fakeGitHub{} + e := newEnv(t, func(d *Deps) { d.GitHub = gh }) + now := time.Now() + for _, p := range []store.Pool{ + {ID: "p1", Name: "big", Label: "big", Arch: "x64", VCPU: 4, MemoryMB: 8192, DiskGB: 64, MaxRunners: 2, Enabled: true, CreatedAt: now, UpdatedAt: now}, + {ID: "p2", Name: "off", Label: "off", Arch: "x64", VCPU: 2, MemoryMB: 4096, DiskGB: 64, MaxRunners: 2, CreatedAt: now, UpdatedAt: now}, + } { + must(t, e.st.CreatePool(context.Background(), p)) + } + const path = "/api/github/pull-requests" + e.login("bob@example.com", auth.RoleMember).do("POST", path, map[string]any{"repository": "acme/web", "label": "big"}, nil).want(t, 403) + admin := e.login("ada@example.com", auth.RoleAdmin) + for _, label := range []string{"off", "gone"} { + admin.do("POST", path, map[string]any{"repository": "acme/web", "label": label}, nil).wantField(t, 422, "body.label") + } + + var pr PullRequest + admin.do("POST", path, map[string]any{"repository": "acme/web", "label": "big"}, &pr).want(t, 200) + if pr.Number != 12 || pr.HTMLURL != "https://github.com/acme/web/pull/12" || !slices.Equal(gh.opened, []string{"acme/web big"}) { + t.Errorf("pull request = %+v after the calls %q, want number 12 from one call for acme/web with big", pr, gh.opened) + } +} + func TestGitHubAndBackupEvents(t *testing.T) { e := newEnv(t) member := e.login("bob@example.com", auth.RoleMember).events(t) diff --git a/internal/github/app.go b/internal/github/app.go index aa6ddad..94ffd3e 100644 --- a/internal/github/app.go +++ b/internal/github/app.go @@ -60,9 +60,13 @@ func (s *Service) Manifest(ctx context.Context, base, accountType, organization // permissions are the GitHub App permissions of an account type. An // organization uses organization runners; a personal account can only -// use repository runners, which need administration. +// use repository runners, which need administration. The pullPermissions +// let runplane open the pull request that moves jobs to its labels. func permissions(accountType string) map[string]string { p := map[string]string{"actions": "write", "metadata": "read"} + for _, name := range pullPermissions { + p[name] = "write" + } if accountType == "organization" { p["organization_self_hosted_runners"] = "write" } else { diff --git a/internal/github/app_test.go b/internal/github/app_test.go index 1c7bff9..a9ebe5f 100644 --- a/internal/github/app_test.go +++ b/internal/github/app_test.go @@ -24,9 +24,11 @@ func TestManifest(t *testing.T) { wantPermissions map[string]any }{ {"organization", "acme", "/organizations/acme/settings/apps/new", - map[string]any{"organization_self_hosted_runners": "write", "actions": "write", "metadata": "read"}}, + map[string]any{"organization_self_hosted_runners": "write", "actions": "write", "metadata": "read", + "contents": "write", "pull_requests": "write", "workflows": "write"}}, {"user", "", "/settings/apps/new", - map[string]any{"administration": "write", "actions": "write", "metadata": "read"}}, + map[string]any{"administration": "write", "actions": "write", "metadata": "read", + "contents": "write", "pull_requests": "write", "workflows": "write"}}, } for _, tt := range tests { t.Run(tt.accountType, func(t *testing.T) { diff --git a/internal/github/installations.go b/internal/github/installations.go index 00725ea..ced69e2 100644 --- a/internal/github/installations.go +++ b/internal/github/installations.go @@ -18,12 +18,13 @@ type account struct { } type installation struct { - ID int64 `json:"id"` - AppID int64 `json:"app_id"` - Account account `json:"account"` - RepositorySelection string `json:"repository_selection"` - SuspendedAt *time.Time `json:"suspended_at"` - CreatedAt time.Time `json:"created_at"` + ID int64 `json:"id"` + AppID int64 `json:"app_id"` + Account account `json:"account"` + RepositorySelection string `json:"repository_selection"` + Permissions map[string]string `json:"permissions"` // that the account accepted, as "contents": "write" + SuspendedAt *time.Time `json:"suspended_at"` + CreatedAt time.Time `json:"created_at"` } // Setup records the installation that GitHub sends the browser back with, diff --git a/internal/github/pulls.go b/internal/github/pulls.go new file mode 100644 index 0000000..78071fc --- /dev/null +++ b/internal/github/pulls.go @@ -0,0 +1,221 @@ +package github + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" + + "github.com/danielgtaylor/huma/v2" + + "github.com/runplane/runplane/internal/store" +) + +// pullBranch is the branch of the pull request that moves jobs to runplane. +// It has no slash, so a branch named runplane cannot block it. +const pullBranch = "runplane-runs-on" + +// pullPermissions are the installation permissions that OpenPullRequest +// uses. A change in .github/workflows needs workflows next to contents. +var pullPermissions = []string{"contents", "pull_requests", "workflows"} + +// hostedRunsOn matches a runs-on line with one GitHub-hosted label that a +// pool can take: ubuntu-latest, or ubuntu-24.04, the release of the runplane +// base image. Quotes and a comment can follow the label. +var hostedRunsOn = regexp.MustCompile(`(?m)^([ \t]*(?:-[ \t]+)?runs-on:[ \t]*["']?)ubuntu-(?:latest|24\.04)(["']?[ \t]*(?:#[^\r\n]*)?\r?)$`) + +// OpenPullRequest opens a pull request in the repository that sets runs-on +// to label in each job on ubuntu-latest or ubuntu-24.04, and returns its +// number and URL. While the pull request of an earlier call is open, it +// returns that one. base is the browser URL of runplane, for the +// description. +func (s *Service) OpenPullRequest(ctx context.Context, base, repository, label string) (int, string, error) { + repo, err := s.st.GetRepositoryByName(ctx, repository) + if errors.Is(err, store.ErrNotFound) { + return 0, "", huma.Error404NotFound("The GitHub App has no access to " + repository + ".") + } + if err != nil { + return 0, "", err + } + if err := s.checkPullPermissions(ctx, repo.InstallationID); err != nil { + return 0, "", err + } + r := repoREST{s.api, installAuth{s, repo.InstallationID}, repo.FullName} + + owner, _, _ := strings.Cut(repo.FullName, "/") + var open []pullRequest + if err := r.json(ctx, http.MethodGet, "/pulls?state=open&per_page=1&head="+url.QueryEscape(owner+":"+pullBranch), nil, &open); err != nil { + return 0, "", err + } + if len(open) > 0 { + return open[0].Number, open[0].HTMLURL, nil + } + + var branch struct { + Commit struct { + SHA string `json:"sha"` + Commit struct { + Tree struct { + SHA string `json:"sha"` + } `json:"tree"` + } `json:"commit"` + } `json:"commit"` + } + if err := r.json(ctx, http.MethodGet, "/branches/"+url.PathEscape(repo.DefaultBranch), nil, &branch); err != nil { + return 0, "", err + } + files, jobs, err := r.moveWorkflows(ctx, branch.Commit.SHA, label) + if err != nil { + return 0, "", err + } + + var made struct { + SHA string `json:"sha"` + } + err = r.json(ctx, http.MethodPost, "/git/trees", map[string]any{"base_tree": branch.Commit.Commit.Tree.SHA, "tree": files}, &made) + if err != nil { + return 0, "", err + } + err = r.json(ctx, http.MethodPost, "/git/commits", map[string]any{ + "message": "Run jobs on runplane\n\nThe jobs on ubuntu-latest and ubuntu-24.04 use the runplane label " + label + ".", + "tree": made.SHA, "parents": []string{branch.Commit.SHA}, + }, &made) + if err != nil { + return 0, "", err + } + err = r.json(ctx, http.MethodPost, "/git/refs", map[string]any{"ref": "refs/heads/" + pullBranch, "sha": made.SHA}, nil) + var apiErr *apiError + if errors.As(err, &apiErr) && apiErr.status == http.StatusUnprocessableEntity { + // The branch of an earlier pull request that is closed now. + err = r.json(ctx, http.MethodPatch, "/git/refs/heads/"+pullBranch, map[string]any{"sha": made.SHA, "force": true}, nil) + } + if err != nil { + return 0, "", err + } + var pr pullRequest + err = r.json(ctx, http.MethodPost, "/pulls", map[string]any{ + "title": "Run jobs on runplane", "head": pullBranch, "base": repo.DefaultBranch, + "body": pullDescription(base, label, jobs, files), + }, &pr) + if err != nil { + return 0, "", err + } + s.log.Info("opened pull request", "repository", repo.FullName, "number", pr.Number, "jobs", jobs) + return pr.Number, pr.HTMLURL, nil +} + +type pullRequest struct { + Number int `json:"number"` + HTMLURL string `json:"html_url"` +} + +// treeFile is a file of a new Git tree, with its full content. +type treeFile struct { + Path string `json:"path"` + Mode string `json:"mode"` + Type string `json:"type"` + Content string `json:"content"` +} + +// checkPullPermissions returns a 403 problem if the account of the +// installation did not accept pullPermissions. An app from before runplane +// asked for them gets them in its settings on GitHub. +func (s *Service) checkPullPermissions(ctx context.Context, installationID int64) error { + var inst installation + err := s.api.json(ctx, call{method: http.MethodGet, path: fmt.Sprintf("/app/installations/%d", installationID), auth: appAuth{s}}, &inst) + if err != nil { + return fmt.Errorf("read the installation: %w", err) + } + for _, name := range pullPermissions { + if inst.Permissions[name] != "write" { + return huma.Error403Forbidden("The GitHub App needs read and write access to Contents, Pull requests, and Workflows. " + + "Add these permissions in the app settings on GitHub, then accept them for " + inst.Account.Login + ".") + } + } + return nil +} + +// repoREST sends REST calls about one repository as its installation. +type repoREST struct { + api *rest + auth auth + name string // owner/name +} + +// json sends a call to path below /repos/owner/name. +func (r repoREST) json(ctx context.Context, method, path string, body, out any) error { + return r.api.json(ctx, call{method: method, path: "/repos/" + r.name + path, body: body, auth: r.auth}, out) +} + +// moveWorkflows reads the workflows at the commit ref and returns the ones +// that moveJobs changes, with the count of moved jobs. +func (r repoREST) moveWorkflows(ctx context.Context, ref, label string) ([]treeFile, int, error) { + var entries []struct { + Type string `json:"type"` + Path string `json:"path"` + SHA string `json:"sha"` + } + err := r.json(ctx, http.MethodGet, "/contents/.github/workflows?ref="+ref, nil, &entries) + var apiErr *apiError + if errors.As(err, &apiErr) && apiErr.status == http.StatusNotFound { + return nil, 0, huma.Error422UnprocessableEntity(r.name + " has no workflows in .github/workflows.") + } + if err != nil { + return nil, 0, err + } + var files []treeFile + jobs := 0 + for _, e := range entries { + if e.Type != "file" || !strings.HasSuffix(e.Path, ".yml") && !strings.HasSuffix(e.Path, ".yaml") { + continue + } + var blob struct { + Content string `json:"content"` + } + if err := r.json(ctx, http.MethodGet, "/git/blobs/"+e.SHA, nil, &blob); err != nil { + return nil, 0, err + } + raw, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(blob.Content, "\n", "")) + if err != nil { + return nil, 0, fmt.Errorf("decode %s of %s: %w", e.Path, r.name, err) + } + moved, n := moveJobs(string(raw), label) + if n == 0 { + continue + } + files = append(files, treeFile{Path: e.Path, Mode: "100644", Type: "blob", Content: moved}) + jobs += n + } + if jobs == 0 { + return nil, 0, huma.Error422UnprocessableEntity("No job in the workflows of " + r.name + " runs on ubuntu-latest or ubuntu-24.04.") + } + return files, jobs, nil +} + +// moveJobs sets runs-on to label in each job of the workflow that runs on +// ubuntu-latest or ubuntu-24.04, and counts these jobs. The other lines +// stay as they are. +func moveJobs(workflow, label string) (string, int) { + n := len(hostedRunsOn.FindAllStringIndex(workflow, -1)) + return hostedRunsOn.ReplaceAllString(workflow, "${1}"+label+"${2}"), n +} + +func pullDescription(base, label string, jobs int, files []treeFile) string { + var b strings.Builder + noun := "jobs" + if jobs == 1 { + noun = "job" + } + fmt.Fprintf(&b, "This pull request sets `runs-on` to `%s` for %d %s on `ubuntu-latest` or `ubuntu-24.04`. "+ + "These jobs then run on your runplane servers. Workflows that run on pull requests use the change for this pull request too, "+ + "so you can see the jobs in runplane before you merge.\n\nChanged workflows:\n\n", label, jobs, noun) + for _, f := range files { + fmt.Fprintf(&b, "- `%s`\n", f.Path) + } + fmt.Fprintf(&b, "\nJobs in runplane: %s/jobs\n", base) + return b.String() +} diff --git a/internal/github/pulls_test.go b/internal/github/pulls_test.go new file mode 100644 index 0000000..40a0a6c --- /dev/null +++ b/internal/github/pulls_test.go @@ -0,0 +1,254 @@ +package github + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/runplane/runplane/internal/store" +) + +func TestMoveJobs(t *testing.T) { + tests := []struct { + name, in, want string + jobs int + }{ + {"ubuntu-latest", " runs-on: ubuntu-latest\n", " runs-on: big\n", 1}, + {"quoted ubuntu-24.04 with a comment", " runs-on: 'ubuntu-24.04' # pinned\n", " runs-on: 'big' # pinned\n", 1}, + {"CRLF line ends", "jobs:\r\n a:\r\n runs-on: ubuntu-latest\r\n", "jobs:\r\n a:\r\n runs-on: big\r\n", 1}, + {"matrix entry", " - runs-on: ubuntu-latest\n", " - runs-on: big\n", 1}, + {"two jobs", " a:\n runs-on: ubuntu-latest\n b:\n runs-on: ubuntu-24.04", " a:\n runs-on: big\n b:\n runs-on: big", 2}, + {"other release", " runs-on: ubuntu-22.04\n", " runs-on: ubuntu-22.04\n", 0}, + {"larger runner", " runs-on: ubuntu-latest-8-cores\n", " runs-on: ubuntu-latest-8-cores\n", 0}, + {"expression", " runs-on: ${{ matrix.os }}\n", " runs-on: ${{ matrix.os }}\n", 0}, + {"label list", " runs-on: [ubuntu-latest]\n", " runs-on: [ubuntu-latest]\n", 0}, + {"other key", " os: ubuntu-latest\n", " os: ubuntu-latest\n", 0}, + } + for _, tt := range tests { + got, jobs := moveJobs(tt.in, "big") + if got != tt.want || jobs != tt.jobs { + t.Errorf("%s: moveJobs = %q, %d; want %q, %d", tt.name, got, jobs, tt.want, tt.jobs) + } + } +} + +const ciWorkflow = `on: pull_request +jobs: + test: + runs-on: ubuntu-latest + steps: + - run: make test + lint: + runs-on: "ubuntu-24.04" # pinned + install: + runs-on: ubuntu-22.04 +` + +const ciMoved = `on: pull_request +jobs: + test: + runs-on: big + steps: + - run: make test + lint: + runs-on: "big" # pinned + install: + runs-on: ubuntu-22.04 +` + +// fakeRepo serves the repository acme/web for OpenPullRequest and keeps +// the bodies of its writes by "METHOD path". +type fakeRepo struct { + mu sync.Mutex + permissions map[string]string + open []map[string]any // open pull requests of runplane-runs-on + workflows map[string]string // file name -> content; nil = no .github/workflows + branchTaken bool // runplane-runs-on exists + writes map[string]map[string]any +} + +func (e *env) repo() *fakeRepo { + e.t.Helper() + ctx := context.Background() + if err := e.st.ReplaceRepositories(ctx, 10, []store.Repository{ + {ID: 100, FullName: "acme/web", Private: true, DefaultBranch: "main", UpdatedAt: time.Now()}, + }); err != nil { + e.t.Fatal(err) + } + f := &fakeRepo{ + permissions: map[string]string{"actions": "write", "contents": "write", "metadata": "read", "pull_requests": "write", "workflows": "write"}, + workflows: map[string]string{"ci.yml": ciWorkflow, "release.yaml": "jobs:\n build:\n runs-on: macos-latest\n", "README.md": "runs-on: ubuntu-latest\n"}, + writes: map[string]map[string]any{}, + } + const repo = "/api/v3/repos/acme/web" + m := e.mux + m.HandleFunc("GET /api/v3/app/installations/10", func(w http.ResponseWriter, r *http.Request) { + e.checkJWT(r) + f.mu.Lock() + defer f.mu.Unlock() + writeJSON(w, http.StatusOK, map[string]any{"id": 10, "app_id": testAppID, "permissions": f.permissions, + "account": map[string]any{"login": "acme", "id": 1, "type": "Organization"}}) + }) + m.HandleFunc("GET "+repo+"/pulls", func(w http.ResponseWriter, r *http.Request) { + if q := r.URL.Query(); q.Get("head") != "acme:runplane-runs-on" || q.Get("state") != "open" { + e.t.Errorf("pull request query %s, want the open pull requests of acme:runplane-runs-on", r.URL.RawQuery) + } + f.mu.Lock() + defer f.mu.Unlock() + writeJSON(w, http.StatusOK, f.open) + }) + m.HandleFunc("GET "+repo+"/branches/main", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"name": "main", + "commit": map[string]any{"sha": "c1", "commit": map[string]any{"tree": map[string]any{"sha": "t1"}}}}) + }) + m.HandleFunc("GET "+repo+"/contents/.github/workflows", func(w http.ResponseWriter, r *http.Request) { + if ref := r.URL.Query().Get("ref"); ref != "c1" { + e.t.Errorf("workflows read at %q, want the head of main", ref) + } + f.mu.Lock() + defer f.mu.Unlock() + if f.workflows == nil { + writeJSON(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) + return + } + entries := []map[string]any{{"type": "dir", "name": "scripts", "path": ".github/workflows/scripts", "sha": "d1"}} + for name := range f.workflows { + entries = append(entries, map[string]any{"type": "file", "name": name, "path": ".github/workflows/" + name, "sha": "blob-" + name}) + } + writeJSON(w, http.StatusOK, entries) + }) + m.HandleFunc("GET "+repo+"/git/blobs/{sha}", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + content := f.workflows[strings.TrimPrefix(r.PathValue("sha"), "blob-")] + f.mu.Unlock() + // GitHub breaks the base64 text into lines of 60 characters. + enc := base64.StdEncoding.EncodeToString([]byte(content)) + var lines []string + for len(enc) > 60 { + lines, enc = append(lines, enc[:60]), enc[60:] + } + writeJSON(w, http.StatusOK, map[string]any{"content": strings.Join(append(lines, enc), "\n") + "\n", "encoding": "base64"}) + }) + write := func(status int, out map[string]any) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + json.NewDecoder(r.Body).Decode(&body) + f.mu.Lock() + f.writes[r.Method+" "+strings.TrimPrefix(r.URL.Path, repo)] = body + taken := f.branchTaken + f.mu.Unlock() + if r.URL.Path == repo+"/git/refs" && taken { + writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": "Reference already exists"}) + return + } + writeJSON(w, status, out) + } + } + m.HandleFunc("POST "+repo+"/git/trees", write(http.StatusCreated, map[string]any{"sha": "t2"})) + m.HandleFunc("POST "+repo+"/git/commits", write(http.StatusCreated, map[string]any{"sha": "c2"})) + m.HandleFunc("POST "+repo+"/git/refs", write(http.StatusCreated, map[string]any{"ref": "refs/heads/runplane-runs-on"})) + m.HandleFunc("PATCH "+repo+"/git/refs/heads/runplane-runs-on", write(http.StatusOK, map[string]any{"ref": "refs/heads/runplane-runs-on"})) + m.HandleFunc("POST "+repo+"/pulls", write(http.StatusCreated, map[string]any{"number": 12, "html_url": "https://github.com/acme/web/pull/12"})) + return f +} + +func (f *fakeRepo) written() map[string]map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + return f.writes +} + +func TestOpenPullRequest(t *testing.T) { + ctx := context.Background() + + t.Run("commits the moved jobs to a new branch", func(t *testing.T) { + e := acmeEnv(t) + f := e.repo() + number, url, err := e.svc.OpenPullRequest(ctx, "https://ci.example.com", "acme/web", "big") + if err != nil || number != 12 || url != "https://github.com/acme/web/pull/12" { + t.Fatalf("OpenPullRequest = %d, %q, %v; want pull request 12", number, url, err) + } + w := f.written() + wantTree := map[string]any{"base_tree": "t1", "tree": []any{map[string]any{ + "path": ".github/workflows/ci.yml", "mode": "100644", "type": "blob", "content": ciMoved, + }}} + if got := w["POST /git/trees"]; !reflect.DeepEqual(got, wantTree) { + t.Errorf("tree = %v, want %v", got, wantTree) + } + if got := w["POST /git/commits"]; got["tree"] != "t2" || !reflect.DeepEqual(got["parents"], []any{"c1"}) { + t.Errorf("commit = %v, want tree t2 on c1", got) + } + if got := w["POST /git/refs"]; got["ref"] != "refs/heads/runplane-runs-on" || got["sha"] != "c2" { + t.Errorf("ref = %v, want runplane-runs-on at c2", got) + } + if got := w["POST /pulls"]; got["head"] != "runplane-runs-on" || got["base"] != "main" { + t.Errorf("pull request = %v, want runplane-runs-on into main", got) + } + }) + + t.Run("gives the open pull request of an earlier call", func(t *testing.T) { + e := acmeEnv(t) + f := e.repo() + f.open = []map[string]any{{"number": 7, "html_url": "https://github.com/acme/web/pull/7"}} + number, url, err := e.svc.OpenPullRequest(ctx, "https://ci.example.com", "acme/web", "big") + if err != nil || number != 7 || url != "https://github.com/acme/web/pull/7" { + t.Errorf("OpenPullRequest = %d, %q, %v; want the open pull request 7", number, url, err) + } + if w := f.written(); len(w) != 0 { + t.Errorf("writes = %v, want none", w) + } + }) + + t.Run("moves the branch of a closed pull request", func(t *testing.T) { + e := acmeEnv(t) + f := e.repo() + f.branchTaken = true + if _, _, err := e.svc.OpenPullRequest(ctx, "https://ci.example.com", "acme/web", "big"); err != nil { + t.Fatal(err) + } + w := f.written() + if got := w["PATCH /git/refs/heads/runplane-runs-on"]; got["sha"] != "c2" || got["force"] != true { + t.Errorf("ref update = %v, want a forced move to c2", got) + } + if w["POST /pulls"] == nil { + t.Error("no pull request after the branch moved") + } + }) + + errorTests := []struct { + name string + repository string + change func(f *fakeRepo) + wantStatus int + }{ + {"unknown repository", "acme/other", func(*fakeRepo) {}, http.StatusNotFound}, + {"no workflows permission", "acme/web", func(f *fakeRepo) { delete(f.permissions, "workflows") }, http.StatusForbidden}, + {"read-only contents", "acme/web", func(f *fakeRepo) { f.permissions["contents"] = "read" }, http.StatusForbidden}, + {"no workflows", "acme/web", func(f *fakeRepo) { f.workflows = nil }, http.StatusUnprocessableEntity}, + {"no job on ubuntu-latest", "acme/web", func(f *fakeRepo) { delete(f.workflows, "ci.yml") }, http.StatusUnprocessableEntity}, + } + for _, tt := range errorTests { + t.Run(tt.name, func(t *testing.T) { + e := acmeEnv(t) + f := e.repo() + tt.change(f) + _, _, err := e.svc.OpenPullRequest(ctx, "https://ci.example.com", tt.repository, "big") + var se huma.StatusError + if !errors.As(err, &se) || se.GetStatus() != tt.wantStatus { + t.Errorf("err = %v, want status %d", err, tt.wantStatus) + } + if w := f.written(); len(w) != 0 { + t.Errorf("writes = %v, want none", w) + } + }) + } +} diff --git a/internal/github/rest.go b/internal/github/rest.go index 779f7bd..c35774f 100644 --- a/internal/github/rest.go +++ b/internal/github/rest.go @@ -1,6 +1,7 @@ package github import ( + "bytes" "cmp" "context" "encoding/json" @@ -70,6 +71,7 @@ func newREST(base string) *rest { type call struct { method string path string + body any // sent as JSON when not nil auth auth // nil = anonymous timeout time.Duration // 0 = callTimeout noRedirect bool @@ -132,12 +134,23 @@ func (c *rest) send(ctx context.Context, cl call, authorization string) (*http.R if strings.HasPrefix(u, "/") { u = c.base + u } + var body io.Reader + if cl.body != nil { + b, err := json.Marshal(cl.body) + if err != nil { + return nil, fmt.Errorf("encode request %s %s: %w", cl.method, cl.path, err) + } + body = bytes.NewReader(b) + } actx, cancel := context.WithTimeout(ctx, cmp.Or(cl.timeout, callTimeout)) - req, err := http.NewRequestWithContext(actx, cl.method, u, nil) + req, err := http.NewRequestWithContext(actx, cl.method, u, body) if err != nil { cancel() return nil, fmt.Errorf("make request %s %s: %w", cl.method, cl.path, err) } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("X-GitHub-Api-Version", "2022-11-28") req.Header.Set("User-Agent", "runplane/"+version.Version) diff --git a/web/src/api/openapi.json b/web/src/api/openapi.json index de89c6f..f2a7353 100644 --- a/web/src/api/openapi.json +++ b/web/src/api/openapi.json @@ -564,6 +564,27 @@ ], "type": "object" }, + "CreatePullRequestRequest": { + "additionalProperties": false, + "properties": { + "label": { + "description": "The label of an enabled pool.", + "pattern": "^[a-z0-9][a-z0-9-]{0,62}$", + "patternDescription": "lowercase letters, digits, and dashes", + "type": "string" + }, + "repository": { + "description": "owner/name of a repository that the GitHub App can access.", + "maxLength": 140, + "type": "string" + } + }, + "required": [ + "repository", + "label" + ], + "type": "object" + }, "CreatedInvite": { "additionalProperties": false, "properties": { @@ -2316,6 +2337,24 @@ ], "type": "object" }, + "PullRequest": { + "additionalProperties": false, + "properties": { + "html_url": { + "description": "Page of the pull request on GitHub.", + "type": "string" + }, + "number": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "number", + "html_url" + ], + "type": "object" + }, "Repository": { "additionalProperties": false, "properties": { @@ -4695,6 +4734,53 @@ ] } }, + "/api/github/pull-requests": { + "post": { + "description": "The pull request sets runs-on to the label for each job on ubuntu-latest or ubuntu-24.04. While an earlier pull request of runplane is open in the repository, the response gives that one.", + "operationId": "create-github-pull-request", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatePullRequestRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PullRequest" + } + } + }, + "description": "OK" + }, + "default": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + }, + "description": "Error" + } + }, + "security": [ + { + "session": [] + } + ], + "summary": "Open a pull request that moves jobs to a runplane label", + "tags": [ + "github" + ] + } + }, "/api/github/setup": { "get": { "description": "The browser comes here from GitHub. The response sends it on to GitHub or to the dashboard. Errors go to the dashboard page in the query parameter error.", diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 991cab8..a931bda 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -166,6 +166,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/github/pull-requests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Open a pull request that moves jobs to a runplane label + * @description The pull request sets runs-on to the label for each job on ubuntu-latest or ubuntu-24.04. While an earlier pull request of runplane is open in the repository, the response gives that one. + */ + post: operations["create-github-pull-request"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/github/setup": { parameters: { query?: never; @@ -1190,6 +1210,12 @@ export interface components { /** Format: int64 */ vcpu: number; }; + CreatePullRequestRequest: { + /** @description The label of an enabled pool. */ + label: string; + /** @description owner/name of a repository that the GitHub App can access. */ + repository: string; + }; CreatedInvite: { invite: components["schemas"]["Invite"]; /** @description Link for the new user. It works one time, for 7 days. */ @@ -1869,6 +1895,12 @@ export interface components { /** Format: int64 */ starting: number; }; + PullRequest: { + /** @description Page of the pull request on GitHub. */ + html_url: string; + /** Format: int64 */ + number: number; + }; Repository: { archived: boolean; /** @description owner/name */ @@ -2909,6 +2941,39 @@ export interface operations { }; }; }; + "create-github-pull-request": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CreatePullRequestRequest"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PullRequest"]; + }; + }; + /** @description Error */ + default: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ErrorModel"]; + }; + }; + }; + }; "github-setup": { parameters: { query?: { diff --git a/web/src/components/pages/github/connect-form.tsx b/web/src/components/pages/github/connect-form.tsx index 2d3fb4d..98b9123 100644 --- a/web/src/components/pages/github/connect-form.tsx +++ b/web/src/components/pages/github/connect-form.tsx @@ -13,18 +13,17 @@ import { borderedList, borderedRow } from './parts' type AccountType = Schemas['ManifestRequest']['account_type'] // The permissions of the manifest. Runners of a personal account are -// repository runners, which need Administration. -const permissions: Record> = { - organization: [ - ['Self-hosted runners', 'Read and write'], - ['Actions', 'Read and write'], - ['Metadata', 'Read'], - ], - user: [ - ['Administration', 'Read and write'], - ['Actions', 'Read and write'], - ['Metadata', 'Read'], - ], +// repository runners, which need Administration. Contents, Pull requests, and +// Workflows let runplane open the pull request of the first job page. +const pullRequests = [ + ['Contents', 'Read and write'], + ['Pull requests', 'Read and write'], + ['Workflows', 'Read and write'], +] as const + +const permissions: Record> = { + organization: [['Self-hosted runners', 'Read and write'], ['Actions', 'Read and write'], ...pullRequests, ['Metadata', 'Read']], + user: [['Administration', 'Read and write'], ['Actions', 'Read and write'], ...pullRequests, ['Metadata', 'Read']], } /** diff --git a/web/src/components/pages/github/links.test.ts b/web/src/components/pages/github/links.test.ts index 173e598..eb44ee8 100644 --- a/web/src/components/pages/github/links.test.ts +++ b/web/src/components/pages/github/links.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest' import type { Schemas } from '~/api/client' -import { repositoryAccess } from './links' +import { jobRepositories, repositoryAccess } from './links' const organization: Schemas['Installation'] = { id: 58213907, @@ -22,3 +22,18 @@ test.each([ ] as const)('repositoryAccess with %s and %i repositories is %j', (selection, count, want) => { expect(repositoryAccess({ ...organization, repository_selection: selection, repository_count: count })).toBe(want) }) + +// A pull request in a repository that runplane refuses gives jobs that never start. +test.each([ + [false, 'vm', ['kestrel-hq/api']], + [true, 'vm', ['kestrel-hq/api', 'kestrel-hq/site']], + [true, 'container', ['kestrel-hq/api']], +] as const)('jobRepositories with allow_public_repos %s in mode %s is %j', (allow, mode, want) => { + const repositories: Schemas['Repository'][] = [ + { id: 1, full_name: 'kestrel-hq/api', private: true, archived: false }, + { id: 2, full_name: 'kestrel-hq/site', private: false, archived: false }, + { id: 3, full_name: 'kestrel-hq/old', private: true, archived: true }, + ] + const suspended = { ...organization, id: 2, account_login: 'wren', suspended: true, repositories: [{ id: 4, full_name: 'wren/app', private: true, archived: false }] } + expect(jobRepositories([{ ...organization, repositories }, suspended], { allow_public_repos: allow, mode })).toEqual(want) +}) diff --git a/web/src/components/pages/github/links.ts b/web/src/components/pages/github/links.ts index d0779d4..2afa72e 100644 --- a/web/src/components/pages/github/links.ts +++ b/web/src/components/pages/github/links.ts @@ -1,6 +1,23 @@ import type { Schemas } from '~/api/client' import { formatCount } from '~/lib/format' +/** + * owner/name of the repositories whose jobs runplane takes: not archived, in an + * installation that is not suspended, and private unless public repositories are on. + */ +export function jobRepositories( + installations: readonly Schemas['Installation'][], + settings: Pick, +): string[] { + // Container mode refuses public repositories whatever the setting says. + const publicRepos = settings.allow_public_repos && settings.mode !== 'container' + return installations + .filter((installation) => !installation.suspended) + .flatMap((installation) => installation.repositories) + .filter((repository) => !repository.archived && (repository.private || publicRepos)) + .map((repository) => repository.full_name) +} + /** "All repositories · 12" or "3 selected repositories". */ export function repositoryAccess({ repository_selection, repository_count }: Schemas['Installation']): string { if (repository_selection === 'all') return `All repositories · ${formatCount(repository_count)}` diff --git a/web/src/components/pages/github/pull-request-form.tsx b/web/src/components/pages/github/pull-request-form.tsx new file mode 100644 index 0000000..5ff8cde --- /dev/null +++ b/web/src/components/pages/github/pull-request-form.tsx @@ -0,0 +1,125 @@ +import { ExternalLink } from 'lucide-react' +import { useState, type FormEvent } from 'react' +import { $api, errorMessage, isApiError } from '~/api/client' +import { StatusIcon } from '~/components/app/status-icon' +import { FormAlert } from '~/components/pages/setup/parts' +import { Button, buttonClassName } from '~/components/ui/button' +import { Combobox, ComboboxInput, ComboboxItem, ComboboxPopup } from '~/components/ui/combobox' +import { Select, SelectItem, SelectPopup, SelectTrigger } from '~/components/ui/select' +import { ExternalTextLink } from './parts' + +type PullRequestFormProps = { + /** owner/name of the repositories whose jobs runplane takes. */ + repositories: string[] + /** The labels of the enabled pools. With more than one, the form shows a label select. */ + labels: string[] + defaultLabel: string + /** The permissions page of the GitHub App. An app from before runplane opened pull requests must get write access there first. */ + permissionsUrl: string | undefined +} + +/** + * runplane sets runs-on to a label in each workflow of a repository and opens + * a pull request. The form stays after a pull request opens, so the next + * repository can follow. + */ +export function PullRequestForm({ repositories, labels, defaultLabel, permissionsUrl }: PullRequestFormProps) { + const [repository, setRepository] = useState(repositories.length === 1 ? (repositories[0] ?? null) : null) + const [label, setLabel] = useState(defaultLabel) + const [unselected, setUnselected] = useState(false) + const create = $api.useMutation('post', '/api/github/pull-requests') + + function submit(event: FormEvent) { + event.preventDefault() + if (repository) create.mutate({ body: { repository, label } }) + else setUnselected(true) + } + + return ( +
+
+ { + setRepository(name) + setUnselected(false) + if (create.isError) create.reset() + }} + autoHighlight + disabled={create.isPending} + > + + + {(name: string) => ( + + {name} + + )} + + + {labels.length > 1 && ( + + )} + +
+

+ runplane sets runs-on to {label} for each job on ubuntu-latest or ubuntu-24.04 in the repository, then opens a pull request for you to + review. +

+ {unselected && Select a repository in the list.} + {create.error && ( + + {errorMessage(create.error)} + {isApiError(create.error, 403) && permissionsUrl && ( + <> + {' '} + + App permissions + + (opens in a new tab) + + + )} + + )} + {create.data && ( +
+

+ + + Pull request #{create.data.number} is open in {create.variables?.body.repository} + +

+ + View on GitHub + + (opens in a new tab) + +
+ )} +
+ ) +} diff --git a/web/src/routes/_app/settings/github.tsx b/web/src/routes/_app/settings/github.tsx index 42910f9..1392823 100644 --- a/web/src/routes/_app/settings/github.tsx +++ b/web/src/routes/_app/settings/github.tsx @@ -10,7 +10,11 @@ import { callbackSearch } from '~/components/pages/github/callback' import { DisconnectGitHub } from '~/components/pages/github/disconnect' import { InstallationList } from '~/components/pages/github/installation-list' import { JobAccess } from '~/components/pages/github/job-access' +import { jobRepositories } from '~/components/pages/github/links' import { CallbackError, InstallRequested, Loading } from '~/components/pages/github/parts' +import { PullRequestForm } from '~/components/pages/github/pull-request-form' +import { suggestedLabel } from '~/components/pages/overview/no-jobs' +import { poolsQuery } from '~/components/pages/runners/queries' import { settingsQuery } from '~/components/pages/settings/settings-api' import { buttonClassName, IconButton } from '~/components/ui/button' import { GithubIcon } from '~/components/ui/icons' @@ -20,7 +24,11 @@ import { pageHead } from '~/lib/head' export const Route = createFileRoute('/_app/settings/github')({ validateSearch: callbackSearch, loader: ({ context: { queryClient } }) => - Promise.all([queryClient.ensureQueryData(githubQuery), queryClient.ensureQueryData(settingsQuery)]), + Promise.all([ + queryClient.ensureQueryData(githubQuery), + queryClient.ensureQueryData(settingsQuery), + queryClient.ensureQueryData(poolsQuery), + ]), head: () => pageHead('GitHub settings'), pendingComponent: () => ( @@ -62,6 +70,7 @@ function GithubSettings() { )} {app && } + {app && isAdmin && } {app && isAdmin && } @@ -114,6 +123,33 @@ function Installations({ app, installations, isAdmin }: InstallationsProps) { ) } +type PullRequestsProps = { + app: Schemas['GitHubApp'] + installations: Schemas['Installation'][] + settings: Schemas['Settings'] +} + +/** "Open a pull request": moves the jobs of one more repository to runplane at any time after the setup. */ +function PullRequests({ app, installations, settings }: PullRequestsProps) { + const pools = useSuspenseQuery(poolsQuery).data + const labels = pools.filter((pool) => pool.enabled).map((pool) => pool.label) + const label = suggestedLabel(pools) + const repositories = jobRepositories(installations, settings) + if (!label || repositories.length === 0) return null + + return ( +
+ + +
+ ) +} + function NotConnected({ isAdmin }: { isAdmin: boolean }) { return ( - Promise.all([queryClient.ensureQueryData(githubQuery), queryClient.ensureQueryData(poolsQuery)]), + Promise.all([ + queryClient.ensureQueryData(githubQuery), + queryClient.ensureQueryData(poolsQuery), + queryClient.ensureQueryData(settingsQuery), + ]), head: () => pageHead('First job'), pendingComponent: () => ( <> @@ -25,10 +32,13 @@ export const Route = createFileRoute('/_setup/setup/first-job')({ function FirstJobStep() { const queryClient = useQueryClient() const navigate = useNavigate() - const { installations } = useSuspenseQuery(githubQuery).data + const admin = useIsAdmin() + const { app, installations } = useSuspenseQuery(githubQuery).data const pools = useSuspenseQuery(poolsQuery).data + const settings = useSuspenseQuery(settingsQuery).data const labels = pools.filter((pool) => pool.enabled) const label = suggestedLabel(pools) + const repositories = jobRepositories(installations, settings) async function openDashboard() { // The overview reads has_jobs from the status to leave its empty state. @@ -41,6 +51,17 @@ function FirstJobStep() {
{label && } + {label && admin && repositories.length > 0 && ( +
+

Open a pull request

+ +
+ )} void openDashboard()} /> @@ -53,4 +74,4 @@ function Header() { Change one line in any workflow. Jobs with a runplane label run on your servers; everything else stays on GitHub. ) -} \ No newline at end of file +}