Harden the app: block project files, add rate limits and security headers

- Root .htaccess refuses everything outside public/, because local Apache
  serves the whole project folder (.env, logs with set-password links, .git).
- Login allows 20 failed attempts a minute per IP across accounts, besides
  5 per email and IP; the forgot-password page 5 requests a minute per IP.
- A global middleware sends X-Frame-Options, frame-ancestors, nosniff,
  Referrer-Policy, Permissions-Policy and HSTS over HTTPS, and drops
  X-Powered-By.
- The weekly time sheet locks the shown week and selected day, so the
  browser cannot set them.
- Users who may not see personal identity codes can save a new code at
  most 10 times an hour, so the duplicate check cannot be used to test codes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 06:25:26 +02:00
co-authored by Claude Opus 5.5
parent fcad0ea939
commit 1acdaa5b19
15 changed files with 229 additions and 8 deletions
+19
View File
@@ -0,0 +1,19 @@
# Local XAMPP serves the whole project folder (DocumentRoot is htdocs), so
# only public/ may be reached: .env, storage/logs, .git, vendor and the rest
# are refused. In production the web server's document root is public/.
<IfModule mod_rewrite.c>
Options -Indexes
RewriteEngine On
# The project folder itself goes to the application.
RewriteRule ^$ public/ [R=302,L]
# Everything outside public/ is forbidden.
RewriteRule !^public(/|$) - [F,L]
</IfModule>
# Without mod_rewrite nothing outside public/ can be told apart: refuse all.
<IfModule !mod_rewrite.c>
Require all denied
</IfModule>
+4 -3
View File
@@ -23,7 +23,8 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`).
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP.
- **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`.
- `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`.
- Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files.
- When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool.
@@ -44,7 +45,7 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
- `<x-input>` without `wire:model` (e.g. a read-only value): pass an explicit `id`, or the label is not tied to it. `<x-clipboard>` has an unlabelled input and a button whose name changes; build copy fields from `<x-input readonly>` + `<x-button>` + a `role="status"` message instead (see `users::form`).
- Contrast: the primary palette is one step darker (`resources/css/app.css`); error text, label error and asterisk, and input/select error colours are changed by soft customization in `App\Providers\AppServiceProvider`; light alert and link text colours are in published colour classes `app/View/Components/TallStackUi/Colors/`. `flat` and `outline` buttons have no dark-mode text colour: use `subtle color="black"` for neutral buttons.
- Finnish strings for TallStackUI's own components are in `lang/vendor/ts-ui/fi/messages.php`.
- **Personal identity codes** (*henkilötunnus*, consumer customers) are sensitive personal data: stored encrypted (`encrypted` cast, `$hidden`) with an HMAC blind index for duplicates, never in `CustomerSummary`, search, logs, exception messages or Livewire public properties, and shown in full only behind `customers.view-personal-identity-code` (admin, management) via `CustomerQueries::personalIdentityCodeOf()`; everyone else sees `masked()`.
- **Personal identity codes** (*henkilötunnus*, consumer customers) are sensitive personal data: stored encrypted (`encrypted` cast, `$hidden`) with an HMAC blind index for duplicates (the "already in use" error tells whether a person is a customer, so users without the view gate may save a new code only 10 times an hour), never in `CustomerSummary`, search, logs, exception messages or Livewire public properties, and shown in full only behind `customers.view-personal-identity-code` (admin, management) via `CustomerQueries::personalIdentityCodeOf()`; everyone else sees `masked()`.
- Never convey meaning by colour alone. Statuses, priorities (e.g. *kiire* = red), errors and warnings always also have visible text or an icon with text.
- Announce dynamic changes: put status text in `role="status"` / `aria-live="polite"` (errors: `role="alert"`), or a TallStackUI toast (`<x-toast />` must then be added to the layout). Keep button names stable instead of putting changing state in them.
- Make everything work with the keyboard alone, with a visible focus indicator and no focus traps. Use `<x-confirm-dialog>` for dialogs (not `<x-modal>`, see above) and check that focus moves in and returns. Drag and drop uses Livewire's `wire:sort` (see `jobs::board`), and every drag has a keyboard alternative (e.g. a status select on each card).
@@ -70,7 +71,7 @@ php artisan users:create-admin "Name" [email protected] # first admin; emails a
- Locally `MAIL_MAILER=log`: emails, including set-password links, are written to `storage/logs/laravel.log`.
- Runs under XAMPP: Apache on port 8080 serves the app at `http://localhost:8080/toiminnanohjaus/public` (this is `APP_URL`). The database is XAMPP MariaDB 10.11 `toiminnanohjaus` (root, no password).
- Runs under XAMPP: Apache on port 8080 serves the app at `http://localhost:8080/toiminnanohjaus/public` (this is `APP_URL`). Apache's document root is `htdocs`, so the project root `.htaccess` refuses everything outside `public/` (`.env`, logs with set-password links, `.git`); keep it. In production the document root is `public/`, with `APP_DEBUG=false`, `SESSION_SECURE_COOKIE=true` and a real mailer. The database is XAMPP MariaDB 10.11 `toiminnanohjaus` (root, no password).
- Tests use in-memory SQLite with array cache/session/mail and the sync queue. `phpunit.xml` sets `APP_URL=http://localhost`, because the subfolder `APP_URL` makes test requests 404.
- Browser tests (`tests/Browser`, Pest browser plugin with Playwright Chromium) run against built assets, so run `npm run build` first. Run only them with `php artisan test --compact tests/Browser`. They need PHP's `sockets` extension (enabled in `C:\xampp\php\php.ini`). In the plugin's `click`/`keys` methods, a selector is treated as CSS only if it starts with `#`, `.` or `[`, or contains a CSS combinator (`html > body`). Otherwise it is matched as visible text, so `button` or `main button` time out.
- Apache serves built assets from `public/build`, so run `npm run build` after CSS/Blade class changes. A leftover `public/hot` file from a stopped `npm run dev` breaks all styling: delete it.
@@ -7,6 +7,8 @@ use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Presentation\Livewire\Forms\CustomerForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Locked;
use Livewire\Component;
@@ -15,6 +17,13 @@ use Livewire\Component;
*/
new class extends Component
{
/**
* Saves with a new personal identity code per hour for users who may not
* see codes. "Already in use" tells whether a person is a customer, so
* the form must not be usable to test many codes.
*/
public const int MAX_IDENTITY_CODE_SAVES_PER_HOUR = 10;
#[Locked]
public ?int $customerId = null;
@@ -52,6 +61,13 @@ new class extends Component
$this->authorize('customers.view-personal-identity-code');
}
if (! $this->identityCodeAttemptAllowed()) {
$this->resetErrorBag('form.personal_identity_code');
$this->addError('form.personal_identity_code', __('customers.errors.personal_identity_code_throttled'));
return;
}
$data = $this->form->toData();
try {
@@ -75,6 +91,27 @@ new class extends Component
$this->redirectRoute('customers.show', $customerId, navigate: true);
}
/**
* Counts a save that carries a new personal identity code; admins and
* management, who see the codes anyway, are not limited.
*/
private function identityCodeAttemptAllowed(): bool
{
if (trim($this->form->personal_identity_code) === '' || Gate::allows('customers.view-personal-identity-code')) {
return true;
}
$key = 'identity-code-save|'.auth()->id();
if (RateLimiter::tooManyAttempts($key, self::MAX_IDENTITY_CODE_SAVES_PER_HOUR)) {
return false;
}
RateLimiter::hit($key, 3600);
return true;
}
public function render(): mixed
{
return $this->view()->title(__($this->customerId === null ? 'customers.create_title' : 'customers.edit_title'));
@@ -6,6 +6,8 @@ use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher;
use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager;
use App\Modules\Shared\Presentation\Http\Middleware\SetSecurityHeaders;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Support\ServiceProvider;
class SharedServiceProvider extends ServiceProvider
@@ -17,4 +19,9 @@ class SharedServiceProvider extends ServiceProvider
TransactionManager::class => LaravelTransactionManager::class,
EventDispatcher::class => LaravelEventDispatcher::class,
];
public function boot(): void
{
$this->app->make(Kernel::class)->pushMiddleware(SetSecurityHeaders::class);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Modules\Shared\Presentation\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Browser security headers on every response of the application.
*
* - No framing by other sites (clickjacking).
* - No MIME sniffing.
* - Only the origin goes to other sites in Referer, so set-password tokens
* in the URL never leave the application.
* - HSTS when the request came over HTTPS.
*
* A full Content-Security-Policy is left out: Alpine and Livewire need
* 'unsafe-eval', which would take away most of its protection.
*/
class SetSecurityHeaders
{
public const int HSTS_MAX_AGE = 31536000;
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('Content-Security-Policy', "frame-ancestors 'none'; base-uri 'self'; object-src 'none'");
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set('Permissions-Policy', 'geolocation=(), microphone=(), payment=(), usb=()');
if ($request->isSecure()) {
$response->headers->set('Strict-Transport-Security', 'max-age='.self::HSTS_MAX_AGE.'; includeSubDomains');
}
if (! headers_sent()) {
header_remove('X-Powered-By');
}
return $response;
}
}
@@ -27,8 +27,10 @@ use Livewire\Component;
new class extends Component
{
/**
* The Monday of the week shown (Y-m-d).
* The Monday of the week shown (Y-m-d). Read from the URL on mount and
* then changed only by showWeek(), so the browser cannot set it.
*/
#[Locked]
#[Url(as: 'viikko', except: '')]
public string $week = '';
@@ -58,6 +60,11 @@ new class extends Component
#[Locked]
public array $rejected = [];
/**
* The day shown on phones; changed only by selectDay(), because it is
* written into element ids and wire:change calls.
*/
#[Locked]
public string $selectedDay = '';
public string $taskSearch = '';
@@ -2,10 +2,13 @@
use App\Modules\Users\Application\UseCases\RequestPasswordReset;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Component;
new class extends Component
{
public const int MAX_REQUESTS_PER_IP_PER_MINUTE = 5;
public string $email = '';
public bool $linkRequested = false;
@@ -23,6 +26,17 @@ new class extends Component
['email.required' => __('auth.email_required'), 'email.email' => __('auth.email_invalid'), 'email.max' => __('auth.email_invalid')],
);
// Laravel allows one link a minute per account; this also limits one
// address asking links for many accounts (mail flooding).
$throttleKey = 'forgot-password|'.request()->ip();
if (RateLimiter::tooManyAttempts($throttleKey, self::MAX_REQUESTS_PER_IP_PER_MINUTE)) {
$this->addError('email', __('auth.forgot_throttle', ['seconds' => RateLimiter::availableIn($throttleKey)]));
return;
}
RateLimiter::hit($throttleKey);
$requestPasswordReset->execute(new EmailAddress($this->email));
$this->linkRequested = true;
@@ -11,6 +11,12 @@ new class extends Component
{
public const int MAX_ATTEMPTS_PER_MINUTE = 5;
/**
* Failed attempts from one address across all accounts, so one common
* password cannot be tried on every account (password spraying).
*/
public const int MAX_ATTEMPTS_PER_IP_PER_MINUTE = 20;
public string $email = '';
public string $password = '';
@@ -44,12 +50,15 @@ new class extends Component
$email = Str::lower(trim($this->email));
$throttleKey = Str::transliterate($email.'|'.request()->ip());
$ipThrottleKey = 'login-ip|'.request()->ip();
if (RateLimiter::tooManyAttempts($throttleKey, self::MAX_ATTEMPTS_PER_MINUTE)) {
foreach ([$throttleKey => self::MAX_ATTEMPTS_PER_MINUTE, $ipThrottleKey => self::MAX_ATTEMPTS_PER_IP_PER_MINUTE] as $key => $maxAttempts) {
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
throw ValidationException::withMessages([
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($throttleKey)]),
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($key)]),
]);
}
}
$signedIn = Auth::attemptWhen(
['email' => $email, 'password' => $this->password],
@@ -59,6 +68,7 @@ new class extends Component
if (! $signedIn) {
RateLimiter::hit($throttleKey);
RateLimiter::hit($ipThrottleKey);
$this->reset('password');
// One message for a wrong password and a disabled account, so the
+1
View File
@@ -4,6 +4,7 @@ return [
'failed' => 'Kirjautuminen ei onnistunut. Tarkista sähköposti ja salasana. Jos tunnuksesi on poistettu käytöstä, ota yhteyttä pääkäyttäjään.',
'password' => 'Salasana on väärin.',
'throttle' => 'Liian monta kirjautumisyritystä. Yritä uudelleen :seconds sekunnin kuluttua.',
'forgot_throttle' => 'Liian monta linkkipyyntöä. Yritä uudelleen :seconds sekunnin kuluttua.',
'account_disabled' => 'Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.',
'logged_out' => 'Olet kirjautunut ulos.',
+1
View File
@@ -106,6 +106,7 @@ return [
'company_personal_identity_code' => 'Yritysasiakkaalla ei voi olla henkilötunnusta.',
'internal_must_be_company' => 'Sisäinen asiakas on oma yritys, joten se ei voi olla kuluttaja.',
'personal_identity_code_taken' => 'Tällä henkilötunnuksella on jo asiakas. Hae asiakas listasta nimellä.',
'personal_identity_code_throttled' => 'Olet tallentanut henkilötunnuksia liian monta kertaa tunnin aikana. Yritä myöhemmin uudelleen tai pyydä johtoa tallentamaan tunnus.',
'contact_name_required' => 'Anna yhteyshenkilön nimi.',
'invalid_contact_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'invalid_email' => 'Sähköpostiosoite ei ole kelvollinen.',
@@ -144,3 +144,23 @@ it('drops the code when a consumer becomes a company', function () {
expect($customer->fresh()->personal_identity_code)->toBeNull();
});
it('limits how many codes an employee can try, but not management', function (string $role, bool $limited) {
$this->actingAs(User::factory()->create(['role' => $role]));
$form = Livewire::test('customers::form')
->set('form.name', 'Maija Meikäläinen')
->set('form.type', CustomerType::Consumer->value);
foreach (range(1, 10) as $attempt) {
$form->set('form.personal_identity_code', 'väärä')->call('save')->assertHasErrors(['form.personal_identity_code']);
}
$form->set('form.personal_identity_code', '131052-308T')->call('save');
$limited
? $form->assertSee('liian monta kertaa tunnin aikana')
: $form->assertHasNoErrors();
})->with([
'employee' => ['employee', true],
'management' => ['management', false],
]);
@@ -0,0 +1,16 @@
<?php
it('sends browser security headers', function () {
$this->get(route('login'))
->assertOk()
->assertHeader('X-Frame-Options', 'DENY')
->assertHeader('Content-Security-Policy', "frame-ancestors 'none'; base-uri 'self'; object-src 'none'")
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
->assertHeaderMissing('Strict-Transport-Security');
});
it('asks browsers to keep to HTTPS when the request came over HTTPS', function () {
$this->get(str_replace('http://', 'https://', route('login')))
->assertHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
});
@@ -6,6 +6,7 @@ use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
@@ -33,6 +34,17 @@ it('saves and clears a cell of the weekly view', function () {
expect(TimeEntryModel::query()->count())->toBe(0);
});
it('takes the week only from the URL and the week buttons', function () {
$this->get(route('time.week', ['viikko' => "abc'); alert(1); ('"]))->assertOk()->assertSee('Mainoskuvat');
$week = Livewire::test('time::week');
expect(fn () => $week->set('week', '2026-05-20'))->toThrow(CannotUpdateLockedPropertyException::class)
->and(fn () => $week->set('selectedDay', "x'); alert(1); ('"))->toThrow(CannotUpdateLockedPropertyException::class);
$week->call('selectDay', "x'); alert(1); ('")->assertSet('selectedDay', now()->toDateString());
});
it('adds hours from the task page to the day entry and locks done jobs', function () {
Livewire::test('time::task', ['task' => $this->task->id])
->set('workedOn', $this->monday)
+17
View File
@@ -90,6 +90,23 @@ it('blocks login after five failed attempts', function () {
$this->assertGuest();
});
it('blocks one address that tries a password on many accounts', function () {
RateLimiter::clear('login-ip|127.0.0.1');
User::factory()->create(['email' => '[email protected]']);
$login = Livewire::test('users::login');
foreach (range(1, 20) as $attempt) {
$login->set('email', "tuntematon{$attempt}@example.test")->set('password', 'Kesä2027!')->call('login');
}
$login->set('email', '[email protected]')
->set('password', 'password')
->call('login')
->assertSee('Liian monta kirjautumisyritystä.');
$this->assertGuest();
});
it('ends the session of a user who is deactivated while signed in', function () {
$user = User::factory()->create();
@@ -55,6 +55,20 @@ it('shows the same message for an unknown address', function () {
Notification::assertNothingSent();
});
it('limits how many links one address can ask for', function () {
Notification::fake();
$forgot = Livewire::test('users::forgot-password');
foreach (range(1, 5) as $attempt) {
$forgot->set('email', "tuntematon{$attempt}@example.test")->call('sendLink')->assertHasNoErrors();
}
$forgot->set('email', '[email protected]')
->call('sendLink')
->assertHasErrors(['email'])
->assertSee('Liian monta linkkipyyntöä.');
});
it('sends no link to a deactivated user or an intern past the last day, with the same message', function (string $state) {
Notification::fake();
$user = match ($state) {