3
* Gallery - a web based photo album viewer and editor
4
* Copyright (C) 2000-2007 Bharat Mediratta
6
* This program is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; either version 2 of the License, or (at
9
* your option) any later version.
11
* This program is distributed in the hope that it will be useful, but
12
* WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
* General Public License for more details.
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21
GalleryCoreApi::requireOnce('modules/httpauth/classes/HttpAuthHelper.class');
24
* HTTP auth helper tests.
27
* @author Jack Bates <ms419@freezone.co.uk>
28
* @version $Revision: 15979 $
30
class HttpAuthHelperTest extends GalleryTestCase {
32
function HttpAuthHelperTest($methodName) {
33
$this->GalleryTestCase($methodName);
39
$urlGenerator =& $gallery->getUrlGenerator();
41
/* Mock activate the rewrite module */
42
$moduleStatus = array('rewrite' => array('active' => true));
43
GalleryDataCache::put('GalleryPluginHelper::fetchPluginList(module)', $moduleStatus);
45
/* Mock preGallery rewrite parser. Mock activate HTTP auth rewrite rules. */
46
$this->_parserType =& HttpAuthHelperTestRewriteApi::_getParserType();
47
$this->_parserType = 'preGallery';
48
$this->_activeRules =& HttpAuthHelperTestRewriteApi::_fetchActiveRulesForModule('httpauth');
49
$this->_activeRules = array('authorization');
50
$this->_markFactoryForCleanup();
51
$this->_registerFactoryImplementationForTest(
52
'RewriteApi', 'HttpAuthHelperTestRewriteApi', 'HttpAuthHelperTestRewriteApi',
53
'modules/httpauth/test/phpunit/HttpAuthHelperTest.class', 'test');
55
/* Define HTTP auth works request */
56
$this->_httpAuthWorksRequest = 'GET ' . $urlGenerator->generateUrl(
57
array('view' => 'httpauth.HttpAuthWorks'),
58
array('forceServerRelativeUrl' => true,
59
'htmlEntities' => false)) . " HTTP/1.0\r\n"
60
. 'Host: ' . $urlGenerator->getHostName() . "\r\n"
61
. 'Authorization: Basic ' . base64_encode('USERNAME:PASSWORD') . "\r\n"
64
/* Define success and failure responses */
65
$this->_accessAuthorizationResponse = implode("\r\n", array(
67
'Date: Mon, 24 Nov 2003 05:40:03 GMT',
68
'Server: Apache/1.3.28 (Unix)',
71
'Content-Type: text/html',
74
. "Basic\nUSERNAME\nPASSWORD";
75
$this->_missingAuthorizationResponse = implode("\r\n", array(
77
'Date: Mon, 24 Nov 2003 05:40:03 GMT',
78
'Server: Apache/1.3.28 (Unix)',
81
'Content-Type: text/html',
86
/* Use HttpAuthHelperTestPlatform */
87
$this->_platform = new HttpAuthHelperTestPlatform();
88
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
89
$this->_accessAuthorizationResponse;
90
$gallery->setPlatform($this->_platform);
92
$ret = $this->_markPluginParametersForCleanup('module', 'httpauth');
94
return $this->failWithStatus($ret);
97
/* Configure plugin */
98
foreach (array('httpAuthPlugin' => true, 'regexAuthPlugin' => true,
99
'authtypePattern' => '//', 'usernameReplace' => '$2',
100
'usernamePattern' => '/^(.+\\\\)?([^\\\\@]+)(@.+)?$/',
101
'serverAuthPlugin' => false, 'useGlobally' => true,
102
'authName' => 'TEST_AUTH_NAME') as $key => $value) {
103
$ret = GalleryCoreApi::setPluginParameter('module', 'httpauth', $key, $value);
105
print $ret->getAsHtml();
106
return $this->failWithStatus($ret);
110
/* Create test user */
111
list ($ret, $this->_user) = $this->_createRandomUser();
113
print $ret->getAsHtml();
114
return $this->failWithStatus($ret);
116
$this->_markForCleanup($this->_user);
118
list ($ret, $this->_authInterface) =
119
GalleryCoreApi::newFactoryInstance('HttpAuthInterface_1_0');
121
print $ret->getAsHtml();
122
return $this->failWithStatus($ret);
124
$this->assert(isset($this->_authInterface), 'Could not instantiate auth interface.');
126
/* Use HttpAuthModuleTestPhpVm */
127
$this->_phpVm = new HttpAuthHelperTestPhpVm();
128
$gallery->_phpVm =& $this->_phpVm;
130
/* Clear response headers */
131
$this->_headers =& GalleryUtilities::_getResponseHeaders();
132
$this->_headers = array();
134
$this->_saveSession = $gallery->_session;
136
$_SERVER['AUTH_TYPE'] = $_SERVER['PHP_AUTH_USER'] = $_SERVER['PHP_AUTH_PW'] = null;
137
GalleryUtilities::removeRequestVariable('authorization');
138
$_SERVER['HTTP_AUTHORIZATION'] = null;
141
function tearDown() {
143
GalleryDataCache::reset();
144
$gallery->_session = $this->_saveSession;
148
if (!empty($this->_resetFactory)) {
149
/* After the plugin parameters have been reset, reset the factory as well */
150
list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'httpauth');
152
$this->failWithStatus($ret);
154
$ret = GalleryCoreApi::unregisterFactoryImplementationsByModuleId('httpauth');
156
$this->failWithStatus($ret);
158
$ret = $module->performFactoryRegistrations();
160
$this->failWithStatus($ret);
164
$storage =& $gallery->getStorage();
165
$ret = $storage->commitTransaction();
167
$this->failWithStatus($ret);
172
function testCheckConfiguration() {
173
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
175
return $this->failWithStatus($ret);
178
$this->assertEquals(0, $code, 'unexpected error code');
181
function testCheckConfigurationRewriteModuleDisabled() {
182
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
183
$this->_missingAuthorizationResponse;
184
$moduleStatus = array();
185
GalleryDataCache::put('GalleryPluginHelper::fetchPluginList(module)', $moduleStatus);
187
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
189
return $this->failWithStatus($ret);
192
$this->assertEquals(HTTPAUTH_STATUS_MISSING_AUTHORIZATION
193
| HTTPAUTH_STATUS_REWRITE_MODULE_DISABLED, $code);
196
function testCheckConfigurationBadRewriteParser() {
197
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
198
$this->_missingAuthorizationResponse;
199
$this->_parserType = 'bogus';
201
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
203
return $this->failWithStatus($ret);
206
$this->assertEquals(HTTPAUTH_STATUS_MISSING_AUTHORIZATION
207
| HTTPAUTH_STATUS_BAD_REWRITE_PARSER, $code);
210
function testCheckConfigurationAuthorizationRuleDisabled() {
211
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
212
$this->_missingAuthorizationResponse;
213
$this->_activeRules = array();
215
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
217
return $this->failWithStatus($ret);
220
$this->assertEquals(HTTPAUTH_STATUS_MISSING_AUTHORIZATION
221
| HTTPAUTH_STATUS_AUTHORIZATION_RULE_DISABLED, $code);
224
function testCheckConfigurationErrorUnknown() {
225
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
226
$this->_missingAuthorizationResponse;
228
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
230
return $this->failWithStatus($ret);
233
$this->assertEquals(HTTPAUTH_STATUS_MISSING_AUTHORIZATION
234
| HTTPAUTH_STATUS_ERROR_UNKNOWN, $code);
237
function testCheckConfigurationHttpAuthWorksIgnoresCauses() {
238
$moduleStatus = array();
239
GalleryDataCache::put('GalleryPluginHelper::fetchPluginList(module)', $moduleStatus);
240
$this->_parserType = 'bogus';
241
$this->_activeRules = array();
243
list ($ret, $code) = HttpAuthHelper::checkConfiguration();
245
return $this->failWithStatus($ret);
248
$this->assert(!$code);
251
function testCheckHttpAuth() {
252
list ($ret, $success) = HttpAuthHelper::checkHttpAuth();
254
return $this->failWithStatus($ret);
257
$this->assert($success);
260
function testCheckHttpAuthMissingAuthorization() {
261
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
262
$this->_missingAuthorizationResponse;
264
list ($ret, $success) = HttpAuthHelper::checkHttpAuth();
266
return $this->failWithStatus($ret);
269
$this->assert(!$success);
272
function testCheckHttpAuthPluginDisabled() {
273
$this->_platform->_messages[$this->_httpAuthWorksRequest] =
274
$this->_missingAuthorizationResponse;
275
$ret = GalleryCoreApi::removePluginParameter('module', 'httpauth', 'httpAuthPlugin');
277
return $this->failWithStatus($ret);
280
list ($ret, $success) = HttpAuthHelper::checkHttpAuth();
282
return $this->failWithStatus($ret);
285
$this->assert($success);
288
function testGetHttpAuth() {
289
$_SERVER['AUTH_TYPE'] = 'AUTHTYPE';
290
$_SERVER['PHP_AUTH_USER'] = 'USERNAME';
291
$_SERVER['PHP_AUTH_PW'] = 'PASSWORD';
293
list ($authtype, $username, $password) = HttpAuthHelper::getHttpAuth();
294
$this->assertEquals('AUTHTYPE', $authtype);
295
$this->assertEquals('USERNAME', $username);
296
$this->assertEquals('PASSWORD', $password);
299
function testGetHttpAuthFromRequestVariable() {
300
GalleryUtilities::putRequestVariable(
301
'authorization', 'AUTHTYPE ' . base64_encode('USERNAME:PASSWORD'));
303
$_SERVER['HTTP_AUTHORIZATION'] = 'OTHER ' . base64_encode('NOUSER:NOPASS');
305
list ($authtype, $username, $password) = HttpAuthHelper::getHttpAuth();
306
$this->assertEquals('AUTHTYPE', $authtype);
307
$this->assertEquals('USERNAME', $username);
308
$this->assertEquals('PASSWORD', $password);
311
function testGetHttpAuthFromHttpAuthorizationHeader() {
312
$_SERVER['HTTP_AUTHORIZATION'] = 'AUTHTYPE ' . base64_encode('USERNAME:PASSWORD');
314
list ($authtype, $username, $password) = HttpAuthHelper::getHttpAuth();
315
$this->assertEquals('AUTHTYPE', $authtype);
316
$this->assertEquals('USERNAME', $username);
317
$this->assertEquals('PASSWORD', $password);
320
function testGetHttpAuthWithoutAuthTypeDefaultsToBasic() {
321
$_SERVER['PHP_AUTH_USER'] = 'USERNAME';
322
$_SERVER['PHP_AUTH_PW'] = 'PASSWORD';
324
list ($authtype, $username, $password) = HttpAuthHelper::getHttpAuth();
325
$this->assertEquals('Basic', $authtype);
326
$this->assertEquals('USERNAME', $username);
327
$this->assertEquals('PASSWORD', $password);
330
function testGetHttpAuthWithoutAuthAndUserDoesNotDefault() {
331
$_SERVER['PHP_AUTH_USER'] = '';
332
$_SERVER['PHP_AUTH_PW'] = 'PASSWORD';
334
list ($authtype, $username, $password) = HttpAuthHelper::getHttpAuth();
335
$this->assertEquals(null, $authtype, 'auth type');
336
$this->assertEquals('', $username, 'user name');
337
$this->assertEquals('PASSWORD', $password, 'password');
340
function testGetUser() {
341
list ($ret, $user) = HttpAuthHelper::getUser('Test', $this->_user->getUserName());
343
return $this->failWithStatus($ret);
346
$this->assertEquals($this->_user, $user);
349
function testGetUserInvalidUser() {
350
list ($ret, $user) = HttpAuthHelper::getUser('Test', 'bogusUser-' . rand());
352
return $this->failWithStatus($ret);
355
$this->assertEquals(null, $user);
358
function testGetUserDisabledUser() {
359
$ret = $this->_disableUserName($this->_user->getUserName());
361
return $this->failWithStatus($ret);
364
list ($ret, $user) = HttpAuthHelper::getUser('Test', $this->_user->getUserName());
366
return $this->failWithStatus($ret);
369
$this->assertEquals(null, $user);
372
function testGetUserAuthtypePattern() {
373
$ret = GalleryCoreApi::setPluginParameter(
374
'module', 'httpauth', 'regexAuthPlugin', true);
376
return $this->failWithStatus($ret);
379
$ret = GalleryCoreApi::setPluginParameter(
380
'module', 'httpauth', 'authtypePattern', '/^Bogus$/');
382
return $this->failWithStatus($ret);
385
list ($ret, $user) = HttpAuthHelper::getUser('Test', $this->_user->getUserName());
387
return $this->failWithStatus($ret);
390
$this->assertEquals(null, $user);
393
function testGetUserUsernamePattern() {
394
$ret = GalleryCoreApi::setPluginParameter(
395
'module', 'httpauth', 'usernamePattern', '/^bogusUser-' . rand() . '$/');
397
return $this->failWithStatus($ret);
400
list ($ret, $user) = HttpAuthHelper::getUser('Test', $this->_user->getUserName());
402
return $this->failWithStatus($ret);
405
$this->assertEquals(null, $user);
408
function testGetUserUsernameReplace() {
410
HttpAuthHelper::getUser('Test', $this->_user->getUserName() . '@REALM.TLD');
412
return $this->failWithStatus($ret);
415
$this->assertEquals($this->_user, $user);
418
function testGetUserIgnoresUseGloballyFlag() {
419
$ret = GalleryCoreApi::setPluginParameter('module', 'httpauth', 'useGlobally', false);
421
return $this->failWithStatus($ret);
424
list ($ret, $user) = HttpAuthHelper::getUser('Test', $this->_user->getUserName());
426
return $this->failWithStatus($ret);
428
$this->assertEquals($this->_user, $user);
431
function testAddHttpAuthToUrl() {
432
$url = 'http://www.example.com/gallery2/main.php?foo=bar&view=baz#some';
433
$this->assertEquals('http://FAKEUSER:FAKEPASS@www.example.com/gallery2/' .
434
'main.php?foo=bar&view=baz#some',
435
HttpAuthHelper::addHttpAuthToUrl($url, 'FAKEUSER', 'FAKEPASS'),
436
'URL with all components');
438
$url = 'webdav://www.example.com/gallery2/main.php?foo=bar&view=baz#some';
439
$this->assertEquals('webdav://FAKEUSER:FAKEPASS@www.example.com/gallery2/' .
440
'main.php?foo=bar&view=baz#some',
441
HttpAuthHelper::addHttpAuthToUrl($url, 'FAKEUSER', 'FAKEPASS'),
442
'non-standard protocol, no HTML entities');
444
$url = 'https://www.example.com/gallery2/main.php';
445
$this->assertEquals('https://FAKEUSER:FAKEPASS@www.example.com/gallery2/main.php',
446
HttpAuthHelper::addHttpAuthToUrl($url, 'FAKEUSER', 'FAKEPASS'),
447
'no query string, anchor');
449
$url = 'http://OLDUSER:OLDPASS@example.com/gallery2/main.php?foo=bar&view=baz#some';
450
$this->assertEquals('http://FAKEUSER:FAKEPASS@example.com/gallery2/' .
451
'main.php?foo=bar&view=baz#some',
452
HttpAuthHelper::addHttpAuthToUrl($url, 'FAKEUSER', 'FAKEPASS'),
453
'URL with existing user:pass');
456
function testStripHttpAuthFromUrl() {
457
$url = 'http://OLDUSER:OLDPASS@example.com/gallery2/main.php?foo=bar&view=baz#some';
458
$this->assertEquals('http://example.com/gallery2/main.php?foo=bar&view=baz#some',
459
HttpAuthHelper::stripHttpAuthFromUrl($url),
460
'URL with user:pass');
462
$url = 'http://www.example.com/gallery2/main.php?foo=bar&view=baz#some';
463
$this->assertEquals('http://www.example.com/gallery2/main.php?foo=bar&view=baz#some',
464
HttpAuthHelper::stripHttpAuthFromUrl($url),
465
'URL without user:pass');
467
$url = 'webdav://OLDUSER:OLDPASS@example.com/gallery2/main.php?foo=bar&view=baz';
468
$this->assertEquals('webdav://example.com/gallery2/main.php?foo=bar&view=baz',
469
HttpAuthHelper::stripHttpAuthFromUrl($url),
470
'URL without HTML entities, anchor, other protocol');
473
function testGetConfiguration() {
474
list ($ret, $authPluginEnabled, $serverPluginEnabled, $usedGlobally) =
475
$this->_authInterface->getConfiguration();
477
return $this->failWithStatus($ret);
480
$this->assertEquals(array(true, false, true),
481
array($authPluginEnabled, $serverPluginEnabled, $usedGlobally));
484
function testSetConfiguration() {
485
$this->_resetFactory = true;
486
$ret = $this->_authInterface->setConfiguration(false, true, false);
488
return $this->failWithStatus($ret);
491
list ($ret, $params) = GalleryCoreApi::fetchAllPluginParameters('module', 'httpauth');
493
return $this->failWithStatus($ret);
496
$this->assert(!(bool)$params['httpAuthPlugin'], 'wrong httpAuthPlugin value');
497
$this->assert((bool)$params['serverAuthPlugin'], 'wrong serverAuthPlugin value');
498
$this->assert(!(bool)$params['useGlobally'], 'wrong useGlobally value');
499
list ($ret, $authPlugins) =
500
GalleryCoreApi::getAllFactoryImplementationIds('GalleryAuthPlugin');
502
return $this->failWithStatus($ret);
504
$this->assert(!isset($authPlugins['HttpAuthPlugin']), 'HttpAuthPlugin still registerd');
505
$this->assert(isset($authPlugins['ServerAuthPlugin']), 'ServerAuthPlugin not registered');
508
function testSetConfigurationDefaults() {
509
$this->_resetFactory = true;
510
$ret = $this->_authInterface->setConfiguration(true);
512
return $this->failWithStatus($ret);
515
list ($ret, $params) = GalleryCoreApi::fetchAllPluginParameters('module', 'httpauth');
517
return $this->failWithStatus($ret);
520
$this->assert((bool)$params['httpAuthPlugin'], 'wrong httpAuthPlugin value');
521
$this->assert(!(bool)$params['serverAuthPlugin'], 'wrong serverAuthPlugin value');
522
$this->assert(!(bool)$params['useGlobally'], 'wrong useGlobally value');
525
function testRequestAuthentication() {
526
$ret = GalleryCoreApi::setPluginParameter('module', 'httpauth', 'useGlobally', false);
528
return $this->failWithStatus($ret);
531
$ret = $this->_authInterface->requestAuthentication();
533
return $this->failWithStatus($ret);
536
$this->assertEquals(array('status' => 'HTTP/1.0 401 Unauthorized',
537
'www-authenticate' => "WWW-Authenticate: Basic realm='TEST_AUTH_NAME'"),
541
function testRequestAuthenticationDoNotIgnoreUseGloballyFlag() {
542
$ret = GalleryCoreApi::setPluginParameter('module', 'httpauth', 'useGlobally', false);
544
return $this->failWithStatus($ret);
547
$ret = HttpAuthHelper::requestAuthentication(false);
549
return $this->failWithStatus($ret);
552
$this->assertEquals(array(), $this->_headers);
555
function testRequestAuthenticationIgnoredIfHttpAuthNotEnabled() {
556
foreach (array('httpAuthPlugin' => false, 'serverAuthPlugin' => true) as $key => $value) {
557
$ret = GalleryCoreApi::setPluginParameter('module', 'httpauth', $key, $value);
559
return $this->failWithStatus($ret);
563
$ret = HttpAuthHelper::requestAuthentication();
565
return $this->failWithStatus($ret);
568
$this->assertEquals(array(), $this->_headers);
571
function testRequestAuthenticationAlsoSentWhenAlreadyLoggedIn() {
572
$this->_becomeGuestUser();
574
$ret = HttpAuthHelper::requestAuthentication();
576
return $this->failWithStatus($ret);
579
$this->assertEquals(array('status' => 'HTTP/1.0 401 Unauthorized',
580
'www-authenticate' => "WWW-Authenticate: Basic realm='TEST_AUTH_NAME'"),
584
function testRegenerateSessionIfNecessary() {
586
$gallery->_session = new HttpAuthHelperTestSession();
588
$ret = HttpAuthHelper::regenerateSessionIfNecessary($this->_user);
590
return $this->failWithStatus($ret);
593
$this->assert($gallery->_session->regenerateWasCalled());
596
function testRegenerateSessionIfNecessarySameUserAsFromSession() {
598
$gallery->_session = new HttpAuthHelperTestSession($this->_user->getId());
600
$ret = HttpAuthHelper::regenerateSessionIfNecessary($this->_user);
602
return $this->failWithStatus($ret);
605
$this->assert(!$gallery->_session->regenerateWasCalled());
608
function testRegenerateSessionIfNecessaryOtherUserThanFromSession() {
610
$gallery->_session = new HttpAuthHelperTestSession('OTHER_USER');
612
$ret = HttpAuthHelper::regenerateSessionIfNecessary($this->_user);
614
return $this->failWithStatus($ret);
617
$this->assert($gallery->_session->regenerateWasCalled());
620
function testRegenerateSessionIfNecessaryNoAuthenticatedUser() {
622
$gallery->_session = new HttpAuthHelperTestSession($this->_user->getId());
624
$ret = HttpAuthHelper::regenerateSessionIfNecessary(null);
626
return $this->failWithStatus($ret);
629
$this->assert(!$gallery->_session->regenerateWasCalled());
633
class HttpAuthHelperTestRewriteApi {
636
function &_fetchActiveRulesForModule($moduleId) {
641
function &_getParserType() {
646
function isCompatibleWithApi($version) {
647
return array(null, true);
650
function fetchActiveRulesForModule($moduleId) {
651
return array(null, HttpAuthHelperTestRewriteApi::_fetchActiveRulesForModule($moduleId));
654
function getParserType() {
655
return HttpAuthHelperTestRewriteApi::_getParserType();
659
class HttpAuthHelperTestPlatform extends GalleryPlatform {
663
function fsockopen($target, $port, &$errno, &$errstr, $timeout) {
667
function feof($handle) {
668
return empty($this->_buffer);
671
function fgets($handle, $length) {
672
if (empty($this->_buffer)) {
676
if (strpos($this->_buffer, "\n") < $length) {
677
$length = strpos($this->_buffer, "\n") + 1;
680
return $this->fread($handle, $length);
683
function fread($handle, $length) {
684
if (empty($this->_buffer)) {
688
$buffer = substr($this->_buffer, 0, $length);
689
$this->_buffer = substr($this->_buffer, $length);
693
function fwrite($handle, $string, $length=0) {
694
if (isset($this->_messages[$string])) {
695
$this->_buffer = $this->_messages[$string];
696
return strlen($string);
698
print "unexpected fwrite: $string ";
702
function fflush($handle) {
706
function fclose($handle) {
711
class HttpAuthHelperTestPhpVm extends GalleryPhpVm {
712
function header($header, $replace=null) {
713
/* Avoid modifying actual header information */
717
class HttpAuthHelperTestSession {
718
function HttpAuthHelperTestSession($userId=null) {
719
$this->_userId = $userId;
720
$this->_regenerateWasCalled = false;
723
function getUserId() {
724
return $this->_userId;
727
function regenerate() {
728
$this->_regenerateWasCalled = true;
731
function regenerateWasCalled() {
732
return $this->_regenerateWasCalled;