1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2013 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;
57 use base 'RT::Record';
59 sub Table {'Principals'}
63 use Cache::Simple::TimedExpiry;
70 # Set up the ACL cache on startup
77 Returns true if this principal is a group.
78 Returns undef, otherwise
84 if ( defined $self->PrincipalType &&
85 $self->PrincipalType eq 'Group' ) {
95 Returns true if this principal is a User.
96 Returns undef, otherwise
102 if ($self->PrincipalType eq 'User') {
114 Returns the user or group associated with this principal
121 unless ( $self->{'object'} ) {
122 if ( $self->IsUser ) {
123 $self->{'object'} = RT::User->new($self->CurrentUser);
125 elsif ( $self->IsGroup ) {
126 $self->{'object'} = RT::Group->new($self->CurrentUser);
129 $RT::Logger->crit("Found a principal (".$self->Id.") that was neither a user nor a group");
132 $self->{'object'}->Load( $self->ObjectId() );
134 return ($self->{'object'});
141 =head2 GrantRight { Right => RIGHTNAME, Object => undef }
143 A helper function which calls RT::ACE->Create
147 Returns a tuple of (STATUS, MESSAGE); If the call succeeded, STATUS is true. Otherwise it's
160 return (0, "Permission denied") if $args{'Right'} eq 'ExecuteCode'
161 and RT->Config->Get('DisallowExecuteCode');
163 #ACL check handled in ACE.pm
164 my $ace = RT::ACE->new( $self->CurrentUser );
166 my $type = $self->_GetPrincipalTypeForACL();
168 RT->System->QueueCacheNeedsUpdate(1) if $args{'Right'} eq 'SeeQueue';
170 # If it's a user, we really want to grant the right to their
171 # user equivalence group
173 RightName => $args{'Right'},
174 Object => $args{'Object'},
175 PrincipalType => $type,
176 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 if ( not $status and $msg =~ /Invalid right/ ) {
217 $RT::Logger->warn("Tried to revoke the invalid right '$args{Right}', ignoring it.");
221 RT->System->QueueCacheNeedsUpdate(1) if $args{'Right'} eq 'SeeQueue';
222 return ($status, $msg) unless $status;
228 =head2 HasRight (Right => 'right' Object => undef)
230 Checks to see whether this principal has the right "Right" for the Object
231 specified. This takes the params:
241 an RT style object (->id will get its id)
245 Returns 1 if a matching ACE was found. Returns undef if no ACE was found.
247 Use L</HasRights> to fill a fast cache, especially if you're going to
248 check many different rights with the same principal and object.
255 my %args = ( Right => undef,
257 EquivObjects => undef,
261 # RT's SystemUser always has all rights
262 if ( $self->id == RT->SystemUser->id ) {
266 $args{'Right'} = RT::ACE->CanonicalizeRightName( $args{'Right'} );
267 unless ( $args{'Right'} ) {
269 "Invalid right. Couldn't canonicalize right '$args{'Right'}'");
273 return undef if $args{'Right'} eq 'ExecuteCode'
274 and RT->Config->Get('DisallowExecuteCode');
276 $args{'EquivObjects'} = [ @{ $args{'EquivObjects'} } ]
277 if $args{'EquivObjects'};
279 if ( $self->__Value('Disabled') ) {
280 $RT::Logger->debug( "Disabled User #"
282 . " failed access check for "
287 if ( eval { $args{'Object'}->id } ) {
288 push @{ $args{'EquivObjects'} }, $args{'Object'};
290 $RT::Logger->crit("HasRight called with no valid object");
295 my $cached = $_ACL_CACHE->fetch(
296 $self->id .';:;'. ref($args{'Object'}) .'-'. $args{'Object'}->id
298 return $cached->{'SuperUser'} || $cached->{ $args{'Right'} }
302 unshift @{ $args{'EquivObjects'} },
303 $args{'Object'}->ACLEquivalenceObjects;
305 unshift @{ $args{'EquivObjects'} }, $RT::System
306 unless $self->can('_IsOverrideGlobalACL')
307 && $self->_IsOverrideGlobalACL( $args{'Object'} );
309 # If we've cached a win or loss for this lookup say so
311 # Construct a hashkeys to cache decisions:
312 # 1) full_hashkey - key for any result and for full combination of uid, right and objects
313 # 2) short_hashkey - one key for each object to store positive results only, it applies
314 # only to direct group rights and partly to role rights
315 my $full_hashkey = join (";:;", $self->id, $args{'Right'});
316 foreach ( @{ $args{'EquivObjects'} } ) {
317 my $ref_id = $self->_ReferenceId($_);
318 $full_hashkey .= ";:;".$ref_id;
320 my $short_hashkey = join(";:;", $self->id, $args{'Right'}, $ref_id);
321 my $cached_answer = $_ACL_CACHE->fetch($short_hashkey);
322 return $cached_answer > 0 if defined $cached_answer;
326 my $cached_answer = $_ACL_CACHE->fetch($full_hashkey);
327 return $cached_answer > 0 if defined $cached_answer;
330 my ( $hitcount, $via_obj ) = $self->_HasRight(%args);
332 $_ACL_CACHE->set( $full_hashkey => $hitcount ? 1 : -1 );
333 $_ACL_CACHE->set( join(';:;', $self->id, $args{'Right'},$via_obj) => 1 )
334 if $via_obj && $hitcount;
341 Returns a hash reference with all rights this principal has on an
342 object. Takes Object as a named argument.
344 Main use case of this method is the following:
346 $ticket->CurrentUser->PrincipalObj->HasRights( Object => $ticket );
348 $ticket->CurrentUserHasRight('A');
350 $ticket->CurrentUserHasRight('Z');
352 Results are cached and the cache is used in this and, as well, in L</HasRight>
353 method speeding it up. Don't use hash reference returned by this method
354 directly for rights checks as it's more complicated then it seems, especially
355 considering config options like 'DisallowExecuteCode'.
363 EquivObjects => undef,
366 return {} if $self->__Value('Disabled');
368 my $object = $args{'Object'};
369 unless ( eval { $object->id } ) {
370 $RT::Logger->crit("HasRights called with no valid object");
373 my $cache_key = $self->id .';:;'. ref($object) .'-'. $object->id;
374 my $cached = $_ACL_CACHE->fetch($cache_key);
375 return $cached if $cached;
377 push @{ $args{'EquivObjects'} }, $object;
378 unshift @{ $args{'EquivObjects'} },
379 $args{'Object'}->ACLEquivalenceObjects;
380 unshift @{ $args{'EquivObjects'} }, $RT::System
381 unless $self->can('_IsOverrideGlobalACL')
382 && $self->_IsOverrideGlobalACL( $object );
387 = "SELECT DISTINCT ACL.RightName "
388 . $self->_HasGroupRightQuery(
389 EquivObjects => $args{'EquivObjects'}
391 my $rights = $RT::Handle->dbh->selectcol_arrayref($query);
393 $RT::Logger->warning( $RT::Handle->dbh->errstr );
396 $res{$_} = 1 foreach @$rights;
401 = "SELECT DISTINCT Groups.Type "
402 . $self->_HasRoleRightQuery(
403 EquivObjects => $args{'EquivObjects'}
405 $roles = $RT::Handle->dbh->selectcol_arrayref($query);
407 $RT::Logger->warning( $RT::Handle->dbh->errstr );
413 = "SELECT DISTINCT ACL.RightName "
414 . $self->_RolesWithRightQuery(
415 EquivObjects => $args{'EquivObjects'}
417 . ' AND ('. join( ' OR ', map "PrincipalType = '$_'", @$roles ) .')'
419 my $rights = $RT::Handle->dbh->selectcol_arrayref($query);
421 $RT::Logger->warning( $RT::Handle->dbh->errstr );
424 $res{$_} = 1 foreach @$rights;
427 delete $res{'ExecuteCode'} if
428 RT->Config->Get('DisallowExecuteCode');
430 $_ACL_CACHE->store( $cache_key, \%res );
436 Low level HasRight implementation, use HasRight method instead.
443 my ( $hit, @other ) = $self->_HasGroupRight(@_);
444 return ( $hit, @other ) if $hit;
447 my ( $hit, @other ) = $self->_HasRoleRight(@_);
448 return ( $hit, @other ) if $hit;
453 # this method handles role rights partly in situations
454 # where user plays role X on an object and as well the right is
455 # assigned to this role X of the object, for example right CommentOnTicket
456 # is granted to Cc role of a queue and user is in cc list of the queue
459 my %args = ( Right => undef,
465 = "SELECT ACL.id, ACL.ObjectType, ACL.ObjectId "
466 . $self->_HasGroupRightQuery( %args );
468 $self->_Handle->ApplyLimits( \$query, 1 );
469 my ( $hit, $obj, $id ) = $self->_Handle->FetchResult($query);
470 return (0) unless $hit;
472 $obj .= "-$id" if $id;
476 sub _HasGroupRightQuery {
485 = "FROM ACL, Principals, CachedGroupMembers WHERE "
487 # Never find disabled groups.
488 . "Principals.id = ACL.PrincipalId "
489 . "AND Principals.PrincipalType = 'Group' "
490 . "AND Principals.Disabled = 0 "
492 # See if the principal is a member of the group recursively or _is the rightholder_
493 # never find recursively disabled group members
494 # also, check to see if the right is being granted _directly_ to this principal,
495 # as is the case when we want to look up group rights
496 . "AND CachedGroupMembers.GroupId = ACL.PrincipalId "
497 . "AND CachedGroupMembers.GroupId = Principals.id "
498 . "AND CachedGroupMembers.MemberId = ". $self->Id . " "
499 . "AND CachedGroupMembers.Disabled = 0 ";
502 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
503 my $type = ref($obj) || $obj;
504 my $clause = "ACL.ObjectType = '$type'";
506 if ( defined eval { $obj->id } ) { # it might be 0
507 $clause .= " AND ACL.ObjectId = " . $obj->id;
510 push @clauses, "($clause)";
513 $query .= " AND (" . join( ' OR ', @clauses ) . ")";
515 if ( my $right = $args{'Right'} ) {
516 # Only find superuser or rights with the name $right
517 $query .= " AND (ACL.RightName = 'SuperUser' "
518 . ( $right ne 'SuperUser' ? "OR ACL.RightName = '$right'" : '' )
526 my %args = ( Right => undef,
531 my @roles = $self->RolesWithRight(%args);
532 return 0 unless @roles;
534 my $query = "SELECT Groups.id "
535 . $self->_HasRoleRightQuery( %args, Roles => \@roles );
537 $self->_Handle->ApplyLimits( \$query, 1 );
538 my ($hit) = $self->_Handle->FetchResult($query);
544 sub _HasRoleRightQuery {
546 my %args = ( Right => undef,
553 " FROM Groups, Principals, CachedGroupMembers WHERE "
555 # Never find disabled things
556 . "Principals.Disabled = 0 " . "AND CachedGroupMembers.Disabled = 0 "
558 # We always grant rights to Groups
559 . "AND Principals.id = Groups.id "
560 . "AND Principals.PrincipalType = 'Group' "
562 # See if the principal is a member of the group recursively or _is the rightholder_
563 # never find recursively disabled group members
564 # also, check to see if the right is being granted _directly_ to this principal,
565 # as is the case when we want to look up group rights
566 . "AND Principals.id = CachedGroupMembers.GroupId "
567 . "AND CachedGroupMembers.MemberId = " . $self->Id . " "
570 if ( $args{'Roles'} ) {
571 $query .= "AND (" . join( ' OR ', map "Groups.Type = '$_'", @{ $args{'Roles'} } ) . ")";
574 my (@object_clauses);
575 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
576 my $type = ref($obj) ? ref($obj) : $obj;
578 my $clause = "Groups.Domain = '$type-Role'";
580 # XXX: Groups.Instance is VARCHAR in DB, we should quote value
581 # if we want mysql 4.0 use indexes here. we MUST convert that
582 # field to integer and drop this quotes.
583 if ( my $id = eval { $obj->id } ) {
584 $clause .= " AND Groups.Instance = '$id'";
586 push @object_clauses, "($clause)";
588 $query .= " AND (" . join( ' OR ', @object_clauses ) . ")";
592 =head2 RolesWithRight
594 Returns list with names of roles that have right on
595 set of objects. Takes Right, EquiveObjects,
596 IncludeSystemRights and IncludeSuperusers arguments.
598 IncludeSystemRights is true by default, rights
599 granted systemwide are ignored when IncludeSystemRights
600 is set to a false value.
602 IncludeSuperusers is true by default, SuperUser right
603 is not checked if it's set to a false value.
609 my %args = ( Right => undef,
610 IncludeSystemRights => 1,
611 IncludeSuperusers => 1,
616 return () if $args{'Right'} eq 'ExecuteCode'
617 and RT->Config->Get('DisallowExecuteCode');
619 my $query = "SELECT DISTINCT PrincipalType "
620 . $self->_RolesWithRightQuery( %args );
622 my $roles = $RT::Handle->dbh->selectcol_arrayref($query);
624 $RT::Logger->warning( $RT::Handle->dbh->errstr );
630 sub _RolesWithRightQuery {
632 my %args = ( Right => undef,
633 IncludeSystemRights => 1,
634 IncludeSuperusers => 1,
639 my $query = " FROM ACL WHERE"
642 . " PrincipalType != 'Group'";
644 if ( my $right = $args{'Right'} ) {
646 # Only find superuser or rights with the requested right
647 " AND ( RightName = '$right' "
649 # Check SuperUser if we were asked to
650 . ( $args{'IncludeSuperusers'} ? "OR RightName = 'SuperUser' " : '' )
654 # skip rights granted on system level if we were asked to
655 unless ( $args{'IncludeSystemRights'} ) {
656 $query .= " AND ObjectType != 'RT::System'";
659 my (@object_clauses);
660 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
661 my $type = ref($obj) ? ref($obj) : $obj;
663 my $object_clause = "ObjectType = '$type'";
664 if ( my $id = eval { $obj->id } ) {
665 $object_clause .= " AND ObjectId = $id";
667 push @object_clauses, "($object_clause)";
670 # find ACLs that are related to our objects only
671 $query .= " AND (" . join( ' OR ', @object_clauses ) . ")"
678 =head2 InvalidateACLCache
680 Cleans out and reinitializes the user rights cache
684 sub InvalidateACLCache {
685 $_ACL_CACHE = Cache::Simple::TimedExpiry->new();
687 $lifetime = $RT::Config->Get('ACLCacheLifetime') if $RT::Config;
688 $_ACL_CACHE->expire_after( $lifetime || 60 );
695 =head2 _GetPrincipalTypeForACL
697 Gets the principal type. if it's a user, it's a user. if it's a role group and it has a Type,
698 return that. if it has no type, return group.
702 sub _GetPrincipalTypeForACL {
704 if ($self->PrincipalType eq 'Group' && $self->Object->Domain =~ /Role$/) {
705 return $self->Object->Type;
707 return $self->PrincipalType;
715 Returns a list uniquely representing an object or normal scalar.
717 For a scalar, its string value is returned.
718 For an object that has an id() method which returns a value, its class name and id are returned as a string separated by a "-".
719 For an object that has an id() method which returns false, its class name is returned.
726 my $id = eval { $scalar->id };
730 return ref($scalar) . "-" . $id;
743 Returns the current value of id.
744 (In the database, id is stored as int(11).)
752 Returns the current value of PrincipalType.
753 (In the database, PrincipalType is stored as varchar(16).)
757 =head2 SetPrincipalType VALUE
760 Set PrincipalType to VALUE.
761 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
762 (In the database, PrincipalType will be stored as a varchar(16).)
770 Returns the current value of ObjectId.
771 (In the database, ObjectId is stored as int(11).)
775 =head2 SetObjectId VALUE
778 Set ObjectId to VALUE.
779 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
780 (In the database, ObjectId will be stored as a int(11).)
788 Returns the current value of Disabled.
789 (In the database, Disabled is stored as smallint(6).)
793 =head2 SetDisabled VALUE
796 Set Disabled to VALUE.
797 Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
798 (In the database, Disabled will be stored as a smallint(6).)
805 sub _CoreAccessible {
809 {read => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => ''},
811 {read => 1, write => 1, sql_type => 12, length => 16, is_blob => 0, is_numeric => 0, type => 'varchar(16)', default => ''},
813 {read => 1, write => 1, sql_type => 4, length => 11, is_blob => 0, is_numeric => 1, type => 'int(11)', default => ''},
815 {read => 1, write => 1, sql_type => 5, length => 6, is_blob => 0, is_numeric => 1, type => 'smallint(6)', default => '0'},
820 RT::Base->_ImportOverlays();