1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "path"
11 "strings"
12
13 "bnema.dev/ermite/internal/domain"
14 "bnema.dev/ermite/internal/ports"
15)
16
17// jobTokenActor is the actor of a run dispatched with a job token, GitHub's name
18// for the account behind a GITHUB_TOKEN.
19const jobTokenActor = "github-actions[bot]"
20
21// DispatchWorkflow starts a run of a workflow file by hand (workflow_dispatch,
22// CI-3 D5), like `gh workflow run`.
23//
24// Who may: a principal with ci:write on the repository, or the holder of a job
25// token whose permissions include "actions: write" (GitHub's one exception to
26// "events made with GITHUB_TOKEN start no run"; a token of a run that is not
27// trusted never has it, TokenPermissions lowers it, so a job token that gets
28// here belongs to a trusted run). A token limited to branch prefixes may only
29// dispatch on a branch under them, and its run is not trusted (D1). Whoever
30// calls, the run is trusted only when the ref it runs on was moved to its commit
31// by a trusted principal (ci_tips.go).
32//
33// The workflow is read at ref (the default branch when empty) and must declare
34// workflow_dispatch; the inputs are checked against its declaration.
35func (c *CI) DispatchWorkflow(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.DispatchParams) (domain.CIRun, error) {
36 repo, actor, pusher, trusted, err := c.dispatchCaller(ctx, p, name)
37 if err != nil {
38 return domain.CIRun{}, err
39 }
40 wfPath, err := dispatchPath(params.WorkflowPath)
41 if err != nil {
42 return domain.CIRun{}, err
43 }
44 pin, err := c.dispatchRef(ctx, name, params.Ref)
45 if err != nil {
46 return domain.CIRun{}, err
47 }
48 ref, commit := pin.ref, pin.commit
49 if c.cfg.DispatchResolved != nil {
50 c.cfg.DispatchResolved()
51 }
52 if !p.AllowsRef(ref) {
53 return domain.CIRun{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, ref)
54 }
55 content, err := c.readWorkflowAt(ctx, name, commit, wfPath)
56 if err != nil {
57 return domain.CIRun{}, err
58 }
59 wf, perrs := parseWorkflow(wfPath, content)
60 if len(perrs) > 0 {
61 lines := make([]string, 0, len(perrs))
62 for _, e := range perrs {
63 lines = append(lines, e.Error())
64 }
65 return domain.CIRun{}, fmt.Errorf("%w: %s is not a valid workflow:\n%s", domain.ErrInvalid, wfPath, strings.Join(lines, "\n"))
66 }
67 ev := wf.On.Event(eventDispatch)
68 if ev == nil {
69 return domain.CIRun{}, fmt.Errorf("%w: %s does not have a %s trigger", domain.ErrPreconditionFailed, wfPath, eventDispatch)
70 }
71 values, err := resolveDispatchInputs(ev.Inputs, params.Inputs)
72 if err != nil {
73 return domain.CIRun{}, err
74 }
75
76 f := pushFacts{
77 update: domain.RefUpdate{Ref: ref, Old: domain.ZeroOID, New: commit.String()}, commit: commit,
78 custom: &customEvent{name: eventDispatch, title: workflowName(wf, wfPath), inputs: values},
79 }
80 if def, _, err := c.cfg.Repos.DefaultBranch(ctx, name); err == nil {
81 f.defaultBranch = def
82 }
83 // The run executes the code of the ref, which the caller did not necessarily
84 // write: it is trusted only if the caller is AND whoever moved the ref to this
85 // commit was (domain.CIRefTip), as a re-run of an agent's run by the owner
86 // does not unlock secrets. A ref with no record is not trusted. This holds for
87 // every caller, the owner and a job token alike.
88 trusted = trusted && c.refTrusted(ctx, name, pin)
89 t := ciTrigger{repo: name, actor: actor, pusher: pusher, trusted: trusted, at: c.now()}
90 if problem := c.matrixProblem(ctx, repo, t, f, wfPath, wf); problem.text != "" {
91 return domain.CIRun{}, fmt.Errorf("%w: %s", domain.ErrInvalid, problem.text)
92 }
93 run, err := c.launchRun(ctx, repo, t, f, wfPath, string(content), wf)
94 if err != nil {
95 return domain.CIRun{}, err
96 }
97 if run.ID == 0 {
98 return domain.CIRun{}, domain.ErrNotFound
99 }
100 ctxLog(ctx).Info().Str("repo", name.String()).Int64("run_id", run.ID).Str("workflow", wfPath).Str("ref", ref).
101 Str("principal", p.Label()).Bool("trusted", trusted).Msg("ci workflow dispatched")
102 return run, nil
103}
104
105// dispatchCaller applies the access rule of a dispatch and returns who the run
106// is for.
107func (c *CI) dispatchCaller(ctx context.Context, p domain.Principal, name domain.RepoName) (repo domain.Repo, actor string, pusher domain.CIPusher, trusted bool, err error) {
108 if p.ViaJobToken() {
109 repo, err = lookupRepo(ctx, c.cfg.Meta, name)
110 if err != nil {
111 return repo, "", pusher, false, err
112 }
113 // The permission is judged on its own: a job of this repository with
114 // actions: write may dispatch even when its contents permission is none
115 // (a private repository is then unreadable to it). JobPermits is true only
116 // for the job's own token on its own repository, so any other caller of
117 // a repository it cannot read still gets not found.
118 switch {
119 case p.JobPermits("actions", domain.PermissionWrite, name):
120 return repo, jobTokenActor, domain.PusherOf(p), true, nil
121 case !canRead(p, repo):
122 return repo, "", pusher, false, domain.ErrNotFound
123 }
124 return repo, "", pusher, false, fmt.Errorf("%w: a job token needs the permission actions: write to dispatch a workflow", domain.ErrForbidden)
125 }
126 repo, err = c.writableRepo(ctx, p, name)
127 if err != nil {
128 return repo, "", pusher, false, err
129 }
130 return repo, authorOf(p), domain.PusherOf(p), domain.TrustedActor(p), nil
131}
132
133// dispatchPath checks the workflow file of a dispatch: a file of
134// .github/workflows, named by its path or by its file name.
135func dispatchPath(s string) (string, error) {
136 s = strings.TrimSpace(s)
137 if s == "" {
138 return "", fmt.Errorf("%w: the workflow file is required", domain.ErrInvalid)
139 }
140 if !strings.Contains(s, "/") {
141 s = workflowDir + "/" + s
142 }
143 ext := strings.ToLower(path.Ext(s))
144 if path.Dir(s) != workflowDir || (ext != ".yml" && ext != ".yaml") {
145 return "", fmt.Errorf("%w: %q is not a workflow file of %s", domain.ErrInvalid, s, workflowDir)
146 }
147 return s, nil
148}
149
150// pinnedRef is what a dispatch resolved its ref to, once: the full name, the
151// commit the run executes and the object the ref points to (the commit for a
152// branch and a lightweight tag, the tag object for an annotated tag). The trust
153// of the run is judged on exactly these, never on the ref as it is read later
154// (ci_tips.go).
155type pinnedRef struct {
156 ref string
157 commit, object domain.ObjectID
158}
159
160// dispatchRef resolves the ref of a dispatch: a branch or a tag, by short or
161// full name; the default branch when empty. A tag is resolved to its commit and
162// its own object together; a tag that moves between the two reads is refused,
163// so the commit and the object always belong to one state of the ref.
164func (c *CI) dispatchRef(ctx context.Context, name domain.RepoName, given string) (pinnedRef, error) {
165 given = strings.TrimSpace(given)
166 if given == "" {
167 def, exists, err := c.cfg.Repos.DefaultBranch(ctx, name)
168 if err != nil {
169 return pinnedRef{}, err
170 }
171 if !exists {
172 return pinnedRef{}, fmt.Errorf("%w: the default branch %q does not exist", domain.ErrNotFound, def)
173 }
174 given = "refs/heads/" + def
175 }
176 rev, err := domain.ParseRevision(given)
177 if err != nil {
178 return pinnedRef{}, err
179 }
180 res, err := c.cfg.Reader.ResolveRevision(ctx, name, rev)
181 if err != nil {
182 return pinnedRef{}, err
183 }
184 pin := pinnedRef{ref: res.Ref, commit: res.CommitID, object: res.CommitID}
185 switch {
186 case strings.HasPrefix(res.Ref, "refs/heads/"):
187 return pin, nil
188 case !strings.HasPrefix(res.Ref, "refs/tags/"):
189 return pinnedRef{}, fmt.Errorf("%w: %q is not a branch or a tag", domain.ErrInvalid, given)
190 }
191 refs, err := c.cfg.Reader.ListRefs(ctx, name)
192 if err != nil {
193 return pinnedRef{}, err
194 }
195 for _, r := range refs {
196 if r.Name != res.Ref {
197 continue
198 }
199 if r.CommitID != res.CommitID || r.ID.IsZero() {
200 break // moved between the two reads
201 }
202 pin.object = r.ID
203 return pin, nil
204 }
205 return pinnedRef{}, fmt.Errorf("%w: tag %q moved while it was resolved, try again", domain.ErrConflict, res.Ref)
206}
207
208// readWorkflowAt reads a workflow file at a commit, bounded; a missing file is
209// domain.ErrNotFound.
210func (c *CI) readWorkflowAt(ctx context.Context, repo domain.RepoName, commit domain.ObjectID, wfPath string) ([]byte, error) {
211 tp, err := domain.ParseTreePath(wfPath)
212 if err != nil {
213 return nil, err
214 }
215 _, rc, err := c.cfg.Reader.OpenBlob(ctx, repo, domain.RevisionOf(commit), tp)
216 if err != nil {
217 if errors.Is(err, domain.ErrNotFound) || errors.Is(err, domain.ErrNotFile) {
218 return nil, fmt.Errorf("%w: workflow %s", domain.ErrNotFound, wfPath)
219 }
220 return nil, fmt.Errorf("read %s: %w", wfPath, err)
221 }
222 content, err := io.ReadAll(io.LimitReader(rc, maxCIWorkflowBytes+1))
223 _ = rc.Close()
224 if err != nil {
225 return nil, fmt.Errorf("read %s: %w", wfPath, err)
226 }
227 if len(content) > maxCIWorkflowBytes {
228 return nil, fmt.Errorf("%w: %s is larger than 1 MiB", domain.ErrInvalid, wfPath)
229 }
230 return content, nil
231}