1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "strings"
10 "time"
11
12 "github.com/bnema/zerowrap"
13
14 "bnema.dev/ermite/internal/domain"
15 "bnema.dev/ermite/internal/ports"
16)
17
18// pushRetries bounds the retries of a metadata update that loses a race.
19const pushRetries = 5
20
21// Pushes are the use cases around a Git push.
22type Pushes struct {
23 meta ports.RepoMetaStore
24 repos *Repos
25 git ports.GitRepos
26 bus ports.EventBus
27 clock ports.Clock
28 maint ports.MaintenanceScheduler
29 auth ports.Revalidator
30 fresh ports.RepoFreshener // nil: the reader needs no telling
31 ci ports.WorkflowTrigger // nil: no CI
32 wf ports.WorkflowGuard // nil: pushes by job tokens are refused
33}
34
35var (
36 _ ports.PushService = (*Pushes)(nil)
37 _ ports.PushHookService = (*Pushes)(nil)
38)
39
40// NewPushes builds the push use cases. Every argument is required: auth
41// re-validates the token of a push when its pre-receive hook runs, maint
42// queues the maintenance that follows a push.
43func NewPushes(meta ports.RepoMetaStore, repos *Repos, git ports.GitRepos, bus ports.EventBus, clock ports.Clock, maint ports.MaintenanceScheduler, auth ports.Revalidator) *Pushes {
44 return &Pushes{meta: meta, repos: repos, git: git, bus: bus, clock: clock, maint: maint, auth: auth}
45}
46
47// WithFreshener makes Record tell the reader that a repository changed, so that
48// it serves the push at once. Call it before the first push; it returns u.
49func (u *Pushes) WithFreshener(f ports.RepoFreshener) *Pushes {
50 u.fresh = f
51 return u
52}
53
54// WithWorkflowTrigger makes Record start the workflows that match the push.
55// Call it before the first push; it returns u.
56func (u *Pushes) WithWorkflowTrigger(t ports.WorkflowTrigger) *Pushes {
57 u.ci = t
58 return u
59}
60
61// WithWorkflowGuard lets Check tell whether a push changes workflow files, which
62// a push by a job token may not do. Without it a push by a job token is
63// refused, as it cannot be judged. Call it before the first push; it returns u.
64func (u *Pushes) WithWorkflowGuard(g ports.WorkflowGuard) *Pushes {
65 u.wf = g
66 return u
67}
68
69// Open decides whether the principal may push to the repository and, with
70// create, creates it when it does not exist yet (private, published as
71// RepoCreated by Repos.Create). create is for the first request of a push only.
72//
73// Anonymous callers get domain.ErrUnauthenticated. A repository the caller
74// cannot read and cannot write, or a missing one it may not create, answers
75// domain.ErrNotFound, so that a private repository never shows itself. One it
76// can read but not write answers domain.ErrForbidden.
77func (u *Pushes) Open(ctx context.Context, p domain.Principal, name domain.RepoName, create bool) error {
78 if p.IsAnonymous() {
79 return domain.ErrUnauthenticated
80 }
81 repo, err := u.meta.Get(ctx, name)
82 switch {
83 case err == nil:
84 return openExisting(p, repo)
85 case !errors.Is(err, domain.ErrNotFound):
86 return fmt.Errorf("get repository %q: %w", name, err)
87 }
88
89 if !create || !canCreateRepo(p, name) {
90 return domain.ErrNotFound
91 }
92 _, err = u.repos.Create(ctx, p, ports.CreateRepoParams{Name: name, Visibility: domain.VisibilityPrivate})
93 switch {
94 case err == nil:
95 return nil // Create published RepoCreated
96 case errors.Is(err, domain.ErrAlreadyExists):
97 // A concurrent first push won the race: this one pushes to its repository.
98 repo, gerr := u.meta.Get(ctx, name)
99 if gerr != nil {
100 return fmt.Errorf("get repository %q: %w", name, gerr)
101 }
102 return openExisting(p, repo)
103 }
104 return err
105}
106
107func openExisting(p domain.Principal, repo domain.Repo) error {
108 switch {
109 case canWrite(p, repo.Name):
110 return nil
111 case canRead(p, repo):
112 return domain.ErrForbidden
113 }
114 return domain.ErrNotFound
115}
116
117// Check is the pre-receive decision. It accepts a push of a principal that
118// may write the repository. A token limited to branch prefixes may only update
119// (create, move or delete) branches under them: the first ref outside them
120// refuses the whole push, tags and every other ref included. Further rules
121// (protected branches, limits) will refuse here too, by returning an error
122// that matches domain.ErrRejected.
123//
124// The prefix rule is domain.Principal.AllowsRef and shares its assumptions: no
125// symbolic ref under refs/heads besides HEAD (ermite never creates one and
126// receive-pack cannot), and case-sensitive ref storage (Linux). The hook sees
127// every ref of the push, so a tag or any other ref is judged like a branch.
128//
129// The token of the push was valid when the request began, but a push can run
130// for long: it is re-validated here, so a token revoked or expired meanwhile
131// stops the push before Git applies it. A failure to tell refuses it too.
132//
133// The token of a CI job (GITHUB_TOKEN with contents: write) may not change
134// workflows (CI-3, D3). The push is refused as a whole, on any ref, branch or
135// tag, when a commit it brings changes .github/workflows (it has workflows that
136// differ from those of every parent; removing them is allowed), or when a ref
137// would end with workflows other than it had: an update with other than the old
138// ones, a new ref with other than those of the default branch head (or any, when
139// there is no head). A new branch cut from existing commits that change nothing
140// is therefore allowed; deleting a ref is not a change. objects locate the
141// objects of the push, which are not in the repository yet.
142func (u *Pushes) Check(ctx context.Context, p domain.Principal, name domain.RepoName, updates []domain.RefUpdate, objects ports.PushObjects) error {
143 if err := u.auth.Revalidate(ctx, p); err != nil {
144 if errors.Is(err, domain.ErrUnauthenticated) {
145 return fmt.Errorf("%w: the token is no longer valid", domain.ErrRejected)
146 }
147 return fmt.Errorf("revalidate token: %w", err)
148 }
149 if !canWrite(p, name) {
150 return fmt.Errorf("%w: no write access to %s", domain.ErrRejected, name)
151 }
152 for _, up := range updates {
153 if !p.AllowsRef(up.Ref) {
154 return fmt.Errorf("%w: %s is outside the branches this token may push (%s)",
155 domain.ErrRejected, up.Ref, strings.Join(p.BranchPrefixes(), ", "))
156 }
157 }
158 if p.ViaJobToken() {
159 if err := u.checkWorkflows(ctx, name, updates, objects); err != nil {
160 return err
161 }
162 }
163 log := zerowrap.FromCtx(ctx)
164 log.Debug().Str("repo", name.String()).Int("refs", len(updates)).Msg("push checked")
165 return nil
166}
167
168// workflowRefusal is GitHub's refusal of a push by the token of a job that
169// changes a workflow (a push to a branch or a tag; the token lacks the
170// "workflows" permission, which no job token can have).
171const workflowRefusal = "refusing to allow a GitHub App to create or update workflow `%s` without `workflows` permission"
172
173func (u *Pushes) checkWorkflows(ctx context.Context, name domain.RepoName, updates []domain.RefUpdate, objects ports.PushObjects) error {
174 if u.wf == nil {
175 return fmt.Errorf("%w: the token of a job may not push here", domain.ErrRejected)
176 }
177 path, err := u.wf.ChangedWorkflow(ctx, name, updates, objects)
178 switch {
179 case errors.Is(err, domain.ErrInvalid):
180 // A push the guard cannot judge within its bounds: refused, with the reason.
181 return fmt.Errorf("%w: %v", domain.ErrRejected, err)
182 case err != nil:
183 return fmt.Errorf("find the workflows changed by a push to %s: %w", name, err)
184 case path != "":
185 return fmt.Errorf("%w: "+workflowRefusal, domain.ErrRejected, path)
186 }
187 return nil
188}
189
190// Record is the post-receive step of an accepted push: it sets pushed_at,
191// repairs HEAD when it points to a missing branch, tells the reader that the
192// repository changed, queues the workflows the push triggers, publishes a
193// PushEvent and schedules maintenance. Every
194// step runs even when an earlier one fails; the failures are returned together
195// and the push itself is not affected.
196func (u *Pushes) Record(ctx context.Context, p domain.Principal, name domain.RepoName, updates []domain.RefUpdate) error {
197 log := zerowrap.FromCtx(ctx)
198 now := u.clock.Now().UTC()
199 var errs []error
200
201 repo, err := touchPushedAt(ctx, u.meta, name, now)
202 if err != nil {
203 errs = append(errs, err)
204 }
205 if err := u.fixDefaultBranch(ctx, name, updates); err != nil {
206 errs = append(errs, err)
207 }
208 if u.fresh != nil {
209 u.fresh.Refresh(ctx, name)
210 }
211 if u.ci != nil {
212 u.ci.OnPush(ctx, name, updates, p) // queues only: never slows or fails the push
213 }
214 u.bus.Publish(ctx, domain.PushEvent{
215 Repo: name, Updates: append([]domain.RefUpdate(nil), updates...), At: now,
216 Visibility: repo.Visibility, CreatedAt: repo.CreatedAt,
217 })
218 u.maint.Schedule(ctx, name)
219 log.Info().
220 Str("repo", name.String()).Int("refs", len(updates)).
221 Str("principal", p.Label()).Str("token_id", p.TokenID()).
222 Msg("push received")
223 return errors.Join(errs...)
224}
225
226// touchPushedAt stores pushed_at, retrying when another write got in between.
227// A repository deleted meanwhile is not an error. It returns the repository
228// as read, or the zero value when it is unknown. A push (Pushes.Record) and a
229// merge, which moves a branch too, both record through it.
230func touchPushedAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
231 for range pushRetries {
232 repo, err := meta.Get(ctx, name)
233 if errors.Is(err, domain.ErrNotFound) {
234 return domain.Repo{}, nil
235 }
236 if err != nil {
237 return domain.Repo{}, fmt.Errorf("get repository %q: %w", name, err)
238 }
239 if !now.After(repo.PushedAt) {
240 return repo, nil // a later push already recorded
241 }
242 repo.PushedAt = now
243 err = meta.Update(ctx, repo)
244 if errors.Is(err, domain.ErrConflict) {
245 continue
246 }
247 if errors.Is(err, domain.ErrNotFound) {
248 return domain.Repo{}, nil
249 }
250 if err != nil {
251 return repo, fmt.Errorf("update repository %q: %w", name, err)
252 }
253 return repo, nil
254 }
255 return domain.Repo{}, fmt.Errorf("update pushed_at of %q: %w", name, domain.ErrConflict)
256}
257
258// fixDefaultBranch points HEAD to a branch that exists when it points to a
259// missing one: main when it was pushed, else the first pushed branch.
260func (u *Pushes) fixDefaultBranch(ctx context.Context, name domain.RepoName, updates []domain.RefUpdate) error {
261 branch, exists, err := u.git.DefaultBranch(ctx, name)
262 if errors.Is(err, domain.ErrNotFound) {
263 return nil // deleted meanwhile
264 }
265 if err != nil {
266 return fmt.Errorf("read default branch of %q: %w", name, err)
267 }
268 if exists {
269 return nil
270 }
271 target := ""
272 for _, up := range updates {
273 b, ok := strings.CutPrefix(up.Ref, "refs/heads/")
274 if !ok || up.IsDelete() {
275 continue
276 }
277 if b == "main" {
278 target = b
279 break
280 }
281 if target == "" {
282 target = b
283 }
284 }
285 if target == "" || target == branch {
286 return nil
287 }
288 err = u.git.SetDefaultBranch(ctx, name, target)
289 if errors.Is(err, domain.ErrNotFound) {
290 return nil // deleted meanwhile
291 }
292 if err != nil {
293 return fmt.Errorf("set default branch of %q to %q: %w", name, target, err)
294 }
295 log := zerowrap.FromCtx(ctx)
296 log.Info().Str("repo", name.String()).Str("branch", target).Msg("default branch set")
297 return nil
298}