cmd/gitbayd/main.go

e9566eed86ebcd185c4b85f63d667b5e671fe787
gitbay/cmd/gitbayd/main.go history · blame · raw

574 lines · 17970 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			drain, cancel := context.WithTimeout(context.Background(), 30*time.Second)
329			defer cancel()
330			if err := hs.Shutdown(drain); err != nil {
331				slog.Warn("http shutdown", "err", err)
332			}
333			if sshSrv != nil {
334				if err := sshSrv.Shutdown(drain); err != nil {
335					slog.Warn("ssh shutdown", "err", err)
336				}
337			}
338			return nil
339		},
340	}
341}
342
343func migrateCmd() *cobra.Command {
344	var to int
345	cmd := &cobra.Command{
346		Use:   "migrate",
347		Short: "apply schema migrations",
348		RunE: func(cmd *cobra.Command, args []string) error {
349			cfg, err := config.Load(configPath)
350			if err != nil {
351				return err
352			}
353			s, err := store.Open(cfg.Server.Root + "/gitbay.db")
354			if err != nil {
355				return err
356			}
357			defer s.Close()
358			if err := s.MigrateTo(to); err != nil {
359				return err
360			}
361			v, err := s.Version()
362			if err != nil {
363				return err
364			}
365			fmt.Println("schema version", v)
366			return nil
367		},
368	}
369	cmd.Flags().IntVar(&to, "to", -1, "target schema version (-1 = latest)")
370	return cmd
371}
372
373func adminCmd() *cobra.Command {
374	admin := &cobra.Command{
375		Use:   "admin",
376		Short: "host-local administration",
377	}
378	userCmd := &cobra.Command{Use: "user", Short: "manage users"}
379	userCmd.AddCommand(
380		hostUserCreateCmd(),
381		hostCmd("list [--state active|pending|disabled|admin] [--limit n] [--cursor c]", "list accounts", "admin", "user", "list"),
382		hostCmd("show <username>", "show an account: keys, emails, orgs, tokens, sessions", "admin", "user", "show"),
383		hostCmd("disable <username>", "suspend an account: keys and sessions refused until re-enabled", "admin", "user", "disable"),
384		hostCmd("enable <username>", "restore a suspended account", "admin", "user", "enable"),
385		hostCmd("delete <username> --yes", "delete an account that anchors nothing (keys, emails, and sessions go with it)", "admin", "user", "delete"),
386		hostCmd("promote <username>", "make an account an instance admin", "admin", "user", "promote"),
387		hostCmd("demote <username>", "remove instance admin from an account (never the last one)", "admin", "user", "demote"),
388		hostCmd("limits <username> [--repos n|default] [--bytes n|default]", "show or set repository and storage caps", "admin", "user", "limits"),
389	)
390	emailCmd := &cobra.Command{Use: "email", Short: "manage user emails"}
391	emailCmd.AddCommand(hostCmd("verify <username> <address>", "mark an email verified by admin assertion", "admin", "email", "verify"))
392	repoCmd := &cobra.Command{Use: "repo", Short: "any repository, for moderation (audited)"}
393	repoCmd.AddCommand(
394		hostCmd("list [--owner o] [--visibility public|private] [--limit n] [--cursor c]", "every repository with size and last push", "admin", "repo", "list"),
395		hostCmd("archive <owner/name>", "archive a repository", "admin", "repo", "archive"),
396		hostCmd("unarchive <owner/name>", "unarchive a repository", "admin", "repo", "unarchive"),
397		hostCmd("visibility <owner/name> public|private", "set a repository's visibility", "admin", "repo", "visibility"),
398		hostCmd("delete <owner/name> --yes", "delete a repository", "admin", "repo", "delete"),
399	)
400	configCmd := &cobra.Command{Use: "config", Short: "the configuration in effect"}
401	configCmd.AddCommand(configShowCmd())
402	admin.AddCommand(
403		userCmd,
404		emailCmd,
405		repoCmd,
406		configCmd,
407		hostCmd("invite --email <address>", "issue a registration invite and email its code", "admin", "invite"),
408		hostCmd("stats [--json]", "instance statistics: counts and per-repository disk usage", "admin", "stats"),
409		hostCmd("runners [--json]", "runner accounts: last poll, scope, the build each holds", "admin", "runners"),
410		hostCmd("audit [--limit n] [--json]", "print the security audit log, newest first", "audit"),
411		backupCmd(),
412		gcCmd(),
413		adminMigrateCommitRefsCmd(),
414		adminMigrateProfileAboutCmd(),
415		adminBackfillActivityCmd(),
416	)
417	return admin
418}
419
420// hostCmd runs a registry command as the host itself: an admin context
421// with no account behind it, so audit rows carry no actor and the source
422// "host". Arguments pass through untouched; the registry owns the flags,
423// which is what keeps this surface and an admin's SSH session from
424// drifting.
425func hostCmd(use, short string, path ...string) *cobra.Command {
426	return &cobra.Command{
427		Use:                use,
428		Short:              short,
429		DisableFlagParsing: true,
430		RunE: func(cmd *cobra.Command, args []string) error {
431			for _, a := range args {
432				if a == "--help" || a == "-h" {
433					return cmd.Help()
434				}
435			}
436			return runAsHost(path, args, os.Stdin)
437		},
438	}
439}
440
441// hostArgs pulls the root's --config out of args: with flag parsing off,
442// cobra hands the persistent flag through untouched.
443func hostArgs(args []string) []string {
444	var rest []string
445	for i := 0; i < len(args); i++ {
446		switch {
447		case args[i] == "--config" && i+1 < len(args):
448			configPath = args[i+1]
449			i++
450		case strings.HasPrefix(args[i], "--config="):
451			configPath = strings.TrimPrefix(args[i], "--config=")
452		default:
453			rest = append(rest, args[i])
454		}
455	}
456	return rest
457}
458
459func runAsHost(path, args []string, stdin io.Reader) error {
460	args = hostArgs(args)
461	cfg, err := config.Load(configPath)
462	if err != nil {
463		return err
464	}
465	st, err := openStore(cfg)
466	if err != nil {
467		return err
468	}
469	c := &control.Ctx{
470		User:   store.User{Username: "host", IsAdmin: true},
471		Scope:  "full",
472		Store:  st,
473		Cfg:    cfg,
474		Stdin:  stdin,
475		Stdout: os.Stdout,
476		Stderr: os.Stderr,
477		Source: "host",
478	}
479	code := control.Dispatch(c, append(append([]string{}, path...), args...))
480	st.Close()
481	if code != 0 {
482		os.Exit(code)
483	}
484	return nil
485}
486
487// hostUserCreateCmd keeps --key <path>, which the registry command cannot
488// take (no file paths over SSH): the file becomes the command's stdin.
489func hostUserCreateCmd() *cobra.Command {
490	return &cobra.Command{
491		Use:                "create <username> [--admin] [--email <address> [--verified]] [--key <file>]",
492		Short:              "create a user (host-local bootstrap; the only path in closed mode)",
493		DisableFlagParsing: true,
494		RunE: func(cmd *cobra.Command, args []string) error {
495			var stdin io.Reader = os.Stdin
496			var rest []string
497			args = hostArgs(args)
498			for i := 0; i < len(args); i++ {
499				switch {
500				case args[i] == "--help" || args[i] == "-h":
501					return cmd.Help()
502				case args[i] == "--key" && i+1 < len(args) && args[i+1] != "-":
503					f, err := os.Open(args[i+1])
504					if err != nil {
505						return err
506					}
507					defer f.Close()
508					stdin = f
509					rest = append(rest, "--key", "-")
510					i++
511				default:
512					rest = append(rest, args[i])
513				}
514			}
515			return runAsHost([]string{"admin", "user", "create"}, rest, stdin)
516		},
517	}
518}
519
520// sweep prunes expired sessions and tokens, and rows past their
521// configured retention, hourly and once at start. GITBAY_SWEEP_TICK
522// shortens the interval for tests.
523func sweep(ctx context.Context, st *store.Store, cfg config.Config) {
524	tick := time.Hour
525	if v := os.Getenv("GITBAY_SWEEP_TICK"); v != "" {
526		if d, err := time.ParseDuration(v); err == nil {
527			tick = d
528		}
529	}
530	audit, events, deliveries, mail, push := cfg.Retention.Durations()
531	r := store.Retention{Audit: audit, Events: events,
532		WebhookDeliveries: deliveries, Mail: mail, Push: push}
533	t := time.NewTicker(tick)
534	defer t.Stop()
535	for {
536		swept, err := st.Sweep(r, time.Now())
537		if err != nil {
538			slog.Error("sweeping", "err", err, "removed", swept.Total())
539		} else if n := swept.Total(); n > 0 {
540			slog.Info("swept expired rows", "removed", n, "tables", swept)
541		}
542		select {
543		case <-ctx.Done():
544			return
545		case <-t.C:
546		}
547	}
548}
549
550// reapPending removes self-registered accounts still unverified after
551// maxAge, hourly and once at start. GITBAY_REAP_TICK shortens the
552// interval for tests.
553func reapPending(ctx context.Context, st *store.Store, maxAge time.Duration) {
554	tick := time.Hour
555	if v := os.Getenv("GITBAY_REAP_TICK"); v != "" {
556		if d, err := time.ParseDuration(v); err == nil {
557			tick = d
558		}
559	}
560	t := time.NewTicker(tick)
561	defer t.Stop()
562	for {
563		if removed, err := st.ReapPendingUsers(maxAge); err != nil {
564			slog.Error("reaping pending accounts", "err", err)
565		} else if len(removed) > 0 {
566			slog.Info("removed unverified accounts", "users", removed)
567		}
568		select {
569		case <-ctx.Done():
570			return
571		case <-t.C:
572		}
573	}
574}