66
77use LogicException ;
88use PHPUnit \Framework \Attributes \AllowMockObjectsWithoutExpectations ;
9+ use PHPUnit \Framework \Attributes \DataProvider ;
10+ use PHPUnit \Framework \MockObject \MockObject ;
911use PHPUnit \Framework \MockObject \Stub ;
1012use PHPUnit \Framework \TestCase ;
1113use Psr \Http \Message \ServerRequestInterface ;
2224use SimpleSAML \Module \oidc \Server \ResponseModes \ResponseModeInterface ;
2325use SimpleSAML \Module \oidc \Services \LoggerService ;
2426use SimpleSAML \Module \oidc \Utils \RequestParamsResolver ;
27+ use Stringable ;
2528
2629/**
30+ * The PKCE (RFC 7636) code challenge check at the authorization endpoint.
31+ *
32+ * A public client has no secret, so this challenge and the verifier checked against it at the token
33+ * endpoint are what bind an authorization code to the software which asked for it. Refusing a public
34+ * client which sends no challenge, and refusing a challenge which does not follow RFC-7636, are
35+ * therefore security controls rather than input tidiness. The token endpoint half is in
36+ * `CodeVerifierRuleTest`.
37+ *
2738 * @covers \SimpleSAML\Module\oidc\Server\RequestRules\Rules\CodeChallengeRule
2839 */
2940#[AllowMockObjectsWithoutExpectations]
3041class CodeChallengeRuleTest extends TestCase
3142{
43+ private const string CLIENT_ID = 'client123 ' ;
44+
45+
3246 protected CodeChallengeRule $ rule ;
3347
3448 protected Stub $ requestStub ;
@@ -41,7 +55,10 @@ class CodeChallengeRuleTest extends TestCase
4155
4256 protected string $ codeChallenge = '123123123123123123123123123123123123123123123123123123123123 ' ;
4357
44- protected Stub $ loggerServiceStub ;
58+ protected LoggerService &MockObject $ loggerServiceMock ;
59+
60+ /** @var array<int,array{level:string,message:string,context:array}> */
61+ protected array $ logRecords = [];
4562
4663 protected Stub $ requestParamsResolverStub ;
4764
@@ -63,7 +80,18 @@ protected function setUp(): void
6380 $ this ->resultBagStub = $ this ->createStub (ResultBagInterface::class);
6481 $ this ->redirectUriResult = new Result (ClientRedirectUriRule::class, 'https://some-uri.org ' );
6582 $ this ->stateResult = new Result (StateRule::class, '123 ' );
66- $ this ->loggerServiceStub = $ this ->createStub (LoggerService::class);
83+ $ this ->loggerServiceMock = $ this ->createMock (LoggerService::class);
84+ foreach (['debug ' , 'info ' , 'notice ' , 'warning ' , 'error ' ] as $ level ) {
85+ $ this ->loggerServiceMock ->method ($ level )->willReturnCallback (
86+ function (string |Stringable $ message , array $ context = []) use ($ level ): void {
87+ $ this ->logRecords [] = [
88+ 'level ' => $ level ,
89+ 'message ' => (string )$ message ,
90+ 'context ' => $ context ,
91+ ];
92+ },
93+ );
94+ }
6795 $ this ->requestParamsResolverStub = $ this ->createStub (RequestParamsResolver::class);
6896 $ this ->clientStub = $ this ->createStub (ClientEntityInterface::class);
6997 $ this ->clientIdResult = new Result (ClientRule::class, $ this ->clientStub );
@@ -94,7 +122,7 @@ public function testCheckRuleRedirectUriDependency(): void
94122 {
95123 $ resultBag = new ResultBag ();
96124 $ this ->expectException (LogicException::class);
97- $ this ->sut ()->checkRule ($ this ->requestStub , $ resultBag , $ this ->loggerServiceStub , [], $ this ->responseModeStub );
125+ $ this ->sut ()->checkRule ($ this ->requestStub , $ resultBag , $ this ->loggerServiceMock , [], $ this ->responseModeStub );
98126 }
99127
100128
@@ -107,7 +135,7 @@ public function testCheckRuleStateDependency(): void
107135 $ resultBag = new ResultBag ();
108136 $ resultBag ->add ($ this ->redirectUriResult );
109137 $ this ->expectException (LogicException::class);
110- $ this ->sut ()->checkRule ($ this ->requestStub , $ resultBag , $ this ->loggerServiceStub , [], $ this ->responseModeStub );
138+ $ this ->sut ()->checkRule ($ this ->requestStub , $ resultBag , $ this ->loggerServiceMock , [], $ this ->responseModeStub );
111139 }
112140
113141
@@ -122,7 +150,7 @@ public function testCheckRuleNoCodeReturnsNullForConfidentialClients(): void
122150 $ result = $ this ->sut ()->checkRule (
123151 $ this ->requestStub ,
124152 $ resultBag ,
125- $ this ->loggerServiceStub ,
153+ $ this ->loggerServiceMock ,
126154 [],
127155 $ this ->responseModeStub ,
128156 );
@@ -131,15 +159,73 @@ public function testCheckRuleNoCodeReturnsNullForConfidentialClients(): void
131159 }
132160
133161
162+ /**
163+ * A challenge which is present is held to RFC-7636's shape (43 to 128 unreserved characters) whoever
164+ * sent it. An empty value is one of these rather than an absent challenge: the request params resolver
165+ * casts a present-but-empty param to '', which is not null, so a public client which sends
166+ * `code_challenge=` is answered for the shape and not for the missing challenge.
167+ *
168+ * @return array<string,array{0:string,1:bool}>
169+ */
170+ public static function malformedCodeChallengeProvider (): array
171+ {
172+ return [
173+ 'one character short of the minimum ' => [str_repeat ('a ' , 42 ), false ],
174+ 'one character past the maximum ' => [str_repeat ('a ' , 129 ), false ],
175+ 'empty, which the resolver reports as a present param ' => ['' , false ],
176+ 'standard base64 rather than base64url (+) ' => [str_repeat ('a ' , 42 ) . '+ ' , false ],
177+ 'standard base64 rather than base64url (/) ' => [str_repeat ('a ' , 42 ) . '/ ' , false ],
178+ 'base64 padding ' => [str_repeat ('a ' , 42 ) . '= ' , false ],
179+ 'a space ' => [str_repeat ('a ' , 42 ) . ' ' , false ],
180+ // Only a single *trailing* newline slips past the pattern (7.21); these do not.
181+ 'a leading newline ' => ["\n" . str_repeat ('a ' , 43 ), false ],
182+ 'an embedded newline ' => [str_repeat ('a ' , 20 ) . "\n" . str_repeat ('a ' , 23 ), false ],
183+ 'two trailing newlines ' => [str_repeat ('a ' , 43 ) . "\n\n" , false ],
184+ 'a trailing carriage return ' => [str_repeat ('a ' , 43 ) . "\r" , false ],
185+ 'a trailing null byte ' => [str_repeat ('a ' , 43 ) . "\0" , false ],
186+ 'a confidential client is held to the same shape ' => [str_repeat ('a ' , 42 ), true ],
187+ ];
188+ }
189+
190+
134191 /**
135192 * @throws \Throwable
136193 */
137- public function testCheckRuleInvalidCodeChallengeThrows (): void
194+ #[DataProvider('malformedCodeChallengeProvider ' )]
195+ public function testCheckRuleInvalidCodeChallengeThrows (string $ codeChallenge , bool $ isConfidential ): void
138196 {
139- $ resultBag = $ this ->prepareValidResultBag ();
140- $ this ->requestParamsResolverStub ->method ('getAsStringBasedOnAllowedMethods ' )->willReturn ('too-short ' );
141- $ this ->expectException (OidcServerException::class);
142- $ this ->sut ()->checkRule ($ this ->requestStub , $ resultBag , $ this ->loggerServiceStub , [], $ this ->responseModeStub );
197+ // The rule fixes the shape RFC-7636 gives a challenge -- 43 to 128 unreserved characters -- so a
198+ // value outside it cannot be the transformation of any verifier the token endpoint will see.
199+ $ this ->clientStub ->method ('isConfidential ' )->willReturn ($ isConfidential );
200+ $ this ->clientStub ->method ('getIdentifier ' )->willReturn (self ::CLIENT_ID );
201+ $ this ->requestParamsResolverStub ->method ('getAsStringBasedOnAllowedMethods ' )->willReturn ($ codeChallenge );
202+
203+ try {
204+ $ this ->sut ()->checkRule (
205+ $ this ->requestStub ,
206+ $ this ->prepareValidResultBag (),
207+ $ this ->loggerServiceMock ,
208+ [],
209+ $ this ->responseModeStub ,
210+ );
211+ $ this ->fail ('A code_challenge which does not follow RFC-7636 must be refused. ' );
212+ } catch (OidcServerException $ exception ) {
213+ $ this ->assertSame ('invalid_request ' , $ exception ->getErrorType ());
214+ $ this ->assertSame ('Code Challenge must follow the specifications of RFC-7636. ' , $ exception ->getHint ());
215+ $ this ->assertSame ('https://some-uri.org ' , $ exception ->getRedirectUri ());
216+ $ this ->assertSame ('123 ' , $ exception ->getPayload ()['state ' ]);
217+ }
218+
219+ $ this ->assertSame (
220+ [
221+ [
222+ 'message ' => 'Authorization request rejected: `code_challenge` does not follow RFC-7636 ' .
223+ '(wrong length or character set). ' ,
224+ 'context ' => ['client_id ' => self ::CLIENT_ID ],
225+ ],
226+ ],
227+ $ this ->logRecordsOfLevel ('notice ' ),
228+ );
143229 }
144230
145231
@@ -155,7 +241,7 @@ public function testCheckRuleForValidCodeChallenge(): void
155241 $ result = $ this ->sut ()->checkRule (
156242 $ this ->requestStub ,
157243 $ resultBag ,
158- $ this ->loggerServiceStub ,
244+ $ this ->loggerServiceMock ,
159245 [],
160246 $ this ->responseModeStub ,
161247 );
@@ -165,6 +251,110 @@ public function testCheckRuleForValidCodeChallenge(): void
165251 }
166252
167253
254+ /**
255+ * @throws \Throwable
256+ */
257+ public function testRefusesAPublicClientWhichSendsNoCodeChallenge (): void
258+ {
259+ // Without a challenge there is nothing for the token endpoint to check a verifier against, so a
260+ // stolen authorization code would be redeemable by whoever holds it.
261+ $ this ->clientStub ->method ('isConfidential ' )->willReturn (false );
262+ $ this ->clientStub ->method ('getIdentifier ' )->willReturn (self ::CLIENT_ID );
263+ $ this ->requestParamsResolverStub ->method ('getAsStringBasedOnAllowedMethods ' )->willReturn (null );
264+
265+ try {
266+ $ this ->sut ()->checkRule (
267+ $ this ->requestStub ,
268+ $ this ->prepareValidResultBag (),
269+ $ this ->loggerServiceMock ,
270+ [],
271+ $ this ->responseModeStub ,
272+ );
273+ $ this ->fail ('A public client which sends no code_challenge must be refused. ' );
274+ } catch (OidcServerException $ exception ) {
275+ $ this ->assertSame ('invalid_request ' , $ exception ->getErrorType ());
276+ $ this ->assertSame (400 , $ exception ->getHttpStatusCode ());
277+ $ this ->assertSame ('Code Challenge must be provided for public clients. ' , $ exception ->getHint ());
278+ $ this ->assertSame ('https://some-uri.org ' , $ exception ->getRedirectUri ());
279+ $ payload = $ exception ->getPayload ();
280+ $ this ->assertSame ('invalid_request ' , $ payload ['error ' ]);
281+ // The hint reaches the client in the error description (`OidcServerException::create()`).
282+ $ this ->assertStringEndsWith (
283+ '(Code Challenge must be provided for public clients.) ' ,
284+ (string )$ payload ['error_description ' ],
285+ );
286+ $ this ->assertSame ('123 ' , $ payload ['state ' ]);
287+ }
288+
289+ $ this ->assertSame (
290+ [
291+ [
292+ 'message ' => 'Authorization request rejected: `code_challenge` (PKCE) is required for ' .
293+ 'public clients. ' ,
294+ 'context ' => ['client_id ' => self ::CLIENT_ID ],
295+ ],
296+ ],
297+ $ this ->logRecordsOfLevel ('notice ' ),
298+ );
299+ }
300+
301+
302+ /**
303+ * PCRE's `$` matches at the end of the subject or before a final newline, and the rule's pattern uses
304+ * neither `\z` nor the `D` modifier, so a challenge of valid shape followed by one newline is accepted
305+ * today (a carriage return is not: it is not `$`'s exception). Pinned as it stands, with the fix queued
306+ * as 7.21 -- the same pattern is in `CodeVerifierRule.php:61`, so both halves of PKCE take it together.
307+ * Nothing is bypassed by it: such a challenge is still redeemable only by a verifier which hashes to it.
308+ *
309+ * @throws \Throwable
310+ */
311+ /**
312+ * @return array<string,array{0:string}>
313+ */
314+ public static function newlineTerminatedCodeChallengeProvider (): array
315+ {
316+ return [
317+ 'the shortest allowed, plus a newline ' => [str_repeat ('a ' , 43 ) . "\n" ],
318+ // 129 characters, so the laxness widens the maximum by one as well as the character set.
319+ 'the longest allowed, plus a newline ' => [str_repeat ('a ' , 128 ) . "\n" ],
320+ ];
321+ }
322+
323+
324+ #[DataProvider('newlineTerminatedCodeChallengeProvider ' )]
325+ public function testAcceptsACodeChallengeWithOneTrailingNewline (string $ codeChallenge ): void
326+ {
327+ $ this ->clientStub ->method ('isConfidential ' )->willReturn (false );
328+ $ this ->requestParamsResolverStub ->method ('getAsStringBasedOnAllowedMethods ' )->willReturn ($ codeChallenge );
329+
330+ $ result = $ this ->sut ()->checkRule (
331+ $ this ->requestStub ,
332+ $ this ->prepareValidResultBag (),
333+ $ this ->loggerServiceMock ,
334+ [],
335+ $ this ->responseModeStub ,
336+ );
337+
338+ $ this ->assertSame ($ codeChallenge , $ result ?->getValue());
339+ $ this ->assertSame ([], $ this ->logRecordsOfLevel ('notice ' ));
340+ }
341+
342+
343+ /**
344+ * The records of one level, so that a test pins the event it is about without being coupled to the
345+ * rule's entry trace.
346+ *
347+ * @return array<int,array{message:string,context:array}>
348+ */
349+ protected function logRecordsOfLevel (string $ level ): array
350+ {
351+ return array_values (array_map (
352+ static fn (array $ record ): array => ['message ' => $ record ['message ' ], 'context ' => $ record ['context ' ]],
353+ array_filter ($ this ->logRecords , static fn (array $ record ): bool => $ record ['level ' ] === $ level ),
354+ ));
355+ }
356+
357+
168358 protected function prepareValidResultBag (): ResultBag
169359 {
170360 $ resultBag = new ResultBag ();
0 commit comments