8 class ApiCSPReportTest
extends MediaWikiIntegrationTestCase
{
10 public function setUp() {
12 $this->setMwGlobals( [
13 'CSPFalsePositiveUrls' => [],
17 public function testInternalReportonly() {
20 'source' => 'internal',
23 'document-uri' => 'https://doc.test/path',
24 'referrer' => 'https://referrer.test/path',
25 'violated-directive' => 'connet-src',
26 'disposition' => 'report',
27 'blocked-uri' => 'https://blocked.test/path?query',
30 'source-file' => 'https://source.test/path?query',
33 $log = $this->doExecute( $params, $cspReport );
38 '[report-only] Received CSP report: ' .
39 '<https://blocked.test> blocked from being loaded on <https://doc.test/path>:4',
41 'method' => 'ApiCSPReport::execute',
42 'user_id' => 'logged-out',
43 'user-agent' => 'Test/0.0',
44 'source' => 'internal'
53 public function testFalsePositiveOriginMatch() {
56 'source' => 'internal',
59 'document-uri' => 'https://doc.test/path',
60 'referrer' => 'https://referrer.test/path',
61 'violated-directive' => 'connet-src',
62 'disposition' => 'report',
63 'blocked-uri' => 'https://blocked.test/path/file?query',
66 'source-file' => 'https://source.test/path/file?query',
69 $this->setMwGlobals( [
70 'wgCSPFalsePositiveUrls' => [
71 'https://blocked.test/path/' => true,
74 $log = $this->doExecute( $params, $cspReport );
83 private function doExecute( array $params, array $cspReport ) {
85 $logger = $this->createMock( Psr\Log\AbstractLogger
::class );
86 $logger->method( 'warning' )->will( $this->returnCallback(
87 function ( $msg, $ctx ) use ( &$log ) {
88 unset( $ctx['csp-report'] );
89 $log[] = [ $msg, $ctx ];
92 $this->setLogger( 'csp-report-only', $logger );
94 $postBody = json_encode( [ 'csp-report' => $cspReport ] );
95 $req = $this->getMockBuilder( FauxRequest
::class )
96 ->setMethods( [ 'getRawInput' ] )
97 ->setConstructorArgs( [ $params, /* $wasPosted */ true ] )
99 $req->method( 'getRawInput' )->willReturn( $postBody );
101 'Content-Type' => 'application/csp-report',
102 'User-Agent' => 'Test/0.0'
105 $api = $this->getMockBuilder( ApiCSPReport
::class )
106 ->disableOriginalConstructor()
107 ->setMethods( [ 'getParameter', 'getRequest', 'getResult' ] )
109 $api->method( 'getParameter' )->will( $this->returnCallback(
110 function ( $key ) use ( $req ) {
111 return $req->getRawVal( $key );
114 $api->method( 'getRequest' )->willReturn( $req );
115 $api->method( 'getResult' )->willReturn( new ApiResult( false ) );