auth = m::mock(AuthManager::class); $this->encrypter = m::mock(Encrypter::class); $this->repository = m::mock(ApiKeyRepositoryInterface::class); } /** * Test that a missing bearer token will throw an exception. */ public function testMissingBearerTokenThrowsException() { $this->request->shouldReceive('bearerToken')->withNoArgs()->once()->andReturnNull(); try { $this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); } catch (HttpException $exception) { $this->assertEquals(401, $exception->getStatusCode()); $this->assertEquals(['WWW-Authenticate' => 'Bearer'], $exception->getHeaders()); } } /** * Test that an invalid API identifer throws an exception. * * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function testInvalidIdentifier() { $this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn('abcd1234'); $this->repository->shouldReceive('findFirstWhere')->andThrow(new RecordNotFoundException); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); } /** * Test that a valid token can continue past the middleware. */ public function testValidToken() { $model = factory(ApiKey::class)->make(); $this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'decrypted'); $this->repository->shouldReceive('findFirstWhere')->with([['identifier', '=', $model->identifier]])->once()->andReturn($model); $this->encrypter->shouldReceive('decrypt')->with($model->token)->once()->andReturn('decrypted'); $this->auth->shouldReceive('guard->loginUsingId')->with($model->user_id)->once()->andReturnNull(); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); $this->assertEquals($model, $this->request->attributes->get('api_key')); } /** * Test that a valid token identifier with an invalid token attached to it * triggers an exception. * * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function testInvalidTokenForIdentifier() { $model = factory(ApiKey::class)->make(); $this->request->shouldReceive('bearerToken')->withNoArgs()->twice()->andReturn($model->identifier . 'asdf'); $this->repository->shouldReceive('findFirstWhere')->with([['identifier', '=', $model->identifier]])->once()->andReturn($model); $this->encrypter->shouldReceive('decrypt')->with($model->token)->once()->andReturn('decrypted'); $this->getMiddleware()->handle($this->request, $this->getClosureAssertions()); } /** * Return an instance of the middleware with mocked dependencies for testing. * * @return \Pterodactyl\Http\Middleware\Api\Admin\AuthenticateKey */ private function getMiddleware(): AuthenticateKey { return new AuthenticateKey($this->repository, $this->auth, $this->encrypter); } }