001: /* Copyright (c) 2001-2005, The HSQL Development Group
002: * All rights reserved.
003: *
004: * Redistribution and use in source and binary forms, with or without
005: * modification, are permitted provided that the following conditions are met:
006: *
007: * Redistributions of source code must retain the above copyright notice, this
008: * list of conditions and the following disclaimer.
009: *
010: * Redistributions in binary form must reproduce the above copyright notice,
011: * this list of conditions and the following disclaimer in the documentation
012: * and/or other materials provided with the distribution.
013: *
014: * Neither the name of the HSQL Development Group nor the names of its
015: * contributors may be used to endorse or promote products derived from this
016: * software without specific prior written permission.
017: *
018: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
019: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
020: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
021: * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
022: * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
023: * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
024: * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025: * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
026: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028: * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029: */
030:
031: package org.hsqldb;
032:
033: import org.hsqldb.HsqlNameManager.HsqlName;
034: import org.hsqldb.lib.HashSet;
035: import org.hsqldb.lib.IntValueHashMap;
036: import org.hsqldb.lib.Iterator;
037: import org.hsqldb.lib.Set;
038:
039: /**
040: * A Grantee Object holds the name, access and administrative rights for a
041: * particular grantee.<p>
042: * It supplies the methods used to grant, revoke, test
043: * and check a grantee's access rights to other database objects.
044: * It also holds a reference to the common PUBLIC User Object,
045: * which represent the special user refered to in
046: * GRANT ... TO PUBLIC statements.<p>
047: * The check(), isAccessible() and getGrantedClassNames() methods check the
048: * rights granted to the PUBLIC User Object, in addition to individually
049: * granted rights, in order to decide which rights exist for the user.
050: *
051: * Method names ending in Direct indicate methods which do not recurse
052: * to look through Roles which "this" object is a member of.
053: *
054: * We use the word "Admin" (e.g., in private variable "admin" and method
055: * "isAdmin()) to mean this Grantee has admin priv by any means.
056: * We use the word "adminDirect" (e.g., in private variable "adminDirect"
057: * and method "isAdminDirect()) to mean this Grantee has admin priv
058: * directly.
059: *
060: * @author boucherb@users
061: * @author fredt@usrs
062: * @author unsaved@users
063: *
064: * @version 1.8.0
065: * @since 1.8.0
066: */
067: public class Grantee {
068:
069: boolean isRole;
070:
071: /**
072: * true if this grantee has database administrator priv directly
073: * (ie., not by membership in any role)
074: */
075: private boolean isAdminDirect = false;
076:
077: /** true if this grantee has database administrator priv by any means. */
078: private boolean isAdmin = false;
079:
080: /** contains righs granted direct, or via roles, expept those of PUBLIC */
081: private IntValueHashMap fullRightsMap = new IntValueHashMap();
082:
083: /**
084: * Grantee name.
085: */
086: private String granteeName;
087:
088: /** map with database object identifier keys and access privileges values */
089: private IntValueHashMap rightsMap;
090:
091: /** These are the DIRECT roles. Each of these may contain nested roles */
092: HashSet roles = new HashSet();
093:
094: /**
095: * The special PUBLIC Grantee object. <p>
096: *
097: * Note: All Grantee objects except the special
098: * SYS and PUBLIC Grantee objects contain a reference to this object
099: */
100: private Grantee pubGrantee;
101:
102: /** Needed only to give access to the roles for this database */
103: private GranteeManager granteeManager;
104:
105: /**
106: * Constructor, with a argument reference to the PUBLIC User Object which
107: * is null if this is the SYS or PUBLIC user.
108: *
109: * The dependency upon a GranteeManager is undesirable. Hopefully we
110: * can get rid of this dependency with an IOC or Listener re-design.
111: */
112: Grantee(String name, Grantee inGrantee, GranteeManager man)
113: throws HsqlException {
114:
115: rightsMap = new IntValueHashMap();
116: granteeName = name;
117: granteeManager = man;
118: pubGrantee = inGrantee;
119: }
120:
121: String getName() {
122: return granteeName;
123: }
124:
125: /**
126: * Retrieves the map object that represents the rights that have been
127: * granted on database objects. <p>
128: *
129: * The map has keys and values with the following interpretation: <P>
130: *
131: * <UL>
132: * <LI> The keys are generally (but not limited to) objects having
133: * an attribute or value equal to the name of an actual database
134: * object.
135: *
136: * <LI> Specifically, the keys act as database object identifiers.
137: *
138: * <LI> The values are always Integer objects, each formed by combining
139: * a set of flags, one for each of the access rights defined in
140: * UserManager: {SELECT, INSERT, UPDATE and DELETE}.
141: * </UL>
142: */
143: IntValueHashMap getRights() {
144:
145: // necessary to create the script
146: return rightsMap;
147: }
148:
149: /**
150: * Grant a role
151: */
152: public void grant(String role) throws HsqlException {
153: roles.add(role);
154: }
155:
156: /**
157: * Revoke a direct role only
158: */
159: public void revoke(String role) throws HsqlException {
160:
161: if (!hasRoleDirect(role)) {
162: throw Trace.error(Trace.DONT_HAVE_ROLE, role);
163: }
164:
165: roles.remove(role);
166: }
167:
168: /**
169: * Gets direct roles, not roles nested within them.
170: */
171: public HashSet getDirectRoles() {
172: return roles;
173: }
174:
175: String getDirectRolesString() {
176: return setToString(roles);
177: }
178:
179: String getAllRolesString() {
180: return setToString(getAllRoles());
181: }
182:
183: public String setToString(Set set) {
184:
185: // Should be sorted
186: // Iterator it = (new java.util.TreeSet(roles)).iterator();
187: Iterator it = set.iterator();
188: StringBuffer sb = new StringBuffer();
189:
190: while (it.hasNext()) {
191: if (sb.length() > 0) {
192: sb.append(',');
193: }
194:
195: sb.append(it.next());
196: }
197:
198: return sb.toString();
199: }
200:
201: /**
202: * Gets direct and nested roles.
203: */
204: public HashSet getAllRoles() {
205:
206: HashSet newSet = new HashSet();
207:
208: addGranteeAndRoles(newSet);
209:
210: // Since we added "Grantee" in addition to Roles, need to remove self.
211: newSet.remove(granteeName);
212:
213: return newSet;
214: }
215:
216: /**
217: * Adds to given Set this.sName plus all roles and nested roles.
218: *
219: * @return Given role with new elements added.
220: */
221: private HashSet addGranteeAndRoles(HashSet set) {
222:
223: String candidateRole;
224:
225: set.add(granteeName);
226:
227: Iterator it = roles.iterator();
228:
229: while (it.hasNext()) {
230: candidateRole = (String) it.next();
231:
232: if (!set.contains(candidateRole)) {
233: try {
234: granteeManager.getRole(candidateRole)
235: .addGranteeAndRoles(set);
236: } catch (HsqlException he) {
237: throw new RuntimeException(he.getMessage());
238: }
239: }
240: }
241:
242: return set;
243: }
244:
245: public boolean hasRoleDirect(String role) {
246: return roles.contains(role);
247: }
248:
249: public boolean hasRole(String role) {
250: return getAllRoles().contains(role);
251: }
252:
253: public String allRolesString() {
254:
255: HashSet allRoles = getAllRoles();
256:
257: if (allRoles.size() < 1) {
258: return null;
259: }
260:
261: Iterator it = getAllRoles().iterator();
262: StringBuffer sb = new StringBuffer();
263:
264: while (it.hasNext()) {
265: if (sb.length() > 0) {
266: sb.append(',');
267: }
268:
269: sb.append((String) it.next());
270: }
271:
272: return sb.toString();
273: }
274:
275: /**
276: * Grants the specified rights on the specified database object. <p>
277: *
278: * Keys stored in rightsMap for database tables are their HsqlName
279: * attribute. This allows rights to persist when a table is renamed. <p>
280: */
281: void grant(Object dbobject, int rights) {
282:
283: if (rights == 0) {
284: return;
285: }
286:
287: int n = rightsMap.get(dbobject, 0);
288:
289: n |= rights;
290:
291: rightsMap.put(dbobject, n);
292: }
293:
294: /**
295: * Revokes the specified rights on the specified database object. <p>
296: *
297: * If, after removing the specified rights, no rights remain on the
298: * database object, then the key/value pair for that object is removed
299: * from the rights map
300: */
301: void revoke(Object dbobject, int rights) {
302:
303: if (rights == 0) {
304: return;
305: }
306:
307: int n = rightsMap.get(dbobject, 0);
308:
309: if (n == 0) {
310: return;
311: }
312:
313: rights = n & (GranteeManager.ALL - rights);
314:
315: if (rights == 0) {
316: rightsMap.remove(dbobject);
317: } else {
318: rightsMap.put(dbobject, rights);
319: }
320: }
321:
322: /**
323: * Revokes all rights on the specified database object.<p>
324: *
325: * This method removes any existing mapping from the rights map
326: */
327: void revokeDbObject(Object dbobject) {
328: rightsMap.remove(dbobject);
329: fullRightsMap.remove(dbobject);
330: }
331:
332: /**
333: * Revokes all rights from this Grantee object. The map is cleared and
334: * the database administrator role attribute is set false.
335: */
336: void clearPrivileges() {
337:
338: roles.clear();
339: rightsMap.clear();
340: fullRightsMap.clear();
341:
342: isAdminDirect = false;
343: }
344:
345: /**
346: * Checks if any of the rights represented by the rights
347: * argument have been granted on the specified database object. <p>
348: *
349: * This is done by checking that a mapping exists in the rights map
350: * from the dbobject argument for at least one of the rights
351: * contained in the rights argument. Otherwise, it throws.
352: */
353: void check(HsqlName dbobject, int rights) throws HsqlException {
354:
355: if (!isAccessible(dbobject, rights)) {
356: throw Trace.error(Trace.ACCESS_IS_DENIED);
357: }
358: }
359:
360: void check(String dbobject) throws HsqlException {
361:
362: if (!isAccessible(dbobject)) {
363: throw Trace.error(Trace.ACCESS_IS_DENIED);
364: }
365: }
366:
367: /**
368: * Returns true if any of the rights represented by the
369: * rights argument has been granted on the database object identified
370: * by the dbobject argument. <p>
371: *
372: * This is done by checking that a mapping exists in the rights map
373: * from the dbobject argument for at least one of the rights
374: * contained in the rights argument.
375: *
376: * Only does one level of recursion to check the PUBLIC role.
377: */
378: boolean isAccessible(HsqlName dbObject, int rights)
379: throws HsqlException {
380:
381: if (isAdmin) {
382: return true;
383: }
384:
385: if (pubGrantee != null
386: && pubGrantee.isAccessible(dbObject, rights)) {
387: return true;
388: }
389:
390: int n = fullRightsMap.get(dbObject, 0);
391:
392: if (n != 0) {
393: return (n & rights) != 0;
394: }
395:
396: return false;
397: }
398:
399: /**
400: * Returns true if any right at all has been granted to this User object
401: * on the database object identified by the dbObject argument.
402: */
403: boolean isAccessible(String functionName) throws HsqlException {
404:
405: if (functionName.startsWith("org.hsqldb.Library")
406: || functionName.startsWith("java.lang.Math")) {
407: return true;
408: }
409:
410: if (isAdmin) {
411: return true;
412: }
413:
414: if (pubGrantee != null && pubGrantee.isAccessible(functionName)) {
415: return true;
416: }
417:
418: int n = fullRightsMap.get(functionName, 0);
419:
420: return n != 0;
421: }
422:
423: /**
424: * Returns true if any of the rights represented by the
425: * rights argument has been granted on the database object identified
426: * by the dbObject argument. <p>
427: *
428: * This is done by checking that a mapping exists in the rights map
429: * from the dbObject argument for at least one of the rights
430: * contained in the rights argument.
431: *
432: * Considers none of pubGranee, nested roles, admin privs, globally
433: * available Class object.
434: */
435: protected boolean isDirectlyAccessible(Object dbObject, int rights)
436: throws HsqlException {
437:
438: int n = rightsMap.get(dbObject, 0);
439:
440: if (n != 0) {
441: return (n & rights) != 0;
442: }
443:
444: return false;
445: }
446:
447: /**
448: * Returns true if any right at all has been granted to this User object
449: * on the database object identified by the dbObject argument.
450: */
451: boolean isAccessible(HsqlName dbObject) throws HsqlException {
452: return isAccessible(dbObject, GranteeManager.ALL);
453: }
454:
455: /**
456: * Checks whether this Grantee has administrative privs either directly
457: * or indirectly. Otherwise it throws.
458: */
459: void checkAdmin() throws HsqlException {
460:
461: if (!isAdmin()) {
462: throw Trace.error(Trace.ACCESS_IS_DENIED);
463: }
464: }
465:
466: /**
467: * Returns true if this Grantee has administrative privs either directly
468: * or indirectly.
469: */
470: boolean isAdmin() {
471: return isAdmin;
472: }
473:
474: /**
475: * Returns true if this grantee object is for a user with Direct
476: * database administrator privileges.
477: * I.e., if this User/Role has Admin priv. directly, not via a
478: * nested Role.
479: */
480: boolean isAdminDirect() {
481: return isAdminDirect;
482: }
483:
484: /**
485: * Retrieves the distinct set of Java <code>Class</code> FQNs
486: * for which this <code>User</code> object has been
487: * granted <code>ALL</code> (the Class execution privilege). <p>
488: * @param andToPublic if <code>true</code>, then the set includes the
489: * names of classes accessible to this <code>User</code> object
490: * through grants to its Roles + <code>PUBLIC</code>
491: * <code>User</code> object attribute, else only role grants
492: * + direct grants are included.
493: * @return the distinct set of Java Class FQNs for which this
494: * this <code>User</code> object has been granted
495: * <code>ALL</code>.
496: */
497: HashSet getGrantedClassNames(boolean andToPublic)
498: throws HsqlException {
499:
500: IntValueHashMap rights;
501: Object key;
502: int right;
503: Iterator i;
504:
505: rights = rightsMap;
506:
507: HashSet out = getGrantedClassNamesDirect();
508:
509: if (andToPublic && pubGrantee != null) {
510: rights = pubGrantee.rightsMap;
511: i = rights.keySet().iterator();
512:
513: while (i.hasNext()) {
514: key = i.next();
515:
516: if (key instanceof String) {
517: right = rights.get(key, 0);
518:
519: if (right == GranteeManager.ALL) {
520: out.add(key);
521: }
522: }
523: }
524: }
525:
526: Iterator it = getAllRoles().iterator();
527:
528: while (it.hasNext()) {
529: out.addAll(((Grantee) granteeManager.getRole((String) it
530: .next())).getGrantedClassNamesDirect());
531: }
532:
533: return out;
534: }
535:
536: /**
537: * Retrieves the distinct set of Java <code>Class</code> FQNs
538: * for which this <code>User</code> object has directly been
539: * granted <code>ALL</code> (the Class execution privilege).
540: *
541: * Does NOT check nested the pubGrantee nor nested roles.
542: * @return the distinct set of Java Class FQNs for which this
543: * this <code>User</code> object has been granted
544: * <code>ALL</code>.
545: *
546: */
547: HashSet getGrantedClassNamesDirect() throws HsqlException {
548:
549: IntValueHashMap rights;
550: HashSet out;
551: Object key;
552: int right;
553: Iterator i;
554:
555: rights = rightsMap;
556: out = new HashSet();
557: i = rightsMap.keySet().iterator();
558:
559: while (i.hasNext()) {
560: key = i.next();
561:
562: if (key instanceof String) {
563: right = rights.get(key, 0);
564:
565: if (right == GranteeManager.ALL) {
566: out.add(key);
567: }
568: }
569: }
570:
571: return out;
572: }
573:
574: /**
575: * Retrieves a string[] whose elements are the names of the rights
576: * explicitly granted with the GRANT command to this <code>User</code>
577: * object on the <code>Table</code> object identified by the
578: * <code>name</code> argument.
579: * * @return array of Strings naming the rights granted to this
580: * <code>User</code> object on the <code>Table</code> object
581: * identified by the <code>name</code> argument.
582: * @param name a <code>Table</code> object identifier
583: *
584: */
585: String[] listGrantedTablePrivileges(HsqlName name) {
586: return GranteeManager.getRightsArray(rightsMap.get(name, 0));
587: }
588:
589: /**
590: * Violates naming convention (for backward compatibility).
591: * Should be "setAdminDirect(boolean").
592: */
593: void setAdminDirect() {
594: isAdmin = isAdminDirect = true;
595: }
596:
597: /**
598: * Recursive method used with ROLE Grantee objects to set the fullRightsMap
599: * and admin flag for all the roles.
600: *
601: * If a new ROLE is granted to a ROLE Grantee object, the ROLE should first
602: * be added to the Set of ROLE Grantee objects (roles) for the grantee.
603: * The grantee will be the parameter.
604: *
605: * If the direct permissions granted to an existing ROLE Grentee is
606: * modified no extra initial action is necessary.
607: * The existing Grantee will b the parameter.
608: *
609: * If an existing ROLE is REVOKEed from a ROLE, it should first be removed
610: * from the set of ROLE Grantee objects in the containing ROLE.
611: * The containing ROLE will be the parameter.
612: *
613: * If an existing ROLE is DROPped, all its privileges should be cleared
614: * first. The ROLE will be the parameter. After calling this method on
615: * all other roles, the DROPped role should be removed from all grantees.
616: *
617: * After the initial modification, this method should be called iteratively
618: * on all the ROLE Grantee objects contained in RoleManager.
619: *
620: * The updateAllRights() method is then called iteratively on all the
621: * USER Grantee objects contained in UserManager.
622: * @param role a modified, revoked or dropped role.
623: * @return true if this Grantee has possibly changed as a result
624: */
625: boolean updateNestedRoles(String role) {
626:
627: boolean hasNested = false;
628: boolean isSelf = role.equals(granteeName);
629:
630: if (!isSelf) {
631: Iterator it = roles.iterator();
632:
633: while (it.hasNext()) {
634: String roleName = (String) it.next();
635:
636: try {
637: Grantee currentRole = granteeManager
638: .getRole(roleName);
639:
640: hasNested |= currentRole.updateNestedRoles(role);
641: } catch (HsqlException e) {
642: }
643: }
644: }
645:
646: if (hasNested) {
647: updateAllRights();
648: }
649:
650: return hasNested || isSelf;
651: }
652:
653: /**
654: * Method used with all Grantee objects to set the full set of rights
655: * according to those inherited form ROLE Grantee objects and those
656: * granted to the object itself.
657: */
658: void updateAllRights() {
659:
660: fullRightsMap.clear();
661:
662: isAdmin = isAdminDirect;
663:
664: Iterator it = roles.iterator();
665:
666: while (it.hasNext()) {
667: String roleName = (String) it.next();
668:
669: try {
670: Grantee currentRole = granteeManager.getRole(roleName);
671:
672: fullRightsMap.putAll(currentRole.fullRightsMap);
673:
674: isAdmin |= currentRole.isAdmin();
675: } catch (HsqlException e) {
676: }
677: }
678:
679: fullRightsMap.putAll(rightsMap);
680: }
681: }
|