cmd/gitbayd/main.go

7effe3feb4612cffb5ed38c02300299559aa8971
gitbay/cmd/gitbayd/main.go history · blame · raw

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