internal/hookd/hookd.go

438 lines · 14621 bytes

  1// Package hookd is the unix-socket bridge between git hooks and the daemon.
  2// The hook process (gitbayd in hook mode) computes git facts — it inherits
  3// git's quarantine environment, which the daemon does not see — and sends
  4// them here; the daemon answers with a policy decision.
  5//
  6// pre-receive is two-phase when the repo requires signed commits: the first
  7// response sets NeedCommits, and the hook answers with the raw commit
  8// objects (only the hook can read them out of quarantine) for verification.
  9// A further phase follows when the repo's secret scan is on: the response
 10// sets ScanSecrets, the hook scans the incoming blobs and answers with a
 11// leaks.Report — where each match is, never what it matched — and the
 12// daemon decides what the findings mean for the push.
 13package hookd
 14
 15import (
 16	"crypto/sha256"
 17	"encoding/json"
 18	"fmt"
 19	"log/slog"
 20	"net"
 21	"os"
 22	"path/filepath"
 23	"slices"
 24	"strings"
 25	"sync"
 26
 27	"gitbay.org/gitbay/internal/config"
 28	"gitbay.org/gitbay/internal/control"
 29	"gitbay.org/gitbay/internal/gitutil"
 30	"gitbay.org/gitbay/internal/leaks"
 31	"gitbay.org/gitbay/internal/policy"
 32	"gitbay.org/gitbay/internal/sig"
 33	"gitbay.org/gitbay/internal/store"
 34)
 35
 36// Env variable names passed to git transport subprocesses and inherited by
 37// hooks.
 38const (
 39	EnvSocket = "GITBAY_HOOK_SOCKET"
 40	EnvRepoID = "GITBAY_REPO_ID"
 41	EnvUserID = "GITBAY_USER_ID"
 42	EnvScope  = "GITBAY_KEY_SCOPE"
 43	// EnvToken names the receive-pack this hook runs under. sshd mints
 44	// it per push; hookd answers only a request carrying a live one
 45	// whose repository, account and scope match the request's.
 46	EnvToken = "GITBAY_PUSH_TOKEN"
 47)
 48
 49type Request struct {
 50	Hook   string `json:"hook"` // pre-receive | post-receive
 51	RepoID int64  `json:"repo_id"`
 52	UserID int64  `json:"user_id"`
 53	// Scope is the pushing key's scope. The user id alone is the account
 54	// the key belongs to, and a deploy key grants nothing outside its
 55	// binding, so anything acting on another repository needs this too.
 56	Scope   string             `json:"scope"`
 57	Token   string             `json:"token"`
 58	Updates []policy.RefUpdate `json:"updates"`
 59}
 60
 61// RawCommit is one incoming commit object. When NeedCommits is set the
 62// hook streams these one per JSON value and ends with a zero one, rather
 63// than sending a single message holding every commit in the push: an
 64// initial push of a large history is tens of thousands of them (#100).
 65type RawCommit struct {
 66	SHA string `json:"sha"`
 67	Raw []byte `json:"raw"`
 68}
 69
 70// Done marks the end of the commit stream.
 71func (c RawCommit) Done() bool { return c.SHA == "" }
 72
 73// Response is the daemon's answer. A Message on an allowed push is a
 74// warning the hook prints for the pusher.
 75type Response struct {
 76	Allow       bool   `json:"allow"`
 77	Message     string `json:"message,omitempty"`
 78	NeedCommits bool   `json:"need_commits,omitempty"`
 79	ScanSecrets bool   `json:"scan_secrets,omitempty"`
 80}
 81
 82// SocketPath returns the hook socket location. It prefers the server root,
 83// but unix socket paths are capped (~104 bytes on macOS, 108 on Linux), so
 84// deep roots fall back to a hashed name under the system temp directory.
 85// Hooks receive the chosen path via GITBAY_HOOK_SOCKET, so both sides always
 86// agree.
 87func SocketPath(root string) string {
 88	p := filepath.Join(root, "hook.sock")
 89	if len(p) <= 100 {
 90		return p
 91	}
 92	sum := sha256.Sum256([]byte(root))
 93	return filepath.Join(os.TempDir(), fmt.Sprintf("gitbay-%x.sock", sum[:8]))
 94}
 95
 96type Server struct {
 97	cfg config.Config
 98	st  *store.Store
 99}
