Skip to content

Commit 8cf955d

Browse files
committed
Give the authentication source Source and Destination before login
An authentication source that reports failed logins, for example in F-ticks, reads $state['Source']['entityid'] and $state['Destination']['entityid']. casserver set them only after login, for the authproc filters, so a failed CAS login named neither entity. handleAuthenticate() now passes both to Auth\Simple::login(), with the values the filters see after a successful login: Source comes from resolveIdpEntityId(), now shared with runAuthProcs(), and Destination is the requesting service, left out when the request names none. This covers interactive, renewed and passive logins. A session keeps neither key, so login()'s check that a resumed state belongs to the requested service does not bind a session to its first service. The tests pin both the equal values and that. Assisted-by: Claude Code (claude-opus-5-5, implementation & unit tests) Assisted-by: Google Antigravity (gemini-3.8-flash-high, review)
1 parent c84be68 commit 8cf955d

5 files changed

Lines changed: 264 additions & 2 deletions

File tree

‎config/module_casserver.php.dist‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ $config = [
102102
* as $state['Source']['entityid']. Filters that key off the authenticating entity (federation
103103
* logging such as F-ticks, per-entity authorization, audit trails) need it. The requesting CAS
104104
* service URL is made available to the same filters as $state['Destination']['entityid'].
105+
* The authentication source gets both in the login state before the user logs in, so that it can
106+
* report a failed login against them.
105107
*
106108
* NOTE: this is unrelated to the ?entityId= query parameter of the login endpoint, which selects
107109
* which upstream SAML IdP the authsource should authenticate against.

‎docs/ChangeLog.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [Unreleased]
4+
5+
### Changed
6+
7+
- Give the authentication source Source and Destination before login, so that it can report a failed login against them (Marko Ivančić)
8+
39
## [7.0.5] - 2026-08-11
410

511
### Changed

‎src/Cas/AttributeExtractor.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ protected function runAuthProcs(array &$state): void
140140

141141

142142
/**
143-
* Resolve the entity ID that casserver presents to the authproc filters as the authenticating IdP.
143+
* Resolve the entity ID that casserver presents as the authenticating IdP, to the authentication
144+
* source before login and to the authproc filters after it.
144145
*
145146
* casserver has no entity ID of its own, so the value is resolved in the following order:
146147
* whatever the state already carries, then the 'idp_entity_id' configuration option, and finally
@@ -152,7 +153,7 @@ protected function runAuthProcs(array &$state): void
152153
* @return string
153154
* @throws \Exception
154155
*/
155-
private function resolveIdpEntityId(mixed $stateEntityId): string
156+
public function resolveIdpEntityId(mixed $stateEntityId = null): string
156157
{
157158
if (\is_string($stateEntityId) && $stateEntityId !== '') {
158159
return $stateEntityId;

‎src/Controller/LoginController.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ public function login(
193193
forceAuthn: $forceAuthn,
194194
returnToUrl: $returnToUrl,
195195
entityId: $entityId,
196+
serviceUrl: $serviceUrl,
196197
);
197198
}
198199

@@ -501,19 +502,22 @@ private function instantiateClassDependencies(): void
501502
* @param bool $forceAuthn
502503
* @param string $returnToUrl
503504
* @param string|null $entityId
505+
* @param string|null $serviceUrl
504506
*
505507
* @return \SimpleSAML\HTTP\RunnableResponse
506508
*/
507509
private function handleInteractiveAuthenticate(
508510
bool $forceAuthn,
509511
string $returnToUrl,
510512
?string $entityId,
513+
?string $serviceUrl,
511514
): RunnableResponse {
512515
return $this->handleAuthenticate(
513516
forceAuthn: $forceAuthn,
514517
gateway: false,
515518
returnToUrl: $returnToUrl,
516519
entityId: $entityId,
520+
serviceUrl: $serviceUrl,
517521
);
518522
}
519523

@@ -548,6 +552,7 @@ private function handleUnauthenticatedGateway(
548552
gateway: true,
549553
returnToUrl: $returnToUrl,
550554
entityId: $entityId,
555+
serviceUrl: $serviceUrl,
551556
);
552557
}
553558

@@ -559,6 +564,7 @@ private function handleUnauthenticatedGateway(
559564
* @param bool $gateway Whether authentication should be passive/non-interactive
560565
* @param string $returnToUrl URL to return to after authentication
561566
* @param string|null $entityId Optional specific IdP entity ID to use
567+
* @param string|null $serviceUrl The requesting CAS service, if the request names one
562568
*
563569
* @return \SimpleSAML\HTTP\RunnableResponse Response containing the login redirect
564570
*/
@@ -567,13 +573,22 @@ private function handleAuthenticate(
567573
bool $gateway,
568574
string $returnToUrl,
569575
?string $entityId,
576+
?string $serviceUrl,
570577
): RunnableResponse {
571578
$params = [
572579
'ForceAuthn' => $forceAuthn,
573580
'isPassive' => $gateway,
574581
'ReturnTo' => $returnToUrl,
582+
// The same entities the authproc filters see after a successful login, so that an authentication
583+
// source can report a failed login against them. They end with the login state: a session does not
584+
// keep them, so they do not bind it to this service.
585+
'Source' => ['entityid' => $this->attributeExtractor->resolveIdpEntityId()],
575586
];
576587

588+
if (!empty($serviceUrl)) {
589+
$params['Destination'] = ['entityid' => $serviceUrl];
590+
}
591+
577592
if (isset($entityId)) {
578593
$params['saml:idp'] = $entityId;
579594
}

‎tests/src/Controller/LoginControllerTest.php‎

Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPUnit\Framework\TestCase;
1010
use SimpleSAML\Auth\ProcessingChain;
1111
use SimpleSAML\Auth\Simple;
12+
use SimpleSAML\Auth\State;
1213
use SimpleSAML\Configuration;
1314
use SimpleSAML\HTTP\RunnableResponse;
1415
use SimpleSAML\Module;
@@ -160,6 +161,8 @@ public static function loginOnAuthenticateParameters(): array
160161
'isPassive' => false,
161162
// phpcs:ignore Generic.Files.LineLength.TooLong
162163
'ReturnTo' => 'http://localhost/?service=https%3A%2F%2Fexample.com%2Fssp%2Fmodule.php%2Fcas%2Flinkback.php',
164+
'Source' => ['entityid' => 'http://localhost/'],
165+
'Destination' => ['entityid' => 'https://example.com/ssp/module.php/cas/linkback.php'],
163166
],
164167
[],
165168
],
@@ -174,6 +177,8 @@ public static function loginOnAuthenticateParameters(): array
174177
'isPassive' => false,
175178
// phpcs:ignore Generic.Files.LineLength.TooLong
176179
'ReturnTo' => 'http://localhost/?service=https%3A%2F%2Fexample.com%2Fssp%2Fmodule.php%2Fcas%2Flinkback.php&entityId=http%3A%2F%2Flocalhost%2FentityId%2Fsso',
180+
'Source' => ['entityid' => 'http://localhost/'],
181+
'Destination' => ['entityid' => 'https://example.com/ssp/module.php/cas/linkback.php'],
177182
],
178183
[],
179184
],
@@ -187,6 +192,8 @@ public static function loginOnAuthenticateParameters(): array
187192
'isPassive' => false,
188193
// phpcs:ignore Generic.Files.LineLength.TooLong
189194
'ReturnTo' => 'http://localhost/?service=https%3A%2F%2Fexample.com%2Fssp%2Fmodule.php%2Fcas%2Flinkback.php&scope=desktop',
195+
'Source' => ['entityid' => 'http://localhost/'],
196+
'Destination' => ['entityid' => 'https://example.com/ssp/module.php/cas/linkback.php'],
190197
'saml:IDPList' => [
191198
'http://localhost/entityId/sso/scope/A',
192199
'http://localhost/entityId/sso/scope/B',
@@ -210,6 +217,8 @@ public static function loginOnAuthenticateParameters(): array
210217
'isPassive' => false,
211218
// phpcs:ignore Generic.Files.LineLength.TooLong
212219
'ReturnTo' => 'http://localhost/?service=https%3A%2F%2Fexample.com%2Fssp%2Fmodule.php%2Fcas%2Flinkback.php&scope=desktop',
220+
'Source' => ['entityid' => 'http://localhost/'],
221+
'Destination' => ['entityid' => 'https://example.com/ssp/module.php/cas/linkback.php'],
213222
'saml:idp' => 'http://localhost/entityId/sso/scope/A',
214223
],
215224
[
@@ -255,6 +264,231 @@ public function testAuthSourceLogin(array $requestParameters, array $loginParame
255264
}
256265

257266

267+
public function testLoginParamsTakeSourceFromTheConfiguration(): void
268+
{
269+
$idpEntityId = 'https://login.example.org/idp/metadata.php';
270+
$moduleConfig = $this->moduleConfig;
271+
$moduleConfig['idp_entity_id'] = $idpEntityId;
272+
273+
$loginParams = $this->loginParamsFor(
274+
$moduleConfig,
275+
['service' => 'https://example.com/ssp/module.php/cas/linkback.php'],
276+
);
277+
278+
$this->assertEquals(['entityid' => $idpEntityId], $loginParams['Source'] ?? null);
279+
}
280+
281+
282+
/**
283+
* Older CAS clients name the service with TARGET.
284+
*/
285+
public function testLoginParamsTakeDestinationFromTarget(): void
286+
{
287+
$serviceUrl = 'https://example.com/ssp/module.php/cas/linkback.php';
288+
289+
$loginParams = $this->loginParamsFor($this->moduleConfig, ['TARGET' => $serviceUrl]);
290+
291+
$this->assertEquals(['entityid' => $serviceUrl], $loginParams['Destination'] ?? null);
292+
}
293+
294+
295+
/**
296+
* A login to casserver itself has no service to name, and such a login does not run authproc filters either.
297+
*/
298+
public function testLoginParamsHaveNoDestinationWithoutAService(): void
299+
{
300+
$loginParams = $this->loginParamsFor($this->moduleConfig, []);
301+
302+
$this->assertEquals(['entityid' => 'http://localhost/'], $loginParams['Source'] ?? null);
303+
$this->assertArrayNotHasKey('Destination', $loginParams);
304+
}
305+
306+
307+
/**
308+
* Renew makes a logged-in user log in again, and that login can fail like any other.
309+
*/
310+
public function testLoginParamsOfARenewedLoginNameTheEntities(): void
311+
{
312+
$serviceUrl = 'https://example.com/ssp/module.php/cas/linkback.php';
313+
314+
$loginParams = $this->loginParamsFor(
315+
$this->moduleConfig,
316+
['service' => $serviceUrl, 'renew' => true, 'renewId' => 'not-the-renew-id-of-this-session'],
317+
authenticated: true,
318+
);
319+
320+
$this->assertTrue($loginParams['ForceAuthn'] ?? null);
321+
$this->assertEquals(['entityid' => 'http://localhost/'], $loginParams['Source'] ?? null);
322+
$this->assertEquals(['entityid' => $serviceUrl], $loginParams['Destination'] ?? null);
323+
}
324+
325+
326+
public static function entitiesProvider(): array
327+
{
328+
$serviceUrl = 'https://example.com/ssp/module.php/cas/linkback.php';
329+
330+
return [
331+
'Configured' => [
332+
'https://login.example.org/idp/metadata.php',
333+
'https://login.example.org/idp/metadata.php',
334+
$serviceUrl,
335+
],
336+
'Base URL when not configured' => [null, 'http://localhost/', $serviceUrl],
337+
// login() checks the service against the legal URLs without its session ID, and keeps it as it came
338+
'Service with a session ID' => [null, 'http://localhost/', $serviceUrl . ';jsessionid=abc123'],
339+
];
340+
}
341+
342+
343+
/**
344+
* An authentication source reporting a failed login has to name the same entities as an authproc
345+
* filter reporting a successful one.
346+
*
347+
* @throws \Exception
348+
*/
349+
#[DataProvider('entitiesProvider')]
350+
public function testLoginParamsNameTheEntitiesTheAuthprocFiltersSee(
351+
?string $configured,
352+
string $expected,
353+
string $serviceUrl,
354+
): void {
355+
$moduleConfig = $this->moduleConfig;
356+
if ($configured !== null) {
357+
$moduleConfig['idp_entity_id'] = $configured;
358+
}
359+
$moduleConfig['authproc'] = [
360+
[
361+
'class' => 'core:PHP',
362+
'code' => '$attributes["observedIdpEntityId"] = [$state["Source"]["entityid"] ?? "MISSING"];'
363+
. '$attributes["observedSpEntityId"] = [$state["Destination"]["entityid"] ?? "MISSING"];',
364+
],
365+
];
366+
367+
$loginParams = $this->loginParamsFor($moduleConfig, ['service' => $serviceUrl]);
368+
$ticket = $this->serviceTicketAfterLogin($moduleConfig, $serviceUrl, $loginParams);
369+
370+
$this->assertEquals(['entityid' => $expected], $loginParams['Source'] ?? null);
371+
$this->assertEquals(['entityid' => $serviceUrl], $loginParams['Destination'] ?? null);
372+
$this->assertEquals([$expected], $ticket['attributes']['observedIdpEntityId'] ?? null);
373+
$this->assertEquals([$serviceUrl], $ticket['attributes']['observedSpEntityId'] ?? null);
374+
}
375+
376+
377+
/**
378+
* A session opened by a login for one service has to stay usable for another. login() refuses a
379+
* service other than the one in the state, so Destination must not reach the session.
380+
*
381+
* @throws \Exception
382+
*/
383+
public function testLoginParamsDoNotBindTheSessionToTheService(): void
384+
{
385+
$otherServiceUrl = 'https://other.example.com/cas/linkback.php';
386+
$moduleConfig = $this->moduleConfig;
387+
$moduleConfig['legal_service_urls'][] = $otherServiceUrl;
388+
389+
$loginParams = $this->loginParamsFor(
390+
$moduleConfig,
391+
['service' => 'https://example.com/ssp/module.php/cas/linkback.php'],
392+
);
393+
$ticket = $this->serviceTicketAfterLogin($moduleConfig, $otherServiceUrl, $loginParams);
394+
395+
$this->assertEquals($otherServiceUrl, $ticket['service'] ?? null);
396+
}
397+
398+
399+
/**
400+
* What the authentication source is asked to log in with.
401+
*
402+
* @param array<string, mixed> $moduleConfig
403+
* @param array<string, mixed> $queryParameters
404+
* @return array<string, mixed>
405+
*/
406+
private function loginParamsFor(array $moduleConfig, array $queryParameters, bool $authenticated = false): array
407+
{
408+
$controllerMock = $this->getMockBuilder(LoginController::class)
409+
->setConstructorArgs([
410+
$this->sspConfig,
411+
Configuration::loadFromArray($moduleConfig),
412+
$this->authSimpleMock,
413+
$this->httpUtils,
414+
])
415+
->onlyMethods(['getSession'])
416+
->getMock();
417+
$controllerMock->expects($this->once())->method('getSession')->willReturn($this->sessionMock);
418+
$this->sessionMock->expects($this->once())->method('getSessionId')->willReturn(session_create_id());
419+
$this->authSimpleMock->expects($this->atMost(1))->method('isAuthenticated')->willReturn($authenticated);
420+
421+
$loginRequest = Request::create(
422+
uri: Module::getModuleURL('casserver/login'),
423+
parameters: $queryParameters,
424+
);
425+
$response = $this->callLogin($controllerMock, $loginRequest, $queryParameters);
426+
427+
$this->assertInstanceOf(RunnableResponse::class, $response);
428+
$this->assertEquals('login', ((array)$response->getCallable())[1] ?? '');
429+
430+
return $response->getArguments()[0] ?? [];
431+
}
432+
433+
434+
/**
435+
* The service ticket issued once the user is back from a login which those parameters started.
436+
* The session holds what SSP keeps of the completed login state, not the state itself.
437+
*
438+
* @param array<string, mixed> $moduleConfig
439+
* @param array<string, mixed> $loginParams
440+
* @return array<string, mixed>
441+
* @throws \Exception
442+
*/
443+
private function serviceTicketAfterLogin(array $moduleConfig, string $serviceUrl, array $loginParams): array
444+
{
445+
$authData = State::getPersistentAuthData(array_merge($loginParams, [
446+
'Attributes' => ['eduPersonPrincipalName' => ['testuser@example.com']],
447+
'Expire' => 9999999999,
448+
]));
449+
450+
$authSimpleMock = $this->getMockBuilder(Simple::class)
451+
->disableOriginalConstructor()
452+
->onlyMethods(['getAuthData', 'isAuthenticated', 'getAuthDataArray'])
453+
->getMock();
454+
$authSimpleMock->expects($this->atLeastOnce())->method('isAuthenticated')->willReturn(true);
455+
$authSimpleMock->expects($this->once())->method('getAuthData')->with('Expire')->willReturn(9999999999);
456+
$authSimpleMock->expects($this->once())->method('getAuthDataArray')->willReturn($authData);
457+
458+
$sessionMock = $this->getMockBuilder(Session::class)
459+
->disableOriginalConstructor()
460+
->onlyMethods(['getSessionId'])
461+
->getMock();
462+
$sessionMock->expects($this->exactly(2))->method('getSessionId')->willReturn(session_create_id());
463+
464+
$controllerMock = $this->getMockBuilder(LoginController::class)
465+
->setConstructorArgs([
466+
$this->sspConfig,
467+
Configuration::loadFromArray($moduleConfig),
468+
$authSimpleMock,
469+
$this->httpUtils,
470+
])
471+
->onlyMethods(['getSession'])
472+
->getMock();
473+
$controllerMock->expects($this->once())->method('getSession')->willReturn($sessionMock);
474+
475+
$queryParameters = ['service' => $serviceUrl];
476+
$loginRequest = Request::create(
477+
uri: Module::getModuleURL('casserver/login'),
478+
parameters: $queryParameters,
479+
);
480+
$response = $this->callLogin($controllerMock, $loginRequest, $queryParameters);
481+
482+
$this->assertInstanceOf(RunnableResponse::class, $response);
483+
$ticketId = array_values($response->getArguments()[1])[0] ?? null;
484+
$this->assertIsString($ticketId);
485+
$ticket = $controllerMock->getTicketStore()->getTicket($ticketId);
486+
$this->assertIsArray($ticket);
487+
488+
return $ticket;
489+
}
490+
491+
258492
/**
259493
* Check authenticated with debugMode false
260494
*/
@@ -625,6 +859,10 @@ public function testGatewayPassiveEnabledPerformsPassiveAttempt(): void
625859
$this->assertTrue($actualLoginParams['isPassive']);
626860
$this->assertArrayHasKey('ReturnTo', $actualLoginParams);
627861
$this->assertIsString($actualLoginParams['ReturnTo']);
862+
863+
// A passive attempt names the same entities as an interactive login
864+
$this->assertEquals(['entityid' => 'http://localhost/'], $actualLoginParams['Source'] ?? null);
865+
$this->assertEquals(['entityid' => $params['service']], $actualLoginParams['Destination'] ?? null);
628866
}
629867

630868

0 commit comments

Comments
 (0)