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