2 Copyright 2018 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
31 // TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
32 // authentication from an oauth2.TokenSource.
33 func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {
34 return func(rt http.RoundTripper) http.RoundTripper {
35 return &tokenSourceTransport{
37 ort: &oauth2.Transport{
45 // NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
46 // file at a specified path and periodically reloads it.
47 func NewCachedFileTokenSource(path string) oauth2.TokenSource {
48 return &cachingTokenSource{
50 leeway: 10 * time.Second,
51 base: &fileTokenSource{
53 // This period was picked because it is half of the duration between when the kubelet
54 // refreshes a projected service account token and when the original token expires.
55 // Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.
56 // This should induce re-reading at a frequency that works with the token volume source.
62 type tokenSourceTransport struct {
63 base http.RoundTripper
67 func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
68 // This is to allow --token to override other bearer token providers.
69 if req.Header.Get("Authorization") != "" {
70 return tst.base.RoundTrip(req)
72 return tst.ort.RoundTrip(req)
75 type fileTokenSource struct {
80 var _ = oauth2.TokenSource(&fileTokenSource{})
82 func (ts *fileTokenSource) Token() (*oauth2.Token, error) {
83 tokb, err := ioutil.ReadFile(ts.path)
85 return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err)
87 tok := strings.TrimSpace(string(tokb))
89 return nil, fmt.Errorf("read empty token from file %q", ts.path)
94 Expiry: time.Now().Add(ts.period),
98 type cachingTokenSource struct {
99 base oauth2.TokenSource
109 var _ = oauth2.TokenSource(&cachingTokenSource{})
111 func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
118 if tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
125 if tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
129 tok, err := ts.base.Token()
134 klog.Errorf("Unable to rotate token: %v", err)