public function testBasics()
 {
     $anonInfo = UserInfo::newAnonymous();
     $userInfo = UserInfo::newFromName('UTSysop', true);
     $unverifiedUserInfo = UserInfo::newFromName('UTSysop', false);
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY - 1, []);
         $this->fail('Expected exception not thrown', 'priority < min');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid priority', $ex->getMessage(), 'priority < min');
     }
     try {
         new SessionInfo(SessionInfo::MAX_PRIORITY + 1, []);
         $this->fail('Expected exception not thrown', 'priority > max');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid priority', $ex->getMessage(), 'priority > max');
     }
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY, ['id' => 'ABC?']);
         $this->fail('Expected exception not thrown', 'bad session ID');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid session ID', $ex->getMessage(), 'bad session ID');
     }
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY, ['userInfo' => new \stdClass()]);
         $this->fail('Expected exception not thrown', 'bad userInfo');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid userInfo', $ex->getMessage(), 'bad userInfo');
     }
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY, []);
         $this->fail('Expected exception not thrown', 'no provider, no id');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Must supply an ID when no provider is given', $ex->getMessage(), 'no provider, no id');
     }
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY, ['copyFrom' => new \stdClass()]);
         $this->fail('Expected exception not thrown', 'bad copyFrom');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid copyFrom', $ex->getMessage(), 'bad copyFrom');
     }
     $manager = new SessionManager();
     $provider = $this->getMockBuilder(SessionProvider::class)->setMethods(['persistsSessionId', 'canChangeUser', '__toString'])->getMockForAbstractClass();
     $provider->setManager($manager);
     $provider->expects($this->any())->method('persistsSessionId')->will($this->returnValue(true));
     $provider->expects($this->any())->method('canChangeUser')->will($this->returnValue(true));
     $provider->expects($this->any())->method('__toString')->will($this->returnValue('Mock'));
     $provider2 = $this->getMockBuilder(SessionProvider::class)->setMethods(['persistsSessionId', 'canChangeUser', '__toString'])->getMockForAbstractClass();
     $provider2->setManager($manager);
     $provider2->expects($this->any())->method('persistsSessionId')->will($this->returnValue(true));
     $provider2->expects($this->any())->method('canChangeUser')->will($this->returnValue(true));
     $provider2->expects($this->any())->method('__toString')->will($this->returnValue('Mock2'));
     try {
         new SessionInfo(SessionInfo::MIN_PRIORITY, ['provider' => $provider, 'userInfo' => $anonInfo, 'metadata' => 'foo']);
         $this->fail('Expected exception not thrown', 'bad metadata');
     } catch (\InvalidArgumentException $ex) {
         $this->assertSame('Invalid metadata', $ex->getMessage(), 'bad metadata');
     }
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'userInfo' => $anonInfo]);
     $this->assertSame($provider, $info->getProvider());
     $this->assertNotNull($info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($anonInfo, $info->getUserInfo());
     $this->assertTrue($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertFalse($info->wasPersisted());
     $this->assertFalse($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'userInfo' => $unverifiedUserInfo, 'metadata' => ['Foo']]);
     $this->assertSame($provider, $info->getProvider());
     $this->assertNotNull($info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($unverifiedUserInfo, $info->getUserInfo());
     $this->assertTrue($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertFalse($info->wasPersisted());
     $this->assertFalse($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertSame(['Foo'], $info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'userInfo' => $userInfo]);
     $this->assertSame($provider, $info->getProvider());
     $this->assertNotNull($info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($userInfo, $info->getUserInfo());
     $this->assertTrue($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertFalse($info->wasPersisted());
     $this->assertTrue($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $id = $manager->generateSessionId();
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'persisted' => true, 'userInfo' => $anonInfo]);
     $this->assertSame($provider, $info->getProvider());
     $this->assertSame($id, $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($anonInfo, $info->getUserInfo());
     $this->assertFalse($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertTrue($info->wasPersisted());
     $this->assertFalse($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'userInfo' => $userInfo]);
     $this->assertSame($provider, $info->getProvider());
     $this->assertSame($id, $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($userInfo, $info->getUserInfo());
     $this->assertFalse($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertFalse($info->wasPersisted());
     $this->assertTrue($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['id' => $id, 'persisted' => true, 'userInfo' => $userInfo, 'metadata' => ['Foo']]);
     $this->assertSame($id, $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertSame($userInfo, $info->getUserInfo());
     $this->assertFalse($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertTrue($info->wasPersisted());
     $this->assertFalse($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['id' => $id, 'remembered' => true, 'userInfo' => $userInfo]);
     $this->assertFalse($info->wasRemembered(), 'no provider');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'remembered' => true]);
     $this->assertFalse($info->wasRemembered(), 'no user');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'remembered' => true, 'userInfo' => $anonInfo]);
     $this->assertFalse($info->wasRemembered(), 'anonymous user');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'remembered' => true, 'userInfo' => $unverifiedUserInfo]);
     $this->assertFalse($info->wasRemembered(), 'unverified user');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'remembered' => false, 'userInfo' => $userInfo]);
     $this->assertFalse($info->wasRemembered(), 'specific override');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['id' => $id, 'idIsSafe' => true]);
     $this->assertSame($id, $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 5, $info->getPriority());
     $this->assertTrue($info->isIdSafe());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['id' => $id, 'forceUse' => true]);
     $this->assertFalse($info->forceUse(), 'no provider');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'forceUse' => true]);
     $this->assertFalse($info->forceUse(), 'no id');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 5, ['provider' => $provider, 'id' => $id, 'forceUse' => true]);
     $this->assertTrue($info->forceUse(), 'correct use');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY, ['id' => $id, 'forceHTTPS' => 1]);
     $this->assertTrue($info->forceHTTPS());
     $fromInfo = new SessionInfo(SessionInfo::MIN_PRIORITY, ['id' => $id . 'A', 'provider' => $provider, 'userInfo' => $userInfo, 'idIsSafe' => true, 'forceUse' => true, 'persisted' => true, 'remembered' => true, 'forceHTTPS' => true, 'metadata' => ['foo!']]);
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 4, ['copyFrom' => $fromInfo]);
     $this->assertSame($id . 'A', $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 4, $info->getPriority());
     $this->assertSame($provider, $info->getProvider());
     $this->assertSame($userInfo, $info->getUserInfo());
     $this->assertTrue($info->isIdSafe());
     $this->assertTrue($info->forceUse());
     $this->assertTrue($info->wasPersisted());
     $this->assertTrue($info->wasRemembered());
     $this->assertTrue($info->forceHTTPS());
     $this->assertSame(['foo!'], $info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY + 4, ['id' => $id . 'X', 'provider' => $provider2, 'userInfo' => $unverifiedUserInfo, 'idIsSafe' => false, 'forceUse' => false, 'persisted' => false, 'remembered' => false, 'forceHTTPS' => false, 'metadata' => null, 'copyFrom' => $fromInfo]);
     $this->assertSame($id . 'X', $info->getId());
     $this->assertSame(SessionInfo::MIN_PRIORITY + 4, $info->getPriority());
     $this->assertSame($provider2, $info->getProvider());
     $this->assertSame($unverifiedUserInfo, $info->getUserInfo());
     $this->assertFalse($info->isIdSafe());
     $this->assertFalse($info->forceUse());
     $this->assertFalse($info->wasPersisted());
     $this->assertFalse($info->wasRemembered());
     $this->assertFalse($info->forceHTTPS());
     $this->assertNull($info->getProviderMetadata());
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY, ['id' => $id]);
     $this->assertSame('[' . SessionInfo::MIN_PRIORITY . "]null<null>{$id}", (string) $info, 'toString');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY, ['provider' => $provider, 'id' => $id, 'persisted' => true, 'userInfo' => $userInfo]);
     $this->assertSame('[' . SessionInfo::MIN_PRIORITY . "]Mock<+:{$userInfo->getId()}:UTSysop>{$id}", (string) $info, 'toString');
     $info = new SessionInfo(SessionInfo::MIN_PRIORITY, ['provider' => $provider, 'id' => $id, 'persisted' => true, 'userInfo' => $unverifiedUserInfo]);
     $this->assertSame('[' . SessionInfo::MIN_PRIORITY . "]Mock<-:{$userInfo->getId()}:UTSysop>{$id}", (string) $info, 'toString');
 }
