/
server.go
305 lines (268 loc) · 9.3 KB
/
server.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
/*
Copyright 2017 by the contributors.
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 server
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/AliyunContainerService/ack-ram-authenticator/pkg/arn"
"github.com/AliyunContainerService/ack-ram-authenticator/pkg/config"
"github.com/AliyunContainerService/ack-ram-authenticator/pkg/token"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
authenticationv1beta1 "k8s.io/api/authentication/v1beta1"
)
// tokenReviewDenyJSON is a static encoding (at init time) of the 'deny' TokenReview
var tokenReviewDenyJSON = func() []byte {
res, err := json.Marshal(authenticationv1beta1.TokenReview{
Status: authenticationv1beta1.TokenReviewStatus{
Authenticated: false,
},
})
if err != nil {
logrus.WithError(err).Fatal("could not create static 'deny' JSON response")
}
return res
}()
// server state (internal)
type handler struct {
http.ServeMux
lowercaseRoleMap map[string]config.RoleMapping
lowercaseUserMap map[string]config.UserMapping
accountMap map[string]bool
verifier token.Verifier
metrics metrics
}
// metrics are handles to the collectors for prometheus for the various metrics we are tracking.
type metrics struct {
latency *prometheus.HistogramVec
}
// namespace for the heptio authenticators metrics
const (
metricNS = "authenticator_ack"
metricMalformed = "malformed_request"
metricInvalid = "invalid_token"
metricSTSError = "sts_error"
metricUnknown = "uknown_user"
metricSuccess = "success"
)
// New creates a new server from a config
func New(config config.Config) *Server {
return &Server{
Config: config,
}
}
// Run the authentication webhook server.
func (c *Server) Run() {
for _, mapping := range c.RoleMappings {
logrus.WithFields(logrus.Fields{
"role": mapping.RoleARN,
"username": mapping.Username,
"groups": mapping.Groups,
}).Infof("mapping RAM role")
}
for _, mapping := range c.UserMappings {
logrus.WithFields(logrus.Fields{
"user": mapping.UserARN,
"username": mapping.Username,
"groups": mapping.Groups,
}).Infof("mapping RAM user")
}
listenAddr := fmt.Sprintf("%s:%d", c.Address, c.HostPort)
listenURL := fmt.Sprintf("https://%s/authenticate", listenAddr)
cert, err := c.GetOrCreateCertificate()
if err != nil {
logrus.WithError(err).Fatalf("could not load/generate a certificate")
}
if !c.KubeconfigPregenerated {
if err := c.CreateKubeconfig(); err != nil {
logrus.WithError(err).Fatalf("could not create kubeconfig")
}
}
// start a TLS listener with our custom certs
listener, err := tls.Listen("tcp", listenAddr, &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{*cert},
})
if err != nil {
logrus.WithError(err).Fatal("could not open TLS listener")
}
defer listener.Close()
// create a logrus logger for HTTP error logs
errLog := logrus.WithField("http", "error").Writer()
defer errLog.Close()
logrus.Infof("listening on %s", listenURL)
logrus.Infof("reconfigure your apiserver with `--authentication-token-webhook-config-file=%s` to enable (assuming default hostPath mounts)", c.GenerateKubeconfigPath)
httpServer := http.Server{
ErrorLog: log.New(errLog, "", 0),
Handler: c.getHandler(),
}
logrus.WithError(httpServer.Serve(listener)).Fatal("HTTP server exited")
}
func (c *Server) getHandler() *handler {
h := &handler{
lowercaseRoleMap: make(map[string]config.RoleMapping),
lowercaseUserMap: make(map[string]config.UserMapping),
accountMap: make(map[string]bool),
verifier: token.NewVerifier(c.ClusterID),
metrics: createMetrics(),
}
for _, m := range c.RoleMappings {
canonicalizedARN, err := arn.Canonicalize(strings.ToLower(m.RoleARN))
if err != nil {
logrus.Errorf("Error canonicalizing ARN: %v", err)
continue
}
h.lowercaseRoleMap[canonicalizedARN] = m
}
for _, m := range c.UserMappings {
canonicalizedARN, err := arn.Canonicalize(strings.ToLower(m.UserARN))
if err != nil {
logrus.Errorf("Error canonicalizing ARN: %v", err)
continue
}
h.lowercaseUserMap[canonicalizedARN] = m
}
h.HandleFunc("/authenticate", h.authenticateEndpoint)
h.Handle("/metrics", promhttp.Handler())
return h
}
func createMetrics() metrics {
m := metrics{
latency: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: metricNS,
Name: "authenticate_latency_seconds",
Help: "The latency for authenticate call",
}, []string{"result"}),
}
prometheus.MustRegister(m.latency)
return m
}
func duration(start time.Time) float64 {
return time.Since(start).Seconds()
}
func (h *handler) authenticateEndpoint(w http.ResponseWriter, req *http.Request) {
start := time.Now()
log := logrus.WithFields(logrus.Fields{
"path": req.URL.Path,
"client": req.RemoteAddr,
"method": req.Method,
})
if req.Method != http.MethodPost {
log.Error("unexpected request method")
http.Error(w, "expected POST", http.StatusMethodNotAllowed)
h.metrics.latency.WithLabelValues(metricMalformed).Observe(duration(start))
return
}
if req.Body == nil {
log.Error("empty request body")
http.Error(w, "expected a request body", http.StatusBadRequest)
h.metrics.latency.WithLabelValues(metricMalformed).Observe(duration(start))
return
}
defer req.Body.Close()
var tokenReview authenticationv1beta1.TokenReview
if err := json.NewDecoder(req.Body).Decode(&tokenReview); err != nil {
log.WithError(err).Error("could not parse request body")
http.Error(w, "expected a request body to be a TokenReview", http.StatusBadRequest)
h.metrics.latency.WithLabelValues(metricMalformed).Observe(duration(start))
return
}
// all responses from here down have JSON bodies
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// if the token is invalid, reject with a 403
identity, err := h.verifier.Verify(tokenReview.Spec.Token)
if err != nil {
if _, ok := err.(token.STSError); ok {
h.metrics.latency.WithLabelValues(metricSTSError).Observe(duration(start))
} else {
h.metrics.latency.WithLabelValues(metricInvalid).Observe(duration(start))
}
log.WithError(err).Warn("access denied")
w.WriteHeader(http.StatusForbidden)
w.Write(tokenReviewDenyJSON)
return
}
log.WithFields(logrus.Fields{
"arn": identity.ARN,
"accountid": identity.AccountID,
"userid": identity.UserID,
"session": identity.SessionName,
}).Info("STS response")
// look up the ARN in each of our mappings to fill in the username and groups
arnLower := strings.ToLower(identity.CanonicalARN)
log = log.WithField("arn", identity.CanonicalARN)
username, groups, err := h.doMapping(identity, arnLower)
if err != nil {
h.metrics.latency.WithLabelValues(metricUnknown).Observe(duration(start))
log.WithError(err).Warn("access denied")
w.WriteHeader(http.StatusForbidden)
w.Write(tokenReviewDenyJSON)
return
}
// use a prefixed UID that includes the RAM account ID and RAM user ID ("AROAAAAAAAAAAAAAAAAAA")
uid := fmt.Sprintf("ack-ram-authenticator:%s:%s", identity.AccountID, identity.UserID)
// the token is valid and the role is mapped, return success!
log.WithFields(logrus.Fields{
"username": username,
"uid": uid,
"groups": groups,
}).Info("access granted")
h.metrics.latency.WithLabelValues(metricSuccess).Observe(duration(start))
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(authenticationv1beta1.TokenReview{
Status: authenticationv1beta1.TokenReviewStatus{
Authenticated: true,
User: authenticationv1beta1.UserInfo{
Username: username,
UID: uid,
Groups: groups,
},
},
})
}
func (h *handler) doMapping(identity *token.Identity, arn string) (string, []string, error) {
if roleMapping, exists := h.lowercaseRoleMap[arn]; exists {
username, err := h.renderTemplate(roleMapping.Username, identity)
if err != nil {
return "", nil, fmt.Errorf("failed mapping username: %s", err.Error())
}
groups := []string{}
for _, groupPattern := range roleMapping.Groups {
group, err := h.renderTemplate(groupPattern, identity)
if err != nil {
return "", nil, fmt.Errorf("failed mapping group: %s", err.Error())
}
groups = append(groups, group)
}
return username, groups, nil
}
if userMapping, exists := h.lowercaseUserMap[arn]; exists {
return userMapping.Username, userMapping.Groups, nil
}
if _, exists := h.accountMap[identity.AccountID]; exists {
return identity.CanonicalARN, []string{}, nil
}
return "", nil, fmt.Errorf("ARN is not mapped: %s", arn)
}
func (h *handler) renderTemplate(template string, identity *token.Identity) (string, error) {
template = strings.Replace(template, "{{AccountID}}", identity.AccountID, -1)
sessionName := strings.Replace(identity.SessionName, "@", "-", -1)
template = strings.Replace(template, "{{SessionName}}", sessionName, -1)
return template, nil
}