When `mod_unique_id` is enabled the ID generated by it will be used for logging. This allows for correlation of the Apache logs and the ownCloud logs.
Testplan:
- [ ] When `mod_unique_id` is enabled the request ID equals the one generated by `mod_unique_id`.
- [ ] When `mod_unique_id` is not available the request ID is a 20 character long random string
- [ ] The generated Id is stable over the lifespan of one request
Changeset looks a little bit larger since I had to adjust every unit test using the HTTP\Request class for proper DI.
Fixes https://github.com/owncloud/core/issues/13366
namespace OC\AppFramework\Http;
use OCP\IRequest;
+use OCP\Security\ISecureRandom;
/**
* Class for accessing variables in the request.
'method',
'requesttoken',
);
+ /** @var ISecureRandom */
+ protected $secureRandom;
+ /** @var string */
+ protected $requestId = '';
/**
* @param array $vars An associative array with the following optional values:
- * @param array 'urlParams' the parameters which were matched from the URL
- * @param array 'get' the $_GET array
- * @param array|string 'post' the $_POST array or JSON string
- * @param array 'files' the $_FILES array
- * @param array 'server' the $_SERVER array
- * @param array 'env' the $_ENV array
- * @param array 'cookies' the $_COOKIE array
- * @param string 'method' the request method (GET, POST etc)
- * @param string|false 'requesttoken' the requesttoken or false when not available
+ * - array 'urlParams' the parameters which were matched from the URL
+ * - array 'get' the $_GET array
+ * - array|string 'post' the $_POST array or JSON string
+ * - array 'files' the $_FILES array
+ * - array 'server' the $_SERVER array
+ * - array 'env' the $_ENV array
+ * - array 'cookies' the $_COOKIE array
+ * - string 'method' the request method (GET, POST etc)
+ * - string|false 'requesttoken' the requesttoken or false when not available
+ * @param ISecureRandom $secureRandom
+ * @param string $stream
* @see http://www.php.net/manual/en/reserved.variables.php
*/
- public function __construct(array $vars=array(), $stream='php://input') {
-
+ public function __construct(array $vars=array(),
+ ISecureRandom $secureRandom,
+ $stream='php://input') {
$this->inputStream = $stream;
$this->items['params'] = array();
+ $this->secureRandom = $secureRandom;
if(!array_key_exists('method', $vars)) {
$vars['method'] = 'GET';
// Valid token
return true;
}
- }}
+ }
+
+ /**
+ * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
+ * If `mod_unique_id` is installed this value will be taken.
+ * @return string
+ */
+ public function getId() {
+ if(isset($this->server['UNIQUE_ID'])) {
+ return $this->server['UNIQUE_ID'];
+ }
+
+ if(empty($this->requestId)) {
+ $this->requestId = $this->secureRandom->getLowStrengthGenerator()->generate(20);
+ }
+
+ return $this->requestId;
+ }
+
+}
$timezone = new DateTimeZone('UTC');
}
$time = new DateTime(null, $timezone);
- $reqId = \OC_Request::getRequestID();
+ $reqId = \OC::$server->getRequest()->getId();
$remoteAddr = \OC_Request::getRemoteAddress();
// remove username/passwords from URLs before writing the to the log file
$time = $time->format($format);
const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost)$/';
- static protected $reqId;
/**
* Returns the remote address, if the connection came from a trusted proxy and `forwarded_for_headers` has been configured
return $remoteAddress;
}
- /**
- * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
- * @return string
- */
- public static function getRequestID() {
- if(self::$reqId === null) {
- self::$reqId = hash('md5', microtime().\OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(20));
- }
- return self::$reqId;
- }
-
/**
* Check overwrite condition
* @param string $type
use OC\Diagnostics\NullQueryLogger;
use OC\Diagnostics\EventLogger;
use OC\Diagnostics\QueryLogger;
-use OC\Files\Config\StorageManager;
use OC\Security\CertificateManager;
use OC\Files\Node\Root;
use OC\Files\View;
}
return new Request(
- array(
+ [
'get' => $_GET,
'post' => $_POST,
'files' => $_FILES,
: null,
'urlParams' => $urlParams,
'requesttoken' => $requestToken,
- ), $stream
+ ],
+ $this->getSecureRandom(),
+ $stream
);
});
$this->registerService('PreviewManager', function ($c) {
$content->assign('trace', $exception->getTraceAsString());
$content->assign('debugMode', defined('DEBUG') && DEBUG === true);
$content->assign('remoteAddr', OC_Request::getRemoteAddress());
- $content->assign('requestID', OC_Request::getRequestID());
+ $content->assign('requestID', \OC::$server->getRequest()->getId());
$content->printPage();
die();
}
* @return bool true if CSRF check passed
*/
public function passesCSRFCheck();
+
+ /**
+ * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
+ * If `mod_unique_id` is installed this value will be taken.
+ * @return string
+ */
+ public function getId();
}
namespace OCP\AppFramework;
use OC\AppFramework\Http\Request;
-use OCP\AppFramework\Http\TemplateResponse;
class ChildApiController extends ApiController {};
class ApiControllerTest extends \Test\TestCase {
-
+ /** @var ChildApiController */
+ protected $controller;
public function testCors() {
$request = new Request(
- array('server' => array('HTTP_ORIGIN' => 'test'))
+ ['server' => ['HTTP_ORIGIN' => 'test']],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$this->controller = new ChildApiController('app', $request, 'verbs',
'headers', 100);
parent::setUp();
$request = new Request(
- array(
- 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'),
- 'post' => array('name' => 'Jane Doe', 'nickname' => 'Janey'),
- 'urlParams' => array('name' => 'Johnny Weissmüller'),
- 'files' => array('file' => 'filevalue'),
- 'env' => array('PATH' => 'daheim'),
- 'session' => array('sezession' => 'kein'),
+ [
+ 'get' => ['name' => 'John Q. Public', 'nickname' => 'Joey'],
+ 'post' => ['name' => 'Jane Doe', 'nickname' => 'Janey'],
+ 'urlParams' => ['name' => 'Johnny Weissmüller'],
+ 'files' => ['file' => 'filevalue'],
+ 'env' => ['PATH' => 'daheim'],
+ 'session' => ['sezession' => 'kein'],
'method' => 'hi',
- )
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$this->app = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer',
public function testMiddlewareDispatcherIncludesSecurityMiddleware(){
- $this->container['Request'] = new Request(array('method' => 'GET'));
+ $this->container['Request'] = new Request(
+ ['method' => 'GET'],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$security = $this->container['SecurityMiddleware'];
$dispatcher = $this->container['MiddlewareDispatcher'];
public function testControllerParametersInjected() {
- $this->request = new Request(array(
- 'post' => array(
+ $this->request = new Request(
+ [
+ 'post' => [
'int' => '3',
'bool' => 'false'
- ),
- 'method' => 'POST'
- ));
+ ],
+ 'method' => 'POST'
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
public function testControllerParametersInjectedDefaultOverwritten() {
- $this->request = new Request(array(
- 'post' => array(
- 'int' => '3',
- 'bool' => 'false',
- 'test2' => 7
- ),
- 'method' => 'POST'
- ));
+ $this->request = new Request(
+ [
+ 'post' => [
+ 'int' => '3',
+ 'bool' => 'false',
+ 'test2' => 7
+ ],
+ 'method' => 'POST',
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
public function testResponseTransformedByUrlFormat() {
- $this->request = new Request(array(
- 'post' => array(
- 'int' => '3',
- 'bool' => 'false'
- ),
- 'urlParams' => array(
- 'format' => 'text'
- ),
- 'method' => 'GET'
- ));
+ $this->request = new Request(
+ [
+ 'post' => [
+ 'int' => '3',
+ 'bool' => 'false'
+ ],
+ 'urlParams' => [
+ 'format' => 'text'
+ ],
+ 'method' => 'GET'
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
public function testResponseTransformsDataResponse() {
- $this->request = new Request(array(
- 'post' => array(
- 'int' => '3',
- 'bool' => 'false'
- ),
- 'urlParams' => array(
- 'format' => 'json'
- ),
- 'method' => 'GET'
- ));
+ $this->request = new Request(
+ [
+ 'post' => [
+ 'int' => '3',
+ 'bool' => 'false'
+ ],
+ 'urlParams' => [
+ 'format' => 'json'
+ ],
+ 'method' => 'GET'
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
public function testResponseTransformedByAcceptHeader() {
- $this->request = new Request(array(
- 'post' => array(
- 'int' => '3',
- 'bool' => 'false'
- ),
- 'server' => array(
- 'HTTP_ACCEPT' => 'application/text, test',
- 'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded'
- ),
- 'method' => 'PUT'
- ));
+ $this->request = new Request(
+ [
+ 'post' => [
+ 'int' => '3',
+ 'bool' => 'false'
+ ],
+ 'server' => [
+ 'HTTP_ACCEPT' => 'application/text, test',
+ 'HTTP_CONTENT_TYPE' => 'application/x-www-form-urlencoded'
+ ],
+ 'method' => 'PUT'
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
public function testResponsePrimarilyTransformedByParameterFormat() {
- $this->request = new Request(array(
- 'post' => array(
- 'int' => '3',
- 'bool' => 'false'
- ),
- 'get' => array(
- 'format' => 'text'
- ),
- 'server' => array(
- 'HTTP_ACCEPT' => 'application/json, test'
- ),
- 'method' => 'POST'
- ));
+ $this->request = new Request(
+ [
+ 'post' => [
+ 'int' => '3',
+ 'bool' => 'false'
+ ],
+ 'get' => [
+ 'format' => 'text'
+ ],
+ 'server' => [
+ 'HTTP_ACCEPT' => 'application/json, test'
+ ],
+ 'method' => 'POST'
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->dispatcher = new Dispatcher(
$this->http, $this->middlewareDispatcher, $this->reflector,
$this->request
namespace OC\AppFramework\Http;
-global $data;
+use OCP\Security\ISecureRandom;
class RequestTest extends \Test\TestCase {
+ /** @var string */
+ protected $stream = 'fakeinput://data';
+ /** @var ISecureRandom */
+ protected $secureRandom;
protected function setUp() {
parent::setUp();
stream_wrapper_unregister('fakeinput');
}
stream_wrapper_register('fakeinput', 'RequestStream');
- $this->stream = 'fakeinput://data';
+
+ $this->secureRandom = $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock();
}
protected function tearDown() {
'method' => 'GET',
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
// Countable
$this->assertEquals(2, count($request));
'method' => 'GET'
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals(3, count($request));
$this->assertEquals('Janey', $request->{'nickname'});
'method' => 'GET'
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$request['nickname'] = 'Janey';
}
'method' => 'GET'
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$request->{'nickname'} = 'Janey';
}
'method' => 'GET',
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$result = $request->post;
}
'method' => 'GET',
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('GET', $request->method);
$result = $request->get;
$this->assertEquals('John Q. Public', $result['name']);
'server' => array('CONTENT_TYPE' => 'application/json; utf-8')
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('POST', $request->method);
$result = $request->post;
$this->assertEquals('John Q. Public', $result['name']);
'server' => array('CONTENT_TYPE' => 'application/x-www-form-urlencoded'),
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('PATCH', $request->method);
$result = $request->patch;
'server' => array('CONTENT_TYPE' => 'application/json; utf-8'),
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('PUT', $request->method);
$result = $request->put;
'server' => array('CONTENT_TYPE' => 'application/json; utf-8'),
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('PATCH', $request->method);
$result = $request->patch;
'server' => array('CONTENT_TYPE' => 'image/png'),
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$this->assertEquals('PUT', $request->method);
$resource = $request->put;
$contents = stream_get_contents($resource);
'urlParams' => array('id' => '2'),
);
- $request = new Request($vars, $this->stream);
+ $request = new Request($vars, $this->secureRandom, $this->stream);
$newParams = array('id' => '3', 'test' => 'test2');
$request->setUrlParameters($newParams);
$this->assertEquals('3', $request->getParam('id'));
$this->assertEquals('3', $request->getParams()['id']);
}
+
+ public function testGetIdWithModUnique() {
+ $vars = [
+ 'server' => [
+ 'UNIQUE_ID' => 'GeneratedUniqueIdByModUnique'
+ ],
+ ];
+
+ $request = new Request($vars, $this->secureRandom, $this->stream);
+ $this->assertSame('GeneratedUniqueIdByModUnique', $request->getId());
+ }
+
+ public function testGetIdWithoutModUnique() {
+ $lowRandomSource = $this->getMockBuilder('\OCP\Security\ISecureRandom')
+ ->disableOriginalConstructor()->getMock();
+ $lowRandomSource->expects($this->once())
+ ->method('generate')
+ ->with('20')
+ ->will($this->returnValue('GeneratedByOwnCloudItself'));
+
+ $this->secureRandom
+ ->expects($this->once())
+ ->method('getLowStrengthGenerator')
+ ->will($this->returnValue($lowRandomSource));
+
+ $request = new Request([], $this->secureRandom, $this->stream);
+ $this->assertSame('GeneratedByOwnCloudItself', $request->getId());
+ }
+
+ public function testGetIdWithoutModUniqueStable() {
+ $request = new Request([], \OC::$server->getSecureRandom(), $this->stream);
+ $firstId = $request->getId();
+ $secondId = $request->getId();
+ $this->assertSame($firstId, $secondId);
+ }
}
private function getControllerMock(){
- return $this->getMock('OCP\AppFramework\Controller', array('method'),
- array('app', new Request(array('method' => 'GET'))));
+ return $this->getMock(
+ 'OCP\AppFramework\Controller',
+ ['method'],
+ ['app',
+ new Request(
+ ['method' => 'GET'],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ )
+ ]
+ );
}
->disableOriginalConstructor()
->getMock();
- $this->controller = $this->getMock('OCP\AppFramework\Controller',
- array(), array($this->api, new Request()));
+ $this->controller = $this->getMock(
+ 'OCP\AppFramework\Controller',
+ [],
+ [
+ $this->api,
+ new Request([], $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock())
+ ]
+ );
$this->exception = new \Exception();
$this->response = $this->getMock('OCP\AppFramework\Http\Response');
}
*/
public function testSetCORSAPIHeader() {
$request = new Request(
- array('server' => array('HTTP_ORIGIN' => 'test'))
+ [
+ 'server' => [
+ 'HTTP_ORIGIN' => 'test'
+ ]
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$this->reflector->reflect($this, __FUNCTION__);
$middleware = new CORSMiddleware($request, $this->reflector);
public function testNoAnnotationNoCORSHEADER() {
$request = new Request(
- array('server' => array('HTTP_ORIGIN' => 'test'))
+ [
+ 'server' => [
+ 'HTTP_ORIGIN' => 'test'
+ ]
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$middleware = new CORSMiddleware($request, $this->reflector);
* @CORS
*/
public function testNoOriginHeaderNoCORSHEADER() {
- $request = new Request();
+ $request = new Request([], $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock());
$this->reflector->reflect($this, __FUNCTION__);
$middleware = new CORSMiddleware($request, $this->reflector);
*/
public function testCorsIgnoredIfWithCredentialsHeaderPresent() {
$request = new Request(
- array('server' => array('HTTP_ORIGIN' => 'test'))
+ [
+ 'server' => [
+ 'HTTP_ORIGIN' => 'test'
+ ]
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$this->reflector->reflect($this, __FUNCTION__);
$middleware = new CORSMiddleware($request, $this->reflector);
public function testAfterExceptionReturnsRedirect(){
$this->request = new Request(
- array('server' =>
- array('HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'REQUEST_URI' => 'owncloud/index.php/apps/specialapp')
- )
+ [
+ 'server' =>
+ [
+ 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
+ 'REQUEST_URI' => 'owncloud/index.php/apps/specialapp'
+ ]
+ ],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
);
$this->middleware = $this->getMiddleware(true, true);
$response = $this->middleware->afterException($this->controller, 'test',
protected function setUp() {
parent::setUp();
- $this->request = new Request();
+ $this->request = new Request(
+ [],
+ $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock()
+ );
$this->reflector = new ControllerMethodReflector();
}