Beispiel #2
0
 /**
  * Load and verify the session info against the store
  *
  * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
  * @param WebRequest $request
  * @return bool Whether the session info matches the stored data (if any)
  */
 private function loadSessionInfoFromStore(SessionInfo &$info, WebRequest $request)
 {
     $key = wfMemcKey('MWSession', $info->getId());
     $blob = $this->store->get($key);
     // If we got data from the store and the SessionInfo says to force use,
     // "fail" means to delete the data from the store and retry. Otherwise,
     // "fail" is just return false.
     if ($info->forceUse() && $blob !== false) {
         $failHandler = function () use($key, &$info, $request) {
             $this->store->delete($key);
             return $this->loadSessionInfoFromStore($info, $request);
         };
     } else {
         $failHandler = function () {
             return false;
         };
     }
     $newParams = [];
     if ($blob !== false) {
         // Sanity check: blob must be an array, if it's saved at all
         if (!is_array($blob)) {
             $this->logger->warning('Session "{session}": Bad data', ['session' => $info]);
             $this->store->delete($key);
             return $failHandler();
         }
         // Sanity check: blob has data and metadata arrays
         if (!isset($blob['data']) || !is_array($blob['data']) || !isset($blob['metadata']) || !is_array($blob['metadata'])) {
             $this->logger->warning('Session "{session}": Bad data structure', ['session' => $info]);
             $this->store->delete($key);
             return $failHandler();
         }
         $data = $blob['data'];
         $metadata = $blob['metadata'];
         // Sanity check: metadata must be an array and must contain certain
         // keys, if it's saved at all
         if (!array_key_exists('userId', $metadata) || !array_key_exists('userName', $metadata) || !array_key_exists('userToken', $metadata) || !array_key_exists('provider', $metadata)) {
             $this->logger->warning('Session "{session}": Bad metadata', ['session' => $info]);
             $this->store->delete($key);
             return $failHandler();
         }
         // First, load the provider from metadata, or validate it against the metadata.
         $provider = $info->getProvider();
         if ($provider === null) {
             $newParams['provider'] = $provider = $this->getProvider($metadata['provider']);
             if (!$provider) {
                 $this->logger->warning('Session "{session}": Unknown provider ' . $metadata['provider'], ['session' => $info]);
                 $this->store->delete($key);
                 return $failHandler();
             }
         } elseif ($metadata['provider'] !== (string) $provider) {
             $this->logger->warning('Session "{session}": Wrong provider ' . $metadata['provider'] . ' !== ' . $provider, ['session' => $info]);
             return $failHandler();
         }
         // Load provider metadata from metadata, or validate it against the metadata
         $providerMetadata = $info->getProviderMetadata();
         if (isset($metadata['providerMetadata'])) {
             if ($providerMetadata === null) {
                 $newParams['metadata'] = $metadata['providerMetadata'];
             } else {
                 try {
                     $newProviderMetadata = $provider->mergeMetadata($metadata['providerMetadata'], $providerMetadata);
                     if ($newProviderMetadata !== $providerMetadata) {
                         $newParams['metadata'] = $newProviderMetadata;
                     }
                 } catch (MetadataMergeException $ex) {
                     $this->logger->warning('Session "{session}": Metadata merge failed: {exception}', ['session' => $info, 'exception' => $ex] + $ex->getContext());
                     return $failHandler();
                 }
             }
         }
         // Next, load the user from metadata, or validate it against the metadata.
         $userInfo = $info->getUserInfo();
         if (!$userInfo) {
             // For loading, id is preferred to name.
             try {
                 if ($metadata['userId']) {
                     $userInfo = UserInfo::newFromId($metadata['userId']);
                 } elseif ($metadata['userName'] !== null) {
                     // Shouldn't happen, but just in case
                     $userInfo = UserInfo::newFromName($metadata['userName']);
                 } else {
                     $userInfo = UserInfo::newAnonymous();
                 }
             } catch (\InvalidArgumentException $ex) {
                 $this->logger->error('Session "{session}": {exception}', ['session' => $info, 'exception' => $ex]);
                 return $failHandler();
             }
             $newParams['userInfo'] = $userInfo;
         } else {
             // User validation passes if user ID matches, or if there
             // is no saved ID and the names match.
             if ($metadata['userId']) {
                 if ($metadata['userId'] !== $userInfo->getId()) {
                     $this->logger->warning('Session "{session}": User ID mismatch, {uid_a} !== {uid_b}', ['session' => $info, 'uid_a' => $metadata['userId'], 'uid_b' => $userInfo->getId()]);
                     return $failHandler();
                 }
                 // If the user was renamed, probably best to fail here.
                 if ($metadata['userName'] !== null && $userInfo->getName() !== $metadata['userName']) {
                     $this->logger->warning('Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}', ['session' => $info, 'uname_a' => $metadata['userName'], 'uname_b' => $userInfo->getName()]);
                     return $failHandler();
                 }
             } elseif ($metadata['userName'] !== null) {
                 // Shouldn't happen, but just in case
                 if ($metadata['userName'] !== $userInfo->getName()) {
                     $this->logger->warning('Session "{session}": User name mismatch, {uname_a} !== {uname_b}', ['session' => $info, 'uname_a' => $metadata['userName'], 'uname_b' => $userInfo->getName()]);
                     return $failHandler();
                 }
             } elseif (!$userInfo->isAnon()) {
                 // Metadata specifies an anonymous user, but the passed-in
                 // user isn't anonymous.
                 $this->logger->warning('Session "{session}": Metadata has an anonymous user, but a non-anon user was provided', ['session' => $info]);
                 return $failHandler();
             }
         }
         // And if we have a token in the metadata, it must match the loaded/provided user.
         if ($metadata['userToken'] !== null && $userInfo->getToken() !== $metadata['userToken']) {
             $this->logger->warning('Session "{session}": User token mismatch', ['session' => $info]);
             return $failHandler();
         }
         if (!$userInfo->isVerified()) {
             $newParams['userInfo'] = $userInfo->verified();
         }
         if (!empty($metadata['remember']) && !$info->wasRemembered()) {
             $newParams['remembered'] = true;
         }
         if (!empty($metadata['forceHTTPS']) && !$info->forceHTTPS()) {
             $newParams['forceHTTPS'] = true;
         }
         if (!empty($metadata['persisted']) && !$info->wasPersisted()) {
             $newParams['persisted'] = true;
         }
         if (!$info->isIdSafe()) {
             $newParams['idIsSafe'] = true;
         }
     } else {
         // No metadata, so we can't load the provider if one wasn't given.
         if ($info->getProvider() === null) {
             $this->logger->warning('Session "{session}": Null provider and no metadata', ['session' => $info]);
             return $failHandler();
         }
         // If no user was provided and no metadata, it must be anon.
         if (!$info->getUserInfo()) {
             if ($info->getProvider()->canChangeUser()) {
                 $newParams['userInfo'] = UserInfo::newAnonymous();
             } else {
                 $this->logger->info('Session "{session}": No user provided and provider cannot set user', ['session' => $info]);
                 return $failHandler();
             }
         } elseif (!$info->getUserInfo()->isVerified()) {
             $this->logger->warning('Session "{session}": Unverified user provided and no metadata to auth it', ['session' => $info]);
             return $failHandler();
         }
         $data = false;
         $metadata = false;
         if (!$info->getProvider()->persistsSessionId() && !$info->isIdSafe()) {
             // The ID doesn't come from the user, so it should be safe
             // (and if not, nothing we can do about it anyway)
             $newParams['idIsSafe'] = true;
         }
     }
     // Construct the replacement SessionInfo, if necessary
     if ($newParams) {
         $newParams['copyFrom'] = $info;
         $info = new SessionInfo($info->getPriority(), $newParams);
     }
     // Allow the provider to check the loaded SessionInfo
     $providerMetadata = $info->getProviderMetadata();
     if (!$info->getProvider()->refreshSessionInfo($info, $request, $providerMetadata)) {
         return $failHandler();
     }
     if ($providerMetadata !== $info->getProviderMetadata()) {
         $info = new SessionInfo($info->getPriority(), ['metadata' => $providerMetadata, 'copyFrom' => $info]);
     }
     // Give hooks a chance to abort. Combined with the SessionMetadata
     // hook, this can allow for tying a session to an IP address or the
     // like.
     $reason = 'Hook aborted';
     if (!\Hooks::run('SessionCheckInfo', [&$reason, $info, $request, $metadata, $data])) {
         $this->logger->warning('Session "{session}": ' . $reason, ['session' => $info]);
         return $failHandler();
     }
     return true;
 }