forked from jptosso/coraza-wasm-filter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magefile.go
293 lines (251 loc) · 8.63 KB
/
magefile.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
// Copyright The OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"github.com/tetratelabs/wabin/binary"
"github.com/tetratelabs/wabin/wasm"
)
var minGoVersion = "1.19"
var tinygoMinorVersion = "0.28"
var addLicenseVersion = "04bfe4ee9ca5764577b029acc6a1957fd1997153" // https://github.com/google/addlicense
var golangCILintVer = "v1.48.0" // https://github.com/golangci/golangci-lint/releases
var gosImportsVer = "v0.3.1" // https://github.com/rinchsan/gosimports/releases/tag/v0.3.1
var errCommitFormatting = errors.New("files not formatted, please commit formatting changes")
var errNoGitDir = errors.New("no .git directory found")
func init() {
for _, check := range []func() error{
checkTinygoVersion,
checkGoVersion,
} {
if err := check(); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
}
}
// checkGoVersion checks the minimum version of Go is supported.
func checkGoVersion() error {
v, err := sh.Output("go", "version")
if err != nil {
return fmt.Errorf("unexpected go error: %v", err)
}
// Version can/cannot include patch version e.g.
// - go version go1.19 darwin/arm64
// - go version go1.19.2 darwin/amd64
versionRegex := regexp.MustCompile("go([0-9]+).([0-9]+).?([0-9]+)?")
compare := versionRegex.FindStringSubmatch(v)
if len(compare) != 4 {
return fmt.Errorf("unexpected go semver: %q", v)
}
compare = compare[1:]
if compare[2] == "" {
compare[2] = "0"
}
base := strings.SplitN(minGoVersion, ".", 3)
if len(base) == 2 {
base = append(base, "0")
}
for i := 0; i < 3; i++ {
baseN, _ := strconv.Atoi(base[i])
compareN, _ := strconv.Atoi(compare[i])
if baseN > compareN {
return fmt.Errorf("unexpected go version, minimum want %q, have %q", minGoVersion, strings.Join(compare, "."))
}
}
return nil
}
// checkTinygoVersion checks that exactly the right tinygo version is supported because
// tinygo isn't stable yet.
func checkTinygoVersion() error {
v, err := sh.Output("tinygo", "version")
if err != nil {
return fmt.Errorf("unexpected tinygo error: %v", err)
}
// Assume a dev build is valid.
if strings.Contains(v, "-dev") {
return nil
}
if !strings.HasPrefix(v, fmt.Sprintf("tinygo version %s", tinygoMinorVersion)) {
return fmt.Errorf("unexpected tinygo version, wanted %s", tinygoMinorVersion)
}
return nil
}
// Format formats code in this repository.
func Format() error {
if err := sh.RunV("go", "mod", "tidy"); err != nil {
return err
}
// addlicense strangely logs skipped files to stderr despite not being erroneous, so use the long sh.Exec form to
// discard stderr too.
if _, err := sh.Exec(map[string]string{}, io.Discard, io.Discard, "go", "run", fmt.Sprintf("github.com/google/addlicense@%s", addLicenseVersion),
"-c", "The OWASP Coraza contributors",
"-s=only",
"-y=",
"-ignore", "**/*.yml",
"-ignore", "**/*.yaml",
"-ignore", "examples/**", "."); err != nil {
return err
}
return sh.RunV("go", "run", fmt.Sprintf("github.com/rinchsan/gosimports/cmd/gosimports@%s", gosImportsVer),
"-w",
"-local",
"github.com/corazawaf/coraza-proxy-wasm",
".")
}
// Lint verifies code quality.
func Lint() error {
if err := sh.RunV("go", "run", fmt.Sprintf("github.com/golangci/golangci-lint/cmd/golangci-lint@%s", golangCILintVer), "run"); err != nil {
return err
}
mg.SerialDeps(Format)
if sh.Run("git", "diff", "--exit-code") != nil {
return errCommitFormatting
}
return nil
}
// Test runs all unit tests.
func Test() error {
// by default multiphase is enabled
if os.Getenv("MULTIPHASE_EVAL") == "false" {
return sh.RunV("go", "test", "./...")
}
return sh.RunV("go", "test", "-tags=coraza.rule.multiphase_evaluation", "./...")
}
// Coverage runs tests with coverage and race detector enabled.
func Coverage() error {
if err := os.MkdirAll("build", 0755); err != nil {
return err
}
if _, err := os.Stat("build/mainraw.wasm"); err != nil {
return errors.New("build/mainraw.wasm not found, please run `go run mage.go build`")
}
if os.Getenv("MULTIPHASE_EVAL") == "false" {
// Test coraza-wasm filter without multiphase evaluation
if err := sh.RunV("go", "test", "-race", "-coverprofile=build/coverage.txt", "-covermode=atomic", "-coverpkg=./...", "./..."); err != nil {
return err
}
return sh.RunV("go", "tool", "cover", "-html=build/coverage.txt", "-o", "build/coverage.html")
} else {
// Test coraza-wasm filter with multiphase evaluation
if err := sh.RunV("go", "test", "-race", "-coverprofile=build/coverage_multi.txt", "-covermode=atomic", "-coverpkg=./...", "-tags=coraza.rule.multiphase_evaluation", "./..."); err != nil {
return err
}
return sh.RunV("go", "tool", "cover", "-html=build/coverage_multi.txt", "-o", "build/coverage.html")
}
}
// Doc runs godoc, access at http://localhost:6060
func Doc() error {
return sh.RunV("go", "run", "golang.org/x/tools/cmd/godoc@latest", "-http=:6060")
}
// Check runs lint and tests.
func Check() {
mg.SerialDeps(Lint, Test)
}
// Build builds the Coraza wasm plugin.
func Build() error {
if err := os.MkdirAll("build", 0755); err != nil {
return err
}
buildTags := []string{"custommalloc", "no_fs_access"}
// By default multiphase evaluation is enabled
if os.Getenv("MULTIPHASE_EVAL") != "false" {
buildTags = append(buildTags, "coraza.rule.multiphase_evaluation")
}
if os.Getenv("TIMING") == "true" {
buildTags = append(buildTags, "timing", "proxywasm_timing")
}
if os.Getenv("MEMSTATS") == "true" {
buildTags = append(buildTags, "memstats")
}
buildTagArg := fmt.Sprintf("-tags='%s'", strings.Join(buildTags, " "))
// ~100MB initial heap
initialPages := 2100
if ipEnv := os.Getenv("INITIAL_PAGES"); ipEnv != "" {
if ip, err := strconv.Atoi(ipEnv); err != nil {
return err
} else {
initialPages = ip
}
}
if err := sh.RunV("tinygo", "build", "-gc=custom", "-opt=2", "-o", filepath.Join("build", "mainraw.wasm"), "-scheduler=none", "-target=wasi", buildTagArg); err != nil {
return err
}
return patchWasm(filepath.Join("build", "mainraw.wasm"), filepath.Join("build", "main.wasm"), initialPages)
}
// E2e runs e2e tests with a built plugin against the example deployment. Requires docker-compose.
func E2e() error {
if err := sh.RunV("docker-compose", "--file", "e2e/docker-compose.yml", "build", "--pull"); err != nil {
return err
}
return sh.RunV("docker-compose", "-f", "e2e/docker-compose.yml", "up", "--abort-on-container-exit", "tests")
}
// Ftw runs ftw tests with a built plugin and Envoy. Requires docker-compose.
func Ftw() error {
if err := sh.RunV("docker-compose", "--file", "ftw/docker-compose.yml", "build", "--pull"); err != nil {
return err
}
defer func() {
_ = sh.RunV("docker-compose", "--file", "ftw/docker-compose.yml", "down", "-v")
}()
env := map[string]string{
"FTW_CLOUDMODE": os.Getenv("FTW_CLOUDMODE"),
"FTW_INCLUDE": os.Getenv("FTW_INCLUDE"),
"ENVOY_IMAGE": os.Getenv("ENVOY_IMAGE"),
}
if os.Getenv("ENVOY_NOWASM") == "true" {
env["ENVOY_CONFIG"] = "/conf/envoy-config-nowasm.yaml"
}
task := "ftw"
if os.Getenv("MEMSTATS") == "true" {
task = "ftw-memstats"
}
return sh.RunWithV(env, "docker-compose", "--file", "ftw/docker-compose.yml", "run", "--rm", task)
}
// RunExample spins up the test environment, access at http://localhost:8080. Requires docker-compose.
func RunExample() error {
return sh.RunWithV(map[string]string{"ENVOY_IMAGE": os.Getenv("ENVOY_IMAGE")}, "docker-compose", "--file", "example/docker-compose.yml", "up", "-d", "envoy-logs")
}
// TeardownExample tears down the test environment. Requires docker-compose.
func TeardownExample() error {
return sh.RunV("docker-compose", "--file", "example/docker-compose.yml", "down")
}
// ReloadExample reload the test environment (container) in case of envoy or wasm update. Requires docker-compose
func ReloadExample() error {
return sh.RunV("docker-compose", "--file", "example/docker-compose.yml", "restart")
}
var Default = Build
func patchWasm(inPath, outPath string, initialPages int) error {
raw, err := os.ReadFile(inPath)
if err != nil {
return err
}
mod, err := binary.DecodeModule(raw, wasm.CoreFeaturesV2)
if err != nil {
return err
}
mod.MemorySection.Min = uint32(initialPages)
for _, imp := range mod.ImportSection {
switch {
case imp.Name == "fd_filestat_get":
imp.Name = "fd_fdstat_get"
case imp.Name == "path_filestat_get":
imp.Module = "env"
imp.Name = "proxy_get_header_map_value"
}
}
out := binary.EncodeModule(mod)
if err = os.WriteFile(outPath, out, 0644); err != nil {
return err
}
return nil
}