This repository has been archived by the owner on Dec 3, 2024. It is now read-only.
generated from open-policy-agent/gatekeeper-external-data-provider
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
211 lines (173 loc) · 6.19 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
/*
Copyright Docker attest-provider 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 (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/docker/attest-provider/pkg/handler"
"github.com/docker/attest-provider/pkg/utils"
"github.com/docker/attest/useragent"
"k8s.io/klog/v2"
)
const (
readHeaderTimeout = 1 * time.Second
)
const (
defaultPort = 8090
certName = "tls.crt"
keyName = "tls.key"
)
var (
certDir string
clientCAFile string
port int
handlerTimeoutSeconds int
tufRoot string
tufChannel string
tufoutputPath string
metadataURL string
targetsURL string
policyDir string
policyCacheDir string
attestationStyle string
referrersRepo string
parameters = make(nameValuePairs)
)
const (
defaultMetadataURL = "registry-1.docker.io/docker/tuf-metadata:latest"
defaultTargetsURL = "registry-1.docker.io/docker/tuf-targets"
defaultTUFChannel = ""
)
var (
defaultTUFOutputPath = filepath.Join("/tuf_temp", ".docker", "tuf")
defaultPolicyCacheDir = filepath.Join("/tuf_temp", ".docker", "policy")
version = ""
)
type nameValuePairs map[string]string
func (nvp nameValuePairs) String() string {
return fmt.Sprintf("%v", map[string]string(nvp))
}
func (nvp nameValuePairs) Set(value string) error {
if value == "" {
return nil
}
parts := strings.Split(value, ",")
for _, part := range parts {
kv := strings.Split(part, "=")
if len(kv) != 2 {
return fmt.Errorf("invalid format, expected name=value")
}
nvp[kv[0]] = kv[1]
}
return nil
}
var timeoutError = string(utils.GatekeeperError("operation timed out"))
// using initFlags to initialize the flags (standard init is a pain for testing).
func initFlags() {
klog.InitFlags(nil)
flag.StringVar(&certDir, "cert-dir", "", "path to directory containing TLS certificates")
flag.StringVar(&clientCAFile, "client-ca-file", "", "path to client CA certificate")
flag.IntVar(&port, "port", defaultPort, "Port for the server to listen on")
flag.IntVar(&handlerTimeoutSeconds, "handler-timeout", 25, "timeout for handler in seconds")
flag.StringVar(&tufRoot, "tuf-root", "prod", "specify embedded tuf root [dev, staging, prod], default [prod]")
flag.StringVar(&tufChannel, "tuf-channel", defaultTUFChannel, "release channel [prod, testing], default [prod]")
flag.StringVar(&metadataURL, "tuf-metadata-source", defaultMetadataURL, "source (URL or repo) for TUF metadata")
flag.StringVar(&targetsURL, "tuf-targets-source", defaultTargetsURL, "source (URL or repo) for TUF targets")
flag.StringVar(&tufoutputPath, "tuf-output-path", defaultTUFOutputPath, "local dir to store TUF repo metadata")
flag.StringVar(&policyDir, "local-policy-dir", "", "path to local policy directory (overrides TUF policy)")
flag.StringVar(&policyCacheDir, "policy-cache-dir", defaultPolicyCacheDir, "path to store policy downloaded from TUF")
flag.StringVar(&attestationStyle, "attestation-style", "referrers", "attestation style [referrers, attached]")
flag.StringVar(&referrersRepo, "referrers-source", "", "repo from which to fetch Referrers for attestation lookup")
flag.Var(¶meters, "parameters", "policy parameters in name=value,name1,value1 format")
flag.Parse()
}
func main() {
initFlags()
mux := http.NewServeMux()
handlerTimeout := time.Duration(handlerTimeoutSeconds) * time.Second
ctx := useragent.Set(context.Background(), "attest-provider/"+version+" (docker)")
if tufChannel == "prod" {
tufChannel = ""
}
validateHandler, err := handler.NewValidateHandler(ctx, &handler.ValidateHandlerOptions{
TUFRoot: tufRoot,
TUFChannel: tufChannel,
TUFOutputPath: tufoutputPath,
TUFMetadataURL: metadataURL,
TUFTargetsURL: targetsURL,
PolicyDir: policyDir,
PolicyCacheDir: policyCacheDir,
AttestationStyle: attestationStyle,
ReferrersRepo: referrersRepo,
Parameters: parameters,
})
if err != nil {
klog.ErrorS(err, "unable to create validate handler")
os.Exit(1)
}
mutateHandler, err := handler.NewMutateHandler()
if err != nil {
klog.ErrorS(err, "unable to create validate handler")
os.Exit(1)
}
mux.Handle("POST /validate", http.TimeoutHandler(validateHandler, handlerTimeout, timeoutError))
mux.Handle("POST /mutate", http.TimeoutHandler(mutateHandler, handlerTimeout, timeoutError))
mux.Handle("GET /ready", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
ReadHeaderTimeout: readHeaderTimeout,
BaseContext: func(_ net.Listener) context.Context {
return ctx
},
}
config := &tls.Config{
MinVersion: tls.VersionTLS13,
}
if clientCAFile != "" {
klog.InfoS("loading Gatekeeper's CA certificate", "clientCAFile", clientCAFile)
caCert, err := os.ReadFile(clientCAFile)
if err != nil {
klog.ErrorS(err, "unable to load Gatekeeper's CA certificate", "clientCAFile", clientCAFile)
os.Exit(1)
}
clientCAs := x509.NewCertPool()
clientCAs.AppendCertsFromPEM(caCert)
config.ClientCAs = clientCAs
config.ClientAuth = tls.VerifyClientCertIfGiven
server.TLSConfig = config
}
if certDir != "" {
certFile := filepath.Join(certDir, certName)
keyFile := filepath.Join(certDir, keyName)
klog.InfoS("starting external data provider server", "port", port, "certFile", certFile, "keyFile", keyFile)
if err := server.ListenAndServeTLS(certFile, keyFile); err != nil {
klog.ErrorS(err, "unable to start external data provider server")
os.Exit(1)
}
} else {
klog.Error("TLS certificates are not provided, the server will not be started")
os.Exit(1)
}
}