aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorVirtualTam <virtualtam+github@flibidi.net>2017-10-25 22:49:22 +0200
committerGitHub <noreply@github.com>2017-10-25 22:49:22 +0200
commit88d38cb290aad669ad1406e2362d85c81e46d4f6 (patch)
tree9a0689e685ba42b44e507f2ae5e22595671b3bc4
parent6bc7afab91c78b893da314220fe346a366aefb8f (diff)
parentae7c954b1279981cc23c9f67d88f55bfecc4d828 (diff)
downloadShaarli-88d38cb290aad669ad1406e2362d85c81e46d4f6.tar.gz
Shaarli-88d38cb290aad669ad1406e2362d85c81e46d4f6.tar.zst
Shaarli-88d38cb290aad669ad1406e2362d85c81e46d4f6.zip
Merge pull request #1005 from virtualtam/refactor/authentication
Refactor session management utilities
-rw-r--r--application/PageBuilder.php6
-rw-r--r--application/SessionManager.php83
-rw-r--r--application/Utils.php30
-rw-r--r--index.php73
-rw-r--r--tests/SessionManagerTest.php160
-rw-r--r--tests/UtilsTest.php58
6 files changed, 272 insertions, 138 deletions
diff --git a/application/PageBuilder.php b/application/PageBuilder.php
index af290671..468f144b 100644
--- a/application/PageBuilder.php
+++ b/application/PageBuilder.php
@@ -32,12 +32,14 @@ class PageBuilder
32 * 32 *
33 * @param ConfigManager $conf Configuration Manager instance (reference). 33 * @param ConfigManager $conf Configuration Manager instance (reference).
34 * @param LinkDB $linkDB instance. 34 * @param LinkDB $linkDB instance.
35 * @param string $token Session token
35 */ 36 */
36 public function __construct(&$conf, $linkDB = null) 37 public function __construct(&$conf, $linkDB = null, $token = null)
37 { 38 {
38 $this->tpl = false; 39 $this->tpl = false;
39 $this->conf = $conf; 40 $this->conf = $conf;
40 $this->linkDB = $linkDB; 41 $this->linkDB = $linkDB;
42 $this->token = $token;
41 } 43 }
42 44
43 /** 45 /**
@@ -92,7 +94,7 @@ class PageBuilder
92 $this->tpl->assign('showatom', $this->conf->get('feed.show_atom', true)); 94 $this->tpl->assign('showatom', $this->conf->get('feed.show_atom', true));
93 $this->tpl->assign('feed_type', $this->conf->get('feed.show_atom', true) !== false ? 'atom' : 'rss'); 95 $this->tpl->assign('feed_type', $this->conf->get('feed.show_atom', true) !== false ? 'atom' : 'rss');
94 $this->tpl->assign('hide_timestamps', $this->conf->get('privacy.hide_timestamps', false)); 96 $this->tpl->assign('hide_timestamps', $this->conf->get('privacy.hide_timestamps', false));
95 $this->tpl->assign('token', getToken($this->conf)); 97 $this->tpl->assign('token', $this->token);
96 98
97 if ($this->linkDB !== null) { 99 if ($this->linkDB !== null) {
98 $this->tpl->assign('tags', $this->linkDB->linksCountPerTag()); 100 $this->tpl->assign('tags', $this->linkDB->linksCountPerTag());
diff --git a/application/SessionManager.php b/application/SessionManager.php
new file mode 100644
index 00000000..3aa4ddfc
--- /dev/null
+++ b/application/SessionManager.php
@@ -0,0 +1,83 @@
1<?php
2namespace Shaarli;
3
4/**
5 * Manages the server-side session
6 */
7class SessionManager
8{
9 protected $session = [];
10
11 /**
12 * Constructor
13 *
14 * @param array $session The $_SESSION array (reference)
15 * @param ConfigManager $conf ConfigManager instance (reference)
16 */
17 public function __construct(& $session, & $conf)
18 {
19 $this->session = &$session;
20 $this->conf = &$conf;
21 }
22
23 /**
24 * Generates a session token
25 *
26 * @return string token
27 */
28 public function generateToken()
29 {
30 $token = sha1(uniqid('', true) .'_'. mt_rand() . $this->conf->get('credentials.salt'));
31 $this->session['tokens'][$token] = 1;
32 return $token;
33 }
34
35 /**
36 * Checks the validity of a session token, and destroys it afterwards
37 *
38 * @param string $token The token to check
39 *
40 * @return bool true if the token is valid, else false
41 */
42 public function checkToken($token)
43 {
44 if (! isset($this->session['tokens'][$token])) {
45 // the token is wrong, or has already been used
46 return false;
47 }
48
49 // destroy the token to prevent future use
50 unset($this->session['tokens'][$token]);
51 return true;
52 }
53
54 /**
55 * Validate session ID to prevent Full Path Disclosure.
56 *
57 * See #298.
58 * The session ID's format depends on the hash algorithm set in PHP settings
59 *
60 * @param string $sessionId Session ID
61 *
62 * @return true if valid, false otherwise.
63 *
64 * @see http://php.net/manual/en/function.hash-algos.php
65 * @see http://php.net/manual/en/session.configuration.php
66 */
67 public static function checkId($sessionId)
68 {
69 if (empty($sessionId)) {
70 return false;
71 }
72
73 if (!$sessionId) {
74 return false;
75 }
76
77 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
78 return false;
79 }
80
81 return true;
82 }
83}
diff --git a/application/Utils.php b/application/Utils.php
index 2f38a8de..97b12fcf 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -182,36 +182,6 @@ function generateLocation($referer, $host, $loopTerms = array())
182} 182}
183 183
184/** 184/**
185 * Validate session ID to prevent Full Path Disclosure.
186 *
187 * See #298.
188 * The session ID's format depends on the hash algorithm set in PHP settings
189 *
190 * @param string $sessionId Session ID
191 *
192 * @return true if valid, false otherwise.
193 *
194 * @see http://php.net/manual/en/function.hash-algos.php
195 * @see http://php.net/manual/en/session.configuration.php
196 */
197function is_session_id_valid($sessionId)
198{
199 if (empty($sessionId)) {
200 return false;
201 }
202
203 if (!$sessionId) {
204 return false;
205 }
206
207 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
208 return false;
209 }
210
211 return true;
212}
213
214/**
215 * Sniff browser language to set the locale automatically. 185 * Sniff browser language to set the locale automatically.
216 * Note that is may not work on your server if the corresponding locale is not installed. 186 * Note that is may not work on your server if the corresponding locale is not installed.
217 * 187 *
diff --git a/index.php b/index.php
index 1dc81843..e1516d37 100644
--- a/index.php
+++ b/index.php
@@ -78,6 +78,7 @@ require_once 'application/Updater.php';
78use \Shaarli\Languages; 78use \Shaarli\Languages;
79use \Shaarli\ThemeUtils; 79use \Shaarli\ThemeUtils;
80use \Shaarli\Config\ConfigManager; 80use \Shaarli\Config\ConfigManager;
81use \Shaarli\SessionManager;
81 82
82// Ensure the PHP version is supported 83// Ensure the PHP version is supported
83try { 84try {
@@ -115,12 +116,13 @@ if (session_id() == '') {
115} 116}
116 117
117// Regenerate session ID if invalid or not defined in cookie. 118// Regenerate session ID if invalid or not defined in cookie.
118if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) { 119if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
119 session_regenerate_id(true); 120 session_regenerate_id(true);
120 $_COOKIE['shaarli'] = session_id(); 121 $_COOKIE['shaarli'] = session_id();
121} 122}
122 123
123$conf = new ConfigManager(); 124$conf = new ConfigManager();
125$sessionManager = new SessionManager($_SESSION, $conf);
124 126
125// Sniff browser language and set date format accordingly. 127// Sniff browser language and set date format accordingly.
126if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { 128if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
@@ -165,7 +167,7 @@ if (! is_file($conf->getConfigFileExt())) {
165 } 167 }
166 168
167 // Display the installation form if no existing config is found 169 // Display the installation form if no existing config is found
168 install($conf); 170 install($conf, $sessionManager);
169} 171}
170 172
171// a token depending of deployment salt, user password, and the current ip 173// a token depending of deployment salt, user password, and the current ip
@@ -381,7 +383,7 @@ if (isset($_POST['login']))
381{ 383{
382 if (!ban_canLogin($conf)) die(t('I said: NO. You are banned for the moment. Go away.')); 384 if (!ban_canLogin($conf)) die(t('I said: NO. You are banned for the moment. Go away.'));
383 if (isset($_POST['password']) 385 if (isset($_POST['password'])
384 && tokenOk($_POST['token']) 386 && $sessionManager->checkToken($_POST['token'])
385 && (check_auth($_POST['login'], $_POST['password'], $conf)) 387 && (check_auth($_POST['login'], $_POST['password'], $conf))
386 ) { // Login/password is OK. 388 ) { // Login/password is OK.
387 ban_loginOk($conf); 389 ban_loginOk($conf);
@@ -455,32 +457,6 @@ if (isset($_POST['login']))
455if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session. 457if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
456 458
457/** 459/**
458 * Returns a token.
459 *
460 * @param ConfigManager $conf Configuration Manager instance.
461 *
462 * @return string token.
463 */
464function getToken($conf)
465{
466 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string.
467 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
468 return $rnd;
469}
470
471// Tells if a token is OK. Using this function will destroy the token.
472// true=token is OK.
473function tokenOk($token)
474{
475 if (isset($_SESSION['tokens'][$token]))
476 {
477 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
478 return true; // Token is OK.
479 }
480 return false; // Wrong token, or already used.
481}
482
483/**
484 * Daily RSS feed: 1 RSS entry per day giving all the links on that day. 460 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
485 * Gives the last 7 days (which have links). 461 * Gives the last 7 days (which have links).
486 * This RSS feed cannot be filtered. 462 * This RSS feed cannot be filtered.
@@ -687,12 +663,13 @@ function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
687/** 663/**
688 * Render HTML page (according to URL parameters and user rights) 664 * Render HTML page (according to URL parameters and user rights)
689 * 665 *
690 * @param ConfigManager $conf Configuration Manager instance. 666 * @param ConfigManager $conf Configuration Manager instance.
691 * @param PluginManager $pluginManager Plugin Manager instance, 667 * @param PluginManager $pluginManager Plugin Manager instance,
692 * @param LinkDB $LINKSDB 668 * @param LinkDB $LINKSDB
693 * @param History $history instance 669 * @param History $history instance
670 * @param SessionManager $sessionManager SessionManager instance
694 */ 671 */
695function renderPage($conf, $pluginManager, $LINKSDB, $history) 672function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager)
696{ 673{
697 $updater = new Updater( 674 $updater = new Updater(
698 read_updates_file($conf->get('resource.updates')), 675 read_updates_file($conf->get('resource.updates')),
@@ -713,7 +690,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
713 die($e->getMessage()); 690 die($e->getMessage());
714 } 691 }
715 692
716 $PAGE = new PageBuilder($conf, $LINKSDB); 693 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken());
717 $PAGE->assign('linkcount', count($LINKSDB)); 694 $PAGE->assign('linkcount', count($LINKSDB));
718 $PAGE->assign('privateLinkcount', count_private($LINKSDB)); 695 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
719 $PAGE->assign('plugin_errors', $pluginManager->getErrors()); 696 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
@@ -1109,13 +1086,13 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1109 1086
1110 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) 1087 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1111 { 1088 {
1112 if (!tokenOk($_POST['token'])) die(t('Wrong token.')); // Go away! 1089 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
1113 1090
1114 // Make sure old password is correct. 1091 // Make sure old password is correct.
1115 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')); 1092 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
1116 if ($oldhash!= $conf->get('credentials.hash')) { 1093 if ($oldhash!= $conf->get('credentials.hash')) {
1117 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>'; 1094 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
1118 exit; 1095 exit;
1119 } 1096 }
1120 // Save new password 1097 // Save new password
1121 // Salt renders rainbow-tables attacks useless. 1098 // Salt renders rainbow-tables attacks useless.
@@ -1149,7 +1126,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1149 { 1126 {
1150 if (!empty($_POST['title']) ) 1127 if (!empty($_POST['title']) )
1151 { 1128 {
1152 if (!tokenOk($_POST['token'])) { 1129 if (!$sessionManager->checkToken($_POST['token'])) {
1153 die(t('Wrong token.')); // Go away! 1130 die(t('Wrong token.')); // Go away!
1154 } 1131 }
1155 $tz = 'UTC'; 1132 $tz = 'UTC';
@@ -1225,7 +1202,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1225 exit; 1202 exit;
1226 } 1203 }
1227 1204
1228 if (!tokenOk($_POST['token'])) { 1205 if (!$sessionManager->checkToken($_POST['token'])) {
1229 die(t('Wrong token.')); 1206 die(t('Wrong token.'));
1230 } 1207 }
1231 1208
@@ -1255,7 +1232,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1255 if (isset($_POST['save_edit'])) 1232 if (isset($_POST['save_edit']))
1256 { 1233 {
1257 // Go away! 1234 // Go away!
1258 if (! tokenOk($_POST['token'])) { 1235 if (! $sessionManager->checkToken($_POST['token'])) {
1259 die(t('Wrong token.')); 1236 die(t('Wrong token.'));
1260 } 1237 }
1261 1238
@@ -1355,7 +1332,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1355 // -------- User clicked the "Delete" button when editing a link: Delete link from database. 1332 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1356 if ($targetPage == Router::$PAGE_DELETELINK) 1333 if ($targetPage == Router::$PAGE_DELETELINK)
1357 { 1334 {
1358 if (! tokenOk($_GET['token'])) { 1335 if (! $sessionManager->checkToken($_GET['token'])) {
1359 die(t('Wrong token.')); 1336 die(t('Wrong token.'));
1360 } 1337 }
1361 1338
@@ -1572,7 +1549,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1572 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>'; 1549 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
1573 exit; 1550 exit;
1574 } 1551 }
1575 if (! tokenOk($_POST['token'])) { 1552 if (! $sessionManager->checkToken($_POST['token'])) {
1576 die('Wrong token.'); 1553 die('Wrong token.');
1577 } 1554 }
1578 $status = NetscapeBookmarkUtils::import( 1555 $status = NetscapeBookmarkUtils::import(
@@ -1639,7 +1616,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history)
1639 // Get a fresh token 1616 // Get a fresh token
1640 if ($targetPage == Router::$GET_TOKEN) { 1617 if ($targetPage == Router::$GET_TOKEN) {
1641 header('Content-Type:text/plain'); 1618 header('Content-Type:text/plain');
1642 echo getToken($conf); 1619 echo $sessionManager->generateToken($conf);
1643 exit; 1620 exit;
1644 } 1621 }
1645 1622
@@ -1965,10 +1942,10 @@ function lazyThumbnail($conf, $url,$href=false)
1965 * Installation 1942 * Installation
1966 * This function should NEVER be called if the file data/config.php exists. 1943 * This function should NEVER be called if the file data/config.php exists.
1967 * 1944 *
1968 * @param ConfigManager $conf Configuration Manager instance. 1945 * @param ConfigManager $conf Configuration Manager instance.
1946 * @param SessionManager $sessionManager SessionManager instance
1969 */ 1947 */
1970function install($conf) 1948function install($conf, $sessionManager) {
1971{
1972 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1949 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1973 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1950 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1974 1951
@@ -2051,7 +2028,7 @@ function install($conf)
2051 exit; 2028 exit;
2052 } 2029 }
2053 2030
2054 $PAGE = new PageBuilder($conf); 2031 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
2055 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get()); 2032 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
2056 $PAGE->assign('continents', $continents); 2033 $PAGE->assign('continents', $continents);
2057 $PAGE->assign('cities', $cities); 2034 $PAGE->assign('cities', $cities);
@@ -2328,7 +2305,7 @@ $response = $app->run(true);
2328if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) { 2305if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2329 // We use UTF-8 for proper international characters handling. 2306 // We use UTF-8 for proper international characters handling.
2330 header('Content-Type: text/html; charset=utf-8'); 2307 header('Content-Type: text/html; charset=utf-8');
2331 renderPage($conf, $pluginManager, $linkDb, $history); 2308 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager);
2332} else { 2309} else {
2333 $app->respond($response); 2310 $app->respond($response);
2334} 2311}
diff --git a/tests/SessionManagerTest.php b/tests/SessionManagerTest.php
new file mode 100644
index 00000000..a92c3ccc
--- /dev/null
+++ b/tests/SessionManagerTest.php
@@ -0,0 +1,160 @@
1<?php
2// Initialize reference data _before_ PHPUnit starts a session
3require_once 'tests/utils/ReferenceSessionIdHashes.php';
4ReferenceSessionIdHashes::genAllHashes();
5
6use \Shaarli\SessionManager;
7use \PHPUnit\Framework\TestCase;
8
9
10/**
11 * Fake ConfigManager
12 */
13class FakeConfigManager
14{
15 public static function get($key)
16 {
17 return $key;
18 }
19}
20
21
22/**
23 * Test coverage for SessionManager
24 */
25class SessionManagerTest extends TestCase
26{
27 // Session ID hashes
28 protected static $sidHashes = null;
29
30 /**
31 * Assign reference data
32 */
33 public static function setUpBeforeClass()
34 {
35 self::$sidHashes = ReferenceSessionIdHashes::getHashes();
36 }
37
38 /**
39 * Generate a session token
40 */
41 public function testGenerateToken()
42 {
43 $session = [];
44 $conf = new FakeConfigManager();
45 $sessionManager = new SessionManager($session, $conf);
46
47 $token = $sessionManager->generateToken();
48
49 $this->assertEquals(1, $session['tokens'][$token]);
50 $this->assertEquals(40, strlen($token));
51 }
52
53 /**
54 * Check a session token
55 */
56 public function testCheckToken()
57 {
58 $token = '4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b';
59 $session = [
60 'tokens' => [
61 $token => 1,
62 ],
63 ];
64 $conf = new FakeConfigManager();
65 $sessionManager = new SessionManager($session, $conf);
66
67
68 // check and destroy the token
69 $this->assertTrue($sessionManager->checkToken($token));
70 $this->assertFalse(isset($session['tokens'][$token]));
71
72 // ensure the token has been destroyed
73 $this->assertFalse($sessionManager->checkToken($token));
74 }
75
76 /**
77 * Generate and check a session token
78 */
79 public function testGenerateAndCheckToken()
80 {
81 $session = [];
82 $conf = new FakeConfigManager();
83 $sessionManager = new SessionManager($session, $conf);
84
85 $token = $sessionManager->generateToken();
86
87 // ensure a token has been generated
88 $this->assertEquals(1, $session['tokens'][$token]);
89 $this->assertEquals(40, strlen($token));
90
91 // check and destroy the token
92 $this->assertTrue($sessionManager->checkToken($token));
93 $this->assertFalse(isset($session['tokens'][$token]));
94
95 // ensure the token has been destroyed
96 $this->assertFalse($sessionManager->checkToken($token));
97 }
98
99 /**
100 * Check an invalid session token
101 */
102 public function testCheckInvalidToken()
103 {
104 $session = [];
105 $conf = new FakeConfigManager();
106 $sessionManager = new SessionManager($session, $conf);
107
108 $this->assertFalse($sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'));
109 }
110
111 /**
112 * Test SessionManager::checkId with a valid ID - TEST ALL THE HASHES!
113 *
114 * This tests extensively covers all hash algorithms / bit representations
115 */
116 public function testIsAnyHashSessionIdValid()
117 {
118 foreach (self::$sidHashes as $algo => $bpcs) {
119 foreach ($bpcs as $bpc => $hash) {
120 $this->assertTrue(SessionManager::checkId($hash));
121 }
122 }
123 }
124
125 /**
126 * Test checkId with a valid ID - SHA-1 hashes
127 */
128 public function testIsSha1SessionIdValid()
129 {
130 $this->assertTrue(SessionManager::checkId(sha1('shaarli')));
131 }
132
133 /**
134 * Test checkId with a valid ID - SHA-256 hashes
135 */
136 public function testIsSha256SessionIdValid()
137 {
138 $this->assertTrue(SessionManager::checkId(hash('sha256', 'shaarli')));
139 }
140
141 /**
142 * Test checkId with a valid ID - SHA-512 hashes
143 */
144 public function testIsSha512SessionIdValid()
145 {
146 $this->assertTrue(SessionManager::checkId(hash('sha512', 'shaarli')));
147 }
148
149 /**
150 * Test checkId with invalid IDs.
151 */
152 public function testIsSessionIdInvalid()
153 {
154 $this->assertFalse(SessionManager::checkId(''));
155 $this->assertFalse(SessionManager::checkId([]));
156 $this->assertFalse(
157 SessionManager::checkId('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=')
158 );
159 }
160}
diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php
index 840eaf21..6cd37a7a 100644
--- a/tests/UtilsTest.php
+++ b/tests/UtilsTest.php
@@ -5,10 +5,6 @@
5 5
6require_once 'application/Utils.php'; 6require_once 'application/Utils.php';
7require_once 'application/Languages.php'; 7require_once 'application/Languages.php';
8require_once 'tests/utils/ReferenceSessionIdHashes.php';
9
10// Initialize reference data before PHPUnit starts a session
11ReferenceSessionIdHashes::genAllHashes();
12 8
13 9
14/** 10/**
@@ -16,9 +12,6 @@ ReferenceSessionIdHashes::genAllHashes();
16 */ 12 */
17class UtilsTest extends PHPUnit_Framework_TestCase 13class UtilsTest extends PHPUnit_Framework_TestCase
18{ 14{
19 // Session ID hashes
20 protected static $sidHashes = null;
21
22 // Log file 15 // Log file
23 protected static $testLogFile = 'tests.log'; 16 protected static $testLogFile = 'tests.log';
24 17
@@ -30,13 +23,11 @@ class UtilsTest extends PHPUnit_Framework_TestCase
30 */ 23 */
31 protected static $defaultTimeZone; 24 protected static $defaultTimeZone;
32 25
33
34 /** 26 /**
35 * Assign reference data 27 * Assign reference data
36 */ 28 */
37 public static function setUpBeforeClass() 29 public static function setUpBeforeClass()
38 { 30 {
39 self::$sidHashes = ReferenceSessionIdHashes::getHashes();
40 self::$defaultTimeZone = date_default_timezone_get(); 31 self::$defaultTimeZone = date_default_timezone_get();
41 // Timezone without DST for test consistency 32 // Timezone without DST for test consistency
42 date_default_timezone_set('Africa/Nairobi'); 33 date_default_timezone_set('Africa/Nairobi');
@@ -221,57 +212,8 @@ class UtilsTest extends PHPUnit_Framework_TestCase
221 $this->assertEquals('?', generateLocation($ref, 'localhost')); 212 $this->assertEquals('?', generateLocation($ref, 'localhost'));
222 } 213 }
223 214
224 /**
225 * Test is_session_id_valid with a valid ID - TEST ALL THE HASHES!
226 *
227 * This tests extensively covers all hash algorithms / bit representations
228 */
229 public function testIsAnyHashSessionIdValid()
230 {
231 foreach (self::$sidHashes as $algo => $bpcs) {
232 foreach ($bpcs as $bpc => $hash) {
233 $this->assertTrue(is_session_id_valid($hash));
234 }
235 }
236 }
237 215
238 /** 216 /**
239 * Test is_session_id_valid with a valid ID - SHA-1 hashes
240 */
241 public function testIsSha1SessionIdValid()
242 {
243 $this->assertTrue(is_session_id_valid(sha1('shaarli')));
244 }
245
246 /**
247 * Test is_session_id_valid with a valid ID - SHA-256 hashes
248 */
249 public function testIsSha256SessionIdValid()
250 {
251 $this->assertTrue(is_session_id_valid(hash('sha256', 'shaarli')));
252 }
253
254 /**
255 * Test is_session_id_valid with a valid ID - SHA-512 hashes
256 */
257 public function testIsSha512SessionIdValid()
258 {
259 $this->assertTrue(is_session_id_valid(hash('sha512', 'shaarli')));
260 }
261
262 /**
263 * Test is_session_id_valid with invalid IDs.
264 */
265 public function testIsSessionIdInvalid()
266 {
267 $this->assertFalse(is_session_id_valid(''));
268 $this->assertFalse(is_session_id_valid(array()));
269 $this->assertFalse(
270 is_session_id_valid('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=')
271 );
272 }
273
274 /**
275 * Test generateSecretApi. 217 * Test generateSecretApi.
276 */ 218 */
277 public function testGenerateSecretApi() 219 public function testGenerateSecretApi()