test: adapt

This commit is contained in:
Sami Mazouz 2023-08-14 13:16:14 +01:00
parent 835eba9178
commit 0db8007002
No known key found for this signature in database
15 changed files with 151 additions and 112 deletions

View File

@ -143,7 +143,7 @@ class LikePostTest extends TestCase
$this->request('GET', '/') $this->request('GET', '/')
); );
$token = $initial->getHeaderLine('X-CSRF-Token'); $token = $initial->headers->get('X-CSRF-Token');
} }
$request = $this->request('PATCH', "/api/posts/$postId", [ $request = $this->request('PATCH', "/api/posts/$postId", [
@ -159,7 +159,7 @@ class LikePostTest extends TestCase
]); ]);
if (! isset($authenticatedAs)) { if (! isset($authenticatedAs)) {
$request = $request->withHeader('X-CSRF-Token', $token); $request->headers->set('X-CSRF-Token', $token);
} }
return $this->send($request); return $this->send($request);

View File

@ -25,7 +25,7 @@ class PasswordResetThrottler
public function __invoke(Request $request): ?bool public function __invoke(Request $request): ?bool
{ {
if (! $request->routeIs('forum.forgot')) { if (! $request->routeIs('api.forgot')) {
return null; return null;
} }

View File

@ -16,6 +16,7 @@ use Flarum\Http\RememberAccessToken;
use Flarum\Http\SessionAccessToken; use Flarum\Http\SessionAccessToken;
use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Illuminate\Http\Request;
class DeleteTest extends TestCase class DeleteTest extends TestCase
{ {
@ -106,10 +107,13 @@ class DeleteTest extends TestCase
->latest() ->latest()
->first(); ->first();
$csrfToken = $responseWithSession->getHeaderLine('X-CSRF-Token'); $csrfToken = $responseWithSession->headers->get('X-CSRF-Token');
$request = $this->requestWithCookiesFrom( $request = $this->requestWithCookiesFrom(
$this->request('DELETE', "/api/access-tokens/$sessionToken->id")->withHeader('X-CSRF-Token', $csrfToken), tap(
$this->request('DELETE', "/api/access-tokens/$sessionToken->id"),
fn (Request $request) => $request->headers->set('X-CSRF-Token', $csrfToken),
),
$responseWithSession $responseWithSession
); );
@ -140,10 +144,13 @@ class DeleteTest extends TestCase
->latest() ->latest()
->first(); ->first();
$csrfToken = $responseWithSession->getHeaderLine('X-CSRF-Token'); $csrfToken = $responseWithSession->headers->get('X-CSRF-Token');
$request = $this->requestWithCookiesFrom( $request = $this->requestWithCookiesFrom(
$this->request('DELETE', '/api/sessions')->withHeader('X-CSRF-Token', $csrfToken), tap(
$this->request('DELETE', '/api/sessions'),
fn (Request $request) => $request->headers->set('X-CSRF-Token', $csrfToken)
),
$responseWithSession $responseWithSession
); );

View File

@ -86,7 +86,7 @@ class ListTest extends TestCase
$response = $this->send( $response = $this->send(
tap( tap(
$this->request('GET', '/api/access-tokens', compact('authenticatedAs')), $this->request('GET', '/api/access-tokens', compact('authenticatedAs')),
fn (Request $request) => $request->query->add([$filters ?? []]) fn (Request $request) => $request->query->add($filters ?? [])
) )
); );

View File

@ -12,6 +12,7 @@ namespace Flarum\Tests\integration\api\access_tokens;
use Carbon\Carbon; use Carbon\Carbon;
use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Illuminate\Http\Request;
class RemembererTest extends TestCase class RemembererTest extends TestCase
{ {
@ -42,9 +43,12 @@ class RemembererTest extends TestCase
Carbon::setTestNow('2021-01-01 02:30:00'); Carbon::setTestNow('2021-01-01 02:30:00');
$response = $this->send( $response = $this->send(
$this->request('GET', '/api')->withCookieParams([ tap(
$this->request('GET', '/api'),
fn (Request $request) => $request->cookies->add([
'flarum_remember' => 'a', 'flarum_remember' => 'a',
]) ])
)
); );
Carbon::setTestNow(); Carbon::setTestNow();
@ -63,9 +67,12 @@ class RemembererTest extends TestCase
Carbon::setTestNow('2027-01-01 02:30:00'); Carbon::setTestNow('2027-01-01 02:30:00');
$response = $this->send( $response = $this->send(
$this->request('GET', '/api')->withCookieParams([ tap(
$this->request('GET', '/api'),
fn (Request $request) => $request->cookies->add([
'flarum_remember' => 'b', 'flarum_remember' => 'b',
]) ])
)
); );
Carbon::setTestNow(); Carbon::setTestNow();
@ -84,9 +91,12 @@ class RemembererTest extends TestCase
Carbon::setTestNow('2021-01-01 02:30:00'); Carbon::setTestNow('2021-01-01 02:30:00');
$response = $this->send( $response = $this->send(
$this->request('GET', '/api')->withCookieParams([ tap(
$this->request('GET', '/api'),
fn (Request $request) => $request->cookies->add([
'flarum_remember' => 'b', 'flarum_remember' => 'b',
]) ])
)
); );
Carbon::setTestNow(); Carbon::setTestNow();

View File

@ -13,6 +13,7 @@ use Carbon\Carbon;
use Flarum\Api\ApiKey; use Flarum\Api\ApiKey;
use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Illuminate\Http\Request;
class WithApiKeyTest extends TestCase class WithApiKeyTest extends TestCase
{ {
@ -55,8 +56,10 @@ class WithApiKeyTest extends TestCase
public function master_token_can_authenticate_as_anyone() public function master_token_can_authenticate_as_anyone()
{ {
$response = $this->send( $response = $this->send(
$this->request('GET', '/api') tap(
->withAddedHeader('Authorization', 'Token mastertoken; userId=1') $this->request('GET', '/api'),
fn (Request $request) => $request->headers->set('Authorization', 'Token mastertoken; userId=1')
)
); );
$data = json_decode($response->getContent(), true); $data = json_decode($response->getContent(), true);
@ -74,8 +77,10 @@ class WithApiKeyTest extends TestCase
public function personal_api_token_cannot_authenticate_as_anyone() public function personal_api_token_cannot_authenticate_as_anyone()
{ {
$response = $this->send( $response = $this->send(
$this->request('GET', '/api') tap(
->withAddedHeader('Authorization', 'Token personaltoken; userId=1') $this->request('GET', '/api'),
fn (Request $request) => $request->headers->set('Authorization', 'Token personaltoken; userId=1')
)
); );
$data = json_decode($response->getContent(), true); $data = json_decode($response->getContent(), true);
@ -93,8 +98,10 @@ class WithApiKeyTest extends TestCase
public function personal_api_token_authenticates_user() public function personal_api_token_authenticates_user()
{ {
$response = $this->send( $response = $this->send(
$this->request('GET', '/api') tap(
->withAddedHeader('Authorization', 'Token personaltoken') $this->request('GET', '/api'),
fn (Request $request) => $request->headers->set('Authorization', 'Token personaltoken')
)
); );
$data = json_decode($response->getContent(), true); $data = json_decode($response->getContent(), true);

View File

@ -11,6 +11,7 @@ namespace Flarum\Tests\integration\api\csrf_protection;
use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Illuminate\Http\Request;
class RequireCsrfTokenTest extends TestCase class RequireCsrfTokenTest extends TestCase
{ {
@ -80,30 +81,28 @@ class RequireCsrfTokenTest extends TestCase
$this->request('GET', '/') $this->request('GET', '/')
); );
$token = $initial->getHeaderLine('X-CSRF-Token'); $token = $initial->headers->get('X-CSRF-Token');
$auth = $this->send( $auth = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/login', [
'/login',
[
'cookiesFrom' => $initial, 'cookiesFrom' => $initial,
'json' => ['identification' => 'admin', 'password' => 'password'], 'json' => ['identification' => 'admin', 'password' => 'password'],
] ]),
)->withHeader('X-CSRF-Token', $token) fn (Request $request) => $request->headers->set('X-CSRF-Token', $token),
)
); );
$token = $auth->getHeaderLine('X-CSRF-Token'); $token = $auth->headers->get('X-CSRF-Token');
$response = $this->send( $response = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/api/settings', [
'/api/settings',
[
'cookiesFrom' => $auth, 'cookiesFrom' => $auth,
'json' => ['csrf_test' => 2], 'json' => ['csrf_test' => 2],
] ]),
)->withHeader('X-CSRF-Token', $token) fn (Request $request) => $request->headers->set('X-CSRF-Token', $token),
)
); );
// Successful response? // Successful response?
@ -125,29 +124,27 @@ class RequireCsrfTokenTest extends TestCase
$this->request('GET', '/') $this->request('GET', '/')
); );
$token = $initial->getHeaderLine('X-CSRF-Token'); $token = $initial->headers->get('X-CSRF-Token');
$auth = $this->send( $auth = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/login', [
'/login',
[
'cookiesFrom' => $initial, 'cookiesFrom' => $initial,
'json' => ['identification' => 'admin', 'password' => 'password', 'csrfToken' => $token], 'json' => ['identification' => 'admin', 'password' => 'password', 'csrfToken' => $token],
] ]),
fn (Request $request) => $request->headers->set('X-CSRF-Token', $token),
) )
); );
$token = $auth->getHeaderLine('X-CSRF-Token'); $token = $auth->headers->get('X-CSRF-Token');
$response = $this->send( $response = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/api/settings', [
'/api/settings',
[
'cookiesFrom' => $auth, 'cookiesFrom' => $auth,
'json' => ['csrf_test' => 2, 'csrfToken' => $token], 'json' => ['csrf_test' => 2, 'csrfToken' => $token],
] ]),
fn (Request $request) => $request->headers->set('X-CSRF-Token', $token),
) )
); );
@ -167,13 +164,12 @@ class RequireCsrfTokenTest extends TestCase
public function master_api_token_does_not_need_csrf_token() public function master_api_token_does_not_need_csrf_token()
{ {
$response = $this->send( $response = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/api/settings', [
'/api/settings',
[
'json' => ['csrf_test' => 2], 'json' => ['csrf_test' => 2],
] ]),
)->withHeader('Authorization', 'Token superadmin') fn (Request $request) => $request->headers->set('Authorization', 'Token superadmin')
)
); );
// Successful response? // Successful response?
@ -196,13 +192,12 @@ class RequireCsrfTokenTest extends TestCase
); );
$response = $this->send( $response = $this->send(
$this->request( tap(
'POST', $this->request('POST', '/api/settings', [
'/api/settings',
[
'json' => ['csrf_test' => 2], 'json' => ['csrf_test' => 2],
] ]),
)->withHeader('Authorization', 'Token myaccesstoken') fn (Request $request) => $request->headers->set('Authorization', 'Token myaccesstoken')
)
); );
// Successful response? // Successful response?

