File tree Expand file tree Collapse file tree 2 files changed +17
-4
lines changed
packages/http/src/Session Expand file tree Collapse file tree 2 files changed +17
-4
lines changed Original file line number Diff line number Diff line change 77use Tempest \Clock \Clock ;
88use Tempest \Core \AppConfig ;
99use Tempest \Core \Priority ;
10+ use Tempest \Cryptography \Encryption \Encrypter ;
1011use Tempest \Http \Cookie \Cookie ;
1112use Tempest \Http \Cookie \CookieManager ;
1213use Tempest \Http \Method ;
@@ -29,6 +30,7 @@ public function __construct(
2930 private SessionConfig $ sessionConfig ,
3031 private CookieManager $ cookies ,
3132 private Clock $ clock ,
33+ private Encrypter $ encrypter ,
3234 ) {}
3335
3436 public function __invoke (Request $ request , HttpMiddlewareCallable $ next ): Response
@@ -67,9 +69,14 @@ private function ensureTokenMatches(Request $request): void
6769 {
6870 $ tokenFromRequest = $ request ->get (
6971 key: Session::CSRF_TOKEN_KEY ,
70- default: $ request ->headers ->get (self ::CSRF_HEADER_KEY ),
7172 );
7273
74+ if (! $ tokenFromRequest && $ request ->headers ->has (self ::CSRF_HEADER_KEY )) {
75+ $ tokenFromRequest = $ this ->encrypter ->decrypt (
76+ urldecode ($ request ->headers ->get (self ::CSRF_HEADER_KEY )),
77+ );
78+ }
79+
7380 if (! $ tokenFromRequest ) {
7481 throw new CsrfTokenDidNotMatch ();
7582 }
Original file line number Diff line number Diff line change 55use PHPUnit \Framework \Attributes \TestWith ;
66use Tempest \Core \AppConfig ;
77use Tempest \Core \Environment ;
8+ use Tempest \Cryptography \Encryption \Encrypter ;
89use Tempest \Http \Cookie \Cookie ;
910use Tempest \Http \GenericRequest ;
1011use Tempest \Http \Method ;
@@ -84,14 +85,19 @@ public function test_matches_from_body(): void
8485 ->assertOk ();
8586 }
8687
87- public function test_matches_from_header (): void
88+ public function test_matches_from_header_when_encrypted (): void
8889 {
8990 $ this ->container ->get (AppConfig::class)->environment = Environment::PRODUCTION ;
90-
9191 $ session = $ this ->container ->get (Session::class);
9292
93+ // Encrypt the token as it would be in a real request
94+ $ sessionCookieValue = $ this ->container
95+ ->get (Encrypter::class)
96+ ->encrypt ($ session ->token )
97+ ->serialize ();
98+
9399 $ this ->http
94- ->post ('/test ' , headers: [VerifyCsrfMiddleware::CSRF_HEADER_KEY => $ session -> token ])
100+ ->post ('/test ' , headers: [VerifyCsrfMiddleware::CSRF_HEADER_KEY => $ sessionCookieValue ])
95101 ->assertOk ();
96102 }
97103
You can’t perform that action at this time.
0 commit comments