/
main.go
194 lines (157 loc) · 4.85 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
/*
Copyright 2022 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"time"
"go.uber.org/zap"
spec "knative.dev/security-guard/pkg/apis/guard/v1alpha1"
utils "knative.dev/security-guard/pkg/guard-utils"
"github.com/kelseyhightower/envconfig"
)
var log *zap.SugaredLogger
const (
serviceIntervalDefault = 5 * time.Minute
)
type config struct {
GuardServiceLogLevel string `split_words:"true" required:"false"`
GuardServiceInterval string `split_words:"true" required:"false"`
}
type learner struct {
services *services
pileLearnTicker *utils.Ticker
}
// Common method used for parsing ns, sid, cmFlag from all requests
func (l *learner) baseHandler(query url.Values) (record *serviceRecord, err error) {
cmFlagSlice := query["cm"]
sidSlice := query["sid"]
nsSlice := query["ns"]
if len(sidSlice) != 1 || len(nsSlice) != 1 || len(cmFlagSlice) > 1 {
err = fmt.Errorf("wrong data sid %d ns %d cmflag %d", len(sidSlice), len(nsSlice), len(cmFlagSlice))
return
}
// extract and sanitize sid and ns
sid := utils.Sanitize(sidSlice[0])
ns := utils.Sanitize(nsSlice[0])
if strings.HasPrefix(sid, "ns-") {
sid = ""
err = fmt.Errorf("illegal sid %s", sid)
return
}
if len(sid) < 1 {
err = fmt.Errorf("wrong sid %s", sidSlice[0])
return
}
if len(ns) < 1 {
err = fmt.Errorf("wrong ns %s", nsSlice[0])
return
}
// extract and sanitize cmFlag
var cmFlag bool
if len(cmFlagSlice) > 0 {
cmFlag = (cmFlagSlice[0] == "true")
}
// get session record, create one if does not exist
log.Debugf("** baseHandler ** ns %s, sid %s, cmFlag %t", ns, sid, cmFlag)
record = l.services.get(ns, sid, cmFlag)
if record == nil {
// should never happen
err = fmt.Errorf("internal error no record created")
}
return
}
func (l *learner) fetchConfig(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" || req.URL.Path != "/config" {
http.Error(w, "404 not found.", http.StatusNotFound)
}
record, err := l.baseHandler(req.URL.Query())
if err != nil {
log.Infof("fetchConfig Missing data %v", err)
http.Error(w, "Missing data", http.StatusBadRequest)
return
}
buf, err := json.Marshal(record.guardianSpec)
if err != nil {
// should never happen
log.Infof("Servicing fetchConfig error while JSON Marshal %v", err)
http.Error(w, "Failed to marshal data", http.StatusInternalServerError)
return
}
w.Write(buf)
}
func (l *learner) processPile(w http.ResponseWriter, req *http.Request) {
var pile spec.SessionDataPile
var err error
record, err := l.baseHandler(req.URL.Query())
if err != nil {
log.Infof("fetchConfig Missing data %v", err)
http.Error(w, "processPile Missing data", http.StatusBadRequest)
return
}
err = json.NewDecoder(req.Body).Decode(&pile)
if err != nil {
log.Infof("processPile error: %s", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
l.services.merge(record, &pile)
log.Debugf("Successful setting record.wsgate")
w.Write([]byte{})
}
func (l *learner) mainEventLoop(quit chan string) {
for {
select {
case <-l.pileLearnTicker.Ch():
l.services.tick()
case reason := <-quit:
log.Infof("mainEventLoop was asked to quit! - Reason: %s", reason)
return
}
}
}
// Set network policies to ensure that only pods in your trust domain can use the service!
func preMain(minimumInterval time.Duration) (*learner, *http.ServeMux, string, chan string) {
var env config
if err := envconfig.Process("", &env); err != nil {
fmt.Fprintf(os.Stderr, "Failed to process environment: %s\n", err.Error())
os.Exit(1)
}
log = utils.CreateLogger(env.GuardServiceLogLevel)
l := new(learner)
l.pileLearnTicker = utils.NewTicker(minimumInterval)
l.pileLearnTicker.Parse(env.GuardServiceInterval, serviceIntervalDefault)
l.pileLearnTicker.Start()
l.services = newServices()
mux := http.NewServeMux()
mux.HandleFunc("/config", l.fetchConfig)
mux.HandleFunc("/pile", l.processPile)
target := ":8888"
quit := make(chan string)
log.Infof("Starting guard-service on %s", target)
return l, mux, target, quit
}
func main() {
l, mux, target, quit := preMain(utils.MinimumInterval)
// cant be tested due to KubeMgr
l.services.start()
// start a mainLoop
go l.mainEventLoop(quit)
err := http.ListenAndServe(target, mux)
log.Infof("Using target: %s - Failed to start %v", target, err)
quit <- "ListenAndServe failed"
}