View File

@ -13,6 +13,8 @@ use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Flarum\User\EmailToken; use Flarum\User\EmailToken;
use Flarum\User\PasswordToken; use Flarum\User\PasswordToken;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
class PasswordEmailTokensTest extends TestCase class PasswordEmailTokensTest extends TestCase
{ {
@ -78,14 +80,17 @@ class PasswordEmailTokensTest extends TestCase
// Use a token to reset password // Use a token to reset password
$response = $this->send( $response = $this->send(
$request = $this->requestWithCsrfToken( $this->requestWithCsrfToken(
tap(
$this->request('POST', '/reset', [ $this->request('POST', '/reset', [
'authenticatedAs' => 2, 'authenticatedAs' => 2,
])->withParsedBody([ ]),
fn (Request $request) => $request->setJson(new ParameterBag([
'passwordToken' => PasswordToken::query()->latest()->first()->token, 'passwordToken' => PasswordToken::query()->latest()->first()->token,
'password' => 'new-password', 'password' => 'new-password',
'password_confirmation' => 'new-password', 'password_confirmation' => 'new-password',
]) ]))
)
) )
); );
@ -162,14 +167,17 @@ class PasswordEmailTokensTest extends TestCase
// Use a token to reset password // Use a token to reset password
$response = $this->send( $response = $this->send(
$request = $this->requestWithCsrfToken( $this->requestWithCsrfToken(
tap(
$this->request('POST', '/reset', [ $this->request('POST', '/reset', [
'authenticatedAs' => 2, 'authenticatedAs' => 2,
])->withParsedBody([ ]),
fn (Request $request) => $request->setJson(new ParameterBag([
'passwordToken' => PasswordToken::query()->latest()->first()->token, 'passwordToken' => PasswordToken::query()->latest()->first()->token,
'password' => 'new-password', 'password' => 'new-password',
'password_confirmation' => 'new-password', 'password_confirmation' => 'new-password',
]) ]))
)
) )
); );

View File

@ -276,6 +276,7 @@ class UpdateTest extends TestCase
], ],
]) ])
); );
$this->assertEquals(403, $response->getStatusCode()); $this->assertEquals(403, $response->getStatusCode());
} }

