blib/lib/Lemonldap/NG/Common/Notifications/LDAP.pm untested

filter: Statementstmt 0.0% 0 / 235 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 378 CC 30 SCAR 44.8
CC
30
Cov
0%
_ldap
272.0
newNotif
30.0
get
12.0
CRAP 88.2
1 ## @file
2 # LDAP storage methods for notifications
3  
4 ## @class
5 # LDAP storage methods for notifications
6  
7 package Lemonldap::NG::Common::Notifications::LDAP;
8  
9 use strict;
10 use Mouse;
11 use Time::Local;
12 use MIME::Base64 qw/encode_base64url/;
13 use Net::LDAP;
14 use utf8;
15  
16 our $VERSION = '2.21.0';
17  
18 extends 'Lemonldap::NG::Common::Notifications';
19  
20 sub import {
21 shift;
22 return Lemonldap::NG::Common::Notifications->import(@_);
23 }
24  
25 has ldapServer => (
26 is => 'ro',
27 lazy => 1,
28 default => sub {
29 $_[0]->conf->{ldapServer};
30 }
31 );
32  
33 has ldapPort => (
34 is => 'ro',
35 lazy => 1,
36 default => sub {
37 $_[0]->conf->{ldapPort};
38 }
39 );
40  
41 has ldapCAFile => (
42 is => 'ro',
43 lazy => 1,
44 default => sub {
45 $_[0]->conf->{ldapCAFile};
46 }
47 );
48  
49 has ldapCAPath => (
50 is => 'ro',
51 lazy => 1,
52 default => sub {
53 $_[0]->conf->{ldapCAPath};
54 }
55 );
56  
57 has ldapVerify => (
58 is => 'ro',
59 lazy => 1,
60 default => sub {
61 $_[0]->conf->{ldapVerify};
62 }
63 );
64  
65 has ldapConfBase => (
66 is => 'ro',
67 trigger => sub {
68 if ( my $table = $_[0]->{table} ) {
69 $_[0]->{ldapConfBase} =~ s/^\w+=\w+(,.*)$/ou=$table$1/;
70 }
71 }
72 );
73  
74 has ldapBindDN => (
75 is => 'ro',
76 lazy => 1,
77 default => sub {
78 $_[0]->conf->{managerDn};
79 }
80 );
81  
82 has ldapBindPassword => (
83 is => 'ro',
84 lazy => 1,
85 default => sub {
86 $_[0]->conf->{managerPassword};
87 }
88 );
89  
90 # Returns notifications corresponding to the user $uid.
91 # If $ref is set, returns only notification corresponding to this reference.
92 sub get {
93 my ( $self, $uid, $ref ) = @_;
94 return () unless ($uid);
95  
96 my $filter =
97 '(&(objectClass=applicationProcess)(!(description={done}*))'
98 . "(description={uid}$uid)"
99 . ( $ref ? '(description={ref}' . $ref . ')' : '' ) . ')';
100 my @entries = _search( $self, $filter );
101  
102 my $result;
103 foreach my $entry (@entries) {
104 my @notifValues = $entry->get_value('description');
105 my $f = {};
106 foreach (@notifValues) {
107 my ( $k, $v ) = ( $_ =~ /\{(.*?)\}(.*)/smg );
108 $v = decodeLdapValue($v);
109 $f->{$k} = $v;
110 }
111 my $xml = $f->{xml};
112 utf8::encode($xml);
113 my $identifier =
114 &getIdentifier( $self, $f->{uid}, $f->{ref}, $f->{date} );
115 $result->{$identifier} = "$xml";
116 $self->logger->info("notification $identifier found");
117  
118 }
119 return $result;
120 }
121  
122 # Returns accepted notifications corresponding to the user $uid.
123 # If $ref is set, returns only notification corresponding to this reference.
124 sub getAccepted {
125 my ( $self, $uid, $ref ) = @_;
126 return () unless ($uid);
127  
128 my $filter =
129 '(&(objectClass=applicationProcess)(description={done}*)'
130 . "(description={uid}$uid)(description={ref}$ref))";
131 my @entries = _search( $self, $filter );
132  
133 my $result;
134 foreach my $entry (@entries) {
135 my @notifValues = $entry->get_value('description');
136 my $f = {};
137 foreach (@notifValues) {
138 my ( $k, $v ) = ( $_ =~ /\{(.*?)\}(.*)/smg );
139 $v = decodeLdapValue($v);
140 $f->{$k} = $v;
141 }
142 my $xml = $f->{xml};
143 utf8::encode($xml);
144 my $identifier =
145 &getIdentifier( $self, $f->{uid}, $f->{ref}, $f->{date} );
146 $result->{$identifier} = "$xml";
147 $self->logger->info("notification $identifier found");
148  
149 }
150 return $result;
151 }
152  
153 ## @method hashref getAll()
154 # Return all pending notifications.
155 # @return hashref where keys are internal reference and values are hashref with
156 # keys date, uid, ref and condition.
157 sub getAll {
158 my $self = shift;
159 my @entries = $self->_search(
160 '(&(objectClass=applicationProcess)(!(description={done}*)))');
161 my $result = {};
162 foreach my $entry (@entries) {
163 my @notifValues = $entry->get_value('description');
164 my $f = {};
165 foreach (@notifValues) {
166 my ( $k, $v ) = ( $_ =~ /\{(.*?)\}(.*)/smg );
167 $v = decodeLdapValue($v);
168 $f->{$k} = $v;
169 }
170 $result->{"$f->{date}#$f->{uid}#$f->{ref}"} = {
171 date => $f->{date},
172 uid => $f->{uid},
173 ref => $f->{ref},
174 condition => $f->{cond},
175 };
176 }
177 return $result;
178 }
179  
180 ## @method hashref getExisting()
181 # Return all notifications.
182 # @return hashref where keys are internal reference and values are hashref with
183 # keys date, uid, ref and condition.
184 sub getExisting {
185 my $self = shift;
186 my @entries = $self->_search('objectClass=applicationProcess');
187 my $result = {};
188 foreach my $entry (@entries) {
189 my @notifValues = $entry->get_value('description');
190 my $f = {};
191 foreach (@notifValues) {
192 my ( $k, $v ) = ( $_ =~ /\{(.*?)\}(.*)/smg );
193 $v = decodeLdapValue($v);
194 $f->{$k} = $v;
195 }
196 $result->{"$f->{date}#$f->{uid}#$f->{ref}"} = {
197 date => $f->{date},
198 uid => $f->{uid},
199 ref => $f->{ref},
200 condition => $f->{cond},
201 };
202 }
203 return $result;
204 }
205  
206 ## @method boolean delete(string myref)
207 # Mark a notification as done.
208 # @param $myref identifier returned by get() or getAll()
209 sub delete {
210 my ( $self, $myref ) = @_;
211 my ( $d, $u, $r );
212 unless ( ( $d, $u, $r ) = ( $myref =~ /^([^#]+)#(.+?)#(.+)$/ ) ) {
213 $self->logger->warn("Bad reference $myref");
214 return 0;
215 }
216 my @ts = localtime();
217 $ts[5] += 1900;
218 $ts[4]++;
219 return _modify(
220 $self,
221 '(&(objectClass=applicationProcess)'
222 . "(description={uid}$u)"
223 . "(description={ref}$r)"
224 . "(description={date}$d)"
225 . '(!(description={done}*)))',
226 "description",
227 "{done}$ts[5]-$ts[4]-$ts[3] $ts[2]:$ts[1]"
228 );
229 }
230  
231 ## @method boolean purge(string myref, boolean force)
232 # Purge notification (really delete record)
233 # @param $myref identifier returned by get or getAll
234 # @param $force force purge for not deleted session
235 # @return true if something was deleted
236 sub purge {
237 my ( $self, $myref, $force ) = @_;
238 my ( $d, $u, $r );
239 unless ( ( $d, $u, $r ) = ( $myref =~ /^([^#]+)#(.+?)#(.+)$/ ) ) {
240 $self->logger->warn("Bad reference $myref");
241 return 0;
242 }
243  
244 my $clause = ( $force ? '' : '(description={done}*)' );
245 return $self->_delete( '(&(objectClass=applicationProcess)'
246 . "(description={uid}$u)"
247 . "(description={ref}$r)"
248 . "(description={date}$d)"
249 . "$clause)" );
250 }
251  
252 # Insert a new notification
253 # @param date Date
254 # @param uid UID
255 # @param ref Reference of the notification
256 # @param condition Condition for the notification
257 # @param xml XML notification
258 # @return true if succeed
259 sub newNotif {
260 my ( $self, $date, $uid, $ref, $condition, $xml ) = @_;
261 my $fns = $self->conf->{fileNameSeparator};
262 $fns ||= '_';
263 my @t = split( /\D+/, $date );
264 $t[1]--;
265 eval {
266 timelocal( $t[5] || 0, $t[4] || 0, $t[3] || 0, $t[2], $t[1], $t[0] );
267 };
268 return ( 0, "Bad date" ) if ($@);
269 $date =~ s/-//g;
270 return ( 0, "Bad date" ) unless ( $date =~ /^\d{8}/ );
271 my $cn = "${date}${fns}${uid}${fns}" . encode_base64url( $ref, '' );
272 $cn .= "${fns}" . encode_base64url( $condition, '' ) if $condition;
273  
274 my $fields =
275 $condition =~ /.+/
276 ? {
277 "date" => "$date",
278 "uid" => "$uid",
279 "ref" => "$ref",
280 "xml" => "$xml",
281 "cond" => "$condition",
282 }
283 : {
284 "date" => "$date",
285 "uid" => "$uid",
286 "ref" => "$ref",
287 "xml" => "$xml",
288 };
289  
290 return _store( $self, $cn, $fields );
291 }
292  
293 ## @method hashref getDone()
294 # Returns a list of notifications that have been done
295 # @return hashref where keys are internal reference and values are hashref with
296 # keys notified, uid and ref.
297 sub getDone {
298 my ($self) = @_;
299 my @entries = _search( $self,
300 '(&(objectClass=applicationProcess)(description={done}*))' );
301  
302 my $result = {};
303 foreach my $entry (@entries) {
304 my @notifValues = $entry->get_value('description');
305 my $f = {};
306 foreach (@notifValues) {
307 my ( $k, $v ) = ( $_ =~ /\{(.*?)\}(.*)/smg );
308 $v = decodeLdapValue($v);
309 $f->{$k} = $v;
310 }
311 my @t = split( /\D+/, $f->{done} );
312 $t[1]--;
313 my $done =
314 eval { timelocal( $t[5], $t[4], $t[3], $t[2], $t[1], $t[0] ) };
315 if ($@) {
316 $self->logger->warn("Bad date: $f->{done}");
317 return {};
318 }
319 $result->{"$f->{date}#$f->{uid}#$f->{ref}"} = {
320 notified => $done,
321 uid => $f->{uid},
322 ref => $f->{ref},
323 condition => $f->{cond}
324 };
325 }
326  
327 # $ldap->unbind() && delete $self->{ldap};
328 return $result;
329 }
330  
331 ## @method object private _ldap()
332 # Return the ldap object (build it if needed).
333 # @param filter The LDAP filter to apply
334 # @return list of entries returned by the LDAP search (set of Net::LDAP::Entry)
335 sub _search {
336 my ( $self, $filter ) = @_;
337  
338 my $ldap = _ldap($self);
339  
340 my $search = $ldap->search(
341 base => $self->{ldapConfBase},
342 filter => "$filter",
343 scope => 'sub',
344 attrs => ['description'],
345 );
346  
347 if ( $search->code ) {
348 $self->logger->error( "search error: " . $search->error() );
349 return ();
350 }
351  
352 return $search->entries();
353 }
354  
355 ## @method object private _delete()
356 # Deletes the all entries found by the given LDAP filter
357 # @param filter The LDAP filter to apply
358 # @return 1 if operation success, else 0
359 sub _delete {
360 my ( $self, $filter ) = @_;
361  
362 my @entries = _search( $self, "$filter" );
363 my $mesg = {};
364 foreach my $entry (@entries) {
365 $mesg = $self->{ldap}->delete( $entry->dn() );
366 $mesg->code && return 0;
367 }
368  
369 # $ldap->unbind() && delete $self->{ldap};
370 return 1;
371 }
372  
373 ## @method object private _modify()
374 # add the given attribute value to all entries found by LDAP filter
375 # @param filter The LDAP filter to apply
376 # @param attr : name of the attribute to modify
377 # @param value : new value to add
378 # @return 1 if operation success, else 0
379 sub _modify {
380 my ( $self, $filter, $attr, $value ) = @_;
381  
382 my @entries = _search( $self, "$filter" );
383  
384 my $mesg = {};
385 foreach my $entry (@entries) {
386 $mesg =
387 $self->{ldap}
388 ->modify( $entry->dn(), add => { "$attr" => "$value", }, );
389 $mesg->code && return 0;
390 }
391  
392 # $ldap->unbind() && delete $self->{ldap};
393 return 1;
394 }
395  
396 ## @method object private _store()
397 # creates the notification defined by dn: cn=$cn,$ldapConfBase and $fields
398 # stored in the description attribute
399 # @param cn : cn value, used as a dn component
400 # @param fields : set of values to store in description attribute
401 # @return 1 if operation success, else 0
402 sub _store {
403 my ( $self, $cn, $fields ) = @_;
404 my $ldap = _ldap($self) or return 0;
405  
406 my $notifName = "$cn";
407 my $notifDN = "cn=$notifName," . $self->{ldapConfBase};
408  
409 # Store values as {key}value
410 my @notifValues;
411 foreach my $k ( keys %$fields ) {
412 my $v = encodeLdapValue( $fields->{$k} );
413 push @notifValues, "{$k}$v";
414 }
415  
416 my $add = $ldap->add(
417 $notifDN,
418 attrs => [
419 objectClass => [ 'top', 'applicationProcess' ],
420 cn => $notifName,
421 description => \@notifValues,
422 ]
423 );
424  
425 if ( $add->code ) {
426 $self->logger->error( $add->error );
427 return 0;
428 }
429  
430 #$ldap->unbind() && delete $self->{ldap};
431 return 1;
432 }
433  
434 ## @method object private encodeLdapValue()
435 # encode ldap value in utf8 (try to encode to latin1, and if it fails, encode to utf8)
436 # @param value value to encode
437 # @return value encoded in utf8
438 sub encodeLdapValue {
439 my $value = shift;
440  
441 eval {
442 my $safevalue = $value;
443 Encode::from_to( $safevalue, "utf8", "iso-8859-1", Encode::FB_CROAK );
444 };
445 if ($@) {
446 Encode::from_to( $value, "iso-8859-1", "utf8", Encode::FB_CROAK );
447 }
448  
449 return $value;
450  
451 }
452  
453 ## @method object private decodeLdapValue()
454 # decode ldap value from utf8 to latin1
455 # @param value value to decode
456 # @return value decoded in latin1
457 sub decodeLdapValue {
458 my $value = shift;
459  
460 Encode::from_to( $value, "utf8", "iso-8859-1", Encode::FB_CROAK );
461  
462 return $value;
463  
464 }
465  
466 ## @method object private _ldap()
467 # Return the ldap object (build it if needed).
468 # @return ldap handle object
469 sub _ldap {
470 my $self = shift;
471  
472 return $self->{ldap} if ( $self->{ldap} );
473  
474 # Parse servers configuration
475 my $useTls = 0;
476 my $tlsParam;
477 my @servers = ();
478 foreach my $server ( split /[\s,]+/, $self->ldapServer ) {
479 if ( $server =~ m{^ldap\+tls://([^/]+)/?\??(.*)$} ) {
480 $useTls = 1;
481 $server = $1;
482 $tlsParam = $2 || "";
483 }
484 else {
485 $useTls = 0;
486 }
487 push @servers, $server;
488 }
489  
490 # Connect
491 my $ldap = Net::LDAP->new(
492 \@servers,
493 onerror => undef,
494 keepalive => 1,
495 ( $self->ldapPort ? ( port => $self->ldapPort ) : () ),
496 ( $self->ldapVerify ? ( verify => $self->ldapVerify ) : () ),
497 ( $self->ldapCAFile ? ( cafile => $self->ldapCAFile ) : () ),
498 ( $self->ldapCAPath ? ( capath => $self->ldapCAPath ) : () ),
499 );
500  
501 unless ($ldap) {
502 use Data::Dumper;
503 die 'connexion failed: ' . $@;
504 }
505 elsif ( $Net::LDAP::VERSION < '0.64' ) {
506  
507 # CentOS7 has a bug in which IO::Socket::SSL will return a broken
508 # socket when certificate validation fails. Net::LDAP does not catch
509 # it, and the process ends up crashing.
510 # As a precaution, make sure the underlying socket is doing fine:
511 if ( $ldap->socket->isa('IO::Socket::SSL')
512 and $ldap->socket->errstr < 0 )
513 {
514 die "SSL connection error: " . $ldap->socket->errstr;
515 }
516 }
517  
518 # Start TLS if needed
519 if ($useTls) {
520 my %h = split( /[&=]/, $tlsParam );
521 $h{cafile} ||= $self->ldapCAFile if ( $self->ldapCAFile );
522 $h{capath} ||= $self->ldapCAPath if ( $self->ldapCAPath );
523 $h{verify} ||= $self->ldapVerify if ( $self->ldapVerify );
524 my $start_tls = $ldap->start_tls(%h);
525 if ( $start_tls->code ) {
526 die 'tls failed: ' . $start_tls->error;
527 }
528 }
529  
530 # Bind with credentials
531 my $bind =
532 $ldap->bind( $self->ldapBindDN, password => $self->ldapBindPassword );
533 if ( $bind->code ) {
534 die 'bind failed: ' . $bind->error;
535 }
536  
537 $self->{ldap} = $ldap;
538 return $ldap;
539 }
540  
541 ## @method string getIdentifier(string uid, string ref, string date)
542 # Get notification identifier
543 # @param $uid uid
544 # @param $ref ref
545 # @param $date date
546 # @return the notification identifier
547 sub getIdentifier {
548 my ( $self, $uid, $ref, $date ) = @_;
549 return $date . "#" . $uid . "#" . $ref;
550 }
551  
552 1;
553