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