View File

@ -9,12 +9,12 @@
namespace Flarum\Tests\integration\extenders; namespace Flarum\Tests\integration\extenders;
use Closure;
use Flarum\Extend; use Flarum\Extend;
use Flarum\Http\Middleware\IlluminateMiddlewareInterface;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Psr\Http\Message\ResponseInterface; use Illuminate\Http\Request;
use Psr\Http\Message\ServerRequestInterface; use Symfony\Component\HttpFoundation\Response;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class MiddlewareTest extends TestCase class MiddlewareTest extends TestCase
{ {
@ -34,7 +34,7 @@ class MiddlewareTest extends TestCase
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayNotHasKey('X-First-Test-Middleware', $response->getHeaders()); $this->assertNull($response->headers->get('X-First-Test-Middleware'));
} }
/** /**
@ -49,7 +49,7 @@ class MiddlewareTest extends TestCase
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayHasKey('X-First-Test-Middleware', $response->getHeaders()); $this->assertNotNull($response->headers->get('X-First-Test-Middleware'));
} }
/** /**
@ -65,8 +65,9 @@ class MiddlewareTest extends TestCase
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayNotHasKey('X-First-Test-Middleware', $response->getHeaders());
$this->assertArrayHasKey('X-Second-Test-Middleware', $response->getHeaders()); $this->assertNull($response->headers->get('X-First-Test-Middleware'));
$this->assertNotNull($response->headers->get('X-Second-Test-Middleware'));
} }
/** /**
@ -82,7 +83,7 @@ class MiddlewareTest extends TestCase
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayNotHasKey('X-First-Test-Middleware', $response->getHeaders()); $this->assertNull($response->headers->get('X-First-Test-Middleware'));
} }
/** /**
@ -96,9 +97,9 @@ class MiddlewareTest extends TestCase
); );
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$headers = $response->getHeaders(); $headers = $response->headers->all();
$newMiddlewarePosition = array_search('X-Second-Test-Middleware', array_keys($headers)); $newMiddlewarePosition = array_search(strtolower('X-Second-Test-Middleware'), array_keys($headers));
$originalMiddlewarePosition = array_search('X-First-Test-Middleware', array_keys($headers)); $originalMiddlewarePosition = array_search(strtolower('X-First-Test-Middleware'), array_keys($headers));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertLessThan($newMiddlewarePosition, $originalMiddlewarePosition); $this->assertLessThan($newMiddlewarePosition, $originalMiddlewarePosition);
@ -115,31 +116,36 @@ class MiddlewareTest extends TestCase
); );
$response = $this->send($this->request('GET', '/')); $response = $this->send($this->request('GET', '/'));
$headers = $response->getHeaders(); $headers = $response->headers->all();
$newMiddlewarePosition = array_search('X-Second-Test-Middleware', array_keys($headers)); $newMiddlewarePosition = array_search(strtolower('X-Second-Test-Middleware'), array_keys($headers));
$originalMiddlewarePosition = array_search('X-First-Test-Middleware', array_keys($headers)); $originalMiddlewarePosition = array_search(strtolower('X-First-Test-Middleware'), array_keys($headers));
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertGreaterThan($newMiddlewarePosition, $originalMiddlewarePosition); $this->assertGreaterThan($newMiddlewarePosition, $originalMiddlewarePosition);
} }
} }
class FirstTestMiddleware implements MiddlewareInterface class FirstTestMiddleware implements IlluminateMiddlewareInterface
{ {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface public function handle(Request $request, Closure $next): Response
{ {
$response = $handler->handle($request); $response = $next($request);
return $response->withAddedHeader('X-First-Test-Middleware', 'This is a test!'); $response->headers->set('X-First-Test-Middleware', 'This is a test!');
return $response;
} }
} }
class SecondTestMiddleware implements MiddlewareInterface class SecondTestMiddleware implements IlluminateMiddlewareInterface
{ {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface public function handle(Request $request, Closure $next): Response
{ {
$response = $handler->handle($request); /** @var Response $response */
$response = $next($request);
return $response->withAddedHeader('X-Second-Test-Middleware', 'This is another test!'); $response->headers->set('X-Second-Test-Middleware', 'This is another test!');
return $response;
} }
} }

