cmd/gitbayd/main.go

447 lines · 13844 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("runners [--json]", "runner accounts: last poll, scope, the build each holds", "admin", "runners"),
340		hostCmd("audit [--limit n] [--json]", "print the security audit log, newest first", "audit"),
341		backupCmd(),
342		gcCmd(),
343		adminMigrateCommitRefsCmd(),
344		adminBackfillActivityCmd(),
345	)
346	return admin
347}
348
349// hostCmd runs a registry command as the host itself: an admin context
350// with no account behind it, so audit rows carry no actor and the source
351// "host". Arguments pass through untouched; the registry owns the flags,
352// which is what keeps this surface and an admin's SSH session from
353// drifting.
354func hostCmd(use, short string, path ...string) *cobra.Command {
355	return &cobra.Command{
356		Use:                use,
357		Short:              short,
358		DisableFlagParsing: true,
359		RunE: func(cmd *cobra.Command, args []string) error {
360			for _, a := range args {
361				if a == "--help" || a == "-h" {
362					return cmd.Help()
363				}
364			}
365			return runAsHost(path, args, os.Stdin)
366		},
367	}
368}
369
370// hostArgs pulls the root's --config out of args: with flag parsing off,
371// cobra hands the persistent flag through untouched.
372func hostArgs(args []string) []string {
373	var rest []string
374	for i := 0; i < len(args); i++ {
375		switch {
376		case args[i] == "--config" && i+1 < len(args):
377			configPath = args[i+1]
378			i++
379		case strings.HasPrefix(args[i], "--config="):
380			configPath = strings.TrimPrefix(args[i], "--config=")
381		default:
382			rest = append(rest, args[i])
383		}
384	}
385	return rest
386}
387
388func runAsHost(path, args []string, stdin io.Reader) error {
389	args = hostArgs(args)
390	cfg, err := config.Load(configPath)
391	if err != nil {
392		return err
393	}
394	st, err := openStore(cfg)
395	if err != nil {
396		return err
397	}
398	c := &control.Ctx{
399		User:   store.User{Username: "host", IsAdmin: true},
400		Scope:  "full",
401		Store:  st,
402		Cfg:    cfg,
403		Stdin:  stdin,
404		Stdout: os.Stdout,
405		Stderr: os.Stderr,
406		Source: "host",
407	}
408	code := control.Dispatch(c, append(append([]string{}, path...), args...))
409	st.Close()
410	if code != 0 {
411		os.Exit(code)
412	}
413	return nil
414}
415
416// hostUserCreateCmd keeps --key <path>, which the registry command cannot
417// take (no file paths over SSH): the file becomes the command's stdin.
418func hostUserCreateCmd() *cobra.Command {
419	return &cobra.Command{
420		Use:                "create <username> [--admin] [--email <address> [--verified]] [--key <file>]",
421		Short:              "create a user (host-local bootstrap; the only path in closed mode)",
422		DisableFlagParsing: true,
423		RunE: func(cmd *cobra.Command, args []string) error {
424			var stdin io.Reader = os.Stdin
425			var rest []string
426			args = hostArgs(args)
427			for i := 0; i < len(args); i++ {
428				switch {
429				case args[i] == "--help" || args[i] == "-h":
430					return cmd.Help()
431				case args[i] == "--key" && i+1 < len(args) && args[i+1] != "-":
432					f, err := os.Open(args[i+1])
433					if err != nil {
434						return err
435					}
436					defer f.Close()
437					stdin = f
438					rest = append(rest, "--key", "-")
439					i++
440				default:
441					rest = append(rest, args[i])
442				}
443			}
444			return runAsHost([]string{"admin", "user", "create"}, rest, stdin)
445		},
446	}
447}