Tests / test (pull_request) Successful in 1m10s
Brings preauth from 18/34 to 30/34 conformance (auth-gateway profile). The
remaining four checks all depend on files this branch cannot change (see below).
PHP toolchain (§1)
- require.php >=8.4 -> ^8.5, and pin config.platform to 8.5.0. The old
constraint also permitted PHP 9, which is not a promise we can keep.
composer.lock regenerated with --lock: content-hash + platform-overrides
only, zero dependency version movement.
- friendsofphp/php-cs-fixer * -> ^3.95. A wildcard meant CI was not
reproducible.
PHPStan (§2.2)
- vendor the shared phpstan.neon.dist (level 6) + a generated baseline.
187 errors are captured rather than fixed; the baseline should only shrink
from here.
- add phpstan/phpstan:^2.1 to require-dev.
Code style (§8.2)
- vendor the shared .php-cs-fixer.dist.php (@Symfony + @Symfony:risky +
declare_strict_types) and apply it: 59 of 67 files reformatted.
- Verified this is a formatting change, not a behaviour change: all 313 tests
pass after the reformat, all in_array() calls already passed strict=true,
and the remaining edits are @Symfony:risky idiom (yoda conditions, \count(),
self:: over the class name).
Repository layout (§4.4)
- docs/{Caddyfile,compose.yaml,example.env} -> docs/examples/, with
example.env becoming the conventional .env.example. This is the layout
GUIDING-LIGHT already cites preauth as doing correctly — it just needed
renaming.
- update the four readme.md references and a stale compose.yaml comment.
- docs/v1.1-plan.md references are left alone deliberately: it is a historical
plan recording what was done at the time, not live documentation.
Licence and security policy (§7)
- add LICENSE (uniform MIT, matching composer.json).
- add SECURITY.md describing the actual threat model: per-request
allow/intercept, no caching of the login flow, app-set security headers,
TOTP, and the fact that REMOTE_USER is trusted input.
Mobile accessibility (§3.3a)
- templates/base.html.twig: drop maximum-scale=1 and add viewport-fit=cover.
preauth was the one app already past the font-size precondition (controls
render at 21.6px = 0.9em x 24px), so removing the lock is safe here and
restores pinch-zoom for Android users.
Conformance tooling (§8.2)
- vendor .ci/conformance.sh and .ci/css-control-size.py so the check runs
from a checkout rather than fetching from the LAN-only private/ci.
- .editorconfig synced from the version that keeps the Caddyfile tab rule.
Not included (blocked by the .gitea/workflows pre-receive hook):
- ci-composer-audit, ci-composer-validate, ci-reusable-workflows.
Workflow files may only change via a trusted ref, so the caller files are
staged but not committed.
Also not included: dockerfile-nonroot (§6.4). Adding USER to an image with
VOLUME [/config, /data] changes volume ownership and needs an actual container
build/run to verify, so it goes in its own change.
121 lines
4.2 KiB
PHP
121 lines
4.2 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Service;
|
||
|
||
use App\AppConstants;
|
||
use App\MonitorCacheKeys;
|
||
use App\Trait\GetTotpTrait;
|
||
use App\Trait\HasLoggerTrait;
|
||
use App\Trait\StringTrait;
|
||
use DateTimeImmutable;
|
||
use Exception;
|
||
use Psr\Cache\CacheItemPoolInterface;
|
||
use Psr\Cache\InvalidArgumentException;
|
||
|
||
/** backup-codes are case‑insensitive alphanumeric strings
|
||
* they are single-use and marked as used after successful authentication */
|
||
final readonly class BackupCodeManager implements BackupCodeInterface
|
||
{
|
||
use GetTotpTrait;
|
||
use HasLoggerTrait;
|
||
use StringTrait;
|
||
|
||
private const int DEFAULT_COUNT = 10;
|
||
/* php base_convert() will break if given too long of an input */
|
||
public const int MAX_LENGTH = 64;
|
||
|
||
private CacheItemPoolInterface $sessionCache;
|
||
|
||
/** @throws InvalidArgumentException */
|
||
public function __construct(CacheItemPoolInterface $sessionCache)
|
||
{
|
||
$this->sessionCache = new MonitorCacheKeys($sessionCache);
|
||
}
|
||
|
||
/** generate a set of backup-codes and return them.
|
||
* @param int $count Number of codes to generate
|
||
*
|
||
* @return string[] Generated backup codes
|
||
*
|
||
* @throws InvalidArgumentException|Exception */
|
||
public function generate(int $count = self::DEFAULT_COUNT): array
|
||
{
|
||
$length = min($this->getTotp()->getDigits() + 2, self::MAX_LENGTH);
|
||
$codes = [];
|
||
for ($i = 0; $i < $count; ++$i) {
|
||
/* output is alphanumeric string of given length */
|
||
$codes[] = strtolower(str_pad(substr(base_convert(bin2hex(
|
||
random_bytes($length),
|
||
), 16, 36), 0, $length), $length, '0', \STR_PAD_LEFT));
|
||
}
|
||
$this->saveCodes($codes);
|
||
$this->logger->info("generated {$count} backup codes");
|
||
|
||
return $codes;
|
||
}
|
||
|
||
/** @throws InvalidArgumentException */
|
||
public function expire(): void
|
||
{
|
||
$itemsToRemove = [];
|
||
foreach ($this->sessionCache->getKeys() as $key) {
|
||
if (str_starts_with($key, 'backup_')) {
|
||
$itemsToRemove[] = $key;
|
||
}
|
||
}
|
||
if (\count($itemsToRemove) > 0) {
|
||
$this->sessionCache->deleteItems($itemsToRemove);
|
||
}
|
||
}
|
||
|
||
/** check if backup-code is valid and mark it as used.
|
||
* @param string $code Code supplied by the client
|
||
*
|
||
* @return bool true if the code is valid and unused
|
||
*
|
||
* @throws InvalidArgumentException */
|
||
public function verifyAndConsume(string $code): bool
|
||
{
|
||
/* remove unallowed characters, since backup codes are case-insensitive alphanumeric */
|
||
$backupKey = 'backup_'.preg_replace('/[^a-z0-9]+/', '', strtolower($code));
|
||
$backupItem = $this->sessionCache->getItem($this->makeCacheKey($backupKey));
|
||
$this->logger->debug('checking backup code: '.($backupItem->isHit() ? 'HIT & ' : 'miss & ').($backupItem->get() ? 'VALID' : 'invalid'));
|
||
if ($backupItem->isHit() && $backupItem->get()) {
|
||
$this->logger->debug('valid backup code');
|
||
/* mark backup code as spent */
|
||
$backupItem->set(false); /* used */
|
||
/* per PSR6, if no expiration is set, implementation may set a default,
|
||
* we want this to keep forever, so a few hundred years should do it */
|
||
$backupItem->expiresAt(DateTimeImmutable::createFromFormat(
|
||
'Y-m-d',
|
||
AppConstants::FAR_FUTURE_DATE,
|
||
));
|
||
$this->sessionCache->save($backupItem);
|
||
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/** @throws InvalidArgumentException */
|
||
private function saveCodes(array $codes): void
|
||
{
|
||
foreach ($codes as $code) {
|
||
$backupItem = $this->sessionCache->getItem($this->makeCacheKey(strtolower("backup_$code")));
|
||
/* mark backup code as ready */
|
||
$backupItem->set(true);
|
||
/* per PSR6, if no expiration is set, implementation may set a default,
|
||
* we want this to keep forever, so a few hundred years should do it */
|
||
$backupItem->expiresAt(DateTimeImmutable::createFromFormat(
|
||
'Y-m-d',
|
||
AppConstants::FAR_FUTURE_DATE,
|
||
));
|
||
$this->sessionCache->saveDeferred($backupItem);
|
||
}
|
||
$this->sessionCache->commit();
|
||
}
|
||
}
|