cmd/gitbayd/main.go

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