-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
177 lines (159 loc) · 4.41 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
package main
import (
"archive/tar"
"bytes"
"cmp"
"compress/gzip"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
)
type PullRequest struct {
// Base may be empty if we only want to evaluate current status.
Base string `json:"base"`
Head string `json:"head"`
}
type Response struct {
SimpleFindings string `json:"simpleFindings"`
}
func internalError(w http.ResponseWriter, err string) {
fmt.Printf("Internal error: %s\n", err)
http.Error(w, fmt.Sprintf("Internal error: %s", err), http.StatusInternalServerError)
}
func handlePull(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req PullRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
fmt.Printf("Unable to decode body: %s\n", err)
http.Error(w, fmt.Sprintf("Unable to read body: %s", err), http.StatusBadRequest)
return
}
if req.Head == "" {
http.Error(w, "head cannot be empty", http.StatusBadRequest)
return
}
fmt.Printf("Attempting to analyze...\n")
// Create temp directories
tmpBase := cmp.Or(os.Getenv("TMPDIR"), "/tmp")
tmpDir, err := os.MkdirTemp(tmpBase, "banditize")
if err != nil {
internalError(w, err.Error())
return
}
defer os.RemoveAll(tmpDir)
baseDir := filepath.Join(tmpDir, "base")
headDir := filepath.Join(tmpDir, "head")
if err := os.Mkdir(baseDir, 0700); err != nil {
internalError(w, err.Error())
return
}
if err := os.Mkdir(headDir, 0700); err != nil {
internalError(w, err.Error())
return
}
baselineFile := filepath.Join(tmpDir, "baseline.json")
// Bandit crashes if you pass --baseline but the file doesn't exist
os.WriteFile(baselineFile, []byte("{}"), 0644)
if req.Base != "" {
if err := unpackTarball(req.Base, baseDir); err != nil {
internalError(w, err.Error())
return
}
baseScan := exec.Command("bandit", "-f", "json", "-o", baselineFile, "-r", "." /*baseDir*/, "--exit-zero")
baseScan.Dir = baseDir // Baselines only work in bandit if the filenames are the same
if output, err := baseScan.CombinedOutput(); err != nil {
fmt.Printf("Bandit output:\n%s\n", output)
internalError(w, fmt.Sprintf("Baseline failed: %s", err.Error()))
return
}
}
if err := unpackTarball(req.Head, headDir); err != nil {
internalError(w, err.Error())
return
}
// Analyze with Bandit
// TODO: add an ini file to ignore tests(?)
headScan := exec.Command("bandit", "--baseline", baselineFile, "-o", "-", "-r", "." /*headDir*/)
headScan.Dir = headDir // Baselines only work in bandit if the filenames are the same
output, err := headScan.Output()
if err == nil {
// Bandit had no findings, (exit status 0), so we can return early
resp := Response{
SimpleFindings: "",
}
fmt.Printf("Success: no findings\n")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() != 1 {
internalError(w, fmt.Sprintf("Bandit failed with exit code %d", exitErr.ExitCode()))
return
}
// Prepare response
resp := Response{
SimpleFindings: string(output),
}
fmt.Printf("Success: findings\n")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func unpackTarball(encoded string, dir string) error {
// Decode base64
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return err
}
buf := bytes.NewBuffer(decoded)
gzReader, err := gzip.NewReader(buf)
if err != nil {
return err
}
defer gzReader.Close()
tarReader := tar.NewReader(gzReader)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if !filepath.IsLocal(header.Name) {
return fmt.Errorf("tar contained invalid name %q", header.Name)
}
target := filepath.Join(dir, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
case tar.TypeReg:
file, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return err
}
if _, err := io.Copy(file, tarReader); err != nil {
file.Close()
return err
}
file.Close()
}
}
return nil
}
func main() {
http.HandleFunc("/pull", handlePull)
port := cmp.Or(os.Getenv("PORT"), "8080")
log.Printf("Listening on port %s\n", port)
log.Fatal(http.ListenAndServe(":" + port, nil))
}