100
101// Serve listens on the unix socket until the listener is closed.
102func Serve(cfg config.Config, st *store.Store) (func() error, error) {
103	path := SocketPath(cfg.Server.Root)
104	os.Remove(path)
105	ln, err := net.Listen("unix", path)
106	if err != nil {
107		return nil, err
108	}
109	// Listen creates the socket under the process umask. Hooks run as
110	// the daemon's own user; nobody else has a reason to connect.
111	if err := os.Chmod(path, 0o600); err != nil {
112		ln.Close()
113		return nil, err
114	}
115	s := &Server{cfg: cfg, st: st}
116	go func() {
117		for {
118			conn, err := ln.Accept()
119			if err != nil {
120				return
121			}
122			go s.handle(conn)
123		}
124	}()
125	return ln.Close, nil
126}
127
128func (s *Server) handle(conn net.Conn) {
129	defer conn.Close()
130	dec := json.NewDecoder(conn)
131	enc := json.NewEncoder(conn)
132	if err := peerCheck(conn); err != nil {
133		slog.Warn("hook socket: refused connection", "err", err)
134		// Nothing about the request is known yet, and no account.
135		control.AuditRefused(s.st, 0, "refused hook", map[string]any{"reason": err.Error()})
136		enc.Encode(Response{Allow: false, Message: "hook socket: " + err.Error()})
137		return
138	}
139	var req Request
140	if err := dec.Decode(&req); err != nil {
141		enc.Encode(Response{Allow: false, Message: "bad hook request"})
142		return
143	}
144	if actor, msg := s.authorize(req); msg != "" {
145		control.AuditRefused(s.st, actor, "refused hook",
146			map[string]any{"repo_id": req.RepoID, "hook": req.Hook, "reason": msg})
147		enc.Encode(Response{Allow: false, Message: msg})
148		return
149	}
150	switch req.Hook {
151	case "pre-receive":
152		preReceiveStarted(req.Token)
153		s.preReceive(req, dec, enc)
154	case "post-receive":
155		s.postReceive(req)
156		enc.Encode(Response{Allow: true})
157	default:
158		enc.Encode(Response{Allow: false, Message: fmt.Sprintf("unknown hook %q", req.Hook)})
159	}
160}
161
162// authorize ties a request to a receive-pack sshd started: its token
163// must be live and name the same repository, account and key scope.
164// On a refusal actor is the token's account when the token is live,
165// and 0 otherwise: the request's own user id is only a claim.
166func (s *Server) authorize(req Request) (actor int64, msg string) {
167	if req.Token == "" {
168		return 0, "push not started by this server"
169	}
170	tok, err := s.st.PushTokenByHash(store.HashToken(req.Token))
171	if err != nil {
172		return 0, "push not started by this server"
173	}
174	if tok.RepoID != req.RepoID || tok.UserID != req.UserID || tok.Scope != req.Scope {
175		return tok.UserID, "push token does not match this request"
176	}
177	return 0, ""
178}
179
180// peerCheck is checkPeer; tests replace it.
181var peerCheck = checkPeer
182
183// auditedRefs is how many ref names a refused-push row keeps; the rest
184// are counted, so one push of many refs cannot write an unbounded row.
185const auditedRefs = 20
186
187// refusePush answers a pre-receive refusal and audits it.
188func (s *Server) refusePush(enc *json.Encoder, req Request, repo store.Repo, msg string) {
189	n := min(len(req.Updates), auditedRefs)
190	refs := make([]string, n)
191	for i, u := range req.Updates[:n] {
192		refs[i] = u.Ref
193	}
194	data := map[string]any{"repo": repo.Path(), "refs": refs, "reason": msg}
195	if more := len(req.Updates) - n; more > 0 {
196		data["more_refs"] = more
197	}
198	control.AuditRefused(s.st, req.UserID, "refused push", data)
199	enc.Encode(Response{Allow: false, Message: msg})
200}
201
202func (s *Server) preReceive(req Request, dec *json.Decoder, enc *json.Encoder) {
203	repo, err := s.st.RepoByID(req.RepoID)
204	if err != nil {
205		enc.Encode(Response{Allow: false, Message: "unknown repository"})
206		return
207	}
208	if msg := policy.CheckPush(repo, req.Updates); msg != "" {
209		s.refusePush(enc, req, repo, msg)
210		return
211	}
212	if msg := s.releaseAnchors(repo, req.Updates); msg != "" {
213		s.refusePush(enc, req, repo, msg)
214		return
215	}
216	if repo.Settings.RequireSignedCommits {
217		if msg, ok := s.verifyIncoming(dec, enc); !ok {
218			return
219		} else if msg != "" {
220			s.refusePush(enc, req, repo, msg)
221			return
222		}
223	}
224	warning := ""
225	if leaks.Mode(repo.Settings.SecretScan) != leaks.ModeOff {
226		if err := enc.Encode(Response{Allow: true, ScanSecrets: true}); err != nil {
227			return
228		}
229		var rep leaks.Report
230		if err := dec.Decode(&rep); err != nil {
231			enc.Encode(Response{Allow: false, Message: "bad secret scan payload"})
232			return
233		}
234		msg, refuse := s.judgeSecrets(req, repo, rep)
235		if refuse {
236			s.refusePush(enc, req, repo, msg)
237			return
238		}
239		warning = msg
240	}
241	enc.Encode(Response{Allow: true, Message: warning})
242}
243
244// verifyIncoming is the signed-commits phase: it asks the hook for the
245// incoming commit objects and verifies each. ok is false when the exchange
246// itself failed and has been answered; otherwise msg is the refusal, or ""
247// when every commit verified.
248func (s *Server) verifyIncoming(dec *json.Decoder, enc *json.Encoder) (msg string, ok bool) {
249	if err := enc.Encode(Response{Allow: true, NeedCommits: true}); err != nil {
250		return "", false
251	}
252	// Each commit is verified as it arrives, so nothing holds the push in
253	// memory. The first refusal decides the answer, but the stream is
254	// still drained to its end before replying: the hook is writing, and
255	// answering early would leave it writing into a socket nobody reads.
256	// Draining costs a decode per commit and no verification.
257	db := store.SigDB{Store: s.st}
258	refusal := ""
259	for {
260		var rc RawCommit
261		if err := dec.Decode(&rc); err != nil {
262			enc.Encode(Response{Allow: false, Message: "bad commits payload"})
263			return "", false
264		}
265		if rc.Done() {
266			break
267		}
268		if refusal != "" {
269			continue
270		}
271		parsed, err := sig.ParseCommit(rc.Raw)
272		if err != nil {
273			refusal = fmt.Sprintf("unparseable commit %s", rc.SHA)
274			continue
275		}
276		res, err := sig.VerifyCommit(db, parsed)
277		if err != nil || res.State != sig.Verified {
278			state := "error"
279			if err == nil {
280				state = string(res.State)
281			}
282			refusal = fmt.Sprintf("this repository requires signed commits: %.10s is %s", rc.SHA, state)
283		}
284	}
285	return refusal, true
286}
287
288// judgeSecrets applies the repository's mode and allowlist to the hook's
289// scan. It returns the message for the pusher, and whether the push is
290// refused. A scan that failed refuses under block, since block promises
291// nothing unscanned lands, and warns under warn. Accepted findings are
292// audited, so they are on record after the warning scrolls away.
293func (s *Server) judgeSecrets(req Request, repo store.Repo, rep leaks.Report) (string, bool) {
294	block := leaks.Mode(repo.Settings.SecretScan) == leaks.ModeBlock
295	if rep.Error != "" {
296		msg := "secret scan failed: " + rep.Error
297		if block {
298			return msg + "\nthis repository blocks pushes it cannot scan", true
299		}
300		return msg, false
301	}
302	found := leaks.Allowed(rep.Findings, repo.Settings.SecretScanAllow)
303	if len(found) == 0 {
304		return "", false
305	}
306	if block {
307		return leaks.Describe("secret scan: refused, "+leaks.Plural(len(found))+" in this push:", found, rep.Truncated) +
308			"\nremove them from the commits and push again; an admin can allow a path with" +
309			"\n  repo settings secret-scan-allow " + repo.Path() + " <glob>...", true
310	}
311	rules := map[string]bool{}
312	for _, f := range found {
313		rules[f.Rule] = true
314	}
315	ruleList := make([]string, 0, len(rules))
316	for r := range rules {
317		ruleList = append(ruleList, r)
318	}
319	slices.Sort(ruleList)
320	s.st.Audit(req.UserID, "push.secrets", map[string]any{
321		"repo": repo.Path(), "findings": len(found), "rules": ruleList, "truncated": rep.Truncated})
322	return leaks.Describe("secret scan: "+leaks.Plural(len(found))+" in this push:", found, rep.Truncated) +
323		"\nthe push was accepted. A real credential is now in this repository's history: revoke it.", false
324}
325
326// releaseAnchors refuses deleting or moving a tag that a release is
327// anchored to. A release outliving its tag served assets for a commit
328// nobody could reach (#201); the release goes first, then the tag.
329func (s *Server) releaseAnchors(repo store.Repo, updates []policy.RefUpdate) string {
330	for _, u := range updates {
331		tag, ok := strings.CutPrefix(u.Ref, "refs/tags/")
332		if !ok || gitutil.ZeroSHA(u.Old) {
333			continue
334		}
335		if _, err := s.st.ReleaseByTag(repo.ID, tag); err != nil {
336			continue
337		}
338		verb := "moved"
339		if u.IsDelete {
340			verb = "deleted"
341		}
342		return fmt.Sprintf("tag %s anchors a release and cannot be %s: delete the release first", tag, verb)
343	}
344	return ""
345}
346
347// postReceive runs the ref-update work for a push; see
348// control.RefsUpdated, which server-side writes to a branch share.
349func (s *Server) postReceive(req Request) {
350	control.RefsUpdated(s.st, s.cfg, req.RepoID, req.UserID, req.Scope, req.Updates)
351}
352
353// Ask sends one request from the hook process to the daemon. stream is
354// called if the daemon asks for the incoming commit objects; it hands each
355// commit to the callback, which writes it on the wire. scan is called if
356// the daemon asks for a secret scan of the incoming blobs.
357func Ask(socketPath string, req Request, stream func(emit func(RawCommit) error) error, scan func() leaks.Report) (Response, error) {
358	conn, err := net.Dial("unix", socketPath)
359	if err != nil {
360		return Response{}, err
361	}
362	defer conn.Close()
363	enc := json.NewEncoder(conn)
364	dec := json.NewDecoder(conn)
365	if err := enc.Encode(req); err != nil {
366		return Response{}, err
367	}
368	for {
369		var resp Response
370		if err := dec.Decode(&resp); err != nil {
371			return Response{}, err
372		}
373		switch {
374		case resp.NeedCommits:
375			if err := stream(func(rc RawCommit) error { return enc.Encode(rc) }); err != nil {
376				return Response{}, err
377			}
378			if err := enc.Encode(RawCommit{}); err != nil { // end of stream
379				return Response{}, err
380			}
381		case resp.ScanSecrets:
382			if err := enc.Encode(scan()); err != nil {
383				return Response{}, err
384			}
385		default:
386			return resp, nil
387		}
388	}
389}
390
391// WriteHookScripts (re)generates the shared hooks directory. Called at
392// daemon startup so a moved binary self-heals; every repo points here via
393// core.hooksPath.
394func WriteHookScripts(hooksDir, gitbaydPath string) error {
395	if err := os.MkdirAll(hooksDir, 0o755); err != nil {
396		return err
397	}
398	for _, hook := range []string{"pre-receive", "post-receive"} {
399		script := fmt.Sprintf("#!/bin/sh\nexec %q hook %s\n", gitbaydPath, hook)
400		if err := os.WriteFile(filepath.Join(hooksDir, hook), []byte(script), 0o755); err != nil {
401			return err
402		}
403	}
404	return nil
405}
406
407// awaiting holds, per push token, a channel closed when that push's
408// pre-receive reaches hookd. sshd uses it to tell a pack still arriving
409// from one being checked.
410var (
411	awaitMu  sync.Mutex
412	awaiting = map[string]chan struct{}{}
413)
414
415// AwaitPreReceive returns a channel that closes when pre-receive for
416// the push holding token reaches this process's hookd, and forget,
417// which drops the registration. Under ssh.mode = "system" the push runs
418// in another process and the channel never closes.
419func AwaitPreReceive(token string) (started <-chan struct{}, forget func()) {
420	ch := make(chan struct{})
421	awaitMu.Lock()
422	awaiting[token] = ch
423	awaitMu.Unlock()
424	return ch, func() {
425		awaitMu.Lock()
426		delete(awaiting, token)
427		awaitMu.Unlock()
428	}
429}
430
431func preReceiveStarted(token string) {
432	awaitMu.Lock()
433	defer awaitMu.Unlock()
434	if ch, ok := awaiting[token]; ok {
435		close(ch)
436		delete(awaiting, token)
437	}
438}