File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\security\GlobalMatrixAuthorizationStrategy.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.security;
25
26 import com.thoughtworks.xstream.converters.Converter;
27 import com.thoughtworks.xstream.converters.MarshallingContext;
28 import com.thoughtworks.xstream.converters.UnmarshallingContext;
29 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
30 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
31 import hudson.diagnosis.OldDataMonitor;
32 import hudson.model.Descriptor;
33 import jenkins.model.Jenkins;
34 import hudson.model.Item;
35 import hudson.util.FormValidation;
36 import hudson.util.FormValidation.Kind;
37 import hudson.util.VersionNumber;
38 import hudson.util.RobustReflectionConverter;
39 import hudson.Functions;
40 import hudson.Extension;
41 import net.sf.json.JSONObject;
42 import org.acegisecurity.AuthenticationException;
43 import org.acegisecurity.userdetails.UsernameNotFoundException;
44 import org.acegisecurity.acls.sid.Sid;
45 import org.kohsuke.stapler.Stapler;
46 import org.kohsuke.stapler.StaplerRequest;
47 import org.kohsuke.stapler.QueryParameter;
48 import org.springframework.dao.DataAccessException;
49
50 import javax.servlet.ServletException;
51 import java.util.ArrayList;
52 import java.util.Arrays;
53 import java.util.HashMap;
54 import java.util.HashSet;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.Map.Entry;
58 import java.util.Set;
59 import java.util.logging.Level;
60 import java.util.logging.Logger;
61 import java.io.IOException;
62 import java.util.Collections;
63 import java.util.SortedMap;
64 import java.util.TreeMap;
65
66 /**
67 * Role-based authorization via a matrix.
68 *
69 * @author Kohsuke Kawaguchi
70 */
71 // TODO: think about the concurrency commitment of this class
72 public class GlobalMatrixAuthorizationStrategy extends AuthorizationStrategy {
73 private transient SidACL acl = new AclImpl();
74
75 /**
76 * List up all permissions that are granted.
77 *
78 * Strings are either the granted authority or the principal,
79 * which is not distinguished.
80 */
81 private final Map<Permission,Set<String>> grantedPermissions = new HashMap<Permission, Set<String>>();
82
83 private final Set<String> sids = new HashSet<String>();
84
85 /**
86 * Adds to {@link #grantedPermissions}.
87 * Use of this method should be limited during construction,
88 * as this object itself is considered immutable once populated.
89 */
90 public void add(Permission p, String sid) {
91 if (p==null)
92 throw new IllegalArgumentException();
93 Set<String> set = grantedPermissions.get(p);
94 if(set==null)
95 grantedPermissions.put(p,set = new HashSet<String>());
96 set.add(sid);
97 sids.add(sid);
98 }
99
100 /**
101 * Works like {@link #add(Permission, String)} but takes both parameters
102 * from a single string of the form <tt>PERMISSIONID:sid</tt>
103 */
104 private void add(String shortForm) {
105 int idx = shortForm.indexOf(':');
106 Permission p = Permission.fromId(shortForm.substring(0, idx));
107 if (p==null)
108 throw new IllegalArgumentException("Failed to parse '"+shortForm+"' --- no such permission");
109 add(p,shortForm.substring(idx+1));
110 }
111
112 @Override
113 public SidACL getRootACL() {
114 return acl;
115 }
116
117 public Set<String> getGroups() {
118 return sids;
119 }
120
121 /**
122 * Due to HUDSON-2324, we want to inject Item.READ permission to everyone who has Hudson.READ,
123 * to remain backward compatible.
124 * @param grantedPermissions
125 */
126 /*package*/ static boolean migrateHudson2324(Map<Permission,Set<String>> grantedPermissions) {
127 boolean result = false;
128 if(Jenkins.getInstance().isUpgradedFromBefore(new VersionNumber("1.300.*"))) {
129 Set<String> f = grantedPermissions.get(Jenkins.READ);
130 if (f!=null) {
131 Set<String> t = grantedPermissions.get(Item.READ);
132 if (t!=null)
133 result = t.addAll(f);
134 else {
135 t = new HashSet<String>(f);
136 result = true;
137 }
138 grantedPermissions.put(Item.READ,t);
139 }
140 }
141 return result;
142 }
143
144 /**
145 * Checks if the given SID has the given permission.
146 */
147 public boolean hasPermission(String sid, Permission p) {
148 for(; p!=null; p=p.impliedBy) {
149 Set<String> set = grantedPermissions.get(p);
150 if(set!=null && set.contains(sid) && p.getEnabled())
151 return true;
152 }
153 return false;
154 }
155
156 /**
157 * Checks if the permission is explicitly given, instead of implied through {@link Permission#impliedBy}.
158 */
159 public boolean hasExplicitPermission(String sid, Permission p) {
160 Set<String> set = grantedPermissions.get(p);
161 return set != null && set.contains(sid) && p.getEnabled();
162 }
163
164 /**
165 * Returns all SIDs configured in this matrix, minus "anonymous"
166 *
167 * @return
168 * Always non-null.
169 */
170 public List<String> getAllSIDs() {
171 Set<String> r = new HashSet<String>();
172 for (Set<String> set : grantedPermissions.values())
173 r.addAll(set);
174 r.remove("anonymous");
175
176 String[] data = r.toArray(new String[r.size()]);
177 Arrays.sort(data);
178 return Arrays.asList(data);
179 }
180
181 private final class AclImpl extends SidACL {
182 protected Boolean hasPermission(Sid p, Permission permission) {
183 if(GlobalMatrixAuthorizationStrategy.this.hasPermission(toString(p),permission))
184 return true;
185 return null;
186 }
187 }
188
189 @Extension
190 public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
191
192 /**
193 * Persist {@link GlobalMatrixAuthorizationStrategy} as a list of IDs that
194 * represent {@link GlobalMatrixAuthorizationStrategy#grantedPermissions}.
195 */
196 public static class ConverterImpl implements Converter {
197 public boolean canConvert(Class type) {
198 return type==GlobalMatrixAuthorizationStrategy.class;
199 }
200
201 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
202 GlobalMatrixAuthorizationStrategy strategy = (GlobalMatrixAuthorizationStrategy)source;
203
204 // Output in alphabetical order for readability.
205 SortedMap<Permission, Set<String>> sortedPermissions = new TreeMap<Permission, Set<String>>(Permission.ID_COMPARATOR);
206 sortedPermissions.putAll(strategy.grantedPermissions);
207 for (Entry<Permission, Set<String>> e : sortedPermissions.entrySet()) {
208 String p = e.getKey().getId();
209 List<String> sids = new ArrayList<String>(e.getValue());
210 Collections.sort(sids);
211 for (String sid : sids) {
212 writer.startNode("permission");
213 writer.setValue(p+':'+sid);
214 writer.endNode();
215 }
216 }
217
218 }
219
220 public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
221 GlobalMatrixAuthorizationStrategy as = create();
222
223 while (reader.hasMoreChildren()) {
224 reader.moveDown();
225 try {
226 as.add(reader.getValue());
227 } catch (IllegalArgumentException ex) {
228 Logger.getLogger(GlobalMatrixAuthorizationStrategy.class.getName())
229 .log(Level.WARNING,"Skipping a non-existent permission",ex);
230 RobustReflectionConverter.addErrorInContext(context, ex);
231 }
232 reader.moveUp();
233 }
234
235 if (migrateHudson2324(as.grantedPermissions))
236 OldDataMonitor.report(context, "1.301");
237
238 return as;
239 }
240
241 protected GlobalMatrixAuthorizationStrategy create() {
242 return new GlobalMatrixAuthorizationStrategy();
243 }
244 }
245
246 public static class DescriptorImpl extends Descriptor<AuthorizationStrategy> {
247 protected DescriptorImpl(Class<? extends GlobalMatrixAuthorizationStrategy> clazz) {
248 super(clazz);
249 }
250
251 public DescriptorImpl() {
252 }
253
254 public String getDisplayName() {
255 return Messages.GlobalMatrixAuthorizationStrategy_DisplayName();
256 }
257
258 @Override
259 public AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException {
260 GlobalMatrixAuthorizationStrategy gmas = create();
261 for(Map.Entry<String,JSONObject> r : (Set<Map.Entry<String,JSONObject>>)formData.getJSONObject("data").entrySet()) {
262 String sid = r.getKey();
263 for(Map.Entry<String,Boolean> e : (Set<Map.Entry<String,Boolean>>)r.getValue().entrySet()) {
264 if(e.getValue()) {
265 Permission p = Permission.fromId(e.getKey());
266 gmas.add(p,sid);
267 }
268 }
269 }
270 return gmas;
271 }
272
273 protected GlobalMatrixAuthorizationStrategy create() {
274 return new GlobalMatrixAuthorizationStrategy();
275 }
276
277 public List<PermissionGroup> getAllGroups() {
278 List<PermissionGroup> groups = new ArrayList<PermissionGroup>(PermissionGroup.getAll());
279 groups.remove(PermissionGroup.get(Permission.class));
280 return groups;
281 }
282
283 public boolean showPermission(Permission p) {
284 return p.getEnabled();
285 }
286
287 public FormValidation doCheckName(@QueryParameter String value ) throws IOException, ServletException {
288 return doCheckName_(value, Jenkins.getInstance(), Jenkins.ADMINISTER);
289 }
290
291 public FormValidation doCheckName_(String value, AccessControlled subject, Permission permission) throws IOException, ServletException {
292 if(!subject.hasPermission(permission)) return FormValidation.ok(); // can't check
293
294 final String v = value.substring(1,value.length()-1);
295 SecurityRealm sr = Jenkins.getInstance().getSecurityRealm();
296 String ev = Functions.escape(v);
297
298 if(v.equals("authenticated"))
299 // system reserved group
300 return FormValidation.respond(Kind.OK, makeImg("user.png") +ev);
301
302 try {
303 try {
304 sr.loadUserByUsername(v);
305 return FormValidation.respond(Kind.OK, makeImg("person.png")+ev);
306 } catch (UserMayOrMayNotExistException e) {
307 // undecidable, meaning the user may exist
308 return FormValidation.respond(Kind.OK, ev);
309 } catch (UsernameNotFoundException e) {
310 // fall through next
311 } catch (DataAccessException e) {
312 // fall through next
313 } catch (AuthenticationException e) {
314 // other seemingly unexpected error.
315 return FormValidation.error(e,"Failed to test the validity of the user name "+v);
316 }
317
318 try {
319 sr.loadGroupByGroupname(v);
320 return FormValidation.respond(Kind.OK, makeImg("user.png") +ev);
321 } catch (UserMayOrMayNotExistException e) {
322 // undecidable, meaning the group may exist
323 return FormValidation.respond(Kind.OK, ev);
324 } catch (UsernameNotFoundException e) {
325 // fall through next
326 } catch (DataAccessException e) {
327 // fall through next
328 } catch (AuthenticationException e) {
329 // other seemingly unexpected error.
330 return FormValidation.error(e,"Failed to test the validity of the group name "+v);
331 }
332
333 // couldn't find it. it doesn't exist
334 return FormValidation.respond(Kind.ERROR, makeImg("error.png") +ev);
335 } catch (Exception e) {
336 // if the check fails miserably, we still want the user to be able to see the name of the user,
337 // so use 'ev' as the message
338 return FormValidation.error(e,ev);
339 }
340 }
341
342 private String makeImg(String gif) {
343 return String.format("<img src='%s%s/images/16x16/%s' style='margin-right:0.2em'>", Stapler.getCurrentRequest().getContextPath(), Jenkins.RESOURCE_PATH, gif);
344 }
345 }
346
347 private static final Logger LOGGER = Logger.getLogger(GlobalMatrixAuthorizationStrategy.class.getName());
348 }
349
350