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 // refs/pull/* belong to ermite (the head and the test merge of the merge
154 // requests): nobody pushes there, whatever the token, the workflow
155 // guard included.
156 if domain.IsPullRefName(up.Ref) {
157 return fmt.Errorf("%w: %s is maintained by ermite: refs/pull/* cannot be pushed", domain.ErrRejected, up.Ref)
158 }
159 if !p.AllowsRef(up.Ref) {
160 return fmt.Errorf("%w: %s is outside the branches this token may push (%s)",
161 domain.ErrRejected, up.Ref, strings.Join(p.BranchPrefixes(), ", "))
162 }
163 }
164 if p.ViaJobToken() {
165 if err := u.checkWorkflows(ctx, name, updates, objects); err != nil {
166 return err
167 }
168 }
169 log := zerowrap.FromCtx(ctx)
170 log.Debug().Str("repo", name.String()).Int("refs", len(updates)).Msg("push checked")
171 return nil
172}
173
174// workflowRefusal is GitHub's refusal of a push by the token of a job that
175// changes a workflow (a push to a branch or a tag; the token lacks the
176// "workflows" permission, which no job token can have).
177const workflowRefusal = "refusing to allow a GitHub App to create or update workflow `%s` without `workflows` permission"
178
179func (u *Pushes) checkWorkflows(ctx context.Context, name domain.RepoName, updates []domain.RefUpdate, objects ports.PushObjects) error {
180 if u.wf == nil {
181 return fmt.Errorf("%w: the token of a job may not push here", domain.ErrRejected)
182 }
183 path, err := u.wf.ChangedWorkflow(ctx, name, updates, objects)
184 switch {
185 case errors.Is(err, domain.ErrInvalid):
186 // A push the guard cannot judge within its bounds: refused, with the reason.
187 return fmt.Errorf("%w: %v", domain.ErrRejected, err)
188 case err != nil:
189 return fmt.Errorf("find the workflows changed by a push to %s: %w", name, err)
190 case path != "":
191 return fmt.Errorf("%w: "+workflowRefusal, domain.ErrRejected, path)
192 }
193 return nil
194}
195
196// Record is the post-receive step of an accepted push: it sets pushed_at,
197// repairs HEAD when it points to a missing branch, tells the reader that the
198// repository changed, queues the workflows the push triggers, publishes a
199// PushEvent and schedules maintenance. Every
200// step runs even when an earlier one fails; the failures are returned together
201// and the push itself is not affected.
202func (u *Pushes) Record(ctx context.Context, p domain.Principal, name domain.RepoName, updates []domain.RefUpdate) error {
203 log := zerowrap.FromCtx(ctx)
204 now := u.clock.Now().UTC()
205 var errs []error
206
207 repo, err := touchPushedAt(ctx, u.meta, name, now)
208 if err != nil {
209 errs = append(errs, err)
210 }
211 if err := u.fixDefaultBranch(ctx, name, updates); err != nil {
212 errs = append(errs, err)
213 }
214 if u.fresh != nil {
215 u.fresh.Refresh(ctx, name)
216 }
217 if u.ci != nil {
218 u.ci.OnPush(ctx, name, updates, p) // queues only: never slows or fails the push
219 }
220 u.bus.Publish(ctx, domain.PushEvent{
221 Repo: name, Updates: append([]domain.RefUpdate(nil), updates...), At: now,
222 Visibility: repo.Visibility, CreatedAt: repo.CreatedAt,
223 })
224 u.maint.Schedule(ctx, name)
225 log.Info().
226 Str("repo", name.String()).Int("refs", len(updates)).
227 Str("principal", p.Label()).Str("token_id", p.TokenID()).
228 Msg("push received")
229 return errors.Join(errs...)
230}
231
232// touchPushedAt stores pushed_at, retrying when another write got in between.
233// A repository deleted meanwhile is not an error. It returns the repository
234// as read, or the zero value when it is unknown. A push (Pushes.Record) and a
235// merge, which moves a branch too, both record through it.
236func touchPushedAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
237 for range pushRetries {
238 repo, err := meta.Get(ctx, name)
239 if errors.Is(err, domain.ErrNotFound) {
240 return domain.Repo{}, nil
241 }
242 if err != nil {
243 return domain.Repo{}, fmt.Errorf("get repository %q: %w", name, err)
244 }
245 if !now.After(repo.PushedAt) {
246 return repo, nil // a later push already recorded
247 }
248 repo.PushedAt = now
249 err = meta.Update(ctx, repo)
250 if errors.Is(err, domain.ErrConflict) {
251 continue
252 }
253 if errors.Is(err, domain.ErrNotFound) {
254 return domain.Repo{}, nil
255 }
256 if err != nil {
257 return repo, fmt.Errorf("update repository %q: %w", name, err)
258 }
259 return repo, nil
260 }
261 return domain.Repo{}, fmt.Errorf("update pushed_at of %q: %w", name, domain.ErrConflict)
262}
263
264// fixDefaultBranch points HEAD to a branch that exists when it points to a
265// missing one: main when it was pushed, else the first pushed branch.
266func (u *Pushes) fixDefaultBranch(ctx context.Context, name domain.RepoName, updates []domain.RefUpdate) error {
267 branch, exists, err := u.git.DefaultBranch(ctx, name)
268 if errors.Is(err, domain.ErrNotFound) {
269 return nil // deleted meanwhile
270 }
271 if err != nil {
272 return fmt.Errorf("read default branch of %q: %w", name, err)
273 }
274 if exists {
275 return nil
276 }
277 target := ""
278 for _, up := range updates {
279 b, ok := strings.CutPrefix(up.Ref, "refs/heads/")
280 if !ok || up.IsDelete() {
281 continue
282 }
283 if b == "main" {
284 target = b
285 break
286 }
287 if target == "" {
288 target = b
289 }
290 }
291 if target == "" || target == branch {
292 return nil
293 }
294 err = u.git.SetDefaultBranch(ctx, name, target)
295 if errors.Is(err, domain.ErrNotFound) {
296 return nil // deleted meanwhile
297 }
298 if err != nil {
299 return fmt.Errorf("set default branch of %q to %q: %w", name, target, err)
300 }
301 log := zerowrap.FromCtx(ctx)
302 log.Info().Str("repo", name.String()).Str("branch", target).Msg("default branch set")
303 return nil
304}