View File

@ -55,7 +55,7 @@ class RoutesTest extends TestCase
{ {
$this->extend( $this->extend(
(new Extend\Routes('api')) (new Extend\Routes('api'))
->remove('forum.show') ->remove('api.forum.show')
); );
$response = $this->send( $response = $this->send(
@ -72,7 +72,7 @@ class RoutesTest extends TestCase
{ {
$this->extend( $this->extend(
(new Extend\Routes('api')) (new Extend\Routes('api'))
->remove('forum.show') ->remove('api.forum.show')
->get('/', 'forum.show', CustomRoute::class) ->get('/', 'forum.show', CustomRoute::class)
); );

View File

@ -41,7 +41,7 @@ class ServiceProviderTest extends TestCase
$this->assertEquals( $this->assertEquals(
'overriden_by_custom_provider_register', 'overriden_by_custom_provider_register',
$this->app->getContainer()->make('flarum.forum.middleware') $this->app->getContainer()->make('flarum.forum.middleware')[0]
); );
} }
@ -60,7 +60,7 @@ class ServiceProviderTest extends TestCase
$this->assertEquals( $this->assertEquals(
'overriden_by_second_custom_provider_register', 'overriden_by_second_custom_provider_register',
$this->app->getContainer()->make('flarum.forum.middleware') $this->app->getContainer()->make('flarum.forum.middleware')[0]
); );
} }
@ -80,7 +80,7 @@ class ServiceProviderTest extends TestCase
$this->assertEquals( $this->assertEquals(
'overriden_by_third_custom_provider_boot', 'overriden_by_third_custom_provider_boot',
$this->app->getContainer()->make('flarum.forum.middleware') $this->app->getContainer()->make('flarum.forum.middleware')[0]
); );
} }
} }
@ -91,7 +91,7 @@ class CustomServiceProvider extends AbstractServiceProvider
{ {
// First we override the singleton here. // First we override the singleton here.
$this->app->extend('flarum.forum.middleware', function () { $this->app->extend('flarum.forum.middleware', function () {
return 'overriden_by_custom_provider_register'; return ['overriden_by_custom_provider_register'];
}); });
} }
} }
@ -102,7 +102,7 @@ class SecondCustomServiceProvider extends AbstractServiceProvider
{ {
// Second we check that the singleton was overriden here. // Second we check that the singleton was overriden here.
$this->app->extend('flarum.forum.middleware', function ($forumRoutes) { $this->app->extend('flarum.forum.middleware', function ($forumRoutes) {
return 'overriden_by_second_custom_provider_register'; return ['overriden_by_second_custom_provider_register'];
}); });
} }
} }
@ -113,7 +113,7 @@ class ThirdCustomProvider extends AbstractServiceProvider
{ {
// Third we override one last time here, to make sure this is the final result. // Third we override one last time here, to make sure this is the final result.
$this->app->extend('flarum.forum.middleware', function ($forumRoutes) { $this->app->extend('flarum.forum.middleware', function ($forumRoutes) {
return 'overriden_by_third_custom_provider_boot'; return ['overriden_by_third_custom_provider_boot'];
}); });
} }
} }

