cmd/gitbayd/hook.go
218 lines · 6514 bytes
1package main
2
3import (
4 "bufio"
5 "context"
6 "fmt"
7 "io"
8 "os"
9 "os/exec"
10 "strconv"
11 "strings"
12 "time"
13
14 "github.com/spf13/cobra"
15
16 "gitbay.org/gitbay/internal/gitutil"
17 "gitbay.org/gitbay/internal/hookd"
18 "gitbay.org/gitbay/internal/leaks"
19 "gitbay.org/gitbay/internal/policy"
20 "gitbay.org/gitbay/internal/toolpath"
21)
22
23// incomingSHAs lists the commits this push introduces, in order, without
24// duplicates. It runs in the hook process, which inherits git's quarantine
25// environment — the daemon cannot see these objects yet.
26func incomingSHAs(updates []policy.RefUpdate) ([]string, error) {
27 seen := map[string]bool{}
28 var out []string
29 for _, u := range updates {
30 if u.IsDelete {
31 continue
32 }
33 // Everything reachable from the new tip that no existing ref has.
34 raw, err := exec.Command(toolpath.Look("git"), "rev-list", u.New, "--not", "--all").Output()
35 if err != nil {
36 return nil, fmt.Errorf("rev-list %s: %w", u.New, err)
37 }
38 for _, sha := range strings.Fields(string(raw)) {
39 if seen[sha] {
40 continue
41 }
42 seen[sha] = true
43 out = append(out, sha)
44 }
45 }
46 return out, nil
47}
48
49// streamIncomingCommits reads every incoming commit through one
50// `cat-file --batch` and hands each to emit as it arrives.
51//
52// This used to fork a cat-file per commit and build the whole payload in
53// memory before sending it: a 50k-commit first push to a protected branch
54// forked 50k processes and held 50k raw commits at once (#100). One
55// subprocess now serves the whole push, and nothing is accumulated.
56func streamIncomingCommits(updates []policy.RefUpdate, emit func(hookd.RawCommit) error) error {
57 shas, err := incomingSHAs(updates)
58 if err != nil {
59 return err
60 }
61 if len(shas) == 0 {
62 return nil
63 }
64 // Cancelling kills git on an early return. Without it, bailing out
65 // part-way through a large push leaves git blocked writing into a
66 // pipe nobody is reading and Wait blocked on git.
67 ctx, cancel := context.WithCancel(context.Background())
68 cmd := exec.CommandContext(ctx, toolpath.Look("git"), "cat-file", "--batch")
69 stdin, err := cmd.StdinPipe()
70 if err != nil {
71 cancel()
72 return err
73 }
74 stdout, err := cmd.StdoutPipe()
75 if err != nil {
76 cancel()
77 return err
78 }
79 if err := cmd.Start(); err != nil {
80 cancel()
81 return fmt.Errorf("cat-file --batch: %w", err)
82 }
83 defer cmd.Wait() // second: reaps the process cancel just signalled
84 defer cancel()
85 // Feeding stdin from another goroutine: the pipe buffer is smaller
86 // than 50k object names, so writing them all before reading would
87 // block against a git that is blocked writing its own output.
88 writeErr := make(chan error, 1)
89 go func() {
90 defer stdin.Close()
91 w := bufio.NewWriter(stdin)
92 for _, sha := range shas {
93 if _, err := fmt.Fprintln(w, sha); err != nil {
94 writeErr <- err
95 return
96 }
97 }
98 writeErr <- w.Flush()
99 }()
100
101 r := bufio.NewReader(stdout)
102 for range shas {
103 // Each record is "<oid> <type> <size>\n", then size bytes, then
104 // a newline.
105 header, err := r.ReadString('\n')
106 if err != nil {
107 return fmt.Errorf("cat-file --batch: %w", err)
108 }
109 fields := strings.Fields(header)
110 if len(fields) != 3 {
111 return fmt.Errorf("cat-file --batch: unexpected %q", strings.TrimSpace(header))
112 }
113 size, err := strconv.Atoi(fields[2])
114 if err != nil {
115 return fmt.Errorf("cat-file --batch: bad size in %q", strings.TrimSpace(header))
116 }
117 raw := make([]byte, size)
118 if _, err := io.ReadFull(r, raw); err != nil {
119 return fmt.Errorf("cat-file %s: %w", fields[0], err)
120 }
121 if _, err := r.Discard(1); err != nil {
122 return fmt.Errorf("cat-file %s: %w", fields[0], err)
123 }
124 if err := emit(hookd.RawCommit{SHA: fields[0], Raw: raw}); err != nil {
125 return err
126 }
127 }
128 if err := <-writeErr; err != nil {
129 return fmt.Errorf("cat-file --batch: %w", err)
130 }
131 return nil
132}
133
134// scanDeadline bounds the secret scan of one push. Past it the scan is
135// reported as truncated: the pusher is waiting.
136const scanDeadline = 90 * time.Second
137
138// scanIncoming scans the blobs this push introduces. Like incomingSHAs it
139// runs in the hook process, the only one that can read the quarantine.
140func scanIncoming(updates []policy.RefUpdate) leaks.Report {
141 var revs []string
142 for _, u := range updates {
143 if !u.IsDelete {
144 revs = append(revs, u.New)
145 }
146 }
147 if len(revs) == 0 {
148 return leaks.Report{}
149 }
150 ctx, cancel := context.WithTimeout(context.Background(), scanDeadline)
151 defer cancel()
152 return leaks.Scan(ctx, ".", append(revs, "--not", "--all")...)
153}
154
155// hookCmd runs inside a git hook. It computes git facts here — the hook
156// process inherits git's quarantine environment, so incoming objects are
157// visible — and asks the daemon for a policy decision over the unix socket.
158func hookCmd() *cobra.Command {
159 return &cobra.Command{
160 Use: "hook <pre-receive|post-receive>",
161 Hidden: true,
162 Args: cobra.ExactArgs(1),
163 RunE: func(cmd *cobra.Command, args []string) error {
164 sock := os.Getenv(hookd.EnvSocket)
165 repoID, err1 := strconv.ParseInt(os.Getenv(hookd.EnvRepoID), 10, 64)
166 userID, err2 := strconv.ParseInt(os.Getenv(hookd.EnvUserID), 10, 64)
167 if sock == "" || err1 != nil || err2 != nil {
168 return fmt.Errorf("missing GITBAY_* environment; this command only runs as a git hook")
169 }
170
171 var updates []policy.RefUpdate
172 scanner := bufio.NewScanner(os.Stdin)
173 for scanner.Scan() {
174 fields := strings.Fields(scanner.Text())
175 if len(fields) != 3 {
176 continue
177 }
178 u := policy.RefUpdate{Old: fields[0], New: fields[1], Ref: fields[2]}
179 u.IsDelete = gitutil.ZeroSHA(u.New)
180 if !u.IsDelete && !gitutil.ZeroSHA(u.Old) {
181 anc, err := gitutil.IsAncestor(".", u.Old, u.New)
182 if err != nil {
183 return fmt.Errorf("checking ancestry for %s: %w", u.Ref, err)
184 }
185 u.IsForce = !anc
186 }
187 updates = append(updates, u)
188 }
189 if err := scanner.Err(); err != nil {
190 return err
191 }
192
193 resp, err := hookd.Ask(sock, hookd.Request{
194 Hook: args[0],
195 RepoID: repoID,
196 UserID: userID,
197 Scope: os.Getenv(hookd.EnvScope),
198 Token: os.Getenv(hookd.EnvToken),
199 Updates: updates,
200 }, func(emit func(hookd.RawCommit) error) error {
201 return streamIncomingCommits(updates, emit)
202 }, func() leaks.Report {
203 return scanIncoming(updates)
204 })
205 if err != nil {
206 return fmt.Errorf("gitbay daemon unreachable: %w", err)
207 }
208 if !resp.Allow {
209 fmt.Fprintln(os.Stderr, resp.Message)
210 os.Exit(1)
211 }
212 if resp.Message != "" {
213 fmt.Fprintln(os.Stderr, resp.Message)
214 }
215 return nil
216 },
217 }
218}