e0d68d3462cff9c565d748aefe49002e2fec32d5
[moodle.git] / auth / db / tests / db_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External database auth sync tests, this also tests adodb drivers
19  * that are matching our four supported Moodle database drivers.
20  *
21  * @package    auth_db
22  * @category   phpunit
23  * @copyright  2012 Petr Skoda {@link http://skodak.org}
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
30 class auth_db_testcase extends advanced_testcase {
31     /** @var string Original error log */
32     protected $oldlog;
34     protected function init_auth_database() {
35         global $DB, $CFG;
36         require_once("$CFG->dirroot/auth/db/auth.php");
38         // Discard error logs from AdoDB.
39         $this->oldlog = ini_get('error_log');
40         ini_set('error_log', "$CFG->dataroot/testlog.log");
42         $dbman = $DB->get_manager();
44         set_config('extencoding', 'utf-8', 'auth/db');
46         set_config('host', $CFG->dbhost, 'auth/db');
47         set_config('user', $CFG->dbuser, 'auth/db');
48         set_config('pass', $CFG->dbpass, 'auth/db');
49         set_config('name', $CFG->dbname, 'auth/db');
51         if (!empty($CFG->dboptions['dbport'])) {
52             set_config('host', $CFG->dbhost.':'.$CFG->dboptions['dbport'], 'auth/db');
53         }
55         switch ($DB->get_dbfamily()) {
57             case 'mysql':
58                 set_config('type', 'mysqli', 'auth/db');
59                 set_config('setupsql', "SET NAMES 'UTF-8'", 'auth/db');
60                 set_config('sybasequoting', '0', 'auth/db');
61                 if (!empty($CFG->dboptions['dbsocket'])) {
62                     $dbsocket = $CFG->dboptions['dbsocket'];
63                     if ((strpos($dbsocket, '/') === false and strpos($dbsocket, '\\') === false)) {
64                         $dbsocket = ini_get('mysqli.default_socket');
65                     }
66                     set_config('type', 'mysqli://'.rawurlencode($CFG->dbuser).':'.rawurlencode($CFG->dbpass).'@'.rawurlencode($CFG->dbhost).'/'.rawurlencode($CFG->dbname).'?socket='.rawurlencode($dbsocket), 'auth/db');
67                 }
68                 break;
70             case 'oracle':
71                 set_config('type', 'oci8po', 'auth/db');
72                 set_config('sybasequoting', '1', 'auth/db');
73                 break;
75             case 'postgres':
76                 set_config('type', 'postgres7', 'auth/db');
77                 $setupsql = "SET NAMES 'UTF-8'";
78                 if (!empty($CFG->dboptions['dbschema'])) {
79                     $setupsql .= "; SET search_path = '".$CFG->dboptions['dbschema']."'";
80                 }
81                 set_config('setupsql', $setupsql, 'auth/db');
82                 set_config('sybasequoting', '0', 'auth/db');
83                 if (!empty($CFG->dboptions['dbsocket']) and ($CFG->dbhost === 'localhost' or $CFG->dbhost === '127.0.0.1')) {
84                     if (strpos($CFG->dboptions['dbsocket'], '/') !== false) {
85                         $socket = $CFG->dboptions['dbsocket'];
86                         if (!empty($CFG->dboptions['dbport'])) {
87                             $socket .= ':' . $CFG->dboptions['dbport'];
88                         }
89                         set_config('host', $socket, 'auth/db');
90                     } else {
91                         set_config('host', '', 'auth/db');
92                     }
93                 }
94                 break;
96             case 'mssql':
97                 if (get_class($DB) == 'mssql_native_moodle_database') {
98                     set_config('type', 'mssql_n', 'auth/db');
99                 } else {
100                     set_config('type', 'mssqlnative', 'auth/db');
101                 }
102                 set_config('sybasequoting', '1', 'auth/db');
103                 break;
105             default:
106                 throw new exception('Unknown database family ' . $DB->get_dbfamily());
107         }
109         $table = new xmldb_table('auth_db_users');
110         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
111         $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null);
112         $table->add_field('pass', XMLDB_TYPE_CHAR, '255', null, null, null);
113         $table->add_field('email', XMLDB_TYPE_CHAR, '255', null, null, null);
114         $table->add_field('firstname', XMLDB_TYPE_CHAR, '255', null, null, null);
115         $table->add_field('lastname', XMLDB_TYPE_CHAR, '255', null, null, null);
116         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
117         if ($dbman->table_exists($table)) {
118             $dbman->drop_table($table);
119         }
120         $dbman->create_table($table);
121         set_config('table', $CFG->prefix.'auth_db_users', 'auth/db');
122         set_config('fielduser', 'name', 'auth/db');
123         set_config('fieldpass', 'pass', 'auth/db');
125         // Setu up field mappings.
127         set_config('field_map_email', 'email', 'auth/db');
128         set_config('field_updatelocal_email', 'oncreate', 'auth/db');
129         set_config('field_updateremote_email', '0', 'auth/db');
130         set_config('field_lock_email', 'unlocked', 'auth/db');
132         // Init the rest of settings.
133         set_config('passtype', 'plaintext', 'auth/db');
134         set_config('changepasswordurl', '', 'auth/db');
135         set_config('debugauthdb', 0, 'auth/db');
136         set_config('removeuser', AUTH_REMOVEUSER_KEEP, 'auth/db');
137     }
139     protected function cleanup_auth_database() {
140         global $DB;
142         $dbman = $DB->get_manager();
143         $table = new xmldb_table('auth_db_users');
144         $dbman->drop_table($table);
146         ini_set('error_log', $this->oldlog);
147     }
149     public function test_plugin() {
150         global $DB, $CFG;
152         $this->resetAfterTest(false);
154         // NOTE: It is strongly discouraged to create new tables in advanced_testcase classes,
155         //       but there is no other simple way to test ext database enrol sync, so let's
156         //       disable transactions are try to cleanup after the tests.
158         $this->preventResetByRollback();
160         $this->init_auth_database();
162         /** @var auth_plugin_db $auth */
163         $auth = get_auth_plugin('db');
165         $authdb = $auth->db_init();
168         // Test adodb may access the table.
170         $user1 = (object)array('name'=>'u1', 'pass'=>'heslo', 'email'=>'u1@example.com');
171         $user1->id = $DB->insert_record('auth_db_users', $user1);
174         $sql = "SELECT * FROM {$auth->config->table}";
175         $rs = $authdb->Execute($sql);
176         $this->assertInstanceOf('ADORecordSet', $rs);
177         $this->assertFalse($rs->EOF);
178         $fields = $rs->FetchRow();
179         $this->assertTrue(is_array($fields));
180         $this->assertTrue($rs->EOF);
181         $rs->Close();
183         $authdb->Close();
186         // Test bulk user account creation.
188         $user2 = (object)array('name'=>'u2', 'pass'=>'heslo', 'email'=>'u2@example.com');
189         $user2->id = $DB->insert_record('auth_db_users', $user2);
191         $user3 = (object)array('name'=>'admin', 'pass'=>'heslo', 'email'=>'admin@example.com'); // Should be skipped.
192         $user3->id = $DB->insert_record('auth_db_users', $user3);
194         $this->assertCount(2, $DB->get_records('user'));
196         $trace = new null_progress_trace();
197         $auth->sync_users($trace, false);
199         $this->assertEquals(4, $DB->count_records('user'));
200         $u1 = $DB->get_record('user', array('username'=>$user1->name, 'auth'=>'db'));
201         $this->assertSame($user1->email, $u1->email);
202         $u2 = $DB->get_record('user', array('username'=>$user2->name, 'auth'=>'db'));
203         $this->assertSame($user2->email, $u2->email);
204         $admin = $DB->get_record('user', array('username'=>'admin', 'auth'=>'manual'));
205         $this->assertNotEmpty($admin);
208         // Test sync updates.
210         $user2b = clone($user2);
211         $user2b->email = 'u2b@example.com';
212         $DB->update_record('auth_db_users', $user2b);
214         $auth->sync_users($trace, false);
215         $this->assertEquals(4, $DB->count_records('user'));
216         $u2 = $DB->get_record('user', array('username'=>$user2->name));
217         $this->assertSame($user2->email, $u2->email);
219         $auth->sync_users($trace, true);
220         $this->assertEquals(4, $DB->count_records('user'));
221         $u2 = $DB->get_record('user', array('username'=>$user2->name));
222         $this->assertSame($user2->email, $u2->email);
224         set_config('field_updatelocal_email', 'onlogin', 'auth/db');
225         $auth->config->field_updatelocal_email = 'onlogin';
227         $auth->sync_users($trace, false);
228         $this->assertEquals(4, $DB->count_records('user'));
229         $u2 = $DB->get_record('user', array('username'=>$user2->name));
230         $this->assertSame($user2->email, $u2->email);
232         $auth->sync_users($trace, true);
233         $this->assertEquals(4, $DB->count_records('user'));
234         $u2 = $DB->get_record('user', array('username'=>$user2->name));
235         $this->assertSame($user2b->email, $u2->email);
238         // Test sync deletes and suspends.
240         $DB->delete_records('auth_db_users', array('id'=>$user2->id));
241         $this->assertCount(2, $DB->get_records('auth_db_users'));
242         unset($user2);
243         unset($user2b);
245         $auth->sync_users($trace, false);
246         $this->assertEquals(4, $DB->count_records('user'));
247         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
248         $this->assertEquals(0, $DB->count_records('user', array('suspended'=>1)));
250         set_config('removeuser', AUTH_REMOVEUSER_SUSPEND, 'auth/db');
251         $auth->config->removeuser = AUTH_REMOVEUSER_SUSPEND;
253         $auth->sync_users($trace, false);
254         $this->assertEquals(4, $DB->count_records('user'));
255         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
256         $this->assertEquals(1, $DB->count_records('user', array('suspended'=>1)));
258         $user2 = (object)array('name'=>'u2', 'pass'=>'heslo', 'email'=>'u2@example.com');
259         $user2->id = $DB->insert_record('auth_db_users', $user2);
261         $auth->sync_users($trace, false);
262         $this->assertEquals(4, $DB->count_records('user'));
263         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
264         $this->assertEquals(0, $DB->count_records('user', array('suspended'=>1)));
266         $DB->delete_records('auth_db_users', array('id'=>$user2->id));
268         set_config('removeuser', AUTH_REMOVEUSER_FULLDELETE, 'auth/db');
269         $auth->config->removeuser = AUTH_REMOVEUSER_FULLDELETE;
271         $auth->sync_users($trace, false);
272         $this->assertEquals(4, $DB->count_records('user'));
273         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
274         $this->assertEquals(0, $DB->count_records('user', array('suspended'=>1)));
276         $user2 = (object)array('name'=>'u2', 'pass'=>'heslo', 'email'=>'u2@example.com');
277         $user2->id = $DB->insert_record('auth_db_users', $user2);
279         $auth->sync_users($trace, false);
280         $this->assertEquals(5, $DB->count_records('user'));
281         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
282         $this->assertEquals(0, $DB->count_records('user', array('suspended'=>1)));
285         // Test user_login().
287         $user3 = (object)array('name'=>'u3', 'pass'=>'heslo', 'email'=>'u3@example.com');
288         $user3->id = $DB->insert_record('auth_db_users', $user3);
290         $this->assertFalse($auth->user_login('u4', 'heslo'));
291         $this->assertTrue($auth->user_login('u1', 'heslo'));
293         $this->assertFalse($DB->record_exists('user', array('username'=>'u3', 'auth'=>'db')));
294         $this->assertTrue($auth->user_login('u3', 'heslo'));
295         $this->assertFalse($DB->record_exists('user', array('username'=>'u3', 'auth'=>'db')));
297         set_config('passtype', 'md5', 'auth/db');
298         $auth->config->passtype = 'md5';
299         $user3->pass = md5('heslo');
300         $DB->update_record('auth_db_users', $user3);
301         $this->assertTrue($auth->user_login('u3', 'heslo'));
303         set_config('passtype', 'sh1', 'auth/db');
304         $auth->config->passtype = 'sha1';
305         $user3->pass = sha1('heslo');
306         $DB->update_record('auth_db_users', $user3);
307         $this->assertTrue($auth->user_login('u3', 'heslo'));
309         require_once($CFG->libdir.'/password_compat/lib/password.php');
310         set_config('passtype', 'saltedcrypt', 'auth/db');
311         $auth->config->passtype = 'saltedcrypt';
312         $user3->pass = password_hash('heslo', PASSWORD_BCRYPT);
313         $DB->update_record('auth_db_users', $user3);
314         $this->assertTrue($auth->user_login('u3', 'heslo'));
316         set_config('passtype', 'internal', 'auth/db');
317         $auth->config->passtype = 'internal';
318         create_user_record('u3', 'heslo', 'db');
319         $this->assertTrue($auth->user_login('u3', 'heslo'));
322         $DB->delete_records('auth_db_users', array('id'=>$user3->id));
324         set_config('removeuser', AUTH_REMOVEUSER_KEEP, 'auth/db');
325         $auth->config->removeuser = AUTH_REMOVEUSER_KEEP;
326         $this->assertTrue($auth->user_login('u3', 'heslo'));
328         set_config('removeuser', AUTH_REMOVEUSER_SUSPEND, 'auth/db');
329         $auth->config->removeuser = AUTH_REMOVEUSER_SUSPEND;
330         $this->assertFalse($auth->user_login('u3', 'heslo'));
332         set_config('removeuser', AUTH_REMOVEUSER_FULLDELETE, 'auth/db');
333         $auth->config->removeuser = AUTH_REMOVEUSER_FULLDELETE;
334         $this->assertFalse($auth->user_login('u3', 'heslo'));
336         set_config('passtype', 'sh1', 'auth/db');
337         $auth->config->passtype = 'sha1';
338         $this->assertFalse($auth->user_login('u3', 'heslo'));
341         // Test login create and update.
343         $user4 = (object)array('name'=>'u4', 'pass'=>'heslo', 'email'=>'u4@example.com');
344         $user4->id = $DB->insert_record('auth_db_users', $user4);
346         set_config('passtype', 'plaintext', 'auth/db');
347         $auth->config->passtype = 'plaintext';
349         $iuser4 = create_user_record('u4', 'heslo', 'db');
350         $this->assertNotEmpty($iuser4);
351         $this->assertSame($user4->name, $iuser4->username);
352         $this->assertSame($user4->email, $iuser4->email);
353         $this->assertSame('db', $iuser4->auth);
354         $this->assertSame($CFG->mnet_localhost_id, $iuser4->mnethostid);
356         $user4b = clone($user4);
357         $user4b->email = 'u4b@example.com';
358         $DB->update_record('auth_db_users', $user4b);
360         set_config('field_updatelocal_email', 'oncreate', 'auth/db');
361         $auth->config->field_updatelocal_email = 'oncreate';
363         update_user_record('u4');
364         $iuser4 = $DB->get_record('user', array('id'=>$iuser4->id));
365         $this->assertSame($user4->email, $iuser4->email);
367         set_config('field_updatelocal_email', 'onlogin', 'auth/db');
368         $auth->config->field_updatelocal_email = 'onlogin';
370         update_user_record('u4');
371         $iuser4 = $DB->get_record('user', array('id'=>$iuser4->id));
372         $this->assertSame($user4b->email, $iuser4->email);
375         // Test user_exists()
377         $this->assertTrue($auth->user_exists('u1'));
378         $this->assertTrue($auth->user_exists('admin'));
379         $this->assertFalse($auth->user_exists('u3'));
380         $this->assertTrue($auth->user_exists('u4'));
382         $this->cleanup_auth_database();
383     }
385     /**
386      * Testing the function _colonscope() from ADOdb.
387      */
388     public function test_adodb_colonscope() {
389         global $CFG;
390         require_once($CFG->libdir.'/adodb/adodb.inc.php');
391         require_once($CFG->libdir.'/adodb/drivers/adodb-odbc.inc.php');
392         require_once($CFG->libdir.'/adodb/drivers/adodb-db2ora.inc.php');
394         $this->resetAfterTest(false);
396         $sql = "select * from table WHERE column=:1 AND anothercolumn > :0";
397         $arr = array('b', 1);
398         list($sqlout, $arrout) = _colonscope($sql,$arr);
399         $this->assertEquals("select * from table WHERE column=? AND anothercolumn > ?", $sqlout);
400         $this->assertEquals(array(1, 'b'), $arrout);
401     }
403     /**
404      * Testing the clean_data() method.
405      */
406     public function test_clean_data() {
407         global $DB;
409         $this->resetAfterTest(false);
410         $this->preventResetByRollback();
411         $this->init_auth_database();
412         $auth = get_auth_plugin('db');
413         $auth->db_init();
415         // Create users on external table.
416         $extdbuser1 = (object)array('name'=>'u1', 'pass'=>'heslo', 'email'=>'u1@example.com');
417         $extdbuser1->id = $DB->insert_record('auth_db_users', $extdbuser1);
419         // User with malicious data on the name.
420         $extdbuser2 = (object)array('name'=>'user<script>alert(1);</script>xss', 'pass'=>'heslo', 'email'=>'xssuser@example.com');
421         $extdbuser2->id = $DB->insert_record('auth_db_users', $extdbuser2);
423         $trace = new null_progress_trace();
425         // Let's test user sync make sure still works as expected..
426         $auth->sync_users($trace, true);
428         // Get the user on moodle user table.
429         $user2 = $DB->get_record('user', array('email'=> $extdbuser2->email, 'auth'=>'db'));
431         // The malicious code should be sanitized.
432         $this->assertEquals($user2->username, 'userscriptalert1scriptxss');
433         $this->assertNotEquals($user2->username, $extdbuser2->name);
435         // User with correct data, should be equal to external db.
436         $user1 = $DB->get_record('user', array('email'=> $extdbuser1->email, 'auth'=>'db'));
437         $this->assertEquals($extdbuser1->name, $user1->username);
438         $this->assertEquals($extdbuser1->email, $user1->email);
440         // Now, let's update the name.
441         $extdbuser2->name = 'user no xss anymore';
442         $DB->update_record('auth_db_users', $extdbuser2);
444         // Run sync again to update the user data.
445         $auth->sync_users($trace, true);
447         // The user information should be updated.
448         $user2 = $DB->get_record('user', array('username' => 'usernoxssanymore', 'auth' => 'db'));
449         // The spaces should be removed, as it's the username.
450         $this->assertEquals($user2->username, 'usernoxssanymore');
452         // Now let's test just the clean_data() method isolated.
453         // Testing PARAM_USERNAME, PARAM_NOTAGS, PARAM_RAW_TRIMMED and others.
454         $user3 = new stdClass();
455         $user3->firstname = 'John <script>alert(1)</script> Doe';
456         $user3->username = 'john%#&~%*_doe';
457         $user3->email = ' john@testing.com ';
458         $user3->deleted = 'no';
459         $user3->description = '<b>A description <script>alert(123)</script>about myself.</b>';
460         $user3cleaned = $auth->clean_data($user3);
462         // Expected results.
463         $this->assertEquals($user3cleaned->firstname, 'John alert(1) Doe');
464         $this->assertEquals($user3cleaned->email, 'john@testing.com');
465         $this->assertEquals($user3cleaned->deleted, 0);
466         $this->assertEquals($user3->description, '<b>A description about myself.</b>');
467         $this->assertEquals($user3->username, 'john_doe');
469         // Try to clean an invalid property (fullname).
470         $user3->fullname = 'John Doe';
471         $auth->clean_data($user3);
472         $this->assertDebuggingCalled("The property 'fullname' could not be cleaned.");
473         $this->cleanup_auth_database();
474     }