-
Notifications
You must be signed in to change notification settings - Fork 153
/
user.go
257 lines (216 loc) · 7.57 KB
/
user.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
Copyright 2020 The Kubermatic Kubernetes Platform contributors.
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
http://www.apache.org/licenses/LICENSE-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 OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"strings"
"time"
apiv1 "github.com/kubermatic/kubermatic/api/pkg/api/v1"
kubermaticv1 "github.com/kubermatic/kubermatic/api/pkg/crd/kubermatic/v1"
"github.com/kubermatic/kubermatic/api/pkg/provider"
"github.com/kubermatic/kubermatic/api/pkg/resources"
providerconfig "github.com/kubermatic/machine-controller/pkg/providerconfig/types"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
type blacklistToken struct {
Token string `json:"token"`
Expiry apiv1.Time `json:"expiry"`
}
// NewUserProvider returns a user provider
func NewUserProvider(client ctrlruntimeclient.Client, isServiceAccountFunc func(email string) bool) *UserProvider {
return &UserProvider{
client: client,
isServiceAccountFunc: isServiceAccountFunc,
}
}
// UserProvider manages user resources
type UserProvider struct {
client ctrlruntimeclient.Client
// since service account are special type of user this functions
// helps to determine if the given email address belongs to a service account
isServiceAccountFunc func(email string) bool
}
// UserByID returns a user by the given ID
func (p *UserProvider) UserByID(id string) (*kubermaticv1.User, error) {
user := &kubermaticv1.User{}
if err := p.client.Get(context.Background(), ctrlruntimeclient.ObjectKey{Name: id}, user); err != nil {
return nil, err
}
return user, nil
}
// UserByEmail returns a user by the given email
func (p *UserProvider) UserByEmail(email string) (*kubermaticv1.User, error) {
users := &kubermaticv1.UserList{}
if err := p.client.List(context.Background(), users); err != nil {
return nil, err
}
for _, user := range users.Items {
if strings.EqualFold(user.Spec.Email, email) {
return user.DeepCopy(), nil
}
}
return nil, provider.ErrNotFound
}
// CreateUser creates a new user.
//
// Note that:
// The name of the newly created resource will be unique and it is derived from the user's email address (sha256(email)
// This prevents creating multiple resources for the same user with the same email address.
//
// In the beginning I was considering to hex-encode the email address as it will produce a unique output because the email address in unique.
// The only issue I have found with this approach is that the length can get quite long quite fast.
// Thus decided to use sha256 as it produces fixed output and the hash collisions are very, very, very, very rare.
func (p *UserProvider) CreateUser(id, name, email string) (*kubermaticv1.User, error) {
if len(id) == 0 || len(name) == 0 || len(email) == 0 {
return nil, kerrors.NewBadRequest("Email, ID and Name cannot be empty when creating a new user resource")
}
if p.isServiceAccountFunc(email) {
return nil, kerrors.NewBadRequest(fmt.Sprintf("cannot add a user with the given email %s as the name is reserved, please try a different email address", email))
}
user := &kubermaticv1.User{
ObjectMeta: v1.ObjectMeta{
Name: fmt.Sprintf("%x", sha256.Sum256([]byte(email))),
},
Spec: kubermaticv1.UserSpec{
ID: id,
Name: name,
Email: email,
},
}
if err := p.client.Create(context.Background(), user); err != nil {
return nil, err
}
return user, nil
}
// UpdateUser updates user.
func (p *UserProvider) UpdateUser(user *kubermaticv1.User) (*kubermaticv1.User, error) {
if err := p.client.Update(context.Background(), user); err != nil {
return nil, err
}
return user, nil
}
func (p *UserProvider) AddUserTokenToBlacklist(user *kubermaticv1.User, token string, expiry apiv1.Time) error {
if user == nil {
return kerrors.NewBadRequest("user cannot be nil")
}
if token == "" {
return kerrors.NewBadRequest("token cannot be empty")
}
ctx := context.Background()
secret, err := ensureTokenBlacklistSecret(ctx, p.client, user)
if err != nil {
return err
}
tokenList, ok := secret.Data[resources.TokenBlacklist]
if !ok {
return fmt.Errorf("secret %s has no key %s", secret.Name, resources.TokenBlacklist)
}
blockedTokens := make([]blacklistToken, 0)
if len(tokenList) > 0 {
if err := json.Unmarshal(tokenList, &blockedTokens); err != nil {
return err
}
}
blockedTokens = append(blockedTokens, blacklistToken{
Token: token,
Expiry: expiry,
})
blockedTokens = clearExpiredTokens(blockedTokens)
tokenJSON, err := json.Marshal(&blockedTokens)
if err != nil {
return err
}
secret.Data = map[string][]byte{
resources.TokenBlacklist: tokenJSON,
}
if err := p.client.Update(ctx, secret); err != nil {
return err
}
return nil
}
func (p *UserProvider) GetUserBlacklistTokens(user *kubermaticv1.User) ([]string, error) {
result := make([]string, 0)
if user == nil {
return nil, kerrors.NewBadRequest("user cannot be nil")
}
if user.Spec.TokenBlackListReference == nil {
return result, nil
}
secretKeyGetter := provider.SecretKeySelectorValueFuncFactory(context.Background(), p.client)
tokenList, err := secretKeyGetter(user.Spec.TokenBlackListReference, resources.TokenBlacklist)
if err != nil {
return nil, err
}
blockedTokens := make([]blacklistToken, 0)
if len(tokenList) > 0 {
if err := json.Unmarshal([]byte(tokenList), &blockedTokens); err != nil {
return nil, err
}
}
for _, token := range blockedTokens {
result = append(result, token.Token)
}
return result, nil
}
func ensureTokenBlacklistSecret(ctx context.Context, client ctrlruntimeclient.Client, user *kubermaticv1.User) (*corev1.Secret, error) {
name := user.GetTokenBlackListSecretName()
namespacedName := types.NamespacedName{Namespace: resources.KubermaticNamespace, Name: name}
existingSecret := &corev1.Secret{}
if err := client.Get(ctx, namespacedName, existingSecret); err != nil && !kerrors.IsNotFound(err) {
return nil, fmt.Errorf("failed to probe for secret %q: %v", name, err)
}
if existingSecret.Name == "" {
existingSecret = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: resources.KubermaticNamespace,
},
Type: corev1.SecretTypeOpaque,
Data: map[string][]byte{
resources.TokenBlacklist: {},
},
}
if err := client.Create(ctx, existingSecret); err != nil {
return nil, fmt.Errorf("failed to create token blacklist secret: %v", err)
}
}
if user.Spec.TokenBlackListReference == nil {
user.Spec.TokenBlackListReference = &providerconfig.GlobalSecretKeySelector{
ObjectReference: corev1.ObjectReference{
Name: name,
Namespace: resources.KubermaticNamespace,
},
}
if err := client.Update(ctx, user); err != nil {
return nil, fmt.Errorf("failed to update user: %v", err)
}
}
return existingSecret, nil
}
func clearExpiredTokens(tokens []blacklistToken) []blacklistToken {
blockedTokens := make([]blacklistToken, 0)
for _, blockedToken := range tokens {
if blockedToken.Expiry.After(time.Now()) {
blockedTokens = append(blockedTokens, blockedToken)
}
}
return blockedTokens
}