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