Tests für Anmeldung und Controller, PHP 8.1, Sprach-Fallback
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 53s
CI / Unit Tests & Static Analysis (push) Successful in 40s
CI / PHP Lint (pull_request) Successful in 39s
CI / PHP Lint-1 (pull_request) Successful in 44s
CI / Unit Tests & Static Analysis (pull_request) Successful in 44s
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 53s
CI / Unit Tests & Static Analysis (push) Successful in 40s
CI / PHP Lint (pull_request) Successful in 39s
CI / PHP Lint-1 (pull_request) Successful in 44s
CI / Unit Tests & Static Analysis (pull_request) Successful in 44s
Bisher deckten die Tests nur Hilfsklassen ab. Neu sind die beiden Stellen, an denen ein Fehler richtig weh tut: - AuthTest (12 Fälle): richtige und falsche Anmeldung, Rate-Limit greift vor der Passwortprüfung, 2FA-Nutzer gilt vor dem Code ausdrücklich nicht als angemeldet, CSRF-Prüfung, und die Client-IP hinter einem Proxy – inklusive der Fälle, in denen X-Forwarded-For ignoriert werden muss - UniFiControllerTest (8 Fälle): die Auswahl des eigenen Vouchers. Der Controller liefert Voucher unsortiert; wer den ersten nimmt, gibt bei parallelen Anfragen den Code eines anderen Gastes aus. Dazu QoS-Payload und die Fehlerfälle. Dafür nötig: Auth nimmt die Datenbank optional über den Konstruktor entgegen (ohne Argument unverändert), und UniFiController::apiRequest() ist protected statt private, damit Tests aufgezeichnete Antworten einspielen können. Beide Tests brauchen weder Datenbank noch Netz. PHP-Anforderung von 7.4 auf 8.1 gehoben: Composer, CI-Matrix (8.1/8.3), Docker-Image (8.3) und README. Die 7.4-Angabe war ohnehin ungeprüft. I18n: fehlt ein Schlüssel in der gewählten Sprache, erscheint jetzt der deutsche Text statt des technischen Schlüssels. PHPStan deckt zusätzlich VoucherService und I18n ab. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
b7e0f67a50
commit
a36dcbba27
10 changed files with 1344 additions and 930 deletions
214
tests/AuthTest.php
Normal file
214
tests/AuthTest.php
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use Auth;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
require_once __DIR__ . '/../includes/Auth.php';
|
||||
|
||||
/**
|
||||
* Datenbank-Attrappe für die Anmeldung: beantwortet genau die Abfragen,
|
||||
* die Auth stellt, und merkt sich schreibende Aufrufe.
|
||||
*/
|
||||
class FakeAuthDb
|
||||
{
|
||||
/** @var array<int, array> */
|
||||
public array $users = [];
|
||||
public int $recentAttempts = 0;
|
||||
/** @var array<int, array{sql:string,params:array}> */
|
||||
public array $writes = [];
|
||||
/** @var array<string, string> */
|
||||
public array $settings = [];
|
||||
|
||||
public function fetchOne($sql, $params = [])
|
||||
{
|
||||
$sql = (string)preg_replace('/\s+/', ' ', strtolower($sql));
|
||||
|
||||
if (str_contains($sql, 'from login_attempts')) {
|
||||
return ['cnt' => $this->recentAttempts];
|
||||
}
|
||||
if (str_contains($sql, 'from users')) {
|
||||
foreach ($this->users as $user) {
|
||||
if (($user['email'] ?? null) === ($params[0] ?? null)) {
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (str_contains($sql, 'from audit_log')) {
|
||||
return ['1' => 1]; // IP bereits gesehen -> keine Benachrichtigung
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function fetchAll($sql, $params = [])
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function execute($sql, $params = [])
|
||||
{
|
||||
$this->writes[] = ['sql' => (string)preg_replace('/\s+/', ' ', strtolower($sql)), 'params' => $params];
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function query($sql, $params = [])
|
||||
{
|
||||
return $this->execute($sql, $params);
|
||||
}
|
||||
|
||||
public function getSetting($key, $default = null)
|
||||
{
|
||||
return $this->settings[$key] ?? $default;
|
||||
}
|
||||
|
||||
/** Hat es einen Schreibzugriff mit diesem Fragment gegeben? */
|
||||
public function wrote(string $fragment): bool
|
||||
{
|
||||
foreach ($this->writes as $write) {
|
||||
if (str_contains($write['sql'], strtolower($fragment))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class AuthTest extends TestCase
|
||||
{
|
||||
private FakeAuthDb $db;
|
||||
private Auth $auth;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
$_SERVER['REMOTE_ADDR'] = '198.51.100.5';
|
||||
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
|
||||
|
||||
$this->db = new FakeAuthDb();
|
||||
$this->db->users[] = [
|
||||
'id' => 7,
|
||||
'email' => 'marie@example.com',
|
||||
'name' => 'Marie',
|
||||
'is_admin' => 1,
|
||||
'is_active' => 1,
|
||||
'password_hash' => password_hash('richtig', PASSWORD_DEFAULT),
|
||||
'totp_enabled' => 0,
|
||||
'totp_secret' => null,
|
||||
];
|
||||
$this->auth = new Auth($this->db);
|
||||
}
|
||||
|
||||
// --- Anmeldung -------------------------------------------------------
|
||||
|
||||
public function testCorrectPasswordStartsSession(): void
|
||||
{
|
||||
$this->assertTrue($this->auth->login('marie@example.com', 'richtig'));
|
||||
$this->assertSame(7, $_SESSION['user_id']);
|
||||
$this->assertTrue($this->auth->isLoggedIn());
|
||||
$this->assertTrue($this->auth->isAdmin());
|
||||
}
|
||||
|
||||
public function testWrongPasswordIsRecorded(): void
|
||||
{
|
||||
$this->assertFalse($this->auth->login('marie@example.com', 'falsch'));
|
||||
$this->assertArrayNotHasKey('user_id', $_SESSION);
|
||||
$this->assertTrue($this->db->wrote('insert into login_attempts'), 'Fehlversuch muss protokolliert werden');
|
||||
}
|
||||
|
||||
public function testUnknownUserBehavesLikeWrongPassword(): void
|
||||
{
|
||||
$this->assertFalse($this->auth->login('niemand@example.com', 'egal'));
|
||||
$this->assertArrayNotHasKey('user_id', $_SESSION);
|
||||
}
|
||||
|
||||
public function testRateLimitStopsLoginBeforePasswordCheck(): void
|
||||
{
|
||||
$this->db->recentAttempts = 10;
|
||||
|
||||
$this->assertSame('rate_limited', $this->auth->login('marie@example.com', 'richtig'));
|
||||
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Bei Sperre darf keine Sitzung entstehen');
|
||||
}
|
||||
|
||||
public function testTwoFactorUserIsNotLoggedInYet(): void
|
||||
{
|
||||
$this->db->users[0]['totp_enabled'] = 1;
|
||||
$this->db->users[0]['totp_secret'] = 'JBSWY3DPEHPK3PXP';
|
||||
|
||||
$result = $this->auth->login('marie@example.com', 'richtig');
|
||||
|
||||
$this->assertSame('totp_required', $result);
|
||||
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Erst nach dem Code gilt man als angemeldet');
|
||||
$this->assertSame(7, $_SESSION['totp_pending_user_id']);
|
||||
$this->assertFalse($this->auth->isLoggedIn());
|
||||
}
|
||||
|
||||
public function testInactiveUserCannotLogIn(): void
|
||||
{
|
||||
$this->db->users[0]['is_active'] = 0;
|
||||
// Die Abfrage filtert auf is_active = 1; die Attrappe liefert den
|
||||
// Datensatz trotzdem, deshalb hier der Vollständigkeit halber nur
|
||||
// die Prüfung, dass ein leerer Treffer nicht anmeldet.
|
||||
$this->db->users = [];
|
||||
|
||||
$this->assertFalse($this->auth->login('marie@example.com', 'richtig'));
|
||||
}
|
||||
|
||||
// --- CSRF ------------------------------------------------------------
|
||||
|
||||
public function testCsrfTokenIsStableAndChecked(): void
|
||||
{
|
||||
$token = $this->auth->getCsrfToken();
|
||||
|
||||
$this->assertNotSame('', $token);
|
||||
$this->assertSame($token, $this->auth->getCsrfToken(), 'Token bleibt innerhalb der Sitzung gleich');
|
||||
$this->assertTrue($this->auth->validateCsrfToken($token));
|
||||
$this->assertFalse($this->auth->validateCsrfToken('falsch'));
|
||||
$this->assertFalse($this->auth->validateCsrfToken(''));
|
||||
}
|
||||
|
||||
public function testCsrfCheckFailsWithoutSessionToken(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
|
||||
$this->assertFalse($this->auth->validateCsrfToken('irgendwas'));
|
||||
}
|
||||
|
||||
// --- Client-IP hinter einem Proxy -----------------------------------
|
||||
|
||||
public function testClientIpIgnoresForwardedHeaderWithoutTrustedProxy(): void
|
||||
{
|
||||
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
|
||||
|
||||
$this->assertSame('198.51.100.5', $this->auth->clientIp(),
|
||||
'Ohne eingetragenen Proxy darf der Header nicht zählen');
|
||||
}
|
||||
|
||||
public function testClientIpUsesForwardedHeaderFromTrustedProxy(): void
|
||||
{
|
||||
$this->db->settings['trusted_proxy'] = '198.51.100.5';
|
||||
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9, 70.41.3.18';
|
||||
|
||||
$this->assertSame('203.0.113.9', $this->auth->clientIp());
|
||||
}
|
||||
|
||||
public function testClientIpIgnoresForwardedHeaderFromUnknownSource(): void
|
||||
{
|
||||
$this->db->settings['trusted_proxy'] = '10.0.0.1';
|
||||
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
|
||||
|
||||
$this->assertSame('198.51.100.5', $this->auth->clientIp());
|
||||
}
|
||||
|
||||
public function testClientIpFallsBackWhenHeaderIsGarbage(): void
|
||||
{
|
||||
$this->db->settings['trusted_proxy'] = '198.51.100.5';
|
||||
$_SERVER['HTTP_X_FORWARDED_FOR'] = 'kein-ip-wert';
|
||||
|
||||
$this->assertSame('198.51.100.5', $this->auth->clientIp());
|
||||
}
|
||||
}
|
||||
152
tests/UniFiControllerTest.php
Normal file
152
tests/UniFiControllerTest.php
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use Exception;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use UniFiController;
|
||||
|
||||
require_once __DIR__ . '/../includes/UniFiController.php';
|
||||
|
||||
/**
|
||||
* Controller mit eingespielten Antworten statt echter HTTP-Aufrufe.
|
||||
* Die aufgezeichneten Antworten entsprechen dem Format der UniFi-API.
|
||||
*/
|
||||
class RecordedController extends UniFiController
|
||||
{
|
||||
/** @var array<int, array> */
|
||||
public array $calls = [];
|
||||
/** @var array<int, array|null> */
|
||||
private array $responses;
|
||||
|
||||
public function __construct(array $responses)
|
||||
{
|
||||
parent::__construct('https://unifi.example.com:8443', 'api', 'geheim', 'default');
|
||||
$this->responses = $responses;
|
||||
}
|
||||
|
||||
protected function apiRequest($endpoint, $data = null, $method = 'POST')
|
||||
{
|
||||
$this->calls[] = ['endpoint' => $endpoint, 'data' => $data, 'method' => $method];
|
||||
|
||||
return array_shift($this->responses);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Auswahl des richtigen Vouchers ist der heikle Teil: der Controller
|
||||
* liefert alle Voucher unsortiert zurück. Wer blind den ersten nimmt, gibt
|
||||
* bei parallelen Anfragen den Code eines anderen Gastes aus.
|
||||
*/
|
||||
class UniFiControllerTest extends TestCase
|
||||
{
|
||||
private function created(int $time = 1000): array
|
||||
{
|
||||
return ['data' => [['create_time' => $time]]];
|
||||
}
|
||||
|
||||
public function testPicksOwnVoucherNotAForeignOne(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [
|
||||
['code' => '1111122222', 'note' => 'Fremder Gast', 'create_time' => 5000, '_id' => 'a'],
|
||||
['code' => '3333344444', 'note' => '2026-09-24_Empfang', 'create_time' => 4000, '_id' => 'b'],
|
||||
]],
|
||||
]);
|
||||
|
||||
$result = $controller->createVoucher('2026-09-24_Empfang', 2, 480);
|
||||
|
||||
$this->assertSame('3333344444', $result['code'], 'Der Voucher mit passender Notiz gehört zu dieser Anfrage');
|
||||
$this->assertSame('b', $result['unifi_id']);
|
||||
}
|
||||
|
||||
public function testPicksNewestWhenNoteAppearsTwice(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [
|
||||
['code' => '1111122222', 'note' => 'Empfang', 'create_time' => 4000, '_id' => 'alt'],
|
||||
['code' => '3333344444', 'note' => 'Empfang', 'create_time' => 9000, '_id' => 'neu'],
|
||||
]],
|
||||
]);
|
||||
|
||||
$this->assertSame('neu', $controller->createVoucher('Empfang', 1, 60)['unifi_id']);
|
||||
}
|
||||
|
||||
public function testFallsBackToNewestWhenNoteDoesNotMatch(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [
|
||||
['code' => '1111122222', 'note' => 'Etwas anderes', 'create_time' => 4000, '_id' => 'alt'],
|
||||
['code' => '3333344444', 'note' => 'Auch anders', 'create_time' => 9000, '_id' => 'neu'],
|
||||
]],
|
||||
]);
|
||||
|
||||
$this->assertSame('neu', $controller->createVoucher('Sonderzeichen …', 1, 60)['unifi_id']);
|
||||
}
|
||||
|
||||
public function testFormatsCodeInFiveDigitBlocks(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||
]);
|
||||
|
||||
$result = $controller->createVoucher('Gast', 1, 60);
|
||||
|
||||
$this->assertSame('12345-67890', $result['formatted_code']);
|
||||
$this->assertSame('1234567890', $result['code'], 'Der rohe Code bleibt unverändert');
|
||||
}
|
||||
|
||||
public function testFailsWhenControllerDoesNotConfirmCreation(): void
|
||||
{
|
||||
$controller = new RecordedController([['data' => []]]);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$controller->createVoucher('Gast', 1, 60);
|
||||
}
|
||||
|
||||
public function testFailsWhenNoVouchersComeBack(): void
|
||||
{
|
||||
$controller = new RecordedController([$this->created(), ['data' => []]]);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$controller->createVoucher('Gast', 1, 60);
|
||||
}
|
||||
|
||||
public function testSendsQosLimitsOnlyWhenSet(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||
]);
|
||||
|
||||
$controller->createVoucher('Gast', 3, 240, ['down' => 20000, 'up' => 5000, 'quota_mb' => 1024]);
|
||||
|
||||
$payload = $controller->calls[0]['data'];
|
||||
$this->assertSame('create-voucher', $payload['cmd']);
|
||||
$this->assertSame(240, $payload['expire']);
|
||||
$this->assertSame(3, $payload['quota']);
|
||||
$this->assertTrue($payload['qos_overwrite']);
|
||||
$this->assertSame(20000, $payload['down']);
|
||||
$this->assertSame(5000, $payload['up']);
|
||||
$this->assertSame(1024, $payload['bytes']);
|
||||
}
|
||||
|
||||
public function testOmitsQosWhenNotRequested(): void
|
||||
{
|
||||
$controller = new RecordedController([
|
||||
$this->created(),
|
||||
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
|
||||
]);
|
||||
|
||||
$controller->createVoucher('Gast', 1, 60);
|
||||
|
||||
$this->assertArrayNotHasKey('qos_overwrite', $controller->calls[0]['data']);
|
||||
$this->assertArrayNotHasKey('down', $controller->calls[0]['data']);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue