Commit 93d98753bc
Verified · cmc ci/build: success ci/quality: success ci/test: success
Layout: unified · split
.qlty/qlty.toml +8
| @@ -76,3 +76,11 @@ enabled = false | ||
| 76 | 76 | |
| 77 | 77 | [smells.file_complexity] |
| 78 | 78 | enabled = false |
| 79 | ||
| 80 | # Six or seven parameters is ordinary for an unexported Go helper. | |
| 81 | [smells.function_parameters] | |
| 82 | threshold = 8 | |
| 83 | ||
| 84 | # The store's hand-written queries each scan their rows in the same loop. | |
| 85 | [language.go.smells.duplication] | |
| 86 | filter_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 | 8 | "fmt" |
| 9 | 9 | "io" |
| 10 | 10 | "os" |
| 11 | "slices" | |
| 11 | 12 | "strings" |
| 12 | 13 | |
| 13 | 14 | "github.com/spf13/cobra" |
| @@ -379,7 +380,7 @@ func isEmptyReader(r io.Reader) bool { | ||
| 379 | 380 | // usesStdin reports whether the arguments request stdin content. |
| 380 | 381 | func usesStdin(args []string) bool { |
| 381 | 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 | 384 | return true |
| 384 | 385 | } |
| 385 | 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 | |
| 478 | func 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. | |
| 481 | func runWithStdin(server []string, what string) func(*cobra.Command, []string) error { | |
| 482 | return func(cmd *cobra.Command, args []string) error { | |
| 482 | 483 | cliPath := cliPathOf(cmd) |
| 483 | 484 | for _, a := range args { |
| 484 | 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 | 489 | t, err := resolveTarget() |
| 489 | 490 | if err != nil { |
| 490 | 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 | 494 | if err != nil { |
| 494 | 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 | 498 | return nil |
| 498 | 499 | } |
| 500 | } | |
| 501 | ||
| 502 | func 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 | 506 | pgpAdd := &cobra.Command{ |
| 500 | 507 | Use: "add", Short: "register an OpenPGP public key (armored, on stdin)", |
| 501 | 508 | Annotations: map[string]string{ |
| @@ -504,24 +511,7 @@ func authCmd() *cobra.Command { | ||
| 504 | 511 | stdinWhat: "an armored OpenPGP public key", |
| 505 | 512 | }, |
| 506 | 513 | 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"), | |
| 525 | 515 | } |
| 526 | 516 | tokens := group("token", "API tokens (minted over SSH, used with the JSON API)", |
| 527 | 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 | 102 | // Each forced command is its own process, so there is no |
| 103 | 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 | 105 | st.Close() |
| 106 | 106 | os.Exit(code) |
| 107 | 107 | return nil |
internal/config/config.go +2 −2
| @@ -682,8 +682,8 @@ func (c Config) Validate() error { | ||
| 682 | 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 || | |
| 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 { | |
| 687 | 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 | 689 | for _, w := range []struct{ name, val string }{ |
internal/control/help.go +17 −9
| @@ -111,6 +111,22 @@ type helpEntry struct { | ||
| 111 | 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. | |
| 116 | func 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 | 130 | // runHelp lists the registry, sorted, so a noun's commands sit together. |
| 115 | 131 | // Bare `help` stays one line per command. A prefix that names one command |
| 116 | 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 | 141 | prefixes = append(prefixes, a.Registered) |
| 126 | 142 | } |
| 127 | 143 | 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) | |
| 137 | 145 | } |
| 138 | 146 | } |
| 139 | 147 | var matched []Command |
internal/control/milestone.go +12 −16
| @@ -217,13 +217,7 @@ func runIssueMilestone(c *Ctx, args []string) int { | ||
| 217 | 217 | if code >= 0 { |
| 218 | 218 | return code |
| 219 | 219 | } |
| 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 { | |
| 227 | 221 | return c.Store.SetIssueMilestone(issue.ID, id) |
| 228 | 222 | }) |
| 229 | 223 | } |
| @@ -233,13 +227,7 @@ func runMRMilestone(c *Ctx, args []string) int { | ||
| 233 | 227 | if code >= 0 { |
| 234 | 228 | return code |
| 235 | 229 | } |
| 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 { | |
| 243 | 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 | 243 | return nil |
| 256 | 244 | } |
| 257 | 245 | |
| 258 | // noun and number name what the milestone was set on, for the event. | |
| 259 | func 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. | |
| 248 | func 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 | 256 | var id int64 |
| 261 | 257 | if title != "none" { |
| 262 | 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 | |
| 168 | 168 | func 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") | |
| 189 | 170 | } |
| 190 | 171 | |
| 191 | 172 | func 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 | 69 | startQuoted = true |
| 70 | 70 | } |
| 71 | 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 | 73 | flush() |
| 74 | 74 | default: |
| 75 | 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) } | ||
| 1266 | 1266 | func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) } |
| 1267 | 1267 | |
| 1268 | 1268 | func 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. | |
| 1274 | func setRepoMark(c *Ctx, args []string, on bool, done, undone string, mark, unmark func(userID, repoID int64) error) int { | |
| 1273 | 1275 | if len(args) != 1 { |
| 1274 | 1276 | return c.usage() |
| 1275 | 1277 | } |
| @@ -1277,53 +1279,33 @@ func setPinned(c *Ctx, args []string, pin bool) int { | ||
| 1277 | 1279 | if code >= 0 { |
| 1278 | 1280 | return code |
| 1279 | 1281 | } |
| 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 { | |
| 1282 | 1285 | return c.fail(protocol.ExitFailure, "%v", err) |
| 1283 | 1286 | } |
| 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) | |
| 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) { | |
| 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()) | |
| 1292 | 1298 | }) |
| 1293 | 1299 | } |
| 1294 | 1300 | |
| 1295 | 1301 | func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) } |
| 1296 | 1302 | func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) } |
| 1297 | 1303 | |
| 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. | |
| 1302 | 1307 | func 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) | |
| 1327 | 1309 | } |
| 1328 | 1310 | |
| 1329 | 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 | |
| 166 | 166 | func 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. | |
| 172 | func runRepoItemAction(c *Ctx, args []string, noun string, act func(repoID, id int64) error, key, done string) int { | |
| 167 | 173 | if len(args) != 2 { |
| 168 | 174 | return c.usage() |
| 169 | 175 | } |
| @@ -173,16 +179,16 @@ func runWebhookRemove(c *Ctx, args []string) int { | ||
| 173 | 179 | } |
| 174 | 180 | id, err := strconv.ParseInt(args[1], 10, 64) |
| 175 | 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 | 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 | 188 | return c.fail(protocol.ExitFailure, "%v", err) |
| 183 | 189 | } |
| 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) | |
| 186 | 192 | }) |
| 187 | 193 | } |
| 188 | 194 | |
| @@ -265,24 +271,5 @@ func runWebhookDeliveries(c *Ctx, args []string) int { | ||
| 265 | 271 | } |
| 266 | 272 | |
| 267 | 273 | func 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") | |
| 288 | 275 | } |
internal/deps/python.go +33 −26
| @@ -37,35 +37,42 @@ func parsePython(read ReadFile) []Dep { | ||
| 37 | 37 | } |
| 38 | 38 | } |
| 39 | 39 | 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]. | |
| 47 | func 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) | |
| 65 | 73 | } |
| 66 | 74 | } |
| 67 | 75 | } |
| 68 | return out | |
| 69 | 76 | } |
| 70 | 77 | |
| 71 | 78 | // splitPEP508 separates the distribution name from its version specifier, |
internal/httpd/diff.go +82 −73
| @@ -334,86 +334,95 @@ type diffLayout struct { | ||
| 334 | 334 | // forms are attached to the lines. |
| 335 | 335 | func splitFiles(files []diffFile) { |
| 336 | 336 | 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. | |
| 342 | func 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 | |
| 379 | 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 | 353 | continue |
| 387 | 354 | } |
| 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 | |
| 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. | |
| 409 | func 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 | |
| 419 | 428 | func pick(s []*diffLine, i int) *diffLine { |
internal/httpd/readme.go +48 −25
| @@ -16,6 +16,37 @@ import ( | ||
| 16 | 16 | // go-org exports .org links as .html, so an .html target whose .org (or |
| 17 | 17 | // .md) source exists in the tree maps back to the source file. |
| 18 | 18 | func 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. | |
| 33 | func 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. | |
| 49 | func rewriteRelativeTargets(rendered template.HTML, rewrite func(v string, src bool) (string, bool)) template.HTML { | |
| 19 | 50 | ctx := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div} |
| 20 | 51 | nodes, err := html.ParseFragment(strings.NewReader(string(rendered)), ctx) |
| 21 | 52 | if err != nil { |
| @@ -27,34 +58,12 @@ func rewriteRelativeLinks(rendered template.HTML, p repoPage, baseDir string) te | ||
| 27 | 58 | for i, a := range n.Attr { |
| 28 | 59 | isHref := a.Key == "href" && n.Data == "a" |
| 29 | 60 | 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) { | |
| 45 | 62 | continue |
| 46 | 63 | } |
| 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 | |
| 56 | 66 | } |
| 57 | n.Attr[i].Val = "/" + p.Repo.Path() + "/blob/" + p.Ref + "/" + target | |
| 58 | 67 | } |
| 59 | 68 | } |
| 60 | 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 | 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:. | |
| 85 | func 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 | 7 | "sort" |
| 8 | 8 | "strings" |
| 9 | 9 | |
| 10 | "golang.org/x/net/html" | |
| 11 | "golang.org/x/net/html/atom" | |
| 12 | ||
| 13 | 10 | "gitbay.org/gitbay/internal/control" |
| 14 | 11 | "gitbay.org/gitbay/internal/gitutil" |
| 15 | 12 | "gitbay.org/gitbay/internal/store" |
| @@ -229,56 +226,23 @@ func trimPageExt(target string) string { | ||
| 229 | 226 | // other relative targets (images) to the wiki raw route. Targets resolve |
| 230 | 227 | // from the current page's folder, as wikiResolve describes. |
| 231 | 228 | func 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 | 229 | 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 | |
| 271 | 234 | } |
| 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 | |
| 274 | 242 | } |
| 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 | |
| 281 | 245 | } |
| 282 | } | |
| 283 | return template.HTML(out.String()) | |
| 246 | return base + "/" + target, true | |
| 247 | }) | |
| 284 | 248 | } |
internal/mailin/authres.go +21 −16
| @@ -83,22 +83,7 @@ func tokenize(s string) []token { | ||
| 83 | 83 | joined = false |
| 84 | 84 | i++ |
| 85 | 85 | 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) | |
| 102 | 87 | joined = false |
| 103 | 88 | case c == '"': |
| 104 | 89 | var b strings.Builder |
| @@ -133,6 +118,26 @@ func tokenize(s string) []token { | ||
| 133 | 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. | |
| 123 | func 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 | 141 | // splitResults splits tokens at each ";". |
| 137 | 142 | func splitResults(ts []token) [][]token { |
| 138 | 143 | segs := [][]token{nil} |
internal/notify/notify.go +20 −13
| @@ -50,24 +50,31 @@ func (m *Mailer) Run(ctx context.Context) { | ||
| 50 | 50 | continue |
| 51 | 51 | } |
| 52 | 52 | 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) | |
| 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. | |
| 61 | func (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 | 78 | // A relay's rejection usually quotes the address it rejected — "550 5.1.1 |
| 72 | 79 | // <x@y>: Recipient address rejected" — so dropping the recipient field |
| 73 | 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 | 39 | i += end + 2 |
| 40 | 40 | case c == '"': |
| 41 | 41 | 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 | |
| 64 | 45 | } |
| 65 | 46 | case c == '\\': |
| 66 | 47 | if i+1 >= len(s) { |
| @@ -69,9 +50,7 @@ func Tokenize(s string) ([]string, error) { | ||
| 69 | 50 | inWord = true |
| 70 | 51 | cur.WriteByte(s[i+1]) |
| 71 | 52 | 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: | |
| 75 | 54 | // Unquoted shell metacharacters are rejected outright rather |
| 76 | 55 | // than passed through: there is no shell here, and silently |
| 77 | 56 | // treating them as literals would mask client quoting bugs. |
| @@ -87,3 +66,21 @@ func Tokenize(s string) ([]string, error) { | ||
| 87 | 66 | } |
| 88 | 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. | |
| 73 | func 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 | 35 | codec := make(chan int, 1) |
| 36 | 36 | start := time.Now() |
| 37 | 37 | 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}) | |
| 40 | 40 | }() |
| 41 | 41 | slotTaken(t, pushes) |
| 42 | 42 | pushEnded(t, codec, pushes, 5*time.Second) |
| @@ -66,8 +66,8 @@ func TestPushKilledAtIdleOncePackStarts(t *testing.T) { | ||
| 66 | 66 | codec := make(chan int, 1) |
| 67 | 67 | start := time.Now() |
| 68 | 68 | 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}) | |
| 71 | 71 | }() |
| 72 | 72 | slotTaken(t, pushes) |
| 73 | 73 | // The signature split across two writes still arms the rule. |
| @@ -116,8 +116,8 @@ func TestPushSilentBeforePackCompletes(t *testing.T) { | ||
| 116 | 116 | pw.Close() |
| 117 | 117 | }() |
| 118 | 118 | 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 { | |
| 121 | 121 | t.Fatalf("exit %d: %s", code, errOut.String()) |
| 122 | 122 | } |
| 123 | 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 | 160 | codec := make(chan int, 1) |
| 161 | 161 | start := time.Now() |
| 162 | 162 | 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}) | |
| 165 | 165 | }() |
| 166 | 166 | slotTaken(t, pushes) |
| 167 | 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 | 58 | bob.Pending = pending |
| 59 | 59 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 60 | 60 | 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}) | |
| 63 | 63 | if code != protocol.ExitDenied { |
| 64 | 64 | t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String()) |
| 65 | 65 | } |
| @@ -85,8 +85,8 @@ func TestCloneRefusedWhenPackSlotsAreFull(t *testing.T) { | ||
| 85 | 85 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 86 | 86 | for _, service := range []string{"git-upload-pack", "git-upload-archive"} { |
| 87 | 87 | 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}) | |
| 90 | 90 | if code != protocol.ExitFailure || !strings.Contains(errOut.String(), "busy") { |
| 91 | 91 | t.Fatalf("%s: exit %d: %q", service, code, errOut.String()) |
| 92 | 92 | } |
| @@ -108,8 +108,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) { | ||
| 108 | 108 | packs := packlimit.New(1, 0, 0, time.Second) |
| 109 | 109 | |
| 110 | 110 | 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 { | |
| 113 | 113 | t.Fatalf("clone: exit %d: %s", code, errOut.String()) |
| 114 | 114 | } |
| 115 | 115 | hold, err := packs.Acquire(nil, "ip:elsewhere") |
| @@ -120,8 +120,8 @@ func TestPushBypassesPackLimitAndCloneReleasesSlot(t *testing.T) { | ||
| 120 | 120 | |
| 121 | 121 | out.Reset() |
| 122 | 122 | 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 { | |
| 125 | 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 | 161 | packs := packlimit.New(1, 0, 0, time.Second) |
| 162 | 162 | codec := make(chan int, 1) |
| 163 | 163 | 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}) | |
| 166 | 166 | }() |
| 167 | 167 | select { |
| 168 | 168 | case code := <-codec: |
| @@ -210,8 +210,8 @@ func TestCloneRunsOnDuringRestart(t *testing.T) { | ||
| 210 | 210 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 211 | 211 | packs := packlimit.New(1, 0, 0, time.Second) |
| 212 | 212 | 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 { | |
| 215 | 215 | t.Fatalf("exit %d: %s", code, errOut.String()) |
| 216 | 216 | } |
| 217 | 217 | } |
| @@ -235,8 +235,8 @@ func TestRefusedCloneStaysOffLimiter(t *testing.T) { | ||
| 235 | 235 | defer hold() |
| 236 | 236 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 237 | 237 | 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}) | |
| 240 | 240 | if code != protocol.ExitNotFound || strings.Contains(errOut.String(), "busy") { |
| 241 | 241 | t.Fatalf("exit %d: %q", code, errOut.String()) |
| 242 | 242 | } |
| @@ -282,8 +282,8 @@ func TestPushPerPrincipalCap(t *testing.T) { | ||
| 282 | 282 | push := func(k store.SSHKey, stdin io.Reader, errOut io.Writer) <-chan int { |
| 283 | 283 | codec := make(chan int, 1) |
| 284 | 284 | 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}) | |
| 287 | 287 | }() |
| 288 | 288 | return codec |
| 289 | 289 | } |
| @@ -320,8 +320,8 @@ func TestPushPerPrincipalCap(t *testing.T) { | ||
| 320 | 320 | queuedFor(t, pushes, principal) |
| 321 | 321 | |
| 322 | 322 | 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 || | |
| 325 | 325 | !strings.Contains(errOut.String(), "limit of concurrent pushes") { |
| 326 | 326 | t.Fatalf("third push: exit %d: %q", code, errOut.String()) |
| 327 | 327 | } |
| @@ -354,8 +354,8 @@ func TestPushKilledWhenKeyRevokedReleasesSlot(t *testing.T) { | ||
| 354 | 354 | revoked := make(chan struct{}) |
| 355 | 355 | codec := make(chan int, 1) |
| 356 | 356 | 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}) | |
| 359 | 359 | }() |
| 360 | 360 | slotTaken(t, pushes) |
| 361 | 361 | close(revoked) |
| @@ -407,8 +407,8 @@ func TestRefusedPushStaysOffLimiter(t *testing.T) { | ||
| 407 | 407 | defer hold() |
| 408 | 408 | key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"} |
| 409 | 409 | 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}) | |
| 412 | 412 | if code != protocol.ExitDenied || strings.Contains(errOut.String(), "busy") { |
| 413 | 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 | 427 | return protocol.ExitDenied |
| 428 | 428 | } |
| 429 | 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 | 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 | 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. | |
| 466 | type 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. | |
| 474 | type Streams struct { | |
| 475 | Stdin io.Reader | |
| 476 | Stdout, Stderr io.Writer | |
| 477 | Done, Stopping, Revoked <-chan struct{} | |
| 478 | } | |
| 479 | ||
| 463 | 480 | // Exec runs one SSH exec command line for an authenticated key. It is the |
| 464 | 481 | // 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. | |
| 468 | func 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). | |
| 483 | func 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 | |
| 470 | 487 | // A person signing in with a full-scope key cancels a scheduled |
| 471 | 488 | // deletion; automation on narrower keys is refused and cannot. |
| 472 | 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 | 509 | if user.Pending { |
| 493 | 510 | fmt.Fprintln(stderr, "your account is not active yet: verify your email first") |
| 494 | 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 | 514 | // A refused push is a refused write, audited like one. runGit |
| 498 | 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 | 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. | |
| 554 | func 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 | 579 | // runGit streams a git transport service after access checks. |
| 534 | func 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 { | |
| 580 | func 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 | |
| 536 | 584 | service, scope := argv[0], key.Scope |
| 537 | 585 | if len(argv) != 2 { |
| 538 | 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 | 711 | kill := make(chan struct{}) |
| 664 | 712 | finished := make(chan struct{}) |
| 665 | 713 | 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) | |
| 692 | 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 | 264 | // UpdateIssueText edits title, body, and/or markup format; nil leaves a field |
| 265 | 265 | // unchanged. |
| 266 | 266 | func (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. | |
| 272 | func (s *Store) updateText(table string, id int64, title, body, format *string) error { | |
| 267 | 273 | set, args := []string{}, []any{} |
| 268 | 274 | if title != nil { |
| 269 | 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 | 284 | return nil |
| 279 | 285 | } |
| 280 | 286 | 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...) | |
| 283 | 289 | if err != nil { |
| 284 | 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 | 395 | // SetIssueAssignee adds or removes an assignee by user id. |
| 390 | 396 | func (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. | |
| 401 | func (s *Store) setItemUser(table, itemCol string, itemID, userID int64, add bool) error { | |
| 391 | 402 | if add { |
| 392 | 403 | _, 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) | |
| 395 | 406 | return err |
| 396 | 407 | } |
| 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) | |
| 399 | 409 | if err != nil { |
| 400 | 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 | 164 | // SetMRReviewRequest adds or removes a review request by user id — the |
| 165 | 165 | // mr review request counterpart of SetIssueAssignee. |
| 166 | 166 | func (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) | |
| 182 | 168 | } |
| 183 | 169 | |
| 184 | 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 | 482 | // UpdateMRText edits title, body, and/or markup format; nil leaves a field |
| 497 | 483 | // unchanged. |
| 498 | 484 | func (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) | |
| 522 | 486 | } |
| 523 | 487 | |
| 524 | 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 | |
| 142 | 142 | func (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) | |
| 157 | 144 | } |
| 158 | 145 | |
| 159 | 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 | |
| 335 | 322 | func (s *Store) UserByID(id int64) (User, error) { |
| 323 | return s.userBy("id", id) | |
| 324 | } | |
| 325 | ||
| 326 | // userBy reads the account whose column equals v. | |
| 327 | func (s *Store) userBy(column string, v any) (User, error) { | |
| 336 | 328 | var u User |
| 337 | 329 | var admin, pending, disabled, ghost int |
| 338 | 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 | 332 | Scan(&u.ID, &u.Username, &admin, &pending, &disabled, &deleteAfter, &ghost) |
| 341 | 333 | if errors.Is(err, sql.ErrNoRows) { |
| 342 | 334 | return u, ErrNotFound |
| @@ -388,13 +380,19 @@ func (s *Store) AddSSHKeyFrom(userID int64, fingerprint, algo string, blob []byt | ||
| 388 | 380 | // RemoveSSHKey removes a key owned by userID, bumps the key epoch, and |
| 389 | 381 | // announces the revocation. |
| 390 | 382 | func (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. | |
| 388 | func (s *Store) removeKey(query string, args ...any) error { | |
| 391 | 389 | tx, err := s.DB.Begin() |
| 392 | 390 | if err != nil { |
| 393 | 391 | return err |
| 394 | 392 | } |
| 395 | 393 | defer tx.Rollback() |
| 396 | 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 | 396 | if errors.Is(err, sql.ErrNoRows) { |
| 399 | 397 | return ErrNotFound |
| 400 | 398 | } |
| @@ -647,27 +645,7 @@ func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error) { | ||
| 647 | 645 | // RemoveDeployKey removes a deploy key from a repository by fingerprint; |
| 648 | 646 | // any repo admin may remove it regardless of who added it. |
| 649 | 647 | func (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( | |
| 657 | 649 | "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) | |
| 673 | 651 | } |
internal/symbols/extract.go +10 −7
| @@ -162,6 +162,11 @@ func extractGo(data []byte) []Symbol { | ||
| 162 | 162 | } |
| 163 | 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 | 170 | for _, d := range f.Decls { |
| 166 | 171 | switch d := d.(type) { |
| 167 | 172 | case *ast.FuncDecl: |
| @@ -176,18 +181,16 @@ func extractGo(data []byte) []Symbol { | ||
| 176 | 181 | } |
| 177 | 182 | add(d.Name, recv+"."+d.Name.Name, "method") |
| 178 | 183 | case *ast.GenDecl: |
| 184 | kind := "var" | |
| 185 | if d.Tok == token.CONST { | |
| 186 | kind = "const" | |
| 187 | } | |
| 179 | 188 | for _, spec := range d.Specs { |
| 180 | 189 | switch s := spec.(type) { |
| 181 | 190 | case *ast.TypeSpec: |
| 182 | 191 | add(s.Name, s.Name.Name, "type") |
| 183 | 192 | 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) | |
| 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 | 80 | for c := item.FirstChild(); c != nil; c = c.NextSibling() { |
| 81 | 81 | if c == item.FirstChild() { |
| 82 | 82 | 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 | |
| 88 | 84 | } |
| 85 | if !n.IsTight { | |
| 86 | r.w.blank() | |
| 87 | } | |
| 88 | r.block(c, hang, hang) | |
| 89 | 89 | } |
| 90 | 90 | p = rest |
| 91 | 91 | } |
internal/texmath/texmath.go +15 −2
| @@ -66,7 +66,7 @@ func Convert(tex string, display bool) (string, error) { | ||
| 66 | 66 | return "", errors.New("texmath: invalid UTF-8") |
| 67 | 67 | } |
| 68 | 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 | 70 | return "", errors.New("texmath: control character") |
| 71 | 71 | } |
| 72 | 72 | } |
| @@ -206,6 +206,19 @@ func (p *parser) next() token { | ||
| 206 | 206 | var starred = map[string]bool{"operatorname": true} |
| 207 | 207 | |
| 208 | 208 | func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } |
| 209 | func 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. | |
| 213 | func 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 | |
| 210 | 223 | func (p *parser) unexpected(t token) error { |
| 211 | 224 | switch t.kind { |
| @@ -402,7 +415,7 @@ func (p *parser) charAtom(t token) (*node, error) { | ||
| 402 | 415 | num := t.val |
| 403 | 416 | for p.pos < len(p.src) { |
| 404 | 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 | 419 | num += string(c) |
| 407 | 420 | p.pos++ |
| 408 | 421 | continue |