Bug 15889: LDAP authentication: Only update mapped attributes
[koha.git] / t / db_dependent / Auth_with_ldap.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 4;
21 use Test::MockModule;
22 use Test::MockObject;
23 use t::lib::TestBuilder;
24 use Test::Warn;
25
26 use C4::Context;
27
28 my $dbh = C4::Context->dbh;
29 # Start transaction
30 $dbh->{ AutoCommit } = 0;
31 $dbh->{ RaiseError } = 1;
32
33 my $builder = t::lib::TestBuilder->new();
34
35 # Variables controlling LDAP server config
36 my $update         = 0;
37 my $replicate      = 0;
38 my $auth_by_bind   = 1;
39 my $anonymous_bind = 1;
40 # Variables controlling LDAP behaviour
41 my $desired_authentication_result = 'success';
42 my $desired_connection_result     = 'error';
43 my $desired_bind_result           = 'error';
44 my $desired_compare_result        = 'error';
45 my $desired_search_result         = 'error';
46 my $desired_count_result          = 1;
47 my $non_anonymous_bind_result     = 'error';
48 my $ret;
49
50 # Mock the context module
51 my $context     = new Test::MockModule( 'C4::Context' );
52 $context->mock( 'config', \&mockedC4Config );
53
54 # Mock the Net::LDAP module
55 my $ldap = new Test::MockModule( 'Net::LDAP' );
56
57 $ldap->mock( 'new',  sub {
58     if ( $desired_connection_result eq 'error' ) {
59         # We were asked to fail the LDAP conexion
60         return;
61     } else {
62         # Return a mocked Net::LDAP object (Test::MockObject)
63         return mock_net_ldap();
64     }
65 });
66
67 my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
68 my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode };
69 my $attrType = $builder->build({
70     source => 'BorrowerAttributeType',
71     value => {
72         category_code => $categorycode
73     }
74 });
75
76 my $borrower = $builder->build({
77     source => 'Borrower',
78     value => {
79         userid => 'hola',
80         branchcode   => $branchcode,
81         categorycode => $categorycode
82     }
83 });
84
85 $builder->build({
86     source => 'BorrowerAttribute',
87     value => {
88         borrowernumber => $borrower->{borrowernumber},
89         code => $attrType->{code},
90         attribute => 'FOO'
91     }
92 });
93
94 # C4::Auth_with_ldap needs several stuff set first ^^^
95 use_ok( 'C4::Auth_with_ldap' );
96 can_ok( 'C4::Auth_with_ldap', qw/
97         checkpw_ldap
98         search_method /);
99
100 subtest "checkpw_ldap tests" => sub {
101
102     plan tests => 4;
103
104     ## Connection fail tests
105     $desired_connection_result = 'error';
106     warning_is { $ret = C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ) }
107         "LDAP connexion failed",
108         "checkpw_ldap prints correct warning if LDAP conexion fails";
109     is( $ret, 0, "checkpw_ldap returns 0 if LDAP conexion fails");
110
111     ## Connection success tests
112     $desired_connection_result = 'success';
113
114     subtest "auth_by_bind = 1 tests" => sub {
115
116         plan tests => 8;
117
118         $auth_by_bind          = 1;
119
120         $desired_authentication_result = 'success';
121         $anonymous_bind        = 1;
122         $desired_bind_result   = 'error';
123         $desired_search_result = 'error';
124         reload_ldap_module();
125
126
127         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
128                                $dbh, 'hola', password => 'hey' ) }
129                     qr/Anonymous LDAP bind failed: LDAP error #1: error_name/,
130                     "checkpw_ldap prints correct warning if LDAP anonymous bind fails";
131         is( $ret, 0, "checkpw_ldap returns 0 if LDAP anonymous bind fails");
132
133         $desired_authentication_result = 'success';
134         $anonymous_bind        = 1;
135         $desired_bind_result   = 'success';
136         $desired_search_result = 'success';
137         $desired_count_result  = 1;
138         $non_anonymous_bind_result = 'success';
139         $update = 1;
140         reload_ldap_module();
141
142         my $auth = new Test::MockModule('C4::Auth_with_ldap');
143         $auth->mock( 'update_local', sub {
144                 return $borrower->{cardnumber};
145         });
146
147         C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey');
148         ok(@{ C4::Members::Attributes::GetBorrowerAttributes($borrower->{borrowernumber}) }, 'Extended attributes are not deleted');
149         $auth->unmock('update_local');
150
151         $update = 0;
152         $desired_count_result = 0; # user auth problem
153         C4::Members::DelMember($borrower->{borrowernumber});
154         reload_ldap_module();
155         is ( C4::Auth_with_ldap::checkpw_ldap( $dbh, 'hola', password => 'hey' ),
156             0, "checkpw_ldap returns 0 if user lookup returns 0");
157
158         $non_anonymous_bind_result = 'error';
159         reload_ldap_module();
160
161         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
162                                $dbh, 'hola', password => 'hey' ) }
163                     qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
164                     "checkpw_ldap prints correct warning if LDAP bind fails";
165         is ( $ret, -1, "checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)");
166
167         # regression tests for bug 12831
168         $desired_authentication_result = 'error';
169         $anonymous_bind        = 0;
170         $desired_bind_result   = 'error';
171         $desired_search_result = 'success';
172         $desired_count_result  = 0; # user auth problem
173         $non_anonymous_bind_result = 'error';
174         reload_ldap_module();
175
176         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
177                                $dbh, 'hola', password => 'hey' ) }
178                     qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/,
179                     "checkpw_ldap prints correct warning if LDAP bind fails";
180         is ( $ret, 0, "checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)");
181
182     };
183
184     subtest "auth_by_bind = 0 tests" => sub {
185
186         plan tests => 8;
187
188         $auth_by_bind = 0;
189
190         # Anonymous bind
191         $anonymous_bind            = 1;
192         $desired_bind_result       = 'error';
193         $non_anonymous_bind_result = 'error';
194         reload_ldap_module();
195
196         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
197                                $dbh, 'hola', password => 'hey' ) }
198                     qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
199                     "checkpw_ldap prints correct warning if LDAP bind fails";
200         is ( $ret, 0, "checkpw_ldap returns 0 if bind fails");
201
202         $anonymous_bind            = 1;
203         $desired_bind_result       = 'success';
204         $non_anonymous_bind_result = 'success';
205         $desired_compare_result    = 'error';
206         reload_ldap_module();
207
208         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
209                                $dbh, 'hola', password => 'hey' ) }
210                     qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
211                     "checkpw_ldap prints correct warning if LDAP bind fails";
212         is ( $ret, -1, "checkpw_ldap returns -1 if bind fails (Bug 8148)");
213
214         # Non-anonymous bind
215         $anonymous_bind            = 0;
216         $desired_bind_result       = 'success';
217         $non_anonymous_bind_result = 'error';
218         $desired_compare_result    = 'dont care';
219         reload_ldap_module();
220
221         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
222                                $dbh, 'hola', password => 'hey' ) }
223                     qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/,
224                     "checkpw_ldap prints correct warning if LDAP bind fails";
225         is ( $ret, 0, "checkpw_ldap returns 0 if bind fails");
226
227         $anonymous_bind            = 0;
228         $desired_bind_result       = 'success';
229         $non_anonymous_bind_result = 'success';
230         $desired_compare_result    = 'error';
231         reload_ldap_module();
232
233         warning_like { $ret = C4::Auth_with_ldap::checkpw_ldap(
234                                $dbh, 'hola', password => 'hey' ) }
235                     qr/LDAP Auth rejected : invalid password for user 'hola'. LDAP error #1: error_name/,
236                     "checkpw_ldap prints correct warning if LDAP bind fails";
237         is ( $ret, -1, "checkpw_ldap returns -1 if bind fails (Bug 8148)");
238
239     };
240 };
241
242 subtest "search_method tests" => sub {
243
244     plan tests => 5;
245
246     my $ldap = mock_net_ldap();
247
248     # Null params tests
249     is( C4::Auth_with_ldap::search_method( $ldap, undef), undef,
250         "search_method returns undef on undefined userid");
251     is( C4::Auth_with_ldap::search_method( undef, "undef"), undef,
252         "search_method returns undef on undefined ldap object");
253
254     # search ->code and !->code
255     $desired_search_result = 'error';
256     reload_ldap_module();
257     eval { $ret = C4::Auth_with_ldap::search_method( $ldap, "undef"); };
258     like( $@, qr/LDAP search failed to return object : 1/,
259         "search_method prints correct warning when db->search returns error code");
260
261     $desired_search_result = 'success';
262     $desired_count_result  = 2;
263     reload_ldap_module();
264     warning_like { $ret = C4::Auth_with_ldap::search_method( $ldap, '123') }
265                    qr/^LDAP Auth rejected \: \(uid\=123\) gets 2 hits/,
266                    "search_method prints correct warning when hits count is not 1";
267     is( $ret, 0, "search_method returns 0 when hits count is not 1" );
268
269 };
270
271 # Function that mocks the call to C4::Context->config(param)
272 sub mockedC4Config {
273
274     my $param =  shift;
275
276     my %ldap_mapping = (
277         firstname    => { is => 'givenname' },
278         surname      => { is => 'sn' },
279         address      => { is => 'postaladdress' },
280         city         => { is => 'l' },
281         zipcode      => { is => 'postalcode' },
282         branchcode   => { is => 'branch' },
283         userid       => { is => 'uid' },
284         password     => { is => 'userpassword' },
285         email        => { is => 'mail' },
286         categorycode => { is => 'employeetype' },
287         phone        => { is => 'telephonenumber' }
288     );
289
290     my %ldap_config  = (
291         anonymous_bind => $anonymous_bind,
292         auth_by_bind   => $auth_by_bind,
293         base           => 'dc=metavore,dc=com',
294         hostname       => 'localhost',
295         mapping        => \%ldap_mapping,
296         pass           => 'metavore',
297         principal_name => '%s@my_domain.com',
298         replicate      => $replicate,
299         update         => $update,
300         user           => 'cn=Manager,dc=metavore,dc=com'
301     );
302
303     return \%ldap_config;
304 };
305
306 # Function that mocks the call to Net::LDAP
307 sub mock_net_ldap {
308
309     my $mocked_ldap = Test::MockObject->new();
310
311     $mocked_ldap->mock( 'bind', sub {
312
313         my @args = @_;
314         my $mocked_message;
315
316         if ( $#args > 1 ) {
317             # Args passed => non-anonymous bind
318             if ( $non_anonymous_bind_result eq 'error' ) {
319                 return mock_net_ldap_message(1,1,'error_name','error_text');
320             } else {
321                 return mock_net_ldap_message(0,0,'','');
322             }
323         } else {
324             $mocked_message = mock_net_ldap_message(
325                 ($desired_bind_result eq 'error' ) ? 1 : 0, # code
326                 ($desired_bind_result eq 'error' ) ? 1 : 0, # error
327                 ($desired_bind_result eq 'error' ) ? 'error_name' : 0, # error_name
328                 ($desired_bind_result eq 'error' ) ? 'error_text' : 0  # error_text
329             );
330         }
331
332         return $mocked_message;
333     });
334
335     $mocked_ldap->mock( 'compare', sub {
336
337         my $mocked_message;
338
339         if ( $desired_compare_result eq 'error' ) {
340             $mocked_message = mock_net_ldap_message(1,1,'error_name','error_text');
341         } else {
342             # we expect return code 6 for success
343             $mocked_message = mock_net_ldap_message(6,0,'','');
344         }
345
346         return $mocked_message;
347     });
348
349     $mocked_ldap->mock( 'search', sub {
350
351         return mock_net_ldap_search(
352             ( $desired_count_result )             # count
353                 ? $desired_count_result
354                 : 1, # default to 1
355             ( $desired_search_result eq 'error' ) # code
356                 ? 1
357                 : 0, # 0 == success
358             ( $desired_search_result eq 'error' ) # error
359                 ? 1
360                 : 0,
361             ( $desired_search_result eq 'error' ) # error_text
362                 ? 'error_text'
363                 : undef,
364             ( $desired_search_result eq 'error' ) # error_name
365                 ? 'error_name'
366                 : undef,
367             mock_net_ldap_entry( 'sampledn', 1 )  # shift_entry
368         );
369
370     });
371
372     return $mocked_ldap;
373 }
374
375 sub mock_net_ldap_search {
376     my ( $count, $code, $error, $error_text,
377          $error_name, $shift_entry ) = @_;
378
379     my $mocked_search = Test::MockObject->new();
380     $mocked_search->mock( 'count',       sub { return $count; } );
381     $mocked_search->mock( 'code',        sub { return $code; } );
382     $mocked_search->mock( 'error',       sub { return $error; } );
383     $mocked_search->mock( 'error_name',  sub { return $error_name; } );
384     $mocked_search->mock( 'error_text',  sub { return $error_text; } );
385     $mocked_search->mock( 'shift_entry', sub { return $shift_entry; } );
386
387     return $mocked_search;
388 }
389
390 sub mock_net_ldap_message {
391     my ( $code, $error, $error_name, $error_text ) = @_;
392
393     my $mocked_message = Test::MockObject->new();
394     $mocked_message->mock( 'code',       sub { $code } );
395     $mocked_message->mock( 'error',      sub { $error } );
396     $mocked_message->mock( 'error_name', sub { $error_name } );
397     $mocked_message->mock( 'error_text', sub { $error_text } );
398
399     return $mocked_message;
400 }
401
402 sub mock_net_ldap_entry {
403     my ( $dn, $exists ) = @_;
404
405     my $mocked_entry = Test::MockObject->new();
406     $mocked_entry->mock( 'dn',     sub { return $dn; } );
407     $mocked_entry->mock( 'exists', sub { return $exists } );
408
409     return $mocked_entry;
410 }
411
412 # TODO: Once we remove the global variables in C4::Auth_with_ldap
413 # we shouldn't need this...
414 # ... Horrible hack
415 sub reload_ldap_module {
416     delete $INC{'C4/Auth_with_ldap.pm'};
417     require C4::Auth_with_ldap;
418     C4::Auth_with_ldap->import;
419 }
420
421 $dbh->rollback;
422
423 1;