-
Notifications
You must be signed in to change notification settings - Fork 306
/
matrix-authorization-strategy.groovy
executable file
·182 lines (163 loc) · 5.93 KB
/
matrix-authorization-strategy.groovy
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
#!groovy
//-------------------------------------------------------------------
// @copyright 2018 DennyZhang.com
// Licensed under MIT
// https://www.dennyzhang.com/wp-content/mit_license.txt
//
// File: matrix-authorization-strategy.groovy
// Author : Denny <https://www.dennyzhang.com/contact>
// Link: https://cheatsheet.dennyzhang.com/cheatsheet-jenkins-groovy-a4
// --
// Created : <2018-04-20>
// Updated: Time-stamp: <2019-05-01 16:53:20>
//-------------------------------------------------------------------
// http://www.tothenew.com/blog/jenkins-implementing-project-based-matrix-authorization-strategy/
/*
Configure matrix authorization strategy with permissions for users and
groups. This script is idempotent and will only change configuration if
necessary.
Example configuration:
authz_strategy_config = [
strategy: 'GlobalMatrixAuthorizationStrategy',
user_permissions: [
anonymous: ['Job Discover'],
authenticated: ['Overall Read', 'Job Read', 'View Read'],
admin: ['Overall Administer']
]
]
Available Authorization Strategies:
GlobalMatrixAuthorizationStrategy
ProjectMatrixAuthorizationStrategy
Available user permissions:
Overall Administer
Overall Read
Agent Configure
Agent Delete
Agent Create
Agent Disconnect
Agent Connect
Agent Build
Agent Provision
Run Delete
Run Update
Job Create
Job Delete
Job Configure
Job Read
Job Discover
Job Build
Job Workspace
Job Cancel
SCM Tag
Credentials Create
Credentials Update
Credentials View
Credentials Delete
Credentials ManageDomains
Job Move
View Create
View Delete
View Configure
View Read
Run Replay
"Job ViewStatus" permission becomes available after installing the
embeddable build status plugin.
*/
import jenkins.model.*
import hudson.security.GlobalMatrixAuthorizationStrategy
import hudson.security.Permission
import hudson.security.ProjectMatrixAuthorizationStrategy
import jenkins.model.Jenkins
class Helper implements Serializable {
static String shortName(Permission p) {
p.id.tokenize('.')[-2..-1].join(' ')
.replace('Hudson','Overall')
.replace('Computer', 'Agent')
.replace('Item', 'Job')
.replace('CredentialsProvider', 'Credentials')
}
static Map getCurrentPermissions(Map config = [:]) {
Map currentPermissions = [:].withDefault { [].toSet() }
if(!('getGrantedPermissions' in Jenkins.instance.authorizationStrategy.metaClass.methods*.name.sort().unique())) {
return currentPermissions
}
Closure merger = { Map nmap, Map m ->
m.each { k, v ->
nmap[k] += v
}
}
Jenkins.instance.authorizationStrategy.grantedPermissions.collect { permission, userList ->
userList.collect { user ->
[ (user): shortName(permission) ]
}
}.flatten().each merger.curry(currentPermissions)
currentPermissions
}
static boolean isConfigurationEqual(Map config) {
Map currentPermissions = getCurrentPermissions(config)
Jenkins.instance.authorizationStrategy.class.name.endsWith(config['strategy']) &&
!(false in config['user_permissions'].collect { k, v -> currentPermissions[k] == v.toSet() }) &&
currentPermissions.keySet() == config['user_permissions'].keySet()
}
static boolean isValidConfig(def config, List<String> validPermissions) {
Map currentPermissions = getCurrentPermissions()
config instanceof Map &&
config.keySet().containsAll(['strategy', 'user_permissions']) &&
config['strategy'] &&
config['strategy'] instanceof String &&
config['strategy'] in ['GlobalMatrixAuthorizationStrategy', 'ProjectMatrixAuthorizationStrategy'] &&
config['user_permissions'] &&
!(false in config['user_permissions'].collect { k, v ->
k instanceof String &&
(v instanceof List || v instanceof Set) &&
!(false in v.collect {
validPermissions.contains(it)
})
})
}
}
Map<String, Permission> permissionIds = Permission.all.findAll { permission ->
List<String> nonConfigurablePerms = ['RunScripts', 'UploadPlugins', 'ConfigureUpdateCenter']
permission.enabled &&
!permission.id.startsWith('hudson.security.Permission') &&
!(true in nonConfigurablePerms.collect { permission.id.endsWith(it) })
}.collect { permission ->
[ (Helper.shortName(permission)): permission ]
}.sum()
/**
* MAIN EXECUTION
*/
if(!binding.hasVariable('authz_strategy_config')) {
authz_strategy_config = [
strategy: 'GlobalMatrixAuthorizationStrategy',
user_permissions: [
'authenticated': ['Overall Read'],
'zdenny': ['Overall Administer']
]
]
}
if(!Helper.isValidConfig(authz_strategy_config, permissionIds.keySet().toList())) {
println([
'Skip configuring matrix authorization strategy because no valid config was provided.',
'Available Authorization Strategies:\n GlobalMatrixAuthorizationStrategy\n ProjectMatrixAuthorizationStrategy',
"Available Permissions:\n ${permissionIds.keySet().join('\n ')}"
].join('\n'))
return
}
if(Helper.isConfigurationEqual(authz_strategy_config)) {
println "Nothing changed. ${authz_strategy_config['strategy']} authorization strategy already configured."
return
}
println "Configuring authorization strategy ${authz_strategy_config['strategy']}"
def authz_strategy = Class.forName("hudson.security.${authz_strategy_config['strategy']}").newInstance()
// build the permissions in the strategy
authz_strategy_config['user_permissions'].each { user, permissions ->
permissions.each { p ->
authz_strategy.add(permissionIds[p], user)
println " For user ${user} grant permission ${p}."
}
}
// configure global authorization
Jenkins.instance.authorizationStrategy = authz_strategy
// save settings to persist across restarts
Jenkins.instance.save()