View File

@ -92,7 +92,12 @@ class ThrottleApiTest extends TestCase
} }
})); }));
$response = $this->send($this->request('POST', '/register')->withAttribute('bypassCsrfToken', true)); $response = $this->send(
tap(
$this->request('POST', '/register'),
fn (Request $request) => $request->attributes->set('bypassCsrfToken', true)
)
);
$this->assertEquals(429, $response->getStatusCode()); $this->assertEquals(429, $response->getStatusCode());
} }

View File

@ -22,7 +22,7 @@ class ContentTypeOptionsTest extends TestCase
$this->request('GET', '/') $this->request('GET', '/')
); );
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayHasKey('X-Content-Type-Options', $response->getHeaders()); $this->assertNotNull($response->headers->get('X-Content-Type-Options'));
$this->assertEquals('nosniff', $response->getHeader('X-Content-Type-Options')[0]); $this->assertEquals('nosniff', $response->headers->get('X-Content-Type-Options'));
} }
} }

View File

@ -22,7 +22,7 @@ class ReferrerPolicyTest extends TestCase
$this->request('GET', '/') $this->request('GET', '/')
); );
$this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(200, $response->getStatusCode());
$this->assertArrayHasKey('Referrer-Policy', $response->headers->all()); $this->assertNotNull($response->headers->get('Referrer-Policy'));
} }
/** /**