Skip to content

Commit ae50d4c

Browse files
authored
Merge pull request #1440 from christopherhein/tokenreview-webhook-support
🌱 adding TokenReview.auth.k8s.io/v1 webhook support
2 parents ce2f0c9 + 6ae3ee1 commit ae50d4c

File tree

11 files changed

+1057
-9
lines changed

11 files changed

+1057
-9
lines changed

examples/tokenreview/main.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"os"
21+
22+
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
23+
"sigs.k8s.io/controller-runtime/pkg/client/config"
24+
"sigs.k8s.io/controller-runtime/pkg/log"
25+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
26+
"sigs.k8s.io/controller-runtime/pkg/manager"
27+
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
28+
"sigs.k8s.io/controller-runtime/pkg/webhook/authentication"
29+
)
30+
31+
func init() {
32+
log.SetLogger(zap.New())
33+
}
34+
35+
func main() {
36+
entryLog := log.Log.WithName("entrypoint")
37+
38+
// Setup a Manager
39+
entryLog.Info("setting up manager")
40+
mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{})
41+
if err != nil {
42+
entryLog.Error(err, "unable to set up overall controller manager")
43+
os.Exit(1)
44+
}
45+
46+
// Setup webhooks
47+
entryLog.Info("setting up webhook server")
48+
hookServer := mgr.GetWebhookServer()
49+
50+
entryLog.Info("registering webhooks to the webhook server")
51+
hookServer.Register("/validate-v1-tokenreview", &authentication.Webhook{Handler: &authenticator{}})
52+
53+
entryLog.Info("starting manager")
54+
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
55+
entryLog.Error(err, "unable to run manager")
56+
os.Exit(1)
57+
}
58+
}

examples/tokenreview/tokenreview.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"context"
21+
22+
v1 "k8s.io/api/authentication/v1"
23+
24+
"sigs.k8s.io/controller-runtime/pkg/webhook/authentication"
25+
)
26+
27+
// authenticator validates tokenreviews
28+
type authenticator struct {
29+
}
30+
31+
// authenticator admits a request by the token.
32+
func (a *authenticator) Handle(ctx context.Context, req authentication.Request) authentication.Response {
33+
if req.Spec.Token == "invalid" {
34+
return authentication.Unauthenticated("invalid is an invalid token", v1.UserInfo{})
35+
}
36+
return authentication.Authenticated("", v1.UserInfo{})
37+
}

pkg/webhook/admission/http.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,21 +51,22 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
5151
}
5252

