-
Notifications
You must be signed in to change notification settings - Fork 4
/
webhook.go
349 lines (294 loc) · 7.76 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package caddy_webhook
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/WingLim/caddy-webhook/webhooks"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport"
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"go.uber.org/zap"
)
// Interface guards.
var (
_ caddy.Module = (*WebHook)(nil)
_ caddy.Provisioner = (*WebHook)(nil)
_ caddy.Validator = (*WebHook)(nil)
_ caddyhttp.MiddlewareHandler = (*WebHook)(nil)
)
func init() {
caddy.RegisterModule(new(WebHook))
httpcaddyfile.RegisterHandlerDirective("webhook", parseHandlerCaddyfile)
}
// WebHook is the module configuration.
type WebHook struct {
// Git repository URL, supported http, https and ssh.
Repository string `json:"repo,omitempty"`
// Path to clone and update repository.
Path string `json:"path,omitempty"`
// Branch to pull.
// Default to `main`.
Branch string `json:"branch,omitempty"`
// Webhook type.
// Default to `github`.
Type string `json:"type,omitempty"`
// Secret to verify webhook request.
Secret string `json:"secret,omitempty"`
// Depth for pull and fetch.
// Default to `0`.
Depth string `json:"depth,omitempty"`
// Enable recurse submodules.
Submodule bool `json:"submodule,omitempty"`
// Command to run when repo initializes or receive a
// correct webhook request.
Command []string `json:"command,omitempty"`
// Path of private key, using to access git with ssh.
Key string `json:"key,omitempty"`
// Password of private key.
KeyPassword string `json:"key_password,omitempty"`
// Username for http auth.
Username string `json:"username,omitempty"`
// Password for http auth.
Password string `json:"password,omitempty"`
// GitHub personal access token.
Token string `json:"token,omitempty"`
hook webhooks.HookService
auth transport.AuthMethod
cmd *Cmd
depth int
repo *Repo
log *zap.Logger
ctx context.Context
setup bool
}
// CaddyModule returns the Caddy module information.
func (*WebHook) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.webhook",
New: func() caddy.Module {
return new(WebHook)
},
}
}
// Provision set's up webhook configuration.
func (w *WebHook) Provision(ctx caddy.Context) error {
w.log = ctx.Logger(w)
w.ctx = ctx.Context
var err error
if w.Path == "" {
// If the path is empty for a repo, try to get the repo name from
// the Repository. If successful set it to "./<repo-name>" else
// set it to current working directory, i.e., "."
name, err := getRepoNameFromURL(w.Repository)
if err != nil {
w.Path = "."
} else {
w.Path = name
}
}
// Get the absolute path for logging
w.Path, err = filepath.Abs(w.Path)
if err != nil {
return err
}
w.setHookType()
// Convert depth from string to int
var depth int
if w.Depth != "" {
depth, err = strconv.Atoi(w.Depth)
if err != nil {
return err
}
} else {
depth = 0
}
w.depth = depth
if w.Command != nil {
w.cmd = &Cmd{}
w.cmd.AddCommand(w.Command, w.Path)
}
if w.Username != "" && w.Password != "" {
w.auth = &githttp.BasicAuth{
Username: w.Username,
Password: w.Password,
}
}
if w.Token != "" {
w.auth = &githttp.BasicAuth{
Username: "git", // This can be anything.
Password: w.Token,
}
}
if w.Key != "" {
publicKeys, err := ssh.NewPublicKeysFromFile("git", w.Key, w.KeyPassword)
if err != nil {
return err
}
w.auth = publicKeys
}
w.repo = NewRepo(w)
if w.Submodule {
w.repo.Submodule = git.DefaultSubmoduleRecursionDepth
} else {
w.repo.Submodule = git.NoRecurseSubmodules
}
return nil
}
// Validate ensures webhook's configuration is valid.
func (w *WebHook) Validate() error {
if w.Repository == "" {
return fmt.Errorf("cannot create repository with empty URL")
}
if w.Path == "" {
return fmt.Errorf("cannot create repository in empty path")
}
if w.Key != "" && w.auth.Name() != ssh.PublicKeysName {
return fmt.Errorf("wrong auth method with public key")
}
if w.Username != "" && w.Password != "" && w.auth.Name() != "http-basic-auth" {
return fmt.Errorf("wrong auth method with username and password")
}
if w.Token != "" && w.auth.Name() != "http-basic-auth" {
return fmt.Errorf("wrong auth method with token")
}
if !isEmptyOrGit(w.Path, w.log) {
return fmt.Errorf("given path is neither empty nor git repository")
}
go func(webhook *WebHook) {
if err := webhook.repo.Setup(webhook.ctx); err != nil {
webhook.log.Error(
"repository not setup",
zap.Error(err),
zap.String("path", webhook.Path))
return
}
webhook.setup = true
}(w)
return nil
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (w *WebHook) ServeHTTP(rw http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
if !w.setup {
return caddyhttp.Error(
http.StatusNotFound,
fmt.Errorf("page not found"),
)
}
if err := ValidateRequest(r); err != nil {
return err
}
hc := &webhooks.HookConf{
Secret: w.Secret,
RefName: w.repo.refName,
}
code, err := w.hook.Handle(r, hc)
if err != nil {
rw.WriteHeader(code)
w.log.Warn(err.Error())
return caddyhttp.Error(code, err)
}
go func(webhook *WebHook) {
webhook.log.Info("updating repository", zap.String("path", webhook.Path))
if err := webhook.repo.Update(webhook.ctx); err != nil {
if err == git.NoErrAlreadyUpToDate {
webhook.log.Info("already up-to-date", zap.String("path", webhook.Path))
} else {
webhook.log.Error(
"cannot update repository",
zap.Error(err),
zap.String("path", webhook.Path),
)
}
return
}
}(w)
return nil
}
// setHookType set the type which hook service we will use.
func (w *WebHook) setHookType() {
switch w.Type {
case "gitee":
w.hook = webhooks.Gitee{}
case "gitlab":
w.hook = webhooks.Gitlab{}
case "bitbucket":
w.hook = webhooks.Bitbucket{}
case "gogs":
w.hook = webhooks.Gogs{}
default:
w.hook = webhooks.Github{}
}
}
// ValidateRequest validates webhook request, the webhook request
// should be POST.
func ValidateRequest(r *http.Request) error {
if r.Method != http.MethodPost {
return fmt.Errorf("only %s method accepted; got %s", http.MethodPost, r.Method)
}
return nil
}
// getRepoNameFromURL extracts the repo name from the HTTP URL of the repo.
func getRepoNameFromURL(u string) (string, error) {
var name string
if strings.HasPrefix(u, "http") {
// Get repo name from http or https link.
// https://github.com/WingLim/caddy-webhook.git
netUrl, err := url.ParseRequestURI(u)
if err != nil {
return "", err
}
pathSegments := strings.Split(netUrl.Path, "/")
name = pathSegments[len(pathSegments)-1]
} else if strings.HasPrefix(u, "git") {
// Get repo name from ssh link.
// [email protected]:WingLim/caddy-webhook.git
pathSegments := strings.Split(u, "/")
name = pathSegments[len(pathSegments)-1]
} else {
return "", fmt.Errorf("unsupported protocol")
}
return strings.TrimSuffix(name, ".git"), nil
}
// isEmptyOrGit will check the path. If the path is neither empty nor a git
// directory, return error.
func isEmptyOrGit(path string, log *zap.Logger) bool {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return true
}
return false
}
if info.IsDir() {
f, err := os.Open(filepath.Clean(path))
if err != nil {
return false
}
defer func(f *os.File) {
if err := f.Close(); err != nil {
log.Error(err.Error())
}
}(f)
_, err = f.Readdirnames(1)
if err == io.EOF {
return true
}
}
_, err = git.PlainOpen(path)
if err != nil {
if err == git.ErrRepositoryNotExists {
return false
}
}
return true
}