-
Notifications
You must be signed in to change notification settings - Fork 62
/
token_review.go
204 lines (175 loc) · 5.83 KB
/
token_review.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package kubeauth
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/hashicorp/go-secure-stdlib/strutil"
authv1 "k8s.io/api/authentication/v1"
kubeerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// This is the result from the token review
type tokenReviewResult struct {
Name string
Namespace string
UID string
}
// This exists so we can use a mock TokenReview when running tests
type tokenReviewer interface {
Review(context.Context, *http.Client, string, []string) (*tokenReviewResult, error)
}
type tokenReviewFactory func(*kubeConfig) tokenReviewer
// This is the real implementation that calls the kubernetes API
type tokenReviewAPI struct {
config *kubeConfig
}
func tokenReviewAPIFactory(config *kubeConfig) tokenReviewer {
return &tokenReviewAPI{
config: config,
}
}
func (t *tokenReviewAPI) Review(ctx context.Context, client *http.Client, jwt string, aud []string) (*tokenReviewResult, error) {
// Create the TokenReview Object and marshal it into json
trReq := &authv1.TokenReview{
Spec: authv1.TokenReviewSpec{
Token: jwt,
Audiences: aud,
},
}
trJSON, err := json.Marshal(trReq)
if err != nil {
return nil, err
}
// Build the request to the token review API
url := fmt.Sprintf("%s/apis/authentication.k8s.io/v1/tokenreviews", strings.TrimSuffix(t.config.Host, "/"))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(trJSON))
if err != nil {
return nil, err
}
// If we have a configured TokenReviewer JWT use it as the bearer, otherwise
// try to use the passed in JWT.
bearer := fmt.Sprintf("Bearer %s", jwt)
if len(t.config.TokenReviewerJWT) > 0 {
bearer = fmt.Sprintf("Bearer %s", t.config.TokenReviewerJWT)
}
setRequestHeader(req, bearer)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
// Parse the resp into a tokenreview object or a kubernetes error type
r, err := parseResponse(resp)
switch {
case kubeerrors.IsUnauthorized(err):
// If the err is unauthorized that means the token has since been deleted;
// this can happen if the service account is deleted, and even if it has
// since been recreated the token will have changed, which means our
// caller will need to be updated accordingly.
return nil, errors.New("lookup failed: service account unauthorized; this could mean it has been deleted or recreated with a new token")
case err != nil:
return nil, err
}
if r.Status.Error != "" {
return nil, fmt.Errorf("lookup failed: %s", r.Status.Error)
}
if !r.Status.Authenticated {
return nil, errors.New("lookup failed: service account jwt not valid")
}
// Ensure the token review endpoint is audience-aware if we requested
// audience validation.
wantAud := trReq.Spec.Audiences
if len(wantAud) != 0 {
intersectionFound := false
for _, aud := range trReq.Spec.Audiences {
if strutil.StrListContains(r.Status.Audiences, aud) {
intersectionFound = true
break
}
}
if !intersectionFound {
return nil, fmt.Errorf("lookup failed: service account jwt valid for audience(s) %v, but wanted %v", r.Status.Audiences, wantAud)
}
}
// The username is of format: system:serviceaccount:(NAMESPACE):(SERVICEACCOUNT)
parts := strings.Split(r.Status.User.Username, ":")
if len(parts) != 4 {
return nil, errors.New("lookup failed: unexpected username format")
}
// Validate the user that comes back from token review is a service account
if parts[0] != "system" || parts[1] != "serviceaccount" {
return nil, errors.New("lookup failed: username returned is not a service account")
}
return &tokenReviewResult{
Name: parts[3],
Namespace: parts[2],
UID: string(r.Status.User.UID),
}, nil
}
// parseResponse takes the API response and either returns the appropriate error
// or the TokenReview Object.
func parseResponse(resp *http.Response) (*authv1.TokenReview, error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// If the request was not a success create a kuberenets error
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
return nil, kubeerrors.NewGenericServerResponse(resp.StatusCode, "POST", schema.GroupResource{}, "", strings.TrimSpace(string(body)), 0, true)
}
// If we can successfully Unmarshal into a status object that means there is
// an error to return
errStatus := &metav1.Status{}
err = json.Unmarshal(body, errStatus)
if err == nil && errStatus.Status != metav1.StatusSuccess {
return nil, kubeerrors.FromObject(runtime.Object(errStatus))
}
// Unmarshal the resp body into a TokenReview Object
trResp := &authv1.TokenReview{}
err = json.Unmarshal(body, trResp)
if err != nil {
return nil, err
}
return trResp, nil
}
// mock review is used while testing
type mockTokenReview struct {
saName string
saNamespace string
saUID string
}
func mockTokenReviewFactory(name, namespace, UID string) tokenReviewFactory {
return func(config *kubeConfig) tokenReviewer {
return &mockTokenReview{
saName: name,
saNamespace: namespace,
saUID: UID,
}
}
}
func (t *mockTokenReview) Review(ctx context.Context, client *http.Client, cjwt string, aud []string) (*tokenReviewResult, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
httpTransport, ok := client.Transport.(*http.Transport)
if !ok {
return nil, errors.New("failed to check whether DisableKeepAlives is false as Transport is not *http.Transport")
}
if httpTransport.DisableKeepAlives {
return nil, errors.New("expected DisableKeepAlives to be false but was true")
}
return &tokenReviewResult{
Name: t.saName,
Namespace: t.saNamespace,
UID: t.saUID,
}, nil
}