/
apikey.go
176 lines (164 loc) · 5.42 KB
/
apikey.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
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package apikey
import (
"bytes"
"context"
"fmt"
jsoniter "github.com/json-iterator/go"
"io/ioutil"
"k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/user"
"net/http"
"net/url"
"tkestack.io/tke/pkg/util/log"
"tkestack.io/tke/pkg/util/transport"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type Options struct {
OIDCIssuerURL string
OIDCCAFile string
TokenReviewPath string
AdminUsername string
AdminPassword string
}
// NewAPIKeyAuthenticator creates a basic auth authenticator and returns it.
func NewAPIKeyAuthenticator(opts *Options) (authenticator.Password, error) {
issuerURL, err := url.Parse(opts.OIDCIssuerURL)
if err != nil {
return nil, err
}
issuerURL.Path = opts.TokenReviewPath
tr, err := transport.NewOneWayTLSTransport(opts.OIDCCAFile, true)
if err != nil {
return nil, err
}
return &Authenticator{
adminUsername: opts.AdminUsername,
adminPassword: opts.AdminPassword,
tokenReviewURL: issuerURL.String(),
tokenReviewTransport: tr,
}, nil
}
// Authenticator according to the basic auth header information in the http
// request, treats the password as the APIKey of the OIDC server, requests the
// token review of the OIDC server, and returns user authentication information.
type Authenticator struct {
adminUsername string
adminPassword string
tokenReviewURL string
tokenReviewTransport *http.Transport
}
// AuthenticatePassword implements authenticator.Password.
func (a *Authenticator) AuthenticatePassword(_ context.Context, username, password string) (*authenticator.Response, bool, error) {
if a.adminPassword != "" &&
a.adminUsername != "" &&
username == a.adminUsername &&
password == a.adminPassword {
log.Debug("Authenticated a system administrator")
u := &user.DefaultInfo{
Name: a.adminUsername,
UID: "",
Groups: nil,
Extra: make(map[string][]string, 0),
}
return &authenticator.Response{
User: u,
}, true, nil
}
if a.tokenReviewURL == "" {
log.Warn("Token review url not specify, failed to review token")
return nil, false, fmt.Errorf("token review url not specify")
}
log.Debug("Start review token", log.String("username", username), log.String("tokenReviewURL", a.tokenReviewURL))
tokenReviewRequest := &v1.TokenReview{
TypeMeta: metav1.TypeMeta{
Kind: "TokenReview",
APIVersion: v1.SchemeGroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "tke",
},
Spec: v1.TokenReviewSpec{
Token: password,
},
}
bs, err := json.Marshal(tokenReviewRequest)
if err != nil {
log.Error("Failed to marshal token review request", log.Any("tokenReview", tokenReviewRequest), log.Err(err))
return nil, false, err
}
req, err := http.NewRequest(http.MethodPost, a.tokenReviewURL, bytes.NewBuffer(bs))
if err != nil {
log.Error("Failed to create token review request", log.Err(err))
return nil, false, err
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{
Transport: a.tokenReviewTransport,
}
res, err := client.Do(req)
if err != nil {
log.Error("Failed to request token review", log.Err(err))
}
defer func() {
_ = res.Body.Close()
}()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error("Failed to read response body", log.Err(err))
return nil, false, err
}
if res.StatusCode != http.StatusOK {
log.Error("Authentication server returns http status code error when token review",
log.Int("statusCode", res.StatusCode),
log.ByteString("responseBody", body))
return nil, false, err
}
var tokenReviewResponse v1.TokenReview
if err := json.Unmarshal(body, &tokenReviewResponse); err != nil {
log.Error("Failed to unmarshal token review response", log.ByteString("body", body), log.Err(err))
return nil, false, err
}
if tokenReviewResponse.Status.Error != "" {
log.Error("Authentication server returns error when token review",
log.String("error", tokenReviewResponse.Status.Error))
return nil, false, fmt.Errorf(tokenReviewResponse.Status.Error)
}
if !tokenReviewResponse.Status.Authenticated {
log.Error("Authentication server returns not authenticated when token review",
log.Any("tokenReviewStatus", tokenReviewResponse.Status))
return nil, false, fmt.Errorf("unknown error when token review")
}
u := &user.DefaultInfo{
Name: tokenReviewResponse.Status.User.Username,
UID: tokenReviewResponse.Status.User.UID,
Groups: tokenReviewResponse.Status.User.Groups,
Extra: make(map[string][]string, 0),
}
if len(tokenReviewResponse.Status.User.Extra) > 0 {
for k, v := range tokenReviewResponse.Status.User.Extra {
u.Extra[k] = v
}
}
return &authenticator.Response{
User: u,
}, true, nil
}