cmd/gitbayd/main.go

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