Commit 93d98753bc

93d98753bcf8e3c5ee2363651c3d66ac019a65e5

parent: 5ff173ff22

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-10-23 04:38 UTC

Fold duplicated and deeply nested code into helpers

- sshd: Exec and runGit take Backend and Streams; the push watchdog
  is cutStalledPush.
- store: userBy, removeKey, updateText and setItemUser replace pairs
  of identical queries.
- control: runRepoItemAction (webhook/mirror remove, redeliver),
  setRepoMark (pin, bookmark), aliasPaths; setItemMilestone checks
  archived and args.
- httpd: readme and wiki links share rewriteRelativeTargets; split
  rows are built per file and per pair.
- protocol, mailin: double-quoted strings and comments read in their
  own functions.
- cli: keys add and pgp add share runWithStdin.
- Qlty: function_parameters threshold 8; ignore the store's row-scan
  loops for duplication.

Layout: unified · split

.qlty/qlty.toml +8
@@ -76,3 +76,11 @@ enabled = false
7676
7777[smells.file_complexity]
7878enabled = false
79
80# Six or seven parameters is ordinary for an unexported Go helper.
81[smells.function_parameters]
82threshold = 8
83
84# The store's hand-written queries each scan their rows in the same loop.
85[language.go.smells.duplication]
86filter_patterns = ["(import_declaration _)", "(for_statement (call_expression function: (selector_expression field: (field_identifier) @_f)) (#eq? @_f \"Next\"))"]
cmd/gitbay/main.go +16 −26
@@ -8,6 +8,7 @@ import (
88 "fmt"
99 "io"
1010 "os"
11 "slices"
1112 "strings"
1213
1314 "github.com/spf13/cobra"
@@ -379,7 +380,7 @@ func isEmptyReader(r io.Reader) bool {
379380// usesStdin reports whether the arguments request stdin content.
380381func usesStdin(args []string) bool {
381382 for i, a := range args {
382 if (a == "--file" || a == "--key" || a == "--secret") && i+1 < len(args) && args[i+1] == "-" {
383 if slices.Contains([]string{"--file", "--key", "--secret"}, a) && i+1 < len(args) && args[i+1] == "-" {
383384 return true
384385 }
385386 if a == "--token-stdin" {
@@ -475,27 +476,33 @@ func local(use, short string, fn func(args []string) int) *cobra.Command {
475476 }
476477}
477478
478func authCmd() *cobra.Command {
479 keysAdd := pass("add", passOpts{server: []string{"keys", "add"}, alwaysStdin: true, stdinWhat: "an SSH public key"})
480 // keys add always reads stdin on the server; wire it through directly.
481 keysAdd.RunE = func(cmd *cobra.Command, args []string) error {
479// runWithStdin runs the server command with the args and what, read
480// from stdin, as its payload.
481func runWithStdin(server []string, what string) func(*cobra.Command, []string) error {
482 return func(cmd *cobra.Command, args []string) error {
482483 cliPath := cliPathOf(cmd)
483484 for _, a := range args {
484485 if a == "--help" || a == "-h" {
485 os.Exit(runServerHelp(passOpts{server: []string{"keys", "add"}}, cliPath))
486 os.Exit(runServerHelp(passOpts{server: server}, cliPath))
486487 }
487488 }
488489 t, err := resolveTarget()
489490 if err != nil {
490491 return err
491492 }
492 in, err := stdinPayload(os.Stdin, "an SSH public key", false)
493 in, err := stdinPayload(os.Stdin, what, false)
493494 if err != nil {
494495 return err
495496 }
496 os.Exit(runSSH(t, withCLIPath(cliPath, "keys add", append([]string{"keys", "add"}, args...)), in))
497 os.Exit(runSSH(t, withCLIPath(cliPath, strings.Join(server, " "), slices.Concat(server, args)), in))
497498 return nil
498499 }
500}
501
502func authCmd() *cobra.Command {
503 keysAdd := pass("add", passOpts{server: []string{"keys", "add"}, alwaysStdin: true, stdinWhat: "an SSH public key"})
504 // keys add always reads stdin on the server; wire it through directly.
505 keysAdd.RunE = runWithStdin([]string{"keys", "add"}, "an SSH public key")
499506 pgpAdd := &cobra.Command{
500507 Use: "add", Short: "register an OpenPGP public key (armored, on stdin)",
501508 Annotations: map[string]string{
@@ -504,24 +511,7 @@ func authCmd() *cobra.Command {
504511 stdinWhat: "an armored OpenPGP public key",
505512 },
506513 DisableFlagParsing: true,
507 RunE: func(cmd *cobra.Command, args []string) error {
508 cliPath := cliPathOf(cmd)
509 for _, a := range args {
510 if a == "--help" || a == "-h" {
511 os.Exit(runServerHelp(passOpts{server: []string{"pgp", "add"}}, cliPath))
512 }
513 }
514 t, err := resolveTarget()
515 if err != nil {
516 return err
517 }
518 in, err := stdinPayload(os.Stdin, "an armored OpenPGP public key", false)
519 if err != nil {
520 return err
521 }
522 os.Exit(runSSH(t, withCLIPath(cliPath, "pgp add", append([]string{"pgp", "add"}, args...)), in))
523 return nil
524 },
514 RunE: runWithStdin([]string{"pgp", "add"}, "an armored OpenPGP public key"),
525515 }
526516 tokens := group("token", "API tokens (minted over SSH, used with the JSON API)",
527517 pass("create", passOpts{server: []string{"token", "create"}}),
cmd/gitbayd/system.go +1 −1
@@ -101,7 +101,7 @@ func shellCmd() *cobra.Command {
101101 }
102102 // Each forced command is its own process, so there is no
103103 // shared pack or push budget in system mode.
104 code := sshd.Exec(cfg, st, nil, nil, user, key, control.ParseTerm(os.Getenv("GITBAY_TERM")), cmdline, os.Stdin, os.Stdout, os.Stderr, nil, nil, nil)
104 code := sshd.Exec(sshd.Backend{Cfg: cfg, St: st}, user, key, control.ParseTerm(os.Getenv("GITBAY_TERM")), cmdline, sshd.Streams{Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr})
105105 st.Close()
106106 os.Exit(code)
107107 return nil
internal/config/config.go +2 −2
@@ -682,8 +682,8 @@ func (c Config) Validate() error {
682682 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
683683 }
684684 }
685 if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 ||
686 c.Limits.MaxOrgsPerUser < 0 || c.Limits.MaxReposPerOrg < 0 || c.Limits.MaxBytesPerOrg < 0 {
685 if min(c.Limits.MaxReposPerUser, c.Limits.MaxSnippetsPerUser, c.Limits.MaxOrgsPerUser, c.Limits.MaxReposPerOrg) < 0 ||
686 min(c.Limits.MaxBytesPerUser, c.Limits.MaxBytesPerOrg) < 0 {
687687 errs = append(errs, errors.New("limits.max_repos_per_user, max_bytes_per_user, max_snippets_per_user, max_orgs_per_user, max_repos_per_org and max_bytes_per_org must not be negative"))
688688 }
689689 for _, w := range []struct{ name, val string }{
internal/control/help.go +17 −9
@@ -111,6 +111,22 @@ type helpEntry struct {
111111 Examples []string `json:"examples,omitempty"`
112112}
113113
114// aliasPaths maps each registered command path under an aliased noun to
115// the path the CLI shows for it.
116func aliasPaths(aliased []nounAlias) map[string]string {
117 paths := map[string]string{}
118 for _, cmd := range registry {
119 p := joinPath(cmd.Path)
120 for _, a := range aliased {
121 if p == a.Registered || strings.HasPrefix(p, a.Registered+" ") {
122 paths[p] = a.CLI + strings.TrimPrefix(p, a.Registered)
123 break
124 }
125 }
126 }
127 return paths
128}
129
114130// runHelp lists the registry, sorted, so a noun's commands sit together.
115131// Bare `help` stays one line per command. A prefix that names one command
116132// exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a
@@ -125,15 +141,7 @@ func runHelp(c *Ctx, args []string) int {
125141 prefixes = append(prefixes, a.Registered)
126142 }
127143 if c.CLIPath != "" {
128 for _, cmd := range registry {
129 p := joinPath(cmd.Path)
130 for _, a := range aliased {
131 if p == a.Registered || strings.HasPrefix(p, a.Registered+" ") {
132 override[p] = a.CLI + strings.TrimPrefix(p, a.Registered)
133 break
134 }
135 }
136 }
144 override = aliasPaths(aliased)
137145 }
138146 }
139147 var matched []Command
internal/control/milestone.go +12 −16
@@ -217,13 +217,7 @@ func runIssueMilestone(c *Ctx, args []string) int {
217217 if code >= 0 {
218218 return code
219219 }
220 if code := refuseArchived(c, repo); code >= 0 {
221 return code
222 }
223 if len(args) != 3 {
224 return c.usage()
225 }
226 return setItemMilestone(c, repo, "issue", issue.Number, args[2], func(id int64) error {
220 return setItemMilestone(c, repo, args, "issue", issue.Number, func(id int64) error {
227221 return c.Store.SetIssueMilestone(issue.ID, id)
228222 })
229223}
@@ -233,13 +227,7 @@ func runMRMilestone(c *Ctx, args []string) int {
233227 if code >= 0 {
234228 return code
235229 }
236 if code := refuseArchived(c, repo); code >= 0 {
237 return code
238 }
239 if len(args) != 3 {
240 return c.usage()
241 }
242 return setItemMilestone(c, repo, "mr", mr.Number, args[2], func(id int64) error {
230 return setItemMilestone(c, repo, args, "mr", mr.Number, func(id int64) error {
243231 return c.Store.SetMRMilestone(mr.ID, id)
244232 })
245233}
@@ -255,8 +243,16 @@ func recordItemMilestone(c *Ctx, repo store.Repo, noun string, number, id int64,
255243 return nil
256244}
257245
258// noun and number name what the milestone was set on, for the event.
259func setItemMilestone(c *Ctx, repo store.Repo, noun string, number int64, title string, set func(int64) error) int {
246// setItemMilestone sets the milestone args[2] titles through set. noun and
247// number name what it was set on, for the event.
248func setItemMilestone(c *Ctx, repo store.Repo, args []string, noun string, number int64, set func(int64) error) int {
249 if code := refuseArchived(c, repo); code >= 0 {
250 return code
251 }
252 if len(args) != 3 {
253 return c.usage()
254 }
255 title := args[2]
260256 var id int64
261257 if title != "none" {
262258 m, err := c.Store.MilestoneByTitle(repo, title)
internal/control/mirrorcmd.go +1 −20
@@ -166,26 +166,7 @@ func orDash(s string) string {
166166}
167167
168168func runMirrorRemove(c *Ctx, args []string) int {
169 if len(args) != 2 {
170 return c.usage()
171 }
172 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
173 if code >= 0 {
174 return code
175 }
176 id, err := strconv.ParseInt(args[1], 10, 64)
177 if err != nil {
178 return c.fail(protocol.ExitUsage, "bad mirror id %q", args[1])
179 }
180 if err := c.Store.RemoveMirror(repo.ID, id); err != nil {
181 if errors.Is(err, store.ErrNotFound) {
182 return c.fail(protocol.ExitNotFound, "no mirror %d on %s", id, repo.Path())
183 }
184 return c.fail(protocol.ExitFailure, "%v", err)
185 }
186 return c.emit(map[string]any{"removed": id}, func(w io.Writer) {
187 fmt.Fprintf(w, "removed mirror %d\n", id)
188 })
169 return runRepoItemAction(c, args, "mirror", c.Store.RemoveMirror, "removed", "removed mirror %d")
189170}
190171
191172func runMirrorSync(c *Ctx, args []string) int {
internal/control/querylang.go +1 −1
@@ -69,7 +69,7 @@ func queryTokens(s string) (toks []string, quoted []bool, err error) {
6969 startQuoted = true
7070 }
7171 in, have = !in, true
72 case !in && (r == ' ' || r == '\t' || r == '\n' || r == '\r'):
72 case !in && strings.ContainsRune(" \t\n\r", r):
7373 flush()
7474 default:
7575 cur.WriteRune(r)
internal/control/repo.go +22 −40
@@ -1266,10 +1266,12 @@ func runRepoPin(c *Ctx, args []string) int { return setPinned(c, args, true) }
12661266func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
12671267
12681268func setPinned(c *Ctx, args []string, pin bool) int {
1269 verb := "pin"
1270 if !pin {
1271 verb = "unpin"
1272 }
1269 return setRepoMark(c, args, pin, "pinned", "unpinned", c.Store.PinRepo, c.Store.UnpinRepo)
1270}
1271
1272// setRepoMark marks a repository the caller can read with mark, or clears
1273// it with unmark; done and undone are the words the output uses.
1274func setRepoMark(c *Ctx, args []string, on bool, done, undone string, mark, unmark func(userID, repoID int64) error) int {
12731275 if len(args) != 1 {
12741276 return c.usage()
12751277 }
@@ -1277,53 +1279,33 @@ func setPinned(c *Ctx, args []string, pin bool) int {
12771279 if code >= 0 {
12781280 return code
12791281 }
1280 if pin {
1281 if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
1282 word := done
1283 if on {
1284 if err := mark(c.User.ID, repo.ID); err != nil {
12821285 return c.fail(protocol.ExitFailure, "%v", err)
12831286 }
1284 } else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
1285 if errors.Is(err, store.ErrNotFound) {
1286 return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
1287 } else {
1288 word = undone
1289 if err := unmark(c.User.ID, repo.ID); err != nil {
1290 if errors.Is(err, store.ErrNotFound) {
1291 return c.fail(protocol.ExitNotFound, "%s is not %s", repo.Path(), done)
1292 }
1293 return c.fail(protocol.ExitFailure, "%v", err)
12871294 }
1288 return c.fail(protocol.ExitFailure, "%v", err)
12891295 }
1290 return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
1291 fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
1296 return c.emit(map[string]string{word: repo.Path()}, func(w io.Writer) {
1297 fmt.Fprintf(w, "%s %s\n", word, repo.Path())
12921298 })
12931299}
12941300
12951301func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) }
12961302func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
12971303
1298// setBookmarked mirrors setPinned. A bookmark needs only read access —
1299// bookmarking is something you do to someone else's repository, which is
1300// the whole point of it — and a private repository you cannot read is
1301// not found, as everywhere.
1304// A bookmark needs only read access — bookmarking is something you do to
1305// someone else's repository, which is the whole point of it — and a
1306// private repository you cannot read is not found, as everywhere.
13021307func setBookmarked(c *Ctx, args []string, on bool) int {
1303 verb := "bookmark"
1304 if !on {
1305 verb = "unbookmark"
1306 }
1307 if len(args) != 1 {
1308 return c.usage()
1309 }
1310 repo, code := resolveRepo(c, args[0], policy.CanRead)
1311 if code >= 0 {
1312 return code
1313 }
1314 if on {
1315 if err := c.Store.BookmarkRepo(c.User.ID, repo.ID); err != nil {
1316 return c.fail(protocol.ExitFailure, "%v", err)
1317 }
1318 } else if err := c.Store.UnbookmarkRepo(c.User.ID, repo.ID); err != nil {
1319 if errors.Is(err, store.ErrNotFound) {
1320 return c.fail(protocol.ExitNotFound, "%s is not bookmarked", repo.Path())
1321 }
1322 return c.fail(protocol.ExitFailure, "%v", err)
1323 }
1324 return c.emit(map[string]string{verb + "ed": repo.Path()}, func(w io.Writer) {
1325 fmt.Fprintf(w, "%sed %s\n", verb, repo.Path())
1326 })
1308 return setRepoMark(c, args, on, "bookmarked", "unbookmarked", c.Store.BookmarkRepo, c.Store.UnbookmarkRepo)
13271309}
13281310
13291311// BookmarkOut is one row of `repo bookmarks`: the repository and how many
internal/control/webhook.go +12 −25
@@ -164,6 +164,12 @@ func runWebhookList(c *Ctx, args []string) int {
164164}
165165
166166func runWebhookRemove(c *Ctx, args []string) int {
167 return runRepoItemAction(c, args, "webhook", c.Store.RemoveWebhook, "removed", "removed webhook %d")
168}
169
170// runRepoItemAction runs act on the <owner/name> <id> in args for a repo
171// admin and reports the id under key, with done as the plain line.
172func runRepoItemAction(c *Ctx, args []string, noun string, act func(repoID, id int64) error, key, done string) int {
167173 if len(args) != 2 {
168174 return c.usage()
169175 }
@@ -173,16 +179,16 @@ func runWebhookRemove(c *Ctx, args []string) int {
173179 }
174180 id, err := strconv.ParseInt(args[1], 10, 64)
175181 if err != nil {
176 return c.fail(protocol.ExitUsage, "bad webhook id %q", args[1])
182 return c.fail(protocol.ExitUsage, "bad %s id %q", noun, args[1])
177183 }
178 if err := c.Store.RemoveWebhook(repo.ID, id); err != nil {
184 if err := act(repo.ID, id); err != nil {
179185 if errors.Is(err, store.ErrNotFound) {
180 return c.fail(protocol.ExitNotFound, "no webhook %d on %s", id, repo.Path())
186 return c.fail(protocol.ExitNotFound, "no %s %d on %s", noun, id, repo.Path())
181187 }
182188 return c.fail(protocol.ExitFailure, "%v", err)
183189 }
184 return c.emit(map[string]any{"removed": id}, func(w io.Writer) {
185 fmt.Fprintf(w, "removed webhook %d\n", id)
190 return c.emit(map[string]any{key: id}, func(w io.Writer) {
191 fmt.Fprintf(w, done+"\n", id)
186192 })
187193}
188194
@@ -265,24 +271,5 @@ func runWebhookDeliveries(c *Ctx, args []string) int {
265271}
266272
267273func runWebhookRedeliver(c *Ctx, args []string) int {
268 if len(args) != 2 {
269 return c.usage()
270 }
271 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
272 if code >= 0 {
273 return code
274 }
275 id, err := strconv.ParseInt(args[1], 10, 64)
276 if err != nil {
277 return c.fail(protocol.ExitUsage, "bad delivery id %q", args[1])
278 }
279 if err := c.Store.Redeliver(repo.ID, id); err != nil {
280 if errors.Is(err, store.ErrNotFound) {
281 return c.fail(protocol.ExitNotFound, "no delivery %d on %s", id, repo.Path())
282 }
283 return c.fail(protocol.ExitFailure, "%v", err)
284 }
285 return c.emit(map[string]any{"requeued": id}, func(w io.Writer) {
286 fmt.Fprintf(w, "delivery %d requeued\n", id)
287 })
274 return runRepoItemAction(c, args, "delivery", c.Store.Redeliver, "requeued", "delivery %d requeued")
288275}
internal/deps/python.go +33 −26
@@ -37,35 +37,42 @@ func parsePython(read ReadFile) []Dep {
3737 }
3838 }
3939 if raw, err := read("pyproject.toml"); err == nil {
40 var doc struct {
41 Project struct {
42 Dependencies []string `toml:"dependencies"`
43 } `toml:"project"`
44 Tool struct {
45 Poetry struct {
46 Dependencies map[string]any `toml:"dependencies"`
47 DevDependencies map[string]any `toml:"dev-dependencies"`
48 } `toml:"poetry"`
49 } `toml:"tool"`
50 }
51 if toml.Unmarshal(raw, &doc) == nil {
52 for _, spec := range doc.Project.Dependencies {
53 name, version := splitPEP508(spec)
54 add(name, version)
55 }
56 poetry := doc.Tool.Poetry
57 for _, set := range []map[string]any{poetry.Dependencies, poetry.DevDependencies} {
58 for name, spec := range set {
59 // Poetry shares Cargo's two forms: a bare string, or a
60 // table that may point somewhere other than PyPI.
61 if req, ok := cargoRequirement(spec); ok {
62 add(name, req)
63 }
64 }
40 pyprojectDeps(raw, add)
41 }
42 return out
43}
44
45// pyprojectDeps adds the dependencies a pyproject.toml lists under
46// [project] and [tool.poetry].
47func pyprojectDeps(raw []byte, add func(name, version string)) {
48 var doc struct {
49 Project struct {
50 Dependencies []string `toml:"dependencies"`
51 } `toml:"project"`
52 Tool struct {
53 Poetry struct {
54 Dependencies map[string]any `toml:"dependencies"`
55 DevDependencies map[string]any `toml:"dev-dependencies"`
56 } `toml:"poetry"`
57 } `toml:"tool"`
58 }
59 if toml.Unmarshal(raw, &doc) != nil {
60 return
61 }
62 for _, spec := range doc.Project.Dependencies {
63 name, version := splitPEP508(spec)
64 add(name, version)
65 }
66 poetry := doc.Tool.Poetry
67 for _, set := range []map[string]any{poetry.Dependencies, poetry.DevDependencies} {
68 for name, spec := range set {
69 // Poetry shares Cargo's two forms: a bare string, or a
70 // table that may point somewhere other than PyPI.
71 if req, ok := cargoRequirement(spec); ok {
72 add(name, req)
6573 }
6674 }
6775 }
68 return out
6976}
7077
7178// splitPEP508 separates the distribution name from its version specifier,
internal/httpd/diff.go +82 −73
@@ -334,86 +334,95 @@ type diffLayout struct {
334334// forms are attached to the lines.
335335func splitFiles(files []diffFile) {
336336 for f := range files {
337 lines := files[f].Lines
338 var rows []splitRow
339 for i := 0; i < len(lines); {
340 ln := &lines[i]
341 switch ln.Class {
342 case "hunk", "meta":
343 if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) {
344 // a marker after a context line: neither side ends in a newline
345 if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New {
346 last.OldNote, last.NewNote = ln.Text, ln.Text
347 i++
348 continue
349 }
350 }
351 rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text})
352 i++
353 case "ctx":
354 r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads}
355 if ln.Compose {
356 r.Compose = ln
357 }
358 rows = append(rows, r)
359 i++
360 default:
361 var dels, adds []*diffLine
362 marker := func() string {
363 if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) {
364 i++
365 return lines[i-1].Text
366 }
367 return ""
368 }
369 var oldNote, newNote string
370 for i < len(lines) && lines[i].Class == "del" {
371 dels = append(dels, &lines[i])
372 i++
373 }
374 if len(dels) > 0 {
375 oldNote = marker()
376 }
377 for i < len(lines) && lines[i].Class == "add" {
378 adds = append(adds, &lines[i])
337 files[f].Rows = splitRows(files[f].Lines)
338 }
339}
340
341// splitRows pairs one file's deletions with its additions, side by side.
342func splitRows(lines []diffLine) []splitRow {
343 var rows []splitRow
344 for i := 0; i < len(lines); {
345 ln := &lines[i]
346 switch ln.Class {
347 case "hunk", "meta":
348 if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) {
349 // a marker after a context line: neither side ends in a newline
350 if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New {
351 last.OldNote, last.NewNote = ln.Text, ln.Text
379352 i++
380 }
381 if len(adds) > 0 {
382 newNote = marker()
383 }
384 if len(dels)+len(adds) == 0 {
385 i++ // an unknown class: skip rather than loop
386353 continue
387354 }
388 first := len(rows)
389 for k := 0; k < len(dels) || k < len(adds); k++ {
390 r := splitRow{Kind: "pair"}
391 for _, l := range []*diffLine{pick(dels, k), pick(adds, k)} {
392 if l == nil {
393 continue
394 }
395 if l.Class == "del" {
396 r.Old = l
397 } else {
398 r.New = l
399 }
400 r.Threads = append(r.Threads, l.Threads...)
401 if l.Compose {
402 r.Compose = l
403 }
404 }
405 rows = append(rows, r)
406 }
407 if len(dels) > 0 {
408 rows[first+len(dels)-1].OldNote = oldNote
409 }
410 if len(adds) > 0 {
411 rows[first+len(adds)-1].NewNote = newNote
355 }
356 rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text})
357 i++
358 case "ctx":
359 r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads}
360 if ln.Compose {
361 r.Compose = ln
362 }
363 rows = append(rows, r)
364 i++
365 default:
366 var dels, adds []*diffLine
367 marker := func() string {
368 if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) {
369 i++
370 return lines[i-1].Text
412371 }
372 return ""
373 }
374 var oldNote, newNote string
375 for i < len(lines) && lines[i].Class == "del" {
376 dels = append(dels, &lines[i])
377 i++
378 }
379 if len(dels) > 0 {
380 oldNote = marker()
381 }
382 for i < len(lines) && lines[i].Class == "add" {
383 adds = append(adds, &lines[i])
384 i++
385 }
386 if len(adds) > 0 {
387 newNote = marker()
388 }
389 if len(dels)+len(adds) == 0 {
390 i++ // an unknown class: skip rather than loop
391 continue
392 }
393 first := len(rows)
394 for k := 0; k < len(dels) || k < len(adds); k++ {
395 rows = append(rows, pairRow(pick(dels, k), pick(adds, k)))
413396 }
397 if len(dels) > 0 {
398 rows[first+len(dels)-1].OldNote = oldNote
399 }
400 if len(adds) > 0 {
401 rows[first+len(adds)-1].NewNote = newNote
402 }
403 }
404 }
405 return rows
406}
407
408// pairRow is the row showing del beside add; either may be nil.
409func pairRow(del, add *diffLine) splitRow {
410 r := splitRow{Kind: "pair"}
411 for _, l := range []*diffLine{del, add} {
412 if l == nil {
413 continue
414 }
415 if l.Class == "del" {
416 r.Old = l
417 } else {
418 r.New = l
419 }
420 r.Threads = append(r.Threads, l.Threads...)
421 if l.Compose {
422 r.Compose = l
414423 }
415 files[f].Rows = rows
416424 }
425 return r
417426}
418427
419428func pick(s []*diffLine, i int) *diffLine {
internal/httpd/readme.go +48 −25
@@ -16,6 +16,37 @@ import (
1616// go-org exports .org links as .html, so an .html target whose .org (or
1717// .md) source exists in the tree maps back to the source file.
1818func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) template.HTML {
19 return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) {
20 target := path.Clean(path.Join(baseDir, v))
21 if strings.HasPrefix(target, "..") {
22 return "", false
23 }
24 if src {
25 return "/" + p.Repo.Path() + "/raw/" + p.Ref + "/" + target, true
26 }
27 return "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + exportSource(p, target), true
28 })
29}
30
31// exportSource maps an .html target back to the .org or .md file in the
32// tree it was exported from, if there is one.
33func exportSource(p repoPage, target string) string {
34 stem, ok := strings.CutSuffix(target, ".html")
35 if !ok {
36 return target
37 }
38 for _, ext := range []string{".org", ".md"} {
39 if _, err := gitutil.ReadBlob(p.Dir, p.Ref, stem+ext, 1); err == nil {
40 return stem + ext
41 }
42 }
43 return target
44}
45
46// rewriteRelativeTargets passes each relative link href and img, video or
47// source src in rendered to rewrite (src is true for the media), and sets
48// the attribute to what it returns when ok.
49func rewriteRelativeTargets(rendered template.HTML, rewrite func(v string, src bool) (string, bool)) template.HTML {
1950 ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div}
2051 nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx)
2152 if err != nil {
@@ -27,34 +58,12 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te
2758 for i, a := range n.Attr {
2859 isHref := a.Key == "href" && n.Data == "a"
2960 isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source")
30 if !isHref && !isSrc {
31 continue
32 }
33 v := a.Val
34 if v == "" || strings.Contains(v, "://") || strings.HasPrefix(v, "/") ||
35 strings.HasPrefix(v, "#") || strings.HasPrefix(v, "mailto:") ||
36 strings.HasPrefix(v, "data:") {
37 continue
38 }
39 target := path.Clean(path.Join(baseDir, v))
40 if strings.HasPrefix(target, "..") {
41 continue
42 }
43 if isSrc {
44 n.Attr[i].Val = "/" + p.Repo.Path() + "/raw/" + p.Ref + "/" + target
61 if (!isHref && !isSrc) || !isRelativeTarget(a.Val) {
4562 continue
4663 }
47 // .html from org/markdown exports maps back to the source.
48 if strings.HasSuffix(target, ".html") {
49 stem := strings.TrimSuffix(target, ".html")
50 for _, ext := range []string{".org", ".md"} {
51 if _, err := gitutil.ReadBlob(p.Dir, p.Ref, stem+ext, 1); err == nil {
52 target = stem + ext
53 break
54 }
55 }
64 if v, ok := rewrite(a.Val, isSrc); ok {
65 n.Attr[i].Val = v
5666 }
57 n.Attr[i].Val = "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + target
5867 }
5968 }
6069 for c := n.FirstChild; c != nil; c = c.NextSibling {
@@ -70,3 +79,17 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te
7079 }
7180 return template.HTML(out.String())
7281}
82
83// isRelativeTarget is false for empty targets, absolute URLs, rooted
84// paths, fragments, mailto: and data:.
85func isRelativeTarget(v string) bool {
86 if v == "" || strings.Contains(v, "://") {
87 return false
88 }
89 for _, prefix := range []string{"/", "#", "mailto:", "data:"} {
90 if strings.HasPrefix(v, prefix) {
91 return false
92 }
93 }
94 return true
95}
internal/httpd/wiki.go +15 −51
@@ -7,9 +7,6 @@ import (
77 "sort"
88 "strings"
99
10 "golang.org/x/net/html"
11 "golang.org/x/net/html/atom"
12
1310 "gitbay.org/gitbay/internal/control"
1411 "gitbay.org/gitbay/internal/gitutil"
1512 "gitbay.org/gitbay/internal/store"
@@ -229,56 +226,23 @@ func trimPageExt(target string) string {
229226// other relative targets (images) to the wiki raw route. Targets resolve
230227// from the current page's folder, as wikiResolve describes.
231228func rewriteWikiLinks(rendered template.HTML, p repoPage, page string, isPage, isFile func(string) bool) template.HTML {
232 ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div}
233 nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx)
234 if err != nil {
235 return rendered
236 }
237229 base := "/" + p.Repo.Path() + "/wiki"
238 var walk func(*html.Node)
239 walk = func(n *html.Node) {
240 if n.Type == html.ElementNode {
241 for i, a := range n.Attr {
242 isHref := a.Key == "href" && n.Data == "a"
243 isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source")
244 if !isHref && !isSrc {
245 continue
246 }
247 v := a.Val
248 if v == "" || strings.Contains(v, "://") || strings.HasPrefix(v, "/") ||
249 strings.HasPrefix(v, "#") || strings.HasPrefix(v, "mailto:") ||
250 strings.HasPrefix(v, "data:") {
251 continue
252 }
253 if isSrc {
254 if target, ok := wikiResolve(page, v, isFile); ok {
255 n.Attr[i].Val = base + "/_raw/" + target
256 }
257 continue
258 }
259 // A plain link is usually to another page, but a link to
260 // an existing non-page file (an .svg, .txt, .pdf) must
261 // go to _raw the same as an image src, or it 404s
262 // against the page route (#283).
263 if target, ok := wikiResolve(page, trimPageExt(v), isPage); ok {
264 if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) {
265 n.Attr[i].Val = base + "/_raw/" + raw
266 } else {
267 n.Attr[i].Val = base + "/" + target
268 }
269 }
270 }
230 return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) {
231 if src {
232 target, ok := wikiResolve(page, v, isFile)
233 return base + "/_raw/" + target, ok
271234 }
272 for c := n.FirstChild; c != nil; c = c.NextSibling {
273 walk(c)
235 // A plain link is usually to another page, but a link to an
236 // existing non-page file (an .svg, .txt, .pdf) must go to _raw
237 // the same as an image src, or it 404s against the page route
238 // (#283).
239 target, ok := wikiResolve(page, trimPageExt(v), isPage)
240 if !ok {
241 return "", false
274242 }
275 }
276 var out strings.Builder
277 for _, n := range nodes {
278 walk(n)
279 if err := html.Render(&out, n); err != nil {
280 return rendered
243 if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) {
244 return base + "/_raw/" + raw, true
281245 }
282 }
283 return template.HTML(out.String())
246 return base + "/" + target, true
247 })
284248}
internal/mailin/authres.go +21 −16
@@ -83,22 +83,7 @@ func tokenize(s string) []token {
8383 joined = false
8484 i++
8585 case c == '(':
86 depth := 0
87 for ; i < len(s); i++ {
88 if s[i] == '\\' {
89 i++
90 continue
91 }
92 if s[i] == '(' {
93 depth++
94 } else if s[i] == ')' {
95 depth--
96 if depth == 0 {
97 i++
98 break
99 }
100 }
101 }
86 i = commentEnd(s, i)
10287 joined = false
10388 case c == '"':
10489 var b strings.Builder
@@ -133,6 +118,26 @@ func tokenize(s string) []token {
133118 return out
134119}
135120
121// commentEnd is the index just past the comment opening at s[i], with
122// nested parentheses and backslash escapes; past the end when unclosed.
123func commentEnd(s string, i int) int {
124 depth := 0
125 for ; i < len(s); i++ {
126 switch s[i] {
127 case '\\':
128 i++
129 case '(':
130 depth++
131 case ')':
132 depth--
133 if depth == 0 {
134 return i + 1
135 }
136 }
137 }
138 return i
139}
140
136141// splitResults splits tokens at each ";".
137142func splitResults(ts []token) [][]token {
138143 segs := [][]token{nil}
internal/notify/notify.go +20 −13
@@ -50,24 +50,31 @@ func (m *Mailer) Run(ctx context.Context) {
5050 continue
5151 }
5252 for _, q := range due {
53 if err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body); err != nil {
54 attempt := q.Attempts + 1
55 if attempt >= m.MaxAttempts {
56 m.St.MarkMailFailed(q.ID, err.Error(), nil)
57 slog.Warn("notification dead-lettered",
58 "mail", q.ID, "attempts", attempt, "err", redactAddresses(err.Error()))
59 } else {
60 next := time.Now().Add(m.RetryBase << (attempt - 1))
61 m.St.MarkMailFailed(q.ID, err.Error(), &next)
62 }
63 continue
64 }
65 m.St.MarkMailSent(q.ID)
53 m.deliver(q)
6654 }
6755 }
6856 }
6957}
7058
59// deliver sends one queued mail, marking it sent, due again after a
60// backoff, or failed once it has had MaxAttempts.
61func (m *Mailer) deliver(q store.QueuedMail) {
62 err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body)
63 if err == nil {
64 m.St.MarkMailSent(q.ID)
65 return
66 }
67 attempt := q.Attempts + 1
68 if attempt >= m.MaxAttempts {
69 m.St.MarkMailFailed(q.ID, err.Error(), nil)
70 slog.Warn("notification dead-lettered",
71 "mail", q.ID, "attempts", attempt, "err", redactAddresses(err.Error()))
72 return
73 }
74 next := time.Now().Add(m.RetryBase << (attempt - 1))
75 m.St.MarkMailFailed(q.ID, err.Error(), &next)
76}
77
7178// A relay's rejection usually quotes the address it rejected — "550 5.1.1
7279// <x@y>: Recipient address rejected" — so dropping the recipient field
7380// alone would not keep an address out of the log.
internal/protocol/tokenize.go +22 −25
@@ -39,28 +39,9 @@ func Tokenize(s string) ([]string, error) {
3939 i += end + 2
4040 case c == '"':
4141 inWord = true
42 i++
43 closed := false
44 for i < len(s) {
45 c = s[i]
46 if c == '"' {
47 closed = true
48 i++
49 break
50 }
51 if c == '\\' && i+1 < len(s) {
52 switch s[i+1] {
53 case '\\', '"', '$', '`':
54 cur.WriteByte(s[i+1])
55 i += 2
56 continue
57 }
58 }
59 cur.WriteByte(c)
60 i++
61 }
62 if !closed {
63 return nil, errors.New("unterminated double quote")
42 var err error
43 if i, err = doubleQuoted(s, i, &cur); err != nil {
44 return nil, err
6445 }
6546 case c == '\\':
6647 if i+1 >= len(s) {
@@ -69,9 +50,7 @@ func Tokenize(s string) ([]string, error) {
6950 inWord = true
7051 cur.WriteByte(s[i+1])
7152 i += 2
72 case c == '$' || c == '`' || c == ';' || c == '&' || c == '|' ||
73 c == '<' || c == '>' || c == '(' || c == ')' || c == '*' ||
74 c == '?' || c == '[' || c == '#' || c == '~':
53 case strings.IndexByte("$`;&|<>()*?[#~", c) >= 0:
7554 // Unquoted shell metacharacters are rejected outright rather
7655 // than passed through: there is no shell here, and silently
7756 // treating them as literals would mask client quoting bugs.
@@ -87,3 +66,21 @@ func Tokenize(s string) ([]string, error) {
8766 }
8867 return argv, nil
8968}
69
70// doubleQuoted writes the double-quoted string opening at s[i] to cur,
71// unescaping \\, \", \$ and \`, and returns the index past its closing
72// quote.
73func doubleQuoted(s string, i int, cur *strings.Builder) (int, error) {
74 for i++; i < len(s); i++ {
75 c := s[i]
76 if c == '"' {
77 return i + 1, nil
78 }
79 if c == '\\' && i+1 < len(s) && strings.IndexByte("\\\"$`", s[i+1]) >= 0 {
80 i++
81 c = s[i]
82 }
83 cur.WriteByte(c)
84 }
85 return i, errors.New("unterminated double quote")
86}
internal/sshd/pushlimit_test.go +8 −8
@@ -35,8 +35,8 @@ func TestSilentPushKilledAtReceiveTimeout(t *testing.T) {
3535 codec := make(chan int, 1)
3636 start := time.Now()
3737 go func() {
38 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
39 silentStdin(t), io.Discard, io.Discard, nil, nil, nil)
38 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
39 Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard})
4040 }()
4141 slotTaken(t, pushes)
4242 pushEnded(t, codec, pushes, 5*time.Second)
@@ -66,8 +66,8 @@ func TestPushKilledAtIdleOncePackStarts(t *testing.T) {
6666 codec := make(chan int, 1)
6767 start := time.Now()
6868 go func() {
69 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
70 r, io.Discard, io.Discard, nil, nil, nil)
69 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
70 Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard})
7171 }()
7272 slotTaken(t, pushes)
7373 // The signature split across two writes still arms the rule.
@@ -116,8 +116,8 @@ func TestPushSilentBeforePackCompletes(t *testing.T) {
116116 pw.Close()
117117 }()
118118 var errOut strings.Builder
119 if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
120 pr, io.Discard, &errOut, nil, nil, nil); code != 0 {
119 if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
120 Streams{Stdin: pr, Stdout: io.Discard, Stderr: &errOut}); code != 0 {
121121 t.Fatalf("exit %d: %s", code, errOut.String())
122122 }
123123 out, err := exec.Command("git", "-C", control.RepoDir(cfg.Server.Root, "alice", "app"), "rev-parse", "refs/heads/main").Output()
@@ -160,8 +160,8 @@ func TestTricklingPushKilledAtReceiveTimeout(t *testing.T) {
160160 codec := make(chan int, 1)
161161 start := time.Now()
162162 go func() {
163 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
164 r, io.Discard, io.Discard, nil, nil, nil)
163 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
164 Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard})
165165 }()
166166 slotTaken(t, pushes)
167167 pushEnded(t, codec, pushes, 5*time.Second)
internal/sshd/refusal_test.go +22 −22
@@ -58,8 +58,8 @@ func TestRefusedPushIsAudited(t *testing.T) {
5858 bob.Pending = pending
5959 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
6060 var out, errOut bytes.Buffer
61 code := Exec(cfg, st, nil, nil, bob, key, control.Term{}, "git-receive-pack alice/app",
62 strings.NewReader(""), &out, &errOut, nil, nil, nil)
61 code := Exec(Backend{Cfg: cfg, St: st}, bob, key, control.Term{}, "git-receive-pack alice/app",
62 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
6363 if code != protocol.ExitDenied {
6464 t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String())
6565 }
@@ -85,8 +85,8 @@ func TestCloneRefusedWhenPackSlotsAreFull(t *testing.T) {
8585 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
8686 for _, service := range []string{"git-upload-pack", "git-upload-archive"} {
8787 var out, errOut bytes.Buffer
88 code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, service+" alice/app",
89 strings.NewReader(""), &out, &errOut, nil, nil, nil)
88 code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, service+" alice/app",
89 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
9090 if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") {
9191 t.Fatalf("%s: exit %d: %q", service, code, errOut.String())
9292 }
@@ -108,8 +108,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) {
108108 packs := packlimit.New(1, 0, 0, time.Second)
109109
110110 var out, errOut bytes.Buffer
111 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app",
112 strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK {
111 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
112 Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK {
113113 t.Fatalf("clone: exit %d: %s", code, errOut.String())
114114 }
115115 hold, err := packs.Acquire(nil, "ip:elsewhere")
@@ -120,8 +120,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) {
120120
121121 out.Reset()
122122 errOut.Reset()
123 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-receive-pack alice/app",
124 strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK {
123 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-receive-pack alice/app",
124 Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK {
125125 t.Fatalf("push with slots full: exit %d: %s", code, errOut.String())
126126 }
127127}
@@ -161,8 +161,8 @@ func killedClone(t *testing.T, stdout io.Writer, done, stopping, revoked <-chan
161161 packs := packlimit.New(1, 0, 0, time.Second)
162162 codec := make(chan int, 1)
163163 go func() {
164 codec <- Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app",
165 silentStdin(t), stdout, io.Discard, done, stopping, revoked)
164 codec <- Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
165 Streams{Stdin: silentStdin(t), Stdout: stdout, Stderr: io.Discard, Done: done, Stopping: stopping, Revoked: revoked})
166166 }()
167167 select {
168168 case code := <-codec:
@@ -210,8 +210,8 @@ func TestCloneRunsOnDuringRestart(t *testing.T) {
210210 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
211211 packs := packlimit.New(1, 0, 0, time.Second)
212212 var errOut bytes.Buffer
213 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app",
214 strings.NewReader("0000"), io.Discard, &errOut, closed(), closed(), nil); code != protocol.ExitOK {
213 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
214 Streams{Stdin: strings.NewReader("0000"), Stdout: io.Discard, Stderr: &errOut, Done: closed(), Stopping: closed()}); code != protocol.ExitOK {
215215 t.Fatalf("exit %d: %s", code, errOut.String())
216216 }
217217}
@@ -235,8 +235,8 @@ func TestRefusedCloneStaysOffLimiter(t *testing.T) {
235235 defer hold()
236236 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
237237 var out, errOut bytes.Buffer
238 code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, "git-upload-pack alice/secret",
239 strings.NewReader(""), &out, &errOut, nil, nil, nil)
238 code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, "git-upload-pack alice/secret",
239 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
240240 if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") {
241241 t.Fatalf("exit %d: %q", code, errOut.String())
242242 }
@@ -282,8 +282,8 @@ func TestPushPerPrincipalCap(t *testing.T) {
282282 push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int {
283283 codec := make(chan int, 1)
284284 go func() {
285 codec <- Exec(cfg, st, nil, pushes, alice, k, control.Term{}, "git-receive-pack alice/app",
286 stdin, io.Discard, errOut, nil, nil, nil)
285 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, k, control.Term{}, "git-receive-pack alice/app",
286 Streams{Stdin: stdin, Stdout: io.Discard, Stderr: errOut})
287287 }()
288288 return codec
289289 }
@@ -320,8 +320,8 @@ func TestPushPerPrincipalCap(t *testing.T) {
320320 queuedFor(t, pushes, principal)
321321
322322 var errOut bytes.Buffer
323 if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
324 strings.NewReader(""), io.Discard, &errOut, nil, nil, nil); code != protocol.ExitFailure ||
323 if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
324 Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut}); code != protocol.ExitFailure ||
325325 !strings.Contains(errOut.String(), "limit of concurrent pushes") {
326326 t.Fatalf("third push: exit %d: %q", code, errOut.String())
327327 }
@@ -354,8 +354,8 @@ func TestPushKilledWhenKeyRevokedReleasesSlot(t *testing.T) {
354354 revoked := make(chan struct{})
355355 codec := make(chan int, 1)
356356 go func() {
357 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app",
358 silentStdin(t), io.Discard, io.Discard, nil, nil, revoked)
357 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
358 Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard, Revoked: revoked})
359359 }()
360360 slotTaken(t, pushes)
361361 close(revoked)
@@ -407,8 +407,8 @@ func TestRefusedPushStaysOffLimiter(t *testing.T) {
407407 defer hold()
408408 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
409409 var errOut bytes.Buffer
410 code := Exec(cfg, st, nil, pushes, bob, key, control.Term{}, "git-receive-pack alice/app",
411 strings.NewReader(""), io.Discard, &errOut, nil, nil, nil)
410 code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, bob, key, control.Term{}, "git-receive-pack alice/app",
411 Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut})
412412 if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") {
413413 t.Fatalf("exit %d: %q", code, errOut.String())
414414 }
internal/sshd/sshd.go +58 −35
@@ -427,7 +427,8 @@ func (s *Server) runExec(c *conn, sconn *ssh.ServerConn, ch ssh.Channel, term co
427427 return protocol.ExitDenied
428428 }
429429 _ = s.st.TouchSSHKey(keyID)
430 return Exec(s.cfg, s.st, s.packs, s.pushes, user, key, term, cmdline, ch, ch, ch.Stderr(), done, s.stopping, c.revoked)
430 return Exec(Backend{Cfg: s.cfg, St: s.st, Packs: s.packs, Pushes: s.pushes}, user, key, term, cmdline,
431 Streams{Stdin: ch, Stdout: ch, Stderr: ch.Stderr(), Done: done, Stopping: s.stopping, Revoked: c.revoked})
431432}
432433
433434// runAnonymous handles a session from an unregistered key: the register
@@ -460,13 +461,29 @@ func (s *Server) runAnonymous(ch ssh.Channel, keyB64, cmdline string) int {
460461 return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr())
461462}
462463
464// Backend is what a command runs against. Packs bounds clones and fetches,
465// and repo download; Pushes bounds receive-pack. A nil limiter is no limit.
466type Backend struct {
467 Cfg config.Config
468 St *store.Store
469 Packs, Pushes *packlimit.Limiter
470}
471
472// Streams are a command's input and output and the channels that end it.
473// Closing Revoked kills a git transport.
474type Streams struct {
475 Stdin io.Reader
476 Stdout, Stderr io.Writer
477 Done, Stopping, Revoked <-chan struct{}
478}
479
463480// Exec runs one SSH exec command line for an authenticated key. It is the
464481// single dispatch path shared by the embedded listener and the system-sshd
465// forced command (gitbayd shell). Closing revoked kills a git transport.
466// packs bounds clones and fetches, and repo download; pushes bounds
467// receive-pack. A nil limiter is no limit.
468func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, user store.User, key store.SSHKey, term control.Term, cmdline string,
469 stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) int {
482// forced command (gitbayd shell).
483func Exec(b Backend, user store.User, key store.SSHKey, term control.Term, cmdline string, s Streams) int {
484 cfg, st, packs := b.Cfg, b.St, b.Packs
485 stdin, stdout, stderr := s.Stdin, s.Stdout, s.Stderr
486 done, stopping := s.Done, s.Stopping
470487 // A person signing in with a full-scope key cancels a scheduled
471488 // deletion; automation on narrower keys is refused and cannot.
472489 if user.Disabled && user.DeleteAfter != "" && key.Scope == "full" && control.CancelScheduledDeletion(st, &user, "ssh") {
@@ -492,7 +509,7 @@ func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter,
492509 if user.Pending {
493510 fmt.Fprintln(stderr, "your account is not active yet: verify your email first")
494511 } else {
495 code = runGit(cfg, st, packs, pushes, user, key, argv, stdin, stdout, stderr, done, stopping, revoked)
512 code = runGit(b, user, key, argv, s)
496513 }
497514 // A refused push is a refused write, audited like one. runGit
498515 // refuses only with the path as the one argument, so argv[1:]
@@ -530,9 +547,40 @@ func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter,
530547 return control.Dispatch(ctx, argv)
531548}
532549
550// cutStalledPush closes kill and the client's streams when the key is
551// revoked, the push goes idle, or receiving fires before pre-receive has
552// started. started arms the idle rule and retires receiving. It returns
553// when finished closes.
554func cutStalledPush(finished, started, revoked, idle <-chan struct{}, receiving <-chan time.Time, arm func(), kill chan struct{}, client ...any) {
555 for {
556 select {
557 case <-finished:
558 return
559 case <-started:
560 arm()
561 started, receiving = nil, nil
562 continue
563 case <-revoked:
564 case <-idle:
565 case <-receiving:
566 }
567 close(kill)
568 // A read blocked on a silent client outlives git; closing the
569 // channel ends it and the stdin copy, so Transport's Wait returns.
570 for _, c := range client {
571 if c, ok := c.(io.Closer); ok {
572 c.Close()
573 }
574 }
575 return
576 }
577}
578
533579// runGit streams a git transport service after access checks.
534func runGit(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, user store.User, key store.SSHKey, argv []string,
535 stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) int {
580func runGit(b Backend, user store.User, key store.SSHKey, argv []string, s Streams) int {
581 cfg, st, packs, pushes := b.Cfg, b.St, b.Packs, b.Pushes
582 stdin, stdout, stderr := s.Stdin, s.Stdout, s.Stderr
583 done, stopping, revoked := s.Done, s.Stopping, s.Revoked
536584 service, scope := argv[0], key.Scope
537585 if len(argv) != 2 {
538586 fmt.Fprintf(stderr, "usage: %s <path>\n", service)
@@ -663,32 +711,7 @@ func runGit(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter
663711 kill := make(chan struct{})
664712 finished := make(chan struct{})
665713 defer close(finished)
666 go func() {
667 receiving := deadline.C
668 for {
669 select {
670 case <-finished:
671 return
672 case <-started:
673 arm()
674 started, receiving = nil, nil
675 continue
676 case <-revoked:
677 case <-idle:
678 case <-receiving:
679 }
680 close(kill)
681 // A read blocked on a silent client outlives git;
682 // closing the channel ends it and the stdin copy, so
683 // Transport's Wait returns.
684 for _, c := range []any{client, clientOut} {
685 if c, ok := c.(io.Closer); ok {
686 c.Close()
687 }
688 }
689 return
690 }
691 }()
714 go cutStalledPush(finished, started, revoked, idle, deadline.C, arm, kill, client, clientOut)
692715 cancel = kill
693716 }
694717 }
internal/store/issues.go +16 −6
@@ -264,6 +264,12 @@ func (s *Store) QueryIssues(repoID int64, f IssueFilter) ([]Issue, error) {
264264// UpdateIssueText edits title, body, and/or markup format; nil leaves a field
265265// unchanged.
266266func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) error {
267 return s.updateText("issues", issueID, title, body, format)
268}
269
270// updateText sets whichever of title, body and body_format are given on
271// the row of table with id, and its updated_at.
272func (s *Store) updateText(table string, id int64, title, body, format *string) error {
267273 set, args := []string{}, []any{}
268274 if title != nil {
269275 set, args = append(set, "title = ?"), append(args, *title)
@@ -278,8 +284,8 @@ func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) erro
278284 return nil
279285 }
280286 set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')")
281 args = append(args, issueID)
282 res, err := s.DB.Exec("UPDATE issues SET "+strings.Join(set, ", ")+" WHERE id = ?", args...)
287 args = append(args, id)
288 res, err := s.DB.Exec("UPDATE "+table+" SET "+strings.Join(set, ", ")+" WHERE id = ?", args...)
283289 if err != nil {
284290 return err
285291 }
@@ -388,14 +394,18 @@ func (s *Store) SetIssueLabel(repo Repo, issueID int64, name string, add bool) e
388394
389395// SetIssueAssignee adds or removes an assignee by user id.
390396func (s *Store) SetIssueAssignee(issueID, userID int64, add bool) error {
397 return s.setItemUser("issue_assignees", "issue_id", issueID, userID, add)
398}
399
400// setItemUser adds or removes the (item, user) row of a join table.
401func (s *Store) setItemUser(table, itemCol string, itemID, userID int64, add bool) error {
391402 if add {
392403 _, err := s.DB.Exec(
393 "INSERT INTO issue_assignees (issue_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
394 issueID, userID)
404 "INSERT INTO "+table+" ("+itemCol+", user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
405 itemID, userID)
395406 return err
396407 }
397 res, err := s.DB.Exec(
398 "DELETE FROM issue_assignees WHERE issue_id = ? AND user_id = ?", issueID, userID)
408 res, err := s.DB.Exec("DELETE FROM "+table+" WHERE "+itemCol+" = ? AND user_id = ?", itemID, userID)
399409 if err != nil {
400410 return err
401411 }
internal/store/mrs.go +2 −38
@@ -164,21 +164,7 @@ func (s *Store) SetMRLabel(repo Repo, mrID int64, name string, add bool) error {
164164// SetMRReviewRequest adds or removes a review request by user id — the
165165// mr review request counterpart of SetIssueAssignee.
166166func (s *Store) SetMRReviewRequest(mrID, userID int64, add bool) error {
167 if add {
168 _, err := s.DB.Exec(
169 "INSERT INTO mr_review_requests (mr_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
170 mrID, userID)
171 return err
172 }
173 res, err := s.DB.Exec(
174 "DELETE FROM mr_review_requests WHERE mr_id = ? AND user_id = ?", mrID, userID)
175 if err != nil {
176 return err
177 }
178 if n, _ := res.RowsAffected(); n == 0 {
179 return ErrNotFound
180 }
181 return nil
167 return s.setItemUser("mr_review_requests", "mr_id", mrID, userID, add)
182168}
183169
184170// MRReviewRequestIDs returns who has been asked for a review, by id — for
@@ -496,29 +482,7 @@ func (s *Store) AddMRComment(mrID, authorID int64, body, format string) error {
496482// UpdateMRText edits title, body, and/or markup format; nil leaves a field
497483// unchanged.
498484func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error {
499 set, args := []string{}, []any{}
500 if title != nil {
501 set, args = append(set, "title = ?"), append(args, *title)
502 }
503 if body != nil {
504 set, args = append(set, "body = ?"), append(args, *body)
505 }
506 if format != nil {
507 set, args = append(set, "body_format = ?"), append(args, *format)
508 }
509 if len(set) == 0 {
510 return nil
511 }
512 set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')")
513 args = append(args, mrID)
514 res, err := s.DB.Exec("UPDATE merge_requests SET "+strings.Join(set, ", ")+" WHERE id = ?", args...)
515 if err != nil {
516 return err
517 }
518 if n, _ := res.RowsAffected(); n == 0 {
519 return ErrNotFound
520 }
521 return nil
485 return s.updateText("merge_requests", mrID, title, body, format)
522486}
523487
524488// AddMRSystemComment is the informational counterpart of AddMRComment.
internal/store/users.go +16 −38
@@ -140,20 +140,7 @@ func (s *Store) OwnerExists(name string) bool {
140140}
141141
142142func (s *Store) UserByUsername(name string) (User, error) {
143 var u User
144 var admin, pending, disabled, ghost int
145 var deleteAfter sql.NullString
146 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE username = ?", name).
147 Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost)
148 if errors.Is(err, sql.ErrNoRows) {
149 return u, ErrNotFound
150 }
151 u.IsAdmin = admin != 0
152 u.Pending = pending != 0
153 u.Disabled = disabled != 0
154 u.DeleteAfter = deleteAfter.String
155 u.Ghost = ghost != 0
156 return u, err
143 return s.userBy("username", name)
157144}
158145
159146// UserEmailAddresses returns every address on the account, verified or not.
@@ -333,10 +320,15 @@ func (s *Store) SetDiffLayout(userID int64, layout string) error {
333320}
334321
335322func (s *Store) UserByID(id int64) (User, error) {
323 return s.userBy("id", id)
324}
325
326// userBy reads the account whose column equals v.
327func (s *Store) userBy(column string, v any) (User, error) {
336328 var u User
337329 var admin, pending, disabled, ghost int
338330 var deleteAfter sql.NullString
339 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE id = ?", id).
331 err := s.DB.QueryRow("SELECT id, username, is_admin, pending, disabled, delete_after, ghost FROM users WHERE "+column+" = ?", v).
340332 Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost)
341333 if errors.Is(err, sql.ErrNoRows) {
342334 return u, ErrNotFound
@@ -388,13 +380,19 @@ func (s *Store) AddSSHKeyFrom(userID int64, fingerprint, algo string, blob []byt
388380// RemoveSSHKey removes a key owned by userID, bumps the key epoch, and
389381// announces the revocation.
390382func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error {
383 return s.removeKey("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ? RETURNING id", userID, fingerprint)
384}
385
386// removeKey deletes the key that query (a DELETE ... RETURNING id)
387// matches, bumps the key epoch, and announces the revocation.
388func (s *Store) removeKey(query string, args ...any) error {
391389 tx, err := s.DB.Begin()
392390 if err != nil {
393391 return err
394392 }
395393 defer tx.Rollback()
396394 var id int64
397 err = tx.QueryRow("DELETE FROM ssh_keys WHERE user_id = ? AND fingerprint = ? RETURNING id", userID, fingerprint).Scan(&id)
395 err = tx.QueryRow(query, args...).Scan(&id)
398396 if errors.Is(err, sql.ErrNoRows) {
399397 return ErrNotFound
400398 }
@@ -647,27 +645,7 @@ func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) {
647645// RemoveDeployKey removes a deploy key from a repository by fingerprint;
648646// any repo admin may remove it regardless of who added it.
649647func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error {
650 tx, err := s.DB.Begin()
651 if err != nil {
652 return err
653 }
654 defer tx.Rollback()
655 var id int64
656 err = tx.QueryRow(
648 return s.removeKey(
657649 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id",
658 fingerprint, repoID).Scan(&id)
659 if errors.Is(err, sql.ErrNoRows) {
660 return ErrNotFound
661 }
662 if err != nil {
663 return err
664 }
665 if err := bumpKeyEpoch(tx); err != nil {
666 return err
667 }
668 if err := tx.Commit(); err != nil {
669 return err
670 }
671 s.announce(Revoked{KeyIDs: []int64{id}})
672 return nil
650 fingerprint, repoID)
673651}
internal/symbols/extract.go +10 −7
@@ -162,6 +162,11 @@ func extractGo(data []byte) []Symbol {
162162 }
163163 out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line})
164164 }
165 addNames := func(ids []*ast.Ident, kind string) {
166 for _, id := range ids {
167 add(id, id.Name, kind)
168 }
169 }
165170 for _, d := range f.Decls {
166171 switch d := d.(type) {
167172 case *ast.FuncDecl:
@@ -176,18 +181,16 @@ func extractGo(data []byte) []Symbol {
176181 }
177182 add(d.Name, recv+"."+d.Name.Name, "method")
178183 case *ast.GenDecl:
184 kind := "var"
185 if d.Tok == token.CONST {
186 kind = "const"
187 }
179188 for _, spec := range d.Specs {
180189 switch s := spec.(type) {
181190 case *ast.TypeSpec:
182191 add(s.Name, s.Name.Name, "type")
183192 case *ast.ValueSpec:
184 kind := "var"
185 if d.Tok == token.CONST {
186 kind = "const"
187 }
188 for _, n := range s.Names {
189 add(n, n.Name, kind)
190 }
193 addNames(s.Names, kind)
191194 }
192195 }
193196 }
internal/termtext/markdown.go +5 −5
@@ -80,12 +80,12 @@ func (r mdRenderer) block(n ast.Node, first, rest string) {
8080 for c := item.FirstChild(); c != nil; c = c.NextSibling() {
8181 if c == item.FirstChild() {
8282 r.block(c, p+marker, hang)
83 } else {
84 if !n.IsTight {
85 r.w.blank()
86 }
87 r.block(c, hang, hang)
83 continue
8884 }
85 if !n.IsTight {
86 r.w.blank()
87 }
88 r.block(c, hang, hang)
8989 }
9090 p = rest
9191 }
internal/texmath/texmath.go +15 −2
@@ -66,7 +66,7 @@ func Convert(tex string, display bool) (string, error) {
6666 return "", errors.New("texmath: invalid UTF-8")
6767 }
6868 for _, r := range tex {
69 if r < 0x20 && r != '\t' && r != '\n' && r != '\r' || r == 0x7F || r == 0xFFFE || r == 0xFFFF {
69 if isControl(r) {
7070 return "", errors.New("texmath: control character")
7171 }
7272 }
@@ -206,6 +206,19 @@ func (p *parser) next() token {
206206var starred = map[string]bool{"operatorname": true}
207207
208208func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
209func isDigit(c byte) bool { return c >= '0' && c <= '9' }
210
211// isControl is a C0 control other than tab and the line ends, DEL, or
212// the noncharacters U+FFFE and U+FFFF.
213func isControl(r rune) bool {
214 switch r {
215 case '\t', '\n', '\r':
216 return false
217 case 0x7F, 0xFFFE, 0xFFFF:
218 return true
219 }
220 return r < 0x20
221}
209222
210223func (p *parser) unexpected(t token) error {
211224 switch t.kind {
@@ -402,7 +415,7 @@ func (p *parser) charAtom(t token) (*node, error) {
402415 num := t.val
403416 for p.pos < len(p.src) {
404417 c := p.src[p.pos]
405 if c >= '0' && c <= '9' || c == '.' && p.pos+1 < len(p.src) && p.src[p.pos+1] >= '0' && p.src[p.pos+1] <= '9' {
418 if isDigit(c) || c == '.' && p.pos+1 < len(p.src) && isDigit(p.src[p.pos+1]) {
406419 num += string(c)
407420 p.pos++
408421 continue