cmd/gitbayd/main.go
580 lines · 18136 bytes
1// gitbayd is the forge server daemon. The same binary also runs in hook mode
2// (invoked by git via core.hooksPath) and hosts the host-local admin commands.
3package main
4
5import (
6 "context"
7 "fmt"
8 "io"
9 "log/slog"
10 "net"
11 "net/http"
12 "os"
13 "os/signal"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "syscall"
18 "time"
19
20 "github.com/spf13/cobra"
21 "golang.org/x/crypto/acme/autocert"
22
23 "gitbay.org/gitbay/internal/buildinfo"
24 "gitbay.org/gitbay/internal/ci"
25 "gitbay.org/gitbay/internal/config"
26 "gitbay.org/gitbay/internal/control"
27 "gitbay.org/gitbay/internal/deps"
28 "gitbay.org/gitbay/internal/gitd"
29 "gitbay.org/gitbay/internal/hookd"
30 "gitbay.org/gitbay/internal/httpd"
31 "gitbay.org/gitbay/internal/mirror"
32 "gitbay.org/gitbay/internal/notify"
33 "gitbay.org/gitbay/internal/push"
34 "gitbay.org/gitbay/internal/sshd"
35 "gitbay.org/gitbay/internal/store"
36 "gitbay.org/gitbay/internal/toolpath"
37 "gitbay.org/gitbay/internal/webhook"
38)
39
40func openStore(cfg config.Config) (*store.Store, error) {
41 s, err := store.Open(filepath.Join(cfg.Server.Root, "gitbay.db"))
42 if err != nil {
43 return nil, err
44 }
45 // Say so when the schema moves. A restart migrates in silence otherwise,
46 // which makes an unexpected schema version hard to attribute to the deploy
47 // that caused it.
48 before, err := s.Version()
49 if err != nil {
50 s.Close()
51 return nil, err
52 }
53 if err := s.MigrateUp(); err != nil {
54 s.Close()
55 return nil, err
56 }
57 after, err := s.Version()
58 if err != nil {
59 s.Close()
60 return nil, err
61 }
62 if after != before {
63 slog.Info("schema migrated", "from", before, "to", after)
64 }
65 return s, nil
66}
67
68var configPath string
69
70func main() {
71 root := &cobra.Command{
72 Use: "gitbayd",
73 Short: "gitbay server daemon",
74 SilenceUsage: true,
75 SilenceErrors: true,
76 }
77 root.PersistentFlags().StringVar(&configPath, "config", "/etc/gitbay/config.toml", "path to config file")
78
79 root.AddCommand(
80 checkConfigCmd(),
81 serveCmd(),
82 migrateCmd(),
83 adminCmd(),
84 hookCmd(),
85 authorizedKeysCmd(),
86 shellCmd(),
87 versionCmd(),
88 )
89
90 if err := root.Execute(); err != nil {
91 fmt.Fprintln(os.Stderr, "gitbayd:", err)
92 os.Exit(1)
93 }
94}
95
96func checkConfigCmd() *cobra.Command {
97 var noHost bool
98 cmd := &cobra.Command{
99 Use: "check-config",
100 Short: "validate the configuration and exit",
101 RunE: func(cmd *cobra.Command, args []string) error {
102 cfg, err := config.Load(configPath)
103 if err != nil {
104 return err
105 }
106 if !noHost {
107 if err := cfg.CheckHost(); err != nil {
108 return err
109 }
110 }
111 fmt.Println("config ok")
112 return nil
113 },
114 }
115 cmd.Flags().BoolVar(&noHost, "no-host-checks", false, "skip host environment probes (port binding, paths)")
116 return cmd
117}
118
119func serveCmd() *cobra.Command {
120 return &cobra.Command{
121 Use: "serve",
122 Short: "run the ssh, http, and git listeners",
123 RunE: func(cmd *cobra.Command, args []string) error {
124 // First line of every run: the journal then says which commit is
125 // serving, without rebuilding the binary to find out.
126 logBuild()
127 // The tools this daemon shells out to are resolved once, at
128 // package init. Say so now rather than failing on whichever
129 // request first needed git.
130 if err := toolpath.Verify(); err != nil {
131 return fmt.Errorf("required tools missing: %w", err)
132 }
133 cfg, err := config.Load(configPath)
134 if err != nil {
135 return err
136 }
137 warnIfUnmerged(cfg)
138 st, err := openStore(cfg)
139 if err != nil {
140 return err
141 }
142 defer st.Close()
143
144 // Regenerate hook scripts so a moved binary self-heals, then
145 // start the hook policy socket.
146 self, err := os.Executable()
147 if err != nil {
148 return err
149 }
150 if err := hookd.WriteHookScripts(control.HooksDir(cfg.Server.Root), self); err != nil {
151 return err
152 }
153 stopHookd, err := hookd.Serve(cfg, st)
154 if err != nil {
155 return err
156 }
157 defer stopHookd()
158
159 // SIGTERM is how a deploy restarts the daemon: stop accepting,
160 // let what is in flight finish, exit 0 (#105).
161 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
162 defer stop()
163
164 // Outbound webhook deliveries, and the mail queue when SMTP is
165 // configured, share one retry base. It is overridable for
166 // tests via GITBAY_WEBHOOK_RETRY_BASE; notify.DefaultRetryBase
167 // names the production default so nothing else has to guess it.
168 retryBase := notify.DefaultRetryBase
169 if v := os.Getenv("GITBAY_WEBHOOK_RETRY_BASE"); v != "" {
170 if d, err := time.ParseDuration(v); err == nil {
171 retryBase = d
172 }
173 }
174 whCtx, whCancel := context.WithCancel(context.Background())
175 defer whCancel()
176 go webhook.New(st, cfg.Webhooks.AllowLocal, retryBase).Run(whCtx)
177 if cfg.Mail.SMTPHost != "" {
178 go notify.New(st, cfg, retryBase).Run(whCtx)
179 }
180 if cfg.Push.Enabled {
181 p, err := push.New(st, cfg.Push, cfg.Server.SiteURL, retryBase)
182 if err != nil {
183 // Config validation already parsed the key, so this
184 // is not a misconfiguration; fail loudly rather than
185 // running with a silent delivery route.
186 slog.Error("push: starting deliverer", "err", err)
187 } else {
188 go p.Run(whCtx)
189 }
190 }
191 go mirror.New(st, cfg).Run(whCtx)
192 if d := cfg.Registration.PendingExpiryDuration(); d > 0 {
193 go reapPending(whCtx, st, d)
194 }
195 go sweep(whCtx, st, cfg)
196 go (&ci.Scheduler{St: st, SiteURL: cfg.Server.SiteURL,
197 RepoDir: func(owner, name string) string {
198 return control.RepoDir(cfg.Server.Root, owner, name)
199 }}).Run(whCtx)
200 go deps.New(st, cfg, func(owner, name string) string {
201 return control.RepoDir(cfg.Server.Root, owner, name)
202 }, buildinfo.String()).Run(whCtx)
203
204 errCh := make(chan error, 3)
205 var sshSrv *sshd.Server
206 var sshLn, gitLn net.Listener
207 if cfg.SSH.Mode == "embedded" {
208 srv, err := sshd.New(cfg, st)
209 if err != nil {
210 return err
211 }
212 ln, err := net.Listen("tcp", net.JoinHostPort("", strconv.Itoa(cfg.SSH.Port)))
213 if err != nil {
214 return err
215 }
216 slog.Info("ssh listening", "addr", ln.Addr())
217 sshSrv, sshLn = srv, ln
218 go func() { errCh <- srv.Serve(ln) }()
219 } else {
220 // system mode: the host sshd owns the SSH port and invokes
221 // this binary via AuthorizedKeysCommand + forced command.
222 slog.Info("ssh handled by host sshd (ssh.mode = system)")
223 }
224
225 web := httpd.New(cfg, st)
226 // Header and idle timeouts bound what an idle or slow client can
227 // hold open. No write timeout: archives and upload-pack stream
228 // for as long as they take (#104).
229 hs := &http.Server{
230 Addr: cfg.HTTP.Addr,
231 Handler: web.Handler(),
232 ReadHeaderTimeout: 10 * time.Second,
233 IdleTimeout: 2 * time.Minute,
234 MaxHeaderBytes: 64 << 10,
235 }
236 go func() {
237 slog.Info("http listening", "addr", cfg.HTTP.Addr, "tls", cfg.HTTP.TLS)
238 switch cfg.HTTP.TLS {
239 case "off":
240 errCh <- hs.ListenAndServe()
241 case "files":
242 errCh <- hs.ListenAndServeTLS(cfg.HTTP.CertFile, cfg.HTTP.KeyFile)
243 case "acme":
244 host := cfg.SiteHost()
245 stripPort := func(hp string) string {
246 if h, _, err := net.SplitHostPort(hp); err == nil {
247 return h
248 }
249 return hp
250 }
251 // Beyond the site host, allow <owner>.<pages domain>
252 // for owners that exist — certs come on demand per
253 // subdomain, no wildcard needed.
254 hostPolicy := func(ctx context.Context, h string) error {
255 if h == host {
256 return nil
257 }
258 if pd := cfg.Pages.Domain; pd != "" {
259 if h == pd {
260 return nil // apex: serves a redirect to the forge
261 }
262 if owner, ok := strings.CutSuffix(h, "."+pd); ok &&
263 !strings.Contains(owner, ".") && st.OwnerExists(owner) {
264 return nil
265 }
266 }
267 // Custom pages domains: certs only for claimed hosts.
268 if _, err := st.PageDomainRepo(h); err == nil {
269 return nil
270 }
271 return fmt.Errorf("host %q not served here", h)
272 }
273 m := &autocert.Manager{
274 Prompt: autocert.AcceptTOS,
275 Cache: autocert.DirCache(filepath.Join(cfg.Server.Root, "acme")),
276 HostPolicy: hostPolicy,
277 Email: cfg.HTTP.ACMEEmail,
278 }
279 // TLS-ALPN-01 rides the HTTPS port itself. The optional
280 // plain-HTTP listener adds HTTP-01 and a redirect; losing
281 // it (port 80 taken, no privileges) is not fatal.
282 if addr := cfg.HTTP.ACMEHTTPAddr; addr != "" && addr != "off" {
283 redirect := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
284 // Pages hosts redirect to themselves, not the
285 // forge host.
286 target := host
287 if hostPolicy(r.Context(), stripPort(r.Host)) == nil {
288 target = stripPort(r.Host)
289 }
290 http.Redirect(w, r, "https://"+target+r.URL.RequestURI(), http.StatusMovedPermanently)
291 })
292 go func() {
293 slog.Info("acme http listening", "addr", addr)
294 acmeHTTP := &http.Server{Addr: addr, Handler: m.HTTPHandler(redirect),
295 ReadHeaderTimeout: 10 * time.Second, IdleTimeout: time.Minute}
296 if err := acmeHTTP.ListenAndServe(); err != nil {
297 slog.Warn("acme http listener failed; continuing with TLS-ALPN only", "err", err)
298 }
299 }()
300 }
301 hs.TLSConfig = m.TLSConfig()
302 errCh <- hs.ListenAndServeTLS("", "")
303 }
304 }()
305
306 if cfg.GitDaemon.Enabled {
307 gln, err := net.Listen("tcp", net.JoinHostPort("", strconv.Itoa(cfg.GitDaemon.Port)))
308 if err != nil {
309 return err
310 }
311 slog.Info("git-daemon listening", "addr", gln.Addr())
312 gitLn = gln
313 go func() { errCh <- gitd.New(cfg, st).Serve(gln) }()
314 }
315
316 select {
317 case err := <-errCh:
318 return err
319 case <-ctx.Done():
320 }
321 slog.Info("shutting down")
322 stop()
323 for _, ln := range []net.Listener{sshLn, gitLn} {
324 if ln != nil {
325 ln.Close()
326 }
327 }
328 // Follows run until a build ends; end them first so the drain
329 // waits only for work that finishes.
330 web.Stop()
331 if sshSrv != nil {
332 sshSrv.Stop()
333 }
334 drain, cancel := context.WithTimeout(context.Background(), 30*time.Second)
335 defer cancel()
336 if err := hs.Shutdown(drain); err != nil {
337 slog.Warn("http shutdown", "err", err)
338 }
339 if sshSrv != nil {
340 if err := sshSrv.Shutdown(drain); err != nil {
341 slog.Warn("ssh shutdown", "err", err)
342 }
343 }
344 return nil
345 },
346 }
347}
348
349func migrateCmd() *cobra.Command {
350 var to int
351 cmd := &cobra.Command{
352 Use: "migrate",
353 Short: "apply schema migrations",
354 RunE: func(cmd *cobra.Command, args []string) error {
355 cfg, err := config.Load(configPath)
356 if err != nil {
357 return err
358 }
359 s, err := store.Open(cfg.Server.Root + "/gitbay.db")
360 if err != nil {
361 return err
362 }
363 defer s.Close()
364 if err := s.MigrateTo(to); err != nil {
365 return err
366 }
367 v, err := s.Version()
368 if err != nil {
369 return err
370 }
371 fmt.Println("schema version", v)
372 return nil
373 },
374 }
375 cmd.Flags().IntVar(&to, "to", -1, "target schema version (-1 = latest)")
376 return cmd
377}
378
379func adminCmd() *cobra.Command {
380 admin := &cobra.Command{
381 Use: "admin",
382 Short: "host-local administration",
383 }
384 userCmd := &cobra.Command{Use: "user", Short: "manage users"}
385 userCmd.AddCommand(
386 hostUserCreateCmd(),
387 hostCmd("list [--state active|pending|disabled|admin] [--limit n] [--cursor c]", "list accounts", "admin", "user", "list"),
388 hostCmd("show <username>", "show an account: keys, emails, orgs, tokens, sessions", "admin", "user", "show"),
389 hostCmd("disable <username>", "suspend an account: keys and sessions refused until re-enabled", "admin", "user", "disable"),
390 hostCmd("enable <username>", "restore a suspended account", "admin", "user", "enable"),
391 hostCmd("delete <username> --yes", "delete an account that anchors nothing (keys, emails, and sessions go with it)", "admin", "user", "delete"),
392 hostCmd("promote <username>", "make an account an instance admin", "admin", "user", "promote"),
393 hostCmd("demote <username>", "remove instance admin from an account (never the last one)", "admin", "user", "demote"),
394 hostCmd("limits <username> [--repos n|default] [--bytes n|default]", "show or set repository and storage caps", "admin", "user", "limits"),
395 )
396 emailCmd := &cobra.Command{Use: "email", Short: "manage user emails"}
397 emailCmd.AddCommand(hostCmd("verify <username> <address>", "mark an email verified by admin assertion", "admin", "email", "verify"))
398 repoCmd := &cobra.Command{Use: "repo", Short: "any repository, for moderation (audited)"}
399 repoCmd.AddCommand(
400 hostCmd("list [--owner o] [--visibility public|private] [--limit n] [--cursor c]", "every repository with size and last push", "admin", "repo", "list"),
401 hostCmd("archive <owner/name>", "archive a repository", "admin", "repo", "archive"),
402 hostCmd("unarchive <owner/name>", "unarchive a repository", "admin", "repo", "unarchive"),
403 hostCmd("visibility <owner/name> public|private", "set a repository's visibility", "admin", "repo", "visibility"),
404 hostCmd("delete <owner/name> --yes", "delete a repository", "admin", "repo", "delete"),
405 )
406 configCmd := &cobra.Command{Use: "config", Short: "the configuration in effect"}
407 configCmd.AddCommand(configShowCmd())
408 admin.AddCommand(
409 userCmd,
410 emailCmd,
411 repoCmd,
412 configCmd,
413 hostCmd("invite --email <address>", "issue a registration invite and email its code", "admin", "invite"),
414 hostCmd("stats [--json]", "instance statistics: counts and per-repository disk usage", "admin", "stats"),
415 hostCmd("runners [--json]", "runner accounts: last poll, scope, the build each holds", "admin", "runners"),
416 hostCmd("audit [--limit n] [--json]", "print the security audit log, newest first", "audit"),
417 backupCmd(),
418 gcCmd(),
419 adminMigrateCommitRefsCmd(),
420 adminMigrateProfileAboutCmd(),
421 adminBackfillActivityCmd(),
422 )
423 return admin
424}
425
426// hostCmd runs a registry command as the host itself: an admin context
427// with no account behind it, so audit rows carry no actor and the source
428// "host". Arguments pass through untouched; the registry owns the flags,
429// which is what keeps this surface and an admin's SSH session from
430// drifting.
431func hostCmd(use, short string, path ...string) *cobra.Command {
432 return &cobra.Command{
433 Use: use,
434 Short: short,
435 DisableFlagParsing: true,
436 RunE: func(cmd *cobra.Command, args []string) error {
437 for _, a := range args {
438 if a == "--help" || a == "-h" {
439 return cmd.Help()
440 }
441 }
442 return runAsHost(path, args, os.Stdin)
443 },
444 }
445}
446
447// hostArgs pulls the root's --config out of args: with flag parsing off,
448// cobra hands the persistent flag through untouched.
449func hostArgs(args []string) []string {
450 var rest []string
451 for i := 0; i < len(args); i++ {
452 switch {
453 case args[i] == "--config" && i+1 < len(args):
454 configPath = args[i+1]
455 i++
456 case strings.HasPrefix(args[i], "--config="):
457 configPath = strings.TrimPrefix(args[i], "--config=")
458 default:
459 rest = append(rest, args[i])
460 }
461 }
462 return rest
463}
464
465func runAsHost(path, args []string, stdin io.Reader) error {
466 args = hostArgs(args)
467 cfg, err := config.Load(configPath)
468 if err != nil {
469 return err
470 }
471 st, err := openStore(cfg)
472 if err != nil {
473 return err
474 }
475 c := &control.Ctx{
476 User: store.User{Username: "host", IsAdmin: true},
477 Scope: "full",
478 Store: st,
479 Cfg: cfg,
480 Stdin: stdin,
481 Stdout: os.Stdout,
482 Stderr: os.Stderr,
483 Source: "host",
484 }
485 code := control.Dispatch(c, append(append([]string{}, path...), args...))
486 st.Close()
487 if code != 0 {
488 os.Exit(code)
489 }
490 return nil
491}
492
493// hostUserCreateCmd keeps --key <path>, which the registry command cannot
494// take (no file paths over SSH): the file becomes the command's stdin.
495func hostUserCreateCmd() *cobra.Command {
496 return &cobra.Command{
497 Use: "create <username> [--admin] [--email <address> [--verified]] [--key <file>]",
498 Short: "create a user (host-local bootstrap; the only path in closed mode)",
499 DisableFlagParsing: true,
500 RunE: func(cmd *cobra.Command, args []string) error {
501 var stdin io.Reader = os.Stdin
502 var rest []string
503 args = hostArgs(args)
504 for i := 0; i < len(args); i++ {
505 switch {
506 case args[i] == "--help" || args[i] == "-h":
507 return cmd.Help()
508 case args[i] == "--key" && i+1 < len(args) && args[i+1] != "-":
509 f, err := os.Open(args[i+1])
510 if err != nil {
511 return err
512 }
513 defer f.Close()
514 stdin = f
515 rest = append(rest, "--key", "-")
516 i++
517 default:
518 rest = append(rest, args[i])
519 }
520 }
521 return runAsHost([]string{"admin", "user", "create"}, rest, stdin)
522 },
523 }
524}
525
526// sweep prunes expired sessions and tokens, and rows past their
527// configured retention, hourly and once at start. GITBAY_SWEEP_TICK
528// shortens the interval for tests.
529func sweep(ctx context.Context, st *store.Store, cfg config.Config) {
530 tick := time.Hour
531 if v := os.Getenv("GITBAY_SWEEP_TICK"); v != "" {
532 if d, err := time.ParseDuration(v); err == nil {
533 tick = d
534 }
535 }
536 audit, events, deliveries, mail, push := cfg.Retention.Durations()
537 r := store.Retention{Audit: audit, Events: events,
538 WebhookDeliveries: deliveries, Mail: mail, Push: push}
539 t := time.NewTicker(tick)
540 defer t.Stop()
541 for {
542 swept, err := st.Sweep(r, time.Now())
543 if err != nil {
544 slog.Error("sweeping", "err", err, "removed", swept.Total())
545 } else if n := swept.Total(); n > 0 {
546 slog.Info("swept expired rows", "removed", n, "tables", swept)
547 }
548 select {
549 case <-ctx.Done():
550 return
551 case <-t.C:
552 }
553 }
554}
555
556// reapPending removes self-registered accounts still unverified after
557// maxAge, hourly and once at start. GITBAY_REAP_TICK shortens the
558// interval for tests.
559func reapPending(ctx context.Context, st *store.Store, maxAge time.Duration) {
560 tick := time.Hour
561 if v := os.Getenv("GITBAY_REAP_TICK"); v != "" {
562 if d, err := time.ParseDuration(v); err == nil {
563 tick = d
564 }
565 }
566 t := time.NewTicker(tick)
567 defer t.Stop()
568 for {
569 if removed, err := st.ReapPendingUsers(maxAge); err != nil {
570 slog.Error("reaping pending accounts", "err", err)
571 } else if len(removed) > 0 {
572 slog.Info("removed unverified accounts", "users", removed)
573 }
574 select {
575 case <-ctx.Done():
576 return
577 case <-t.C:
578 }
579 }
580}