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
76 76
77[smells.file_complexity] 77[smells.file_complexity]
78enabled = false 78enabled = 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 (
8 "fmt" 8 "fmt"
9 "io" 9 "io"
10 "os" 10 "os"
11 "slices"
11 "strings" 12 "strings"
12 13
13 "github.com/spf13/cobra" 14 "github.com/spf13/cobra"
@@ -379,7 +380,7 @@ func isEmptyReader(r io.Reader) bool {
379// usesStdin reports whether the arguments request stdin content. 380// usesStdin reports whether the arguments request stdin content.
380func usesStdin(args []string) bool { 381func usesStdin(args []string) bool {
381 for i, a := range args { 382 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] == "-" {
383 return true 384 return true
384 } 385 }
385 if a == "--token-stdin" { 386 if a == "--token-stdin" {
@@ -475,27 +476,33 @@ func local(use, short string, fn func(args []string) int) *cobra.Command {
475 } 476 }
476} 477}
477 478
478func authCmd() *cobra.Command { 479// runWithStdin runs the server command with the args and what, read
479 keysAdd := pass("add", passOpts{server: []string{"keys", "add"}, alwaysStdin: true, stdinWhat: "an SSH public key"}) 480// from stdin, as its payload.
480 // keys add always reads stdin on the server; wire it through directly. 481func runWithStdin(server []string, what string) func(*cobra.Command, []string) error {
481 keysAdd.RunE = func(cmd *cobra.Command, args []string) error { 482 return func(cmd *cobra.Command, args []string) error {
482 cliPath := cliPathOf(cmd) 483 cliPath := cliPathOf(cmd)
483 for _, a := range args { 484 for _, a := range args {
484 if a == "--help" || a == "-h" { 485 if a == "--help" || a == "-h" {
485 os.Exit(runServerHelp(passOpts{server: []string{"keys", "add"}}, cliPath)) 486 os.Exit(runServerHelp(passOpts{server: server}, cliPath))
486 } 487 }
487 } 488 }
488 t, err := resolveTarget() 489 t, err := resolveTarget()
489 if err != nil { 490 if err != nil {
490 return err 491 return err
491 } 492 }
492 in, err := stdinPayload(os.Stdin, "an SSH public key", false) 493 in, err := stdinPayload(os.Stdin, what, false)
493 if err != nil { 494 if err != nil {
494 return err 495 return err
495 } 496 }
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))
497 return nil 498 return nil
498 } 499 }
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")
499 pgpAdd := &cobra.Command{ 506 pgpAdd := &cobra.Command{
500 Use: "add", Short: "register an OpenPGP public key (armored, on stdin)", 507 Use: "add", Short: "register an OpenPGP public key (armored, on stdin)",
501 Annotations: map[string]string{ 508 Annotations: map[string]string{
@@ -504,24 +511,7 @@ func authCmd() *cobra.Command {
504 stdinWhat: "an armored OpenPGP public key", 511 stdinWhat: "an armored OpenPGP public key",
505 }, 512 },
506 DisableFlagParsing: true, 513 DisableFlagParsing: true,
507 RunE: func(cmd *cobra.Command, args []string) error { 514 RunE: runWithStdin([]string{"pgp", "add"}, "an armored OpenPGP public key"),
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 },
525 } 515 }
526 tokens := group("token", "API tokens (minted over SSH, used with the JSON API)", 516 tokens := group("token", "API tokens (minted over SSH, used with the JSON API)",
527 pass("create", passOpts{server: []string{"token", "create"}}), 517 pass("create", passOpts{server: []string{"token", "create"}}),
cmd/gitbayd/system.go +1 −1
@@ -101,7 +101,7 @@ func shellCmd() *cobra.Command {
101 } 101 }
102 // Each forced command is its own process, so there is no 102 // Each forced command is its own process, so there is no
103 // shared pack or push budget in system mode. 103 // 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})
105 st.Close() 105 st.Close()
106 os.Exit(code) 106 os.Exit(code)
107 return nil 107 return nil
internal/config/config.go +2 −2
@@ -682,8 +682,8 @@ func (c Config) Validate() error {
682 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry)) 682 errs = append(errs, fmt.Errorf("registration.pending_expiry %q must be a positive duration such as 168h", c.Registration.PendingExpiry))
683 } 683 }
684 } 684 }
685 if c.Limits.MaxReposPerUser < 0 || c.Limits.MaxBytesPerUser < 0 || c.Limits.MaxSnippetsPerUser < 0 || 685 if min(c.Limits.MaxReposPerUser, c.Limits.MaxSnippetsPerUser, c.Limits.MaxOrgsPerUser, c.Limits.MaxReposPerOrg) < 0 ||
686 c.Limits.MaxOrgsPerUser < 0 || c.Limits.MaxReposPerOrg < 0 || c.Limits.MaxBytesPerOrg < 0 { 686 min(c.Limits.MaxBytesPerUser, c.Limits.MaxBytesPerOrg) < 0 {
687 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")) 687 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"))
688 } 688 }
689 for _, w := range []struct{ name, val string }{ 689 for _, w := range []struct{ name, val string }{
internal/control/help.go +17 −9
@@ -111,6 +111,22 @@ type helpEntry struct {
111 Examples []string `json:"examples,omitempty"` 111 Examples []string `json:"examples,omitempty"`
112} 112}
113 113
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
114// runHelp lists the registry, sorted, so a noun's commands sit together. 130// runHelp lists the registry, sorted, so a noun's commands sit together.
115// Bare `help` stays one line per command. A prefix that names one command 131// Bare `help` stays one line per command. A prefix that names one command
116// exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a 132// exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a
@@ -125,15 +141,7 @@ func runHelp(c *Ctx, args []string) int {
125 prefixes = append(prefixes, a.Registered) 141 prefixes = append(prefixes, a.Registered)
126 } 142 }
127 if c.CLIPath != "" { 143 if c.CLIPath != "" {
128 for _, cmd := range registry { 144 override = aliasPaths(aliased)
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 }
137 } 145 }
138 } 146 }
139 var matched []Command 147 var matched []Command
internal/control/milestone.go +12 −16
@@ -217,13 +217,7 @@ func runIssueMilestone(c *Ctx, args []string) int {
217 if code >= 0 { 217 if code >= 0 {
218 return code 218 return code
219 } 219 }
220 if code := refuseArchived(c, repo); code >= 0 { 220 return setItemMilestone(c, repo, args, "issue", issue.Number, func(id int64) error {
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 {
227 return c.Store.SetIssueMilestone(issue.ID, id) 221 return c.Store.SetIssueMilestone(issue.ID, id)
228 }) 222 })
229} 223}
@@ -233,13 +227,7 @@ func runMRMilestone(c *Ctx, args []string) int {
233 if code >= 0 { 227 if code >= 0 {
234 return code 228 return code
235 } 229 }
236 if code := refuseArchived(c, repo); code >= 0 { 230 return setItemMilestone(c, repo, args, "mr", mr.Number, func(id int64) error {
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 {
243 return c.Store.SetMRMilestone(mr.ID, id) 231 return c.Store.SetMRMilestone(mr.ID, id)
244 }) 232 })
245} 233}
@@ -255,8 +243,16 @@ func recordItemMilestone(c *Ctx, repo store.Repo, noun string, number, id int64,
255 return nil 243 return nil
256} 244}
257 245
258// noun and number name what the milestone was set on, for the event. 246// setItemMilestone sets the milestone args[2] titles through set. noun and
259func setItemMilestone(c *Ctx, repo store.Repo, noun string, number int64, title string, set func(int64) error) int { 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]
260 var id int64 256 var id int64
261 if title != "none" { 257 if title != "none" {
262 m, err := c.Store.MilestoneByTitle(repo, title) 258 m, err := c.Store.MilestoneByTitle(repo, title)
internal/control/mirrorcmd.go +1 −20
@@ -166,26 +166,7 @@ func orDash(s string) string {
166} 166}
167 167
168func runMirrorRemove(c *Ctx, args []string) int { 168func runMirrorRemove(c *Ctx, args []string) int {
169 if len(args) != 2 { 169 return runRepoItemAction(c, args, "mirror", c.Store.RemoveMirror, "removed", "removed mirror %d")
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 })
189} 170}
190 171
191func runMirrorSync(c *Ctx, args []string) int { 172func 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) {
69 startQuoted = true 69 startQuoted = true
70 } 70 }
71 in, have = !in, true 71 in, have = !in, true
72 case !in && (r == ' ' || r == '\t' || r == '\n' || r == '\r'): 72 case !in && strings.ContainsRune(" \t\n\r", r):
73 flush() 73 flush()
74 default: 74 default:
75 cur.WriteRune(r) 75 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) }
1266func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) } 1266func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
1267 1267
1268func setPinned(c *Ctx, args []string, pin bool) int { 1268func setPinned(c *Ctx, args []string, pin bool) int {
1269 verb := "pin" 1269 return setRepoMark(c, args, pin, "pinned", "unpinned", c.Store.PinRepo, c.Store.UnpinRepo)
1270 if !pin { 1270}
1271 verb = "unpin" 1271
1272 } 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 {
1273 if len(args) != 1 { 1275 if len(args) != 1 {
1274 return c.usage() 1276 return c.usage()
1275 } 1277 }
@@ -1277,53 +1279,33 @@ func setPinned(c *Ctx, args []string, pin bool) int {
1277 if code >= 0 { 1279 if code >= 0 {
1278 return code 1280 return code
1279 } 1281 }
1280 if pin { 1282 word := done
1281 if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil { 1283 if on {
1284 if err := mark(c.User.ID, repo.ID); err != nil {
1282 return c.fail(protocol.ExitFailure, "%v", err) 1285 return c.fail(protocol.ExitFailure, "%v", err)
1283 } 1286 }
1284 } else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil { 1287 } else {
1285 if errors.Is(err, store.ErrNotFound) { 1288 word = undone
1286 return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path()) 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)
1287 } 1294 }
1288 return c.fail(protocol.ExitFailure, "%v", err)
1289 } 1295 }
1290 return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) { 1296 return c.emit(map[string]string{word: repo.Path()}, func(w io.Writer) {
1291 fmt.Fprintf(w, "%sned %s\n", verb, repo.Path()) 1297 fmt.Fprintf(w, "%s %s\n", word, repo.Path())
1292 }) 1298 })
1293} 1299}
1294 1300
1295func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) } 1301func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) }
1296func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) } 1302func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
1297 1303
1298// setBookmarked mirrors setPinned. A bookmark needs only read access — 1304// A bookmark needs only read access — bookmarking is something you do to
1299// bookmarking is something you do to someone else's repository, which is 1305// someone else's repository, which is the whole point of it — and a
1300// the whole point of it — and a private repository you cannot read is 1306// private repository you cannot read is not found, as everywhere.
1301// not found, as everywhere.
1302func setBookmarked(c *Ctx, args []string, on bool) int { 1307func setBookmarked(c *Ctx, args []string, on bool) int {
1303 verb := "bookmark" 1308 return setRepoMark(c, args, on, "bookmarked", "unbookmarked", c.Store.BookmarkRepo, c.Store.UnbookmarkRepo)
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 })
1327} 1309}
1328 1310
1329// BookmarkOut is one row of `repo bookmarks`: the repository and how many 1311// 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 {
164} 164}
165 165
166func runWebhookRemove(c *Ctx, args []string) int { 166func 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 {
167 if len(args) != 2 { 173 if len(args) != 2 {
168 return c.usage() 174 return c.usage()
169 } 175 }
@@ -173,16 +179,16 @@ func runWebhookRemove(c *Ctx, args []string) int {
173 } 179 }
174 id, err := strconv.ParseInt(args[1], 10, 64) 180 id, err := strconv.ParseInt(args[1], 10, 64)
175 if err != nil { 181 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])
177 } 183 }
178 if err := c.Store.RemoveWebhook(repo.ID, id); err != nil { 184 if err := act(repo.ID, id); err != nil {
179 if errors.Is(err, store.ErrNotFound) { 185 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())
181 } 187 }
182 return c.fail(protocol.ExitFailure, "%v", err) 188 return c.fail(protocol.ExitFailure, "%v", err)
183 } 189 }
184 return c.emit(map[string]any{"removed": id}, func(w io.Writer) { 190 return c.emit(map[string]any{key: id}, func(w io.Writer) {
185 fmt.Fprintf(w, "removed webhook %d\n", id) 191 fmt.Fprintf(w, done+"\n", id)
186 }) 192 })
187} 193}
188 194
@@ -265,24 +271,5 @@ func runWebhookDeliveries(c *Ctx, args []string) int {
265} 271}
266 272
267func runWebhookRedeliver(c *Ctx, args []string) int { 273func runWebhookRedeliver(c *Ctx, args []string) int {
268 if len(args) != 2 { 274 return runRepoItemAction(c, args, "delivery", c.Store.Redeliver, "requeued", "delivery %d requeued")
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 })
288} 275}
internal/deps/python.go +33 −26
@@ -37,35 +37,42 @@ func parsePython(read ReadFile) []Dep {
37 } 37 }
38 } 38 }
39 if raw, err := read("pyproject.toml"); err == nil { 39 if raw, err := read("pyproject.toml"); err == nil {
40 var doc struct { 40 pyprojectDeps(raw, add)
41 Project struct { 41 }
42 Dependencies []string `toml:"dependencies"` 42 return out
43 } `toml:"project"` 43}
44 Tool struct { 44
45 Poetry struct { 45// pyprojectDeps adds the dependencies a pyproject.toml lists under
46 Dependencies map[string]any `toml:"dependencies"` 46// [project] and [tool.poetry].
47 DevDependencies map[string]any `toml:"dev-dependencies"` 47func pyprojectDeps(raw []byte, add func(name, version string)) {
48 } `toml:"poetry"` 48 var doc struct {
49 } `toml:"tool"` 49 Project struct {
50 } 50 Dependencies []string `toml:"dependencies"`
51 if toml.Unmarshal(raw, &doc) == nil { 51 } `toml:"project"`
52 for _, spec := range doc.Project.Dependencies { 52 Tool struct {
53 name, version := splitPEP508(spec) 53 Poetry struct {
54 add(name, version) 54 Dependencies map[string]any `toml:"dependencies"`
55 } 55 DevDependencies map[string]any `toml:"dev-dependencies"`
56 poetry := doc.Tool.Poetry 56 } `toml:"poetry"`
57 for _, set := range []map[string]any{poetry.Dependencies, poetry.DevDependencies} { 57 } `toml:"tool"`
58 for name, spec := range set { 58 }
59 // Poetry shares Cargo's two forms: a bare string, or a 59 if toml.Unmarshal(raw, &doc) != nil {
60 // table that may point somewhere other than PyPI. 60 return
61 if req, ok := cargoRequirement(spec); ok { 61 }
62 add(name, req) 62 for _, spec := range doc.Project.Dependencies {
63 } 63 name, version := splitPEP508(spec)
64 } 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)
65 } 73 }
66 } 74 }
67 } 75 }
68 return out
69} 76}
70 77
71// splitPEP508 separates the distribution name from its version specifier, 78// splitPEP508 separates the distribution name from its version specifier,
internal/httpd/diff.go +82 −73
@@ -334,86 +334,95 @@ type diffLayout struct {
334// forms are attached to the lines. 334// forms are attached to the lines.
335func splitFiles(files []diffFile) { 335func splitFiles(files []diffFile) {
336 for f := range files { 336 for f := range files {
337 lines := files[f].Lines 337 files[f].Rows = splitRows(files[f].Lines)
338 var rows []splitRow 338 }
339 for i := 0; i < len(lines); { 339}
340 ln := &lines[i] 340
341 switch ln.Class { 341// splitRows pairs one file's deletions with its additions, side by side.
342 case "hunk", "meta": 342func splitRows(lines []diffLine) []splitRow {
343 if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) { 343 var rows []splitRow
344 // a marker after a context line: neither side ends in a newline 344 for i := 0; i < len(lines); {
345 if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New { 345 ln := &lines[i]
346 last.OldNote, last.NewNote = ln.Text, ln.Text 346 switch ln.Class {
347 i++ 347 case "hunk", "meta":
348 continue 348 if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) {
349 } 349 // a marker after a context line: neither side ends in a newline
350 } 350 if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New {
351 rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text}) 351 last.OldNote, last.NewNote = ln.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])
379 i++ 352 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
386 continue 353 continue
387 } 354 }
388 first := len(rows) 355 }
389 for k := 0; k < len(dels) || k < len(adds); k++ { 356 rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text})
390 r := splitRow{Kind: "pair"} 357 i++
391 for _, l := range []*diffLine{pick(dels, k), pick(adds, k)} { 358 case "ctx":
392 if l == nil { 359 r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads}
393 continue 360 if ln.Compose {
394 } 361 r.Compose = ln
395 if l.Class == "del" { 362 }
396 r.Old = l 363 rows = append(rows, r)
397 } else { 364 i++
398 r.New = l 365 default:
399 } 366 var dels, adds []*diffLine
400 r.Threads = append(r.Threads, l.Threads...) 367 marker := func() string {
401 if l.Compose { 368 if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) {
402 r.Compose = l 369 i++
403 } 370 return lines[i-1].Text
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
412 } 371 }
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)))
413 } 396 }
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
414 } 423 }
415 files[f].Rows = rows
416 } 424 }
425 return r
417} 426}
418 427
419func pick(s []*diffLine, i int) *diffLine { 428func pick(s []*diffLine, i int) *diffLine {
internal/httpd/readme.go +48 −25
@@ -16,6 +16,37 @@ import (
16// go-org exports .org links as .html, so an .html target whose .org (or 16// go-org exports .org links as .html, so an .html target whose .org (or
17// .md) source exists in the tree maps back to the source file. 17// .md) source exists in the tree maps back to the source file.
18func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) template.HTML { 18func 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 {
19 ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} 50 ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div}
20 nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx) 51 nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx)
21 if err != nil { 52 if err != nil {
@@ -27,34 +58,12 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te
27 for i, a := range n.Attr { 58 for i, a := range n.Attr {
28 isHref := a.Key == "href" && n.Data == "a" 59 isHref := a.Key == "href" && n.Data == "a"
29 isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source") 60 isSrc := a.Key == "src" && (n.Data == "img" || n.Data == "video" || n.Data == "source")
30 if !isHref && !isSrc { 61 if (!isHref && !isSrc) || !isRelativeTarget(a.Val) {
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
45 continue 62 continue
46 } 63 }
47 // .html from org/markdown exports maps back to the source. 64 if v, ok := rewrite(a.Val, isSrc); ok {
48 if strings.HasSuffix(target, ".html") { 65 n.Attr[i].Val = v
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 }
56 } 66 }
57 n.Attr[i].Val = "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + target
58 } 67 }
59 } 68 }
60 for c := n.FirstChild; c != nil; c = c.NextSibling { 69 for c := n.FirstChild; c != nil; c = c.NextSibling {
@@ -70,3 +79,17 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te
70 } 79 }
71 return template.HTML(out.String()) 80 return template.HTML(out.String())
72} 81}
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 (
7 "sort" 7 "sort"
8 "strings" 8 "strings"
9 9
10 "golang.org/x/net/html"
11 "golang.org/x/net/html/atom"
12
13 "gitbay.org/gitbay/internal/control" 10 "gitbay.org/gitbay/internal/control"
14 "gitbay.org/gitbay/internal/gitutil" 11 "gitbay.org/gitbay/internal/gitutil"
15 "gitbay.org/gitbay/internal/store" 12 "gitbay.org/gitbay/internal/store"
@@ -229,56 +226,23 @@ func trimPageExt(target string) string {
229// other relative targets (images) to the wiki raw route. Targets resolve 226// other relative targets (images) to the wiki raw route. Targets resolve
230// from the current page's folder, as wikiResolve describes. 227// from the current page's folder, as wikiResolve describes.
231func rewriteWikiLinks(rendered template.HTML, p repoPage, page string, isPage, isFile func(string) bool) template.HTML { 228func 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 }
237 base := "/" + p.Repo.Path() + "/wiki" 229 base := "/" + p.Repo.Path() + "/wiki"
238 var walk func(*html.Node) 230 return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) {
239 walk = func(n *html.Node) { 231 if src {
240 if n.Type == html.ElementNode { 232 target, ok := wikiResolve(page, v, isFile)
241 for i, a := range n.Attr { 233 return base + "/_raw/" + target, ok
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 }
271 } 234 }
272 for c := n.FirstChild; c != nil; c = c.NextSibling { 235 // A plain link is usually to another page, but a link to an
273 walk(c) 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
274 } 242 }
275 } 243 if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) {
276 var out strings.Builder 244 return base + "/_raw/" + raw, true
277 for _, n := range nodes {
278 walk(n)
279 if err := html.Render(&out, n); err != nil {
280 return rendered
281 } 245 }
282 } 246 return base + "/" + target, true
283 return template.HTML(out.String()) 247 })
284} 248}
internal/mailin/authres.go +21 −16
@@ -83,22 +83,7 @@ func tokenize(s string) []token {
83 joined = false 83 joined = false
84 i++ 84 i++
85 case c == '(': 85 case c == '(':
86 depth := 0 86 i = commentEnd(s, i)
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 }
102 joined = false 87 joined = false
103 case c == '"': 88 case c == '"':
104 var b strings.Builder 89 var b strings.Builder
@@ -133,6 +118,26 @@ func tokenize(s string) []token {
133 return out 118 return out
134} 119}
135 120
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
136// splitResults splits tokens at each ";". 141// splitResults splits tokens at each ";".
137func splitResults(ts []token) [][]token { 142func splitResults(ts []token) [][]token {
138 segs := [][]token{nil} 143 segs := [][]token{nil}
internal/notify/notify.go +20 −13
@@ -50,24 +50,31 @@ func (m *Mailer) Run(ctx context.Context) {
50 continue 50 continue
51 } 51 }
52 for _, q := range due { 52 for _, q := range due {
53 if err := mail.SendReplyTo(m.Cfg, q.Recipient, q.ReplyTo, q.Subject, q.Body); err != nil { 53 m.deliver(q)
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)
66 } 54 }
67 } 55 }
68 } 56 }
69} 57}
70 58
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
71// A relay's rejection usually quotes the address it rejected — "550 5.1.1 78// A relay's rejection usually quotes the address it rejected — "550 5.1.1
72// <x@y>: Recipient address rejected" — so dropping the recipient field 79// <x@y>: Recipient address rejected" — so dropping the recipient field
73// alone would not keep an address out of the log. 80// 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) {
39 i += end + 2 39 i += end + 2
40 case c == '"': 40 case c == '"':
41 inWord = true 41 inWord = true
42 i++ 42 var err error
43 closed := false 43 if i, err = doubleQuoted(s, i, &cur); err != nil {
44 for i < len(s) { 44 return nil, err
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")
64 } 45 }
65 case c == '\\': 46 case c == '\\':
66 if i+1 >= len(s) { 47 if i+1 >= len(s) {
@@ -69,9 +50,7 @@ func Tokenize(s string) ([]string, error) {
69 inWord = true 50 inWord = true
70 cur.WriteByte(s[i+1]) 51 cur.WriteByte(s[i+1])
71 i += 2 52 i += 2
72 case c == '$' || c == '`' || c == ';' || c == '&' || c == '|' || 53 case strings.IndexByte("$`;&|<>()*?[#~", c) >= 0:
73 c == '<' || c == '>' || c == '(' || c == ')' || c == '*' ||
74 c == '?' || c == '[' || c == '#' || c == '~':
75 // Unquoted shell metacharacters are rejected outright rather 54 // Unquoted shell metacharacters are rejected outright rather
76 // than passed through: there is no shell here, and silently 55 // than passed through: there is no shell here, and silently
77 // treating them as literals would mask client quoting bugs. 56 // treating them as literals would mask client quoting bugs.
@@ -87,3 +66,21 @@ func Tokenize(s string) ([]string, error) {
87 } 66 }
88 return argv, nil 67 return argv, nil
89} 68}
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) {
35 codec := make(chan int, 1) 35 codec := make(chan int, 1)
36 start := time.Now() 36 start := time.Now()
37 go func() { 37 go func() {
38 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 38 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
39 silentStdin(t), io.Discard, io.Discard, nil, nil, nil) 39 Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard})
40 }() 40 }()
41 slotTaken(t, pushes) 41 slotTaken(t, pushes)
42 pushEnded(t, codec, pushes, 5*time.Second) 42 pushEnded(t, codec, pushes, 5*time.Second)
@@ -66,8 +66,8 @@ func TestPushKilledAtIdleOncePackStarts(t *testing.T) {
66 codec := make(chan int, 1) 66 codec := make(chan int, 1)
67 start := time.Now() 67 start := time.Now()
68 go func() { 68 go func() {
69 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 69 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
70 r, io.Discard, io.Discard, nil, nil, nil) 70 Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard})
71 }() 71 }()
72 slotTaken(t, pushes) 72 slotTaken(t, pushes)
73 // The signature split across two writes still arms the rule. 73 // The signature split across two writes still arms the rule.
@@ -116,8 +116,8 @@ func TestPushSilentBeforePackCompletes(t *testing.T) {
116 pw.Close() 116 pw.Close()
117 }() 117 }()
118 var errOut strings.Builder 118 var errOut strings.Builder
119 if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 119 if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
120 pr, io.Discard, &errOut, nil, nil, nil); code != 0 { 120 Streams{Stdin: pr, Stdout: io.Discard, Stderr: &errOut}); code != 0 {
121 t.Fatalf("exit %d: %s", code, errOut.String()) 121 t.Fatalf("exit %d: %s", code, errOut.String())
122 } 122 }
123 out, err := exec.Command("git", "-C", control.RepoDir(cfg.Server.Root, "alice", "app"), "rev-parse", "refs/heads/main").Output() 123 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) {
160 codec := make(chan int, 1) 160 codec := make(chan int, 1)
161 start := time.Now() 161 start := time.Now()
162 go func() { 162 go func() {
163 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 163 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
164 r, io.Discard, io.Discard, nil, nil, nil) 164 Streams{Stdin: r, Stdout: io.Discard, Stderr: io.Discard})
165 }() 165 }()
166 slotTaken(t, pushes) 166 slotTaken(t, pushes)
167 pushEnded(t, codec, pushes, 5*time.Second) 167 pushEnded(t, codec, pushes, 5*time.Second)
internal/sshd/refusal_test.go +22 −22
@@ -58,8 +58,8 @@ func TestRefusedPushIsAudited(t *testing.T) {
58 bob.Pending = pending 58 bob.Pending = pending
59 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} 59 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
60 var out, errOut bytes.Buffer 60 var out, errOut bytes.Buffer
61 code := Exec(cfg, st, nil, nil, bob, key, control.Term{}, "git-receive-pack alice/app", 61 code := Exec(Backend{Cfg: cfg, St: st}, bob, key, control.Term{}, "git-receive-pack alice/app",
62 strings.NewReader(""), &out, &errOut, nil, nil, nil) 62 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
63 if code != protocol.ExitDenied { 63 if code != protocol.ExitDenied {
64 t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String()) 64 t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String())
65 } 65 }
@@ -85,8 +85,8 @@ func TestCloneRefusedWhenPackSlotsAreFull(t *testing.T) {
85 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} 85 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
86 for _, service := range []string{"git-upload-pack", "git-upload-archive"} { 86 for _, service := range []string{"git-upload-pack", "git-upload-archive"} {
87 var out, errOut bytes.Buffer 87 var out, errOut bytes.Buffer
88 code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, service+" alice/app", 88 code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, service+" alice/app",
89 strings.NewReader(""), &out, &errOut, nil, nil, nil) 89 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
90 if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") { 90 if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") {
91 t.Fatalf("%s: exit %d: %q", service, code, errOut.String()) 91 t.Fatalf("%s: exit %d: %q", service, code, errOut.String())
92 } 92 }
@@ -108,8 +108,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) {
108 packs := packlimit.New(1, 0, 0, time.Second) 108 packs := packlimit.New(1, 0, 0, time.Second)
109 109
110 var out, errOut bytes.Buffer 110 var out, errOut bytes.Buffer
111 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", 111 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
112 strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK { 112 Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK {
113 t.Fatalf("clone: exit %d: %s", code, errOut.String()) 113 t.Fatalf("clone: exit %d: %s", code, errOut.String())
114 } 114 }
115 hold, err := packs.Acquire(nil, "ip:elsewhere") 115 hold, err := packs.Acquire(nil, "ip:elsewhere")
@@ -120,8 +120,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) {
120 120
121 out.Reset() 121 out.Reset()
122 errOut.Reset() 122 errOut.Reset()
123 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-receive-pack alice/app", 123 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-receive-pack alice/app",
124 strings.NewReader("0000"), &out, &errOut, nil, nil, nil); code != protocol.ExitOK { 124 Streams{Stdin: strings.NewReader("0000"), Stdout: &out, Stderr: &errOut}); code != protocol.ExitOK {
125 t.Fatalf("push with slots full: exit %d: %s", code, errOut.String()) 125 t.Fatalf("push with slots full: exit %d: %s", code, errOut.String())
126 } 126 }
127} 127}
@@ -161,8 +161,8 @@ func killedClone(t *testing.T, stdout io.Writer, done, stopping, revoked <-chan
161 packs := packlimit.New(1, 0, 0, time.Second) 161 packs := packlimit.New(1, 0, 0, time.Second)
162 codec := make(chan int, 1) 162 codec := make(chan int, 1)
163 go func() { 163 go func() {
164 codec <- Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", 164 codec <- Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
165 silentStdin(t), stdout, io.Discard, done, stopping, revoked) 165 Streams{Stdin: silentStdin(t), Stdout: stdout, Stderr: io.Discard, Done: done, Stopping: stopping, Revoked: revoked})
166 }() 166 }()
167 select { 167 select {
168 case code := <-codec: 168 case code := <-codec:
@@ -210,8 +210,8 @@ func TestCloneRunsOnDuringRestart(t *testing.T) {
210 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} 210 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
211 packs := packlimit.New(1, 0, 0, time.Second) 211 packs := packlimit.New(1, 0, 0, time.Second)
212 var errOut bytes.Buffer 212 var errOut bytes.Buffer
213 if code := Exec(cfg, st, packs, nil, alice, key, control.Term{}, "git-upload-pack alice/app", 213 if code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, alice, key, control.Term{}, "git-upload-pack alice/app",
214 strings.NewReader("0000"), io.Discard, &errOut, closed(), closed(), nil); code != protocol.ExitOK { 214 Streams{Stdin: strings.NewReader("0000"), Stdout: io.Discard, Stderr: &errOut, Done: closed(), Stopping: closed()}); code != protocol.ExitOK {
215 t.Fatalf("exit %d: %s", code, errOut.String()) 215 t.Fatalf("exit %d: %s", code, errOut.String())
216 } 216 }
217} 217}
@@ -235,8 +235,8 @@ func TestRefusedCloneStaysOffLimiter(t *testing.T) {
235 defer hold() 235 defer hold()
236 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} 236 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
237 var out, errOut bytes.Buffer 237 var out, errOut bytes.Buffer
238 code := Exec(cfg, st, packs, nil, bob, key, control.Term{}, "git-upload-pack alice/secret", 238 code := Exec(Backend{Cfg: cfg, St: st, Packs: packs}, bob, key, control.Term{}, "git-upload-pack alice/secret",
239 strings.NewReader(""), &out, &errOut, nil, nil, nil) 239 Streams{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errOut})
240 if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") { 240 if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") {
241 t.Fatalf("exit %d: %q", code, errOut.String()) 241 t.Fatalf("exit %d: %q", code, errOut.String())
242 } 242 }
@@ -282,8 +282,8 @@ func TestPushPerPrincipalCap(t *testing.T) {
282 push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int { 282 push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int {
283 codec := make(chan int, 1) 283 codec := make(chan int, 1)
284 go func() { 284 go func() {
285 codec <- Exec(cfg, st, nil, pushes, alice, k, control.Term{}, "git-receive-pack alice/app", 285 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, k, control.Term{}, "git-receive-pack alice/app",
286 stdin, io.Discard, errOut, nil, nil, nil) 286 Streams{Stdin: stdin, Stdout: io.Discard, Stderr: errOut})
287 }() 287 }()
288 return codec 288 return codec
289 } 289 }
@@ -320,8 +320,8 @@ func TestPushPerPrincipalCap(t *testing.T) {
320 queuedFor(t, pushes, principal) 320 queuedFor(t, pushes, principal)
321 321
322 var errOut bytes.Buffer 322 var errOut bytes.Buffer
323 if code := Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 323 if code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
324 strings.NewReader(""), io.Discard, &errOut, nil, nil, nil); code != protocol.ExitFailure || 324 Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut}); code != protocol.ExitFailure ||
325 !strings.Contains(errOut.String(), "limit of concurrent pushes") { 325 !strings.Contains(errOut.String(), "limit of concurrent pushes") {
326 t.Fatalf("third push: exit %d: %q", code, errOut.String()) 326 t.Fatalf("third push: exit %d: %q", code, errOut.String())
327 } 327 }
@@ -354,8 +354,8 @@ func TestPushKilledWhenKeyRevokedReleasesSlot(t *testing.T) {
354 revoked := make(chan struct{}) 354 revoked := make(chan struct{})
355 codec := make(chan int, 1) 355 codec := make(chan int, 1)
356 go func() { 356 go func() {
357 codec <- Exec(cfg, st, nil, pushes, alice, key, control.Term{}, "git-receive-pack alice/app", 357 codec <- Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, alice, key, control.Term{}, "git-receive-pack alice/app",
358 silentStdin(t), io.Discard, io.Discard, nil, nil, revoked) 358 Streams{Stdin: silentStdin(t), Stdout: io.Discard, Stderr: io.Discard, Revoked: revoked})
359 }() 359 }()
360 slotTaken(t, pushes) 360 slotTaken(t, pushes)
361 close(revoked) 361 close(revoked)
@@ -407,8 +407,8 @@ func TestRefusedPushStaysOffLimiter(t *testing.T) {
407 defer hold() 407 defer hold()
408 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} 408 key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
409 var errOut bytes.Buffer 409 var errOut bytes.Buffer
410 code := Exec(cfg, st, nil, pushes, bob, key, control.Term{}, "git-receive-pack alice/app", 410 code := Exec(Backend{Cfg: cfg, St: st, Pushes: pushes}, bob, key, control.Term{}, "git-receive-pack alice/app",
411 strings.NewReader(""), io.Discard, &errOut, nil, nil, nil) 411 Streams{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: &errOut})
412 if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") { 412 if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") {
413 t.Fatalf("exit %d: %q", code, errOut.String()) 413 t.Fatalf("exit %d: %q", code, errOut.String())
414 } 414 }
internal/sshd/sshd.go +58 −35
@@ -427,7 +427,8 @@ func (s *Server) runExec(c *conn, sconn *ssh.ServerConn, ch ssh.Channel, term co
427 return protocol.ExitDenied 427 return protocol.ExitDenied
428 } 428 }
429 _ = s.st.TouchSSHKey(keyID) 429 _ = 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})
431} 432}
432 433
433// runAnonymous handles a session from an unregistered key: the register 434// 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 {
460 return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr()) 461 return control.RunRegister(s.cfg, s.st, pub, argv, ch, ch.Stderr())
461} 462}
462 463
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
463// Exec runs one SSH exec command line for an authenticated key. It is the 480// Exec runs one SSH exec command line for an authenticated key. It is the
464// single dispatch path shared by the embedded listener and the system-sshd 481// single dispatch path shared by the embedded listener and the system-sshd
465// forced command (gitbayd shell). Closing revoked kills a git transport. 482// forced command (gitbayd shell).
466// packs bounds clones and fetches, and repo download; pushes bounds 483func Exec(b Backend, user store.User, key store.SSHKey, term control.Term, cmdline string, s Streams) int {
467// receive-pack. A nil limiter is no limit. 484 cfg, st, packs := b.Cfg, b.St, b.Packs
468func Exec(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter, user store.User, key store.SSHKey, term control.Term, cmdline string, 485 stdin, stdout, stderr := s.Stdin, s.Stdout, s.Stderr
469 stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) int { 486 done, stopping := s.Done, s.Stopping
470 // A person signing in with a full-scope key cancels a scheduled 487 // A person signing in with a full-scope key cancels a scheduled
471 // deletion; automation on narrower keys is refused and cannot. 488 // deletion; automation on narrower keys is refused and cannot.
472 if user.Disabled && user.DeleteAfter != "" && key.Scope == "full" && control.CancelScheduledDeletion(st, &user, "ssh") { 489 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,
492 if user.Pending { 509 if user.Pending {
493 fmt.Fprintln(stderr, "your account is not active yet: verify your email first") 510 fmt.Fprintln(stderr, "your account is not active yet: verify your email first")
494 } else { 511 } 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)
496 } 513 }
497 // A refused push is a refused write, audited like one. runGit 514 // A refused push is a refused write, audited like one. runGit
498 // refuses only with the path as the one argument, so argv[1:] 515 // 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,
530 return control.Dispatch(ctx, argv) 547 return control.Dispatch(ctx, argv)
531} 548}
532 549
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
533// runGit streams a git transport service after access checks. 579// 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, 580func runGit(b Backend, user store.User, key store.SSHKey, argv []string, s Streams) int {
535 stdin io.Reader, stdout, stderr io.Writer, done, stopping, revoked <-chan struct{}) 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
536 service, scope := argv[0], key.Scope 584 service, scope := argv[0], key.Scope
537 if len(argv) != 2 { 585 if len(argv) != 2 {
538 fmt.Fprintf(stderr, "usage: %s <path>\n", service) 586 fmt.Fprintf(stderr, "usage: %s <path>\n", service)
@@ -663,32 +711,7 @@ func runGit(cfg config.Config, st *store.Store, packs, pushes *packlimit.Limiter
663 kill := make(chan struct{}) 711 kill := make(chan struct{})
664 finished := make(chan struct{}) 712 finished := make(chan struct{})
665 defer close(finished) 713 defer close(finished)
666 go func() { 714 go cutStalledPush(finished, started, revoked, idle, deadline.C, arm, kill, client, clientOut)
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 }()
692 cancel = kill 715 cancel = kill
693 } 716 }
694 } 717 }
internal/store/issues.go +16 −6
@@ -264,6 +264,12 @@ func (s *Store) QueryIssues(repoID int64, f IssueFilter) ([]Issue, error) {
264// UpdateIssueText edits title, body, and/or markup format; nil leaves a field 264// UpdateIssueText edits title, body, and/or markup format; nil leaves a field
265// unchanged. 265// unchanged.
266func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) error { 266func (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 {
267 set, args := []string{}, []any{} 273 set, args := []string{}, []any{}
268 if title != nil { 274 if title != nil {
269 set, args = append(set, "title = ?"), append(args, *title) 275 set, args = append(set, "title = ?"), append(args, *title)
@@ -278,8 +284,8 @@ func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) erro
278 return nil 284 return nil
279 } 285 }
280 set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')") 286 set = append(set, "updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')")
281 args = append(args, issueID) 287 args = append(args, id)
282 res, err := s.DB.Exec("UPDATE issues SET "+strings.Join(set, ", ")+" WHERE id = ?", args...) 288 res, err := s.DB.Exec("UPDATE "+table+" SET "+strings.Join(set, ", ")+" WHERE id = ?", args...)
283 if err != nil { 289 if err != nil {
284 return err 290 return err
285 } 291 }
@@ -388,14 +394,18 @@ func (s *Store) SetIssueLabel(repo Repo, issueID int64, name string, add bool) e
388 394
389// SetIssueAssignee adds or removes an assignee by user id. 395// SetIssueAssignee adds or removes an assignee by user id.
390func (s *Store) SetIssueAssignee(issueID, userID int64, add bool) error { 396func (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 {
391 if add { 402 if add {
392 _, err := s.DB.Exec( 403 _, err := s.DB.Exec(
393 "INSERT INTO issue_assignees (issue_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING", 404 "INSERT INTO "+table+" ("+itemCol+", user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
394 issueID, userID) 405 itemID, userID)
395 return err 406 return err
396 } 407 }
397 res, err := s.DB.Exec( 408 res, err := s.DB.Exec("DELETE FROM "+table+" WHERE "+itemCol+" = ? AND user_id = ?", itemID, userID)
398 "DELETE FROM issue_assignees WHERE issue_id = ? AND user_id = ?", issueID, userID)
399 if err != nil { 409 if err != nil {
400 return err 410 return err
401 } 411 }
internal/store/mrs.go +2 −38
@@ -164,21 +164,7 @@ func (s *Store) SetMRLabel(repo Repo, mrID int64, name string, add bool) error {
164// SetMRReviewRequest adds or removes a review request by user id — the 164// SetMRReviewRequest adds or removes a review request by user id — the
165// mr review request counterpart of SetIssueAssignee. 165// mr review request counterpart of SetIssueAssignee.
166func (s *Store) SetMRReviewRequest(mrID, userID int64, add bool) error { 166func (s *Store) SetMRReviewRequest(mrID, userID int64, add bool) error {
167 if add { 167 return s.setItemUser("mr_review_requests", "mr_id", mrID, userID, 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
182} 168}
183 169
184// MRReviewRequestIDs returns who has been asked for a review, by id — for 170// 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 {
496// UpdateMRText edits title, body, and/or markup format; nil leaves a field 482// UpdateMRText edits title, body, and/or markup format; nil leaves a field
497// unchanged. 483// unchanged.
498func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error { 484func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error {
499 set, args := []string{}, []any{} 485 return s.updateText("merge_requests", mrID, title, body, format)
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
522} 486}
523 487
524// AddMRSystemComment is the informational counterpart of AddMRComment. 488// AddMRSystemComment is the informational counterpart of AddMRComment.
internal/store/users.go +16 −38
@@ -140,20 +140,7 @@ func (s *Store) OwnerExists(name string) bool {
140} 140}
141 141
142func (s *Store) UserByUsername(name string) (User, error) { 142func (s *Store) UserByUsername(name string) (User, error) {
143 var u User 143 return s.userBy("username", name)
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
157} 144}
158 145
159// UserEmailAddresses returns every address on the account, verified or not. 146// UserEmailAddresses returns every address on the account, verified or not.
@@ -333,10 +320,15 @@ func (s *Store) SetDiffLayout(userID int64, layout string) error {
333} 320}
334 321
335func (s *Store) UserByID(id int64) (User, error) { 322func (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) {
336 var u User 328 var u User
337 var admin, pending, disabled, ghost int 329 var admin, pending, disabled, ghost int
338 var deleteAfter sql.NullString 330 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).
340 Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost) 332 Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost)
341 if errors.Is(err, sql.ErrNoRows) { 333 if errors.Is(err, sql.ErrNoRows) {
342 return u, ErrNotFound 334 return u, ErrNotFound
@@ -388,13 +380,19 @@ func (s *Store) AddSSHKeyFrom(userID int64, fingerprint, algo string, blob []byt
388// RemoveSSHKey removes a key owned by userID, bumps the key epoch, and 380// RemoveSSHKey removes a key owned by userID, bumps the key epoch, and
389// announces the revocation. 381// announces the revocation.
390func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error { 382func (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 {
391 tx, err := s.DB.Begin() 389 tx, err := s.DB.Begin()
392 if err != nil { 390 if err != nil {
393 return err 391 return err
394 } 392 }
395 defer tx.Rollback() 393 defer tx.Rollback()
396 var id int64 394 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)
398 if errors.Is(err, sql.ErrNoRows) { 396 if errors.Is(err, sql.ErrNoRows) {
399 return ErrNotFound 397 return ErrNotFound
400 } 398 }
@@ -647,27 +645,7 @@ func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) {
647// RemoveDeployKey removes a deploy key from a repository by fingerprint; 645// RemoveDeployKey removes a deploy key from a repository by fingerprint;
648// any repo admin may remove it regardless of who added it. 646// any repo admin may remove it regardless of who added it.
649func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error { 647func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error {
650 tx, err := s.DB.Begin() 648 return s.removeKey(
651 if err != nil {
652 return err
653 }
654 defer tx.Rollback()
655 var id int64
656 err = tx.QueryRow(
657 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id", 649 "DELETE FROM ssh_keys WHERE fingerprint = ? AND scope LIKE 'deploy:' || ? || ':%' RETURNING id",
658 fingerprint, repoID).Scan(&id) 650 fingerprint, repoID)
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
673} 651}
internal/symbols/extract.go +10 −7
@@ -162,6 +162,11 @@ func extractGo(data []byte) []Symbol {
162 } 162 }
163 out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line}) 163 out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line})
164 } 164 }
165 addNames := func(ids []*ast.Ident, kind string) {
166 for _, id := range ids {
167 add(id, id.Name, kind)
168 }
169 }
165 for _, d := range f.Decls { 170 for _, d := range f.Decls {
166 switch d := d.(type) { 171 switch d := d.(type) {
167 case *ast.FuncDecl: 172 case *ast.FuncDecl:
@@ -176,18 +181,16 @@ func extractGo(data []byte) []Symbol {
176 } 181 }
177 add(d.Name, recv+"."+d.Name.Name, "method") 182 add(d.Name, recv+"."+d.Name.Name, "method")
178 case *ast.GenDecl: 183 case *ast.GenDecl:
184 kind := "var"
185 if d.Tok == token.CONST {
186 kind = "const"
187 }
179 for _, spec := range d.Specs { 188 for _, spec := range d.Specs {
180 switch s := spec.(type) { 189 switch s := spec.(type) {
181 case *ast.TypeSpec: 190 case *ast.TypeSpec:
182 add(s.Name, s.Name.Name, "type") 191 add(s.Name, s.Name.Name, "type")
183 case *ast.ValueSpec: 192 case *ast.ValueSpec:
184 kind := "var" 193 addNames(s.Names, kind)
185 if d.Tok == token.CONST {
186 kind = "const"
187 }
188 for _, n := range s.Names {
189 add(n, n.Name, kind)
190 }
191 } 194 }
192 } 195 }
193 } 196 }
internal/termtext/markdown.go +5 −5
@@ -80,12 +80,12 @@ func (r mdRenderer) block(n ast.Node, first, rest string) {
80 for c := item.FirstChild(); c != nil; c = c.NextSibling() { 80 for c := item.FirstChild(); c != nil; c = c.NextSibling() {
81 if c == item.FirstChild() { 81 if c == item.FirstChild() {
82 r.block(c, p+marker, hang) 82 r.block(c, p+marker, hang)
83 } else { 83 continue
84 if !n.IsTight {
85 r.w.blank()
86 }
87 r.block(c, hang, hang)
88 } 84 }
85 if !n.IsTight {
86 r.w.blank()
87 }
88 r.block(c, hang, hang)
89 } 89 }
90 p = rest 90 p = rest
91 } 91 }
internal/texmath/texmath.go +15 −2
@@ -66,7 +66,7 @@ func Convert(tex string, display bool) (string, error) {
66 return "", errors.New("texmath: invalid UTF-8") 66 return "", errors.New("texmath: invalid UTF-8")
67 } 67 }
68 for _, r := range tex { 68 for _, r := range tex {
69 if r < 0x20 && r != '\t' && r != '\n' && r != '\r' || r == 0x7F || r == 0xFFFE || r == 0xFFFF { 69 if isControl(r) {
70 return "", errors.New("texmath: control character") 70 return "", errors.New("texmath: control character")
71 } 71 }
72 } 72 }
@@ -206,6 +206,19 @@ func (p *parser) next() token {
206var starred = map[string]bool{"operatorname": true} 206var starred = map[string]bool{"operatorname": true}
207 207
208func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } 208func 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}
209 222
210func (p *parser) unexpected(t token) error { 223func (p *parser) unexpected(t token) error {
211 switch t.kind { 224 switch t.kind {
@@ -402,7 +415,7 @@ func (p *parser) charAtom(t token) (*node, error) {
402 num := t.val 415 num := t.val
403 for p.pos < len(p.src) { 416 for p.pos < len(p.src) {
404 c := p.src[p.pos] 417 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]) {
406 num += string(c) 419 num += string(c)
407 p.pos++ 420 p.pos++
408 continue 421 continue