RBAC.pm

filter: Statementstmt 94.2% 114 / 121 Branchbran 73.0% 38 / 52 Conditioncond 100% 2 / 2 MC/DCmcdc 100% 1 / 1 Subroutinesub 100% 16 / 16 Podpod 100% 2 / 2 totaltotal 89.1% 173 / 194 CC 32 SCAR 19.5
CC
32
Cov
88%
check_permission
12.1
can_access
11.0
_get_cache
5.3
CRAP 7.0
↑ Summary RBAC/Backend/DBIx.pm »
1 package Authorization::RBAC;
2 3 $Authorization::RBAC::VERSION = '0.12';
3 3 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 with 'MooseX::Object::Pluggable';
6  
7 3 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Config::ZOMG;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 3 subtype MyConf => as 'HashRef';
12 coerce 'MyConf'
13 1 ▶ => from 'Str' => via {
Subroutine __ANON__: called CC=2 SCAR=7.1
14 1 my $conf = shift;
15 1 ▶ my ($jfdi_h, $jfdi) = Config::ZOMG->open($conf)
Branch: 1 branch
BranchTrueFalseTotal
() = "Config::ZOMG"->open($conf) or croak("Error (conf: $conf) : $!\n") 1 0 1
16 or croak "Error (conf: $conf) : $!\n";
17 1 return $jfdi_h;
18 3 };
19  
20 has conf => ( is => 'rw',
21 isa => 'MyConf',
22 coerce => 1,
23 1 ▶ trigger => sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
24 1 my $self = shift;
25 1 my $args = shift;
26  
27 croak "Error: Can not find " . $self->ns . " in your conf !"
28 1 ▶ if ( ! $args->{$self->ns});
Branch: 1 branch
BranchTrueFalseTotal
unless $$args{$self->ns} 0 1 1
29  
30 1 $self->config($args->{$self->ns});
31  
32 1 ▶ $self->debug($self->config->{'debug'}) if ( defined $self->config->{'debug'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->config->{"debug"} 1 0 1
33  
34 1 ▶ $self->_load_backend if ! $self->can('backend');
Branch: 1 branch
BranchTrueFalseTotal
if not $self->can("backend") 1 0 1
35 }
36 3 );
37  
38 # optional (used by DBIX backend )
39 3 has 'schema' => (
40 is => 'rw',
41 predicate => 'has_schema',
42 );
43  
44 3 has 'debug' => (
45 is => 'rw',
46 );
47  
48 has _plugin_ns => (
49 is => 'rw',
50 required => 1,
51 isa => 'Str',
52 1 ▶ default => sub{ 'Backend' },
Subroutine __ANON__: called CC=1 SCAR=0.0
53 3 );
54  
55 # namespace
56 has 'ns' => (
57 is => 'rw',
58 1 ▶ default => sub { __PACKAGE__ },
Subroutine __ANON__: called CC=1 SCAR=0.0
59 3 );
60  
61 3 has config => (
62 isa => "HashRef",
63 is => "rw",
64 );
65  
66 3 has cache => (
67 is => "rw",
68 required => 0,
69 );
70  
71  
72 1 ▶sub _load_backend {
Subroutine _load_backend: called CC=1 SCAR=0.0
73 1 my $self = shift;
74 1 my $backend = $self->config->{'backend'}->{name};
75  
76 1 $self->_log("Loading $backend backend ...");
77 1 $self->load_plugin( $backend );
78 }
79  
80  
81 # can_access check if user or roles have permissions on all operations
82 # of a object or more.
83 28 ▶sub can_access {
Subroutine can_access: called CC=11 SCAR=24.0
Pod documented
84 28 my ( $self, $roles, $objects, $additional_operations ) = @_;
85  
86 28 my $key = $self->_get_key($roles, $objects, $additional_operations);
87 # Get cache ?
88 28 my $result = $self->_get_cache($key);
89  
90 28 ▶ return $result if ( defined $result );
Branch: 1 branch
BranchTrueFalseTotal
if defined $result 0 28 28
91  
92 # Check perm on all objects
93 28 foreach my $obj (@$objects) {
94  
95 # Not necessary to check if it's not an object
96 34 ▶ next if ! ref($obj);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $obj 6 28 34
97  
98 # copy obj to not disturb objets
99 28 my $obj2 = $obj;
100  
101 # build parent objects
102 28 my @allobjs;
103 28 ▶ while ( $obj2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj2) 70 28 98
104 70 push(@allobjs, $obj2);
105 70 my $typeobj = ref($obj2);
106 70 $typeobj =~ s/.*:://;
107 70 ▶ my $parent_field = $self->config->{typeobj}->{$typeobj}->{parent_field} || 'parent';
Condition100%2/2
$self->config->{'typeobj'}{$typeobj}{'parent_field'} || 'parent'
l!l
682
MC/DC100%1/1
$self->config->{'typeobj'}{$typeobj}{'parent_field'} || 'parent'
$self->config->{'typeobj'}{$typeobj}{'parent_field'}
Truth table100%2/2
A
A= $self->config->{'typeobj'}{$typeobj}{'parent_field'}
Aresult
11
00
108 70 ▶ if ( $obj2->can( $parent_field)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj2->can($parent_field)) { } 68 2 70
109 68 $obj2 = $obj2->$parent_field;
110 }
111 2 else { $obj2 = 0 }
112  
113 }
114  
115 # check permission on each object
116 28 my $ops;
117 28 foreach my $obj2 ( reverse @allobjs ) {
118  
119 64 my $typeobj2 = ref($obj2);
120 64 $typeobj2 =~ s/.*:://;
121 64 my $msg = "> Search if we can access to ${typeobj2}_" . $obj2->id;
122 64 ▶ $msg .= " " . $obj2->name if $obj2->can('name');
Branch: 1 branch
BranchTrueFalseTotal
if $obj2->can("name") 62 2 64
123 64 $self->_log( $msg );
124  
125 64 ▶ if ( $obj2 eq $obj ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj2 eq $obj) { } 24 40 64
126 24 $ops = $additional_operations;
127 } else {
128 40 $ops = [];
129 }
130 64 ▶ if ( ! $self->check_permission( $roles, $obj2, $ops )){
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->check_permission($roles, $obj2, $ops)) 12 52 64
131 12 $self->_log("return 0");
132 12 $self->_set_cache($key,0);
133 12 return 0;
134 }
135 }
136 }
137  
138 16 $self->_log("return 1");
139 16 $self->_set_cache($key, 1);
140 16 return 1;
141 }
142  
143  
144 # Is roles can an operation on object
145 64 ▶sub check_permission {
Subroutine check_permission: called CC=12 SCAR=24.9
Pod documented
146 64 my ( $self, $roles, $obj, $additional_operations ) = @_;
147  
148 64 my $typeobj = ref($obj);
149 64 $typeobj =~ s/.*:://;
150  
151 64 my @ops_to_access = $obj->ops_to_access;
152 64 ▶ if ( $additional_operations ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($additional_operations) 43 21 64
153 43 push(@ops_to_access, $self->get_operations($additional_operations));
154 }
155  
156 64 ▶ $self->_log(" [OK] Object is not protected") if ( ! $ops_to_access[0] );
Branch: 1 branch
BranchTrueFalseTotal
unless $ops_to_access[0] 17 47 64
157  
158 # Looking operations protecting the object
159 64 my %already_checked;
160 64 foreach my $op ( @ops_to_access ) {
161  
162 50 ▶ next if ! $op;
Branch: 1 branch
BranchTrueFalseTotal
unless $op 0 50 50
163  
164 50 ▶ next if $already_checked{$op->name};
Branch: 1 branch
BranchTrueFalseTotal
if $already_checked{$op->name} 0 50 50
165 50 $already_checked{$op->name} = 1;
166  
167 50 my $ret = 0;
168 50 ROLES: foreach my $r ( @$roles ) {
169  
170 51 ▶ next if ! $r;
Branch: 1 branch
BranchTrueFalseTotal
unless $r 0 51 51
171 51 $self->_log("- Search if role " . $r->name ." can '" . $op->name . "' '${typeobj}_" . $obj->id."'");
172  
173 # get permission from backend
174 51 my ($result, $inheritable) = $self->get_permission($r, $op, $obj);
175  
176 51 ▶ if ( ! defined $result ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $result) { } 4 47 51
elsif (not $result) { } 9 38 47
elsif ($result) { } 38 0 38
177 4 next;
178 }
179 elsif ( ! $result ) {
180 9 $self->_log( " [KO] ".$r->name." cannot '" . $op->name . "' '${typeobj}_" . $obj->id."'" );
181 9 $ret = 0;
182 }
183 elsif ( $result ) {
184 38 $self->_log( " [OK] ".$r->name." can '" . $op->name . "' '${typeobj}_" . $obj->id."'" );
185 38 $ret = 1;
186 38 last ROLES;
187 }
188 }
189 50 ▶ return 0 if ! $ret;
Branch: 1 branch
BranchTrueFalseTotal
unless $ret 12 38 50
190 }
191  
192 52 return 1;
193 }
194  
195  
196  
197 222 ▶sub _log{
Subroutine _log: called CC=2 SCAR=8.1
198 222 my ($self, $msg ) = @_;
199  
200 222 ▶ return if ! $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->debug 222 0 222
201  
202 0 say STDERR "[debug] $msg";
203 }
204  
205 28 ▶sub _get_cache {
Subroutine _get_cache: called CC=3 SCAR=16.7
206 28 my ( $self, $key ) = @_;
207 28 ▶ if ( defined $self->cache ){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->cache) 0 28 28
208 0 my $res = $self->cache->get($key);
209 0 ▶ my $ret = defined $res ? $res : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $res ? : 0 0 0
210 0 $self->_log("get cache $key : $ret");
211 0 return $res;
212 }
213 return
214 28 }
215  
216  
217  
218 28 ▶sub _get_key {
Subroutine _get_key: called CC=3 SCAR=11.0
219 28 my ( $self, $roles, $objects, $additional_operations ) = @_;
220  
221 # TODO : Add type of object in key <============
222 29 my $key .= join('|', map { $_->name} @$roles)
223 28 ▶ . '-' . join('|', map { ref($_) ? $_->id : $_ } @$objects);
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 28 9 37
224 28 ▶ $key .= '-' . join('|', @$additional_operations) if (defined $additional_operations);
Branch: 1 branch
BranchTrueFalseTotal
if defined $additional_operations 3 25 28
225  
226 28 return $key;
227 }
228  
229 28 ▶sub _set_cache {
Subroutine _set_cache: called CC=2 SCAR=9.2
230 28 my ( $self, $key, $value ) = @_;
231 28 ▶ if ( defined $self->cache ){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->cache) 0 28 28
232 0 $self->_log("set cache $key = $value");
233 0 $self->cache->set($key, $value);
234 }
235 }
236  
237 =encoding utf8
238  
239 =head1 NAME
240  
241 Authorization::RBAC - Role-Based Access Control system
242  
243  
244  
245 =head1 VERSION
246  
247 version 0.12
248  
249 =head1 SYNOPSIS
250  
251 use Authorization::RBAC;
252  
253 my $conf = 't/conf/permsfromdbix.yml';
254 my $rbac = Authorization::RBAC->new( conf => $conf ); # add schema => $schema if DBIx backend
255  
256 my $page = $rbac->schema->resultset('Page')->search( name => 'add' , parent => 7 );
257 my $roles = ... function that returns the roles ...
258  
259 if ( $rbac->can_access($roles, $page, [ 'create_Page' ]) ){
260 # Role 'member' can access to Page /page/wiki/add
261 }
262  
263 # add a cache
264 $rbac->cache($cache);
265  
266  
267 =head1 DESCRIPTION
268  
269 Role-based access control (RBAC) is an approach to restricting system access to authorized users.
270  
271 User -> Role(s)
272  
273 Role -> Permission -> Object (Typeobj, unique)
274 -> Operation
275  
276  
277 So you can apply a permission to an instance of a Object and not only on all the class of the Object.
278  
279 La suite en Français ...
280  
281 Pourquoi ce module: J'étais à la recherche d'un module pouvant assurer la protection des accès à des objets. J'ai bien trouvé des modules sur le CPAN qui semblait répondre au besoin mais il y avait toujours un détail, une approche qui ne me convenait pas. La plupart de ces modules répondent à la question 'Est-ce que ce rôle peut faire cette opération ?'. Par exemple 'Est-ce que le rôle 'anonyme' peut créer un commentaire ?' mais jamais à la question 'Est-ce que ce rôle peut faire cette opération sur cet objet ?', exemple : 'Est que le role anonyme peut créer un commentaire sur cette page ?'. De plus je souhaitais que ce système de permissions soit récursif si l'objet à protéger comportait un champ 'parent'.
282  
283  
284 Comment ça marche :
285  
286 Actuellement Authorization::RBAC comporte un seul backend : DBIx
287  
288 Définition des acteurs du système :
289  
290 - Un Type d'objet : Ce peut être une 'Page', un 'Commentaire', 'Une pièce jointe' ...
291  
292 - Opération : Il s'agit d'un action sur un Type d'objet'. ( 'Add_Page', 'Del_Comment')
293  
294 - Un Objet : c'est une instance du Type d'objet. 'Page login', 'Comment n°33', ...
295  
296 - Une Permission : c'est une opération sur un Objet. Elle peut être récursive.
297  
298 - Un Role : Il hérite de Permission(s)
299  
300 Pour accéder à un Objet, le(s) role(s) doit posséder une Permission répondant à une Opération par défaut. Pour cela l'Objet doit avoir une méthode 'ops_to_access' qui retourne le ou les Operations qui le protège (en fait une référence à un tableau d'Opération). Par exemple la méthode ops_to_access de l'Objet 'Page /' retourne ['view_Page'], ce qui signifie "Pour accéder à la Page / le role doit avoir la Permission view_Page sur Page /".
301  
302 La méthode 'can_access' permet d'interroger le système:
303  
304 my $access = $rbac->can_access($roles, $objet, $additional_operations );
305  
306  
307 Un Objet peut avoir une méthode 'parent'. Si c'est le cas alors 2 mécanismes s'ajoute au système de permission :
308  
309 - L'accès à un objet est obtenu si l'accès est permit à tous ses parents. Par exemple, pour accéder à la Page '/admin/user/add', le(s) role(s) devra successivement accéder à '/', 'admin', 'user' et enfin 'add'.
310  
311 - En second lieu une Permission peut être rechercher récursivement sur les parents de l'Objet.
312  
313 Par exemple si nous avons les relations suivantes :
314  
315 Page:
316 /:
317 ops_to_access: view_Page
318 admin:
319 ops_to_access: view_Page
320 add:
321 ops_to_access: create_Page
322  
323 Pour accéder à l'Objet 'Page /admin/user/add', le(s) role(s) devra posséder des Permissions répondant à 'view_Page sur Page /', 'view_Page sur Page admin' et 'create_Page sur Page add'.
324 Imaginons que le(s) role(s) ne peut accèder à l'Objet. Par exemple si le(s) role(s) ne possède pas la Permission 'create_Page sur Page add' alors la recherche de la Permission se fera aussi sur 'admin' puis sur '/'. Pour que cette règle s'applique il faut que la Permission ait une méthode 'inheritable' qui si elle retourne 1 rendra la Permission héritable par ses enfants. Si elle retourne 0 cela a l'effet inverse, ça signifie que le role n'a pas ou plus cette Permission.
325  
326 Imaginons maintenant que les roles aient les Permissions suivantes :
327  
328 Roles:
329 administrateur:
330 view_Page:
331 Page_/: 1
332 inheritable: 1
333 Page_admin: 1
334 inheritable: 1
335 create_Page:
336 Page_/: 1
337 inheritable: 1
338 anonymous:
339 view_Page:
340 Page_/; 1
341 inheritable: 1
342 Page_admin: 0
343 inheritable: 1
344  
345  
346 Ainsi lorsque l'on recherche si le role 'administrateur' peut accéder à / admin / user / add, on ne trouvera pas de Permission 'create_Page sur Page add' mais on la retrouvera sur le parent racine et cette Permission est héritable.
347  
348 Attention car nous avons donné la Permission 'view_Page sur Page / héritable' à 'anonymous' donc si rien n'est fait il a aussi accès à /admin. C'est pourquoi Nous lui avons aussi donné la Permission 'Ne peut view_Page sur Page_Admin héritable'. Ainsi l'accès à /admin est bloqué.
349  
350  
351  
352 =head1 CONFIGURATION
353  
354 See t/conf/permfromdb.yml
355  
356 And also L<Authorization::RBAC::Backend::DBIx>
357  
358 =head1 PROVIDED METHODS
359  
360 =head2 can_access($roles, $objects, $additional_operations )
361  
362 =head2 check_permission($roles, $objects, $additional_operations )
363  
364 =head1 AUTHOR
365  
366 Daniel Brosseau, C<< <dab at catapulse.org> >>
367  
368 =head1 BUGS
369  
370 Please report any bugs or feature requests to C<bug-authorization-rbac at rt.cpan.org>, or through
371 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Authorization-RBAC>. I will be notified, and then you'll
372 automatically be notified of progress on your bug as I make changes.
373  
374  
375  
376  
377 =head1 SUPPORT
378  
379 You can find documentation for this module with the perldoc command.
380  
381 perldoc Authorization::RBAC
382  
383  
384 You can also look for information at:
385  
386 =over 4
387  
388 =item * RT: CPAN's request tracker (report bugs here)
389  
390 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Authorization-RBAC>
391  
392 =item * AnnoCPAN: Annotated CPAN documentation
393  
394 L<http://annocpan.org/dist/Authorization-RBAC>
395  
396 =item * CPAN Ratings
397  
398 L<http://cpanratings.perl.org/d/Authorization-RBAC>
399  
400 =item * Search CPAN
401  
402 L<http://search.cpan.org/dist/Authorization-RBAC/>
403  
404 =back
405  
406  
407 =head1 ACKNOWLEDGEMENTS
408  
409  
410 =head1 LICENSE AND COPYRIGHT
411  
412 Copyright 2015 Daniel Brosseau.
413  
414 This program is free software; you can redistribute it and/or modify it
415 under the terms of either: the GNU General Public License as published
416 by the Free Software Foundation; or the Artistic License.
417  
418 See http://dev.perl.org/licenses/ for more information.
419  
420  
421 =cut
422  
423 3 1; # End of Authorization::RBAC
↑ Summary RBAC/Backend/DBIx.pm »