cmd/gitbayd/main.go

01856d444da2d5d102113c67e35d1a477bae0541
gitbay/cmd/gitbayd/main.go

581 lines · 18182 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					hs.TLSConfig = serverTLS(nil)
243					errCh <- hs.ListenAndServeTLS(cfg.HTTP.CertFile, cfg.HTTP.KeyFile)
244				case "acme":
245					host := cfg.SiteHost()
246					stripPort := func(hp string) string {
247						if h, _, err := net.SplitHostPort(hp); err == nil {
248							return h
249						}
250						return hp
251					}
252					// Beyond the site host, allow <owner>.<pages domain>
253					// for owners that exist — certs come on demand per
254					// subdomain, no wildcard needed.
255					hostPolicy := func(ctx context.Context, h string) error {
256						if h == host {
257							return nil
258						}
259						if pd := cfg.Pages.Domain; pd != "" {
260							if h == pd {
261								return nil // apex: serves a redirect to the forge
262							}
263							if owner, ok := strings.CutSuffix(h, "."+pd); ok &&
264								!strings.Contains(owner, ".") && st.OwnerExists(owner) {
265								return nil
266							}
267						}
268						// Custom pages domains: certs only for claimed hosts.
269						if _, err := st.PageDomainRepo(h); err == nil {
270							return nil
271						}
272						return fmt.Errorf("host %q not served here", h)
273					}
274					m := &autocert.Manager{
275						Prompt:     autocert.AcceptTOS,
276						Cache:      autocert.DirCache(filepath.Join(cfg.Server.Root, "acme")),
277						HostPolicy: hostPolicy,
278						Email:      cfg.HTTP.ACMEEmail,
279					}
280					// TLS-ALPN-01 rides the HTTPS port itself. The optional
281					// plain-HTTP listener adds HTTP-01 and a redirect; losing
282					// it (port 80 taken, no privileges) is not fatal.
283					if addr := cfg.HTTP.ACMEHTTPAddr; addr != "" && addr != "off" {
284						redirect := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
285							// Pages hosts redirect to themselves, not the
286							// forge host.
287							target := host
288							if hostPolicy(r.Context(), stripPort(r.Host)) == nil {
289								target = stripPort(r.Host)
290							}
291							http.Redirect(w, r, "https://"+target+r.URL.RequestURI(), http.StatusMovedPermanently)
292						})
293						go func() {
294							slog.Info("acme http listening", "addr", addr)
295							acmeHTTP := &http.Server{Addr: addr, Handler: m.HTTPHandler(redirect),
296								ReadHeaderTimeout: 10 * time.Second, IdleTimeout: time.Minute}
297							if err := acmeHTTP.ListenAndServe(); err != nil {
298								slog.Warn("acme http listener failed; continuing with TLS-ALPN only", "err", err)
299							}
300						}()
301					}
302					hs.TLSConfig = serverTLS(m.TLSConfig())
303					errCh <- hs.ListenAndServeTLS("", "")
304				}
305			}()
306
307			if cfg.GitDaemon.Enabled {
308				gln, err := net.Listen("tcp", net.JoinHostPort("", strconv.Itoa(cfg.GitDaemon.Port)))
309				if err != nil {
310					return err
311				}
312				slog.Info("git-daemon listening", "addr", gln.Addr())
313				gitLn = gln
314				go func() { errCh <- gitd.New(cfg, st).Serve(gln) }()
315			}
316
317			select {
318			case err := <-errCh:
319				return err
320			case <-ctx.Done():
321			}
322			slog.Info("shutting down")
323			stop()
324			for _, ln := range []net.Listener{sshLn, gitLn} {
325				if ln != nil {
326					ln.Close()
327				}
328			}
329			// Follows run until a build ends; end them first so the drain
330			// waits only for work that finishes.
331			web.Stop()
332			if sshSrv != nil {
333				sshSrv.Stop()
334			}
335			drain, cancel := context.WithTimeout(context.Background(), 30*time.Second)
336			defer cancel()
337			if err := hs.Shutdown(drain); err != nil {
338				slog.Warn("http shutdown", "err", err)
339			}
340			if sshSrv != nil {
341				if err := sshSrv.Shutdown(drain); err != nil {
342					slog.Warn("ssh shutdown", "err", err)
343				}
344			}
345			return nil
346		},
347	}
348}
349
350func migrateCmd() *cobra.Command {
351	var to int
352	cmd := &cobra.Command{
353		Use:   "migrate",
354		Short: "apply schema migrations",
355		RunE: func(cmd *cobra.Command, args []string) error {
356			cfg, err := config.Load(configPath)
357			if err != nil {
358				return err
359			}
360			s, err := store.Open(cfg.Server.Root + "/gitbay.db")
361			if err != nil {
362				return err
363			}
364			defer s.Close()
365			if err := s.MigrateTo(to); err != nil {
366				return err
367			}
368			v, err := s.Version()
369			if err != nil {
370				return err
371			}
372			fmt.Println("schema version", v)
373			return nil
374		},
375	}
376	cmd.Flags().IntVar(&to, "to", -1, "target schema version (-1 = latest)")
377	return cmd
378}
379
380func adminCmd() *cobra.Command {
381	admin := &cobra.Command{
382		Use:   "admin",
383		Short: "host-local administration",
384	}
385	userCmd := &cobra.Command{Use: "user", Short: "manage users"}
386	userCmd.AddCommand(
387		hostUserCreateCmd(),
388		hostCmd("list [--state active|pending|disabled|admin] [--limit n] [--cursor c]", "list accounts", "admin", "user", "list"),
389		hostCmd("show <username>", "show an account: keys, emails, orgs, tokens, sessions", "admin", "user", "show"),
390		hostCmd("disable <username>", "suspend an account: keys and sessions refused until re-enabled", "admin", "user", "disable"),
391		hostCmd("enable <username>", "restore a suspended account", "admin", "user", "enable"),
392		hostCmd("delete <username> --yes", "delete an account that anchors nothing (keys, emails, and sessions go with it)", "admin", "user", "delete"),
393		hostCmd("promote <username>", "make an account an instance admin", "admin", "user", "promote"),
394		hostCmd("demote <username>", "remove instance admin from an account (never the last one)", "admin", "user", "demote"),
395		hostCmd("limits <username> [--repos n|default] [--bytes n|default]", "show or set repository and storage caps", "admin", "user", "limits"),
396	)
397	emailCmd := &cobra.Command{Use: "email", Short: "manage user emails"}
398	emailCmd.AddCommand(hostCmd("verify <username> <address>", "mark an email verified by admin assertion", "admin", "email", "verify"))
399	repoCmd := &cobra.Command{Use: "repo", Short: "any repository, for moderation (audited)"}
400	repoCmd.AddCommand(
401		hostCmd("list [--owner o] [--visibility public|private] [--limit n] [--cursor c]", "every repository with size and last push", "admin", "repo", "list"),
402		hostCmd("archive <owner/name>", "archive a repository", "admin", "repo", "archive"),
403		hostCmd("unarchive <owner/name>", "unarchive a repository", "admin", "repo", "unarchive"),
404		hostCmd("visibility <owner/name> public|private", "set a repository's visibility", "admin", "repo", "visibility"),
405		hostCmd("delete <owner/name> --yes", "delete a repository", "admin", "repo", "delete"),
406	)
407	configCmd := &cobra.Command{Use: "config", Short: "the configuration in effect"}
408	configCmd.AddCommand(configShowCmd())
409	admin.AddCommand(
410		userCmd,
411		emailCmd,
412		repoCmd,
413		configCmd,
414		hostCmd("invite --email <address>", "issue a registration invite and email its code", "admin", "invite"),
415		hostCmd("stats [--json]", "instance statistics: counts and per-repository disk usage", "admin", "stats"),
416		hostCmd("runners [--json]", "runner accounts: last poll, scope, the build each holds", "admin", "runners"),
417		hostCmd("audit [--limit n] [--json]", "print the security audit log, newest first", "audit"),
418		backupCmd(),
419		gcCmd(),
420		adminMigrateCommitRefsCmd(),
421		adminMigrateProfileAboutCmd(),
422		adminBackfillActivityCmd(),
423	)
424	return admin
425}
426
427// hostCmd runs a registry command as the host itself: an admin context
428// with no account behind it, so audit rows carry no actor and the source
429// "host". Arguments pass through untouched; the registry owns the flags,
430// which is what keeps this surface and an admin's SSH session from
431// drifting.
432func hostCmd(use, short string, path ...string) *cobra.Command {
433	return &cobra.Command{
434		Use:                use,
435		Short:              short,
436		DisableFlagParsing: true,
437		RunE: func(cmd *cobra.Command, args []string) error {
438			for _, a := range args {
439				if a == "--help" || a == "-h" {
440					return cmd.Help()
441				}
442			}
443			return runAsHost(path, args, os.Stdin)
444		},
445	}
446}
447
448// hostArgs pulls the root's --config out of args: with flag parsing off,
449// cobra hands the persistent flag through untouched.
450func hostArgs(args []string) []string {
451	var rest []string
452	for i := 0; i < len(args); i++ {
453		switch {
454		case args[i] == "--config" && i+1 < len(args):
455			configPath = args[i+1]
456			i++
457		case strings.HasPrefix(args[i], "--config="):
458			configPath = strings.TrimPrefix(args[i], "--config=")
459		default:
460			rest = append(rest, args[i])
461		}
462	}
463	return rest
464}
465
466func runAsHost(path, args []string, stdin io.Reader) error {
467	args = hostArgs(args)
468	cfg, err := config.Load(configPath)
469	if err != nil {
470		return err
471	}
472	st, err := openStore(cfg)
473	if err != nil {
474		return err
475	}
476	c := &control.Ctx{
477		User:   store.User{Username: "host", IsAdmin: true},
478		Scope:  "full",
479		Store:  st,
480		Cfg:    cfg,
481		Stdin:  stdin,
482		Stdout: os.Stdout,
483		Stderr: os.Stderr,
484		Source: "host",
485	}
486	code := control.Dispatch(c, append(append([]string{}, path...), args...))
487	st.Close()
488	if code != 0 {
489		os.Exit(code)
490	}
491	return nil
492}
493
494// hostUserCreateCmd keeps --key <path>, which the registry command cannot
495// take (no file paths over SSH): the file becomes the command's stdin.
496func hostUserCreateCmd() *cobra.Command {
497	return &cobra.Command{
498		Use:                "create <username> [--admin] [--email <address> [--verified]] [--key <file>]",
499		Short:              "create a user (host-local bootstrap; the only path in closed mode)",
500		DisableFlagParsing: true,
501		RunE: func(cmd *cobra.Command, args []string) error {
502			var stdin io.Reader = os.Stdin
503			var rest []string
504			args = hostArgs(args)
505			for i := 0; i < len(args); i++ {
506				switch {
507				case args[i] == "--help" || args[i] == "-h":
508					return cmd.Help()
509				case args[i] == "--key" && i+1 < len(args) && args[i+1] != "-":
510					f, err := os.Open(args[i+1])
511					if err != nil {
512						return err
513					}
514					defer f.Close()
515					stdin = f
516					rest = append(rest, "--key", "-")
517					i++
518				default:
519					rest = append(rest, args[i])
520				}
521			}
522			return runAsHost([]string{"admin", "user", "create"}, rest, stdin)
523		},
524	}
525}
526
527// sweep prunes expired sessions and tokens, and rows past their
528// configured retention, hourly and once at start. GITBAY_SWEEP_TICK
529// shortens the interval for tests.
530func sweep(ctx context.Context, st *store.Store, cfg config.Config) {
531	tick := time.Hour
532	if v := os.Getenv("GITBAY_SWEEP_TICK"); v != "" {
533		if d, err := time.ParseDuration(v); err == nil {
534			tick = d
535		}
536	}
537	audit, events, deliveries, mail, push := cfg.Retention.Durations()
538	r := store.Retention{Audit: audit, Events: events,
539		WebhookDeliveries: deliveries, Mail: mail, Push: push}
540	t := time.NewTicker(tick)
541	defer t.Stop()
542	for {
543		swept, err := st.Sweep(r, time.Now())
544		if err != nil {
545			slog.Error("sweeping", "err", err, "removed", swept.Total())
546		} else if n := swept.Total(); n > 0 {
547			slog.Info("swept expired rows", "removed", n, "tables", swept)
548		}
549		select {
550		case <-ctx.Done():
551			return
552		case <-t.C:
553		}
554	}
555}
556
557// reapPending removes self-registered accounts still unverified after
558// maxAge, hourly and once at start. GITBAY_REAP_TICK shortens the
559// interval for tests.
560func reapPending(ctx context.Context, st *store.Store, maxAge time.Duration) {
561	tick := time.Hour
562	if v := os.Getenv("GITBAY_REAP_TICK"); v != "" {
563		if d, err := time.ParseDuration(v); err == nil {
564			tick = d
565		}
566	}
567	t := time.NewTicker(tick)
568	defer t.Stop()
569	for {
570		if removed, err := st.ReapPendingUsers(maxAge); err != nil {
571			slog.Error("reaping pending accounts", "err", err)
572		} else if len(removed) > 0 {
573			slog.Info("removed unverified accounts", "users", removed)
574		}
575		select {
576		case <-ctx.Done():
577			return
578		case <-t.C:
579		}
580	}
581}