1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
6 # <jesse@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 # If it's a user, we really want to grant the right to their
167 # user equivalence group
169 RightName => $args{'Right'},
170 Object => $args{'Object'},
171 PrincipalType => $type,
172 PrincipalId => $self->Id,
179 =head2 RevokeRight { Right => "RightName", Object => "object" }
181 Delete a right that a user has
184 Returns a tuple of (STATUS, MESSAGE); If the call succeeded, STATUS is true. Otherwise it's
199 #if we haven't specified any sort of right, we're talking about a global right
200 if (!defined $args{'Object'} && !defined $args{'ObjectId'} && !defined $args{'ObjectType'}) {
201 $args{'Object'} = $RT::System;
203 #ACL check handled in ACE.pm
204 my $type = $self->_GetPrincipalTypeForACL();
206 my $ace = RT::ACE->new( $self->CurrentUser );
207 my ($status, $msg) = $ace->LoadByValues(
208 RightName => $args{'Right'},
209 Object => $args{'Object'},
210 PrincipalType => $type,
211 PrincipalId => $self->Id
213 return ($status, $msg) unless $status;
219 # {{{ sub _CleanupInvalidDelegations
221 =head2 sub _CleanupInvalidDelegations { InsideTransaction => undef }
223 Revokes all ACE entries delegated by this principal which are
224 inconsistent with this principal's current delegation rights. Does
225 not perform permission checks, but takes no action and returns success
226 if this principal still retains DelegateRights. Should only ever be
227 called from inside the RT library.
229 If this principal is a group, recursively calls this method on each
230 cached user member of itself.
232 If called from inside a transaction, specify a true value for the
233 InsideTransaction parameter.
235 Returns a true value if the deletion succeeded; returns a false value
236 and logs an internal error if the deletion fails (should not happen).
240 # This is currently just a stub for the methods of the same name in
241 # RT::User and RT::Group.
243 sub _CleanupInvalidDelegations {
245 unless ( $self->Id ) {
246 $RT::Logger->warning("Principal not loaded.");
249 return ($self->Object->_CleanupInvalidDelegations(@_));
256 =head2 sub HasRight (Right => 'right' Object => undef)
259 Checks to see whether this principal has the right "Right" for the Object
260 specified. If the Object parameter is omitted, checks to see whether the
261 user has the right globally.
263 This still hard codes to check to see if a user has queue-level rights
264 if we ask about a specific ticket.
267 This takes the params:
269 Right => name of a right
273 Object => an RT style object (->id will get its id)
276 Returns 1 if a matching ACE was found.
278 Returns undef if no ACE was found.
288 EquivObjects => undef,
292 unless ( $args{'Right'} ) {
293 $RT::Logger->crit("HasRight called without a right");
297 my $canonic_name = RT::ACE->CanonicalizeRightName( $args{'Right'} );
298 unless ( $canonic_name ) {
299 $RT::Logger->error("Invalid right. Couldn't canonicalize right '$args{'Right'}'");
302 $args{'Right'} = $canonic_name;
304 $args{'EquivObjects'} = [ @{ $args{'EquivObjects'} } ]
305 if $args{'EquivObjects'};
307 if ( $self->Disabled ) {
308 $RT::Logger->debug( "Disabled User #"
310 . " failed access check for "
315 if ( defined( $args{'Object'} )
316 && UNIVERSAL::can( $args{'Object'}, 'id' )
317 && $args{'Object'}->id ) {
319 push @{ $args{'EquivObjects'} }, $args{'Object'};
322 $RT::Logger->crit("HasRight called with no valid object");
327 unshift @{ $args{'EquivObjects'} }, $args{'Object'}->ACLEquivalenceObjects;
329 unshift @{ $args{'EquivObjects'} }, $RT::System
330 unless $self->can('_IsOverrideGlobalACL')
331 && $self->_IsOverrideGlobalACL( $args{'Object'} );
333 # {{{ If we've cached a win or loss for this lookup say so
335 # Construct a hashkeys to cache decisions:
336 # 1) full_hashkey - key for any result and for full combination of uid, right and objects
337 # 2) short_hashkey - one key for each object to store positive results only, it applies
338 # only to direct group rights and partly to role rights
339 my $self_id = $self->id;
340 my $full_hashkey = join ";:;", $self_id, $args{'Right'};
341 foreach ( @{ $args{'EquivObjects'} } ) {
342 my $ref_id = _ReferenceId($_);
343 $full_hashkey .= ";:;$ref_id";
345 my $short_hashkey = join ";:;", $self_id, $args{'Right'}, $ref_id;
346 my $cached_answer = $_ACL_CACHE->fetch($short_hashkey);
347 return $cached_answer > 0 if defined $cached_answer;
351 my $cached_answer = $_ACL_CACHE->fetch($full_hashkey);
352 return $cached_answer > 0 if defined $cached_answer;
356 my ($hitcount, $via_obj) = $self->_HasRight( %args );
358 $_ACL_CACHE->set( $full_hashkey => $hitcount? 1: -1 );
359 $_ACL_CACHE->set( "$self_id;:;$args{'Right'};:;$via_obj" => 1 )
360 if $via_obj && $hitcount;
367 Low level HasRight implementation, use HasRight method instead.
375 my ($hit, @other) = $self->_HasGroupRight( @_ );
376 return ($hit, @other) if $hit;
379 my ($hit, @other) = $self->_HasRoleRight( @_ );
380 return ($hit, @other) if $hit;
385 # this method handles role rights partly in situations
386 # where user plays role X on an object and as well the right is
387 # assigned to this role X of the object, for example right CommentOnTicket
388 # is granted to Cc role of a queue and user is in cc list of the queue
397 my $right = $args{'Right'};
400 "SELECT ACL.id, ACL.ObjectType, ACL.ObjectId " .
401 "FROM ACL, Principals, CachedGroupMembers WHERE " .
403 # Only find superuser or rights with the name $right
404 "(ACL.RightName = 'SuperUser' OR ACL.RightName = '$right') "
406 # Never find disabled groups.
407 . "AND Principals.id = ACL.PrincipalId "
408 . "AND Principals.PrincipalType = 'Group' "
409 . "AND Principals.Disabled = 0 "
411 # See if the principal is a member of the group recursively or _is the rightholder_
412 # never find recursively disabled group members
413 # also, check to see if the right is being granted _directly_ to this principal,
414 # as is the case when we want to look up group rights
415 . "AND CachedGroupMembers.GroupId = ACL.PrincipalId "
416 . "AND CachedGroupMembers.GroupId = Principals.id "
417 . "AND CachedGroupMembers.MemberId = ". $self->Id ." "
418 . "AND CachedGroupMembers.Disabled = 0 ";
421 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
422 my $type = ref( $obj ) || $obj;
423 my $clause = "ACL.ObjectType = '$type'";
425 if ( ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id ) {
426 $clause .= " AND ACL.ObjectId = ". $obj->id;
429 push @clauses, "($clause)";
432 $query .= " AND (". join( ' OR ', @clauses ) .")";
435 $self->_Handle->ApplyLimits( \$query, 1 );
436 my ($hit, $obj, $id) = $self->_Handle->FetchResult( $query );
437 return (0) unless $hit;
439 $obj .= "-$id" if $id;
452 my @roles = $self->RolesWithRight( %args );
453 return 0 unless @roles;
455 my $right = $args{'Right'};
459 . "FROM Groups, Principals, CachedGroupMembers WHERE "
461 # Never find disabled things
462 . "Principals.Disabled = 0 "
463 . "AND CachedGroupMembers.Disabled = 0 "
465 # We always grant rights to Groups
466 . "AND Principals.id = Groups.id "
467 . "AND Principals.PrincipalType = 'Group' "
469 # See if the principal is a member of the group recursively or _is the rightholder_
470 # never find recursively disabled group members
471 # also, check to see if the right is being granted _directly_ to this principal,
472 # as is the case when we want to look up group rights
473 . "AND Principals.id = CachedGroupMembers.GroupId "
474 . "AND CachedGroupMembers.MemberId = ". $self->Id ." "
476 . "AND (". join(' OR ', map "Groups.Type = '$_'", @roles ) .")"
479 my (@object_clauses);
480 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
481 my $type = ref($obj)? ref($obj): $obj;
483 $id = $obj->id if ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id;
485 my $clause = "Groups.Domain = '$type-Role'";
486 # XXX: Groups.Instance is VARCHAR in DB, we should quote value
487 # if we want mysql 4.0 use indexes here. we MUST convert that
488 # field to integer and drop this quotes.
489 $clause .= " AND Groups.Instance = '$id'" if $id;
490 push @object_clauses, "($clause)";
492 $query .= " AND (". join( ' OR ', @object_clauses ) .")";
494 $self->_Handle->ApplyLimits( \$query, 1 );
495 my ($hit) = $self->_Handle->FetchResult( $query );
501 =head2 RolesWithRight
503 Returns list with names of roles that have right on
504 set of objects. Takes Right, EquiveObjects,
505 IncludeSystemRights and IncludeSuperusers arguments.
507 IncludeSystemRights is true by default, rights
508 granted on system level are not accouned when option
509 is set to false value.
511 IncludeSuperusers is true by default, SuperUser right
512 is not checked if it's set to false value.
520 IncludeSystemRights => 1,
521 IncludeSuperusers => 1,
525 my $right = $args{'Right'};
528 "SELECT DISTINCT PrincipalType FROM ACL"
529 # Only find superuser or rights with the name $right
530 ." WHERE ( RightName = '$right' "
531 # Check SuperUser if we were asked to
532 . ($args{'IncludeSuperusers'}? "OR RightName = 'SuperUser' " : '' )
535 ." AND PrincipalType != 'Group'"
538 # skip rights granted on system level if we were asked to
539 unless ( $args{'IncludeSystemRights'} ) {
540 $query .= " AND ObjectType != 'RT::System'";
543 my (@object_clauses);
544 foreach my $obj ( @{ $args{'EquivObjects'} } ) {
545 my $type = ref($obj)? ref($obj): $obj;
547 $id = $obj->id if ref($obj) && UNIVERSAL::can($obj, 'id') && $obj->id;
549 my $object_clause = "ObjectType = '$type'";
550 $object_clause .= " AND ObjectId = $id" if $id;
551 push @object_clauses, "($object_clause)";
553 # find ACLs that are related to our objects only
554 $query .= " AND (". join( ' OR ', @object_clauses ) .")"
557 my $dbh = $RT::Handle->dbh;
558 my $roles = $dbh->selectcol_arrayref($query);
560 $RT::Logger->warning( $dbh->errstr );
573 # {{{ InvalidateACLCache
575 =head2 InvalidateACLCache
577 Cleans out and reinitializes the user rights cache
581 sub InvalidateACLCache {
582 $_ACL_CACHE = Cache::Simple::TimedExpiry->new();
584 $lifetime = $RT::Config->Get('ACLCacheLifetime') if $RT::Config;
585 $_ACL_CACHE->expire_after( $lifetime || 60 );
593 # {{{ _GetPrincipalTypeForACL
595 =head2 _GetPrincipalTypeForACL
597 Gets the principal type. if it's a user, it's a user. if it's a role group and it has a Type,
598 return that. if it has no type, return group.
602 sub _GetPrincipalTypeForACL {
605 if ($self->PrincipalType eq 'Group' && $self->Object->Domain =~ /Role$/) {
606 $type = $self->Object->Type;
609 $type = $self->PrincipalType;
621 Returns a list uniquely representing an object or normal scalar.
623 For scalars, its string value is returned; for objects that has an
624 id() method, its class name and Id are returned as a string separated by a "-".
631 # just return the value for non-objects
632 return $scalar unless UNIVERSAL::can($scalar, 'id');
634 return ref($scalar) unless $scalar->id;
636 # an object -- return the class and id
637 return(ref($scalar)."-". $scalar->id);