-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
370 lines (332 loc) · 8.73 KB
/
main.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"time"
"github.com/hashicorp/logutils"
"github.com/FuzzyMonkeyCo/monkey/pkg/as"
"github.com/FuzzyMonkeyCo/monkey/pkg/code"
"github.com/FuzzyMonkeyCo/monkey/pkg/cwid"
"github.com/FuzzyMonkeyCo/monkey/pkg/modeler"
rt "github.com/FuzzyMonkeyCo/monkey/pkg/runtime"
"github.com/FuzzyMonkeyCo/monkey/pkg/tags"
"github.com/FuzzyMonkeyCo/monkey/pkg/update"
)
const (
binName = "monkey"
githubSlug = "FuzzyMonkeyCo/" + binName
// Environment variables used
envAPIKey = "FUZZYMONKEY_API_KEY"
)
var (
binVersion = "M.m.p"
binTitle = strings.Join([]string{binName, binVersion,
regexp.MustCompile(`go[0-9.]+`).FindString(runtime.Version()),
runtime.GOOS, runtime.GOARCH}, " ")
)
func main() {
log.SetFlags(log.Lshortfile | log.Lmicroseconds | log.LUTC)
os.Exit(actualMain())
}
func actualMain() int {
start := time.Now()
args, ret := usage()
if args == nil {
return ret
}
if args.Version {
fmt.Println(binTitle)
return code.OK
}
if args.Logs {
return doLogs(args.File, args.LogOffset)
}
if args.Pastseed {
return doPastseed(args.File)
}
if args.Env {
return doEnv(args.EnvVars)
}
if args.Update {
return doUpdate()
}
if err := cwid.MakePwdID(binName, args.File, 0); err != nil {
as.ColorERR.Println(err) // Print as LogFile isn't set up yet
return code.Failed
}
logCatchall, err := os.OpenFile(cwid.LogFile(), os.O_WRONLY|os.O_CREATE, 0640)
if err != nil {
as.ColorERR.Println(err)
return retryOrReport()
}
defer logCatchall.Close()
logFiltered := &logutils.LevelFilter{
Levels: []logutils.LogLevel{"DBG", "NFO", "ERR", "NOP"},
MinLevel: logLevel(args.Verbosity),
Writer: os.Stderr,
}
log.SetOutput(io.MultiWriter(logCatchall, logFiltered))
log.Printf("[ERR] (not an error) %s %s %#v", binTitle, cwid.LogFile(), args)
defer func() { log.Printf("[ERR] (not an error) ran for %s", time.Since(start)) }()
if args.Fmt {
if err := rt.Format(args.File, args.FmtW); err != nil {
if e, ok := err.(rt.FmtError); ok {
for i := 0; i < len(e); i += 3 {
as.ColorNFO.Printf("%s ", e[i])
as.ColorOK.Printf("%s ", e[i+1])
as.ColorERR.Printf("%s\n", e[i+2])
}
} else {
as.ColorERR.Println(err)
}
return code.FailedFmt
}
return code.OK
}
mrt, err := rt.NewMonkey(binTitle, args.File, args.Labels)
if err != nil {
as.ColorERR.Println(err)
return code.Failed
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigC := make(chan os.Signal, 1)
signal.Notify(sigC, os.Interrupt)
go func() {
select {
case <-ctx.Done():
log.Println("[NFO] background context done")
signal.Stop(sigC)
case <-sigC:
log.Println("[NFO] received ^C: terminating")
cancel()
}
}()
// Always lint
if err := mrt.Lint(ctx, args.ShowSpec); err != nil {
as.ColorERR.Println(err)
return code.FailedLint
}
if args.Lint {
e := "Configuration is valid."
log.Println("[NFO]", e)
as.ColorNFO.Println(e)
return code.OK
}
if args.Exec {
var fn func(context.Context) error
switch {
case args.Start:
fn = mrt.JustExecStart
case args.Reset:
fn = mrt.JustExecReset
case args.Stop:
fn = mrt.JustExecStop
case args.Repl:
fn = mrt.JustExecREPL
default:
panic("unreachable")
}
if err := fn(ctx); err != nil {
if e := err.Error(); e != "" {
as.ColorERR.Println(e)
}
return code.FailedExec
}
return code.OK
}
if args.Schema {
ref := args.ValidateAgainst
if ref == "" {
mrt.WriteAbsoluteReferences(os.Stdout)
return code.OK
}
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Println("[ERR]", err)
return code.FailedSchema
}
if err := mrt.ValidateAgainstSchema(ref, data); err != nil {
switch err {
case modeler.ErrUnparsablePayload:
case modeler.ErrNoSuchSchema:
as.ColorERR.Printf("No such $ref '%s'\n", ref)
mrt.WriteAbsoluteReferences(os.Stdout)
default:
as.ColorERR.Println(err)
}
return code.FailedSchema
}
as.ColorNFO.Println("Payload is valid")
return code.OK
}
apiKey := os.Getenv(envAPIKey)
if apiKey == "" {
err := fmt.Errorf("$%s is unset", envAPIKey)
log.Println("[ERR]", err)
as.ColorERR.Println(err)
return code.Failed
}
as.ColorNFO.Printf("%d named schemas\n", mrt.InputsCount())
if err = mrt.FilterEndpoints(os.Args); err != nil {
as.ColorERR.Println(err)
return code.Failed
}
tagsFilter, err := newTagsFilter(args, os.Args)
if err != nil {
log.Println("[ERR]", err)
as.ColorERR.Println(err)
return code.Failed
}
if timeout := args.OverallBudgetTime; timeout != 0 {
ctx, cancel = context.WithTimeout(ctx, timeout)
}
defer cancel()
as.ColorNFO.Printf("\n Running tests...\n\n")
err = mrt.Fuzz(ctx, args.N, args.Seed, args.Verbosity, tagsFilter, args.Progress, apiKey)
defer func() {
if errC := mrt.Cleanup(context.Background()); errC != nil {
as.ColorERR.Println(err)
}
}()
switch {
case strings.Contains(err.Error(), context.Canceled.Error()):
as.ColorERR.Println("Testing interrupted.")
return code.Failed
case strings.Contains(err.Error(), context.DeadlineExceeded.Error()):
as.ColorERR.Printf("Testing interrupted (given: --time-budget-overall=%s).\n", args.OverallBudgetTime)
return code.OK
case strings.Contains(err.Error(), "unexpected client version, please update"):
return pleaseUpdate()
default:
log.Println("[ERR]", err)
}
switch err.(type) {
case *rt.TestingCampaignSuccess:
return code.OK
case *rt.TestingCampaignFailure:
return code.FailedFuzz
case *rt.TestingCampaignFailureDueToResetterError:
as.ColorERR.Println(err)
return code.FailedExec
}
as.ColorERR.Println(err)
return retryOrReport()
}
func logLevel(verbosity uint8) logutils.LogLevel {
lvl := map[uint8]string{
0: "NOP",
1: "ERR",
2: "NFO",
3: "DBG",
}[verbosity]
return logutils.LogLevel(lvl)
}
func doLogs(starfile string, offset uint64) int {
if err := cwid.MakePwdID(binName, starfile, offset); err != nil {
as.ColorERR.Println(err) // Print as LogFile isn't set up yet
return code.Failed
}
fn := cwid.LogFile()
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
as.ColorERR.Println("No logs for current project. Please change your working directory.")
return code.Failed
}
as.ColorERR.Println(err)
return code.Failed
}
defer f.Close()
os.Stderr.WriteString(fn + "\n")
if _, err := io.Copy(os.Stdout, f); err != nil {
as.ColorERR.Println(err)
return retryOrReport()
}
return code.OK
}
func doUpdate() int {
rel := update.NewGithubRelease(githubSlug, binName)
latest, err := rel.PeekLatestRelease()
if err != nil {
return retryOrReport()
}
if latest != binVersion {
fmt.Println("A version newer than", binVersion, "is out:", latest)
if err := rel.ReplaceCurrentRelease(latest); err != nil {
as.ColorERR.Println("The update failed 🙈 please try again later")
const latest = "https://github.com/" + githubSlug + "/releases/latest"
fmt.Println("You can always upgrade from", latest)
return code.FailedUpdate
}
}
return code.OK
}
func doEnv(vars []string) int {
all := map[string]bool{
envAPIKey: false,
}
penv := func(key string) { fmt.Printf("%s=%q\n", key, os.Getenv(key)) }
if len(vars) == 0 {
for key := range all {
penv(key)
}
return code.OK
}
penv = func(key string) { fmt.Println(os.Getenv(key)) }
for _, key := range vars {
if printed, ok := all[key]; !ok || printed {
return code.Failed
}
all[key] = true
penv(key)
}
return code.OK
}
func newTagsFilter(args *params, osargs []string) (*tags.Filter, error) {
var hasInclude, hasExclude bool
var included, excluded []string
if args.Tags != nil {
if csv := *args.Tags; csv != "" {
included = strings.Split(csv, ",")
}
hasInclude = len(included) == 0
}
if args.TagsExcluded != nil {
if csv := *args.TagsExcluded; csv != "" {
excluded = strings.Split(csv, ",")
}
hasExclude = len(excluded) == 0
}
return tags.NewFilter(hasInclude, hasExclude, included, excluded)
}
func pleaseUpdate() int {
w := os.Stderr
fmt.Fprintln(w, "\nThis program appears to be out of date. To update it, please run:")
fmt.Fprintf(w, "\n\tmonkey update\n")
maybeReport(w)
return code.FailedConnecting
}
func maybeReport(w io.Writer) {
const issues = "https://github.com/" + githubSlug + "/issues"
const email = "[email protected]"
fmt.Fprintf(w, "\nIf that doesn't fix it, take a look at %s\n", cwid.LogFile())
fmt.Fprintf(w, "or come by %s\n", issues)
fmt.Fprintf(w, "or drop us a line at %s\n", email)
fmt.Fprintln(w, "\nThank you for your patience & sorry about this :)")
}
func retryOrReport() int {
w := os.Stderr
fmt.Fprintln(w, "\nLooks like something went wrong... Maybe try again with -vv?")
fmt.Fprintf(w, "\nYou may want to try `monkey update`.\n")
maybeReport(w)
return code.Failed
}