forked from kyma-project/api-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
315 lines (266 loc) · 10 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
/*
Copyright 2022.
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 (
"flag"
"fmt"
"os"
"strings"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"istio.io/api/networking/v1beta1"
rulev1alpha1 "github.com/ory/oathkeeper-maester/api/v1alpha1"
"github.com/vrischmann/envconfig"
networkingv1beta1 "istio.io/client-go/pkg/apis/networking/v1beta1"
securityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1"
gatewayv1beta1 "github.com/kyma-project/api-gateway/api/v1beta1"
"github.com/kyma-project/api-gateway/controllers"
"github.com/kyma-project/api-gateway/internal/validation"
"github.com/pkg/errors"
//+kubebuilder:scaffold:imports
)
type config struct {
SystemNamespace string `envconfig:"default=kyma-system"`
}
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(gatewayv1beta1.AddToScheme(scheme))
utilruntime.Must(networkingv1beta1.AddToScheme(scheme))
utilruntime.Must(rulev1alpha1.AddToScheme(scheme))
utilruntime.Must(securityv1beta1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var healthProbeAddr string
var enableLeaderElection bool
var oathkeeperSvcAddr string
var oathkeeperSvcPort uint
var blockListedServices string
var allowListedDomains string
var domainName string
var corsAllowOrigins, corsAllowMethods, corsAllowHeaders string
var generatedObjectsLabels string
var reconciliationPeriod uint
var errorReconciliationPeriod uint
const blockListedSubdomains string = "api"
flag.StringVar(&oathkeeperSvcAddr, "oathkeeper-svc-address", "", "Oathkeeper proxy service")
flag.UintVar(&oathkeeperSvcPort, "oathkeeper-svc-port", 0, "Oathkeeper proxy service port")
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&healthProbeAddr, "health-probe-addr", ":8081", "The address the health probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
flag.StringVar(&blockListedServices, "service-blocklist", "kubernetes.default,kube-dns.kube-system", "List of services to be blocklisted from exposure.")
flag.StringVar(&allowListedDomains, "domain-allowlist", "", "List of domains to be allowed.")
flag.StringVar(&domainName, "default-domain-name", "", "A default domain name for hostnames with no domain provided. Optional.")
flag.StringVar(&corsAllowOrigins, "cors-allow-origins", "regex:.*", "list of allowed origins")
flag.StringVar(&corsAllowMethods, "cors-allow-methods", "GET,POST,PUT,DELETE", "list of allowed methods")
flag.StringVar(&corsAllowHeaders, "cors-allow-headers", "JwtAuthorization,Content-Type,*", "list of allowed headers")
flag.StringVar(&generatedObjectsLabels, "generated-objects-labels", "", "Comma-separated list of key=value pairs used to label generated objects")
flag.UintVar(&reconciliationPeriod, "reconciliation-period", 0, "Default reconciliation period when no error happened in the previous run [s]")
flag.UintVar(&errorReconciliationPeriod, "error-reconciliation-period", 0, "Reconciliation period after an error happened in the previous run (e.g. VirtualService confict) [s]")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
if oathkeeperSvcAddr == "" {
setupLog.Error(fmt.Errorf("oathkeeper-svc-address can't be empty"), "unable to create controller", "controller", "Api")
os.Exit(1)
}
if oathkeeperSvcPort == 0 {
setupLog.Error(fmt.Errorf("oathkeeper-svc-port can't be empty"), "unable to create controller", "controller", "Api")
os.Exit(1)
}
if allowListedDomains != "" {
for _, domain := range getList(allowListedDomains) {
if !validation.ValidateDomainName(domain) {
setupLog.Error(fmt.Errorf("invalid domain in domain-allowlist"), "unable to create controller", "controller", "Api")
os.Exit(1)
}
}
}
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
cfg := &config{}
setupLog.Info("reading webhook configuration")
if err := envconfig.Init(cfg); err != nil {
panic(errors.Wrap(err, "while reading env variables"))
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
},
HealthProbeBindAddress: healthProbeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "69358922.kyma-project.io",
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
additionalLabels, err := parseLabels(generatedObjectsLabels)
if err != nil {
setupLog.Error(err, "parsing labels failed")
os.Exit(1)
}
config := controllers.ApiRuleReconcilerConfiguration{
OathkeeperSvcAddr: oathkeeperSvcAddr,
OathkeeperSvcPort: oathkeeperSvcPort,
AllowListedDomains: allowListedDomains,
BlockListedServices: blockListedServices,
DomainName: domainName,
CorsAllowOrigins: corsAllowOrigins,
CorsAllowMethods: corsAllowMethods,
CorsAllowHeaders: corsAllowHeaders,
AdditionalLabels: additionalLabels,
ReconciliationPeriod: reconciliationPeriod,
ErrorReconciliationPeriod: errorReconciliationPeriod,
}
reconciler, err := controllers.NewApiRuleReconciler(mgr, config)
if err != nil {
setupLog.Error(err, "unable to create controller", "controller", "APIRule")
os.Exit(1)
}
if err = reconciler.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to setup controller", "controller", "APIRule")
os.Exit(1)
}
//+kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
func getList(raw string) []string {
var result []string
for _, s := range strings.Split(raw, ",") {
trim := strings.TrimSpace(s)
if trim != "" {
result = append(result, trim)
}
}
return result
}
func getStringMatch(raw string) []*v1beta1.StringMatch {
var result []*v1beta1.StringMatch
for _, s := range getList(raw) {
matchTypePair := strings.SplitN(s, ":", 2)
matchType := matchTypePair[0]
value := matchTypePair[1]
var stringMatch *v1beta1.StringMatch
switch {
case matchType == "regex":
stringMatch = regex(value)
case matchType == "prefix":
stringMatch = prefix(value)
case matchType == "exact":
stringMatch = exact(value)
}
result = append(result, stringMatch)
}
return result
}
func getNamespaceServiceMap(raw string) map[string][]string {
result := make(map[string][]string)
for _, s := range getList(raw) {
if !validation.ValidateServiceName(s) {
setupLog.Error(fmt.Errorf("invalid service in service-blocklist"), "unable to create controller", "controller", "Api")
os.Exit(1)
}
namespacedService := strings.Split(s, ".")
namespace := namespacedService[1]
service := namespacedService[0]
result[namespace] = append(result[namespace], service)
}
return result
}
func getHostBlockListFrom(blockListedSubdomains string, domainName string) []string {
var result []string
for _, subdomain := range getList(blockListedSubdomains) {
if !validation.ValidateSubdomainName(subdomain) {
setupLog.Error(fmt.Errorf("invalid subdomain in subdomain-blocklist"), "unable to create controller", "controller", "Api")
os.Exit(1)
}
blockedHost := strings.Join([]string{subdomain, domainName}, ".")
result = append(result, blockedHost)
}
return result
}
func parseLabels(labelsString string) (map[string]string, error) {
output := make(map[string]string)
if labelsString == "" {
return output, nil
}
var err error
for _, labelString := range strings.Split(labelsString, ",") {
trim := strings.TrimSpace(labelString)
if trim != "" {
label := strings.Split(trim, "=")
if len(label) != 2 {
return nil, errors.New("invalid label format")
}
key, value := label[0], label[1]
if err = validation.VerifyLabelKey(key); err != nil {
return nil, errors.Wrap(err, "invalid label key")
}
if err = validation.VerifyLabelValue(value); err != nil {
return nil, errors.Wrap(err, "invalid label value")
}
_, exists := output[key]
if exists {
return nil, fmt.Errorf("duplicated label: %s", key)
}
output[key] = value
}
}
return output, nil
}
func regex(val string) *v1beta1.StringMatch {
return &v1beta1.StringMatch{
MatchType: &v1beta1.StringMatch_Regex{Regex: val},
}
}
func prefix(val string) *v1beta1.StringMatch {
return &v1beta1.StringMatch{
MatchType: &v1beta1.StringMatch_Prefix{Prefix: val},
}
}
func exact(val string) *v1beta1.StringMatch {
return &v1beta1.StringMatch{
MatchType: &v1beta1.StringMatch_Exact{Exact: val},
}
}