Skip to content

Commit 4400082

Browse files
authored
write tests for session cleanup (#541)
1 parent 604039f commit 4400082

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
class SessionCleanupTest extends UnityWebPortalTestCase
4+
{
5+
public function testSessionCleanup()
6+
{
7+
global $_SESSION;
8+
$this->switchUser("Normal");
9+
$first_session_id = session_id();
10+
$_SESSION["csrf_tokens"] = ["foobar"];
11+
// set last login timestamp to 1970-00-00 00:00
12+
// assume duration from epoch until now is greater than config session_cleanup_idle_seconds
13+
$_SESSION["LAST_ACTIVITY"] = 0;
14+
$this->switchUser("Normal");
15+
$this->assertEquals($first_session_id, session_id());
16+
$this->assertEmpty($_SESSION["csrf_tokens"]);
17+
}
18+
19+
public function testSessionNotCleanedUp()
20+
{
21+
global $_SESSION;
22+
$this->switchUser("Normal");
23+
$first_session_id = session_id();
24+
$_SESSION["csrf_tokens"] = ["foobar"];
25+
// set last login timestamp to a future timestamp
26+
// assume negative time delta is less than config session_cleanup_idle_seconds
27+
$_SESSION["LAST_ACTIVITY"] = time() + 999;
28+
$this->switchUser("Normal");
29+
$this->assertEquals($first_session_id, session_id());
30+
$this->assertEqualsCanonicalizing(["foobar"], $_SESSION["csrf_tokens"]);
31+
}
32+
}

test/phpunit-bootstrap.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ class UnityWebPortalTestCase extends TestCase
253253
{
254254
private ?string $last_user_nickname = null;
255255
private ?string $current_user_nickname = null;
256-
private array $uid_to_latest_session_id = [];
256+
private array $nickname_to_latest_session_id = [];
257257
// FIXME these names are wrong
258258
private static array $UID2ATTRIBUTES = [
259259
"user1_org1_test" => ["user1@org1.test", "foo", "bar", "user1@org1.test"],
@@ -529,12 +529,13 @@ function switchUser(
529529
if (session_status() === PHP_SESSION_ACTIVE) {
530530
session_write_close();
531531
}
532-
if (!$reuse_last_session || !array_key_exists($nickname, $this->uid_to_latest_session_id)) {
532+
$previous_session_id = $this->nickname_to_latest_session_id[$nickname] ?? null;
533+
if (!$reuse_last_session || !$previous_session_id) {
533534
$session_id = str_replace(["_", "@", "."], "-", uniqid($eppn . "_"));
534-
$this->uid_to_latest_session_id[$uid] = $session_id;
535+
$this->nickname_to_latest_session_id[$nickname] = $session_id;
535536
session_id($session_id);
536537
} else {
537-
session_id($this->uid_to_latest_session_id[$uid]);
538+
session_id($previous_session_id);
538539
}
539540
$this->last_user_nickname = $this->current_user_nickname;
540541
$this->current_user_nickname = $nickname;

0 commit comments

Comments
 (0)