1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
6 # <sales@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 # General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
30 # CONTRIBUTION SUBMISSION POLICY:
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
47 # END BPS TAGGED BLOCK }}}
51 package RT::Principal;
56 use Cache::Simple::TimedExpiry;
63 # Set up the ACL cache on startup
71 Returns true if this principal is a group.
72 Returns undef, otherwise
78 if ( defined $self->PrincipalType &&
79 $self->PrincipalType eq 'Group' ) {
91 Returns true if this principal is a User.
92 Returns undef, otherwise
98 if ($self->PrincipalType eq 'User') {
112 Returns the user or group associated with this principal
119 unless ( $self->{'object'} ) {
120 if ( $self->IsUser ) {
121 $self->{'object'} = RT::User->new($self->CurrentUser);
123 elsif ( $self->IsGroup ) {
124 $self->{'object'} = RT::Group->new($self->CurrentUser);
127 $RT::Logger->crit("Found a principal (".$self->Id.") that was neither a user nor a group");
130 $self->{'object'}->Load( $self->ObjectId() );
132 return ($self->{'object'});
138 # {{{ ACL Related routines
142 =head2 GrantRight { Right => RIGHTNAME, Object => undef }
144 A helper function which calls RT::ACE->Create
148 Returns a tuple of (STATUS, MESSAGE); If the call succeeded, STATUS is true. Otherwise it's
161 #ACL check handled in ACE.pm
162 my $ace = RT::ACE->new( $self->CurrentUser );
164 my $type = $self->_GetPrincipalTypeForACL();
166 RT->System->QueueCacheNeedsUpdate(1) if $args{'Right'} eq 'SeeQueue';
168 # If it's a user, we really want to grant the right to their
169 # user equivalence group
171 RightName => $args{'Right'},
172 Object => $args{'Object'},
173 PrincipalType => $type,
174 PrincipalId => $self->Id,
181 =head2 RevokeRight { Right => "RightName", Object => "object" }
183 Delete a right that a user has
186 Returns a tuple of (STATUS, MESSAGE); If the call succeeded, STATUS is true. Otherwise it's
201 #if we haven't specified any sort of right, we're talking about a global right
202 if (!defined $args{'Object'} && !defined $args{'ObjectId'} && !defined $args{'ObjectType'}) {
203 $args{'Object'} = $RT::System;
205 #ACL check handled in ACE.pm
206 my $type = $self->_GetPrincipalTypeForACL();
208 my $ace = RT::ACE->new( $self->CurrentUser );
209 my ($status, $msg) = $ace->LoadByValues(
210 RightName => $args{'Right'},
211 Object => $args{'Object'},
212 PrincipalType => $type,
213 PrincipalId => $self->Id
216 RT->System->QueueCacheNeedsUpdate(1) if $args{'Right'} eq 'SeeQueue';
217 return ($status, $msg) unless $status;
223 # {{{ sub _CleanupInvalidDelegations
225 =head2 sub _CleanupInvalidDelegations { InsideTransaction => undef }
227 Revokes all ACE entries delegated by this principal which are
228 inconsistent with this principal's current delegation rights. Does
229 not perform permission checks, but takes no action and returns success
230 if this principal still retains DelegateRights. Should only ever be
231 called from inside the RT library.
233 If this principal is a group, recursively calls this method on each
234 cached user member of itself.
236 If called from inside a transaction, specify a true value for the
237 InsideTransaction parameter.
239 Returns a true value if the deletion succeeded; returns a false value
240 and logs an internal error if the deletion fails (should not happen).
244 # This is currently just a stub for the methods of the same name in
245 # RT::User and RT::Group.
247 sub _CleanupInvalidDelegations {
249 unless ( $self->Id ) {
250 $RT::Logger->warning("Principal not loaded.");
253 return ($self->Object->_CleanupInvalidDelegations(@_));
260 =head2 sub HasRight (Right => 'right' Object => undef)
263 Checks to see whether this principal has the right "Right" for the Object
264 specified. If the Object parameter is omitted, checks to see whether the
265 user has the right globally.
267 This still hard codes to check to see if a user has queue-level rights
268 if we ask about a specific ticket.
271 This takes the params:
273 Right => name of a right
277 Object => an RT style object (->id will get its id)
280 Returns 1 if a matching ACE was found.
282 Returns undef if no ACE was found.
292 EquivObjects => undef,
296 unless ( $args{'Right'} ) {
297 $RT::Logger->crit("HasRight called without a right");
301 my $canonic_name = RT::ACE->CanonicalizeRightName( $args{'Right'} );
302 unless ( $canonic_name ) {
303 $RT::Logger->error("Invalid right. Couldn't canonicalize right '$args{'Right'}'");
306 $args{'Right'} = $canonic_name;
308 $args{'EquivObjects'} = [ @{ $args{'EquivObjects'} } ]
309 if $args{'EquivObjects'};
311 if ( $self->Disabled ) {
312 $RT::Logger->debug( "Disabled User #"
314 . " failed access check for "
319 if ( defined( $args{'Object'} )
320 && UNIVERSAL::can( $args{'Object'}, 'id' )
321 && $args{'Object'}->id ) {
323 push @{ $args{'EquivObjects'} }, $args{'Object'};
326 $RT::Logger->crit("HasRight called with no valid object");
331 unshift @{ $args{'EquivObjects'} }, $args{'Object'}->ACLEquivalenceObjects;
333 unshift @{ $args{'EquivObjects'} }, $RT::System
334 unless $self->can('_IsOverrideGlobalACL')
335 && $self->_IsOverrideGlobalACL( $args{'Object'} );
337 # {{{ If we've cached a win or loss for this lookup say so
339 # Construct a hashkeys to cache decisions:
340 # 1) full_hashkey - key for any result and for full combination of uid, right and objects
341 # 2) short_hashkey - one key for each object to store positive results only, it applies
342 # only to direct group rights and partly to role rights
343 my $self_id = $self->id;
344 my $full_hashkey = join ";:;", $self_id, $args{'Right'};
345 foreach ( @{ $args{'EquivObjects'} } ) {
346 my $ref_id = _ReferenceId($_);
347 $full_hashkey .= ";:;$ref_id";
349 my $short_hashkey = join ";:;", $self_id, $args{'Right'}, $ref_id;
350 my $cached_answer = $_ACL_CACHE->fetch($short_hashkey);
351 return $cached_answer > 0 if defined $cached_answer;
355 my $cached_answer = $_ACL_CACHE->fetch($full_hashkey);
356 return $cached_answer > 0 if defined $cached_answer;
360 my ($hitcount, $via_obj) = $self->_HasRight( %args );
362 $_ACL_CACHE->set( $full_hashkey => $hitcount? 1: -1 );
363 $_ACL_CACHE->set( "$self_id;:;$args{'Right'};:;$via_obj" => 1 )
364 if $via_obj && $hitcount;
371 Low level HasRight implementation, use HasRight method instead.
379 my ($hit, @other) = $self->_HasGroupRight( @_ );
380 return ($hit, @other) if $hit;
383 my ($hit, @other) = $self->_HasRoleRight( @_ );
384 return ($hit, @other) if $hit;
389 # this method handles role rights partly in situations
390 # where user plays role X on an object and as well the right is
391 # assigned to this role X of the object, for example right CommentOnTicket
392 # is granted to Cc role of a queue and user is in cc list of the queue
401 my $right = $args{'Right'};
404 "SELECT ACL.id, ACL.ObjectType, ACL.ObjectId " .
405 "FROM ACL, Principals, CachedGroupMembers WHERE " .
407 # Only find superuser or rights with the name $right
408 "(ACL.RightName = 'SuperUser' OR ACL.RightName = '$right') "
410 # Never find disabled groups.
411 . "AND Principals.id = ACL.PrincipalId "
412 . "AND Principals.PrincipalType = 'Group' "
413 . "AND Principals.Disabled = 0 "
415 # See if the principal is a member of the group recursively or _is the rightholder_
416 # never find recursively disabled group members
417 # also, check to see if the right is being granted _directly_ to this principal,
418 # as is the case when we want to look up group rights
419 . "AND CachedGroupMembers.GroupId = ACL.PrincipalId "
420 . "AND CachedGroupMembers.GroupId = Principals.id "
421 . "AND CachedGroupMembers.MemberId = ". $self->Id ." "
422 . "AND CachedGroupMembers.Disabled = 0 ";
425 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
426 my $type = ref( $obj ) || $obj;
427 my $clause = "ACL.ObjectType = '$type'";
429 if ( ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id ) {
430 $clause .= " AND ACL.ObjectId = ". $obj->id;
433 push @clauses, "($clause)";
436 $query .= " AND (". join( ' OR ', @clauses ) .")";
439 $self->_Handle->ApplyLimits( \$query, 1 );
440 my ($hit, $obj, $id) = $self->_Handle->FetchResult( $query );
441 return (0) unless $hit;
443 $obj .= "-$id" if $id;
456 my @roles = $self->RolesWithRight( %args );
457 return 0 unless @roles;
459 my $right = $args{'Right'};
463 . "FROM Groups, Principals, CachedGroupMembers WHERE "
465 # Never find disabled things
466 . "Principals.Disabled = 0 "
467 . "AND CachedGroupMembers.Disabled = 0 "
469 # We always grant rights to Groups
470 . "AND Principals.id = Groups.id "
471 . "AND Principals.PrincipalType = 'Group' "
473 # See if the principal is a member of the group recursively or _is the rightholder_
474 # never find recursively disabled group members
475 # also, check to see if the right is being granted _directly_ to this principal,
476 # as is the case when we want to look up group rights
477 . "AND Principals.id = CachedGroupMembers.GroupId "
478 . "AND CachedGroupMembers.MemberId = ". $self->Id ." "
480 . "AND (". join(' OR ', map "Groups.Type = '$_'", @roles ) .")"
483 my (@object_clauses);
484 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
485 my $type = ref($obj)? ref($obj): $obj;
487 $id = $obj->id if ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id;
489 my $clause = "Groups.Domain = '$type-Role'";
490 # XXX: Groups.Instance is VARCHAR in DB, we should quote value
491 # if we want mysql 4.0 use indexes here. we MUST convert that
492 # field to integer and drop this quotes.
493 $clause .= " AND Groups.Instance = '$id'" if $id;
494 push @object_clauses, "($clause)";
496 $query .= " AND (". join( ' OR ', @object_clauses ) .")";
498 $self->_Handle->ApplyLimits( \$query, 1 );
499 my ($hit) = $self->_Handle->FetchResult( $query );
505 =head2 RolesWithRight
507 Returns list with names of roles that have right on
508 set of objects. Takes Right, EquiveObjects,
509 IncludeSystemRights and IncludeSuperusers arguments.
511 IncludeSystemRights is true by default, rights
512 granted on system level are not accouned when option
513 is set to false value.
515 IncludeSuperusers is true by default, SuperUser right
516 is not checked if it's set to false value.
524 IncludeSystemRights => 1,
525 IncludeSuperusers => 1,
529 my $right = $args{'Right'};
532 "SELECT DISTINCT PrincipalType FROM ACL"
533 # Only find superuser or rights with the name $right
534 ." WHERE ( RightName = '$right' "
535 # Check SuperUser if we were asked to
536 . ($args{'IncludeSuperusers'}? "OR RightName = 'SuperUser' " : '' )
539 ." AND PrincipalType != 'Group'"
542 # skip rights granted on system level if we were asked to
543 unless ( $args{'IncludeSystemRights'} ) {
544 $query .= " AND ObjectType != 'RT::System'";
547 my (@object_clauses);
548 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
549 my $type = ref($obj)? ref($obj): $obj;
551 $id = $obj->id if ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id;
553 my $object_clause = "ObjectType = '$type'";
554 $object_clause .= " AND ObjectId = $id" if $id;
555 push @object_clauses, "($object_clause)";
557 # find ACLs that are related to our objects only
558 $query .= " AND (". join( ' OR ', @object_clauses ) .")"
561 my $dbh = $RT::Handle->dbh;
562 my $roles = $dbh->selectcol_arrayref($query);
564 $RT::Logger->warning( $dbh->errstr );
577 # {{{ InvalidateACLCache
579 =head2 InvalidateACLCache
581 Cleans out and reinitializes the user rights cache
585 sub InvalidateACLCache {
586 $_ACL_CACHE = Cache::Simple::TimedExpiry->new();
588 $lifetime = $RT::Config->Get('ACLCacheLifetime') if $RT::Config;
589 $_ACL_CACHE->expire_after( $lifetime || 60 );
597 # {{{ _GetPrincipalTypeForACL
599 =head2 _GetPrincipalTypeForACL
601 Gets the principal type. if it's a user, it's a user. if it's a role group and it has a Type,
602 return that. if it has no type, return group.
606 sub _GetPrincipalTypeForACL {
609 if ($self->PrincipalType eq 'Group' && $self->Object->Domain =~ /Role$/) {
610 $type = $self->Object->Type;
613 $type = $self->PrincipalType;
625 Returns a list uniquely representing an object or normal scalar.
627 For scalars, its string value is returned; for objects that has an
628 id() method, its class name and Id are returned as a string separated by a "-".
635 # just return the value for non-objects
636 return $scalar unless UNIVERSAL::can($scalar, 'id');
638 return ref($scalar) unless $scalar->id;
640 # an object -- return the class and id
641 return(ref($scalar)."-". $scalar->id);