]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
892ffbacf31501d833d626e7314bdad6a9cf6c78
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.authorization.importer;
25
26 import java.io.File;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import java.util.ArrayList;
30 import java.util.Hashtable;
31 import java.util.List;
32 import javax.xml.bind.JAXBContext;
33 import javax.xml.bind.Marshaller;
34 import org.collectionspace.services.authorization.perms.Permission;
35 import org.collectionspace.services.authorization.PermissionRole;
36 import org.collectionspace.services.authorization.PermissionValue;
37 import org.collectionspace.services.authorization.perms.PermissionsList;
38 import org.collectionspace.services.authorization.PermissionsRolesList;
39 import org.collectionspace.services.client.TenantClient;
40 import org.collectionspace.services.authorization.Role;
41 import org.collectionspace.services.authorization.RoleValue;
42 import org.collectionspace.services.authorization.RolesList;
43 import org.collectionspace.services.authorization.SubjectType;
44 import org.collectionspace.services.common.authorization_mgt.AuthorizationCommon;
45 import org.collectionspace.services.common.config.ServicesConfigReaderImpl;
46 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
47 import org.collectionspace.services.common.security.SecurityUtils;
48 import org.collectionspace.services.config.service.ServiceBindingType;
49 import org.collectionspace.services.config.tenant.TenantBindingType;
50
51 /**
52  * AuthorizationGen generates authorizations (permissions and roles)
53  * for tenant services
54  * @author 
55  */
56 public class AuthorizationGen {
57
58     //
59     // Should the base resource act as a proxy for its sub-resources for AuthZ purposes
60     //
61     final public static boolean AUTHZ_IS_ENTITY_PROXY = false;
62     
63     final public static String TENANT_MGMNT_ID = "0";
64     
65         private static final boolean USE_APP_GENERATED_BINDINGS = true;
66     
67     final Logger logger = LoggerFactory.getLogger(AuthorizationGen.class);
68     private List<Permission> tenantMgmntPermList = new ArrayList<Permission>();
69     private List<PermissionRole> tenantMgmntPermRoleList = new ArrayList<PermissionRole>();
70     private List<Permission> adminPermList = new ArrayList<Permission>();
71     private List<PermissionRole> adminPermRoleList = new ArrayList<PermissionRole>();
72     private List<Permission> readerPermList = new ArrayList<Permission>();
73     private List<PermissionRole> readerPermRoleList = new ArrayList<PermissionRole>();
74     private List<Role> adminRoles = new ArrayList<Role>();
75     private List<Role> readerRoles = new ArrayList<Role>();
76     private Role cspaceTenantMgmntRole;
77     private Hashtable<String, TenantBindingType> tenantBindings =
78             new Hashtable<String, TenantBindingType>();
79         //
80     // Store the list of default roles, perms, and roleperms
81     //
82     private List<PermissionRole> allPermRoleList = null;
83         private List<Permission> allPermList;
84         private List<Role> allRoleList;
85
86     public void initialize(String tenantRootDirPath) throws Exception {
87         ServicesConfigReaderImpl servicesConfigReader = new ServicesConfigReaderImpl(tenantRootDirPath);
88         servicesConfigReader.read(USE_APP_GENERATED_BINDINGS);        
89         Boolean useAppGeneratedBindings = servicesConfigReader.getConfiguration().isUseAppGeneratedTenantBindings();
90
91         TenantBindingConfigReaderImpl tenantBindingConfigReader =
92                 new TenantBindingConfigReaderImpl(tenantRootDirPath);
93         tenantBindingConfigReader.read(useAppGeneratedBindings);
94         // Note that we build permissions for all tenants, whether or not they are marked create disabled.
95         // This is a hack until we can correctly run an incremental import.
96         tenantBindings = tenantBindingConfigReader.getTenantBindings(
97                                                         TenantBindingConfigReaderImpl.INCLUDE_CREATE_DISABLED_TENANTS);
98         cspaceTenantMgmntRole = buildTenantMgmntRole();
99
100         if (logger.isDebugEnabled()) {
101             logger.debug("initialized with tenant bindings from " + tenantRootDirPath);
102         }
103     }
104
105     /**
106      * createDefaultPermissions creates default admin and reader permissions
107      * for each tenant found in the given tenant binding file
108      * @see initialize
109      * @return
110      */
111     public void createDefaultPermissions() {
112         for (String tenantId : tenantBindings.keySet()) {
113             List<Permission> adminPerms = createDefaultAdminPermissions(tenantId, AUTHZ_IS_ENTITY_PROXY);
114             adminPermList.addAll(adminPerms);
115
116             List<Permission> readerPerms = createDefaultReaderPermissions(tenantId, AUTHZ_IS_ENTITY_PROXY);
117             readerPermList.addAll(readerPerms);
118         }
119         
120         List<Permission> tenantMgmntPerms = createDefaultTenantMgmntPermissions();
121         tenantMgmntPermList.addAll(tenantMgmntPerms);
122     }
123
124     /**
125      * createDefaultAdminPermissions creates default admin permissions for all services
126      * used by the given tenant
127      * @param tenantId
128      * @return
129      */
130     public List<Permission> createDefaultAdminPermissions(String tenantId, boolean isEntityProxy) {
131         ArrayList<Permission> apcList = new ArrayList<Permission>();
132         TenantBindingType tbinding = tenantBindings.get(tenantId);
133         for (ServiceBindingType sbinding : tbinding.getServiceBindings()) {
134
135             //add permissions for the main path
136                 String resourceName = sbinding.getName().toLowerCase().trim();
137                 if (isEntityProxy == true) {
138                         resourceName = SecurityUtils.getResourceEntity(resourceName);
139                 }
140             Permission perm = buildAdminPermission(tbinding.getId(),
141                     resourceName);
142             apcList.add(perm);
143
144             //add permissions for alternate paths
145             if (isEntityProxy == false) {
146                     List<String> uriPaths = sbinding.getUriPath();
147                     for (String uriPath : uriPaths) {
148                         perm = buildAdminPermission(tbinding.getId(),
149                                 uriPath.toLowerCase());
150                         apcList.add(perm);
151                     }
152             }
153         }
154         
155         return apcList;
156     }
157
158     /**
159      * createDefaultTenantMgmntPermissions creates default permissions for known 
160      * Tenant Mgmnt services. 
161      * @return
162      */
163     public List<Permission> createDefaultTenantMgmntPermissions() {
164         ArrayList<Permission> apcList = new ArrayList<Permission>();
165         // Later can think about ways to configure this if we want to
166         Permission perm = createTenantMgmntPermission(TenantClient.SERVICE_NAME);
167         apcList.add(perm);
168         
169         return apcList;
170     }
171
172     /**
173      * createTenantMgmntPermission creates special admin permissions for tenant management
174      * @return
175      */
176     private Permission  createTenantMgmntPermission(String resourceName) {
177         Permission perm = buildAdminPermission(TENANT_MGMNT_ID, resourceName);
178         return perm;
179     }
180
181     private Permission buildAdminPermission(String tenantId, String resourceName) {
182         String description = "Generated admin permission.";
183         return AuthorizationCommon.createPermission(tenantId, resourceName, description, AuthorizationCommon.ACTIONGROUP_CRUDL_NAME);
184     }
185
186     /**
187      * createDefaultReaderPermissions creates read only permissions for all services
188      * used by the given tenant
189      * @param tenantId
190      * @return
191      */
192     public List<Permission> createDefaultReaderPermissions(String tenantId, boolean isEntityProxy) {
193         ArrayList<Permission> apcList = new ArrayList<Permission>();
194         TenantBindingType tbinding = tenantBindings.get(tenantId);
195         for (ServiceBindingType sbinding : tbinding.getServiceBindings()) {
196             //add permissions for the main path
197                 String resourceName = sbinding.getName().toLowerCase().trim();
198                 if (isEntityProxy == true) {
199                         resourceName = SecurityUtils.getResourceEntity(resourceName);
200                 }               
201             Permission perm = buildReaderPermission(tbinding.getId(),
202                     resourceName);
203             apcList.add(perm);
204
205             //add permissions for alternate paths
206             if (isEntityProxy == false) {
207                     List<String> uriPaths = sbinding.getUriPath();
208                     for (String uriPath : uriPaths) {
209                         perm = buildReaderPermission(tbinding.getId(),
210                                 uriPath.toLowerCase());
211                         apcList.add(perm);
212                     }
213             }
214         }
215         return apcList;
216
217     }
218
219     private Permission buildReaderPermission(String tenantId, String resourceName) {
220         String description = "Generated read-only permission.";
221         return AuthorizationCommon.createPermission(tenantId, resourceName, description, AuthorizationCommon.ACTIONGROUP_RL_NAME);      
222     }
223
224     public List<Permission> getDefaultPermissions() {
225         if (allPermList == null) {
226                 allPermList = new ArrayList<Permission>();
227                 allPermList.addAll(adminPermList);
228                 allPermList.addAll(readerPermList);
229                 allPermList.addAll(tenantMgmntPermList);
230         }
231         return allPermList;
232     }
233
234     public List<Permission> getDefaultAdminPermissions() {
235         return adminPermList;
236     }
237
238     public List<Permission> getDefaultReaderPermissions() {
239         return readerPermList;
240     }
241
242     public List<Permission> getDefaultTenantMgmntPermissions() {
243         return tenantMgmntPermList;
244     }
245
246     /**
247      * createDefaultRoles creates default admin and reader roles
248      * for each tenant found in the given tenant binding file
249      */
250     public void createDefaultRoles() {
251         for (String tenantId : tenantBindings.keySet()) {
252
253             Role arole = buildTenantAdminRole(tenantId);
254             adminRoles.add(arole);
255
256             Role rrole = buildTenantReaderRole(tenantId);
257             readerRoles.add(rrole);
258         }
259     }
260
261     private Role buildTenantAdminRole(String tenantId) {
262         String type = "admin";
263         Role result = AuthorizationCommon.getRole(tenantId, AuthorizationCommon.ROLE_TENANT_ADMINISTRATOR);
264         
265         if (result == null) {
266                 // the role doesn't exist already, so we need to create it
267                 String description = "Generated tenant " + type + " role.";
268                 result = AuthorizationCommon.createRole(tenantId, AuthorizationCommon.ROLE_TENANT_ADMINISTRATOR, description, true /*immutable*/);
269         }
270         
271         return result;
272     }
273
274     private Role buildTenantReaderRole(String tenantId) {
275         String type = "read only";
276         Role result = AuthorizationCommon.getRole(tenantId, AuthorizationCommon.ROLE_TENANT_READER);
277         
278         if (result == null) {
279                 // the role doesn't exist already, so we need to create it
280                 String description = "Generated tenant " + type + " role.";
281                 result = AuthorizationCommon.createRole(tenantId, AuthorizationCommon.ROLE_TENANT_READER, description, true /*immutable*/);
282         }
283         
284         return result;
285     }
286     
287
288     public List<Role> getDefaultRoles() {
289         if (allRoleList == null) {
290                 allRoleList = new ArrayList<Role>();
291                 allRoleList.addAll(adminRoles);
292                 allRoleList.addAll(readerRoles);
293                 // Finally, add the tenant manager role to the list
294                 allRoleList.add(cspaceTenantMgmntRole);
295         }
296         return allRoleList;
297     }
298
299     public void associateDefaultPermissionsRoles() {
300         for (Permission p : adminPermList) {
301             PermissionRole permAdmRole = associatePermissionRoles(p, adminRoles, true);
302             adminPermRoleList.add(permAdmRole);
303         }
304
305         for (Permission p : readerPermList) {
306             PermissionRole permRdrRole = associatePermissionRoles(p, readerRoles, true);
307             readerPermRoleList.add(permRdrRole);
308         }
309         
310         //CSpace Tenant Manager has all access
311         // PLS - this looks wrong. This should be a tenantMgmnt role, and only have access to 
312         // tenantMgmnt perms. Will leave this for now...
313         List<Role> roles = new ArrayList<Role>();
314         roles.add(cspaceTenantMgmntRole);
315         /* for (Permission p : adminPermList) {
316             PermissionRole permCAdmRole = associatePermissionRoles(p, roles, false);
317             adminPermRoleList.add(permCAdmRole);
318         }  */       
319         // Now associate the tenant management perms to the role
320         for (Permission p : tenantMgmntPermList) {
321                 // Note we enforce tenant, as should all be tenant 0 (the special one)
322             PermissionRole permTMRole = associatePermissionRoles(p, roles, true);
323             tenantMgmntPermRoleList.add(permTMRole);
324         }        
325     }
326
327     public List<PermissionRole> associatePermissionsRoles(List<Permission> perms, List<Role> roles, boolean enforceTenancy) {
328         List<PermissionRole> result = null;
329         
330         List<PermissionRole> permRoles = new ArrayList<PermissionRole>();
331         for (Permission perm : perms) {
332             PermissionRole permRole = associatePermissionRoles(perm, roles, enforceTenancy);
333             if (permRole != null) {
334                 permRoles.add(permRole);
335             }
336         }
337         
338         if (permRoles.isEmpty() == false) {
339                 result = permRoles;
340         }
341         
342         return result;
343     }
344
345     private PermissionRole associatePermissionRoles(Permission perm,
346             List<Role> roles, boolean enforceTenancy) {
347         PermissionRole result = null;
348         
349         PermissionRole pr = new PermissionRole();
350         pr.setSubject(SubjectType.ROLE);
351         List<PermissionValue> permValues = new ArrayList<PermissionValue>();
352         pr.setPermission(permValues);
353         PermissionValue permValue = new PermissionValue();
354         permValue.setPermissionId(perm.getCsid());
355         permValue.setResourceName(perm.getResourceName().toLowerCase());
356         permValue.setActionGroup(perm.getActionGroup());
357         permValues.add(permValue);
358
359         List<RoleValue> roleValues = new ArrayList<RoleValue>();
360         for (Role role : roles) {
361                 boolean tenantIdsMatched = true;
362                 if (enforceTenancy == true) {
363                         tenantIdsMatched = role.getTenantId().equals(perm.getTenantId());
364                 }
365                 if (tenantIdsMatched == true) {
366                     RoleValue rv = new RoleValue();
367                     // This needs to use the qualified name, not the display name
368                     rv.setRoleName(role.getRoleName().toUpperCase());
369                     rv.setRoleId(role.getCsid());
370                     roleValues.add(rv);
371                 } else {
372                         if (logger.isTraceEnabled() == true) {
373                                 logger.trace("Role and Permission tenant ID did not match."); //FIXME: REM - Remove this debug statement.
374                         }
375                 }
376         }
377         //
378         // If 'roleValues' is not empty, then associate it with the incoming 'perm' values
379         // otherwise, return null;
380         //
381         if (roleValues.isEmpty() == false) {
382                 pr.setRole(roleValues);
383                 result = pr;
384         }
385
386         return result;
387     }
388
389     public List<PermissionRole> getDefaultPermissionRoles() {
390         if (allPermRoleList  == null) {
391                 allPermRoleList = new ArrayList<PermissionRole>();
392                 allPermRoleList.addAll(adminPermRoleList);
393                 allPermRoleList.addAll(readerPermRoleList);
394                 allPermRoleList.addAll(tenantMgmntPermRoleList);
395         }
396         return allPermRoleList;
397     }
398
399     public List<PermissionRole> getDefaultAdminPermissionRoles() {
400         return adminPermRoleList;
401     }
402
403     public List<PermissionRole> getDefaultReaderPermissionRoles() {
404         return readerPermRoleList;
405     }
406
407     private Role buildTenantMgmntRole() {
408         Role role = new Role();
409         
410         role.setDescription("A generated super role that has permissions to manage tenants.");
411         role.setDisplayName(AuthorizationCommon.ROLE_ALL_TENANTS_MANAGER);
412         role.setRoleName(AuthorizationCommon.getQualifiedRoleName(
413                         AuthorizationCommon.ALL_TENANTS_MANAGER_TENANT_ID, role.getDisplayName()));
414         role.setCsid(AuthorizationCommon.ROLE_ALL_TENANTS_MANAGER_ID);
415         role.setTenantId(AuthorizationCommon.ALL_TENANTS_MANAGER_TENANT_ID);
416         
417         return role;
418     }
419     
420
421     public void exportDefaultRoles(String fileName) {
422         RolesList rList = new RolesList();
423         rList.setRole(this.getDefaultRoles());
424         //
425         // Since it is missing the @XMLRootElement annotation, create a JAXBElement wrapper for the RoleList instance
426         // so we can have it marshalled it correctly.
427         //
428         org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
429         toFile(objectFactory.createRolesList(rList), RolesList.class,
430                 fileName);
431         if (logger.isDebugEnabled()) {
432             logger.debug("exported roles to " + fileName);
433         }
434     }
435
436     public void exportDefaultPermissions(String fileName) {
437         PermissionsList pcList = new PermissionsList();
438         pcList.setPermission(this.getDefaultPermissions());
439         org.collectionspace.services.authorization.ObjectFactory objectFactory =
440                 new org.collectionspace.services.authorization.ObjectFactory();
441         toFile(pcList, PermissionsList.class,
442 //        toFile(objectFactory.createPermissionsList(pcList), PermissionsList.class,
443                 fileName);
444         if (logger.isDebugEnabled()) {
445             logger.debug("exported permissions to " + fileName);
446         }
447     }
448
449     public void exportDefaultPermissionRoles(String fileName) {
450         PermissionsRolesList psrsl = new PermissionsRolesList();
451         psrsl.setPermissionRole(this.getDefaultAdminPermissionRoles());
452         toFile(psrsl, PermissionsRolesList.class,
453                 fileName);
454         if (logger.isDebugEnabled()) {
455             logger.debug("exported permissions-roles to " + fileName);
456         }
457     }
458
459     private void toFile(Object o, Class jaxbClass, String fileName) {
460         File f = new File(fileName);
461         try {
462             JAXBContext jc = JAXBContext.newInstance(jaxbClass);
463             Marshaller m = jc.createMarshaller();
464             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
465                     Boolean.TRUE);
466             m.marshal(o, f);
467         } catch (Exception e) {
468             e.printStackTrace();
469         }
470     }
471 }