/** * @test */ public function buildResponseIfApplicableRetunsHttpRequestIfApplicableRedirectIsFound() { $this->mockHttpRequest->expects($this->atLeastOnce())->method('getRelativePath')->willReturn('some/relative/path'); $mockRedirect = $this->getMockBuilder(Redirect::class)->disableOriginalConstructor()->getMock(); $mockRedirect->expects($this->atLeastOnce())->method('getStatusCode')->willReturn(301); $this->mockRedirectStorage->expects($this->once())->method('getOneBySourceUriPathAndHost')->with('some/relative/path')->willReturn($mockRedirect); $this->inject($this->redirectService, 'redirectStorage', $this->mockRedirectStorage); $request = $this->redirectService->buildResponseIfApplicable($this->mockHttpRequest); $this->assertInstanceOf(Response::class, $request); }
/** * Extracts the WidgetContext from the given $httpRequest. * If the request contains an argument "__widgetId" the context is fetched from the session (AjaxWidgetContextHolder). * Otherwise the argument "__widgetContext" is expected to contain the serialized WidgetContext (protected by a HMAC suffix) * * @param Request $httpRequest * @return WidgetContext */ protected function extractWidgetContext(Request $httpRequest) { if ($httpRequest->hasArgument('__widgetId')) { return $this->ajaxWidgetContextHolder->get($httpRequest->getArgument('__widgetId')); } elseif ($httpRequest->hasArgument('__widgetContext')) { $serializedWidgetContextWithHmac = $httpRequest->getArgument('__widgetContext'); $serializedWidgetContext = $this->hashService->validateAndStripHmac($serializedWidgetContextWithHmac); return unserialize(base64_decode($serializedWidgetContext)); } return null; }
public function setUp() { $this->fileSystemTarget = new FileSystemTarget('test'); $this->mockBootstrap = $this->getMockBuilder(Bootstrap::class)->disableOriginalConstructor()->getMock(); $this->mockRequestHandler = $this->createMock(HttpRequestHandlerInterface::class); $this->mockHttpRequest = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock(); $this->mockHttpRequest->expects($this->any())->method('getBaseUri')->will($this->returnValue(new Uri('http://detected/base/uri/'))); $this->mockRequestHandler->expects($this->any())->method('getHttpRequest')->will($this->returnValue($this->mockHttpRequest)); $this->mockBootstrap->expects($this->any())->method('getActiveRequestHandler')->will($this->returnValue($this->mockRequestHandler)); $this->inject($this->fileSystemTarget, 'bootstrap', $this->mockBootstrap); }
/** * @return void */ public function setUp() { $this->viewHelperVariableContainer = $this->createMock(\TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperVariableContainer::class); $this->viewHelperVariableContainer->expects($this->any())->method('exists')->will($this->returnCallback(array($this, 'viewHelperVariableContainerExistsCallback'))); $this->viewHelperVariableContainer->expects($this->any())->method('get')->will($this->returnCallback(array($this, 'viewHelperVariableContainerGetCallback'))); $this->templateVariableContainer = $this->createMock(TemplateVariableContainer::class); $this->uriBuilder = $this->createMock(\Neos\Flow\Mvc\Routing\UriBuilder::class); $this->uriBuilder->expects($this->any())->method('reset')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setArguments')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setSection')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setFormat')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setCreateAbsoluteUri')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setAddQueryString')->will($this->returnValue($this->uriBuilder)); $this->uriBuilder->expects($this->any())->method('setArgumentsToBeExcludedFromQueryString')->will($this->returnValue($this->uriBuilder)); // BACKPORTER TOKEN #1 $httpRequest = \Neos\Flow\Http\Request::create(new \Neos\Flow\Http\Uri('http://localhost/foo')); $this->request = $this->getMockBuilder(\Neos\Flow\Mvc\ActionRequest::class)->setConstructorArgs(array($httpRequest))->getMock(); $this->request->expects($this->any())->method('isMainRequest')->will($this->returnValue(true)); $this->controllerContext = $this->getMockBuilder(\Neos\Flow\Mvc\Controller\ControllerContext::class)->disableOriginalConstructor()->getMock(); $this->controllerContext->expects($this->any())->method('getUriBuilder')->will($this->returnValue($this->uriBuilder)); $this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($this->request)); $this->tagBuilder = $this->createMock(TagBuilder::class); $this->arguments = array(); $this->renderingContext = new \Neos\FluidAdaptor\Core\Rendering\RenderingContext(new StandaloneView(), []); $this->renderingContext->setVariableProvider($this->templateVariableContainer); $this->renderingContext->setViewHelperVariableContainer($this->viewHelperVariableContainer); $this->renderingContext->setControllerContext($this->controllerContext); }
/** * @test */ public function updateCredentialsSetsTheCorrectAuthenticationStatusIfNoCredentialsArrived() { $httpRequest = Request::create(new Uri('http://foo.com')); $mockActionRequest = $this->getMockBuilder(ActionRequest::class)->disableOriginalConstructor()->getMock(); $mockActionRequest->expects($this->atLeastOnce())->method('getHttpRequest')->will($this->returnValue($httpRequest)); $this->token->updateCredentials($mockActionRequest); $this->assertSame(TokenInterface::NO_CREDENTIALS_GIVEN, $this->token->getAuthenticationStatus()); }
/** * @test */ public function handleMergesInternalArgumentsWithRoutingMatchResults() { $this->mockHttpRequest->expects($this->any())->method('getArguments')->will($this->returnValue(['__internalArgument1' => 'request', '__internalArgument2' => 'request', '__internalArgument3' => 'request'])); $this->mockHttpRequest->expects(self::any())->method('getContent')->willReturn('requestBody'); $this->mockPropertyMapper->expects($this->any())->method('convert')->will($this->returnValue(['__internalArgument2' => 'requestBody', '__internalArgument3' => 'requestBody'])); $this->mockComponentContext->expects($this->atLeastOnce())->method('getParameter')->with(RoutingComponent::class, 'matchResults')->will($this->returnValue(['__internalArgument3' => 'routing'])); $this->mockActionRequest->expects($this->once())->method('setArguments')->with(['__internalArgument1' => 'request', '__internalArgument2' => 'requestBody', '__internalArgument3' => 'routing']); $this->dispatchComponent->handle($this->mockComponentContext); }
/** * Create a mock controllerContext * * @return \PHPUnit_Framework_MockObject_MockObject */ protected function getMockControllerContext() { $httpRequest = Request::create(new Uri('http://robertlemke.com/blog')); $mockRequest = $this->getMockBuilder(\Neos\Flow\Mvc\ActionRequest::class)->setConstructorArgs(array($httpRequest))->getMock(); $mockRequest->expects($this->any())->method('getControllerPackageKey')->will($this->returnValue('Acme.Demo')); $mockControllerContext = $this->getMockBuilder(\Neos\Flow\Mvc\Controller\ControllerContext::class)->setMethods(array('getRequest'))->disableOriginalConstructor()->getMock(); $mockControllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($mockRequest)); return $mockControllerContext; }
/** * @return ControllerContext */ protected function createControllerContextFromEnvironment() { $httpRequest = Request::createFromEnvironment(); /** @var ActionRequest $request */ $request = new ActionRequest($httpRequest); $uriBuilder = new UriBuilder(); $uriBuilder->setRequest($request); return new ControllerContext($request, new Response(), new Arguments(array()), $uriBuilder); }
/** * @test */ public function tokenCanBeCastToString() { $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = '******'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = '******'; $this->mockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('POST')); $this->mockActionRequest->expects($this->atLeastOnce())->method('getInternalArguments')->will($this->returnValue($arguments)); $this->token->updateCredentials($this->mockActionRequest); $this->assertEquals('Username: "******"', (string) $this->token); }
/** * @test */ public function buildDoesNotPrependsScriptRequestPathIfCreateRelativePathsCompatibilityFlagIsTrue() { $this->mockHttpRequest->expects($this->never())->method('getScriptRequestPath'); $this->mockRouter->expects($this->once())->method('resolve')->will($this->returnValue('resolvedUri')); $this->uriBuilder->setCreateAbsoluteUri(false); $this->uriBuilder->setCreateRelativePaths(true); $expectedResult = 'resolvedUri'; $actualResult = $this->uriBuilder->build(); $this->assertEquals($expectedResult, $actualResult); }
/** * @test */ public function actionRequestDoesNotStripParentActionRequest() { $httpRequest = Request::create(new Uri('http://neos.io')); $parentActionRequest = new ActionRequest($httpRequest); $actionRequest = new ActionRequest($parentActionRequest); $serializedActionRequest = serialize($actionRequest); /* @var $unserializedActionRequest ActionRequest */ $unserializedActionRequest = unserialize($serializedActionRequest); $this->assertNotNull($unserializedActionRequest->getParentRequest(), 'Parent action request should not be NULL after deserialization'); }
/** * @test */ public function renderEscapesBaseUri() { $baseUri = new Uri('<some nasty uri>'); $this->request->expects($this->any())->method('getHttpRequest')->will($this->returnValue(Request::create($baseUri))); $viewHelper = new BaseViewHelper(); $this->injectDependenciesIntoViewHelper($viewHelper); $expectedResult = '<base href="http://' . htmlspecialchars($baseUri) . '/" />'; $actualResult = $viewHelper->render(); $this->assertSame($expectedResult, $actualResult); }
/** * @test */ public function initializeControllerInitializesRequestUriBuilderArgumentsAndContext() { $request = new ActionRequest(Request::create(new Uri('http://localhost/foo'))); $controller = $this->getAccessibleMock(AbstractController::class, ['processRequest']); $this->inject($controller, 'flashMessageContainer', new FlashMessageContainer()); $this->assertFalse($request->isDispatched()); $controller->_call('initializeController', $request, $this->mockHttpResponse); $this->assertTrue($request->isDispatched()); $this->assertInstanceOf(Arguments::class, $controller->_get('arguments')); $this->assertSame($request, $controller->_get('uriBuilder')->getRequest()); $this->assertSame($request, $controller->getControllerContext()->getRequest()); }
/** * @test */ public function extractWidgetContextDecodesSerializedWidgetContextIfPresent() { $ajaxWidgetComponent = $this->getAccessibleMock(\Neos\FluidAdaptor\Core\Widget\AjaxWidgetComponent::class, array('dummy')); $this->inject($ajaxWidgetComponent, 'hashService', $this->mockHashService); $mockWidgetContext = 'SomeWidgetContext'; $mockSerializedWidgetContext = base64_encode(serialize($mockWidgetContext)); $mockSerializedWidgetContextWithHmac = $mockSerializedWidgetContext . 'HMAC'; $this->mockHttpRequest->expects($this->at(0))->method('hasArgument')->with('__widgetId')->will($this->returnValue(false)); $this->mockHttpRequest->expects($this->at(1))->method('hasArgument')->with('__widgetContext')->will($this->returnValue(true)); $this->mockHttpRequest->expects($this->atLeastOnce())->method('getArgument')->with('__widgetContext')->will($this->returnValue($mockSerializedWidgetContextWithHmac)); $this->mockHashService->expects($this->atLeastOnce())->method('validateAndStripHmac')->with($mockSerializedWidgetContextWithHmac)->will($this->returnValue($mockSerializedWidgetContext)); $actualResult = $ajaxWidgetComponent->_call('extractWidgetContext', $this->mockHttpRequest); $this->assertEquals($mockWidgetContext, $actualResult); }
/** * Starts the authentication: Redirect to login page * * @param Request $request The current request * @param Response $response The current response * @return void * @throws MissingConfigurationException */ public function startAuthentication(Request $request, Response $response) { if (isset($this->options['routeValues'])) { $routeValues = $this->options['routeValues']; if (!is_array($routeValues)) { throw new MissingConfigurationException(sprintf('The configuration for the WebRedirect authentication entry point is incorrect. "routeValues" must be an array, got "%s".', gettype($routeValues)), 1345040415); } $actionRequest = new ActionRequest($request); $this->uriBuilder->setRequest($actionRequest); $actionName = $this->extractRouteValue($routeValues, '@action'); $controllerName = $this->extractRouteValue($routeValues, '@controller'); $packageKey = $this->extractRouteValue($routeValues, '@package'); $subPackageKey = $this->extractRouteValue($routeValues, '@subpackage'); $uri = $this->uriBuilder->setCreateAbsoluteUri(true)->uriFor($actionName, $routeValues, $controllerName, $packageKey, $subPackageKey); } elseif (isset($this->options['uri'])) { $uri = strpos($this->options['uri'], '://') !== false ? $this->options['uri'] : $request->getBaseUri() . $this->options['uri']; } else { throw new MissingConfigurationException('The configuration for the WebRedirect authentication entry point is incorrect or missing. You need to specify either the target "uri" or "routeValues".', 1237282583); } $response->setContent(sprintf('<html><head><meta http-equiv="refresh" content="0;url=%s"/></head></html>', htmlentities($uri, ENT_QUOTES, 'utf-8'))); $response->setStatus(303); $response->setHeader('Location', $uri); }
/** * @test */ public function startAuthenticationSetsTheCorrectValuesInTheResponseObjectIfRouteValuesAreSpecified() { $request = Request::create(new Uri('http://robertlemke.com/admin')); $response = new Response(); $entryPoint = $this->getAccessibleMock(WebRedirect::class, ['dummy']); $routeValues = ['@package' => 'SomePackage', '@subpackage' => 'SomeSubPackage', '@controller' => 'SomeController', '@action' => 'someAction', '@format' => 'someFormat', 'otherArguments' => ['foo' => 'bar']]; $entryPoint->setOptions(['routeValues' => $routeValues]); $mockUriBuilder = $this->createMock(UriBuilder::class); $mockUriBuilder->expects($this->once())->method('setCreateAbsoluteUri')->with(true)->will($this->returnValue($mockUriBuilder)); $mockUriBuilder->expects($this->once())->method('uriFor')->with('someAction', ['otherArguments' => ['foo' => 'bar'], '@format' => 'someFormat'], 'SomeController', 'SomePackage', 'SomeSubPackage')->will($this->returnValue('http://resolved/redirect/uri')); $entryPoint->_set('uriBuilder', $mockUriBuilder); $entryPoint->startAuthentication($request, $response); $this->assertEquals('303', substr($response->getStatus(), 0, 3)); $this->assertEquals('http://resolved/redirect/uri', $response->getHeader('Location')); }
/** * Helper to build a Fusion view object * * @return FusionView */ protected function buildView() { $view = new FusionView(); $httpRequest = Request::createFromEnvironment(); $request = $httpRequest->createActionRequest(); $uriBuilder = new UriBuilder(); $uriBuilder->setRequest($request); $this->controllerContext = new ControllerContext($request, new Response(), new Arguments(array()), $uriBuilder); $view->setControllerContext($this->controllerContext); $view->disableFallbackView(); $view->setPackageKey('Neos.Fusion'); $view->setTypoScriptPathPattern(__DIR__ . '/Fixtures/TypoScript'); $view->assign('fixtureDirectory', __DIR__ . '/Fixtures/'); return $view; }
/** * Helper to build mock controller context needed to test expandGenericPathPattern. * * @param string $packageKey * @param string $subPackageKey * @param string $controllerName * @param string $format * @return ControllerContext */ protected function setupMockControllerContextForPathResolving($packageKey, $subPackageKey, $controllerName, $format) { $controllerObjectName = 'TYPO3\\' . $packageKey . '\\' . ($subPackageKey != $subPackageKey . '\\' ?: '') . 'Controller\\' . $controllerName . 'Controller'; $httpRequest = Request::create(new Uri('http://robertlemke.com/blog')); $mockRequest = $this->createMock(\Neos\Flow\Mvc\ActionRequest::class, array(), array($httpRequest)); $mockRequest->expects($this->any())->method('getControllerPackageKey')->will($this->returnValue($packageKey)); $mockRequest->expects($this->any())->method('getControllerSubPackageKey')->will($this->returnValue($subPackageKey)); $mockRequest->expects($this->any())->method('getControllerName')->will($this->returnValue($controllerName)); $mockRequest->expects($this->any())->method('getControllerObjectName')->will($this->returnValue($controllerObjectName)); $mockRequest->expects($this->any())->method('getFormat')->will($this->returnValue($format)); /** @var $mockControllerContext ControllerContext */ $mockControllerContext = $this->createMock(\Neos\Flow\Mvc\Controller\ControllerContext::class, array('getRequest'), array(), '', false); $mockControllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($mockRequest)); return $mockControllerContext; }
/** * @test */ public function processRequestShouldSetWidgetConfiguration() { /** @var \Neos\Flow\Mvc\ActionRequest $mockActionRequest */ $mockActionRequest = $this->createMock(\Neos\Flow\Mvc\ActionRequest::class); $mockResponse = $this->createMock(\Neos\Flow\Http\Response::class); $httpRequest = Request::create(new Uri('http://localhost')); $mockActionRequest->expects($this->any())->method('getHttpRequest')->will($this->returnValue($httpRequest)); $expectedWidgetConfiguration = array('foo' => uniqid()); $widgetContext = new WidgetContext(); $widgetContext->setAjaxWidgetConfiguration($expectedWidgetConfiguration); $mockActionRequest->expects($this->atLeastOnce())->method('getInternalArgument')->with('__widgetContext')->will($this->returnValue($widgetContext)); $abstractWidgetController = $this->getAccessibleMock(\Neos\FluidAdaptor\Core\Widget\AbstractWidgetController::class, array('resolveActionMethodName', 'initializeActionMethodArguments', 'initializeActionMethodValidators', 'mapRequestArgumentsToControllerArguments', 'detectFormat', 'resolveView', 'callActionMethod')); $abstractWidgetController->_set('mvcPropertyMappingConfigurationService', $this->createMock(\Neos\Flow\Mvc\Controller\MvcPropertyMappingConfigurationService::class)); $abstractWidgetController->processRequest($mockActionRequest, $mockResponse); $actualWidgetConfiguration = $abstractWidgetController->_get('widgetConfiguration'); $this->assertEquals($expectedWidgetConfiguration, $actualWidgetConfiguration); }
/** * Handles a HTTP request * * @return void */ public function handleRequest() { // Create the request very early so the Resource Management has a chance to grab it: $this->request = Request::createFromEnvironment(); $this->response = new Response(); $this->checkBasicRequirementsAndDisplayLoadingScreen(); $this->boot(); $this->resolveDependencies(); if (isset($this->settings['http']['baseUri'])) { $this->request->setBaseUri(new Uri($this->settings['http']['baseUri'])); } $componentContext = new ComponentContext($this->request, $this->response); $this->baseComponentChain->handle($componentContext); $this->response->send(); $this->bootstrap->shutdown('Runtime'); $this->exit->__invoke(); }
/** * @param Request $httpRequest * @param RedirectInterface $redirect * @return Response|null */ protected function buildResponse(Request $httpRequest, RedirectInterface $redirect) { if (headers_sent() === true && FLOW_SAPITYPE !== 'CLI') { return null; } $response = new Response(); $statusCode = $redirect->getStatusCode(); $response->setStatus($statusCode); if ($statusCode >= 300 && $statusCode <= 399) { $location = $redirect->getTargetUriPath(); if (parse_url($location, PHP_URL_SCHEME) === null) { $location = $httpRequest->getBaseUri() . $location; } $response->setHeaders(new Headers(['Location' => $location, 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Expires' => 'Sat, 26 Jul 1997 05:00:00 GMT'])); } elseif ($statusCode >= 400 && $statusCode <= 599) { $exception = new Exception(); $exception->setStatusCode($statusCode); throw $exception; } return $response; }
/** * Sets up this test case */ public function setUp() { $this->routerCachingService = $this->getAccessibleMock(RouterCachingService::class, ['dummy']); $this->mockRouteCache = $this->getMockBuilder(VariableFrontend::class)->disableOriginalConstructor()->getMock(); $this->inject($this->routerCachingService, 'routeCache', $this->mockRouteCache); $this->mockResolveCache = $this->getMockBuilder(StringFrontend::class)->disableOriginalConstructor()->getMock(); $this->inject($this->routerCachingService, 'resolveCache', $this->mockResolveCache); $this->mockPersistenceManager = $this->getMockBuilder(PersistenceManagerInterface::class)->getMock(); $this->inject($this->routerCachingService, 'persistenceManager', $this->mockPersistenceManager); $this->mockSystemLogger = $this->getMockBuilder(SystemLoggerInterface::class)->getMock(); $this->inject($this->routerCachingService, 'systemLogger', $this->mockSystemLogger); $this->mockObjectManager = $this->createMock(ObjectManagerInterface::class); $this->mockApplicationContext = $this->getMockBuilder(ApplicationContext::class)->disableOriginalConstructor()->getMock(); $this->mockObjectManager->expects($this->any())->method('getContext')->will($this->returnValue($this->mockApplicationContext)); $this->inject($this->routerCachingService, 'objectManager', $this->mockObjectManager); $this->inject($this->routerCachingService, 'objectManager', $this->mockObjectManager); $this->mockHttpRequest = $this->getMockBuilder(\Neos\Flow\Http\Request::class)->disableOriginalConstructor()->getMock(); $this->mockHttpRequest->expects($this->any())->method('getMethod')->will($this->returnValue('GET')); $this->mockHttpRequest->expects($this->any())->method('getRelativePath')->will($this->returnValue('some/route/path')); $this->mockUri = $this->getMockBuilder(\Neos\Flow\Http\Uri::class)->disableOriginalConstructor()->getMock(); $this->mockUri->expects($this->any())->method('getHost')->will($this->returnValue('subdomain.domain.com')); $this->mockHttpRequest->expects($this->any())->method('getUri')->will($this->returnValue($this->mockUri)); }
/** * @test */ public function shutdownCreatesSpecialDataEntryForSessionWithAuthenticatedAccounts() { $session = new Session(); $this->inject($session, 'bootstrap', $this->mockBootstrap); $this->inject($session, 'objectManager', $this->mockObjectManager); $this->inject($session, 'settings', $this->settings); $this->inject($session, 'metaDataCache', $this->createCache('Meta')); $this->inject($session, 'storageCache', $this->createCache('Storage')); $session->initializeObject(); $session->start(); $account = new Account(); $account->setAccountIdentifier('admin'); $account->setAuthenticationProviderName('MyProvider'); $token = new UsernamePassword(); $token->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); $token->setAccount($account); $this->mockSecurityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(true)); $this->mockSecurityContext->expects($this->any())->method('getAuthenticationTokens')->will($this->returnValue([$token])); $session->close(); $this->httpRequest->setCookie($this->httpResponse->getCookie('TYPO3_Flow_Session')); $session->resume(); $this->assertEquals(['MyProvider:admin'], $session->getData('TYPO3_Flow_Security_Accounts')); }
/** * @test */ public function postRequestOnRestrictedActionWithoutCsrfTokenCausesAccessDeniedException() { $this->markTestIncomplete('Needs to be implemented'); $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = '******'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = '******'; $request = Request::create(new Uri('http://localhost/test/security/authentication/usernamepassword/authenticate'), 'POST', $arguments); $response = $this->browser->sendRequest($request); $sessionCookie = $response->getCookie('TYPO3_Flow_Session'); $request = Request::create(new Uri('http://localhost/test/security/restricted/admin')); $request->setCookie($sessionCookie); $response = $this->browser->sendRequest($request); // Expect an exception because no account is authenticated: $response = $this->browser->request(new Uri('http://localhost/test/security/restricted/customer'), 'POST'); // ... // Expect an different exception because although an account is authenticated, the request lacks a CSRF token: $response = $this->browser->request(new Uri('http://localhost/test/security/restricted/customer'), 'POST', $arguments); // ... // Expect that it works after you logged in $csrfToken = $this->securityContext->getCsrfProtectionToken(); $request = Request::create(new Uri('http://localhost/test/security/restricted/customer'), 'POST'); // ... }
/** * @return ControllerContext */ protected function buildMockControllerContext() { $httpRequest = Request::create(new Uri('http://foo.bar/bazfoo')); $request = new ActionRequest($httpRequest); $response = new Response(); /** @var Arguments $mockArguments */ $mockArguments = $this->getMockBuilder(Arguments::class)->disableOriginalConstructor()->getMock(); $uriBuilder = new UriBuilder(); $controllerContext = new ControllerContext($request, $response, $mockArguments, $uriBuilder, $this->createMock(FlashMessageContainer::class)); return $controllerContext; }
/** * Analyzes this response, considering the given request and makes additions * or removes certain headers in order to make the response compliant to * RFC 2616 and related standards. * * It is recommended to call this method before the response is sent and Flow * does so by default in its built-in HTTP request handler. * * @param Request $request The corresponding request * @return void * @api */ public function makeStandardsCompliant(Request $request) { if ($request->hasHeader('If-Modified-Since') && $this->headers->has('Last-Modified') && $this->statusCode === 200) { $ifModifiedSinceDate = $request->getHeader('If-Modified-Since'); $lastModifiedDate = $this->headers->get('Last-Modified'); if ($lastModifiedDate <= $ifModifiedSinceDate) { $this->setStatus(304); $this->content = ''; } } elseif ($request->hasHeader('If-Unmodified-Since') && $this->headers->has('Last-Modified') && ($this->statusCode >= 200 && $this->statusCode <= 299 || $this->statusCode === 412)) { $unmodifiedSinceDate = $request->getHeader('If-Unmodified-Since'); $lastModifiedDate = $this->headers->get('Last-Modified'); if ($lastModifiedDate > $unmodifiedSinceDate) { $this->setStatus(412); } } if (in_array($this->statusCode, [100, 101, 204, 304])) { $this->content = ''; } if ($this->headers->getCacheControlDirective('no-cache') !== null || $this->headers->has('Expires')) { $this->headers->removeCacheControlDirective('max-age'); } if ($request->getMethod() === 'HEAD') { if (!$this->headers->has('Content-Length')) { $this->headers->set('Content-Length', strlen($this->content)); } $this->content = ''; } if (!$this->headers->has('Content-Length')) { $this->headers->set('Content-Length', strlen($this->content)); } if ($this->headers->has('Transfer-Encoding')) { $this->headers->remove('Content-Length'); } }
/** * @test */ public function matchRequestReturnsFalseIfAuthorizationChecksAreDisabled() { $httpRequest = Request::create(new Uri('http://localhost'), 'POST'); $this->mockActionRequest->expects($this->any())->method('getHttpRequest')->will($this->returnValue($httpRequest)); $mockAuthenticationManager = $this->getMockBuilder(AuthenticationManagerInterface::class)->disableOriginalConstructor()->getMock(); $mockAuthenticationManager->expects($this->any())->method('isAuthenticated')->will($this->returnValue(true)); $mockSecurityContext = $this->createMock(Security\Context::class); $mockSecurityContext->expects($this->atLeastOnce())->method('areAuthorizationChecksDisabled')->will($this->returnValue(true)); $mockCsrfProtectionPattern = $this->getAccessibleMock(Security\RequestPattern\CsrfProtection::class, ['dummy']); $mockCsrfProtectionPattern->_set('authenticationManager', $mockAuthenticationManager); $mockCsrfProtectionPattern->_set('systemLogger', $this->mockSystemLogger); $mockCsrfProtectionPattern->_set('securityContext', $mockSecurityContext); $this->assertFalse($mockCsrfProtectionPattern->matchRequest($this->mockActionRequest)); }
/** * Sets up security test requirements * * Security is based on action requests so we need a working route for the TestingProvider. * * @return void */ protected function setupSecurity() { if ($this->securityInitialized === true) { return; } $this->privilegeManager = $this->objectManager->get(PrivilegeManagerInterface::class); $this->privilegeManager->setOverrideDecision(null); $this->policyService = $this->objectManager->get(PolicyService::class); $this->authenticationManager = $this->objectManager->get(AuthenticationProviderManager::class); $this->testingProvider = $this->objectManager->get(TestingProvider::class); $this->testingProvider->setName('TestingProvider'); $this->securityContext = $this->objectManager->get(Security\Context::class); $this->securityContext->clearContext(); $httpRequest = Request::createFromEnvironment(); $this->mockActionRequest = new ActionRequest($httpRequest); $this->mockActionRequest->setControllerObjectName(AuthenticationController::class); $this->securityContext->setRequest($this->mockActionRequest); $this->securityInitialized = true; }
/** * Checks whether $routePath corresponds to this Route. * If all Route Parts match successfully TRUE is returned and * $this->matchResults contains an array combining Route default values and * calculated matchResults from the individual Route Parts. * * @param Request $httpRequest the HTTP request to match * @return boolean TRUE if this Route corresponds to the given $routePath, otherwise FALSE * @throws InvalidRoutePartValueException * @see getMatchResults() */ public function matches(Request $httpRequest) { $routePath = $httpRequest->getRelativePath(); $this->matchResults = null; if ($this->uriPattern === null) { return false; } if (!$this->isParsed) { $this->parse(); } if ($this->hasHttpMethodConstraints() && !in_array($httpRequest->getMethod(), $this->httpMethods)) { return false; } $matchResults = []; $routePath = trim($routePath, '/'); $skipOptionalParts = false; $optionalPartCount = 0; /** @var $routePart RoutePartInterface */ foreach ($this->routeParts as $routePart) { if ($routePart->isOptional()) { $optionalPartCount++; if ($skipOptionalParts) { if ($routePart->getDefaultValue() === null) { return false; } continue; } } else { $optionalPartCount = 0; $skipOptionalParts = false; } if ($routePart->match($routePath) !== true) { if ($routePart->isOptional() && $optionalPartCount === 1) { if ($routePart->getDefaultValue() === null) { return false; } $skipOptionalParts = true; } else { return false; } } $routePartValue = $routePart->getValue(); if ($routePartValue !== null) { if ($this->containsObject($routePartValue)) { throw new InvalidRoutePartValueException('RoutePart::getValue() must only return simple types after calling RoutePart::match(). RoutePart "' . get_class($routePart) . '" returned one or more objects in Route "' . $this->getName() . '".'); } $matchResults = Arrays::setValueByPath($matchResults, $routePart->getName(), $routePartValue); } } if (strlen($routePath) > 0) { return false; } $this->matchResults = Arrays::arrayMergeRecursiveOverrule($this->defaults, $matchResults); return true; }
/** * RFC 2616 / 14.28 (If-Unmodified-Since) * * @test */ public function makeStandardsCompliantReturns412StatusIfUnmodifiedSinceDoesNotMatch() { $request = Request::create(new Uri('http://localhost')); $response = new Response(); $unmodifiedSince = \DateTime::createFromFormat(DATE_RFC2822, 'Tue, 15 May 2012 09:00:00 GMT'); $lastModified = \DateTime::createFromFormat(DATE_RFC2822, 'Sun, 20 May 2012 08:00:00 UTC'); $request->setHeader('If-Unmodified-Since', $unmodifiedSince); $response->setHeader('Last-Modified', $lastModified); $response->makeStandardsCompliant($request); $this->assertSame(412, $response->getStatusCode()); $response = new Response(); $unmodifiedSince = \DateTime::createFromFormat(DATE_RFC2822, 'Tue, 15 May 2012 09:00:00 GMT'); $lastModified = \DateTime::createFromFormat(DATE_RFC2822, 'Tue, 15 May 2012 08:00:00 UTC'); $request->setHeader('If-Unmodified-Since', $unmodifiedSince); $response->setHeader('Last-Modified', $lastModified); $response->makeStandardsCompliant($request); $this->assertSame(200, $response->getStatusCode()); }