Skip to content

Commit fe774d6

Browse files
adding TokenReview.auth.k8s.io/v1 webhook support
Signed-off-by: Chris Hein <[email protected]>
1 parent 197751d commit fe774d6

File tree

11 files changed

+1072
-0
lines changed

11 files changed

+1072
-0
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"
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", &webhook.Authentication{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/alias.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package webhook
1919
import (
2020
"gomodules.xyz/jsonpatch/v2"
2121
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
22+
"sigs.k8s.io/controller-runtime/pkg/webhook/authentication"
2223
)
2324

2425
// define some aliases for common bits of the webhook functionality
@@ -54,6 +55,20 @@ type AdmissionHandler = admission.Handler
5455
// AdmissionDecoder knows how to decode objects from admission requests.
5556
type AdmissionDecoder = admission.Decoder
5657

58+
// AuthenticationRequest defines the input for an authentication handler.
59+
// It contains the token & audiences from the client.
60+
type AuthenticationRequest = authentication.Request
61+
62+
// AuthenticationResponse is the output of an authentication handler.
63+
// It contains a response indicating if a given operation is allowed.
64+
type AuthenticationResponse = authentication.Response
65+
66+
// Authentication is webhook suitable for registration with the server
67+
type Authentication = authentication.Webhook
68+
69+
// AuthenticationHandler knows how to process authentication requests.
70+
type AuthenticationHandler = authentication.Handler
71+
5772
// JSONPatchOp represents a single JSONPatch patch operation.
5873
type JSONPatchOp = jsonpatch.Operation
5974

@@ -70,4 +85,13 @@ var (
7085

7186
// Errored indicates that an error occurred in the admission request.
7287
Errored = admission.Errored
88+
89+
// Authenticated indicates that the token review should be allowed for the given reason.
90+
Authenticated = authentication.Authenticated
91+
92+
// Unauthenticated indicates that the token review should be unauthorized for the given reson.
93+
Unauthenticated = authentication.Unauthenticated
94+
95+
// AuthenticationErrored indicates that an error occurred in the token review
96+
AuthenticationErrored = authentication.Errored
7397
)
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+
v1 "k8s.io/api/authentication/v1"
28+
"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(v1.AddToScheme(authenticationScheme))
40+
utilruntime.Must(v1beta1.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+
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(err)
58+
wh.writeResponse(w, reviewResponse)
59+
return
60+
}
61+
} else {
62+
err = errors.New("request body is empty")
63+
wh.log.Error(err, "bad request")
64+
reviewResponse = Errored(err)
65+
wh.writeResponse(w, reviewResponse)
66+
return
67+
}
68+
69+
// verify the content type is accurate
70+
contentType := r.Header.Get("Content-Type")
71+
if contentType != "application/json" {
72+
err = fmt.Errorf("contentType=%s, expected application/json", contentType)
73+
wh.log.Error(err, "unable to process a request with an unknown content type", "content type", contentType)
74+
reviewResponse = Errored(err)
75+
wh.writeResponse(w, reviewResponse)
76+
return
77+
}
78+
79+
// Both v1 and v1beta1 TokenReview types are exactly the same, so the v1beta1 type can
80+
// be decoded into the v1 type. However the runtime codec's decoder guesses which type to
81+
// decode into by type name if an Object's TypeMeta isn't set. By setting TypeMeta of an
82+
// unregistered type to the v1 GVK, the decoder will coerce a v1beta1 TokenReview to v1.
83+
// The actual TokenReview GVK will be used to write a typed response in case the
84+
// webhook config permits multiple versions, otherwise this response will fail.
85+
req := Request{}
86+
ar := unversionedTokenReview{}
87+
// avoid an extra copy
88+
ar.TokenReview = &req.TokenReview
89+
ar.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("TokenReview"))
90+
_, actualTokRevGVK, err := authenticationCodecs.UniversalDeserializer().Decode(body, nil, &ar)
91+
if err != nil {
92+
wh.log.Error(err, "unable to decode the request")
93+
reviewResponse = Errored(err)
94+
wh.writeResponse(w, reviewResponse)
95+
return
96+
}
97+
wh.log.V(1).Info("received request", "UID", req.UID, "kind", req.Kind)
98+
99+
if req.Spec.Token == "" {
100+
err = errors.New("token is empty")
101+
wh.log.Error(err, "bad request")
102+
reviewResponse = Errored(err)
103+
wh.writeResponse(w, reviewResponse)
104+
return
105+
}
106+
107+
// TODO: add panic-recovery for Handle
108+
reviewResponse = wh.Handle(ctx, req)
109+
wh.writeResponseTyped(w, reviewResponse, actualTokRevGVK)
110+
}
111+
112+
// writeResponse writes response to w generically, i.e. without encoding GVK information.
113+
func (wh *Webhook) writeResponse(w io.Writer, response Response) {
114+
wh.writeTokenResponse(w, response.TokenReview)
115+
}
116+
117+
// writeResponseTyped writes response to w with GVK set to tokRevGVK, which is necessary
118+
// if multiple TokenReview versions are permitted by the webhook.
119+
func (wh *Webhook) writeResponseTyped(w io.Writer, response Response, tokRevGVK *schema.GroupVersionKind) {
120+
ar := response.TokenReview
121+
122+
// Default to a v1 TokenReview, otherwise the API server may not recognize the request
123+
// if multiple TokenReview versions are permitted by the webhook config.
124+
if tokRevGVK == nil || *tokRevGVK == (schema.GroupVersionKind{}) {
125+
ar.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("TokenReview"))
126+
} else {
127+
ar.SetGroupVersionKind(*tokRevGVK)
128+
}
129+
wh.writeTokenResponse(w, ar)
130+
}
131+
132+
// writeTokenResponse writes ar to w.
133+
func (wh *Webhook) writeTokenResponse(w io.Writer, ar v1.TokenReview) {
134+
err := json.NewEncoder(w).Encode(ar)
135+
if err != nil {
136+
wh.log.Error(err, "unable to encode the response")
137+
wh.writeResponse(w, Errored(err))
138+
} else {
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+
}
144+
}
145+
146+
// unversionedTokenReview is used to decode both v1 and v1beta1 TokenReview types.
147+
type unversionedTokenReview struct {
148+
*v1.TokenReview
149+
}
150+
151+
var _ runtime.Object = &unversionedTokenReview{}

0 commit comments

Comments
 (0)