/
request_handler_config.go
185 lines (169 loc) · 5.79 KB
/
request_handler_config.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
//
// Copyright 2020 IBM Corporation
//
// 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 config
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/sigstore/k8s-manifest-sigstore/pkg/k8smanifest"
"github.com/sigstore/k8s-manifest-sigstore/pkg/util/kubeutil"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeclient "k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
const k8sLogLevelEnvKey = "K8S_MANIFEST_SIGSTORE_LOG_LEVEL"
const defaultConfigKeyInConfigMap = "config.yaml"
const defaultPodNamespace = "integrity-shield-operator-system"
const defaultHandlerConfigMapName = "request-handler-config"
var logLevelMap = map[string]log.Level{
"panic": log.PanicLevel,
"fatal": log.FatalLevel,
"error": log.ErrorLevel,
"warn": log.WarnLevel,
"info": log.InfoLevel,
"debug": log.DebugLevel,
"trace": log.TraceLevel,
}
type RequestHandlerConfig struct {
ImageVerificationConfig ImageVerificationConfig `json:"imageVerificationConfig,omitempty"`
KeyPathList []string `json:"keyPathList,omitempty"`
SigStoreConfig SigStoreConfig `json:"sigStoreConfig,omitempty"`
RequestFilterProfile RequestFilterProfile `json:"requestFilterProfile,omitempty"`
Log LogConfig `json:"log,omitempty"`
SideEffectConfig SideEffectConfig `json:"sideEffect,omitempty"`
DefaultConstraintAction Action `json:"defaultConstraintAction,omitempty"`
Options []string
}
type LogConfig struct {
Level string `json:"level,omitempty"`
ManifestSigstoreLogLevel string `json:"manifestSigstoreLogLevel,omitempty"`
Format string `json:"format,omitempty"`
}
type SideEffectConfig struct {
// Event
CreateDenyEvent bool `json:"createDenyEvent"`
}
type ImageVerificationConfig struct {
}
type SigStoreConfig struct {
RekorServer string `json:"rekorServer,omitempty"`
}
type RequestFilterProfile struct {
SkipObjects k8smanifest.ObjectReferenceList `json:"skipObjects,omitempty"`
SkipUsers ObjectUserBindingList `json:"skipUsers,omitempty"`
IgnoreFields k8smanifest.ObjectFieldBindingList `json:"ignoreFields,omitempty"`
}
func SetupLogger(config LogConfig, req admission.Request) {
logLevelStr := config.Level
k8sLogLevelStr := config.ManifestSigstoreLogLevel
if logLevelStr == "" && k8sLogLevelStr == "" {
logLevelStr = "info"
k8sLogLevelStr = "info"
}
if logLevelStr == "" && k8sLogLevelStr != "" {
logLevelStr = k8sLogLevelStr
}
if logLevelStr != "" && k8sLogLevelStr == "" {
k8sLogLevelStr = logLevelStr
}
_ = os.Setenv(k8sLogLevelEnvKey, k8sLogLevelStr)
logLevel, ok := logLevelMap[logLevelStr]
if !ok {
logLevel = log.InfoLevel
}
log.SetLevel(logLevel)
// format
if config.Format == "json" {
log.SetFormatter(&log.JSONFormatter{TimestampFormat: time.RFC3339Nano})
}
}
func LoadKeySecret(keySecretNamespace, keySecretName string) (string, error) {
obj, err := kubeutil.GetResource("v1", "Secret", keySecretNamespace, keySecretName)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("failed to get a secret `%s` in `%s` namespace", keySecretName, keySecretNamespace))
}
objBytes, _ := json.Marshal(obj.Object)
var secret v1.Secret
_ = json.Unmarshal(objBytes, &secret)
keyDir := fmt.Sprintf("/tmp/%s/%s/", keySecretNamespace, keySecretName)
sumErr := []string{}
keyPath := ""
for fname, keyData := range secret.Data {
os.MkdirAll(keyDir, os.ModePerm)
fpath := filepath.Join(keyDir, fname)
err := ioutil.WriteFile(fpath, keyData, 0644)
if err != nil {
sumErr = append(sumErr, err.Error())
continue
}
keyPath = fpath
break
}
if keyPath == "" && len(sumErr) > 0 {
return "", errors.New(fmt.Sprintf("failed to save secret data as a file; %s", strings.Join(sumErr, "; ")))
}
if keyPath == "" {
return "", errors.New(fmt.Sprintf("no key files are found in the secret `%s` in `%s` namespace", keySecretName, keySecretNamespace))
}
return keyPath, nil
}
func LoadRequestHandlerConfig() (*RequestHandlerConfig, error) {
namespace := os.Getenv("POD_NAMESPACE")
if namespace == "" {
namespace = defaultPodNamespace
}
configName := os.Getenv("REQUEST_HANDLER_CONFIG_NAME")
if configName == "" {
configName = defaultHandlerConfigMapName
}
configKey := os.Getenv("REQUEST_HANDLER_CONFIG_KEY")
if configKey == "" {
configKey = defaultConfigKeyInConfigMap
}
// load
config, err := kubeutil.GetKubeConfig()
if err != nil {
return nil, nil
}
clientset, err := kubeclient.NewForConfig(config)
if err != nil {
log.Error(err)
return nil, nil
}
cm, err := clientset.CoreV1().ConfigMaps(namespace).Get(context.Background(), configName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to get a configmap `%s` in `%s` namespace", configName, namespace))
}
cfgBytes, found := cm.Data[configKey]
if !found {
return nil, errors.New(fmt.Sprintf("`%s` is not found in configmap", configKey))
}
var sc *RequestHandlerConfig
err = yaml.Unmarshal([]byte(cfgBytes), &sc)
if err != nil {
return sc, errors.Wrap(err, fmt.Sprintf("failed to unmarshal config.yaml into %T", sc))
}
return sc, nil
}