-
Notifications
You must be signed in to change notification settings - Fork 143
/
project.go
520 lines (478 loc) · 12.9 KB
/
project.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// Copyright 2020 The PipeCD Authors.
//
// 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 model
import (
"crypto/subtle"
"fmt"
"net/url"
"golang.org/x/crypto/bcrypt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
var (
githubScopes = []string{"read:org"}
builtinAdminRBACRole = &ProjectRBACRole{
Name: builtinRBACRoleAdmin.String(),
Policies: builtinAdminRBACPolicy,
IsBuiltin: true,
}
builtinAdminRBACPolicy = []*ProjectRBACPolicy{
{
Resources: []*ProjectRBACResource{
{
Type: ProjectRBACResource_ALL,
},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_ALL,
},
},
}
builtinEditorRBACRole = &ProjectRBACRole{
Name: builtinRBACRoleEditor.String(),
Policies: builtinEditorRBACPolicy,
IsBuiltin: true,
}
builtinEditorRBACPolicy = []*ProjectRBACPolicy{
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_APPLICATION},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_ALL,
},
},
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_DEPLOYMENT},
{Type: ProjectRBACResource_PIPED},
{Type: ProjectRBACResource_DEPLOYMENT_CHAIN},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_GET,
ProjectRBACPolicy_LIST,
},
},
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_EVENT},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_LIST,
},
},
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_INSIGHT},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_GET,
},
},
}
builtinViewerRBACRole = &ProjectRBACRole{
Name: builtinRBACRoleViewer.String(),
Policies: builtinViewerRBACPolicy,
IsBuiltin: true,
}
builtinViewerRBACPolicy = []*ProjectRBACPolicy{
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_APPLICATION},
{Type: ProjectRBACResource_DEPLOYMENT},
{Type: ProjectRBACResource_PIPED},
{Type: ProjectRBACResource_DEPLOYMENT_CHAIN},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_GET,
ProjectRBACPolicy_LIST,
},
},
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_EVENT},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_LIST,
},
},
{
Resources: []*ProjectRBACResource{
{Type: ProjectRBACResource_INSIGHT},
},
Actions: []ProjectRBACPolicy_Action{
ProjectRBACPolicy_GET,
},
},
}
)
type BuiltinRBACRole string
const (
builtinRBACRoleAdmin BuiltinRBACRole = "Admin"
builtinRBACRoleEditor BuiltinRBACRole = "Editor"
builtinRBACRoleViewer BuiltinRBACRole = "Viewer"
)
func (b BuiltinRBACRole) String() string {
return string(b)
}
type encrypter interface {
Encrypt(text string) (string, error)
}
type decrypter interface {
Decrypt(encryptedText string) (string, error)
}
// SetStaticAdmin sets admin data.
func (p *Project) SetStaticAdmin(username, password string) error {
encoded, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
p.StaticAdmin = &ProjectStaticUser{
Username: username,
PasswordHash: string(encoded),
}
return nil
}
// RedactSensitiveData redacts sensitive data.
func (p *Project) RedactSensitiveData() {
if p.StaticAdmin != nil {
p.StaticAdmin.RedactSensitiveData()
}
if p.Sso != nil {
p.Sso.RedactSensitiveData()
}
}
func (p *Project) SetUpdatedAt(t int64) {
p.UpdatedAt = t
}
// RedactSensitiveData redacts sensitive data.
func (p *ProjectStaticUser) RedactSensitiveData() {
p.PasswordHash = redactedMessage
}
// Update updates ProjectStaticUser with given data.
func (p *ProjectStaticUser) Update(username, password string) error {
if username != "" {
p.Username = username
}
if password != "" {
encoded, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
p.PasswordHash = string(encoded)
}
return nil
}
// Auth confirms username and password.
func (p *ProjectStaticUser) Auth(username, password string) error {
if username == "" {
return fmt.Errorf("username is empty")
}
if subtle.ConstantTimeCompare([]byte(p.Username), []byte(username)) != 1 {
return fmt.Errorf("wrong username %q", username)
}
if password == "" {
return fmt.Errorf("password is empty")
}
if err := bcrypt.CompareHashAndPassword([]byte(p.PasswordHash), []byte(password)); err != nil {
return fmt.Errorf("wrong password for username %q: %v", username, err)
}
return nil
}
// RedactSensitiveData redacts sensitive data.
func (p *ProjectSSOConfig) RedactSensitiveData() {
if p.Github != nil {
p.Github.RedactSensitiveData()
}
if p.Google != nil {
}
}
// Update updates ProjectSSOConfig with given data.
func (p *ProjectSSOConfig) Update(sso *ProjectSSOConfig) error {
p.Provider = sso.Provider
if sso.Github != nil {
if p.Github == nil {
p.Github = &ProjectSSOConfig_GitHub{}
}
if err := p.Github.Update(sso.Github); err != nil {
return err
}
}
if sso.Google != nil {
}
return nil
}
// Encrypt encrypts sensitive data in ProjectSSOConfig.
func (p *ProjectSSOConfig) Encrypt(encrypter encrypter) error {
if p.Github != nil {
if err := p.Github.Encrypt(encrypter); err != nil {
return err
}
}
if p.Google != nil {
}
return nil
}
// Decrypt decrypts encrypted data in ProjectSSOConfig.
func (p *ProjectSSOConfig) Decrypt(decrypter decrypter) error {
if p.Github != nil {
if err := p.Github.Decrypt(decrypter); err != nil {
return err
}
}
if p.Google != nil {
}
return nil
}
// GenerateAuthCodeURL generates an auth URL for the specified configuration.
func (p *ProjectSSOConfig) GenerateAuthCodeURL(project, callbackURL, state string) (string, error) {
switch p.Provider {
case ProjectSSOConfig_GITHUB:
if p.Github == nil {
return "", fmt.Errorf("missing GitHub oauth in the SSO configuration")
}
return p.Github.GenerateAuthCodeURL(project, callbackURL, state)
default:
return "", fmt.Errorf("not implemented")
}
}
// RedactSensitiveData redacts sensitive data.
func (p *ProjectSSOConfig_GitHub) RedactSensitiveData() {
p.ClientId = redactedMessage
p.ClientSecret = redactedMessage
}
// Update updates ProjectSSOConfig with given data.
func (p *ProjectSSOConfig_GitHub) Update(input *ProjectSSOConfig_GitHub) error {
if input.ClientId != "" {
p.ClientId = input.ClientId
}
if input.ClientSecret != "" {
p.ClientSecret = input.ClientSecret
}
if input.BaseUrl != "" {
p.BaseUrl = input.BaseUrl
}
if input.UploadUrl != "" {
p.UploadUrl = input.UploadUrl
}
return nil
}
// Encrypt encrypts sensitive data in ProjectSSOConfig.
func (p *ProjectSSOConfig_GitHub) Encrypt(encrypter encrypter) error {
if p.ClientId != "" {
encrypedClientID, err := encrypter.Encrypt(p.ClientId)
if err != nil {
return err
}
p.ClientId = encrypedClientID
}
if p.ClientSecret != "" {
encryptedClientSecret, err := encrypter.Encrypt(p.ClientSecret)
if err != nil {
return err
}
p.ClientSecret = encryptedClientSecret
}
return nil
}
// Decrypt decrypts ProjectSSOConfig.
func (p *ProjectSSOConfig_GitHub) Decrypt(decrypter decrypter) error {
if p.ClientId != "" {
decrypedClientID, err := decrypter.Decrypt(p.ClientId)
if err != nil {
return err
}
p.ClientId = decrypedClientID
}
if p.ClientSecret != "" {
decryptedClientSecret, err := decrypter.Decrypt(p.ClientSecret)
if err != nil {
return err
}
p.ClientSecret = decryptedClientSecret
}
return nil
}
// GenerateAuthCodeURL generates an auth URL for the specified configuration.
func (p *ProjectSSOConfig_GitHub) GenerateAuthCodeURL(project, callbackURL, state string) (string, error) {
cfg := oauth2.Config{
ClientID: p.ClientId,
Endpoint: github.Endpoint,
}
if p.BaseUrl != "" {
u, err := url.Parse(p.BaseUrl)
if err != nil {
return "", err
}
cfg.Endpoint.AuthURL = fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, "/login/oauth/authorize")
}
cfg.Scopes = githubScopes
cfg.RedirectURL = fmt.Sprintf("%s?project=%s", callbackURL, project)
authURL := cfg.AuthCodeURL(state, oauth2.ApprovalForce, oauth2.AccessTypeOnline)
return authURL, nil
}
// HasRBACRole checks whether the RBAC role is exists.
func (p *Project) HasRBACRole(name string) bool {
for _, v := range p.RbacRoles {
if v.Name == name {
return true
}
}
return false
}
// HasUserGroup checks whether the user group is exists.
func (p *Project) HasUserGroup(sso string) bool {
for _, v := range p.UserGroups {
if v.SsoGroup == sso {
return true
}
}
if r := p.Rbac; r != nil {
return r.Admin == sso || r.Editor == sso || r.Viewer == sso
}
return false
}
// GetAllUserGroups returns user groups and the old RBAC confg if exists.
// If the same team exists in the old RBAC config, this method just only returns the user group that has the highest authority level.
func (p *Project) GetAllUserGroups() []*ProjectUserGroup {
rbac := p.Rbac
if rbac == nil {
return p.UserGroups
}
// The full list also contains 3 legacy user groups.
all := make([]*ProjectUserGroup, 0, len(p.UserGroups)+3)
if rbac.Admin != "" {
all = append(all, &ProjectUserGroup{
SsoGroup: rbac.Admin,
Role: builtinRBACRoleAdmin.String(),
})
}
if rbac.Editor != "" && rbac.Editor != rbac.Admin {
all = append(all, &ProjectUserGroup{
SsoGroup: rbac.Editor,
Role: builtinRBACRoleEditor.String(),
})
}
if rbac.Viewer != "" && rbac.Viewer != rbac.Admin && rbac.Viewer != rbac.Editor {
all = append(all, &ProjectUserGroup{
SsoGroup: rbac.Viewer,
Role: builtinRBACRoleViewer.String(),
})
}
all = append(all, p.UserGroups...)
return all
}
// AddUserGroup adds a user group.
func (p *Project) AddUserGroup(sso, role string) error {
if p.HasUserGroup(sso) {
return fmt.Errorf("%s is already being used. The SSO group must be unique", sso)
}
if !p.HasRBACRole(role) {
return fmt.Errorf("%s role does not exist", role)
}
p.UserGroups = append(p.UserGroups, &ProjectUserGroup{
SsoGroup: sso,
Role: role,
})
return nil
}
// DeleteUserGroup deletes a user group.
func (p *Project) DeleteUserGroup(sso string) error {
for i, v := range p.UserGroups {
if v.SsoGroup == sso {
c := copy(p.UserGroups[i:], p.UserGroups[i+1:])
p.UserGroups = p.UserGroups[:i+c]
return nil
}
}
deleted := false
if p.Rbac != nil {
if p.Rbac.Admin == sso {
p.Rbac.Admin, deleted = "", true
}
if p.Rbac.Editor == sso {
p.Rbac.Editor, deleted = "", true
}
if p.Rbac.Viewer == sso {
p.Rbac.Viewer, deleted = "", true
}
}
if deleted {
return nil
}
return fmt.Errorf("%s user group does not exist", sso)
}
// GetAllRBACRoles returns user groups and built-in roles.
func (p *Project) GetAllRBACRoles() []*ProjectRBACRole {
builtin := []*ProjectRBACRole{
builtinAdminRBACRole,
builtinEditorRBACRole,
builtinViewerRBACRole,
}
all := make([]*ProjectRBACRole, 0, len(p.RbacRoles)+len(builtin))
// Set built-in rbac role.
all = append(all, builtin...)
// Set custom rbac role.
all = append(all, p.RbacRoles...)
return all
}
// isBuiltinRBACRole checks whether the name is the name of built-in role.
func isBuiltinRBACRole(name string) bool {
return name == builtinRBACRoleAdmin.String() ||
name == builtinRBACRoleEditor.String() ||
name == builtinRBACRoleViewer.String()
}
// AddRBACRole adds a custom RBAC role.
func (p *Project) AddRBACRole(name string, policies []*ProjectRBACPolicy) error {
if p.HasRBACRole(name) {
return fmt.Errorf("the name of %s is already used", name)
}
if isBuiltinRBACRole(name) {
return fmt.Errorf("the name of built-in role cannot be used")
}
p.RbacRoles = append(p.RbacRoles, &ProjectRBACRole{
Name: name,
Policies: policies,
})
return nil
}
// UpdateRBACRole updates a custom RBAC role.
// Built-in role cannot be updated.
func (p *Project) UpdateRBACRole(name string, policies []*ProjectRBACPolicy) error {
for _, v := range p.RbacRoles {
if v.Name == name {
v.Policies = policies
return nil
}
}
if isBuiltinRBACRole(name) {
return fmt.Errorf("built-in role cannot be updated")
}
return fmt.Errorf("%s role does not exist", name)
}
// DeleteRBACRole deletes a custom RBAC role.
// Built-in role cannot be deleted.
func (p *Project) DeleteRBACRole(name string) error {
if isBuiltinRBACRole(name) {
return fmt.Errorf("built-in role cannot be deleted")
}
for i, v := range p.RbacRoles {
if v.Name == name {
c := copy(p.RbacRoles[i:], p.RbacRoles[i+1:])
p.RbacRoles = p.RbacRoles[:i+c]
return nil
}
}
return fmt.Errorf("%s role does nott exist", name)
}