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