Skip to content

Commit 2015a7f

Browse files
committed
Adds ClientForMetadataTokenRequestEmptyAud and
EmptyAudienceTokenFromMetadata manager/util package helper funcs for building clients and parsing the empty audience request token. Signed-off-by: joshvanl <[email protected]>
1 parent dd8ae5d commit 2015a7f

File tree

3 files changed

+262
-0
lines changed

3 files changed

+262
-0
lines changed

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ require (
88
github.com/golang/protobuf v1.5.2 // indirect
99
github.com/jetstack/cert-manager v1.3.1
1010
github.com/kubernetes-csi/csi-lib-utils v0.9.1
11+
github.com/stretchr/testify v1.6.1
1112
golang.org/x/net v0.0.0-20210224082022-3d97a244fca7
1213
google.golang.org/grpc v1.37.0
1314
k8s.io/apimachinery v0.21.0

manager/util/tokenrequest.go

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/*
2+
Copyright 2021 The cert-manager 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 util
18+
19+
import (
20+
"encoding/json"
21+
"errors"
22+
"fmt"
23+
24+
cmclient "github.com/jetstack/cert-manager/pkg/client/clientset/versioned"
25+
"k8s.io/client-go/rest"
26+
27+
"github.com/cert-manager/csi-lib/manager"
28+
"github.com/cert-manager/csi-lib/metadata"
29+
)
30+
31+
// ClientForMetadataTokenRequestEmptyAud returns a
32+
// manager.ClientForMetadataFunc that returns a cert-manager rest client whose
33+
// authentication is built using the passed empty audience ("") token request
34+
// in the metadata VolumeContext. The resulting cert-manager client is
35+
// authenticated against the Kubernetes API server using the mounting Pod's
36+
// ServiceAccount.
37+
//
38+
// Intended to be used as a manager ClientForMetadata so that created
39+
// CertificateRequests will have UserInfo fields of the mounting Pods
40+
// ServiceAccount.
41+
//
42+
// Drivers using this function _must_ have the empty audience tokenRequest
43+
// defined on the CSIDriver manifest definition, along with setting
44+
// requiresRepublish to true:
45+
//
46+
// tokenRequests:
47+
// - audience: ""
48+
// expirationSeconds: 3600
49+
// requiresRepublish: true
50+
//
51+
// restConfig must contain the Kubernetes API server Host, and a valid
52+
// TLSClientConfig.
53+
func ClientForMetadataTokenRequestEmptyAud(restConfig *rest.Config) manager.ClientForMetadataFunc {
54+
restConfigGetter := restConfigForMetadataTokenRequestEmptyAud(restConfig)
55+
return func(meta metadata.Metadata) (cmclient.Interface, error) {
56+
cmRestConfig, err := restConfigGetter(meta)
57+
if err != nil {
58+
return nil, err
59+
}
60+
return cmclient.NewForConfig(cmRestConfig)
61+
}
62+
}
63+
64+
// restConfigForMetadataTokenRequestEmptyAud returns a Kubernetes rest config
65+
// getter that returns a rest config that is authenticated using a
66+
// ServiceAccount defined in the empty audience token request passed in the
67+
// volume context.
68+
// The Host, TLSClientConfig, UserAgent, Timeout, and Proxy are preserved from
69+
// the seed rest config.
70+
func restConfigForMetadataTokenRequestEmptyAud(restConfig *rest.Config) func(meta metadata.Metadata) (*rest.Config, error) {
71+
host := restConfig.Host
72+
tlsClientConfig := *restConfig.DeepCopy()
73+
userAgent := restConfig.UserAgent
74+
timeout := restConfig.Timeout
75+
proxy := restConfig.Proxy
76+
77+
return func(meta metadata.Metadata) (*rest.Config, error) {
78+
apiToken, err := EmptyAudienceTokenFromMetadata(meta)
79+
if err != nil {
80+
return nil, err
81+
}
82+
83+
return &rest.Config{
84+
Host: host,
85+
TLSClientConfig: tlsClientConfig,
86+
UserAgent: userAgent,
87+
Timeout: timeout,
88+
Proxy: proxy,
89+
BearerToken: apiToken,
90+
}, nil
91+
}
92+
}
93+
94+
// EmptyAudienceTokenFromMetadata returns the empty audience service account
95+
// token from the volume attributes contained within the metadata. This token
96+
// should be present in the token request
97+
// `csi.storage.k8s.io/serviceAccount.tokens` key of the metadata
98+
// VolumeContext.
99+
// This function will only return tokens if the CSI driver has been defined
100+
// with tokenRequests enabled with an empty ("") audience.
101+
func EmptyAudienceTokenFromMetadata(meta metadata.Metadata) (string, error) {
102+
tokens := make(map[string]struct {
103+
Token string `json:"token"`
104+
})
105+
106+
tokensJson, ok := meta.VolumeContext["csi.storage.k8s.io/serviceAccount.tokens"]
107+
if !ok {
108+
return "", errors.New("'csi.storage.k8s.io/serviceAccount.tokens' not present in volume context, driver likely doesn't have token requests enabled")
109+
}
110+
111+
err := json.Unmarshal([]byte(tokensJson), &tokens)
112+
if err != nil {
113+
return "", fmt.Errorf("failed to parse service account tokens from CSI volume context: %w",
114+
err)
115+
}
116+
117+
apiToken, ok := tokens[""]
118+
if !ok || len(apiToken.Token) == 0 {
119+
return "", errors.New("empty audience service account token doesn't exist in CSI volume context, driver likely doesn't have an empty audience token request configured")
120+
}
121+
122+
return apiToken.Token, nil
123+
}

manager/util/tokenrequest_test.go

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
/*
2+
Copyright 2021 The cert-manager 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 util
18+
19+
import (
20+
"testing"
21+
"time"
22+
23+
"k8s.io/client-go/rest"
24+
25+
"github.com/cert-manager/csi-lib/metadata"
26+
"github.com/stretchr/testify/assert"
27+
)
28+
29+
func Test_restConfigForMetadataTokenRequestEmptyAud(t *testing.T) {
30+
var (
31+
baseRestConfig = &rest.Config{
32+
Host: "my-host",
33+
TLSClientConfig: rest.TLSClientConfig{
34+
ServerName: "my-server",
35+
},
36+
BearerToken: "my-token",
37+
UserAgent: "csi.cert-manager.io/unit-tests",
38+
Timeout: time.Millisecond,
39+
}
40+
)
41+
42+
tests := map[string]struct {
43+
volumeContext map[string]string
44+
expRestConfig *rest.Config
45+
expErr bool
46+
}{
47+
"volume context doesn't contain any token requests should error": {
48+
volumeContext: map[string]string{},
49+
expRestConfig: nil,
50+
expErr: true,
51+
},
52+
"volume context contains token request entry but json is garbage should error": {
53+
volumeContext: map[string]string{
54+
"csi.storage.k8s.io/serviceAccount.tokens": "garbage-data",
55+
},
56+
expRestConfig: nil,
57+
expErr: true,
58+
},
59+
"volume context contains token requests, but not an empty audience should error": {
60+
volumeContext: map[string]string{
61+
"csi.storage.k8s.io/serviceAccount.tokens": `
62+
{
63+
"vault": {
64+
"token": "vault-token",
65+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
66+
},
67+
"kubernetes.io": {
68+
"token": "kube-token",
69+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
70+
}
71+
}
72+
`,
73+
},
74+
expRestConfig: nil,
75+
expErr: true,
76+
},
77+
"volume context contains only an empty audience token should return a rest config with token": {
78+
volumeContext: map[string]string{
79+
"csi.storage.k8s.io/serviceAccount.tokens": `
80+
{
81+
"": {
82+
"token": "empty-aud-token",
83+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
84+
}
85+
}
86+
`,
87+
},
88+
expRestConfig: &rest.Config{
89+
Host: "my-host",
90+
TLSClientConfig: rest.TLSClientConfig{
91+
ServerName: "my-server",
92+
},
93+
UserAgent: "csi.cert-manager.io/unit-tests",
94+
Timeout: time.Millisecond,
95+
BearerToken: "empty-aud-token",
96+
},
97+
expErr: false,
98+
},
99+
"volume context contains multiple request tokens including the empty audience should return a rest config with empty audience token": {
100+
volumeContext: map[string]string{
101+
"csi.storage.k8s.io/serviceAccount.tokens": `
102+
{
103+
"vault": {
104+
"token": "vault-token",
105+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
106+
},
107+
"": {
108+
"token": "another-empty-aud-token",
109+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
110+
},
111+
"kubernetes.io": {
112+
"token": "kube-token",
113+
"expiry": "Wed, 11 Aug 2021 09:03:03 GMT"
114+
}
115+
}
116+
`,
117+
},
118+
expRestConfig: &rest.Config{
119+
Host: "my-host",
120+
TLSClientConfig: rest.TLSClientConfig{
121+
ServerName: "my-server",
122+
},
123+
UserAgent: "csi.cert-manager.io/unit-tests",
124+
Timeout: time.Millisecond,
125+
BearerToken: "another-empty-aud-token",
126+
},
127+
expErr: false,
128+
},
129+
}
130+
131+
for name, test := range tests {
132+
t.Run(name, func(t *testing.T) {
133+
restConfig, gotErr := restConfigForMetadataTokenRequestEmptyAud(baseRestConfig)(metadata.Metadata{VolumeContext: test.volumeContext})
134+
assert.Equal(t, test.expErr, gotErr != nil, "%v", gotErr)
135+
assert.Equal(t, test.expRestConfig, restConfig)
136+
})
137+
}
138+
}

0 commit comments

Comments
 (0)