5353
var reviewResponse Response
54-
if r.Body != nil {
55-
if body, err = ioutil.ReadAll(r.Body); err != nil {
56-
wh.log.Error(err, "unable to read the body from the incoming request")
57-
reviewResponse = Errored(http.StatusBadRequest, err)
58-
wh.writeResponse(w, reviewResponse)
59-
return
60-
}
61-
} else {
54+
if r.Body == nil {
6255
err = errors.New("request body is empty")
6356
wh.log.Error(err, "bad request")
6457
reviewResponse = Errored(http.StatusBadRequest, err)
6558
wh.writeResponse(w, reviewResponse)
6659
return
6760
}
6861

62+
defer r.Body.Close()
63+
if body, err = ioutil.ReadAll(r.Body); err != nil {
64+
wh.log.Error(err, "unable to read the body from the incoming request")
65+
reviewResponse = Errored(http.StatusBadRequest, err)
66+
wh.writeResponse(w, reviewResponse)
67+
return
68+
}
69+
6970
// verify the content type is accurate
7071
contentType := r.Header.Get("Content-Type")
7172
if contentType != "application/json" {
@@ -96,7 +97,6 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
9697
}
9798
wh.log.V(1).Info("received request", "UID", req.UID, "kind", req.Kind, "resource", req.Resource)
9899

99-
// TODO: add panic-recovery for Handle
100100
reviewResponse = wh.Handle(ctx, req)
101101
wh.writeResponseTyped(w, reviewResponse, actualAdmRevGVK)
102102
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package authentication
18+
19+
import (
20+
"testing"
21+
22+
. "github.com/onsi/ginkgo"
23+
. "github.com/onsi/gomega"
24+
25+
"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
26+
logf "sigs.k8s.io/controller-runtime/pkg/log"
27+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
28+
)
29+
30+
func TestAuthenticationWebhook(t *testing.T) {
31+
RegisterFailHandler(Fail)
32+
suiteName := "Authentication Webhook Suite"
33+
RunSpecsWithDefaultAndCustomReporters(t, suiteName, []Reporter{printer.NewlineReporter{}, printer.NewProwReporter(suiteName)})
34+
}
35+
36+
var _ = BeforeSuite(func(done Done) {
37+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
38+
39+
close(done)
40+
}, 60)

pkg/webhook/authentication/doc.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
/*
18+
Package authentication provides implementation for authentication webhook and
19+
methods to implement authentication webhook handlers.
20+
21+
See examples/tokenreview/ for an example of authentication webhooks.
22+
*/
23+
package authentication
24+
25+
import (
26+
logf "sigs.k8s.io/controller-runtime/pkg/internal/log"
27+
)
28+
29+
var log = logf.RuntimeLog.WithName("authentication")

pkg/webhook/authentication/http.go

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package authentication
18+
19+
import (
20+
"encoding/json"
21+
"errors"
22+
"fmt"
23+
"io"
24+
"io/ioutil"
25+
"net/http"
26+
27+
authenticationv1 "k8s.io/api/authentication/v1"
28+
authenticationv1beta1 "k8s.io/api/authentication/v1beta1"
29+
"k8s.io/apimachinery/pkg/runtime"
30+
"k8s.io/apimachinery/pkg/runtime/schema"
31+
"k8s.io/apimachinery/pkg/runtime/serializer"
32+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
33+
)
34+
35+
var authenticationScheme = runtime.NewScheme()
36+
var authenticationCodecs = serializer.NewCodecFactory(authenticationScheme)
37+
38+
func init() {
39+
utilruntime.Must(authenticationv1.AddToScheme(authenticationScheme))
40+
utilruntime.Must(authenticationv1beta1.AddToScheme(authenticationScheme))
41+
}
42+
43+
var _ http.Handler = &Webhook{}
44+
45+
func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
46+
var body []byte
47+
var err error
48+
ctx := r.Context()
49+
if wh.WithContextFunc != nil {
50+
ctx = wh.WithContextFunc(ctx, r)
51+
}
52+
53+
var reviewResponse Response
54+
if r.Body == nil {
55+
err = errors.New("request body is empty")
56+
wh.log.Error(err, "bad request")
57+
reviewResponse = Errored(err)
58+
wh.writeResponse(w, reviewResponse)
59+
return
60+
}
61+
62+
defer r.Body.Close()
63+
if body, err = ioutil.ReadAll(r.Body); err != nil {
64+
wh.log.Error(err, "unable to read the body from the incoming request")
65+
reviewResponse = Errored(err)
66+
wh.writeResponse(w, reviewResponse)
67+
return
68+
}
69+
70+
// verify the content type is accurate
71+
contentType := r.Header.Get("Content-Type")
72+
if contentType != "application/json" {
73+
err = fmt.Errorf("contentType=%s, expected application/json", contentType)
74+
wh.log.Error(err, "unable to process a request with an unknown content type", "content type", contentType)
75+
reviewResponse = Errored(err)
76+
wh.writeResponse(w, reviewResponse)
77+
return
78+
}
79+
80+
// Both v1 and v1beta1 TokenReview types are exactly the same, so the v1beta1 type can
81+
// be decoded into the v1 type. The v1beta1 api is deprecated as of 1.19 and will be
82+
// removed in authenticationv1.22. However the runtime codec's decoder guesses which type to
83+
// decode into by type name if an Object's TypeMeta isn't set. By setting TypeMeta of an
84+
// unregistered type to the v1 GVK, the decoder will coerce a v1beta1 TokenReview to authenticationv1.
85+
// The actual TokenReview GVK will be used to write a typed response in case the
86+
// webhook config permits multiple versions, otherwise this response will fail.
87+
req := Request{}
88+
ar := unversionedTokenReview{}
89+
// avoid an extra copy
90+
ar.TokenReview = &req.TokenReview
91+
ar.SetGroupVersionKind(authenticationv1.SchemeGroupVersion.WithKind("TokenReview"))
92+
_, actualTokRevGVK, err := authenticationCodecs.UniversalDeserializer().Decode(body, nil, &ar)
93+
if err != nil {
94+
wh.log.Error(err, "unable to decode the request")
95+
reviewResponse = Errored(err)
96+
wh.writeResponse(w, reviewResponse)
97+
return
98+
}
99+
wh.log.V(1).Info("received request", "UID", req.UID, "kind", req.Kind)
100+
101+
if req.Spec.Token == "" {
102+
err = errors.New("token is empty")
103+
wh.log.Error(err, "bad request")
104+
reviewResponse = Errored(err)
105+
wh.writeResponse(w, reviewResponse)
106+
return
107+
}
108+
109+
reviewResponse = wh.Handle(ctx, req)
110+
wh.writeResponseTyped(w, reviewResponse, actualTokRevGVK)
111+
}
112+
113+
// writeResponse writes response to w generically, i.e. without encoding GVK information.
114+
func (wh *Webhook) writeResponse(w io.Writer, response Response) {
115+
wh.writeTokenResponse(w, response.TokenReview)
116+
}
117+
118+
// writeResponseTyped writes response to w with GVK set to tokRevGVK, which is necessary
119+
// if multiple TokenReview versions are permitted by the webhook.
120+
func (wh *Webhook) writeResponseTyped(w io.Writer, response Response, tokRevGVK *schema.GroupVersionKind) {
121+
ar := response.TokenReview
122+
123+
// Default to a v1 TokenReview, otherwise the API server may not recognize the request
124+
// if multiple TokenReview versions are permitted by the webhook config.
125+
if tokRevGVK == nil || *tokRevGVK == (schema.GroupVersionKind{}) {
126+
ar.SetGroupVersionKind(authenticationv1.SchemeGroupVersion.WithKind("TokenReview"))
127+
} else {
128+
ar.SetGroupVersionKind(*tokRevGVK)
129+
}
130+
wh.writeTokenResponse(w, ar)
131+
}
132+
133+
// writeTokenResponse writes ar to w.
134+
func (wh *Webhook) writeTokenResponse(w io.Writer, ar authenticationv1.TokenReview) {
135+
if err := json.NewEncoder(w).Encode(ar); err != nil {
136+
wh.log.Error(err, "unable to encode the response")
137+
wh.writeResponse(w, Errored(err))
138+
}
139+
res := ar
140+
if log := wh.log; log.V(1).Enabled() {
141+
log.V(1).Info("wrote response", "UID", res.UID, "authenticated", res.Status.Authenticated)
142+
}
143+
return
144+
}
145+
146+
// unversionedTokenReview is used to decode both v1 and v1beta1 TokenReview types.
147+
type unversionedTokenReview struct {
148+
*authenticationv1.TokenReview
149+
}
150+
151+
var _ runtime.Object = &unversionedTokenReview{}

0 commit comments

Comments
 (0)